xref: /titanic_52/usr/src/uts/common/inet/tcp/tcp.c (revision 55f5292c612446ce6f93ddd248c0019b5974618b)
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 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #define	_SUN_TPI_VERSION 2
35 #include <sys/tihdr.h>
36 #include <sys/timod.h>
37 #include <sys/ddi.h>
38 #include <sys/sunddi.h>
39 #include <sys/suntpi.h>
40 #include <sys/xti_inet.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/sdt.h>
44 #include <sys/vtrace.h>
45 #include <sys/kmem.h>
46 #include <sys/ethernet.h>
47 #include <sys/cpuvar.h>
48 #include <sys/dlpi.h>
49 #include <sys/pattr.h>
50 #include <sys/policy.h>
51 #include <sys/priv.h>
52 #include <sys/zone.h>
53 #include <sys/sunldi.h>
54 
55 #include <sys/errno.h>
56 #include <sys/signal.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/sockio.h>
60 #include <sys/isa_defs.h>
61 #include <sys/md5.h>
62 #include <sys/random.h>
63 #include <sys/uio.h>
64 #include <sys/systm.h>
65 #include <netinet/in.h>
66 #include <netinet/tcp.h>
67 #include <netinet/ip6.h>
68 #include <netinet/icmp6.h>
69 #include <net/if.h>
70 #include <net/route.h>
71 #include <inet/ipsec_impl.h>
72 
73 #include <inet/common.h>
74 #include <inet/ip.h>
75 #include <inet/ip_impl.h>
76 #include <inet/ip6.h>
77 #include <inet/ip_ndp.h>
78 #include <inet/proto_set.h>
79 #include <inet/mib2.h>
80 #include <inet/nd.h>
81 #include <inet/optcom.h>
82 #include <inet/snmpcom.h>
83 #include <inet/kstatcom.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/udp_impl.h>
87 #include <net/pfkeyv2.h>
88 #include <inet/ipdrop.h>
89 
90 #include <inet/ipclassifier.h>
91 #include <inet/ip_ire.h>
92 #include <inet/ip_ftable.h>
93 #include <inet/ip_if.h>
94 #include <inet/ipp_common.h>
95 #include <inet/ip_rts.h>
96 #include <inet/ip_netinfo.h>
97 #include <sys/squeue_impl.h>
98 #include <sys/squeue.h>
99 #include <inet/kssl/ksslapi.h>
100 #include <sys/tsol/label.h>
101 #include <sys/tsol/tnet.h>
102 #include <rpc/pmap_prot.h>
103 #include <sys/callo.h>
104 
105 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
106 
107 /*
108  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
109  *
110  * (Read the detailed design doc in PSARC case directory)
111  *
112  * The entire tcp state is contained in tcp_t and conn_t structure
113  * which are allocated in tandem using ipcl_conn_create() and passing
114  * IPCL_TCPCONN as a flag. We use 'conn_ref' and 'conn_lock' to protect
115  * the references on the tcp_t. The tcp_t structure is never compressed
116  * and packets always land on the correct TCP perimeter from the time
117  * eager is created till the time tcp_t dies (as such the old mentat
118  * TCP global queue is not used for detached state and no IPSEC checking
119  * is required). The global queue is still allocated to send out resets
120  * for connection which have no listeners and IP directly calls
121  * tcp_xmit_listeners_reset() which does any policy check.
122  *
123  * Protection and Synchronisation mechanism:
124  *
125  * The tcp data structure does not use any kind of lock for protecting
126  * its state but instead uses 'squeues' for mutual exclusion from various
127  * read and write side threads. To access a tcp member, the thread should
128  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
129  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
130  * can pass any tcp function having prototype of edesc_t as argument
131  * (different from traditional STREAMs model where packets come in only
132  * designated entry points). The list of functions that can be directly
133  * called via squeue are listed before the usual function prototype.
134  *
135  * Referencing:
136  *
137  * TCP is MT-Hot and we use a reference based scheme to make sure that the
138  * tcp structure doesn't disappear when its needed. When the application
139  * creates an outgoing connection or accepts an incoming connection, we
140  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
141  * The IP reference is just a symbolic reference since ip_tcpclose()
142  * looks at tcp structure after tcp_close_output() returns which could
143  * have dropped the last TCP reference. So as long as the connection is
144  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
145  * conn_t. The classifier puts its own reference when the connection is
146  * inserted in listen or connected hash. Anytime a thread needs to enter
147  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
148  * on write side or by doing a classify on read side and then puts a
149  * reference on the conn before doing squeue_enter/tryenter/fill. For
150  * read side, the classifier itself puts the reference under fanout lock
151  * to make sure that tcp can't disappear before it gets processed. The
152  * squeue will drop this reference automatically so the called function
153  * doesn't have to do a DEC_REF.
154  *
155  * Opening a new connection:
156  *
157  * The outgoing connection open is pretty simple. tcp_open() does the
158  * work in creating the conn/tcp structure and initializing it. The
159  * squeue assignment is done based on the CPU the application
160  * is running on. So for outbound connections, processing is always done
161  * on application CPU which might be different from the incoming CPU
162  * being interrupted by the NIC. An optimal way would be to figure out
163  * the NIC <-> CPU binding at listen time, and assign the outgoing
164  * connection to the squeue attached to the CPU that will be interrupted
165  * for incoming packets (we know the NIC based on the bind IP address).
166  * This might seem like a problem if more data is going out but the
167  * fact is that in most cases the transmit is ACK driven transmit where
168  * the outgoing data normally sits on TCP's xmit queue waiting to be
169  * transmitted.
170  *
171  * Accepting a connection:
172  *
173  * This is a more interesting case because of various races involved in
174  * establishing a eager in its own perimeter. Read the meta comment on
175  * top of tcp_input_listener(). But briefly, the squeue is picked by
176  * ip_fanout based on the ring or the sender (if loopback).
177  *
178  * Closing a connection:
179  *
180  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
181  * via squeue to do the close and mark the tcp as detached if the connection
182  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
183  * reference but tcp_close() drop IP's reference always. So if tcp was
184  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
185  * and 1 because it is in classifier's connected hash. This is the condition
186  * we use to determine that its OK to clean up the tcp outside of squeue
187  * when time wait expires (check the ref under fanout and conn_lock and
188  * if it is 2, remove it from fanout hash and kill it).
189  *
190  * Although close just drops the necessary references and marks the
191  * tcp_detached state, tcp_close needs to know the tcp_detached has been
192  * set (under squeue) before letting the STREAM go away (because a
193  * inbound packet might attempt to go up the STREAM while the close
194  * has happened and tcp_detached is not set). So a special lock and
195  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
196  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
197  * tcp_detached.
198  *
199  * Special provisions and fast paths:
200  *
201  * We make special provisions for sockfs by marking tcp_issocket
202  * whenever we have only sockfs on top of TCP. This allows us to skip
203  * putting the tcp in acceptor hash since a sockfs listener can never
204  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
205  * since eager has already been allocated and the accept now happens
206  * on acceptor STREAM. There is a big blob of comment on top of
207  * tcp_input_listener explaining the new accept. When socket is POP'd,
208  * sockfs sends us an ioctl to mark the fact and we go back to old
209  * behaviour. Once tcp_issocket is unset, its never set for the
210  * life of that connection.
211  *
212  * IPsec notes :
213  *
214  * Since a packet is always executed on the correct TCP perimeter
215  * all IPsec processing is defered to IP including checking new
216  * connections and setting IPSEC policies for new connection. The
217  * only exception is tcp_xmit_listeners_reset() which is called
218  * directly from IP and needs to policy check to see if TH_RST
219  * can be sent out.
220  */
221 
222 /*
223  * Values for squeue switch:
224  * 1: SQ_NODRAIN
225  * 2: SQ_PROCESS
226  * 3: SQ_FILL
227  */
228 int tcp_squeue_wput = 2;	/* /etc/systems */
229 int tcp_squeue_flag;
230 
231 /*
232  * This controls how tiny a write must be before we try to copy it
233  * into the mblk on the tail of the transmit queue.  Not much
234  * speedup is observed for values larger than sixteen.  Zero will
235  * disable the optimisation.
236  */
237 int tcp_tx_pull_len = 16;
238 
239 /*
240  * TCP Statistics.
241  *
242  * How TCP statistics work.
243  *
244  * There are two types of statistics invoked by two macros.
245  *
246  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
247  * supposed to be used in non MT-hot paths of the code.
248  *
249  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
250  * supposed to be used for DEBUG purposes and may be used on a hot path.
251  *
252  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
253  * (use "kstat tcp" to get them).
254  *
255  * There is also additional debugging facility that marks tcp_clean_death()
256  * instances and saves them in tcp_t structure. It is triggered by
257  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
258  * tcp_clean_death() calls that counts the number of times each tag was hit. It
259  * is triggered by TCP_CLD_COUNTERS define.
260  *
261  * How to add new counters.
262  *
263  * 1) Add a field in the tcp_stat structure describing your counter.
264  * 2) Add a line in the template in tcp_kstat2_init() with the name
265  *    of the counter.
266  *
267  *    IMPORTANT!! - make sure that both are in sync !!
268  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
269  *
270  * Please avoid using private counters which are not kstat-exported.
271  *
272  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
273  * in tcp_t structure.
274  *
275  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
276  */
277 
278 #ifndef TCP_DEBUG_COUNTER
279 #ifdef DEBUG
280 #define	TCP_DEBUG_COUNTER 1
281 #else
282 #define	TCP_DEBUG_COUNTER 0
283 #endif
284 #endif
285 
286 #define	TCP_CLD_COUNTERS 0
287 
288 #define	TCP_TAG_CLEAN_DEATH 1
289 #define	TCP_MAX_CLEAN_DEATH_TAG 32
290 
291 #ifdef lint
292 static int _lint_dummy_;
293 #endif
294 
295 #if TCP_CLD_COUNTERS
296 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
297 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
298 #elif defined(lint)
299 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
300 #else
301 #define	TCP_CLD_STAT(x)
302 #endif
303 
304 #if TCP_DEBUG_COUNTER
305 #define	TCP_DBGSTAT(tcps, x)	\
306 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
307 #define	TCP_G_DBGSTAT(x)	\
308 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
309 #elif defined(lint)
310 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
311 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
312 #else
313 #define	TCP_DBGSTAT(tcps, x)
314 #define	TCP_G_DBGSTAT(x)
315 #endif
316 
317 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
318 
319 tcp_g_stat_t	tcp_g_statistics;
320 kstat_t		*tcp_g_kstat;
321 
322 /* Macros for timestamp comparisons */
323 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
324 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
325 
326 /*
327  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
328  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
329  * by adding three components: a time component which grows by 1 every 4096
330  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
331  * a per-connection component which grows by 125000 for every new connection;
332  * and an "extra" component that grows by a random amount centered
333  * approximately on 64000.  This causes the ISS generator to cycle every
334  * 4.89 hours if no TCP connections are made, and faster if connections are
335  * made.
336  *
337  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
338  * components: a time component which grows by 250000 every second; and
339  * a per-connection component which grows by 125000 for every new connections.
340  *
341  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
342  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
343  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
344  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
345  * password.
346  */
347 #define	ISS_INCR	250000
348 #define	ISS_NSEC_SHT	12
349 
350 static sin_t	sin_null;	/* Zero address for quick clears */
351 static sin6_t	sin6_null;	/* Zero address for quick clears */
352 
353 /*
354  * This implementation follows the 4.3BSD interpretation of the urgent
355  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
356  * incompatible changes in protocols like telnet and rlogin.
357  */
358 #define	TCP_OLD_URP_INTERPRETATION	1
359 
360 /*
361  * Since tcp_listener is not cleared atomically with tcp_detached
362  * being cleared we need this extra bit to tell a detached connection
363  * apart from one that is in the process of being accepted.
364  */
365 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
366 	(TCP_IS_DETACHED(tcp) &&	\
367 	    (!(tcp)->tcp_hard_binding))
368 
369 /*
370  * TCP reassembly macros.  We hide starting and ending sequence numbers in
371  * b_next and b_prev of messages on the reassembly queue.  The messages are
372  * chained using b_cont.  These macros are used in tcp_reass() so we don't
373  * have to see the ugly casts and assignments.
374  */
375 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
376 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
377 					(mblk_t *)(uintptr_t)(u))
378 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
379 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
380 					(mblk_t *)(uintptr_t)(u))
381 
382 /*
383  * Implementation of TCP Timers.
384  * =============================
385  *
386  * INTERFACE:
387  *
388  * There are two basic functions dealing with tcp timers:
389  *
390  *	timeout_id_t	tcp_timeout(connp, func, time)
391  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
392  *	TCP_TIMER_RESTART(tcp, intvl)
393  *
394  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
395  * after 'time' ticks passed. The function called by timeout() must adhere to
396  * the same restrictions as a driver soft interrupt handler - it must not sleep
397  * or call other functions that might sleep. The value returned is the opaque
398  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
399  * cancel the request. The call to tcp_timeout() may fail in which case it
400  * returns zero. This is different from the timeout(9F) function which never
401  * fails.
402  *
403  * The call-back function 'func' always receives 'connp' as its single
404  * argument. It is always executed in the squeue corresponding to the tcp
405  * structure. The tcp structure is guaranteed to be present at the time the
406  * call-back is called.
407  *
408  * NOTE: The call-back function 'func' is never called if tcp is in
409  * 	the TCPS_CLOSED state.
410  *
411  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
412  * request. locks acquired by the call-back routine should not be held across
413  * the call to tcp_timeout_cancel() or a deadlock may result.
414  *
415  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
416  * Otherwise, it returns an integer value greater than or equal to 0. In
417  * particular, if the call-back function is already placed on the squeue, it can
418  * not be canceled.
419  *
420  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
421  * 	within squeue context corresponding to the tcp instance. Since the
422  *	call-back is also called via the same squeue, there are no race
423  *	conditions described in untimeout(9F) manual page since all calls are
424  *	strictly serialized.
425  *
426  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
427  *	stored in tcp_timer_tid and starts a new one using
428  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
429  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
430  *	field.
431  *
432  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
433  *	call-back may still be called, so it is possible tcp_timer() will be
434  *	called several times. This should not be a problem since tcp_timer()
435  *	should always check the tcp instance state.
436  *
437  *
438  * IMPLEMENTATION:
439  *
440  * TCP timers are implemented using three-stage process. The call to
441  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
442  * when the timer expires. The tcp_timer_callback() arranges the call of the
443  * tcp_timer_handler() function via squeue corresponding to the tcp
444  * instance. The tcp_timer_handler() calls actual requested timeout call-back
445  * and passes tcp instance as an argument to it. Information is passed between
446  * stages using the tcp_timer_t structure which contains the connp pointer, the
447  * tcp call-back to call and the timeout id returned by the timeout(9F).
448  *
449  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
450  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
451  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
452  * returns the pointer to this mblk.
453  *
454  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
455  * looks like a normal mblk without actual dblk attached to it.
456  *
457  * To optimize performance each tcp instance holds a small cache of timer
458  * mblocks. In the current implementation it caches up to two timer mblocks per
459  * tcp instance. The cache is preserved over tcp frees and is only freed when
460  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
461  * timer processing happens on a corresponding squeue, the cache manipulation
462  * does not require any locks. Experiments show that majority of timer mblocks
463  * allocations are satisfied from the tcp cache and do not involve kmem calls.
464  *
465  * The tcp_timeout() places a refhold on the connp instance which guarantees
466  * that it will be present at the time the call-back function fires. The
467  * tcp_timer_handler() drops the reference after calling the call-back, so the
468  * call-back function does not need to manipulate the references explicitly.
469  */
470 
471 typedef struct tcp_timer_s {
472 	conn_t	*connp;
473 	void 	(*tcpt_proc)(void *);
474 	callout_id_t   tcpt_tid;
475 } tcp_timer_t;
476 
477 static kmem_cache_t *tcp_timercache;
478 kmem_cache_t	*tcp_sack_info_cache;
479 
480 /*
481  * For scalability, we must not run a timer for every TCP connection
482  * in TIME_WAIT state.  To see why, consider (for time wait interval of
483  * 4 minutes):
484  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
485  *
486  * This list is ordered by time, so you need only delete from the head
487  * until you get to entries which aren't old enough to delete yet.
488  * The list consists of only the detached TIME_WAIT connections.
489  *
490  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
491  * becomes detached TIME_WAIT (either by changing the state and already
492  * being detached or the other way around). This means that the TIME_WAIT
493  * state can be extended (up to doubled) if the connection doesn't become
494  * detached for a long time.
495  *
496  * The list manipulations (including tcp_time_wait_next/prev)
497  * are protected by the tcp_time_wait_lock. The content of the
498  * detached TIME_WAIT connections is protected by the normal perimeters.
499  *
500  * This list is per squeue and squeues are shared across the tcp_stack_t's.
501  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
502  * and conn_netstack.
503  * The tcp_t's that are added to tcp_free_list are disassociated and
504  * have NULL tcp_tcps and conn_netstack pointers.
505  */
506 typedef struct tcp_squeue_priv_s {
507 	kmutex_t	tcp_time_wait_lock;
508 	callout_id_t	tcp_time_wait_tid;
509 	tcp_t		*tcp_time_wait_head;
510 	tcp_t		*tcp_time_wait_tail;
511 	tcp_t		*tcp_free_list;
512 	uint_t		tcp_free_list_cnt;
513 } tcp_squeue_priv_t;
514 
515 /*
516  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
517  * Running it every 5 seconds seems to give the best results.
518  */
519 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
520 
521 /*
522  * To prevent memory hog, limit the number of entries in tcp_free_list
523  * to 1% of available memory / number of cpus
524  */
525 uint_t tcp_free_list_max_cnt = 0;
526 
527 #define	TCP_XMIT_LOWATER	4096
528 #define	TCP_XMIT_HIWATER	49152
529 #define	TCP_RECV_LOWATER	2048
530 #define	TCP_RECV_HIWATER	128000
531 
532 /*
533  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
534  */
535 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
536 
537 #define	TIDUSZ	4096	/* transport interface data unit size */
538 
539 /*
540  * Bind hash list size and has function.  It has to be a power of 2 for
541  * hashing.
542  */
543 #define	TCP_BIND_FANOUT_SIZE	512
544 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
545 /*
546  * Size of listen and acceptor hash list.  It has to be a power of 2 for
547  * hashing.
548  */
549 #define	TCP_FANOUT_SIZE		256
550 
551 #ifdef	_ILP32
552 #define	TCP_ACCEPTOR_HASH(accid)					\
553 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
554 #else
555 #define	TCP_ACCEPTOR_HASH(accid)					\
556 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
557 #endif	/* _ILP32 */
558 
559 #define	IP_ADDR_CACHE_SIZE	2048
560 #define	IP_ADDR_CACHE_HASH(faddr)					\
561 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
562 
563 /*
564  * TCP options struct returned from tcp_parse_options.
565  */
566 typedef struct tcp_opt_s {
567 	uint32_t	tcp_opt_mss;
568 	uint32_t	tcp_opt_wscale;
569 	uint32_t	tcp_opt_ts_val;
570 	uint32_t	tcp_opt_ts_ecr;
571 	tcp_t		*tcp;
572 } tcp_opt_t;
573 
574 /*
575  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
576  */
577 
578 #ifdef _BIG_ENDIAN
579 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
580 	(TCPOPT_TSTAMP << 8) | 10)
581 #else
582 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
583 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
584 #endif
585 
586 /*
587  * Flags returned from tcp_parse_options.
588  */
589 #define	TCP_OPT_MSS_PRESENT	1
590 #define	TCP_OPT_WSCALE_PRESENT	2
591 #define	TCP_OPT_TSTAMP_PRESENT	4
592 #define	TCP_OPT_SACK_OK_PRESENT	8
593 #define	TCP_OPT_SACK_PRESENT	16
594 
595 /* TCP option length */
596 #define	TCPOPT_NOP_LEN		1
597 #define	TCPOPT_MAXSEG_LEN	4
598 #define	TCPOPT_WS_LEN		3
599 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
600 #define	TCPOPT_TSTAMP_LEN	10
601 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
602 #define	TCPOPT_SACK_OK_LEN	2
603 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
604 #define	TCPOPT_REAL_SACK_LEN	4
605 #define	TCPOPT_MAX_SACK_LEN	36
606 #define	TCPOPT_HEADER_LEN	2
607 
608 /* TCP cwnd burst factor. */
609 #define	TCP_CWND_INFINITE	65535
610 #define	TCP_CWND_SS		3
611 #define	TCP_CWND_NORMAL		5
612 
613 /* Maximum TCP initial cwin (start/restart). */
614 #define	TCP_MAX_INIT_CWND	8
615 
616 /*
617  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
618  * either tcp_slow_start_initial or tcp_slow_start_after idle
619  * depending on the caller.  If the upper layer has not used the
620  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
621  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
622  * If the upper layer has changed set the tcp_init_cwnd, just use
623  * it to calculate the tcp_cwnd.
624  */
625 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
626 {									\
627 	if ((tcp)->tcp_init_cwnd == 0) {				\
628 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
629 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
630 	} else {							\
631 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
632 	}								\
633 	tcp->tcp_cwnd_cnt = 0;						\
634 }
635 
636 /* TCP Timer control structure */
637 typedef struct tcpt_s {
638 	pfv_t	tcpt_pfv;	/* The routine we are to call */
639 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
640 } tcpt_t;
641 
642 /*
643  * Functions called directly via squeue having a prototype of edesc_t.
644  */
645 void		tcp_input_listener(void *arg, mblk_t *mp, void *arg2,
646     ip_recv_attr_t *ira);
647 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2,
648     ip_recv_attr_t *dummy);
649 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2,
650     ip_recv_attr_t *dummy);
651 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2,
652     ip_recv_attr_t *dummy);
653 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2,
654     ip_recv_attr_t *dummy);
655 void		tcp_input_data(void *arg, mblk_t *mp, void *arg2,
656     ip_recv_attr_t *ira);
657 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2,
658     ip_recv_attr_t *dummy);
659 void		tcp_output(void *arg, mblk_t *mp, void *arg2,
660     ip_recv_attr_t *dummy);
661 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2,
662     ip_recv_attr_t *dummy);
663 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2,
664     ip_recv_attr_t *dummy);
665 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2,
666     ip_recv_attr_t *dummy);
667 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2,
668     ip_recv_attr_t *dummy);
669 
670 
671 /* Prototype for TCP functions */
672 static void	tcp_random_init(void);
673 int		tcp_random(void);
674 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
675 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
676 		    tcp_t *eager);
677 static int	tcp_set_destination(tcp_t *tcp);
678 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
679     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
680     boolean_t user_specified);
681 static void	tcp_closei_local(tcp_t *tcp);
682 static void	tcp_close_detached(tcp_t *tcp);
683 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr,
684 		    mblk_t *idmp, mblk_t **defermp, ip_recv_attr_t *ira);
685 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
686 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
687 		    in_port_t dstport, uint_t srcid);
688 static int	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
689 		    in_port_t dstport, uint32_t flowinfo,
690 		    uint_t srcid, uint32_t scope_id);
691 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
692 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
693 static char	*tcp_display(tcp_t *tcp, char *, char);
694 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
695 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
696 static void	tcp_eager_unlink(tcp_t *tcp);
697 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
698 		    int unixerr);
699 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
700 		    int tlierr, int unixerr);
701 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
702 		    cred_t *cr);
703 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
704 		    char *value, caddr_t cp, cred_t *cr);
705 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
706 		    char *value, caddr_t cp, cred_t *cr);
707 static int	tcp_tpistate(tcp_t *tcp);
708 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
709     int caller_holds_lock);
710 static void	tcp_bind_hash_remove(tcp_t *tcp);
711 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
712 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
713 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
714 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
715 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
716 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
717 static void	tcp_init_values(tcp_t *tcp);
718 static void	tcp_ip_notify(tcp_t *tcp);
719 static void	tcp_iss_init(tcp_t *tcp);
720 static void	tcp_keepalive_killer(void *arg);
721 static int	tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt);
722 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
723 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
724 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
725 static boolean_t tcp_allow_connopt_set(int level, int name);
726 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
727 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
728 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
729     tcp_stack_t *);
730 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
731 		    caddr_t cp, cred_t *cr);
732 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
733 		    caddr_t cp, cred_t *cr);
734 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
735 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
736 		    caddr_t cp, cred_t *cr);
737 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
738 static void	tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt);
739 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
740 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
741 static void	tcp_reinit(tcp_t *tcp);
742 static void	tcp_reinit_values(tcp_t *tcp);
743 
744 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
745 static uint_t	tcp_rcv_drain(tcp_t *tcp);
746 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
747 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
748 static void	tcp_ss_rexmit(tcp_t *tcp);
749 static mblk_t	*tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
750     ip_recv_attr_t *);
751 static void	tcp_process_options(tcp_t *, tcpha_t *);
752 static void	tcp_rsrv(queue_t *q);
753 static int	tcp_snmp_state(tcp_t *tcp);
754 static void	tcp_timer(void *arg);
755 static void	tcp_timer_callback(void *);
756 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
757     boolean_t random);
758 static in_port_t tcp_get_next_priv_port(const tcp_t *);
759 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
760 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
761 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
762 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
763 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
764 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
765 static int	tcp_send(tcp_t *tcp, const int mss,
766 		    const int total_hdr_len, const int tcp_hdr_len,
767 		    const int num_sack_blk, int *usable, uint_t *snxt,
768 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time);
769 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
770 		    int num_sack_blk);
771 static void	tcp_wsrv(queue_t *q);
772 static int	tcp_xmit_end(tcp_t *tcp);
773 static void	tcp_ack_timer(void *arg);
774 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
775 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
776 		    uint32_t seq, uint32_t ack, int ctl, ip_recv_attr_t *,
777 		    ip_stack_t *, conn_t *);
778 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
779 		    uint32_t ack, int ctl);
780 static void	tcp_set_rto(tcp_t *, time_t);
781 static void	tcp_icmp_input(void *, mblk_t *, void *, ip_recv_attr_t *);
782 static void	tcp_icmp_error_ipv6(tcp_t *, mblk_t *, ip_recv_attr_t *);
783 static boolean_t tcp_verifyicmp(conn_t *, void *, icmph_t *, icmp6_t *,
784     ip_recv_attr_t *);
785 static int	tcp_build_hdrs(tcp_t *);
786 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
787     uint32_t seg_seq, uint32_t seg_ack, int seg_len, tcpha_t *tcpha,
788     ip_recv_attr_t *ira);
789 boolean_t	tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp);
790 static boolean_t tcp_zcopy_check(tcp_t *);
791 static void	tcp_zcopy_notify(tcp_t *);
792 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, boolean_t);
793 static void	tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa);
794 static void	tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only);
795 static void	tcp_update_zcopy(tcp_t *tcp);
796 static void	tcp_notify(void *, ip_xmit_attr_t *, ixa_notify_type_t,
797     ixa_notify_arg_t);
798 static void	tcp_rexmit_after_error(tcp_t *tcp);
799 static void	tcp_send_data(tcp_t *, mblk_t *);
800 extern mblk_t	*tcp_timermp_alloc(int);
801 extern void	tcp_timermp_free(tcp_t *);
802 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
803 static void	tcp_stop_lingering(tcp_t *tcp);
804 static void	tcp_close_linger_timeout(void *arg);
805 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
806 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
807 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
808 static void	tcp_g_kstat_fini(kstat_t *);
809 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
810 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
811 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
812 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
813 static int	tcp_kstat_update(kstat_t *kp, int rw);
814 static mblk_t	*tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
815     ip_recv_attr_t *ira);
816 static mblk_t	*tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
817     ip_recv_attr_t *ira);
818 static int	tcp_squeue_switch(int);
819 
820 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
821 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
822 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
823 static int	tcp_tpi_close(queue_t *, int);
824 static int	tcp_tpi_close_accept(queue_t *);
825 
826 static void	tcp_squeue_add(squeue_t *);
827 static void	tcp_setcred_data(mblk_t *, ip_recv_attr_t *);
828 
829 extern void	tcp_kssl_input(tcp_t *, mblk_t *, cred_t *);
830 
831 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy);
832 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
833     ip_recv_attr_t *dummy);
834 
835 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
836 	    sock_upper_handle_t, cred_t *);
837 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
838 static int tcp_do_listen(conn_t *, struct sockaddr *, socklen_t, int, cred_t *,
839     boolean_t);
840 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
841     cred_t *, pid_t);
842 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
843     boolean_t);
844 static int tcp_do_unbind(conn_t *);
845 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
846     boolean_t);
847 
848 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_t *);
849 
850 /*
851  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
852  *
853  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
854  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
855  * (defined in tcp.h) needs to be filled in and passed into the kernel
856  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
857  * structure contains the four-tuple of a TCP connection and a range of TCP
858  * states (specified by ac_start and ac_end). The use of wildcard addresses
859  * and ports is allowed. Connections with a matching four tuple and a state
860  * within the specified range will be aborted. The valid states for the
861  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
862  * inclusive.
863  *
864  * An application which has its connection aborted by this ioctl will receive
865  * an error that is dependent on the connection state at the time of the abort.
866  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
867  * though a RST packet has been received.  If the connection state is equal to
868  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
869  * and all resources associated with the connection will be freed.
870  */
871 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
872 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
873 static void	tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
874     ip_recv_attr_t *dummy);
875 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
876 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
877 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
878     boolean_t, tcp_stack_t *);
879 
880 static struct module_info tcp_rinfo =  {
881 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
882 };
883 
884 static struct module_info tcp_winfo =  {
885 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
886 };
887 
888 /*
889  * Entry points for TCP as a device. The normal case which supports
890  * the TCP functionality.
891  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
892  */
893 struct qinit tcp_rinitv4 = {
894 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
895 };
896 
897 struct qinit tcp_rinitv6 = {
898 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
899 };
900 
901 struct qinit tcp_winit = {
902 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
903 };
904 
905 /* Initial entry point for TCP in socket mode. */
906 struct qinit tcp_sock_winit = {
907 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
908 };
909 
910 /* TCP entry point during fallback */
911 struct qinit tcp_fallback_sock_winit = {
912 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
913 };
914 
915 /*
916  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
917  * an accept. Avoid allocating data structures since eager has already
918  * been created.
919  */
920 struct qinit tcp_acceptor_rinit = {
921 	NULL, (pfi_t)tcp_rsrv, NULL, tcp_tpi_close_accept, NULL, &tcp_winfo
922 };
923 
924 struct qinit tcp_acceptor_winit = {
925 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
926 };
927 
928 /* For AF_INET aka /dev/tcp */
929 struct streamtab tcpinfov4 = {
930 	&tcp_rinitv4, &tcp_winit
931 };
932 
933 /* For AF_INET6 aka /dev/tcp6 */
934 struct streamtab tcpinfov6 = {
935 	&tcp_rinitv6, &tcp_winit
936 };
937 
938 sock_downcalls_t sock_tcp_downcalls;
939 
940 /* Setable only in /etc/system. Move to ndd? */
941 boolean_t tcp_icmp_source_quench = B_FALSE;
942 
943 /*
944  * Following assumes TPI alignment requirements stay along 32 bit
945  * boundaries
946  */
947 #define	ROUNDUP32(x) \
948 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
949 
950 /* Template for response to info request. */
951 static struct T_info_ack tcp_g_t_info_ack = {
952 	T_INFO_ACK,		/* PRIM_type */
953 	0,			/* TSDU_size */
954 	T_INFINITE,		/* ETSDU_size */
955 	T_INVALID,		/* CDATA_size */
956 	T_INVALID,		/* DDATA_size */
957 	sizeof (sin_t),		/* ADDR_size */
958 	0,			/* OPT_size - not initialized here */
959 	TIDUSZ,			/* TIDU_size */
960 	T_COTS_ORD,		/* SERV_type */
961 	TCPS_IDLE,		/* CURRENT_state */
962 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
963 };
964 
965 static struct T_info_ack tcp_g_t_info_ack_v6 = {
966 	T_INFO_ACK,		/* PRIM_type */
967 	0,			/* TSDU_size */
968 	T_INFINITE,		/* ETSDU_size */
969 	T_INVALID,		/* CDATA_size */
970 	T_INVALID,		/* DDATA_size */
971 	sizeof (sin6_t),	/* ADDR_size */
972 	0,			/* OPT_size - not initialized here */
973 	TIDUSZ,		/* TIDU_size */
974 	T_COTS_ORD,		/* SERV_type */
975 	TCPS_IDLE,		/* CURRENT_state */
976 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
977 };
978 
979 #define	MS	1L
980 #define	SECONDS	(1000 * MS)
981 #define	MINUTES	(60 * SECONDS)
982 #define	HOURS	(60 * MINUTES)
983 #define	DAYS	(24 * HOURS)
984 
985 #define	PARAM_MAX (~(uint32_t)0)
986 
987 /* Max size IP datagram is 64k - 1 */
988 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcpha_t)))
989 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcpha_t)))
990 /* Max of the above */
991 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
992 
993 /* Largest TCP port number */
994 #define	TCP_MAX_PORT	(64 * 1024 - 1)
995 
996 /*
997  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
998  * layer header.  It has to be a multiple of 4.
999  */
1000 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1001 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1002 
1003 /*
1004  * All of these are alterable, within the min/max values given, at run time.
1005  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1006  * per the TCP spec.
1007  */
1008 /* BEGIN CSTYLED */
1009 static tcpparam_t	lcl_tcp_param_arr[] = {
1010  /*min		max		value		name */
1011  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1012  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1013  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1014  { 1,		1024,		1,		"tcp_conn_req_min" },
1015  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1016  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1017  { 0,		10,		0,		"tcp_debug" },
1018  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1019  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1020  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1021  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1022  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1023  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1024  { 1,		255,		64,		"tcp_ipv4_ttl"},
1025  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1026  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1027  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1028  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1029  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1030  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1031  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1032  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1033  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1034  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1035  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1036  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1037  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1038  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1039  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1040  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1041  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1042  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1043  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1044  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1045  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1046  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1047  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1048 /*
1049  * Question:  What default value should I set for tcp_strong_iss?
1050  */
1051  { 0,		2,		1,		"tcp_strong_iss"},
1052  { 0,		65536,		20,		"tcp_rtt_updates"},
1053  { 0,		1,		1,		"tcp_wscale_always"},
1054  { 0,		1,		0,		"tcp_tstamp_always"},
1055  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1056  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1057  { 0,		16,		2,		"tcp_deferred_acks_max"},
1058  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1059  { 1,		4,		4,		"tcp_slow_start_initial"},
1060  { 0,		2,		2,		"tcp_sack_permitted"},
1061  { 0,		1,		1,		"tcp_compression_enabled"},
1062  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1063  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1064  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1065  { 0,		1,		0,		"tcp_rev_src_routes"},
1066  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1067  { 0,		16,		8,		"tcp_local_dacks_max"},
1068  { 0,		2,		1,		"tcp_ecn_permitted"},
1069  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1070  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1071  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1072  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1073  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1074  { 0,		1,		0,		"tcp_dev_flow_ctl"},
1075 };
1076 /* END CSTYLED */
1077 
1078 /* Round up the value to the nearest mss. */
1079 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1080 
1081 /*
1082  * Set ECN capable transport (ECT) code point in IP header.
1083  *
1084  * Note that there are 2 ECT code points '01' and '10', which are called
1085  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1086  * point ECT(0) for TCP as described in RFC 2481.
1087  */
1088 #define	SET_ECT(tcp, iph) \
1089 	if ((tcp)->tcp_connp->conn_ipversion == IPV4_VERSION) { \
1090 		/* We need to clear the code point first. */ \
1091 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1092 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1093 	} else { \
1094 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1095 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1096 	}
1097 
1098 /*
1099  * The format argument to pass to tcp_display().
1100  * DISP_PORT_ONLY means that the returned string has only port info.
1101  * DISP_ADDR_AND_PORT means that the returned string also contains the
1102  * remote and local IP address.
1103  */
1104 #define	DISP_PORT_ONLY		1
1105 #define	DISP_ADDR_AND_PORT	2
1106 
1107 #define	IS_VMLOANED_MBLK(mp) \
1108 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1109 
1110 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1111 
1112 /*
1113  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1114  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1115  * determined dynamically during tcp_set_destination(), which is the default.
1116  */
1117 boolean_t tcp_static_maxpsz = B_FALSE;
1118 
1119 /* Setable in /etc/system */
1120 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1121 uint32_t tcp_random_anon_port = 1;
1122 
1123 /*
1124  * To reach to an eager in Q0 which can be dropped due to an incoming
1125  * new SYN request when Q0 is full, a new doubly linked list is
1126  * introduced. This list allows to select an eager from Q0 in O(1) time.
1127  * This is needed to avoid spending too much time walking through the
1128  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1129  * this new list has to be a member of Q0.
1130  * This list is headed by listener's tcp_t. When the list is empty,
1131  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1132  * of listener's tcp_t point to listener's tcp_t itself.
1133  *
1134  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1135  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1136  * These macros do not affect the eager's membership to Q0.
1137  */
1138 
1139 
1140 #define	MAKE_DROPPABLE(listener, eager)					\
1141 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1142 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1143 		    = (eager);						\
1144 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1145 		(eager)->tcp_eager_next_drop_q0 =			\
1146 		    (listener)->tcp_eager_next_drop_q0;			\
1147 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1148 	}
1149 
1150 #define	MAKE_UNDROPPABLE(eager)						\
1151 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1152 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1153 		    = (eager)->tcp_eager_prev_drop_q0;			\
1154 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1155 		    = (eager)->tcp_eager_next_drop_q0;			\
1156 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1157 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1158 	}
1159 
1160 /*
1161  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1162  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1163  * data, TCP will not respond with an ACK.  RFC 793 requires that
1164  * TCP responds with an ACK for such a bogus ACK.  By not following
1165  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1166  * an attacker successfully spoofs an acceptable segment to our
1167  * peer; or when our peer is "confused."
1168  */
1169 uint32_t tcp_drop_ack_unsent_cnt = 10;
1170 
1171 /*
1172  * Hook functions to enable cluster networking
1173  * On non-clustered systems these vectors must always be NULL.
1174  */
1175 
1176 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1177 			    sa_family_t addr_family, uint8_t *laddrp,
1178 			    in_port_t lport, void *args) = NULL;
1179 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1180 			    sa_family_t addr_family, uint8_t *laddrp,
1181 			    in_port_t lport, void *args) = NULL;
1182 
1183 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1184 			    boolean_t is_outgoing,
1185 			    sa_family_t addr_family,
1186 			    uint8_t *laddrp, in_port_t lport,
1187 			    uint8_t *faddrp, in_port_t fport,
1188 			    void *args) = NULL;
1189 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1190 			    sa_family_t addr_family, uint8_t *laddrp,
1191 			    in_port_t lport, uint8_t *faddrp,
1192 			    in_port_t fport, void *args) = NULL;
1193 
1194 
1195 /*
1196  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1197  */
1198 #define	CL_INET_CONNECT(connp, is_outgoing, err) {		\
1199 	(err) = 0;						\
1200 	if (cl_inet_connect2 != NULL) {				\
1201 		/*						\
1202 		 * Running in cluster mode - register active connection	\
1203 		 * information						\
1204 		 */							\
1205 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1206 			if ((connp)->conn_laddr_v4 != 0) {		\
1207 				(err) = (*cl_inet_connect2)(		\
1208 				    (connp)->conn_netstack->netstack_stackid,\
1209 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1210 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1211 				    (in_port_t)(connp)->conn_lport,	\
1212 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1213 				    (in_port_t)(connp)->conn_fport, NULL); \
1214 			}						\
1215 		} else {						\
1216 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1217 			    &(connp)->conn_laddr_v6)) {			\
1218 				(err) = (*cl_inet_connect2)(		\
1219 				    (connp)->conn_netstack->netstack_stackid,\
1220 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1221 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1222 				    (in_port_t)(connp)->conn_lport,	\
1223 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1224 				    (in_port_t)(connp)->conn_fport, NULL); \
1225 			}						\
1226 		}							\
1227 	}								\
1228 }
1229 
1230 #define	CL_INET_DISCONNECT(connp)	{				\
1231 	if (cl_inet_disconnect != NULL) {				\
1232 		/*							\
1233 		 * Running in cluster mode - deregister active		\
1234 		 * connection information				\
1235 		 */							\
1236 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1237 			if ((connp)->conn_laddr_v4 != 0) {		\
1238 				(*cl_inet_disconnect)(			\
1239 				    (connp)->conn_netstack->netstack_stackid,\
1240 				    IPPROTO_TCP, AF_INET,		\
1241 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1242 				    (in_port_t)(connp)->conn_lport,	\
1243 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1244 				    (in_port_t)(connp)->conn_fport, NULL); \
1245 			}						\
1246 		} else {						\
1247 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1248 			    &(connp)->conn_laddr_v6)) {			\
1249 				(*cl_inet_disconnect)(			\
1250 				    (connp)->conn_netstack->netstack_stackid,\
1251 				    IPPROTO_TCP, AF_INET6,		\
1252 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1253 				    (in_port_t)(connp)->conn_lport,	\
1254 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1255 				    (in_port_t)(connp)->conn_fport, NULL); \
1256 			}						\
1257 		}							\
1258 	}								\
1259 }
1260 
1261 /*
1262  * Cluster networking hook for traversing current connection list.
1263  * This routine is used to extract the current list of live connections
1264  * which must continue to to be dispatched to this node.
1265  */
1266 int cl_tcp_walk_list(netstackid_t stack_id,
1267     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1268 
1269 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1270     void *arg, tcp_stack_t *tcps);
1271 
1272 static void
1273 tcp_set_recv_threshold(tcp_t *tcp, uint32_t new_rcvthresh)
1274 {
1275 	uint32_t default_threshold = SOCKET_RECVHIWATER >> 3;
1276 
1277 	if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
1278 		conn_t *connp = tcp->tcp_connp;
1279 		struct sock_proto_props sopp;
1280 
1281 		/*
1282 		 * only increase rcvthresh upto default_threshold
1283 		 */
1284 		if (new_rcvthresh > default_threshold)
1285 			new_rcvthresh = default_threshold;
1286 
1287 		sopp.sopp_flags = SOCKOPT_RCVTHRESH;
1288 		sopp.sopp_rcvthresh = new_rcvthresh;
1289 
1290 		(*connp->conn_upcalls->su_set_proto_props)
1291 		    (connp->conn_upper_handle, &sopp);
1292 	}
1293 }
1294 /*
1295  * Figure out the value of window scale opton.  Note that the rwnd is
1296  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1297  * We cannot find the scale value and then do a round up of tcp_rwnd
1298  * because the scale value may not be correct after that.
1299  *
1300  * Set the compiler flag to make this function inline.
1301  */
1302 static void
1303 tcp_set_ws_value(tcp_t *tcp)
1304 {
1305 	int i;
1306 	uint32_t rwnd = tcp->tcp_rwnd;
1307 
1308 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1309 	    i++, rwnd >>= 1)
1310 		;
1311 	tcp->tcp_rcv_ws = i;
1312 }
1313 
1314 /*
1315  * Remove a connection from the list of detached TIME_WAIT connections.
1316  * It returns B_FALSE if it can't remove the connection from the list
1317  * as the connection has already been removed from the list due to an
1318  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1319  */
1320 static boolean_t
1321 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1322 {
1323 	boolean_t	locked = B_FALSE;
1324 
1325 	if (tcp_time_wait == NULL) {
1326 		tcp_time_wait = *((tcp_squeue_priv_t **)
1327 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1328 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1329 		locked = B_TRUE;
1330 	} else {
1331 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1332 	}
1333 
1334 	if (tcp->tcp_time_wait_expire == 0) {
1335 		ASSERT(tcp->tcp_time_wait_next == NULL);
1336 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1337 		if (locked)
1338 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1339 		return (B_FALSE);
1340 	}
1341 	ASSERT(TCP_IS_DETACHED(tcp));
1342 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1343 
1344 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1345 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1346 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1347 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1348 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1349 			    NULL;
1350 		} else {
1351 			tcp_time_wait->tcp_time_wait_tail = NULL;
1352 		}
1353 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1354 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1355 		ASSERT(tcp->tcp_time_wait_next == NULL);
1356 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1357 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1358 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1359 	} else {
1360 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1361 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1362 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1363 		    tcp->tcp_time_wait_next;
1364 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1365 		    tcp->tcp_time_wait_prev;
1366 	}
1367 	tcp->tcp_time_wait_next = NULL;
1368 	tcp->tcp_time_wait_prev = NULL;
1369 	tcp->tcp_time_wait_expire = 0;
1370 
1371 	if (locked)
1372 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1373 	return (B_TRUE);
1374 }
1375 
1376 /*
1377  * Add a connection to the list of detached TIME_WAIT connections
1378  * and set its time to expire.
1379  */
1380 static void
1381 tcp_time_wait_append(tcp_t *tcp)
1382 {
1383 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1384 	tcp_squeue_priv_t *tcp_time_wait =
1385 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1386 	    SQPRIVATE_TCP));
1387 
1388 	tcp_timers_stop(tcp);
1389 
1390 	/* Freed above */
1391 	ASSERT(tcp->tcp_timer_tid == 0);
1392 	ASSERT(tcp->tcp_ack_tid == 0);
1393 
1394 	/* must have happened at the time of detaching the tcp */
1395 	ASSERT(tcp->tcp_ptpahn == NULL);
1396 	ASSERT(tcp->tcp_flow_stopped == 0);
1397 	ASSERT(tcp->tcp_time_wait_next == NULL);
1398 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1399 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1400 	ASSERT(tcp->tcp_listener == NULL);
1401 
1402 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1403 	/*
1404 	 * The value computed below in tcp->tcp_time_wait_expire may
1405 	 * appear negative or wrap around. That is ok since our
1406 	 * interest is only in the difference between the current lbolt
1407 	 * value and tcp->tcp_time_wait_expire. But the value should not
1408 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1409 	 * The corresponding comparison in tcp_time_wait_collector() uses
1410 	 * modular arithmetic.
1411 	 */
1412 	tcp->tcp_time_wait_expire +=
1413 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1414 	if (tcp->tcp_time_wait_expire == 0)
1415 		tcp->tcp_time_wait_expire = 1;
1416 
1417 	ASSERT(TCP_IS_DETACHED(tcp));
1418 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1419 	ASSERT(tcp->tcp_time_wait_next == NULL);
1420 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1421 	TCP_DBGSTAT(tcps, tcp_time_wait);
1422 
1423 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1424 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1425 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1426 		tcp_time_wait->tcp_time_wait_head = tcp;
1427 	} else {
1428 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1429 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1430 		    TCPS_TIME_WAIT);
1431 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1432 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1433 	}
1434 	tcp_time_wait->tcp_time_wait_tail = tcp;
1435 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1436 }
1437 
1438 /* ARGSUSED */
1439 void
1440 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1441 {
1442 	conn_t	*connp = (conn_t *)arg;
1443 	tcp_t	*tcp = connp->conn_tcp;
1444 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1445 
1446 	ASSERT(tcp != NULL);
1447 	if (tcp->tcp_state == TCPS_CLOSED) {
1448 		return;
1449 	}
1450 
1451 	ASSERT((connp->conn_family == AF_INET &&
1452 	    connp->conn_ipversion == IPV4_VERSION) ||
1453 	    (connp->conn_family == AF_INET6 &&
1454 	    (connp->conn_ipversion == IPV4_VERSION ||
1455 	    connp->conn_ipversion == IPV6_VERSION)));
1456 	ASSERT(!tcp->tcp_listener);
1457 
1458 	TCP_STAT(tcps, tcp_time_wait_reap);
1459 	ASSERT(TCP_IS_DETACHED(tcp));
1460 
1461 	/*
1462 	 * Because they have no upstream client to rebind or tcp_close()
1463 	 * them later, we axe the connection here and now.
1464 	 */
1465 	tcp_close_detached(tcp);
1466 }
1467 
1468 /*
1469  * Remove cached/latched IPsec references.
1470  */
1471 void
1472 tcp_ipsec_cleanup(tcp_t *tcp)
1473 {
1474 	conn_t		*connp = tcp->tcp_connp;
1475 
1476 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1477 
1478 	if (connp->conn_latch != NULL) {
1479 		IPLATCH_REFRELE(connp->conn_latch);
1480 		connp->conn_latch = NULL;
1481 	}
1482 	if (connp->conn_latch_in_policy != NULL) {
1483 		IPPOL_REFRELE(connp->conn_latch_in_policy);
1484 		connp->conn_latch_in_policy = NULL;
1485 	}
1486 	if (connp->conn_latch_in_action != NULL) {
1487 		IPACT_REFRELE(connp->conn_latch_in_action);
1488 		connp->conn_latch_in_action = NULL;
1489 	}
1490 	if (connp->conn_policy != NULL) {
1491 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1492 		connp->conn_policy = NULL;
1493 	}
1494 }
1495 
1496 /*
1497  * Cleaup before placing on free list.
1498  * Disassociate from the netstack/tcp_stack_t since the freelist
1499  * is per squeue and not per netstack.
1500  */
1501 void
1502 tcp_cleanup(tcp_t *tcp)
1503 {
1504 	mblk_t		*mp;
1505 	tcp_sack_info_t	*tcp_sack_info;
1506 	conn_t		*connp = tcp->tcp_connp;
1507 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1508 	netstack_t	*ns = tcps->tcps_netstack;
1509 	mblk_t		*tcp_rsrv_mp;
1510 
1511 	tcp_bind_hash_remove(tcp);
1512 
1513 	/* Cleanup that which needs the netstack first */
1514 	tcp_ipsec_cleanup(tcp);
1515 	ixa_cleanup(connp->conn_ixa);
1516 
1517 	if (connp->conn_ht_iphc != NULL) {
1518 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
1519 		connp->conn_ht_iphc = NULL;
1520 		connp->conn_ht_iphc_allocated = 0;
1521 		connp->conn_ht_iphc_len = 0;
1522 		connp->conn_ht_ulp = NULL;
1523 		connp->conn_ht_ulp_len = 0;
1524 		tcp->tcp_ipha = NULL;
1525 		tcp->tcp_ip6h = NULL;
1526 		tcp->tcp_tcpha = NULL;
1527 	}
1528 
1529 	/* We clear any IP_OPTIONS and extension headers */
1530 	ip_pkt_free(&connp->conn_xmit_ipp);
1531 
1532 	tcp_free(tcp);
1533 
1534 	/* Release any SSL context */
1535 	if (tcp->tcp_kssl_ent != NULL) {
1536 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1537 		tcp->tcp_kssl_ent = NULL;
1538 	}
1539 
1540 	if (tcp->tcp_kssl_ctx != NULL) {
1541 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1542 		tcp->tcp_kssl_ctx = NULL;
1543 	}
1544 	tcp->tcp_kssl_pending = B_FALSE;
1545 
1546 	/*
1547 	 * Since we will bzero the entire structure, we need to
1548 	 * remove it and reinsert it in global hash list. We
1549 	 * know the walkers can't get to this conn because we
1550 	 * had set CONDEMNED flag earlier and checked reference
1551 	 * under conn_lock so walker won't pick it and when we
1552 	 * go the ipcl_globalhash_remove() below, no walker
1553 	 * can get to it.
1554 	 */
1555 	ipcl_globalhash_remove(connp);
1556 
1557 	/* Save some state */
1558 	mp = tcp->tcp_timercache;
1559 
1560 	tcp_sack_info = tcp->tcp_sack_info;
1561 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1562 
1563 	if (connp->conn_cred != NULL) {
1564 		crfree(connp->conn_cred);
1565 		connp->conn_cred = NULL;
1566 	}
1567 	ipcl_conn_cleanup(connp);
1568 	connp->conn_flags = IPCL_TCPCONN;
1569 
1570 	/*
1571 	 * Now it is safe to decrement the reference counts.
1572 	 * This might be the last reference on the netstack
1573 	 * in which case it will cause the freeing of the IP Instance.
1574 	 */
1575 	connp->conn_netstack = NULL;
1576 	connp->conn_ixa->ixa_ipst = NULL;
1577 	netstack_rele(ns);
1578 	ASSERT(tcps != NULL);
1579 	tcp->tcp_tcps = NULL;
1580 
1581 	bzero(tcp, sizeof (tcp_t));
1582 
1583 	/* restore the state */
1584 	tcp->tcp_timercache = mp;
1585 
1586 	tcp->tcp_sack_info = tcp_sack_info;
1587 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1588 
1589 	tcp->tcp_connp = connp;
1590 
1591 	ASSERT(connp->conn_tcp == tcp);
1592 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1593 	connp->conn_state_flags = CONN_INCIPIENT;
1594 	ASSERT(connp->conn_proto == IPPROTO_TCP);
1595 	ASSERT(connp->conn_ref == 1);
1596 }
1597 
1598 /*
1599  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1600  * is done forwards from the head.
1601  * This walks all stack instances since
1602  * tcp_time_wait remains global across all stacks.
1603  */
1604 /* ARGSUSED */
1605 void
1606 tcp_time_wait_collector(void *arg)
1607 {
1608 	tcp_t *tcp;
1609 	clock_t now;
1610 	mblk_t *mp;
1611 	conn_t *connp;
1612 	kmutex_t *lock;
1613 	boolean_t removed;
1614 
1615 	squeue_t *sqp = (squeue_t *)arg;
1616 	tcp_squeue_priv_t *tcp_time_wait =
1617 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1618 
1619 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1620 	tcp_time_wait->tcp_time_wait_tid = 0;
1621 
1622 	if (tcp_time_wait->tcp_free_list != NULL &&
1623 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1624 		TCP_G_STAT(tcp_freelist_cleanup);
1625 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1626 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1627 			tcp->tcp_time_wait_next = NULL;
1628 			tcp_time_wait->tcp_free_list_cnt--;
1629 			ASSERT(tcp->tcp_tcps == NULL);
1630 			CONN_DEC_REF(tcp->tcp_connp);
1631 		}
1632 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1633 	}
1634 
1635 	/*
1636 	 * In order to reap time waits reliably, we should use a
1637 	 * source of time that is not adjustable by the user -- hence
1638 	 * the call to ddi_get_lbolt().
1639 	 */
1640 	now = ddi_get_lbolt();
1641 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1642 		/*
1643 		 * Compare times using modular arithmetic, since
1644 		 * lbolt can wrapover.
1645 		 */
1646 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1647 			break;
1648 		}
1649 
1650 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1651 		ASSERT(removed);
1652 
1653 		connp = tcp->tcp_connp;
1654 		ASSERT(connp->conn_fanout != NULL);
1655 		lock = &connp->conn_fanout->connf_lock;
1656 		/*
1657 		 * This is essentially a TW reclaim fast path optimization for
1658 		 * performance where the timewait collector checks under the
1659 		 * fanout lock (so that no one else can get access to the
1660 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1661 		 * the classifier hash list. If ref count is indeed 2, we can
1662 		 * just remove the conn under the fanout lock and avoid
1663 		 * cleaning up the conn under the squeue, provided that
1664 		 * clustering callbacks are not enabled. If clustering is
1665 		 * enabled, we need to make the clustering callback before
1666 		 * setting the CONDEMNED flag and after dropping all locks and
1667 		 * so we forego this optimization and fall back to the slow
1668 		 * path. Also please see the comments in tcp_closei_local
1669 		 * regarding the refcnt logic.
1670 		 *
1671 		 * Since we are holding the tcp_time_wait_lock, its better
1672 		 * not to block on the fanout_lock because other connections
1673 		 * can't add themselves to time_wait list. So we do a
1674 		 * tryenter instead of mutex_enter.
1675 		 */
1676 		if (mutex_tryenter(lock)) {
1677 			mutex_enter(&connp->conn_lock);
1678 			if ((connp->conn_ref == 2) &&
1679 			    (cl_inet_disconnect == NULL)) {
1680 				ipcl_hash_remove_locked(connp,
1681 				    connp->conn_fanout);
1682 				/*
1683 				 * Set the CONDEMNED flag now itself so that
1684 				 * the refcnt cannot increase due to any
1685 				 * walker.
1686 				 */
1687 				connp->conn_state_flags |= CONN_CONDEMNED;
1688 				mutex_exit(lock);
1689 				mutex_exit(&connp->conn_lock);
1690 				if (tcp_time_wait->tcp_free_list_cnt <
1691 				    tcp_free_list_max_cnt) {
1692 					/* Add to head of tcp_free_list */
1693 					mutex_exit(
1694 					    &tcp_time_wait->tcp_time_wait_lock);
1695 					tcp_cleanup(tcp);
1696 					ASSERT(connp->conn_latch == NULL);
1697 					ASSERT(connp->conn_policy == NULL);
1698 					ASSERT(tcp->tcp_tcps == NULL);
1699 					ASSERT(connp->conn_netstack == NULL);
1700 
1701 					mutex_enter(
1702 					    &tcp_time_wait->tcp_time_wait_lock);
1703 					tcp->tcp_time_wait_next =
1704 					    tcp_time_wait->tcp_free_list;
1705 					tcp_time_wait->tcp_free_list = tcp;
1706 					tcp_time_wait->tcp_free_list_cnt++;
1707 					continue;
1708 				} else {
1709 					/* Do not add to tcp_free_list */
1710 					mutex_exit(
1711 					    &tcp_time_wait->tcp_time_wait_lock);
1712 					tcp_bind_hash_remove(tcp);
1713 					ixa_cleanup(tcp->tcp_connp->conn_ixa);
1714 					tcp_ipsec_cleanup(tcp);
1715 					CONN_DEC_REF(tcp->tcp_connp);
1716 				}
1717 			} else {
1718 				CONN_INC_REF_LOCKED(connp);
1719 				mutex_exit(lock);
1720 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1721 				mutex_exit(&connp->conn_lock);
1722 				/*
1723 				 * We can reuse the closemp here since conn has
1724 				 * detached (otherwise we wouldn't even be in
1725 				 * time_wait list). tcp_closemp_used can safely
1726 				 * be changed without taking a lock as no other
1727 				 * thread can concurrently access it at this
1728 				 * point in the connection lifecycle.
1729 				 */
1730 
1731 				if (tcp->tcp_closemp.b_prev == NULL)
1732 					tcp->tcp_closemp_used = B_TRUE;
1733 				else
1734 					cmn_err(CE_PANIC,
1735 					    "tcp_timewait_collector: "
1736 					    "concurrent use of tcp_closemp: "
1737 					    "connp %p tcp %p\n", (void *)connp,
1738 					    (void *)tcp);
1739 
1740 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1741 				mp = &tcp->tcp_closemp;
1742 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1743 				    tcp_timewait_output, connp, NULL,
1744 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1745 			}
1746 		} else {
1747 			mutex_enter(&connp->conn_lock);
1748 			CONN_INC_REF_LOCKED(connp);
1749 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1750 			mutex_exit(&connp->conn_lock);
1751 			/*
1752 			 * We can reuse the closemp here since conn has
1753 			 * detached (otherwise we wouldn't even be in
1754 			 * time_wait list). tcp_closemp_used can safely
1755 			 * be changed without taking a lock as no other
1756 			 * thread can concurrently access it at this
1757 			 * point in the connection lifecycle.
1758 			 */
1759 
1760 			if (tcp->tcp_closemp.b_prev == NULL)
1761 				tcp->tcp_closemp_used = B_TRUE;
1762 			else
1763 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1764 				    "concurrent use of tcp_closemp: "
1765 				    "connp %p tcp %p\n", (void *)connp,
1766 				    (void *)tcp);
1767 
1768 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1769 			mp = &tcp->tcp_closemp;
1770 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1771 			    tcp_timewait_output, connp, NULL,
1772 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1773 		}
1774 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1775 	}
1776 
1777 	if (tcp_time_wait->tcp_free_list != NULL)
1778 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1779 
1780 	tcp_time_wait->tcp_time_wait_tid =
1781 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1782 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1783 	    CALLOUT_FLAG_ROUNDUP);
1784 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1785 }
1786 
1787 /*
1788  * Reply to a clients T_CONN_RES TPI message. This function
1789  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1790  * on the acceptor STREAM and processed in tcp_accept_common().
1791  * Read the block comment on top of tcp_input_listener().
1792  */
1793 static void
1794 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1795 {
1796 	tcp_t		*acceptor;
1797 	tcp_t		*eager;
1798 	tcp_t   	*tcp;
1799 	struct T_conn_res	*tcr;
1800 	t_uscalar_t	acceptor_id;
1801 	t_scalar_t	seqnum;
1802 	mblk_t		*discon_mp = NULL;
1803 	mblk_t		*ok_mp;
1804 	mblk_t		*mp1;
1805 	tcp_stack_t	*tcps = listener->tcp_tcps;
1806 	conn_t		*econnp;
1807 
1808 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1809 		tcp_err_ack(listener, mp, TPROTO, 0);
1810 		return;
1811 	}
1812 	tcr = (struct T_conn_res *)mp->b_rptr;
1813 
1814 	/*
1815 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1816 	 * read side queue of the streams device underneath us i.e. the
1817 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1818 	 * look it up in the queue_hash.  Under LP64 it sends down the
1819 	 * minor_t of the accepting endpoint.
1820 	 *
1821 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1822 	 * fanout hash lock is held.
1823 	 * This prevents any thread from entering the acceptor queue from
1824 	 * below (since it has not been hard bound yet i.e. any inbound
1825 	 * packets will arrive on the listener conn_t and
1826 	 * go through the classifier).
1827 	 * The CONN_INC_REF will prevent the acceptor from closing.
1828 	 *
1829 	 * XXX It is still possible for a tli application to send down data
1830 	 * on the accepting stream while another thread calls t_accept.
1831 	 * This should not be a problem for well-behaved applications since
1832 	 * the T_OK_ACK is sent after the queue swapping is completed.
1833 	 *
1834 	 * If the accepting fd is the same as the listening fd, avoid
1835 	 * queue hash lookup since that will return an eager listener in a
1836 	 * already established state.
1837 	 */
1838 	acceptor_id = tcr->ACCEPTOR_id;
1839 	mutex_enter(&listener->tcp_eager_lock);
1840 	if (listener->tcp_acceptor_id == acceptor_id) {
1841 		eager = listener->tcp_eager_next_q;
1842 		/* only count how many T_CONN_INDs so don't count q0 */
1843 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1844 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1845 			mutex_exit(&listener->tcp_eager_lock);
1846 			tcp_err_ack(listener, mp, TBADF, 0);
1847 			return;
1848 		}
1849 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1850 			/* Throw away all the eagers on q0. */
1851 			tcp_eager_cleanup(listener, 1);
1852 		}
1853 		if (listener->tcp_syn_defense) {
1854 			listener->tcp_syn_defense = B_FALSE;
1855 			if (listener->tcp_ip_addr_cache != NULL) {
1856 				kmem_free(listener->tcp_ip_addr_cache,
1857 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1858 				listener->tcp_ip_addr_cache = NULL;
1859 			}
1860 		}
1861 		/*
1862 		 * Transfer tcp_conn_req_max to the eager so that when
1863 		 * a disconnect occurs we can revert the endpoint to the
1864 		 * listen state.
1865 		 */
1866 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1867 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1868 		/*
1869 		 * Get a reference on the acceptor just like the
1870 		 * tcp_acceptor_hash_lookup below.
1871 		 */
1872 		acceptor = listener;
1873 		CONN_INC_REF(acceptor->tcp_connp);
1874 	} else {
1875 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1876 		if (acceptor == NULL) {
1877 			if (listener->tcp_connp->conn_debug) {
1878 				(void) strlog(TCP_MOD_ID, 0, 1,
1879 				    SL_ERROR|SL_TRACE,
1880 				    "tcp_accept: did not find acceptor 0x%x\n",
1881 				    acceptor_id);
1882 			}
1883 			mutex_exit(&listener->tcp_eager_lock);
1884 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1885 			return;
1886 		}
1887 		/*
1888 		 * Verify acceptor state. The acceptable states for an acceptor
1889 		 * include TCPS_IDLE and TCPS_BOUND.
1890 		 */
1891 		switch (acceptor->tcp_state) {
1892 		case TCPS_IDLE:
1893 			/* FALLTHRU */
1894 		case TCPS_BOUND:
1895 			break;
1896 		default:
1897 			CONN_DEC_REF(acceptor->tcp_connp);
1898 			mutex_exit(&listener->tcp_eager_lock);
1899 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
1900 			return;
1901 		}
1902 	}
1903 
1904 	/* The listener must be in TCPS_LISTEN */
1905 	if (listener->tcp_state != TCPS_LISTEN) {
1906 		CONN_DEC_REF(acceptor->tcp_connp);
1907 		mutex_exit(&listener->tcp_eager_lock);
1908 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
1909 		return;
1910 	}
1911 
1912 	/*
1913 	 * Rendezvous with an eager connection request packet hanging off
1914 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
1915 	 * tcp structure when the connection packet arrived in
1916 	 * tcp_input_listener().
1917 	 */
1918 	seqnum = tcr->SEQ_number;
1919 	eager = listener;
1920 	do {
1921 		eager = eager->tcp_eager_next_q;
1922 		if (eager == NULL) {
1923 			CONN_DEC_REF(acceptor->tcp_connp);
1924 			mutex_exit(&listener->tcp_eager_lock);
1925 			tcp_err_ack(listener, mp, TBADSEQ, 0);
1926 			return;
1927 		}
1928 	} while (eager->tcp_conn_req_seqnum != seqnum);
1929 	mutex_exit(&listener->tcp_eager_lock);
1930 
1931 	/*
1932 	 * At this point, both acceptor and listener have 2 ref
1933 	 * that they begin with. Acceptor has one additional ref
1934 	 * we placed in lookup while listener has 3 additional
1935 	 * ref for being behind the squeue (tcp_accept() is
1936 	 * done on listener's squeue); being in classifier hash;
1937 	 * and eager's ref on listener.
1938 	 */
1939 	ASSERT(listener->tcp_connp->conn_ref >= 5);
1940 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
1941 
1942 	/*
1943 	 * The eager at this point is set in its own squeue and
1944 	 * could easily have been killed (tcp_accept_finish will
1945 	 * deal with that) because of a TH_RST so we can only
1946 	 * ASSERT for a single ref.
1947 	 */
1948 	ASSERT(eager->tcp_connp->conn_ref >= 1);
1949 
1950 	/*
1951 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
1952 	 * use it if something failed.
1953 	 */
1954 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
1955 	    sizeof (struct stroptions)), BPRI_HI);
1956 	if (discon_mp == NULL) {
1957 		CONN_DEC_REF(acceptor->tcp_connp);
1958 		CONN_DEC_REF(eager->tcp_connp);
1959 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
1960 		return;
1961 	}
1962 
1963 	econnp = eager->tcp_connp;
1964 
1965 	/* Hold a copy of mp, in case reallocb fails */
1966 	if ((mp1 = copymsg(mp)) == NULL) {
1967 		CONN_DEC_REF(acceptor->tcp_connp);
1968 		CONN_DEC_REF(eager->tcp_connp);
1969 		freemsg(discon_mp);
1970 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
1971 		return;
1972 	}
1973 
1974 	tcr = (struct T_conn_res *)mp1->b_rptr;
1975 
1976 	/*
1977 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
1978 	 * which allocates a larger mblk and appends the new
1979 	 * local address to the ok_ack.  The address is copied by
1980 	 * soaccept() for getsockname().
1981 	 */
1982 	{
1983 		int extra;
1984 
1985 		extra = (econnp->conn_family == AF_INET) ?
1986 		    sizeof (sin_t) : sizeof (sin6_t);
1987 
1988 		/*
1989 		 * Try to re-use mp, if possible.  Otherwise, allocate
1990 		 * an mblk and return it as ok_mp.  In any case, mp
1991 		 * is no longer usable upon return.
1992 		 */
1993 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
1994 			CONN_DEC_REF(acceptor->tcp_connp);
1995 			CONN_DEC_REF(eager->tcp_connp);
1996 			freemsg(discon_mp);
1997 			/* Original mp has been freed by now, so use mp1 */
1998 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
1999 			return;
2000 		}
2001 
2002 		mp = NULL;	/* We should never use mp after this point */
2003 
2004 		switch (extra) {
2005 		case sizeof (sin_t): {
2006 			sin_t *sin = (sin_t *)ok_mp->b_wptr;
2007 
2008 			ok_mp->b_wptr += extra;
2009 			sin->sin_family = AF_INET;
2010 			sin->sin_port = econnp->conn_lport;
2011 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
2012 			break;
2013 		}
2014 		case sizeof (sin6_t): {
2015 			sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2016 
2017 			ok_mp->b_wptr += extra;
2018 			sin6->sin6_family = AF_INET6;
2019 			sin6->sin6_port = econnp->conn_lport;
2020 			sin6->sin6_addr = econnp->conn_laddr_v6;
2021 			sin6->sin6_flowinfo = econnp->conn_flowinfo;
2022 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
2023 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
2024 				sin6->sin6_scope_id =
2025 				    econnp->conn_ixa->ixa_scopeid;
2026 			} else {
2027 				sin6->sin6_scope_id = 0;
2028 			}
2029 			sin6->__sin6_src_id = 0;
2030 			break;
2031 		}
2032 		default:
2033 			break;
2034 		}
2035 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2036 	}
2037 
2038 	/*
2039 	 * If there are no options we know that the T_CONN_RES will
2040 	 * succeed. However, we can't send the T_OK_ACK upstream until
2041 	 * the tcp_accept_swap is done since it would be dangerous to
2042 	 * let the application start using the new fd prior to the swap.
2043 	 */
2044 	tcp_accept_swap(listener, acceptor, eager);
2045 
2046 	/*
2047 	 * tcp_accept_swap unlinks eager from listener but does not drop
2048 	 * the eager's reference on the listener.
2049 	 */
2050 	ASSERT(eager->tcp_listener == NULL);
2051 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2052 
2053 	/*
2054 	 * The eager is now associated with its own queue. Insert in
2055 	 * the hash so that the connection can be reused for a future
2056 	 * T_CONN_RES.
2057 	 */
2058 	tcp_acceptor_hash_insert(acceptor_id, eager);
2059 
2060 	/*
2061 	 * We now do the processing of options with T_CONN_RES.
2062 	 * We delay till now since we wanted to have queue to pass to
2063 	 * option processing routines that points back to the right
2064 	 * instance structure which does not happen until after
2065 	 * tcp_accept_swap().
2066 	 *
2067 	 * Note:
2068 	 * The sanity of the logic here assumes that whatever options
2069 	 * are appropriate to inherit from listner=>eager are done
2070 	 * before this point, and whatever were to be overridden (or not)
2071 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2072 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2073 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2074 	 * This may not be true at this point in time but can be fixed
2075 	 * independently. This option processing code starts with
2076 	 * the instantiated acceptor instance and the final queue at
2077 	 * this point.
2078 	 */
2079 
2080 	if (tcr->OPT_length != 0) {
2081 		/* Options to process */
2082 		int t_error = 0;
2083 		int sys_error = 0;
2084 		int do_disconnect = 0;
2085 
2086 		if (tcp_conprim_opt_process(eager, mp1,
2087 		    &do_disconnect, &t_error, &sys_error) < 0) {
2088 			eager->tcp_accept_error = 1;
2089 			if (do_disconnect) {
2090 				/*
2091 				 * An option failed which does not allow
2092 				 * connection to be accepted.
2093 				 *
2094 				 * We allow T_CONN_RES to succeed and
2095 				 * put a T_DISCON_IND on the eager queue.
2096 				 */
2097 				ASSERT(t_error == 0 && sys_error == 0);
2098 				eager->tcp_send_discon_ind = 1;
2099 			} else {
2100 				ASSERT(t_error != 0);
2101 				freemsg(ok_mp);
2102 				/*
2103 				 * Original mp was either freed or set
2104 				 * to ok_mp above, so use mp1 instead.
2105 				 */
2106 				tcp_err_ack(listener, mp1, t_error, sys_error);
2107 				goto finish;
2108 			}
2109 		}
2110 		/*
2111 		 * Most likely success in setting options (except if
2112 		 * eager->tcp_send_discon_ind set).
2113 		 * mp1 option buffer represented by OPT_length/offset
2114 		 * potentially modified and contains results of setting
2115 		 * options at this point
2116 		 */
2117 	}
2118 
2119 	/* We no longer need mp1, since all options processing has passed */
2120 	freemsg(mp1);
2121 
2122 	putnext(listener->tcp_connp->conn_rq, ok_mp);
2123 
2124 	mutex_enter(&listener->tcp_eager_lock);
2125 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2126 		tcp_t	*tail;
2127 		mblk_t	*conn_ind;
2128 
2129 		/*
2130 		 * This path should not be executed if listener and
2131 		 * acceptor streams are the same.
2132 		 */
2133 		ASSERT(listener != acceptor);
2134 
2135 		tcp = listener->tcp_eager_prev_q0;
2136 		/*
2137 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2138 		 * deferred T_conn_ind queue. We need to get to the head of
2139 		 * the queue in order to send up T_conn_ind the same order as
2140 		 * how the 3WHS is completed.
2141 		 */
2142 		while (tcp != listener) {
2143 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2144 				break;
2145 			else
2146 				tcp = tcp->tcp_eager_prev_q0;
2147 		}
2148 		ASSERT(tcp != listener);
2149 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2150 		ASSERT(conn_ind != NULL);
2151 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2152 
2153 		/* Move from q0 to q */
2154 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2155 		listener->tcp_conn_req_cnt_q0--;
2156 		listener->tcp_conn_req_cnt_q++;
2157 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2158 		    tcp->tcp_eager_prev_q0;
2159 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2160 		    tcp->tcp_eager_next_q0;
2161 		tcp->tcp_eager_prev_q0 = NULL;
2162 		tcp->tcp_eager_next_q0 = NULL;
2163 		tcp->tcp_conn_def_q0 = B_FALSE;
2164 
2165 		/* Make sure the tcp isn't in the list of droppables */
2166 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2167 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2168 
2169 		/*
2170 		 * Insert at end of the queue because sockfs sends
2171 		 * down T_CONN_RES in chronological order. Leaving
2172 		 * the older conn indications at front of the queue
2173 		 * helps reducing search time.
2174 		 */
2175 		tail = listener->tcp_eager_last_q;
2176 		if (tail != NULL)
2177 			tail->tcp_eager_next_q = tcp;
2178 		else
2179 			listener->tcp_eager_next_q = tcp;
2180 		listener->tcp_eager_last_q = tcp;
2181 		tcp->tcp_eager_next_q = NULL;
2182 		mutex_exit(&listener->tcp_eager_lock);
2183 		putnext(tcp->tcp_connp->conn_rq, conn_ind);
2184 	} else {
2185 		mutex_exit(&listener->tcp_eager_lock);
2186 	}
2187 
2188 	/*
2189 	 * Done with the acceptor - free it
2190 	 *
2191 	 * Note: from this point on, no access to listener should be made
2192 	 * as listener can be equal to acceptor.
2193 	 */
2194 finish:
2195 	ASSERT(acceptor->tcp_detached);
2196 	acceptor->tcp_connp->conn_rq = NULL;
2197 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2198 	acceptor->tcp_connp->conn_wq = NULL;
2199 	(void) tcp_clean_death(acceptor, 0, 2);
2200 	CONN_DEC_REF(acceptor->tcp_connp);
2201 
2202 	/*
2203 	 * We pass discon_mp to tcp_accept_finish to get on the right squeue.
2204 	 *
2205 	 * It will update the setting for sockfs/stream head and also take
2206 	 * care of any data that arrived before accept() wad called.
2207 	 * In case we already received a FIN then tcp_accept_finish will send up
2208 	 * the ordrel. It will also send up a window update if the window
2209 	 * has opened up.
2210 	 */
2211 
2212 	/*
2213 	 * XXX: we currently have a problem if XTI application closes the
2214 	 * acceptor stream in between. This problem exists in on10-gate also
2215 	 * and is well know but nothing can be done short of major rewrite
2216 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2217 	 * eager same squeue as listener (we can distinguish non socket
2218 	 * listeners at the time of handling a SYN in tcp_input_listener)
2219 	 * and do most of the work that tcp_accept_finish does here itself
2220 	 * and then get behind the acceptor squeue to access the acceptor
2221 	 * queue.
2222 	 */
2223 	/*
2224 	 * We already have a ref on tcp so no need to do one before squeue_enter
2225 	 */
2226 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, discon_mp,
2227 	    tcp_accept_finish, eager->tcp_connp, NULL, SQ_FILL,
2228 	    SQTAG_TCP_ACCEPT_FINISH);
2229 }
2230 
2231 /*
2232  * Swap information between the eager and acceptor for a TLI/XTI client.
2233  * The sockfs accept is done on the acceptor stream and control goes
2234  * through tcp_tli_accept() and tcp_accept()/tcp_accept_swap() is not
2235  * called. In either case, both the eager and listener are in their own
2236  * perimeter (squeue) and the code has to deal with potential race.
2237  *
2238  * See the block comment on top of tcp_accept() and tcp_tli_accept().
2239  */
2240 static void
2241 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2242 {
2243 	conn_t	*econnp, *aconnp;
2244 
2245 	ASSERT(eager->tcp_connp->conn_rq == listener->tcp_connp->conn_rq);
2246 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2247 	ASSERT(!TCP_IS_SOCKET(acceptor));
2248 	ASSERT(!TCP_IS_SOCKET(eager));
2249 	ASSERT(!TCP_IS_SOCKET(listener));
2250 
2251 	/*
2252 	 * Trusted Extensions may need to use a security label that is
2253 	 * different from the acceptor's label on MLP and MAC-Exempt
2254 	 * sockets. If this is the case, the required security label
2255 	 * already exists in econnp->conn_ixa->ixa_tsl. Since we make the
2256 	 * acceptor stream refer to econnp we atomatically get that label.
2257 	 */
2258 
2259 	acceptor->tcp_detached = B_TRUE;
2260 	/*
2261 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2262 	 * the acceptor id.
2263 	 */
2264 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2265 
2266 	/* remove eager from listen list... */
2267 	mutex_enter(&listener->tcp_eager_lock);
2268 	tcp_eager_unlink(eager);
2269 	ASSERT(eager->tcp_eager_next_q == NULL &&
2270 	    eager->tcp_eager_last_q == NULL);
2271 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2272 	    eager->tcp_eager_prev_q0 == NULL);
2273 	mutex_exit(&listener->tcp_eager_lock);
2274 
2275 	econnp = eager->tcp_connp;
2276 	aconnp = acceptor->tcp_connp;
2277 	econnp->conn_rq = aconnp->conn_rq;
2278 	econnp->conn_wq = aconnp->conn_wq;
2279 	econnp->conn_rq->q_ptr = econnp;
2280 	econnp->conn_wq->q_ptr = econnp;
2281 
2282 	/*
2283 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2284 	 * which might be a different squeue from our peer TCP instance.
2285 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2286 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2287 	 * membar_producer() to ensure that the assignments of conn_rq/conn_wq
2288 	 * above reach global visibility prior to the clearing of tcp_detached.
2289 	 */
2290 	membar_producer();
2291 	eager->tcp_detached = B_FALSE;
2292 
2293 	ASSERT(eager->tcp_ack_tid == 0);
2294 
2295 	econnp->conn_dev = aconnp->conn_dev;
2296 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2297 
2298 	ASSERT(econnp->conn_minor_arena != NULL);
2299 	if (econnp->conn_cred != NULL)
2300 		crfree(econnp->conn_cred);
2301 	econnp->conn_cred = aconnp->conn_cred;
2302 	aconnp->conn_cred = NULL;
2303 	econnp->conn_cpid = aconnp->conn_cpid;
2304 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2305 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2306 
2307 	econnp->conn_zoneid = aconnp->conn_zoneid;
2308 	econnp->conn_allzones = aconnp->conn_allzones;
2309 	econnp->conn_ixa->ixa_zoneid = aconnp->conn_ixa->ixa_zoneid;
2310 
2311 	econnp->conn_mac_mode = aconnp->conn_mac_mode;
2312 	econnp->conn_zone_is_global = aconnp->conn_zone_is_global;
2313 	aconnp->conn_mac_mode = CONN_MAC_DEFAULT;
2314 
2315 	/* Do the IPC initialization */
2316 	CONN_INC_REF(econnp);
2317 
2318 	/* Done with old IPC. Drop its ref on its connp */
2319 	CONN_DEC_REF(aconnp);
2320 }
2321 
2322 
2323 /*
2324  * Adapt to the information, such as rtt and rtt_sd, provided from the
2325  * DCE and IRE maintained by IP.
2326  *
2327  * Checks for multicast and broadcast destination address.
2328  * Returns zero if ok; an errno on failure.
2329  *
2330  * Note that the MSS calculation here is based on the info given in
2331  * the DCE and IRE.  We do not do any calculation based on TCP options.  They
2332  * will be handled in tcp_input_data() when TCP knows which options to use.
2333  *
2334  * Note on how TCP gets its parameters for a connection.
2335  *
2336  * When a tcp_t structure is allocated, it gets all the default parameters.
2337  * In tcp_set_destination(), it gets those metric parameters, like rtt, rtt_sd,
2338  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2339  * default.
2340  *
2341  * An incoming SYN with a multicast or broadcast destination address is dropped
2342  * in ip_fanout_v4/v6.
2343  *
2344  * An incoming SYN with a multicast or broadcast source address is always
2345  * dropped in tcp_set_destination, since IPDF_ALLOW_MCBC is not set in
2346  * conn_connect.
2347  * The same logic in tcp_set_destination also serves to
2348  * reject an attempt to connect to a broadcast or multicast (destination)
2349  * address.
2350  */
2351 static int
2352 tcp_set_destination(tcp_t *tcp)
2353 {
2354 	uint32_t	mss_max;
2355 	uint32_t	mss;
2356 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2357 	conn_t		*connp = tcp->tcp_connp;
2358 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2359 	iulp_t		uinfo;
2360 	int		error;
2361 	uint32_t	flags;
2362 
2363 	flags = IPDF_LSO | IPDF_ZCOPY;
2364 	/*
2365 	 * Make sure we have a dce for the destination to avoid dce_ident
2366 	 * contention for connected sockets.
2367 	 */
2368 	flags |= IPDF_UNIQUE_DCE;
2369 
2370 	if (!tcps->tcps_ignore_path_mtu)
2371 		connp->conn_ixa->ixa_flags |= IXAF_PMTU_DISCOVERY;
2372 
2373 	/* Use conn_lock to satify ASSERT; tcp is already serialized */
2374 	mutex_enter(&connp->conn_lock);
2375 	error = conn_connect(connp, &uinfo, flags);
2376 	mutex_exit(&connp->conn_lock);
2377 	if (error != 0)
2378 		return (error);
2379 
2380 	error = tcp_build_hdrs(tcp);
2381 	if (error != 0)
2382 		return (error);
2383 
2384 	tcp->tcp_localnet = uinfo.iulp_localnet;
2385 
2386 	if (uinfo.iulp_rtt != 0) {
2387 		clock_t	rto;
2388 
2389 		tcp->tcp_rtt_sa = uinfo.iulp_rtt;
2390 		tcp->tcp_rtt_sd = uinfo.iulp_rtt_sd;
2391 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2392 		    tcps->tcps_rexmit_interval_extra +
2393 		    (tcp->tcp_rtt_sa >> 5);
2394 
2395 		if (rto > tcps->tcps_rexmit_interval_max) {
2396 			tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2397 		} else if (rto < tcps->tcps_rexmit_interval_min) {
2398 			tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2399 		} else {
2400 			tcp->tcp_rto = rto;
2401 		}
2402 	}
2403 	if (uinfo.iulp_ssthresh != 0)
2404 		tcp->tcp_cwnd_ssthresh = uinfo.iulp_ssthresh;
2405 	else
2406 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2407 	if (uinfo.iulp_spipe > 0) {
2408 		connp->conn_sndbuf = MIN(uinfo.iulp_spipe,
2409 		    tcps->tcps_max_buf);
2410 		if (tcps->tcps_snd_lowat_fraction != 0) {
2411 			connp->conn_sndlowat = connp->conn_sndbuf /
2412 			    tcps->tcps_snd_lowat_fraction;
2413 		}
2414 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2415 	}
2416 	/*
2417 	 * Note that up till now, acceptor always inherits receive
2418 	 * window from the listener.  But if there is a metrics
2419 	 * associated with a host, we should use that instead of
2420 	 * inheriting it from listener. Thus we need to pass this
2421 	 * info back to the caller.
2422 	 */
2423 	if (uinfo.iulp_rpipe > 0) {
2424 		tcp->tcp_rwnd = MIN(uinfo.iulp_rpipe,
2425 		    tcps->tcps_max_buf);
2426 	}
2427 
2428 	if (uinfo.iulp_rtomax > 0) {
2429 		tcp->tcp_second_timer_threshold =
2430 		    uinfo.iulp_rtomax;
2431 	}
2432 
2433 	/*
2434 	 * Use the metric option settings, iulp_tstamp_ok and
2435 	 * iulp_wscale_ok, only for active open. What this means
2436 	 * is that if the other side uses timestamp or window
2437 	 * scale option, TCP will also use those options. That
2438 	 * is for passive open.  If the application sets a
2439 	 * large window, window scale is enabled regardless of
2440 	 * the value in iulp_wscale_ok.  This is the behavior
2441 	 * since 2.6.  So we keep it.
2442 	 * The only case left in passive open processing is the
2443 	 * check for SACK.
2444 	 * For ECN, it should probably be like SACK.  But the
2445 	 * current value is binary, so we treat it like the other
2446 	 * cases.  The metric only controls active open.For passive
2447 	 * open, the ndd param, tcp_ecn_permitted, controls the
2448 	 * behavior.
2449 	 */
2450 	if (!tcp_detached) {
2451 		/*
2452 		 * The if check means that the following can only
2453 		 * be turned on by the metrics only IRE, but not off.
2454 		 */
2455 		if (uinfo.iulp_tstamp_ok)
2456 			tcp->tcp_snd_ts_ok = B_TRUE;
2457 		if (uinfo.iulp_wscale_ok)
2458 			tcp->tcp_snd_ws_ok = B_TRUE;
2459 		if (uinfo.iulp_sack == 2)
2460 			tcp->tcp_snd_sack_ok = B_TRUE;
2461 		if (uinfo.iulp_ecn_ok)
2462 			tcp->tcp_ecn_ok = B_TRUE;
2463 	} else {
2464 		/*
2465 		 * Passive open.
2466 		 *
2467 		 * As above, the if check means that SACK can only be
2468 		 * turned on by the metric only IRE.
2469 		 */
2470 		if (uinfo.iulp_sack > 0) {
2471 			tcp->tcp_snd_sack_ok = B_TRUE;
2472 		}
2473 	}
2474 
2475 	/*
2476 	 * XXX Note that currently, iulp_mtu can be as small as 68
2477 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2478 	 * length of all those options exceeds 28 bytes.  But because
2479 	 * of the tcp_mss_min check below, we may not have a problem if
2480 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2481 	 * the negative problem still exists.  And the check defeats PMTUd.
2482 	 * In fact, if PMTUd finds that the MSS should be smaller than
2483 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2484 	 * value.
2485 	 *
2486 	 * We do not deal with that now.  All those problems related to
2487 	 * PMTUd will be fixed later.
2488 	 */
2489 	ASSERT(uinfo.iulp_mtu != 0);
2490 	mss = tcp->tcp_initial_pmtu = uinfo.iulp_mtu;
2491 
2492 	/* Sanity check for MSS value. */
2493 	if (connp->conn_ipversion == IPV4_VERSION)
2494 		mss_max = tcps->tcps_mss_max_ipv4;
2495 	else
2496 		mss_max = tcps->tcps_mss_max_ipv6;
2497 
2498 	if (tcp->tcp_ipsec_overhead == 0)
2499 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2500 
2501 	mss -= tcp->tcp_ipsec_overhead;
2502 
2503 	if (mss < tcps->tcps_mss_min)
2504 		mss = tcps->tcps_mss_min;
2505 	if (mss > mss_max)
2506 		mss = mss_max;
2507 
2508 	/* Note that this is the maximum MSS, excluding all options. */
2509 	tcp->tcp_mss = mss;
2510 
2511 	/*
2512 	 * Update the tcp connection with LSO capability.
2513 	 */
2514 	tcp_update_lso(tcp, connp->conn_ixa);
2515 
2516 	/*
2517 	 * Initialize the ISS here now that we have the full connection ID.
2518 	 * The RFC 1948 method of initial sequence number generation requires
2519 	 * knowledge of the full connection ID before setting the ISS.
2520 	 */
2521 	tcp_iss_init(tcp);
2522 
2523 	tcp->tcp_loopback = (uinfo.iulp_loopback | uinfo.iulp_local);
2524 
2525 	/*
2526 	 * Make sure that conn is not marked incipient
2527 	 * for incoming connections. A blind
2528 	 * removal of incipient flag is cheaper than
2529 	 * check and removal.
2530 	 */
2531 	mutex_enter(&connp->conn_lock);
2532 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2533 	mutex_exit(&connp->conn_lock);
2534 	return (0);
2535 }
2536 
2537 static void
2538 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2539 {
2540 	int	error;
2541 	conn_t	*connp = tcp->tcp_connp;
2542 	struct sockaddr	*sa;
2543 	mblk_t  *mp1;
2544 	struct T_bind_req *tbr;
2545 	int	backlog;
2546 	socklen_t	len;
2547 	sin_t	*sin;
2548 	sin6_t	*sin6;
2549 	cred_t		*cr;
2550 
2551 	/*
2552 	 * All Solaris components should pass a db_credp
2553 	 * for this TPI message, hence we ASSERT.
2554 	 * But in case there is some other M_PROTO that looks
2555 	 * like a TPI message sent by some other kernel
2556 	 * component, we check and return an error.
2557 	 */
2558 	cr = msg_getcred(mp, NULL);
2559 	ASSERT(cr != NULL);
2560 	if (cr == NULL) {
2561 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2562 		return;
2563 	}
2564 
2565 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2566 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2567 		if (connp->conn_debug) {
2568 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2569 			    "tcp_tpi_bind: bad req, len %u",
2570 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2571 		}
2572 		tcp_err_ack(tcp, mp, TPROTO, 0);
2573 		return;
2574 	}
2575 	/* Make sure the largest address fits */
2576 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t), 1);
2577 	if (mp1 == NULL) {
2578 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2579 		return;
2580 	}
2581 	mp = mp1;
2582 	tbr = (struct T_bind_req *)mp->b_rptr;
2583 
2584 	backlog = tbr->CONIND_number;
2585 	len = tbr->ADDR_length;
2586 
2587 	switch (len) {
2588 	case 0:		/* request for a generic port */
2589 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2590 		if (connp->conn_family == AF_INET) {
2591 			tbr->ADDR_length = sizeof (sin_t);
2592 			sin = (sin_t *)&tbr[1];
2593 			*sin = sin_null;
2594 			sin->sin_family = AF_INET;
2595 			sa = (struct sockaddr *)sin;
2596 			len = sizeof (sin_t);
2597 			mp->b_wptr = (uchar_t *)&sin[1];
2598 		} else {
2599 			ASSERT(connp->conn_family == AF_INET6);
2600 			tbr->ADDR_length = sizeof (sin6_t);
2601 			sin6 = (sin6_t *)&tbr[1];
2602 			*sin6 = sin6_null;
2603 			sin6->sin6_family = AF_INET6;
2604 			sa = (struct sockaddr *)sin6;
2605 			len = sizeof (sin6_t);
2606 			mp->b_wptr = (uchar_t *)&sin6[1];
2607 		}
2608 		break;
2609 
2610 	case sizeof (sin_t):    /* Complete IPv4 address */
2611 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
2612 		    sizeof (sin_t));
2613 		break;
2614 
2615 	case sizeof (sin6_t): /* Complete IPv6 address */
2616 		sa = (struct sockaddr *)mi_offset_param(mp,
2617 		    tbr->ADDR_offset, sizeof (sin6_t));
2618 		break;
2619 
2620 	default:
2621 		if (connp->conn_debug) {
2622 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2623 			    "tcp_tpi_bind: bad address length, %d",
2624 			    tbr->ADDR_length);
2625 		}
2626 		tcp_err_ack(tcp, mp, TBADADDR, 0);
2627 		return;
2628 	}
2629 
2630 	if (backlog > 0) {
2631 		error = tcp_do_listen(connp, sa, len, backlog, DB_CRED(mp),
2632 		    tbr->PRIM_type != O_T_BIND_REQ);
2633 	} else {
2634 		error = tcp_do_bind(connp, sa, len, DB_CRED(mp),
2635 		    tbr->PRIM_type != O_T_BIND_REQ);
2636 	}
2637 done:
2638 	if (error > 0) {
2639 		tcp_err_ack(tcp, mp, TSYSERR, error);
2640 	} else if (error < 0) {
2641 		tcp_err_ack(tcp, mp, -error, 0);
2642 	} else {
2643 		/*
2644 		 * Update port information as sockfs/tpi needs it for checking
2645 		 */
2646 		if (connp->conn_family == AF_INET) {
2647 			sin = (sin_t *)sa;
2648 			sin->sin_port = connp->conn_lport;
2649 		} else {
2650 			sin6 = (sin6_t *)sa;
2651 			sin6->sin6_port = connp->conn_lport;
2652 		}
2653 		mp->b_datap->db_type = M_PCPROTO;
2654 		tbr->PRIM_type = T_BIND_ACK;
2655 		putnext(connp->conn_rq, mp);
2656 	}
2657 }
2658 
2659 /*
2660  * If the "bind_to_req_port_only" parameter is set, if the requested port
2661  * number is available, return it, If not return 0
2662  *
2663  * If "bind_to_req_port_only" parameter is not set and
2664  * If the requested port number is available, return it.  If not, return
2665  * the first anonymous port we happen across.  If no anonymous ports are
2666  * available, return 0. addr is the requested local address, if any.
2667  *
2668  * In either case, when succeeding update the tcp_t to record the port number
2669  * and insert it in the bind hash table.
2670  *
2671  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
2672  * without setting SO_REUSEADDR. This is needed so that they
2673  * can be viewed as two independent transport protocols.
2674  */
2675 static in_port_t
2676 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
2677     int reuseaddr, boolean_t quick_connect,
2678     boolean_t bind_to_req_port_only, boolean_t user_specified)
2679 {
2680 	/* number of times we have run around the loop */
2681 	int count = 0;
2682 	/* maximum number of times to run around the loop */
2683 	int loopmax;
2684 	conn_t *connp = tcp->tcp_connp;
2685 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2686 
2687 	/*
2688 	 * Lookup for free addresses is done in a loop and "loopmax"
2689 	 * influences how long we spin in the loop
2690 	 */
2691 	if (bind_to_req_port_only) {
2692 		/*
2693 		 * If the requested port is busy, don't bother to look
2694 		 * for a new one. Setting loop maximum count to 1 has
2695 		 * that effect.
2696 		 */
2697 		loopmax = 1;
2698 	} else {
2699 		/*
2700 		 * If the requested port is busy, look for a free one
2701 		 * in the anonymous port range.
2702 		 * Set loopmax appropriately so that one does not look
2703 		 * forever in the case all of the anonymous ports are in use.
2704 		 */
2705 		if (connp->conn_anon_priv_bind) {
2706 			/*
2707 			 * loopmax =
2708 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
2709 			 */
2710 			loopmax = IPPORT_RESERVED -
2711 			    tcps->tcps_min_anonpriv_port;
2712 		} else {
2713 			loopmax = (tcps->tcps_largest_anon_port -
2714 			    tcps->tcps_smallest_anon_port + 1);
2715 		}
2716 	}
2717 	do {
2718 		uint16_t	lport;
2719 		tf_t		*tbf;
2720 		tcp_t		*ltcp;
2721 		conn_t		*lconnp;
2722 
2723 		lport = htons(port);
2724 
2725 		/*
2726 		 * Ensure that the tcp_t is not currently in the bind hash.
2727 		 * Hold the lock on the hash bucket to ensure that
2728 		 * the duplicate check plus the insertion is an atomic
2729 		 * operation.
2730 		 *
2731 		 * This function does an inline lookup on the bind hash list
2732 		 * Make sure that we access only members of tcp_t
2733 		 * and that we don't look at tcp_tcp, since we are not
2734 		 * doing a CONN_INC_REF.
2735 		 */
2736 		tcp_bind_hash_remove(tcp);
2737 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
2738 		mutex_enter(&tbf->tf_lock);
2739 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
2740 		    ltcp = ltcp->tcp_bind_hash) {
2741 			if (lport == ltcp->tcp_connp->conn_lport)
2742 				break;
2743 		}
2744 
2745 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
2746 			boolean_t not_socket;
2747 			boolean_t exclbind;
2748 
2749 			lconnp = ltcp->tcp_connp;
2750 
2751 			/*
2752 			 * On a labeled system, we must treat bindings to ports
2753 			 * on shared IP addresses by sockets with MAC exemption
2754 			 * privilege as being in all zones, as there's
2755 			 * otherwise no way to identify the right receiver.
2756 			 */
2757 			if (!IPCL_BIND_ZONE_MATCH(lconnp, connp))
2758 				continue;
2759 
2760 			/*
2761 			 * If TCP_EXCLBIND is set for either the bound or
2762 			 * binding endpoint, the semantics of bind
2763 			 * is changed according to the following.
2764 			 *
2765 			 * spec = specified address (v4 or v6)
2766 			 * unspec = unspecified address (v4 or v6)
2767 			 * A = specified addresses are different for endpoints
2768 			 *
2769 			 * bound	bind to		allowed
2770 			 * -------------------------------------
2771 			 * unspec	unspec		no
2772 			 * unspec	spec		no
2773 			 * spec		unspec		no
2774 			 * spec		spec		yes if A
2775 			 *
2776 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
2777 			 * as TCP_EXCLBIND, except that zoneid is ignored.
2778 			 *
2779 			 * Note:
2780 			 *
2781 			 * 1. Because of TLI semantics, an endpoint can go
2782 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
2783 			 * TCPS_BOUND, depending on whether it is originally
2784 			 * a listener or not.  That is why we need to check
2785 			 * for states greater than or equal to TCPS_BOUND
2786 			 * here.
2787 			 *
2788 			 * 2. Ideally, we should only check for state equals
2789 			 * to TCPS_LISTEN. And the following check should be
2790 			 * added.
2791 			 *
2792 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
2793 			 *	!reuseaddr || !lconnp->conn_reuseaddr) {
2794 			 *		...
2795 			 * }
2796 			 *
2797 			 * The semantics will be changed to this.  If the
2798 			 * endpoint on the list is in state not equal to
2799 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
2800 			 * set, let the bind succeed.
2801 			 *
2802 			 * Because of (1), we cannot do that for TLI
2803 			 * endpoints.  But we can do that for socket endpoints.
2804 			 * If in future, we can change this going back
2805 			 * semantics, we can use the above check for TLI also.
2806 			 */
2807 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
2808 			    TCP_IS_SOCKET(tcp));
2809 			exclbind = lconnp->conn_exclbind ||
2810 			    connp->conn_exclbind;
2811 
2812 			if ((lconnp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2813 			    (connp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2814 			    (exclbind && (not_socket ||
2815 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
2816 				if (V6_OR_V4_INADDR_ANY(
2817 				    lconnp->conn_bound_addr_v6) ||
2818 				    V6_OR_V4_INADDR_ANY(*laddr) ||
2819 				    IN6_ARE_ADDR_EQUAL(laddr,
2820 				    &lconnp->conn_bound_addr_v6)) {
2821 					break;
2822 				}
2823 				continue;
2824 			}
2825 
2826 			/*
2827 			 * Check ipversion to allow IPv4 and IPv6 sockets to
2828 			 * have disjoint port number spaces, if *_EXCLBIND
2829 			 * is not set and only if the application binds to a
2830 			 * specific port. We use the same autoassigned port
2831 			 * number space for IPv4 and IPv6 sockets.
2832 			 */
2833 			if (connp->conn_ipversion != lconnp->conn_ipversion &&
2834 			    bind_to_req_port_only)
2835 				continue;
2836 
2837 			/*
2838 			 * Ideally, we should make sure that the source
2839 			 * address, remote address, and remote port in the
2840 			 * four tuple for this tcp-connection is unique.
2841 			 * However, trying to find out the local source
2842 			 * address would require too much code duplication
2843 			 * with IP, since IP needs needs to have that code
2844 			 * to support userland TCP implementations.
2845 			 */
2846 			if (quick_connect &&
2847 			    (ltcp->tcp_state > TCPS_LISTEN) &&
2848 			    ((connp->conn_fport != lconnp->conn_fport) ||
2849 			    !IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
2850 			    &lconnp->conn_faddr_v6)))
2851 				continue;
2852 
2853 			if (!reuseaddr) {
2854 				/*
2855 				 * No socket option SO_REUSEADDR.
2856 				 * If existing port is bound to
2857 				 * a non-wildcard IP address
2858 				 * and the requesting stream is
2859 				 * bound to a distinct
2860 				 * different IP addresses
2861 				 * (non-wildcard, also), keep
2862 				 * going.
2863 				 */
2864 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
2865 				    !V6_OR_V4_INADDR_ANY(
2866 				    lconnp->conn_bound_addr_v6) &&
2867 				    !IN6_ARE_ADDR_EQUAL(laddr,
2868 				    &lconnp->conn_bound_addr_v6))
2869 					continue;
2870 				if (ltcp->tcp_state >= TCPS_BOUND) {
2871 					/*
2872 					 * This port is being used and
2873 					 * its state is >= TCPS_BOUND,
2874 					 * so we can't bind to it.
2875 					 */
2876 					break;
2877 				}
2878 			} else {
2879 				/*
2880 				 * socket option SO_REUSEADDR is set on the
2881 				 * binding tcp_t.
2882 				 *
2883 				 * If two streams are bound to
2884 				 * same IP address or both addr
2885 				 * and bound source are wildcards
2886 				 * (INADDR_ANY), we want to stop
2887 				 * searching.
2888 				 * We have found a match of IP source
2889 				 * address and source port, which is
2890 				 * refused regardless of the
2891 				 * SO_REUSEADDR setting, so we break.
2892 				 */
2893 				if (IN6_ARE_ADDR_EQUAL(laddr,
2894 				    &lconnp->conn_bound_addr_v6) &&
2895 				    (ltcp->tcp_state == TCPS_LISTEN ||
2896 				    ltcp->tcp_state == TCPS_BOUND))
2897 					break;
2898 			}
2899 		}
2900 		if (ltcp != NULL) {
2901 			/* The port number is busy */
2902 			mutex_exit(&tbf->tf_lock);
2903 		} else {
2904 			/*
2905 			 * This port is ours. Insert in fanout and mark as
2906 			 * bound to prevent others from getting the port
2907 			 * number.
2908 			 */
2909 			tcp->tcp_state = TCPS_BOUND;
2910 			connp->conn_lport = htons(port);
2911 
2912 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
2913 			    connp->conn_lport)] == tbf);
2914 			tcp_bind_hash_insert(tbf, tcp, 1);
2915 
2916 			mutex_exit(&tbf->tf_lock);
2917 
2918 			/*
2919 			 * We don't want tcp_next_port_to_try to "inherit"
2920 			 * a port number supplied by the user in a bind.
2921 			 */
2922 			if (user_specified)
2923 				return (port);
2924 
2925 			/*
2926 			 * This is the only place where tcp_next_port_to_try
2927 			 * is updated. After the update, it may or may not
2928 			 * be in the valid range.
2929 			 */
2930 			if (!connp->conn_anon_priv_bind)
2931 				tcps->tcps_next_port_to_try = port + 1;
2932 			return (port);
2933 		}
2934 
2935 		if (connp->conn_anon_priv_bind) {
2936 			port = tcp_get_next_priv_port(tcp);
2937 		} else {
2938 			if (count == 0 && user_specified) {
2939 				/*
2940 				 * We may have to return an anonymous port. So
2941 				 * get one to start with.
2942 				 */
2943 				port =
2944 				    tcp_update_next_port(
2945 				    tcps->tcps_next_port_to_try,
2946 				    tcp, B_TRUE);
2947 				user_specified = B_FALSE;
2948 			} else {
2949 				port = tcp_update_next_port(port + 1, tcp,
2950 				    B_FALSE);
2951 			}
2952 		}
2953 		if (port == 0)
2954 			break;
2955 
2956 		/*
2957 		 * Don't let this loop run forever in the case where
2958 		 * all of the anonymous ports are in use.
2959 		 */
2960 	} while (++count < loopmax);
2961 	return (0);
2962 }
2963 
2964 /*
2965  * tcp_clean_death / tcp_close_detached must not be called more than once
2966  * on a tcp. Thus every function that potentially calls tcp_clean_death
2967  * must check for the tcp state before calling tcp_clean_death.
2968  * Eg. tcp_input_data, tcp_eager_kill, tcp_clean_death_wrapper,
2969  * tcp_timer_handler, all check for the tcp state.
2970  */
2971 /* ARGSUSED */
2972 void
2973 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
2974     ip_recv_attr_t *dummy)
2975 {
2976 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
2977 
2978 	freemsg(mp);
2979 	if (tcp->tcp_state > TCPS_BOUND)
2980 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
2981 		    ETIMEDOUT, 5);
2982 }
2983 
2984 /*
2985  * We are dying for some reason.  Try to do it gracefully.  (May be called
2986  * as writer.)
2987  *
2988  * Return -1 if the structure was not cleaned up (if the cleanup had to be
2989  * done by a service procedure).
2990  * TBD - Should the return value distinguish between the tcp_t being
2991  * freed and it being reinitialized?
2992  */
2993 static int
2994 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
2995 {
2996 	mblk_t	*mp;
2997 	queue_t	*q;
2998 	conn_t	*connp = tcp->tcp_connp;
2999 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3000 
3001 	TCP_CLD_STAT(tag);
3002 
3003 #if TCP_TAG_CLEAN_DEATH
3004 	tcp->tcp_cleandeathtag = tag;
3005 #endif
3006 
3007 	if (tcp->tcp_fused)
3008 		tcp_unfuse(tcp);
3009 
3010 	if (tcp->tcp_linger_tid != 0 &&
3011 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3012 		tcp_stop_lingering(tcp);
3013 	}
3014 
3015 	ASSERT(tcp != NULL);
3016 	ASSERT((connp->conn_family == AF_INET &&
3017 	    connp->conn_ipversion == IPV4_VERSION) ||
3018 	    (connp->conn_family == AF_INET6 &&
3019 	    (connp->conn_ipversion == IPV4_VERSION ||
3020 	    connp->conn_ipversion == IPV6_VERSION)));
3021 
3022 	if (TCP_IS_DETACHED(tcp)) {
3023 		if (tcp->tcp_hard_binding) {
3024 			/*
3025 			 * Its an eager that we are dealing with. We close the
3026 			 * eager but in case a conn_ind has already gone to the
3027 			 * listener, let tcp_accept_finish() send a discon_ind
3028 			 * to the listener and drop the last reference. If the
3029 			 * listener doesn't even know about the eager i.e. the
3030 			 * conn_ind hasn't gone up, blow away the eager and drop
3031 			 * the last reference as well. If the conn_ind has gone
3032 			 * up, state should be BOUND. tcp_accept_finish
3033 			 * will figure out that the connection has received a
3034 			 * RST and will send a DISCON_IND to the application.
3035 			 */
3036 			tcp_closei_local(tcp);
3037 			if (!tcp->tcp_tconnind_started) {
3038 				CONN_DEC_REF(connp);
3039 			} else {
3040 				tcp->tcp_state = TCPS_BOUND;
3041 			}
3042 		} else {
3043 			tcp_close_detached(tcp);
3044 		}
3045 		return (0);
3046 	}
3047 
3048 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3049 
3050 	q = connp->conn_rq;
3051 
3052 	/* Trash all inbound data */
3053 	if (!IPCL_IS_NONSTR(connp)) {
3054 		ASSERT(q != NULL);
3055 		flushq(q, FLUSHALL);
3056 	}
3057 
3058 	/*
3059 	 * If we are at least part way open and there is error
3060 	 * (err==0 implies no error)
3061 	 * notify our client by a T_DISCON_IND.
3062 	 */
3063 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3064 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3065 		    !TCP_IS_SOCKET(tcp)) {
3066 			/*
3067 			 * Send M_FLUSH according to TPI. Because sockets will
3068 			 * (and must) ignore FLUSHR we do that only for TPI
3069 			 * endpoints and sockets in STREAMS mode.
3070 			 */
3071 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3072 		}
3073 		if (connp->conn_debug) {
3074 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3075 			    "tcp_clean_death: discon err %d", err);
3076 		}
3077 		if (IPCL_IS_NONSTR(connp)) {
3078 			/* Direct socket, use upcall */
3079 			(*connp->conn_upcalls->su_disconnected)(
3080 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3081 		} else {
3082 			mp = mi_tpi_discon_ind(NULL, err, 0);
3083 			if (mp != NULL) {
3084 				putnext(q, mp);
3085 			} else {
3086 				if (connp->conn_debug) {
3087 					(void) strlog(TCP_MOD_ID, 0, 1,
3088 					    SL_ERROR|SL_TRACE,
3089 					    "tcp_clean_death, sending M_ERROR");
3090 				}
3091 				(void) putnextctl1(q, M_ERROR, EPROTO);
3092 			}
3093 		}
3094 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3095 			/* SYN_SENT or SYN_RCVD */
3096 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3097 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3098 			/* ESTABLISHED or CLOSE_WAIT */
3099 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3100 		}
3101 	}
3102 
3103 	tcp_reinit(tcp);
3104 	if (IPCL_IS_NONSTR(connp))
3105 		(void) tcp_do_unbind(connp);
3106 
3107 	return (-1);
3108 }
3109 
3110 /*
3111  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3112  * to expire, stop the wait and finish the close.
3113  */
3114 static void
3115 tcp_stop_lingering(tcp_t *tcp)
3116 {
3117 	clock_t	delta = 0;
3118 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3119 	conn_t		*connp = tcp->tcp_connp;
3120 
3121 	tcp->tcp_linger_tid = 0;
3122 	if (tcp->tcp_state > TCPS_LISTEN) {
3123 		tcp_acceptor_hash_remove(tcp);
3124 		mutex_enter(&tcp->tcp_non_sq_lock);
3125 		if (tcp->tcp_flow_stopped) {
3126 			tcp_clrqfull(tcp);
3127 		}
3128 		mutex_exit(&tcp->tcp_non_sq_lock);
3129 
3130 		if (tcp->tcp_timer_tid != 0) {
3131 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3132 			tcp->tcp_timer_tid = 0;
3133 		}
3134 		/*
3135 		 * Need to cancel those timers which will not be used when
3136 		 * TCP is detached.  This has to be done before the conn_wq
3137 		 * is cleared.
3138 		 */
3139 		tcp_timers_stop(tcp);
3140 
3141 		tcp->tcp_detached = B_TRUE;
3142 		connp->conn_rq = NULL;
3143 		connp->conn_wq = NULL;
3144 
3145 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3146 			tcp_time_wait_append(tcp);
3147 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3148 			goto finish;
3149 		}
3150 
3151 		/*
3152 		 * If delta is zero the timer event wasn't executed and was
3153 		 * successfully canceled. In this case we need to restart it
3154 		 * with the minimal delta possible.
3155 		 */
3156 		if (delta >= 0) {
3157 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3158 			    delta ? delta : 1);
3159 		}
3160 	} else {
3161 		tcp_closei_local(tcp);
3162 		CONN_DEC_REF(connp);
3163 	}
3164 finish:
3165 	/* Signal closing thread that it can complete close */
3166 	mutex_enter(&tcp->tcp_closelock);
3167 	tcp->tcp_detached = B_TRUE;
3168 	connp->conn_rq = NULL;
3169 	connp->conn_wq = NULL;
3170 
3171 	tcp->tcp_closed = 1;
3172 	cv_signal(&tcp->tcp_closecv);
3173 	mutex_exit(&tcp->tcp_closelock);
3174 }
3175 
3176 /*
3177  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3178  * expires.
3179  */
3180 static void
3181 tcp_close_linger_timeout(void *arg)
3182 {
3183 	conn_t	*connp = (conn_t *)arg;
3184 	tcp_t 	*tcp = connp->conn_tcp;
3185 
3186 	tcp->tcp_client_errno = ETIMEDOUT;
3187 	tcp_stop_lingering(tcp);
3188 }
3189 
3190 static void
3191 tcp_close_common(conn_t *connp, int flags)
3192 {
3193 	tcp_t		*tcp = connp->conn_tcp;
3194 	mblk_t 		*mp = &tcp->tcp_closemp;
3195 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3196 	mblk_t		*bp;
3197 
3198 	ASSERT(connp->conn_ref >= 2);
3199 
3200 	/*
3201 	 * Mark the conn as closing. ipsq_pending_mp_add will not
3202 	 * add any mp to the pending mp list, after this conn has
3203 	 * started closing.
3204 	 */
3205 	mutex_enter(&connp->conn_lock);
3206 	connp->conn_state_flags |= CONN_CLOSING;
3207 	if (connp->conn_oper_pending_ill != NULL)
3208 		conn_ioctl_cleanup_reqd = B_TRUE;
3209 	CONN_INC_REF_LOCKED(connp);
3210 	mutex_exit(&connp->conn_lock);
3211 	tcp->tcp_closeflags = (uint8_t)flags;
3212 	ASSERT(connp->conn_ref >= 3);
3213 
3214 	/*
3215 	 * tcp_closemp_used is used below without any protection of a lock
3216 	 * as we don't expect any one else to use it concurrently at this
3217 	 * point otherwise it would be a major defect.
3218 	 */
3219 
3220 	if (mp->b_prev == NULL)
3221 		tcp->tcp_closemp_used = B_TRUE;
3222 	else
3223 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3224 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3225 
3226 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3227 
3228 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3229 	    NULL, tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3230 
3231 	mutex_enter(&tcp->tcp_closelock);
3232 	while (!tcp->tcp_closed) {
3233 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3234 			/*
3235 			 * The cv_wait_sig() was interrupted. We now do the
3236 			 * following:
3237 			 *
3238 			 * 1) If the endpoint was lingering, we allow this
3239 			 * to be interrupted by cancelling the linger timeout
3240 			 * and closing normally.
3241 			 *
3242 			 * 2) Revert to calling cv_wait()
3243 			 *
3244 			 * We revert to using cv_wait() to avoid an
3245 			 * infinite loop which can occur if the calling
3246 			 * thread is higher priority than the squeue worker
3247 			 * thread and is bound to the same cpu.
3248 			 */
3249 			if (connp->conn_linger && connp->conn_lingertime > 0) {
3250 				mutex_exit(&tcp->tcp_closelock);
3251 				/* Entering squeue, bump ref count. */
3252 				CONN_INC_REF(connp);
3253 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3254 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3255 				    tcp_linger_interrupted, connp, NULL,
3256 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3257 				mutex_enter(&tcp->tcp_closelock);
3258 			}
3259 			break;
3260 		}
3261 	}
3262 	while (!tcp->tcp_closed)
3263 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3264 	mutex_exit(&tcp->tcp_closelock);
3265 
3266 	/*
3267 	 * In the case of listener streams that have eagers in the q or q0
3268 	 * we wait for the eagers to drop their reference to us. conn_rq and
3269 	 * conn_wq of the eagers point to our queues. By waiting for the
3270 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3271 	 * up their queue pointers and also dropped their references to us.
3272 	 */
3273 	if (tcp->tcp_wait_for_eagers) {
3274 		mutex_enter(&connp->conn_lock);
3275 		while (connp->conn_ref != 1) {
3276 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3277 		}
3278 		mutex_exit(&connp->conn_lock);
3279 	}
3280 	/*
3281 	 * ioctl cleanup. The mp is queued in the ipx_pending_mp.
3282 	 */
3283 	if (conn_ioctl_cleanup_reqd)
3284 		conn_ioctl_cleanup(connp);
3285 
3286 	connp->conn_cpid = NOPID;
3287 }
3288 
3289 static int
3290 tcp_tpi_close(queue_t *q, int flags)
3291 {
3292 	conn_t		*connp;
3293 
3294 	ASSERT(WR(q)->q_next == NULL);
3295 
3296 	if (flags & SO_FALLBACK) {
3297 		/*
3298 		 * stream is being closed while in fallback
3299 		 * simply free the resources that were allocated
3300 		 */
3301 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3302 		qprocsoff(q);
3303 		goto done;
3304 	}
3305 
3306 	connp = Q_TO_CONN(q);
3307 	/*
3308 	 * We are being closed as /dev/tcp or /dev/tcp6.
3309 	 */
3310 	tcp_close_common(connp, flags);
3311 
3312 	qprocsoff(q);
3313 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3314 
3315 	/*
3316 	 * Drop IP's reference on the conn. This is the last reference
3317 	 * on the connp if the state was less than established. If the
3318 	 * connection has gone into timewait state, then we will have
3319 	 * one ref for the TCP and one more ref (total of two) for the
3320 	 * classifier connected hash list (a timewait connections stays
3321 	 * in connected hash till closed).
3322 	 *
3323 	 * We can't assert the references because there might be other
3324 	 * transient reference places because of some walkers or queued
3325 	 * packets in squeue for the timewait state.
3326 	 */
3327 	CONN_DEC_REF(connp);
3328 done:
3329 	q->q_ptr = WR(q)->q_ptr = NULL;
3330 	return (0);
3331 }
3332 
3333 static int
3334 tcp_tpi_close_accept(queue_t *q)
3335 {
3336 	vmem_t	*minor_arena;
3337 	dev_t	conn_dev;
3338 
3339 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3340 
3341 	/*
3342 	 * We had opened an acceptor STREAM for sockfs which is
3343 	 * now being closed due to some error.
3344 	 */
3345 	qprocsoff(q);
3346 
3347 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3348 	conn_dev = (dev_t)RD(q)->q_ptr;
3349 	ASSERT(minor_arena != NULL);
3350 	ASSERT(conn_dev != 0);
3351 	inet_minor_free(minor_arena, conn_dev);
3352 	q->q_ptr = WR(q)->q_ptr = NULL;
3353 	return (0);
3354 }
3355 
3356 /*
3357  * Called by tcp_close() routine via squeue when lingering is
3358  * interrupted by a signal.
3359  */
3360 
3361 /* ARGSUSED */
3362 static void
3363 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3364 {
3365 	conn_t	*connp = (conn_t *)arg;
3366 	tcp_t	*tcp = connp->conn_tcp;
3367 
3368 	freeb(mp);
3369 	if (tcp->tcp_linger_tid != 0 &&
3370 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3371 		tcp_stop_lingering(tcp);
3372 		tcp->tcp_client_errno = EINTR;
3373 	}
3374 }
3375 
3376 /*
3377  * Called by streams close routine via squeues when our client blows off her
3378  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3379  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3380  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3381  * acked.
3382  *
3383  * NOTE: tcp_close potentially returns error when lingering.
3384  * However, the stream head currently does not pass these errors
3385  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3386  * errors to the application (from tsleep()) and not errors
3387  * like ECONNRESET caused by receiving a reset packet.
3388  */
3389 
3390 /* ARGSUSED */
3391 static void
3392 tcp_close_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3393 {
3394 	char	*msg;
3395 	conn_t	*connp = (conn_t *)arg;
3396 	tcp_t	*tcp = connp->conn_tcp;
3397 	clock_t	delta = 0;
3398 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3399 
3400 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3401 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3402 
3403 	mutex_enter(&tcp->tcp_eager_lock);
3404 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3405 		/* Cleanup for listener */
3406 		tcp_eager_cleanup(tcp, 0);
3407 		tcp->tcp_wait_for_eagers = 1;
3408 	}
3409 	mutex_exit(&tcp->tcp_eager_lock);
3410 
3411 	tcp->tcp_lso = B_FALSE;
3412 
3413 	msg = NULL;
3414 	switch (tcp->tcp_state) {
3415 	case TCPS_CLOSED:
3416 	case TCPS_IDLE:
3417 	case TCPS_BOUND:
3418 	case TCPS_LISTEN:
3419 		break;
3420 	case TCPS_SYN_SENT:
3421 		msg = "tcp_close, during connect";
3422 		break;
3423 	case TCPS_SYN_RCVD:
3424 		/*
3425 		 * Close during the connect 3-way handshake
3426 		 * but here there may or may not be pending data
3427 		 * already on queue. Process almost same as in
3428 		 * the ESTABLISHED state.
3429 		 */
3430 		/* FALLTHRU */
3431 	default:
3432 		if (tcp->tcp_fused)
3433 			tcp_unfuse(tcp);
3434 
3435 		/*
3436 		 * If SO_LINGER has set a zero linger time, abort the
3437 		 * connection with a reset.
3438 		 */
3439 		if (connp->conn_linger && connp->conn_lingertime == 0) {
3440 			msg = "tcp_close, zero lingertime";
3441 			break;
3442 		}
3443 
3444 		/*
3445 		 * Abort connection if there is unread data queued.
3446 		 */
3447 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3448 			msg = "tcp_close, unread data";
3449 			break;
3450 		}
3451 		/*
3452 		 * We have done a qwait() above which could have possibly
3453 		 * drained more messages in turn causing transition to a
3454 		 * different state. Check whether we have to do the rest
3455 		 * of the processing or not.
3456 		 */
3457 		if (tcp->tcp_state <= TCPS_LISTEN)
3458 			break;
3459 
3460 		/*
3461 		 * Transmit the FIN before detaching the tcp_t.
3462 		 * After tcp_detach returns this queue/perimeter
3463 		 * no longer owns the tcp_t thus others can modify it.
3464 		 */
3465 		(void) tcp_xmit_end(tcp);
3466 
3467 		/*
3468 		 * If lingering on close then wait until the fin is acked,
3469 		 * the SO_LINGER time passes, or a reset is sent/received.
3470 		 */
3471 		if (connp->conn_linger && connp->conn_lingertime > 0 &&
3472 		    !(tcp->tcp_fin_acked) &&
3473 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3474 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3475 				tcp->tcp_client_errno = EWOULDBLOCK;
3476 			} else if (tcp->tcp_client_errno == 0) {
3477 
3478 				ASSERT(tcp->tcp_linger_tid == 0);
3479 
3480 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3481 				    tcp_close_linger_timeout,
3482 				    connp->conn_lingertime * hz);
3483 
3484 				/* tcp_close_linger_timeout will finish close */
3485 				if (tcp->tcp_linger_tid == 0)
3486 					tcp->tcp_client_errno = ENOSR;
3487 				else
3488 					return;
3489 			}
3490 
3491 			/*
3492 			 * Check if we need to detach or just close
3493 			 * the instance.
3494 			 */
3495 			if (tcp->tcp_state <= TCPS_LISTEN)
3496 				break;
3497 		}
3498 
3499 		/*
3500 		 * Make sure that no other thread will access the conn_rq of
3501 		 * this instance (through lookups etc.) as conn_rq will go
3502 		 * away shortly.
3503 		 */
3504 		tcp_acceptor_hash_remove(tcp);
3505 
3506 		mutex_enter(&tcp->tcp_non_sq_lock);
3507 		if (tcp->tcp_flow_stopped) {
3508 			tcp_clrqfull(tcp);
3509 		}
3510 		mutex_exit(&tcp->tcp_non_sq_lock);
3511 
3512 		if (tcp->tcp_timer_tid != 0) {
3513 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3514 			tcp->tcp_timer_tid = 0;
3515 		}
3516 		/*
3517 		 * Need to cancel those timers which will not be used when
3518 		 * TCP is detached.  This has to be done before the conn_wq
3519 		 * is set to NULL.
3520 		 */
3521 		tcp_timers_stop(tcp);
3522 
3523 		tcp->tcp_detached = B_TRUE;
3524 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3525 			tcp_time_wait_append(tcp);
3526 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3527 			ASSERT(connp->conn_ref >= 3);
3528 			goto finish;
3529 		}
3530 
3531 		/*
3532 		 * If delta is zero the timer event wasn't executed and was
3533 		 * successfully canceled. In this case we need to restart it
3534 		 * with the minimal delta possible.
3535 		 */
3536 		if (delta >= 0)
3537 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3538 			    delta ? delta : 1);
3539 
3540 		ASSERT(connp->conn_ref >= 3);
3541 		goto finish;
3542 	}
3543 
3544 	/* Detach did not complete. Still need to remove q from stream. */
3545 	if (msg) {
3546 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3547 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3548 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3549 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3550 		    tcp->tcp_state == TCPS_SYN_RCVD)
3551 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3552 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3553 	}
3554 
3555 	tcp_closei_local(tcp);
3556 	CONN_DEC_REF(connp);
3557 	ASSERT(connp->conn_ref >= 2);
3558 
3559 finish:
3560 	mutex_enter(&tcp->tcp_closelock);
3561 	/*
3562 	 * Don't change the queues in the case of a listener that has
3563 	 * eagers in its q or q0. It could surprise the eagers.
3564 	 * Instead wait for the eagers outside the squeue.
3565 	 */
3566 	if (!tcp->tcp_wait_for_eagers) {
3567 		tcp->tcp_detached = B_TRUE;
3568 		connp->conn_rq = NULL;
3569 		connp->conn_wq = NULL;
3570 	}
3571 
3572 	/* Signal tcp_close() to finish closing. */
3573 	tcp->tcp_closed = 1;
3574 	cv_signal(&tcp->tcp_closecv);
3575 	mutex_exit(&tcp->tcp_closelock);
3576 }
3577 
3578 /*
3579  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
3580  * Some stream heads get upset if they see these later on as anything but NULL.
3581  */
3582 static void
3583 tcp_close_mpp(mblk_t **mpp)
3584 {
3585 	mblk_t	*mp;
3586 
3587 	if ((mp = *mpp) != NULL) {
3588 		do {
3589 			mp->b_next = NULL;
3590 			mp->b_prev = NULL;
3591 		} while ((mp = mp->b_cont) != NULL);
3592 
3593 		mp = *mpp;
3594 		*mpp = NULL;
3595 		freemsg(mp);
3596 	}
3597 }
3598 
3599 /* Do detached close. */
3600 static void
3601 tcp_close_detached(tcp_t *tcp)
3602 {
3603 	if (tcp->tcp_fused)
3604 		tcp_unfuse(tcp);
3605 
3606 	/*
3607 	 * Clustering code serializes TCP disconnect callbacks and
3608 	 * cluster tcp list walks by blocking a TCP disconnect callback
3609 	 * if a cluster tcp list walk is in progress. This ensures
3610 	 * accurate accounting of TCPs in the cluster code even though
3611 	 * the TCP list walk itself is not atomic.
3612 	 */
3613 	tcp_closei_local(tcp);
3614 	CONN_DEC_REF(tcp->tcp_connp);
3615 }
3616 
3617 /*
3618  * Stop all TCP timers, and free the timer mblks if requested.
3619  */
3620 void
3621 tcp_timers_stop(tcp_t *tcp)
3622 {
3623 	if (tcp->tcp_timer_tid != 0) {
3624 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3625 		tcp->tcp_timer_tid = 0;
3626 	}
3627 	if (tcp->tcp_ka_tid != 0) {
3628 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
3629 		tcp->tcp_ka_tid = 0;
3630 	}
3631 	if (tcp->tcp_ack_tid != 0) {
3632 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
3633 		tcp->tcp_ack_tid = 0;
3634 	}
3635 	if (tcp->tcp_push_tid != 0) {
3636 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
3637 		tcp->tcp_push_tid = 0;
3638 	}
3639 }
3640 
3641 /*
3642  * The tcp_t is going away. Remove it from all lists and set it
3643  * to TCPS_CLOSED. The freeing up of memory is deferred until
3644  * tcp_inactive. This is needed since a thread in tcp_rput might have
3645  * done a CONN_INC_REF on this structure before it was removed from the
3646  * hashes.
3647  */
3648 static void
3649 tcp_closei_local(tcp_t *tcp)
3650 {
3651 	conn_t		*connp = tcp->tcp_connp;
3652 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3653 
3654 	if (!TCP_IS_SOCKET(tcp))
3655 		tcp_acceptor_hash_remove(tcp);
3656 
3657 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
3658 	tcp->tcp_ibsegs = 0;
3659 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
3660 	tcp->tcp_obsegs = 0;
3661 
3662 	/*
3663 	 * If we are an eager connection hanging off a listener that
3664 	 * hasn't formally accepted the connection yet, get off his
3665 	 * list and blow off any data that we have accumulated.
3666 	 */
3667 	if (tcp->tcp_listener != NULL) {
3668 		tcp_t	*listener = tcp->tcp_listener;
3669 		mutex_enter(&listener->tcp_eager_lock);
3670 		/*
3671 		 * tcp_tconnind_started == B_TRUE means that the
3672 		 * conn_ind has already gone to listener. At
3673 		 * this point, eager will be closed but we
3674 		 * leave it in listeners eager list so that
3675 		 * if listener decides to close without doing
3676 		 * accept, we can clean this up. In tcp_tli_accept
3677 		 * we take care of the case of accept on closed
3678 		 * eager.
3679 		 */
3680 		if (!tcp->tcp_tconnind_started) {
3681 			tcp_eager_unlink(tcp);
3682 			mutex_exit(&listener->tcp_eager_lock);
3683 			/*
3684 			 * We don't want to have any pointers to the
3685 			 * listener queue, after we have released our
3686 			 * reference on the listener
3687 			 */
3688 			ASSERT(tcp->tcp_detached);
3689 			connp->conn_rq = NULL;
3690 			connp->conn_wq = NULL;
3691 			CONN_DEC_REF(listener->tcp_connp);
3692 		} else {
3693 			mutex_exit(&listener->tcp_eager_lock);
3694 		}
3695 	}
3696 
3697 	/* Stop all the timers */
3698 	tcp_timers_stop(tcp);
3699 
3700 	if (tcp->tcp_state == TCPS_LISTEN) {
3701 		if (tcp->tcp_ip_addr_cache) {
3702 			kmem_free((void *)tcp->tcp_ip_addr_cache,
3703 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
3704 			tcp->tcp_ip_addr_cache = NULL;
3705 		}
3706 	}
3707 	mutex_enter(&tcp->tcp_non_sq_lock);
3708 	if (tcp->tcp_flow_stopped)
3709 		tcp_clrqfull(tcp);
3710 	mutex_exit(&tcp->tcp_non_sq_lock);
3711 
3712 	tcp_bind_hash_remove(tcp);
3713 	/*
3714 	 * If the tcp_time_wait_collector (which runs outside the squeue)
3715 	 * is trying to remove this tcp from the time wait list, we will
3716 	 * block in tcp_time_wait_remove while trying to acquire the
3717 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
3718 	 * requires the ipcl_hash_remove to be ordered after the
3719 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
3720 	 */
3721 	if (tcp->tcp_state == TCPS_TIME_WAIT)
3722 		(void) tcp_time_wait_remove(tcp, NULL);
3723 	CL_INET_DISCONNECT(connp);
3724 	ipcl_hash_remove(connp);
3725 	ixa_cleanup(connp->conn_ixa);
3726 
3727 	/*
3728 	 * Mark the conn as CONDEMNED
3729 	 */
3730 	mutex_enter(&connp->conn_lock);
3731 	connp->conn_state_flags |= CONN_CONDEMNED;
3732 	mutex_exit(&connp->conn_lock);
3733 
3734 	/* Need to cleanup any pending ioctls */
3735 	ASSERT(tcp->tcp_time_wait_next == NULL);
3736 	ASSERT(tcp->tcp_time_wait_prev == NULL);
3737 	ASSERT(tcp->tcp_time_wait_expire == 0);
3738 	tcp->tcp_state = TCPS_CLOSED;
3739 
3740 	/* Release any SSL context */
3741 	if (tcp->tcp_kssl_ent != NULL) {
3742 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
3743 		tcp->tcp_kssl_ent = NULL;
3744 	}
3745 	if (tcp->tcp_kssl_ctx != NULL) {
3746 		kssl_release_ctx(tcp->tcp_kssl_ctx);
3747 		tcp->tcp_kssl_ctx = NULL;
3748 	}
3749 	tcp->tcp_kssl_pending = B_FALSE;
3750 
3751 	tcp_ipsec_cleanup(tcp);
3752 }
3753 
3754 /*
3755  * tcp is dying (called from ipcl_conn_destroy and error cases).
3756  * Free the tcp_t in either case.
3757  */
3758 void
3759 tcp_free(tcp_t *tcp)
3760 {
3761 	mblk_t		*mp;
3762 	conn_t		*connp = tcp->tcp_connp;
3763 
3764 	ASSERT(tcp != NULL);
3765 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
3766 
3767 	connp->conn_rq = NULL;
3768 	connp->conn_wq = NULL;
3769 
3770 	tcp_close_mpp(&tcp->tcp_xmit_head);
3771 	tcp_close_mpp(&tcp->tcp_reass_head);
3772 	if (tcp->tcp_rcv_list != NULL) {
3773 		/* Free b_next chain */
3774 		tcp_close_mpp(&tcp->tcp_rcv_list);
3775 	}
3776 	if ((mp = tcp->tcp_urp_mp) != NULL) {
3777 		freemsg(mp);
3778 	}
3779 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
3780 		freemsg(mp);
3781 	}
3782 
3783 	if (tcp->tcp_fused_sigurg_mp != NULL) {
3784 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3785 		freeb(tcp->tcp_fused_sigurg_mp);
3786 		tcp->tcp_fused_sigurg_mp = NULL;
3787 	}
3788 
3789 	if (tcp->tcp_ordrel_mp != NULL) {
3790 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3791 		freeb(tcp->tcp_ordrel_mp);
3792 		tcp->tcp_ordrel_mp = NULL;
3793 	}
3794 
3795 	if (tcp->tcp_sack_info != NULL) {
3796 		if (tcp->tcp_notsack_list != NULL) {
3797 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
3798 			    tcp);
3799 		}
3800 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
3801 	}
3802 
3803 	if (tcp->tcp_hopopts != NULL) {
3804 		mi_free(tcp->tcp_hopopts);
3805 		tcp->tcp_hopopts = NULL;
3806 		tcp->tcp_hopoptslen = 0;
3807 	}
3808 	ASSERT(tcp->tcp_hopoptslen == 0);
3809 	if (tcp->tcp_dstopts != NULL) {
3810 		mi_free(tcp->tcp_dstopts);
3811 		tcp->tcp_dstopts = NULL;
3812 		tcp->tcp_dstoptslen = 0;
3813 	}
3814 	ASSERT(tcp->tcp_dstoptslen == 0);
3815 	if (tcp->tcp_rthdrdstopts != NULL) {
3816 		mi_free(tcp->tcp_rthdrdstopts);
3817 		tcp->tcp_rthdrdstopts = NULL;
3818 		tcp->tcp_rthdrdstoptslen = 0;
3819 	}
3820 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
3821 	if (tcp->tcp_rthdr != NULL) {
3822 		mi_free(tcp->tcp_rthdr);
3823 		tcp->tcp_rthdr = NULL;
3824 		tcp->tcp_rthdrlen = 0;
3825 	}
3826 	ASSERT(tcp->tcp_rthdrlen == 0);
3827 
3828 	/*
3829 	 * Following is really a blowing away a union.
3830 	 * It happens to have exactly two members of identical size
3831 	 * the following code is enough.
3832 	 */
3833 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
3834 }
3835 
3836 
3837 /*
3838  * Put a connection confirmation message upstream built from the
3839  * address/flowid information with the conn and iph. Report our success or
3840  * failure.
3841  */
3842 static boolean_t
3843 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, mblk_t *idmp,
3844     mblk_t **defermp, ip_recv_attr_t *ira)
3845 {
3846 	sin_t	sin;
3847 	sin6_t	sin6;
3848 	mblk_t	*mp;
3849 	char	*optp = NULL;
3850 	int	optlen = 0;
3851 	conn_t	*connp = tcp->tcp_connp;
3852 
3853 	if (defermp != NULL)
3854 		*defermp = NULL;
3855 
3856 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
3857 		/*
3858 		 * Return in T_CONN_CON results of option negotiation through
3859 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
3860 		 * negotiation, then what is received from remote end needs
3861 		 * to be taken into account but there is no such thing (yet?)
3862 		 * in our TCP/IP.
3863 		 * Note: We do not use mi_offset_param() here as
3864 		 * tcp_opts_conn_req contents do not directly come from
3865 		 * an application and are either generated in kernel or
3866 		 * from user input that was already verified.
3867 		 */
3868 		mp = tcp->tcp_conn.tcp_opts_conn_req;
3869 		optp = (char *)(mp->b_rptr +
3870 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
3871 		optlen = (int)
3872 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
3873 	}
3874 
3875 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
3876 
3877 		/* packet is IPv4 */
3878 		if (connp->conn_family == AF_INET) {
3879 			sin = sin_null;
3880 			sin.sin_addr.s_addr = connp->conn_faddr_v4;
3881 			sin.sin_port = connp->conn_fport;
3882 			sin.sin_family = AF_INET;
3883 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
3884 			    (int)sizeof (sin_t), optp, optlen);
3885 		} else {
3886 			sin6 = sin6_null;
3887 			sin6.sin6_addr = connp->conn_faddr_v6;
3888 			sin6.sin6_port = connp->conn_fport;
3889 			sin6.sin6_family = AF_INET6;
3890 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
3891 			    (int)sizeof (sin6_t), optp, optlen);
3892 
3893 		}
3894 	} else {
3895 		ip6_t	*ip6h = (ip6_t *)iphdr;
3896 
3897 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
3898 		ASSERT(connp->conn_family == AF_INET6);
3899 		sin6 = sin6_null;
3900 		sin6.sin6_addr = connp->conn_faddr_v6;
3901 		sin6.sin6_port = connp->conn_fport;
3902 		sin6.sin6_family = AF_INET6;
3903 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
3904 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
3905 		    (int)sizeof (sin6_t), optp, optlen);
3906 	}
3907 
3908 	if (!mp)
3909 		return (B_FALSE);
3910 
3911 	mblk_copycred(mp, idmp);
3912 
3913 	if (defermp == NULL) {
3914 		conn_t *connp = tcp->tcp_connp;
3915 		if (IPCL_IS_NONSTR(connp)) {
3916 			(*connp->conn_upcalls->su_connected)
3917 			    (connp->conn_upper_handle, tcp->tcp_connid,
3918 			    ira->ira_cred, ira->ira_cpid);
3919 			freemsg(mp);
3920 		} else {
3921 			if (ira->ira_cred != NULL) {
3922 				/* So that getpeerucred works for TPI sockfs */
3923 				mblk_setcred(mp, ira->ira_cred, ira->ira_cpid);
3924 			}
3925 			putnext(connp->conn_rq, mp);
3926 		}
3927 	} else {
3928 		*defermp = mp;
3929 	}
3930 
3931 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
3932 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
3933 	return (B_TRUE);
3934 }
3935 
3936 /*
3937  * Defense for the SYN attack -
3938  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
3939  *    one from the list of droppable eagers. This list is a subset of q0.
3940  *    see comments before the definition of MAKE_DROPPABLE().
3941  * 2. Don't drop a SYN request before its first timeout. This gives every
3942  *    request at least til the first timeout to complete its 3-way handshake.
3943  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
3944  *    requests currently on the queue that has timed out. This will be used
3945  *    as an indicator of whether an attack is under way, so that appropriate
3946  *    actions can be taken. (It's incremented in tcp_timer() and decremented
3947  *    either when eager goes into ESTABLISHED, or gets freed up.)
3948  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
3949  *    # of timeout drops back to <= q0len/32 => SYN alert off
3950  */
3951 static boolean_t
3952 tcp_drop_q0(tcp_t *tcp)
3953 {
3954 	tcp_t	*eager;
3955 	mblk_t	*mp;
3956 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3957 
3958 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
3959 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
3960 
3961 	/* Pick oldest eager from the list of droppable eagers */
3962 	eager = tcp->tcp_eager_prev_drop_q0;
3963 
3964 	/* If list is empty. return B_FALSE */
3965 	if (eager == tcp) {
3966 		return (B_FALSE);
3967 	}
3968 
3969 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
3970 	if ((mp = allocb(0, BPRI_HI)) == NULL)
3971 		return (B_FALSE);
3972 
3973 	/*
3974 	 * Take this eager out from the list of droppable eagers since we are
3975 	 * going to drop it.
3976 	 */
3977 	MAKE_UNDROPPABLE(eager);
3978 
3979 	if (tcp->tcp_connp->conn_debug) {
3980 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
3981 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
3982 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
3983 		    tcp->tcp_conn_req_cnt_q0,
3984 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
3985 	}
3986 
3987 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
3988 
3989 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
3990 	CONN_INC_REF(eager->tcp_connp);
3991 
3992 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
3993 	    tcp_clean_death_wrapper, eager->tcp_connp, NULL,
3994 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
3995 
3996 	return (B_TRUE);
3997 }
3998 
3999 /*
4000  * Handle a SYN on an AF_INET6 socket; can be either IPv4 or IPv6
4001  */
4002 static mblk_t *
4003 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4004     ip_recv_attr_t *ira)
4005 {
4006 	tcp_t 		*ltcp = lconnp->conn_tcp;
4007 	tcp_t		*tcp = connp->conn_tcp;
4008 	mblk_t		*tpi_mp;
4009 	ipha_t		*ipha;
4010 	ip6_t		*ip6h;
4011 	sin6_t 		sin6;
4012 	uint_t		ifindex = ira->ira_ruifindex;
4013 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4014 
4015 	if (ira->ira_flags & IRAF_IS_IPV4) {
4016 		ipha = (ipha_t *)mp->b_rptr;
4017 
4018 		connp->conn_ipversion = IPV4_VERSION;
4019 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4020 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4021 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4022 
4023 		sin6 = sin6_null;
4024 		sin6.sin6_addr = connp->conn_faddr_v6;
4025 		sin6.sin6_port = connp->conn_fport;
4026 		sin6.sin6_family = AF_INET6;
4027 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4028 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4029 
4030 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4031 			sin6_t	sin6d;
4032 
4033 			sin6d = sin6_null;
4034 			sin6d.sin6_addr = connp->conn_laddr_v6;
4035 			sin6d.sin6_port = connp->conn_lport;
4036 			sin6d.sin6_family = AF_INET;
4037 			tpi_mp = mi_tpi_extconn_ind(NULL,
4038 			    (char *)&sin6d, sizeof (sin6_t),
4039 			    (char *)&tcp,
4040 			    (t_scalar_t)sizeof (intptr_t),
4041 			    (char *)&sin6d, sizeof (sin6_t),
4042 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4043 		} else {
4044 			tpi_mp = mi_tpi_conn_ind(NULL,
4045 			    (char *)&sin6, sizeof (sin6_t),
4046 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4047 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4048 		}
4049 	} else {
4050 		ip6h = (ip6_t *)mp->b_rptr;
4051 
4052 		connp->conn_ipversion = IPV6_VERSION;
4053 		connp->conn_laddr_v6 = ip6h->ip6_dst;
4054 		connp->conn_faddr_v6 = ip6h->ip6_src;
4055 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4056 
4057 		sin6 = sin6_null;
4058 		sin6.sin6_addr = connp->conn_faddr_v6;
4059 		sin6.sin6_port = connp->conn_fport;
4060 		sin6.sin6_family = AF_INET6;
4061 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4062 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4063 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4064 
4065 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4066 			/* Pass up the scope_id of remote addr */
4067 			sin6.sin6_scope_id = ifindex;
4068 		} else {
4069 			sin6.sin6_scope_id = 0;
4070 		}
4071 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4072 			sin6_t	sin6d;
4073 
4074 			sin6d = sin6_null;
4075 			sin6.sin6_addr = connp->conn_laddr_v6;
4076 			sin6d.sin6_port = connp->conn_lport;
4077 			sin6d.sin6_family = AF_INET6;
4078 			if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_laddr_v6))
4079 				sin6d.sin6_scope_id = ifindex;
4080 
4081 			tpi_mp = mi_tpi_extconn_ind(NULL,
4082 			    (char *)&sin6d, sizeof (sin6_t),
4083 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4084 			    (char *)&sin6d, sizeof (sin6_t),
4085 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4086 		} else {
4087 			tpi_mp = mi_tpi_conn_ind(NULL,
4088 			    (char *)&sin6, sizeof (sin6_t),
4089 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4090 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4091 		}
4092 	}
4093 
4094 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4095 	return (tpi_mp);
4096 }
4097 
4098 /* Handle a SYN on an AF_INET socket */
4099 mblk_t *
4100 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4101     ip_recv_attr_t *ira)
4102 {
4103 	tcp_t 		*ltcp = lconnp->conn_tcp;
4104 	tcp_t		*tcp = connp->conn_tcp;
4105 	sin_t		sin;
4106 	mblk_t		*tpi_mp = NULL;
4107 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4108 	ipha_t		*ipha;
4109 
4110 	ASSERT(ira->ira_flags & IRAF_IS_IPV4);
4111 	ipha = (ipha_t *)mp->b_rptr;
4112 
4113 	connp->conn_ipversion = IPV4_VERSION;
4114 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4115 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4116 	connp->conn_saddr_v6 = connp->conn_laddr_v6;
4117 
4118 	sin = sin_null;
4119 	sin.sin_addr.s_addr = connp->conn_faddr_v4;
4120 	sin.sin_port = connp->conn_fport;
4121 	sin.sin_family = AF_INET;
4122 	if (lconnp->conn_recv_ancillary.crb_recvdstaddr) {
4123 		sin_t	sind;
4124 
4125 		sind = sin_null;
4126 		sind.sin_addr.s_addr = connp->conn_laddr_v4;
4127 		sind.sin_port = connp->conn_lport;
4128 		sind.sin_family = AF_INET;
4129 		tpi_mp = mi_tpi_extconn_ind(NULL,
4130 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4131 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4132 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4133 	} else {
4134 		tpi_mp = mi_tpi_conn_ind(NULL,
4135 		    (char *)&sin, sizeof (sin_t),
4136 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4137 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4138 	}
4139 
4140 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4141 	return (tpi_mp);
4142 }
4143 
4144 /*
4145  * tcp_get_conn/tcp_free_conn
4146  *
4147  * tcp_get_conn is used to get a clean tcp connection structure.
4148  * It tries to reuse the connections put on the freelist by the
4149  * time_wait_collector failing which it goes to kmem_cache. This
4150  * way has two benefits compared to just allocating from and
4151  * freeing to kmem_cache.
4152  * 1) The time_wait_collector can free (which includes the cleanup)
4153  * outside the squeue. So when the interrupt comes, we have a clean
4154  * connection sitting in the freelist. Obviously, this buys us
4155  * performance.
4156  *
4157  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_input_listener
4158  * has multiple disadvantages - tying up the squeue during alloc.
4159  * But allocating the conn/tcp in IP land is also not the best since
4160  * we can't check the 'q' and 'q0' which are protected by squeue and
4161  * blindly allocate memory which might have to be freed here if we are
4162  * not allowed to accept the connection. By using the freelist and
4163  * putting the conn/tcp back in freelist, we don't pay a penalty for
4164  * allocating memory without checking 'q/q0' and freeing it if we can't
4165  * accept the connection.
4166  *
4167  * Care should be taken to put the conn back in the same squeue's freelist
4168  * from which it was allocated. Best results are obtained if conn is
4169  * allocated from listener's squeue and freed to the same. Time wait
4170  * collector will free up the freelist is the connection ends up sitting
4171  * there for too long.
4172  */
4173 void *
4174 tcp_get_conn(void *arg, tcp_stack_t *tcps)
4175 {
4176 	tcp_t			*tcp = NULL;
4177 	conn_t			*connp = NULL;
4178 	squeue_t		*sqp = (squeue_t *)arg;
4179 	tcp_squeue_priv_t 	*tcp_time_wait;
4180 	netstack_t		*ns;
4181 	mblk_t			*tcp_rsrv_mp = NULL;
4182 
4183 	tcp_time_wait =
4184 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
4185 
4186 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
4187 	tcp = tcp_time_wait->tcp_free_list;
4188 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
4189 	if (tcp != NULL) {
4190 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
4191 		tcp_time_wait->tcp_free_list_cnt--;
4192 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4193 		tcp->tcp_time_wait_next = NULL;
4194 		connp = tcp->tcp_connp;
4195 		connp->conn_flags |= IPCL_REUSED;
4196 
4197 		ASSERT(tcp->tcp_tcps == NULL);
4198 		ASSERT(connp->conn_netstack == NULL);
4199 		ASSERT(tcp->tcp_rsrv_mp != NULL);
4200 		ns = tcps->tcps_netstack;
4201 		netstack_hold(ns);
4202 		connp->conn_netstack = ns;
4203 		connp->conn_ixa->ixa_ipst = ns->netstack_ip;
4204 		tcp->tcp_tcps = tcps;
4205 		ipcl_globalhash_insert(connp);
4206 
4207 		connp->conn_ixa->ixa_notify_cookie = tcp;
4208 		ASSERT(connp->conn_ixa->ixa_notify == tcp_notify);
4209 		connp->conn_recv = tcp_input_data;
4210 		ASSERT(connp->conn_recvicmp == tcp_icmp_input);
4211 		ASSERT(connp->conn_verifyicmp == tcp_verifyicmp);
4212 		return ((void *)connp);
4213 	}
4214 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4215 	/*
4216 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
4217 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
4218 	 */
4219 	tcp_rsrv_mp = allocb(0, BPRI_HI);
4220 	if (tcp_rsrv_mp == NULL)
4221 		return (NULL);
4222 
4223 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
4224 	    tcps->tcps_netstack)) == NULL) {
4225 		freeb(tcp_rsrv_mp);
4226 		return (NULL);
4227 	}
4228 
4229 	tcp = connp->conn_tcp;
4230 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
4231 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
4232 
4233 	tcp->tcp_tcps = tcps;
4234 
4235 	connp->conn_recv = tcp_input_data;
4236 	connp->conn_recvicmp = tcp_icmp_input;
4237 	connp->conn_verifyicmp = tcp_verifyicmp;
4238 
4239 	/*
4240 	 * Register tcp_notify to listen to capability changes detected by IP.
4241 	 * This upcall is made in the context of the call to conn_ip_output
4242 	 * thus it is inside the squeue.
4243 	 */
4244 	connp->conn_ixa->ixa_notify = tcp_notify;
4245 	connp->conn_ixa->ixa_notify_cookie = tcp;
4246 
4247 	return ((void *)connp);
4248 }
4249 
4250 /* BEGIN CSTYLED */
4251 /*
4252  *
4253  * The sockfs ACCEPT path:
4254  * =======================
4255  *
4256  * The eager is now established in its own perimeter as soon as SYN is
4257  * received in tcp_input_listener(). When sockfs receives conn_ind, it
4258  * completes the accept processing on the acceptor STREAM. The sending
4259  * of conn_ind part is common for both sockfs listener and a TLI/XTI
4260  * listener but a TLI/XTI listener completes the accept processing
4261  * on the listener perimeter.
4262  *
4263  * Common control flow for 3 way handshake:
4264  * ----------------------------------------
4265  *
4266  * incoming SYN (listener perimeter)	-> tcp_input_listener()
4267  *
4268  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_input_data()
4269  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
4270  *
4271  * Sockfs ACCEPT Path:
4272  * -------------------
4273  *
4274  * open acceptor stream (tcp_open allocates tcp_tli_accept()
4275  * as STREAM entry point)
4276  *
4277  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_tli_accept()
4278  *
4279  * tcp_tli_accept() extracts the eager and makes the q->q_ptr <-> eager
4280  * association (we are not behind eager's squeue but sockfs is protecting us
4281  * and no one knows about this stream yet. The STREAMS entry point q->q_info
4282  * is changed to point at tcp_wput().
4283  *
4284  * tcp_accept_common() sends any deferred eagers via tcp_send_pending() to
4285  * listener (done on listener's perimeter).
4286  *
4287  * tcp_tli_accept() calls tcp_accept_finish() on eagers perimeter to finish
4288  * accept.
4289  *
4290  * TLI/XTI client ACCEPT path:
4291  * ---------------------------
4292  *
4293  * soaccept() sends T_CONN_RES on the listener STREAM.
4294  *
4295  * tcp_tli_accept() -> tcp_accept_swap() complete the processing and send
4296  * a M_SETOPS mblk to eager perimeter to finish accept (tcp_accept_finish()).
4297  *
4298  * Locks:
4299  * ======
4300  *
4301  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
4302  * and listeners->tcp_eager_next_q.
4303  *
4304  * Referencing:
4305  * ============
4306  *
4307  * 1) We start out in tcp_input_listener by eager placing a ref on
4308  * listener and listener adding eager to listeners->tcp_eager_next_q0.
4309  *
4310  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
4311  * doing so we place a ref on the eager. This ref is finally dropped at the
4312  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
4313  * reference is dropped by the squeue framework.
4314  *
4315  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
4316  *
4317  * The reference must be released by the same entity that added the reference
4318  * In the above scheme, the eager is the entity that adds and releases the
4319  * references. Note that tcp_accept_finish executes in the squeue of the eager
4320  * (albeit after it is attached to the acceptor stream). Though 1. executes
4321  * in the listener's squeue, the eager is nascent at this point and the
4322  * reference can be considered to have been added on behalf of the eager.
4323  *
4324  * Eager getting a Reset or listener closing:
4325  * ==========================================
4326  *
4327  * Once the listener and eager are linked, the listener never does the unlink.
4328  * If the listener needs to close, tcp_eager_cleanup() is called which queues
4329  * a message on all eager perimeter. The eager then does the unlink, clears
4330  * any pointers to the listener's queue and drops the reference to the
4331  * listener. The listener waits in tcp_close outside the squeue until its
4332  * refcount has dropped to 1. This ensures that the listener has waited for
4333  * all eagers to clear their association with the listener.
4334  *
4335  * Similarly, if eager decides to go away, it can unlink itself and close.
4336  * When the T_CONN_RES comes down, we check if eager has closed. Note that
4337  * the reference to eager is still valid because of the extra ref we put
4338  * in tcp_send_conn_ind.
4339  *
4340  * Listener can always locate the eager under the protection
4341  * of the listener->tcp_eager_lock, and then do a refhold
4342  * on the eager during the accept processing.
4343  *
4344  * The acceptor stream accesses the eager in the accept processing
4345  * based on the ref placed on eager before sending T_conn_ind.
4346  * The only entity that can negate this refhold is a listener close
4347  * which is mutually exclusive with an active acceptor stream.
4348  *
4349  * Eager's reference on the listener
4350  * ===================================
4351  *
4352  * If the accept happens (even on a closed eager) the eager drops its
4353  * reference on the listener at the start of tcp_accept_finish. If the
4354  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
4355  * the reference is dropped in tcp_closei_local. If the listener closes,
4356  * the reference is dropped in tcp_eager_kill. In all cases the reference
4357  * is dropped while executing in the eager's context (squeue).
4358  */
4359 /* END CSTYLED */
4360 
4361 /* Process the SYN packet, mp, directed at the listener 'tcp' */
4362 
4363 /*
4364  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
4365  * tcp_input_data will not see any packets for listeners since the listener
4366  * has conn_recv set to tcp_input_listener.
4367  */
4368 /* ARGSUSED */
4369 void
4370 tcp_input_listener(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4371 {
4372 	tcpha_t		*tcpha;
4373 	uint32_t	seg_seq;
4374 	tcp_t		*eager;
4375 	int		err;
4376 	conn_t		*econnp = NULL;
4377 	squeue_t	*new_sqp;
4378 	mblk_t		*mp1;
4379 	uint_t 		ip_hdr_len;
4380 	conn_t		*lconnp = (conn_t *)arg;
4381 	tcp_t		*listener = lconnp->conn_tcp;
4382 	tcp_stack_t	*tcps = listener->tcp_tcps;
4383 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
4384 	uint_t		flags;
4385 	mblk_t		*tpi_mp;
4386 	uint_t		ifindex = ira->ira_ruifindex;
4387 
4388 	ip_hdr_len = ira->ira_ip_hdr_length;
4389 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
4390 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
4391 
4392 	if (!(flags & TH_SYN)) {
4393 		if ((flags & TH_RST) || (flags & TH_URG)) {
4394 			freemsg(mp);
4395 			return;
4396 		}
4397 		if (flags & TH_ACK) {
4398 			/* Note this executes in listener's squeue */
4399 			tcp_xmit_listeners_reset(mp, ira, ipst, lconnp);
4400 			return;
4401 		}
4402 
4403 		freemsg(mp);
4404 		return;
4405 	}
4406 
4407 	if (listener->tcp_state != TCPS_LISTEN)
4408 		goto error2;
4409 
4410 	ASSERT(IPCL_IS_BOUND(lconnp));
4411 
4412 	mutex_enter(&listener->tcp_eager_lock);
4413 	if (listener->tcp_conn_req_cnt_q >= listener->tcp_conn_req_max) {
4414 		mutex_exit(&listener->tcp_eager_lock);
4415 		TCP_STAT(tcps, tcp_listendrop);
4416 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
4417 		if (lconnp->conn_debug) {
4418 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
4419 			    "tcp_input_listener: listen backlog (max=%d) "
4420 			    "overflow (%d pending) on %s",
4421 			    listener->tcp_conn_req_max,
4422 			    listener->tcp_conn_req_cnt_q,
4423 			    tcp_display(listener, NULL, DISP_PORT_ONLY));
4424 		}
4425 		goto error2;
4426 	}
4427 
4428 	if (listener->tcp_conn_req_cnt_q0 >=
4429 	    listener->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
4430 		/*
4431 		 * Q0 is full. Drop a pending half-open req from the queue
4432 		 * to make room for the new SYN req. Also mark the time we
4433 		 * drop a SYN.
4434 		 *
4435 		 * A more aggressive defense against SYN attack will
4436 		 * be to set the "tcp_syn_defense" flag now.
4437 		 */
4438 		TCP_STAT(tcps, tcp_listendropq0);
4439 		listener->tcp_last_rcv_lbolt = ddi_get_lbolt64();
4440 		if (!tcp_drop_q0(listener)) {
4441 			mutex_exit(&listener->tcp_eager_lock);
4442 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
4443 			if (lconnp->conn_debug) {
4444 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4445 				    "tcp_input_listener: listen half-open "
4446 				    "queue (max=%d) full (%d pending) on %s",
4447 				    tcps->tcps_conn_req_max_q0,
4448 				    listener->tcp_conn_req_cnt_q0,
4449 				    tcp_display(listener, NULL,
4450 				    DISP_PORT_ONLY));
4451 			}
4452 			goto error2;
4453 		}
4454 	}
4455 	mutex_exit(&listener->tcp_eager_lock);
4456 
4457 	/*
4458 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
4459 	 * or based on the ring (for packets from GLD). Otherwise it is
4460 	 * set based on lbolt i.e., a somewhat random number.
4461 	 */
4462 	ASSERT(ira->ira_sqp != NULL);
4463 	new_sqp = ira->ira_sqp;
4464 
4465 	econnp = (conn_t *)tcp_get_conn(arg2, tcps);
4466 	if (econnp == NULL)
4467 		goto error2;
4468 
4469 	ASSERT(econnp->conn_netstack == lconnp->conn_netstack);
4470 	econnp->conn_sqp = new_sqp;
4471 	econnp->conn_initial_sqp = new_sqp;
4472 	econnp->conn_ixa->ixa_sqp = new_sqp;
4473 
4474 	econnp->conn_fport = tcpha->tha_lport;
4475 	econnp->conn_lport = tcpha->tha_fport;
4476 
4477 	err = conn_inherit_parent(lconnp, econnp);
4478 	if (err != 0)
4479 		goto error3;
4480 
4481 	ASSERT(OK_32PTR(mp->b_rptr));
4482 	ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION ||
4483 	    IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
4484 
4485 	if (lconnp->conn_family == AF_INET) {
4486 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
4487 		tpi_mp = tcp_conn_create_v4(lconnp, econnp, mp, ira);
4488 	} else {
4489 		tpi_mp = tcp_conn_create_v6(lconnp, econnp, mp, ira);
4490 	}
4491 
4492 	if (tpi_mp == NULL)
4493 		goto error3;
4494 
4495 	eager = econnp->conn_tcp;
4496 	eager->tcp_detached = B_TRUE;
4497 	SOCK_CONNID_INIT(eager->tcp_connid);
4498 
4499 	tcp_init_values(eager);
4500 
4501 	ASSERT((econnp->conn_ixa->ixa_flags &
4502 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4503 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO)) ==
4504 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4505 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO));
4506 
4507 	if (!tcps->tcps_dev_flow_ctl)
4508 		econnp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
4509 
4510 	/* Prepare for diffing against previous packets */
4511 	eager->tcp_recvifindex = 0;
4512 	eager->tcp_recvhops = 0xffffffffU;
4513 
4514 	if (!(ira->ira_flags & IRAF_IS_IPV4) && econnp->conn_bound_if == 0) {
4515 		if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_faddr_v6) ||
4516 		    IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6)) {
4517 			econnp->conn_incoming_ifindex = ifindex;
4518 			econnp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
4519 			econnp->conn_ixa->ixa_scopeid = ifindex;
4520 		}
4521 	}
4522 
4523 	if ((ira->ira_flags & (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS)) ==
4524 	    (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS) &&
4525 	    tcps->tcps_rev_src_routes) {
4526 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
4527 		ip_pkt_t *ipp = &econnp->conn_xmit_ipp;
4528 
4529 		/* Source routing option copyover (reverse it) */
4530 		err = ip_find_hdr_v4(ipha, ipp, B_TRUE);
4531 		if (err != 0) {
4532 			freemsg(tpi_mp);
4533 			goto error3;
4534 		}
4535 		ip_pkt_source_route_reverse_v4(ipp);
4536 	}
4537 
4538 	ASSERT(eager->tcp_conn.tcp_eager_conn_ind == NULL);
4539 	ASSERT(!eager->tcp_tconnind_started);
4540 	/*
4541 	 * If the SYN came with a credential, it's a loopback packet or a
4542 	 * labeled packet; attach the credential to the TPI message.
4543 	 */
4544 	if (ira->ira_cred != NULL)
4545 		mblk_setcred(tpi_mp, ira->ira_cred, ira->ira_cpid);
4546 
4547 	eager->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4548 
4549 	/* Inherit the listener's SSL protection state */
4550 	if ((eager->tcp_kssl_ent = listener->tcp_kssl_ent) != NULL) {
4551 		kssl_hold_ent(eager->tcp_kssl_ent);
4552 		eager->tcp_kssl_pending = B_TRUE;
4553 	}
4554 
4555 	/* Inherit the listener's non-STREAMS flag */
4556 	if (IPCL_IS_NONSTR(lconnp)) {
4557 		econnp->conn_flags |= IPCL_NONSTR;
4558 	}
4559 
4560 	ASSERT(eager->tcp_ordrel_mp == NULL);
4561 
4562 	if (!IPCL_IS_NONSTR(econnp)) {
4563 		/*
4564 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
4565 		 * at close time, we will always have that to send up.
4566 		 * Otherwise, we need to do special handling in case the
4567 		 * allocation fails at that time.
4568 		 */
4569 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
4570 			goto error3;
4571 	}
4572 	/*
4573 	 * Now that the IP addresses and ports are setup in econnp we
4574 	 * can do the IPsec policy work.
4575 	 */
4576 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
4577 		if (lconnp->conn_policy != NULL) {
4578 			/*
4579 			 * Inherit the policy from the listener; use
4580 			 * actions from ira
4581 			 */
4582 			if (!ip_ipsec_policy_inherit(econnp, lconnp, ira)) {
4583 				CONN_DEC_REF(econnp);
4584 				freemsg(mp);
4585 				goto error3;
4586 			}
4587 		}
4588 	}
4589 
4590 	/* Inherit various TCP parameters from the listener */
4591 	eager->tcp_naglim = listener->tcp_naglim;
4592 	eager->tcp_first_timer_threshold = listener->tcp_first_timer_threshold;
4593 	eager->tcp_second_timer_threshold =
4594 	    listener->tcp_second_timer_threshold;
4595 	eager->tcp_first_ctimer_threshold =
4596 	    listener->tcp_first_ctimer_threshold;
4597 	eager->tcp_second_ctimer_threshold =
4598 	    listener->tcp_second_ctimer_threshold;
4599 
4600 	/*
4601 	 * tcp_set_destination() may set tcp_rwnd according to the route
4602 	 * metrics. If it does not, the eager's receive window will be set
4603 	 * to the listener's receive window later in this function.
4604 	 */
4605 	eager->tcp_rwnd = 0;
4606 
4607 	/*
4608 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
4609 	 * calling tcp_process_options() which set the initial cwnd.
4610 	 */
4611 	eager->tcp_init_cwnd = listener->tcp_init_cwnd;
4612 
4613 	if (is_system_labeled()) {
4614 		ip_xmit_attr_t *ixa = econnp->conn_ixa;
4615 
4616 		ASSERT(ira->ira_tsl != NULL);
4617 		/* Discard any old label */
4618 		if (ixa->ixa_free_flags & IXA_FREE_TSL) {
4619 			ASSERT(ixa->ixa_tsl != NULL);
4620 			label_rele(ixa->ixa_tsl);
4621 			ixa->ixa_free_flags &= ~IXA_FREE_TSL;
4622 			ixa->ixa_tsl = NULL;
4623 		}
4624 		if ((lconnp->conn_mlp_type != mlptSingle ||
4625 		    lconnp->conn_mac_mode != CONN_MAC_DEFAULT) &&
4626 		    ira->ira_tsl != NULL) {
4627 			/*
4628 			 * If this is an MLP connection or a MAC-Exempt
4629 			 * connection with an unlabeled node, packets are to be
4630 			 * exchanged using the security label of the received
4631 			 * SYN packet instead of the server application's label.
4632 			 * tsol_check_dest called from ip_set_destination
4633 			 * might later update TSF_UNLABELED by replacing
4634 			 * ixa_tsl with a new label.
4635 			 */
4636 			label_hold(ira->ira_tsl);
4637 			ip_xmit_attr_replace_tsl(ixa, ira->ira_tsl);
4638 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
4639 			    econnp, ts_label_t *, ixa->ixa_tsl)
4640 		} else {
4641 			ixa->ixa_tsl = crgetlabel(econnp->conn_cred);
4642 			DTRACE_PROBE2(syn_accept, conn_t *,
4643 			    econnp, ts_label_t *, ixa->ixa_tsl)
4644 		}
4645 		/*
4646 		 * conn_connect() called from tcp_set_destination will verify
4647 		 * the destination is allowed to receive packets at the
4648 		 * security label of the SYN-ACK we are generating. As part of
4649 		 * that, tsol_check_dest() may create a new effective label for
4650 		 * this connection.
4651 		 * Finally conn_connect() will call conn_update_label.
4652 		 * All that remains for TCP to do is to call
4653 		 * conn_build_hdr_template which is done as part of
4654 		 * tcp_set_destination.
4655 		 */
4656 	}
4657 
4658 	/*
4659 	 * Since we will clear tcp_listener before we clear tcp_detached
4660 	 * in the accept code we need tcp_hard_binding aka tcp_accept_inprogress
4661 	 * so we can tell a TCP_DETACHED_NONEAGER apart.
4662 	 */
4663 	eager->tcp_hard_binding = B_TRUE;
4664 
4665 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
4666 	    TCP_BIND_HASH(econnp->conn_lport)], eager, 0);
4667 
4668 	CL_INET_CONNECT(econnp, B_FALSE, err);
4669 	if (err != 0) {
4670 		tcp_bind_hash_remove(eager);
4671 		goto error3;
4672 	}
4673 
4674 	/*
4675 	 * No need to check for multicast destination since ip will only pass
4676 	 * up multicasts to those that have expressed interest
4677 	 * TODO: what about rejecting broadcasts?
4678 	 * Also check that source is not a multicast or broadcast address.
4679 	 */
4680 	eager->tcp_state = TCPS_SYN_RCVD;
4681 	SOCK_CONNID_BUMP(eager->tcp_connid);
4682 
4683 	/*
4684 	 * Adapt our mss, ttl, ... based on the remote address.
4685 	 */
4686 
4687 	if (tcp_set_destination(eager) != 0) {
4688 		BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4689 		/* Undo the bind_hash_insert */
4690 		tcp_bind_hash_remove(eager);
4691 		goto error3;
4692 	}
4693 
4694 	/* Process all TCP options. */
4695 	tcp_process_options(eager, tcpha);
4696 
4697 	/* Is the other end ECN capable? */
4698 	if (tcps->tcps_ecn_permitted >= 1 &&
4699 	    (tcpha->tha_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
4700 		eager->tcp_ecn_ok = B_TRUE;
4701 	}
4702 
4703 	/*
4704 	 * The listener's conn_rcvbuf should be the default window size or a
4705 	 * window size changed via SO_RCVBUF option. First round up the
4706 	 * eager's tcp_rwnd to the nearest MSS. Then find out the window
4707 	 * scale option value if needed. Call tcp_rwnd_set() to finish the
4708 	 * setting.
4709 	 *
4710 	 * Note if there is a rpipe metric associated with the remote host,
4711 	 * we should not inherit receive window size from listener.
4712 	 */
4713 	eager->tcp_rwnd = MSS_ROUNDUP(
4714 	    (eager->tcp_rwnd == 0 ? econnp->conn_rcvbuf :
4715 	    eager->tcp_rwnd), eager->tcp_mss);
4716 	if (eager->tcp_snd_ws_ok)
4717 		tcp_set_ws_value(eager);
4718 	/*
4719 	 * Note that this is the only place tcp_rwnd_set() is called for
4720 	 * accepting a connection.  We need to call it here instead of
4721 	 * after the 3-way handshake because we need to tell the other
4722 	 * side our rwnd in the SYN-ACK segment.
4723 	 */
4724 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
4725 
4726 	ASSERT(eager->tcp_connp->conn_rcvbuf != 0 &&
4727 	    eager->tcp_connp->conn_rcvbuf == eager->tcp_rwnd);
4728 
4729 	ASSERT(econnp->conn_rcvbuf != 0 &&
4730 	    econnp->conn_rcvbuf == eager->tcp_rwnd);
4731 
4732 	/* Put a ref on the listener for the eager. */
4733 	CONN_INC_REF(lconnp);
4734 	mutex_enter(&listener->tcp_eager_lock);
4735 	listener->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
4736 	eager->tcp_eager_next_q0 = listener->tcp_eager_next_q0;
4737 	listener->tcp_eager_next_q0 = eager;
4738 	eager->tcp_eager_prev_q0 = listener;
4739 
4740 	/* Set tcp_listener before adding it to tcp_conn_fanout */
4741 	eager->tcp_listener = listener;
4742 	eager->tcp_saved_listener = listener;
4743 
4744 	/*
4745 	 * Tag this detached tcp vector for later retrieval
4746 	 * by our listener client in tcp_accept().
4747 	 */
4748 	eager->tcp_conn_req_seqnum = listener->tcp_conn_req_seqnum;
4749 	listener->tcp_conn_req_cnt_q0++;
4750 	if (++listener->tcp_conn_req_seqnum == -1) {
4751 		/*
4752 		 * -1 is "special" and defined in TPI as something
4753 		 * that should never be used in T_CONN_IND
4754 		 */
4755 		++listener->tcp_conn_req_seqnum;
4756 	}
4757 	mutex_exit(&listener->tcp_eager_lock);
4758 
4759 	if (listener->tcp_syn_defense) {
4760 		/* Don't drop the SYN that comes from a good IP source */
4761 		ipaddr_t *addr_cache;
4762 
4763 		addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
4764 		if (addr_cache != NULL && econnp->conn_faddr_v4 ==
4765 		    addr_cache[IP_ADDR_CACHE_HASH(econnp->conn_faddr_v4)]) {
4766 			eager->tcp_dontdrop = B_TRUE;
4767 		}
4768 	}
4769 
4770 	/*
4771 	 * We need to insert the eager in its own perimeter but as soon
4772 	 * as we do that, we expose the eager to the classifier and
4773 	 * should not touch any field outside the eager's perimeter.
4774 	 * So do all the work necessary before inserting the eager
4775 	 * in its own perimeter. Be optimistic that conn_connect()
4776 	 * will succeed but undo everything if it fails.
4777 	 */
4778 	seg_seq = ntohl(tcpha->tha_seq);
4779 	eager->tcp_irs = seg_seq;
4780 	eager->tcp_rack = seg_seq;
4781 	eager->tcp_rnxt = seg_seq + 1;
4782 	eager->tcp_tcpha->tha_ack = htonl(eager->tcp_rnxt);
4783 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
4784 	eager->tcp_state = TCPS_SYN_RCVD;
4785 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
4786 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
4787 	if (mp1 == NULL) {
4788 		/*
4789 		 * Increment the ref count as we are going to
4790 		 * enqueueing an mp in squeue
4791 		 */
4792 		CONN_INC_REF(econnp);
4793 		goto error;
4794 	}
4795 
4796 	/*
4797 	 * We need to start the rto timer. In normal case, we start
4798 	 * the timer after sending the packet on the wire (or at
4799 	 * least believing that packet was sent by waiting for
4800 	 * conn_ip_output() to return). Since this is the first packet
4801 	 * being sent on the wire for the eager, our initial tcp_rto
4802 	 * is at least tcp_rexmit_interval_min which is a fairly
4803 	 * large value to allow the algorithm to adjust slowly to large
4804 	 * fluctuations of RTT during first few transmissions.
4805 	 *
4806 	 * Starting the timer first and then sending the packet in this
4807 	 * case shouldn't make much difference since tcp_rexmit_interval_min
4808 	 * is of the order of several 100ms and starting the timer
4809 	 * first and then sending the packet will result in difference
4810 	 * of few micro seconds.
4811 	 *
4812 	 * Without this optimization, we are forced to hold the fanout
4813 	 * lock across the ipcl_bind_insert() and sending the packet
4814 	 * so that we don't race against an incoming packet (maybe RST)
4815 	 * for this eager.
4816 	 *
4817 	 * It is necessary to acquire an extra reference on the eager
4818 	 * at this point and hold it until after tcp_send_data() to
4819 	 * ensure against an eager close race.
4820 	 */
4821 
4822 	CONN_INC_REF(econnp);
4823 
4824 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
4825 
4826 	/*
4827 	 * Insert the eager in its own perimeter now. We are ready to deal
4828 	 * with any packets on eager.
4829 	 */
4830 	if (ipcl_conn_insert(econnp) != 0)
4831 		goto error;
4832 
4833 	/*
4834 	 * Send the SYN-ACK. Can't use tcp_send_data since we can't update
4835 	 * pmtu etc; we are not on the eager's squeue
4836 	 */
4837 	ASSERT(econnp->conn_ixa->ixa_notify_cookie == econnp->conn_tcp);
4838 	(void) conn_ip_output(mp1, econnp->conn_ixa);
4839 	CONN_DEC_REF(econnp);
4840 	freemsg(mp);
4841 
4842 	return;
4843 error:
4844 	freemsg(mp1);
4845 	eager->tcp_closemp_used = B_TRUE;
4846 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
4847 	mp1 = &eager->tcp_closemp;
4848 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
4849 	    econnp, NULL, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
4850 
4851 	/*
4852 	 * If a connection already exists, send the mp to that connections so
4853 	 * that it can be appropriately dealt with.
4854 	 */
4855 	ipst = tcps->tcps_netstack->netstack_ip;
4856 
4857 	if ((econnp = ipcl_classify(mp, ira, ipst)) != NULL) {
4858 		if (!IPCL_IS_CONNECTED(econnp)) {
4859 			/*
4860 			 * Something bad happened. ipcl_conn_insert()
4861 			 * failed because a connection already existed
4862 			 * in connected hash but we can't find it
4863 			 * anymore (someone blew it away). Just
4864 			 * free this message and hopefully remote
4865 			 * will retransmit at which time the SYN can be
4866 			 * treated as a new connection or dealth with
4867 			 * a TH_RST if a connection already exists.
4868 			 */
4869 			CONN_DEC_REF(econnp);
4870 			freemsg(mp);
4871 		} else {
4872 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp, tcp_input_data,
4873 			    econnp, ira, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
4874 		}
4875 	} else {
4876 		/* Nobody wants this packet */
4877 		freemsg(mp);
4878 	}
4879 	return;
4880 error3:
4881 	CONN_DEC_REF(econnp);
4882 error2:
4883 	freemsg(mp);
4884 }
4885 
4886 /*
4887  * In an ideal case of vertical partition in NUMA architecture, its
4888  * beneficial to have the listener and all the incoming connections
4889  * tied to the same squeue. The other constraint is that incoming
4890  * connections should be tied to the squeue attached to interrupted
4891  * CPU for obvious locality reason so this leaves the listener to
4892  * be tied to the same squeue. Our only problem is that when listener
4893  * is binding, the CPU that will get interrupted by the NIC whose
4894  * IP address the listener is binding to is not even known. So
4895  * the code below allows us to change that binding at the time the
4896  * CPU is interrupted by virtue of incoming connection's squeue.
4897  *
4898  * This is usefull only in case of a listener bound to a specific IP
4899  * address. For other kind of listeners, they get bound the
4900  * very first time and there is no attempt to rebind them.
4901  */
4902 void
4903 tcp_input_listener_unbound(void *arg, mblk_t *mp, void *arg2,
4904     ip_recv_attr_t *ira)
4905 {
4906 	conn_t		*connp = (conn_t *)arg;
4907 	squeue_t	*sqp = (squeue_t *)arg2;
4908 	squeue_t	*new_sqp;
4909 	uint32_t	conn_flags;
4910 
4911 	/*
4912 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
4913 	 * or based on the ring (for packets from GLD). Otherwise it is
4914 	 * set based on lbolt i.e., a somewhat random number.
4915 	 */
4916 	ASSERT(ira->ira_sqp != NULL);
4917 	new_sqp = ira->ira_sqp;
4918 
4919 	if (connp->conn_fanout == NULL)
4920 		goto done;
4921 
4922 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
4923 		mutex_enter(&connp->conn_fanout->connf_lock);
4924 		mutex_enter(&connp->conn_lock);
4925 		/*
4926 		 * No one from read or write side can access us now
4927 		 * except for already queued packets on this squeue.
4928 		 * But since we haven't changed the squeue yet, they
4929 		 * can't execute. If they are processed after we have
4930 		 * changed the squeue, they are sent back to the
4931 		 * correct squeue down below.
4932 		 * But a listner close can race with processing of
4933 		 * incoming SYN. If incoming SYN processing changes
4934 		 * the squeue then the listener close which is waiting
4935 		 * to enter the squeue would operate on the wrong
4936 		 * squeue. Hence we don't change the squeue here unless
4937 		 * the refcount is exactly the minimum refcount. The
4938 		 * minimum refcount of 4 is counted as - 1 each for
4939 		 * TCP and IP, 1 for being in the classifier hash, and
4940 		 * 1 for the mblk being processed.
4941 		 */
4942 
4943 		if (connp->conn_ref != 4 ||
4944 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
4945 			mutex_exit(&connp->conn_lock);
4946 			mutex_exit(&connp->conn_fanout->connf_lock);
4947 			goto done;
4948 		}
4949 		if (connp->conn_sqp != new_sqp) {
4950 			while (connp->conn_sqp != new_sqp)
4951 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
4952 			/* No special MT issues for outbound ixa_sqp hint */
4953 			connp->conn_ixa->ixa_sqp = new_sqp;
4954 		}
4955 
4956 		do {
4957 			conn_flags = connp->conn_flags;
4958 			conn_flags |= IPCL_FULLY_BOUND;
4959 			(void) cas32(&connp->conn_flags, connp->conn_flags,
4960 			    conn_flags);
4961 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
4962 
4963 		mutex_exit(&connp->conn_fanout->connf_lock);
4964 		mutex_exit(&connp->conn_lock);
4965 
4966 		/*
4967 		 * Assume we have picked a good squeue for the listener. Make
4968 		 * subsequent SYNs not try to change the squeue.
4969 		 */
4970 		connp->conn_recv = tcp_input_listener;
4971 	}
4972 
4973 done:
4974 	if (connp->conn_sqp != sqp) {
4975 		CONN_INC_REF(connp);
4976 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
4977 		    ira, SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
4978 	} else {
4979 		tcp_input_listener(connp, mp, sqp, ira);
4980 	}
4981 }
4982 
4983 /*
4984  * Successful connect request processing begins when our client passes
4985  * a T_CONN_REQ message into tcp_wput(), which performs function calls into
4986  * IP and the passes a T_OK_ACK (or T_ERROR_ACK upstream).
4987  *
4988  * After various error checks are completed, tcp_tpi_connect() lays
4989  * the target address and port into the composite header template.
4990  * Then we ask IP for information, including a source address if we didn't
4991  * already have one. Finally we prepare to send the SYN packet, and then
4992  * send up the T_OK_ACK reply message.
4993  */
4994 static void
4995 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
4996 {
4997 	sin_t		*sin;
4998 	struct T_conn_req	*tcr;
4999 	struct sockaddr	*sa;
5000 	socklen_t	len;
5001 	int		error;
5002 	cred_t		*cr;
5003 	pid_t		cpid;
5004 	conn_t		*connp = tcp->tcp_connp;
5005 	queue_t		*q = connp->conn_wq;
5006 
5007 	/*
5008 	 * All Solaris components should pass a db_credp
5009 	 * for this TPI message, hence we ASSERT.
5010 	 * But in case there is some other M_PROTO that looks
5011 	 * like a TPI message sent by some other kernel
5012 	 * component, we check and return an error.
5013 	 */
5014 	cr = msg_getcred(mp, &cpid);
5015 	ASSERT(cr != NULL);
5016 	if (cr == NULL) {
5017 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5018 		return;
5019 	}
5020 
5021 	tcr = (struct T_conn_req *)mp->b_rptr;
5022 
5023 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5024 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5025 		tcp_err_ack(tcp, mp, TPROTO, 0);
5026 		return;
5027 	}
5028 
5029 	/*
5030 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5031 	 * will always have that to send up.  Otherwise, we need to do
5032 	 * special handling in case the allocation fails at that time.
5033 	 * If the end point is TPI, the tcp_t can be reused and the
5034 	 * tcp_ordrel_mp may be allocated already.
5035 	 */
5036 	if (tcp->tcp_ordrel_mp == NULL) {
5037 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5038 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5039 			return;
5040 		}
5041 	}
5042 
5043 	/*
5044 	 * Determine packet type based on type of address passed in
5045 	 * the request should contain an IPv4 or IPv6 address.
5046 	 * Make sure that address family matches the type of
5047 	 * family of the address passed down.
5048 	 */
5049 	switch (tcr->DEST_length) {
5050 	default:
5051 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5052 		return;
5053 
5054 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5055 		/*
5056 		 * XXX: The check for valid DEST_length was not there
5057 		 * in earlier releases and some buggy
5058 		 * TLI apps (e.g Sybase) got away with not feeding
5059 		 * in sin_zero part of address.
5060 		 * We allow that bug to keep those buggy apps humming.
5061 		 * Test suites require the check on DEST_length.
5062 		 * We construct a new mblk with valid DEST_length
5063 		 * free the original so the rest of the code does
5064 		 * not have to keep track of this special shorter
5065 		 * length address case.
5066 		 */
5067 		mblk_t *nmp;
5068 		struct T_conn_req *ntcr;
5069 		sin_t *nsin;
5070 
5071 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5072 		    tcr->OPT_length, BPRI_HI);
5073 		if (nmp == NULL) {
5074 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5075 			return;
5076 		}
5077 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5078 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5079 		ntcr->PRIM_type = T_CONN_REQ;
5080 		ntcr->DEST_length = sizeof (sin_t);
5081 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5082 
5083 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5084 		*nsin = sin_null;
5085 		/* Get pointer to shorter address to copy from original mp */
5086 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5087 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5088 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5089 			freemsg(nmp);
5090 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5091 			return;
5092 		}
5093 		nsin->sin_family = sin->sin_family;
5094 		nsin->sin_port = sin->sin_port;
5095 		nsin->sin_addr = sin->sin_addr;
5096 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5097 		nmp->b_wptr = (uchar_t *)&nsin[1];
5098 		if (tcr->OPT_length != 0) {
5099 			ntcr->OPT_length = tcr->OPT_length;
5100 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5101 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5102 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5103 			    tcr->OPT_length);
5104 			nmp->b_wptr += tcr->OPT_length;
5105 		}
5106 		freemsg(mp);	/* original mp freed */
5107 		mp = nmp;	/* re-initialize original variables */
5108 		tcr = ntcr;
5109 	}
5110 	/* FALLTHRU */
5111 
5112 	case sizeof (sin_t):
5113 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5114 		    sizeof (sin_t));
5115 		len = sizeof (sin_t);
5116 		break;
5117 
5118 	case sizeof (sin6_t):
5119 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5120 		    sizeof (sin6_t));
5121 		len = sizeof (sin6_t);
5122 		break;
5123 	}
5124 
5125 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
5126 	if (error != 0) {
5127 		tcp_err_ack(tcp, mp, TSYSERR, error);
5128 		return;
5129 	}
5130 
5131 	/*
5132 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5133 	 * should key on their sequence number and cut them loose.
5134 	 */
5135 
5136 	/*
5137 	 * If options passed in, feed it for verification and handling
5138 	 */
5139 	if (tcr->OPT_length != 0) {
5140 		mblk_t	*ok_mp;
5141 		mblk_t	*discon_mp;
5142 		mblk_t  *conn_opts_mp;
5143 		int t_error, sys_error, do_disconnect;
5144 
5145 		conn_opts_mp = NULL;
5146 
5147 		if (tcp_conprim_opt_process(tcp, mp,
5148 		    &do_disconnect, &t_error, &sys_error) < 0) {
5149 			if (do_disconnect) {
5150 				ASSERT(t_error == 0 && sys_error == 0);
5151 				discon_mp = mi_tpi_discon_ind(NULL,
5152 				    ECONNREFUSED, 0);
5153 				if (!discon_mp) {
5154 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5155 					    TSYSERR, ENOMEM);
5156 					return;
5157 				}
5158 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5159 				if (!ok_mp) {
5160 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5161 					    TSYSERR, ENOMEM);
5162 					return;
5163 				}
5164 				qreply(q, ok_mp);
5165 				qreply(q, discon_mp); /* no flush! */
5166 			} else {
5167 				ASSERT(t_error != 0);
5168 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5169 				    sys_error);
5170 			}
5171 			return;
5172 		}
5173 		/*
5174 		 * Success in setting options, the mp option buffer represented
5175 		 * by OPT_length/offset has been potentially modified and
5176 		 * contains results of option processing. We copy it in
5177 		 * another mp to save it for potentially influencing returning
5178 		 * it in T_CONN_CONN.
5179 		 */
5180 		if (tcr->OPT_length != 0) { /* there are resulting options */
5181 			conn_opts_mp = copyb(mp);
5182 			if (!conn_opts_mp) {
5183 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5184 				    TSYSERR, ENOMEM);
5185 				return;
5186 			}
5187 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5188 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5189 			/*
5190 			 * Note:
5191 			 * These resulting option negotiation can include any
5192 			 * end-to-end negotiation options but there no such
5193 			 * thing (yet?) in our TCP/IP.
5194 			 */
5195 		}
5196 	}
5197 
5198 	/* call the non-TPI version */
5199 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
5200 	if (error < 0) {
5201 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
5202 	} else if (error > 0) {
5203 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
5204 	} else {
5205 		mp = mi_tpi_ok_ack_alloc(mp);
5206 	}
5207 
5208 	/*
5209 	 * Note: Code below is the "failure" case
5210 	 */
5211 	/* return error ack and blow away saved option results if any */
5212 connect_failed:
5213 	if (mp != NULL)
5214 		putnext(connp->conn_rq, mp);
5215 	else {
5216 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5217 		    TSYSERR, ENOMEM);
5218 	}
5219 }
5220 
5221 /*
5222  * Handle connect to IPv4 destinations, including connections for AF_INET6
5223  * sockets connecting to IPv4 mapped IPv6 destinations.
5224  * Returns zero if OK, a positive errno, or a negative TLI error.
5225  */
5226 static int
5227 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
5228     uint_t srcid)
5229 {
5230 	ipaddr_t 	dstaddr = *dstaddrp;
5231 	uint16_t 	lport;
5232 	conn_t		*connp = tcp->tcp_connp;
5233 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5234 	int		error;
5235 
5236 	ASSERT(connp->conn_ipversion == IPV4_VERSION);
5237 
5238 	/* Check for attempt to connect to INADDR_ANY */
5239 	if (dstaddr == INADDR_ANY)  {
5240 		/*
5241 		 * SunOS 4.x and 4.3 BSD allow an application
5242 		 * to connect a TCP socket to INADDR_ANY.
5243 		 * When they do this, the kernel picks the
5244 		 * address of one interface and uses it
5245 		 * instead.  The kernel usually ends up
5246 		 * picking the address of the loopback
5247 		 * interface.  This is an undocumented feature.
5248 		 * However, we provide the same thing here
5249 		 * in order to have source and binary
5250 		 * compatibility with SunOS 4.x.
5251 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5252 		 * generate the T_CONN_CON.
5253 		 */
5254 		dstaddr = htonl(INADDR_LOOPBACK);
5255 		*dstaddrp = dstaddr;
5256 	}
5257 
5258 	/* Handle __sin6_src_id if socket not bound to an IP address */
5259 	if (srcid != 0 && connp->conn_laddr_v4 == INADDR_ANY) {
5260 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5261 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5262 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5263 	}
5264 
5265 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &connp->conn_faddr_v6);
5266 	connp->conn_fport = dstport;
5267 
5268 	/*
5269 	 * At this point the remote destination address and remote port fields
5270 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5271 	 * have to see which state tcp was in so we can take appropriate action.
5272 	 */
5273 	if (tcp->tcp_state == TCPS_IDLE) {
5274 		/*
5275 		 * We support a quick connect capability here, allowing
5276 		 * clients to transition directly from IDLE to SYN_SENT
5277 		 * tcp_bindi will pick an unused port, insert the connection
5278 		 * in the bind hash and transition to BOUND state.
5279 		 */
5280 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5281 		    tcp, B_TRUE);
5282 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5283 		    B_FALSE, B_FALSE);
5284 		if (lport == 0)
5285 			return (-TNOADDR);
5286 	}
5287 
5288 	/*
5289 	 * Lookup the route to determine a source address and the uinfo.
5290 	 * Setup TCP parameters based on the metrics/DCE.
5291 	 */
5292 	error = tcp_set_destination(tcp);
5293 	if (error != 0)
5294 		return (error);
5295 
5296 	/*
5297 	 * Don't let an endpoint connect to itself.
5298 	 */
5299 	if (connp->conn_faddr_v4 == connp->conn_laddr_v4 &&
5300 	    connp->conn_fport == connp->conn_lport)
5301 		return (-TBADADDR);
5302 
5303 	tcp->tcp_state = TCPS_SYN_SENT;
5304 
5305 	return (ipcl_conn_insert_v4(connp));
5306 }
5307 
5308 /*
5309  * Handle connect to IPv6 destinations.
5310  * Returns zero if OK, a positive errno, or a negative TLI error.
5311  */
5312 static int
5313 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
5314     uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
5315 {
5316 	uint16_t 	lport;
5317 	conn_t		*connp = tcp->tcp_connp;
5318 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5319 	int		error;
5320 
5321 	ASSERT(connp->conn_family == AF_INET6);
5322 
5323 	/*
5324 	 * If we're here, it means that the destination address is a native
5325 	 * IPv6 address.  Return an error if conn_ipversion is not IPv6.  A
5326 	 * reason why it might not be IPv6 is if the socket was bound to an
5327 	 * IPv4-mapped IPv6 address.
5328 	 */
5329 	if (connp->conn_ipversion != IPV6_VERSION)
5330 		return (-TBADADDR);
5331 
5332 	/*
5333 	 * Interpret a zero destination to mean loopback.
5334 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
5335 	 * generate the T_CONN_CON.
5336 	 */
5337 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp))
5338 		*dstaddrp = ipv6_loopback;
5339 
5340 	/* Handle __sin6_src_id if socket not bound to an IP address */
5341 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6)) {
5342 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5343 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5344 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5345 	}
5346 
5347 	/*
5348 	 * Take care of the scope_id now.
5349 	 */
5350 	if (scope_id != 0 && IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
5351 		connp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
5352 		connp->conn_ixa->ixa_scopeid = scope_id;
5353 	} else {
5354 		connp->conn_ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
5355 	}
5356 
5357 	connp->conn_flowinfo = flowinfo;
5358 	connp->conn_faddr_v6 = *dstaddrp;
5359 	connp->conn_fport = dstport;
5360 
5361 	/*
5362 	 * At this point the remote destination address and remote port fields
5363 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5364 	 * have to see which state tcp was in so we can take appropriate action.
5365 	 */
5366 	if (tcp->tcp_state == TCPS_IDLE) {
5367 		/*
5368 		 * We support a quick connect capability here, allowing
5369 		 * clients to transition directly from IDLE to SYN_SENT
5370 		 * tcp_bindi will pick an unused port, insert the connection
5371 		 * in the bind hash and transition to BOUND state.
5372 		 */
5373 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5374 		    tcp, B_TRUE);
5375 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5376 		    B_FALSE, B_FALSE);
5377 		if (lport == 0)
5378 			return (-TNOADDR);
5379 	}
5380 
5381 	/*
5382 	 * Lookup the route to determine a source address and the uinfo.
5383 	 * Setup TCP parameters based on the metrics/DCE.
5384 	 */
5385 	error = tcp_set_destination(tcp);
5386 	if (error != 0)
5387 		return (error);
5388 
5389 	/*
5390 	 * Don't let an endpoint connect to itself.
5391 	 */
5392 	if (IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6, &connp->conn_laddr_v6) &&
5393 	    connp->conn_fport == connp->conn_lport)
5394 		return (-TBADADDR);
5395 
5396 	tcp->tcp_state = TCPS_SYN_SENT;
5397 
5398 	return (ipcl_conn_insert_v6(connp));
5399 }
5400 
5401 /*
5402  * Disconnect
5403  * Note that unlike other functions this returns a positive tli error
5404  * when it fails; it never returns an errno.
5405  */
5406 static int
5407 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
5408 {
5409 	conn_t		*lconnp;
5410 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5411 	conn_t		*connp = tcp->tcp_connp;
5412 
5413 	/*
5414 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
5415 	 * when the stream is in BOUND state. Do not send a reset,
5416 	 * since the destination IP address is not valid, and it can
5417 	 * be the initialized value of all zeros (broadcast address).
5418 	 */
5419 	if (tcp->tcp_state <= TCPS_BOUND) {
5420 		if (connp->conn_debug) {
5421 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
5422 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
5423 		}
5424 		return (TOUTSTATE);
5425 	}
5426 
5427 
5428 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
5429 
5430 		/*
5431 		 * According to TPI, for non-listeners, ignore seqnum
5432 		 * and disconnect.
5433 		 * Following interpretation of -1 seqnum is historical
5434 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
5435 		 * a valid seqnum should not be -1).
5436 		 *
5437 		 *	-1 means disconnect everything
5438 		 *	regardless even on a listener.
5439 		 */
5440 
5441 		int old_state = tcp->tcp_state;
5442 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
5443 
5444 		/*
5445 		 * The connection can't be on the tcp_time_wait_head list
5446 		 * since it is not detached.
5447 		 */
5448 		ASSERT(tcp->tcp_time_wait_next == NULL);
5449 		ASSERT(tcp->tcp_time_wait_prev == NULL);
5450 		ASSERT(tcp->tcp_time_wait_expire == 0);
5451 		/*
5452 		 * If it used to be a listener, check to make sure no one else
5453 		 * has taken the port before switching back to LISTEN state.
5454 		 */
5455 		if (connp->conn_ipversion == IPV4_VERSION) {
5456 			lconnp = ipcl_lookup_listener_v4(connp->conn_lport,
5457 			    connp->conn_laddr_v4, IPCL_ZONEID(connp), ipst);
5458 		} else {
5459 			uint_t ifindex = 0;
5460 
5461 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)
5462 				ifindex = connp->conn_ixa->ixa_scopeid;
5463 
5464 			/* Allow conn_bound_if listeners? */
5465 			lconnp = ipcl_lookup_listener_v6(connp->conn_lport,
5466 			    &connp->conn_laddr_v6, ifindex, IPCL_ZONEID(connp),
5467 			    ipst);
5468 		}
5469 		if (tcp->tcp_conn_req_max && lconnp == NULL) {
5470 			tcp->tcp_state = TCPS_LISTEN;
5471 		} else if (old_state > TCPS_BOUND) {
5472 			tcp->tcp_conn_req_max = 0;
5473 			tcp->tcp_state = TCPS_BOUND;
5474 		}
5475 		if (lconnp != NULL)
5476 			CONN_DEC_REF(lconnp);
5477 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
5478 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
5479 		} else if (old_state == TCPS_ESTABLISHED ||
5480 		    old_state == TCPS_CLOSE_WAIT) {
5481 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
5482 		}
5483 
5484 		if (tcp->tcp_fused)
5485 			tcp_unfuse(tcp);
5486 
5487 		mutex_enter(&tcp->tcp_eager_lock);
5488 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
5489 		    (tcp->tcp_conn_req_cnt_q != 0)) {
5490 			tcp_eager_cleanup(tcp, 0);
5491 		}
5492 		mutex_exit(&tcp->tcp_eager_lock);
5493 
5494 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
5495 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
5496 
5497 		tcp_reinit(tcp);
5498 
5499 		return (0);
5500 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
5501 		return (TBADSEQ);
5502 	}
5503 	return (0);
5504 }
5505 
5506 /*
5507  * Our client hereby directs us to reject the connection request
5508  * that tcp_input_listener() marked with 'seqnum'.  Rejection consists
5509  * of sending the appropriate RST, not an ICMP error.
5510  */
5511 static void
5512 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
5513 {
5514 	t_scalar_t seqnum;
5515 	int	error;
5516 	conn_t	*connp = tcp->tcp_connp;
5517 
5518 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5519 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
5520 		tcp_err_ack(tcp, mp, TPROTO, 0);
5521 		return;
5522 	}
5523 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
5524 	error = tcp_disconnect_common(tcp, seqnum);
5525 	if (error != 0)
5526 		tcp_err_ack(tcp, mp, error, 0);
5527 	else {
5528 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
5529 			/* Send M_FLUSH according to TPI */
5530 			(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
5531 		}
5532 		mp = mi_tpi_ok_ack_alloc(mp);
5533 		if (mp != NULL)
5534 			putnext(connp->conn_rq, mp);
5535 	}
5536 }
5537 
5538 /*
5539  * Diagnostic routine used to return a string associated with the tcp state.
5540  * Note that if the caller does not supply a buffer, it will use an internal
5541  * static string.  This means that if multiple threads call this function at
5542  * the same time, output can be corrupted...  Note also that this function
5543  * does not check the size of the supplied buffer.  The caller has to make
5544  * sure that it is big enough.
5545  */
5546 static char *
5547 tcp_display(tcp_t *tcp, char *sup_buf, char format)
5548 {
5549 	char		buf1[30];
5550 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
5551 	char		*buf;
5552 	char		*cp;
5553 	in6_addr_t	local, remote;
5554 	char		local_addrbuf[INET6_ADDRSTRLEN];
5555 	char		remote_addrbuf[INET6_ADDRSTRLEN];
5556 	conn_t		*connp;
5557 
5558 	if (sup_buf != NULL)
5559 		buf = sup_buf;
5560 	else
5561 		buf = priv_buf;
5562 
5563 	if (tcp == NULL)
5564 		return ("NULL_TCP");
5565 
5566 	connp = tcp->tcp_connp;
5567 	switch (tcp->tcp_state) {
5568 	case TCPS_CLOSED:
5569 		cp = "TCP_CLOSED";
5570 		break;
5571 	case TCPS_IDLE:
5572 		cp = "TCP_IDLE";
5573 		break;
5574 	case TCPS_BOUND:
5575 		cp = "TCP_BOUND";
5576 		break;
5577 	case TCPS_LISTEN:
5578 		cp = "TCP_LISTEN";
5579 		break;
5580 	case TCPS_SYN_SENT:
5581 		cp = "TCP_SYN_SENT";
5582 		break;
5583 	case TCPS_SYN_RCVD:
5584 		cp = "TCP_SYN_RCVD";
5585 		break;
5586 	case TCPS_ESTABLISHED:
5587 		cp = "TCP_ESTABLISHED";
5588 		break;
5589 	case TCPS_CLOSE_WAIT:
5590 		cp = "TCP_CLOSE_WAIT";
5591 		break;
5592 	case TCPS_FIN_WAIT_1:
5593 		cp = "TCP_FIN_WAIT_1";
5594 		break;
5595 	case TCPS_CLOSING:
5596 		cp = "TCP_CLOSING";
5597 		break;
5598 	case TCPS_LAST_ACK:
5599 		cp = "TCP_LAST_ACK";
5600 		break;
5601 	case TCPS_FIN_WAIT_2:
5602 		cp = "TCP_FIN_WAIT_2";
5603 		break;
5604 	case TCPS_TIME_WAIT:
5605 		cp = "TCP_TIME_WAIT";
5606 		break;
5607 	default:
5608 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
5609 		cp = buf1;
5610 		break;
5611 	}
5612 	switch (format) {
5613 	case DISP_ADDR_AND_PORT:
5614 		if (connp->conn_ipversion == IPV4_VERSION) {
5615 			/*
5616 			 * Note that we use the remote address in the tcp_b
5617 			 * structure.  This means that it will print out
5618 			 * the real destination address, not the next hop's
5619 			 * address if source routing is used.
5620 			 */
5621 			IN6_IPADDR_TO_V4MAPPED(connp->conn_laddr_v4, &local);
5622 			IN6_IPADDR_TO_V4MAPPED(connp->conn_faddr_v4, &remote);
5623 
5624 		} else {
5625 			local = connp->conn_laddr_v6;
5626 			remote = connp->conn_faddr_v6;
5627 		}
5628 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
5629 		    sizeof (local_addrbuf));
5630 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
5631 		    sizeof (remote_addrbuf));
5632 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
5633 		    local_addrbuf, ntohs(connp->conn_lport), remote_addrbuf,
5634 		    ntohs(connp->conn_fport), cp);
5635 		break;
5636 	case DISP_PORT_ONLY:
5637 	default:
5638 		(void) mi_sprintf(buf, "[%u, %u] %s",
5639 		    ntohs(connp->conn_lport), ntohs(connp->conn_fport), cp);
5640 		break;
5641 	}
5642 
5643 	return (buf);
5644 }
5645 
5646 /*
5647  * Called via squeue to get on to eager's perimeter. It sends a
5648  * TH_RST if eager is in the fanout table. The listener wants the
5649  * eager to disappear either by means of tcp_eager_blowoff() or
5650  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
5651  * called (via squeue) if the eager cannot be inserted in the
5652  * fanout table in tcp_input_listener().
5653  */
5654 /* ARGSUSED */
5655 void
5656 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5657 {
5658 	conn_t	*econnp = (conn_t *)arg;
5659 	tcp_t	*eager = econnp->conn_tcp;
5660 	tcp_t	*listener = eager->tcp_listener;
5661 
5662 	/*
5663 	 * We could be called because listener is closing. Since
5664 	 * the eager was using listener's queue's, we avoid
5665 	 * using the listeners queues from now on.
5666 	 */
5667 	ASSERT(eager->tcp_detached);
5668 	econnp->conn_rq = NULL;
5669 	econnp->conn_wq = NULL;
5670 
5671 	/*
5672 	 * An eager's conn_fanout will be NULL if it's a duplicate
5673 	 * for an existing 4-tuples in the conn fanout table.
5674 	 * We don't want to send an RST out in such case.
5675 	 */
5676 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
5677 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
5678 		    eager, eager->tcp_snxt, 0, TH_RST);
5679 	}
5680 
5681 	/* We are here because listener wants this eager gone */
5682 	if (listener != NULL) {
5683 		mutex_enter(&listener->tcp_eager_lock);
5684 		tcp_eager_unlink(eager);
5685 		if (eager->tcp_tconnind_started) {
5686 			/*
5687 			 * The eager has sent a conn_ind up to the
5688 			 * listener but listener decides to close
5689 			 * instead. We need to drop the extra ref
5690 			 * placed on eager in tcp_input_data() before
5691 			 * sending the conn_ind to listener.
5692 			 */
5693 			CONN_DEC_REF(econnp);
5694 		}
5695 		mutex_exit(&listener->tcp_eager_lock);
5696 		CONN_DEC_REF(listener->tcp_connp);
5697 	}
5698 
5699 	if (eager->tcp_state != TCPS_CLOSED)
5700 		tcp_close_detached(eager);
5701 }
5702 
5703 /*
5704  * Reset any eager connection hanging off this listener marked
5705  * with 'seqnum' and then reclaim it's resources.
5706  */
5707 static boolean_t
5708 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
5709 {
5710 	tcp_t	*eager;
5711 	mblk_t 	*mp;
5712 	tcp_stack_t	*tcps = listener->tcp_tcps;
5713 
5714 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
5715 	eager = listener;
5716 	mutex_enter(&listener->tcp_eager_lock);
5717 	do {
5718 		eager = eager->tcp_eager_next_q;
5719 		if (eager == NULL) {
5720 			mutex_exit(&listener->tcp_eager_lock);
5721 			return (B_FALSE);
5722 		}
5723 	} while (eager->tcp_conn_req_seqnum != seqnum);
5724 
5725 	if (eager->tcp_closemp_used) {
5726 		mutex_exit(&listener->tcp_eager_lock);
5727 		return (B_TRUE);
5728 	}
5729 	eager->tcp_closemp_used = B_TRUE;
5730 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5731 	CONN_INC_REF(eager->tcp_connp);
5732 	mutex_exit(&listener->tcp_eager_lock);
5733 	mp = &eager->tcp_closemp;
5734 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
5735 	    eager->tcp_connp, NULL, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
5736 	return (B_TRUE);
5737 }
5738 
5739 /*
5740  * Reset any eager connection hanging off this listener
5741  * and then reclaim it's resources.
5742  */
5743 static void
5744 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
5745 {
5746 	tcp_t	*eager;
5747 	mblk_t	*mp;
5748 	tcp_stack_t	*tcps = listener->tcp_tcps;
5749 
5750 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
5751 
5752 	if (!q0_only) {
5753 		/* First cleanup q */
5754 		TCP_STAT(tcps, tcp_eager_blowoff_q);
5755 		eager = listener->tcp_eager_next_q;
5756 		while (eager != NULL) {
5757 			if (!eager->tcp_closemp_used) {
5758 				eager->tcp_closemp_used = B_TRUE;
5759 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5760 				CONN_INC_REF(eager->tcp_connp);
5761 				mp = &eager->tcp_closemp;
5762 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
5763 				    tcp_eager_kill, eager->tcp_connp, NULL,
5764 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
5765 			}
5766 			eager = eager->tcp_eager_next_q;
5767 		}
5768 	}
5769 	/* Then cleanup q0 */
5770 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
5771 	eager = listener->tcp_eager_next_q0;
5772 	while (eager != listener) {
5773 		if (!eager->tcp_closemp_used) {
5774 			eager->tcp_closemp_used = B_TRUE;
5775 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5776 			CONN_INC_REF(eager->tcp_connp);
5777 			mp = &eager->tcp_closemp;
5778 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
5779 			    tcp_eager_kill, eager->tcp_connp, NULL, SQ_FILL,
5780 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
5781 		}
5782 		eager = eager->tcp_eager_next_q0;
5783 	}
5784 }
5785 
5786 /*
5787  * If we are an eager connection hanging off a listener that hasn't
5788  * formally accepted the connection yet, get off his list and blow off
5789  * any data that we have accumulated.
5790  */
5791 static void
5792 tcp_eager_unlink(tcp_t *tcp)
5793 {
5794 	tcp_t	*listener = tcp->tcp_listener;
5795 
5796 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
5797 	ASSERT(listener != NULL);
5798 	if (tcp->tcp_eager_next_q0 != NULL) {
5799 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
5800 
5801 		/* Remove the eager tcp from q0 */
5802 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
5803 		    tcp->tcp_eager_prev_q0;
5804 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
5805 		    tcp->tcp_eager_next_q0;
5806 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
5807 		listener->tcp_conn_req_cnt_q0--;
5808 
5809 		tcp->tcp_eager_next_q0 = NULL;
5810 		tcp->tcp_eager_prev_q0 = NULL;
5811 
5812 		/*
5813 		 * Take the eager out, if it is in the list of droppable
5814 		 * eagers.
5815 		 */
5816 		MAKE_UNDROPPABLE(tcp);
5817 
5818 		if (tcp->tcp_syn_rcvd_timeout != 0) {
5819 			/* we have timed out before */
5820 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
5821 			listener->tcp_syn_rcvd_timeout--;
5822 		}
5823 	} else {
5824 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
5825 		tcp_t	*prev = NULL;
5826 
5827 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
5828 			if (tcpp[0] == tcp) {
5829 				if (listener->tcp_eager_last_q == tcp) {
5830 					/*
5831 					 * If we are unlinking the last
5832 					 * element on the list, adjust
5833 					 * tail pointer. Set tail pointer
5834 					 * to nil when list is empty.
5835 					 */
5836 					ASSERT(tcp->tcp_eager_next_q == NULL);
5837 					if (listener->tcp_eager_last_q ==
5838 					    listener->tcp_eager_next_q) {
5839 						listener->tcp_eager_last_q =
5840 						    NULL;
5841 					} else {
5842 						/*
5843 						 * We won't get here if there
5844 						 * is only one eager in the
5845 						 * list.
5846 						 */
5847 						ASSERT(prev != NULL);
5848 						listener->tcp_eager_last_q =
5849 						    prev;
5850 					}
5851 				}
5852 				tcpp[0] = tcp->tcp_eager_next_q;
5853 				tcp->tcp_eager_next_q = NULL;
5854 				tcp->tcp_eager_last_q = NULL;
5855 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
5856 				listener->tcp_conn_req_cnt_q--;
5857 				break;
5858 			}
5859 			prev = tcpp[0];
5860 		}
5861 	}
5862 	tcp->tcp_listener = NULL;
5863 }
5864 
5865 /* Shorthand to generate and send TPI error acks to our client */
5866 static void
5867 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
5868 {
5869 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
5870 		putnext(tcp->tcp_connp->conn_rq, mp);
5871 }
5872 
5873 /* Shorthand to generate and send TPI error acks to our client */
5874 static void
5875 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
5876     int t_error, int sys_error)
5877 {
5878 	struct T_error_ack	*teackp;
5879 
5880 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
5881 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
5882 		teackp = (struct T_error_ack *)mp->b_rptr;
5883 		teackp->ERROR_prim = primitive;
5884 		teackp->TLI_error = t_error;
5885 		teackp->UNIX_error = sys_error;
5886 		putnext(tcp->tcp_connp->conn_rq, mp);
5887 	}
5888 }
5889 
5890 /*
5891  * Note: No locks are held when inspecting tcp_g_*epriv_ports
5892  * but instead the code relies on:
5893  * - the fact that the address of the array and its size never changes
5894  * - the atomic assignment of the elements of the array
5895  */
5896 /* ARGSUSED */
5897 static int
5898 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
5899 {
5900 	int i;
5901 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
5902 
5903 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
5904 		if (tcps->tcps_g_epriv_ports[i] != 0)
5905 			(void) mi_mpprintf(mp, "%d ",
5906 			    tcps->tcps_g_epriv_ports[i]);
5907 	}
5908 	return (0);
5909 }
5910 
5911 /*
5912  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
5913  * threads from changing it at the same time.
5914  */
5915 /* ARGSUSED */
5916 static int
5917 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
5918     cred_t *cr)
5919 {
5920 	long	new_value;
5921 	int	i;
5922 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
5923 
5924 	/*
5925 	 * Fail the request if the new value does not lie within the
5926 	 * port number limits.
5927 	 */
5928 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
5929 	    new_value <= 0 || new_value >= 65536) {
5930 		return (EINVAL);
5931 	}
5932 
5933 	mutex_enter(&tcps->tcps_epriv_port_lock);
5934 	/* Check if the value is already in the list */
5935 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
5936 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
5937 			mutex_exit(&tcps->tcps_epriv_port_lock);
5938 			return (EEXIST);
5939 		}
5940 	}
5941 	/* Find an empty slot */
5942 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
5943 		if (tcps->tcps_g_epriv_ports[i] == 0)
5944 			break;
5945 	}
5946 	if (i == tcps->tcps_g_num_epriv_ports) {
5947 		mutex_exit(&tcps->tcps_epriv_port_lock);
5948 		return (EOVERFLOW);
5949 	}
5950 	/* Set the new value */
5951 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
5952 	mutex_exit(&tcps->tcps_epriv_port_lock);
5953 	return (0);
5954 }
5955 
5956 /*
5957  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
5958  * threads from changing it at the same time.
5959  */
5960 /* ARGSUSED */
5961 static int
5962 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
5963     cred_t *cr)
5964 {
5965 	long	new_value;
5966 	int	i;
5967 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
5968 
5969 	/*
5970 	 * Fail the request if the new value does not lie within the
5971 	 * port number limits.
5972 	 */
5973 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
5974 	    new_value >= 65536) {
5975 		return (EINVAL);
5976 	}
5977 
5978 	mutex_enter(&tcps->tcps_epriv_port_lock);
5979 	/* Check that the value is already in the list */
5980 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
5981 		if (tcps->tcps_g_epriv_ports[i] == new_value)
5982 			break;
5983 	}
5984 	if (i == tcps->tcps_g_num_epriv_ports) {
5985 		mutex_exit(&tcps->tcps_epriv_port_lock);
5986 		return (ESRCH);
5987 	}
5988 	/* Clear the value */
5989 	tcps->tcps_g_epriv_ports[i] = 0;
5990 	mutex_exit(&tcps->tcps_epriv_port_lock);
5991 	return (0);
5992 }
5993 
5994 /* Return the TPI/TLI equivalent of our current tcp_state */
5995 static int
5996 tcp_tpistate(tcp_t *tcp)
5997 {
5998 	switch (tcp->tcp_state) {
5999 	case TCPS_IDLE:
6000 		return (TS_UNBND);
6001 	case TCPS_LISTEN:
6002 		/*
6003 		 * Return whether there are outstanding T_CONN_IND waiting
6004 		 * for the matching T_CONN_RES. Therefore don't count q0.
6005 		 */
6006 		if (tcp->tcp_conn_req_cnt_q > 0)
6007 			return (TS_WRES_CIND);
6008 		else
6009 			return (TS_IDLE);
6010 	case TCPS_BOUND:
6011 		return (TS_IDLE);
6012 	case TCPS_SYN_SENT:
6013 		return (TS_WCON_CREQ);
6014 	case TCPS_SYN_RCVD:
6015 		/*
6016 		 * Note: assumption: this has to the active open SYN_RCVD.
6017 		 * The passive instance is detached in SYN_RCVD stage of
6018 		 * incoming connection processing so we cannot get request
6019 		 * for T_info_ack on it.
6020 		 */
6021 		return (TS_WACK_CRES);
6022 	case TCPS_ESTABLISHED:
6023 		return (TS_DATA_XFER);
6024 	case TCPS_CLOSE_WAIT:
6025 		return (TS_WREQ_ORDREL);
6026 	case TCPS_FIN_WAIT_1:
6027 		return (TS_WIND_ORDREL);
6028 	case TCPS_FIN_WAIT_2:
6029 		return (TS_WIND_ORDREL);
6030 
6031 	case TCPS_CLOSING:
6032 	case TCPS_LAST_ACK:
6033 	case TCPS_TIME_WAIT:
6034 	case TCPS_CLOSED:
6035 		/*
6036 		 * Following TS_WACK_DREQ7 is a rendition of "not
6037 		 * yet TS_IDLE" TPI state. There is no best match to any
6038 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6039 		 * choose a value chosen that will map to TLI/XTI level
6040 		 * state of TSTATECHNG (state is process of changing) which
6041 		 * captures what this dummy state represents.
6042 		 */
6043 		return (TS_WACK_DREQ7);
6044 	default:
6045 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6046 		    tcp->tcp_state, tcp_display(tcp, NULL,
6047 		    DISP_PORT_ONLY));
6048 		return (TS_UNBND);
6049 	}
6050 }
6051 
6052 static void
6053 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6054 {
6055 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6056 	conn_t		*connp = tcp->tcp_connp;
6057 
6058 	if (connp->conn_family == AF_INET6)
6059 		*tia = tcp_g_t_info_ack_v6;
6060 	else
6061 		*tia = tcp_g_t_info_ack;
6062 	tia->CURRENT_state = tcp_tpistate(tcp);
6063 	tia->OPT_size = tcp_max_optsize;
6064 	if (tcp->tcp_mss == 0) {
6065 		/* Not yet set - tcp_open does not set mss */
6066 		if (connp->conn_ipversion == IPV4_VERSION)
6067 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
6068 		else
6069 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
6070 	} else {
6071 		tia->TIDU_size = tcp->tcp_mss;
6072 	}
6073 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6074 }
6075 
6076 static void
6077 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
6078     t_uscalar_t cap_bits1)
6079 {
6080 	tcap->CAP_bits1 = 0;
6081 
6082 	if (cap_bits1 & TC1_INFO) {
6083 		tcp_copy_info(&tcap->INFO_ack, tcp);
6084 		tcap->CAP_bits1 |= TC1_INFO;
6085 	}
6086 
6087 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6088 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6089 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6090 	}
6091 
6092 }
6093 
6094 /*
6095  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6096  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6097  * tcp_g_t_info_ack.  The current state of the stream is copied from
6098  * tcp_state.
6099  */
6100 static void
6101 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6102 {
6103 	t_uscalar_t		cap_bits1;
6104 	struct T_capability_ack	*tcap;
6105 
6106 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6107 		freemsg(mp);
6108 		return;
6109 	}
6110 
6111 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6112 
6113 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6114 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6115 	if (mp == NULL)
6116 		return;
6117 
6118 	tcap = (struct T_capability_ack *)mp->b_rptr;
6119 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
6120 
6121 	putnext(tcp->tcp_connp->conn_rq, mp);
6122 }
6123 
6124 /*
6125  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
6126  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
6127  * The current state of the stream is copied from tcp_state.
6128  */
6129 static void
6130 tcp_info_req(tcp_t *tcp, mblk_t *mp)
6131 {
6132 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
6133 	    T_INFO_ACK);
6134 	if (!mp) {
6135 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6136 		return;
6137 	}
6138 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
6139 	putnext(tcp->tcp_connp->conn_rq, mp);
6140 }
6141 
6142 /* Respond to the TPI addr request */
6143 static void
6144 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
6145 {
6146 	struct sockaddr *sa;
6147 	mblk_t	*ackmp;
6148 	struct T_addr_ack *taa;
6149 	conn_t	*connp = tcp->tcp_connp;
6150 	uint_t	addrlen;
6151 
6152 	/* Make it large enough for worst case */
6153 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
6154 	    2 * sizeof (sin6_t), 1);
6155 	if (ackmp == NULL) {
6156 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6157 		return;
6158 	}
6159 
6160 	taa = (struct T_addr_ack *)ackmp->b_rptr;
6161 
6162 	bzero(taa, sizeof (struct T_addr_ack));
6163 	ackmp->b_wptr = (uchar_t *)&taa[1];
6164 
6165 	taa->PRIM_type = T_ADDR_ACK;
6166 	ackmp->b_datap->db_type = M_PCPROTO;
6167 
6168 	if (connp->conn_family == AF_INET)
6169 		addrlen = sizeof (sin_t);
6170 	else
6171 		addrlen = sizeof (sin6_t);
6172 
6173 	/*
6174 	 * Note: Following code assumes 32 bit alignment of basic
6175 	 * data structures like sin_t and struct T_addr_ack.
6176 	 */
6177 	if (tcp->tcp_state >= TCPS_BOUND) {
6178 		/*
6179 		 * Fill in local address first
6180 		 */
6181 		taa->LOCADDR_offset = sizeof (*taa);
6182 		taa->LOCADDR_length = addrlen;
6183 		sa = (struct sockaddr *)&taa[1];
6184 		(void) conn_getsockname(connp, sa, &addrlen);
6185 		ackmp->b_wptr += addrlen;
6186 	}
6187 	if (tcp->tcp_state >= TCPS_SYN_RCVD) {
6188 		/*
6189 		 * Fill in Remote address
6190 		 */
6191 		taa->REMADDR_length = addrlen;
6192 		/* assumed 32-bit alignment */
6193 		taa->REMADDR_offset = taa->LOCADDR_offset + taa->LOCADDR_length;
6194 		sa = (struct sockaddr *)(ackmp->b_rptr + taa->REMADDR_offset);
6195 		(void) conn_getpeername(connp, sa, &addrlen);
6196 		ackmp->b_wptr += addrlen;
6197 	}
6198 	ASSERT(ackmp->b_wptr <= ackmp->b_datap->db_lim);
6199 	putnext(tcp->tcp_connp->conn_rq, ackmp);
6200 }
6201 
6202 /*
6203  * Handle reinitialization of a tcp structure.
6204  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
6205  */
6206 static void
6207 tcp_reinit(tcp_t *tcp)
6208 {
6209 	mblk_t		*mp;
6210 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6211 	conn_t		*connp  = tcp->tcp_connp;
6212 
6213 	TCP_STAT(tcps, tcp_reinit_calls);
6214 
6215 	/* tcp_reinit should never be called for detached tcp_t's */
6216 	ASSERT(tcp->tcp_listener == NULL);
6217 	ASSERT((connp->conn_family == AF_INET &&
6218 	    connp->conn_ipversion == IPV4_VERSION) ||
6219 	    (connp->conn_family == AF_INET6 &&
6220 	    (connp->conn_ipversion == IPV4_VERSION ||
6221 	    connp->conn_ipversion == IPV6_VERSION)));
6222 
6223 	/* Cancel outstanding timers */
6224 	tcp_timers_stop(tcp);
6225 
6226 	/*
6227 	 * Reset everything in the state vector, after updating global
6228 	 * MIB data from instance counters.
6229 	 */
6230 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
6231 	tcp->tcp_ibsegs = 0;
6232 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
6233 	tcp->tcp_obsegs = 0;
6234 
6235 	tcp_close_mpp(&tcp->tcp_xmit_head);
6236 	if (tcp->tcp_snd_zcopy_aware)
6237 		tcp_zcopy_notify(tcp);
6238 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
6239 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
6240 	mutex_enter(&tcp->tcp_non_sq_lock);
6241 	if (tcp->tcp_flow_stopped &&
6242 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
6243 		tcp_clrqfull(tcp);
6244 	}
6245 	mutex_exit(&tcp->tcp_non_sq_lock);
6246 	tcp_close_mpp(&tcp->tcp_reass_head);
6247 	tcp->tcp_reass_tail = NULL;
6248 	if (tcp->tcp_rcv_list != NULL) {
6249 		/* Free b_next chain */
6250 		tcp_close_mpp(&tcp->tcp_rcv_list);
6251 		tcp->tcp_rcv_last_head = NULL;
6252 		tcp->tcp_rcv_last_tail = NULL;
6253 		tcp->tcp_rcv_cnt = 0;
6254 	}
6255 	tcp->tcp_rcv_last_tail = NULL;
6256 
6257 	if ((mp = tcp->tcp_urp_mp) != NULL) {
6258 		freemsg(mp);
6259 		tcp->tcp_urp_mp = NULL;
6260 	}
6261 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
6262 		freemsg(mp);
6263 		tcp->tcp_urp_mark_mp = NULL;
6264 	}
6265 	if (tcp->tcp_fused_sigurg_mp != NULL) {
6266 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6267 		freeb(tcp->tcp_fused_sigurg_mp);
6268 		tcp->tcp_fused_sigurg_mp = NULL;
6269 	}
6270 	if (tcp->tcp_ordrel_mp != NULL) {
6271 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6272 		freeb(tcp->tcp_ordrel_mp);
6273 		tcp->tcp_ordrel_mp = NULL;
6274 	}
6275 
6276 	/*
6277 	 * Following is a union with two members which are
6278 	 * identical types and size so the following cleanup
6279 	 * is enough.
6280 	 */
6281 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
6282 
6283 	CL_INET_DISCONNECT(connp);
6284 
6285 	/*
6286 	 * The connection can't be on the tcp_time_wait_head list
6287 	 * since it is not detached.
6288 	 */
6289 	ASSERT(tcp->tcp_time_wait_next == NULL);
6290 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6291 	ASSERT(tcp->tcp_time_wait_expire == 0);
6292 
6293 	if (tcp->tcp_kssl_pending) {
6294 		tcp->tcp_kssl_pending = B_FALSE;
6295 
6296 		/* Don't reset if the initialized by bind. */
6297 		if (tcp->tcp_kssl_ent != NULL) {
6298 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
6299 			    KSSL_NO_PROXY);
6300 		}
6301 	}
6302 	if (tcp->tcp_kssl_ctx != NULL) {
6303 		kssl_release_ctx(tcp->tcp_kssl_ctx);
6304 		tcp->tcp_kssl_ctx = NULL;
6305 	}
6306 
6307 	/*
6308 	 * Reset/preserve other values
6309 	 */
6310 	tcp_reinit_values(tcp);
6311 	ipcl_hash_remove(connp);
6312 	ixa_cleanup(connp->conn_ixa);
6313 	tcp_ipsec_cleanup(tcp);
6314 
6315 	connp->conn_laddr_v6 = connp->conn_bound_addr_v6;
6316 	connp->conn_saddr_v6 = connp->conn_bound_addr_v6;
6317 
6318 	if (tcp->tcp_conn_req_max != 0) {
6319 		/*
6320 		 * This is the case when a TLI program uses the same
6321 		 * transport end point to accept a connection.  This
6322 		 * makes the TCP both a listener and acceptor.  When
6323 		 * this connection is closed, we need to set the state
6324 		 * back to TCPS_LISTEN.  Make sure that the eager list
6325 		 * is reinitialized.
6326 		 *
6327 		 * Note that this stream is still bound to the four
6328 		 * tuples of the previous connection in IP.  If a new
6329 		 * SYN with different foreign address comes in, IP will
6330 		 * not find it and will send it to the global queue.  In
6331 		 * the global queue, TCP will do a tcp_lookup_listener()
6332 		 * to find this stream.  This works because this stream
6333 		 * is only removed from connected hash.
6334 		 *
6335 		 */
6336 		tcp->tcp_state = TCPS_LISTEN;
6337 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
6338 		tcp->tcp_eager_next_drop_q0 = tcp;
6339 		tcp->tcp_eager_prev_drop_q0 = tcp;
6340 		/*
6341 		 * Initially set conn_recv to tcp_input_listener_unbound to try
6342 		 * to pick a good squeue for the listener when the first SYN
6343 		 * arrives. tcp_input_listener_unbound sets it to
6344 		 * tcp_input_listener on that first SYN.
6345 		 */
6346 		connp->conn_recv = tcp_input_listener_unbound;
6347 
6348 		connp->conn_proto = IPPROTO_TCP;
6349 		connp->conn_faddr_v6 = ipv6_all_zeros;
6350 		connp->conn_fport = 0;
6351 
6352 		(void) ipcl_bind_insert(connp);
6353 	} else {
6354 		tcp->tcp_state = TCPS_BOUND;
6355 	}
6356 
6357 	/*
6358 	 * Initialize to default values
6359 	 */
6360 	tcp_init_values(tcp);
6361 
6362 	ASSERT(tcp->tcp_ptpbhn != NULL);
6363 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6364 	tcp->tcp_mss = connp->conn_ipversion != IPV4_VERSION ?
6365 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
6366 }
6367 
6368 /*
6369  * Force values to zero that need be zero.
6370  * Do not touch values asociated with the BOUND or LISTEN state
6371  * since the connection will end up in that state after the reinit.
6372  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
6373  * structure!
6374  */
6375 static void
6376 tcp_reinit_values(tcp)
6377 	tcp_t *tcp;
6378 {
6379 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6380 	conn_t		*connp = tcp->tcp_connp;
6381 
6382 #ifndef	lint
6383 #define	DONTCARE(x)
6384 #define	PRESERVE(x)
6385 #else
6386 #define	DONTCARE(x)	((x) = (x))
6387 #define	PRESERVE(x)	((x) = (x))
6388 #endif	/* lint */
6389 
6390 	PRESERVE(tcp->tcp_bind_hash_port);
6391 	PRESERVE(tcp->tcp_bind_hash);
6392 	PRESERVE(tcp->tcp_ptpbhn);
6393 	PRESERVE(tcp->tcp_acceptor_hash);
6394 	PRESERVE(tcp->tcp_ptpahn);
6395 
6396 	/* Should be ASSERT NULL on these with new code! */
6397 	ASSERT(tcp->tcp_time_wait_next == NULL);
6398 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6399 	ASSERT(tcp->tcp_time_wait_expire == 0);
6400 	PRESERVE(tcp->tcp_state);
6401 	PRESERVE(connp->conn_rq);
6402 	PRESERVE(connp->conn_wq);
6403 
6404 	ASSERT(tcp->tcp_xmit_head == NULL);
6405 	ASSERT(tcp->tcp_xmit_last == NULL);
6406 	ASSERT(tcp->tcp_unsent == 0);
6407 	ASSERT(tcp->tcp_xmit_tail == NULL);
6408 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
6409 
6410 	tcp->tcp_snxt = 0;			/* Displayed in mib */
6411 	tcp->tcp_suna = 0;			/* Displayed in mib */
6412 	tcp->tcp_swnd = 0;
6413 	DONTCARE(tcp->tcp_cwnd);	/* Init in tcp_process_options */
6414 
6415 	ASSERT(tcp->tcp_ibsegs == 0);
6416 	ASSERT(tcp->tcp_obsegs == 0);
6417 
6418 	if (connp->conn_ht_iphc != NULL) {
6419 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
6420 		connp->conn_ht_iphc = NULL;
6421 		connp->conn_ht_iphc_allocated = 0;
6422 		connp->conn_ht_iphc_len = 0;
6423 		connp->conn_ht_ulp = NULL;
6424 		connp->conn_ht_ulp_len = 0;
6425 		tcp->tcp_ipha = NULL;
6426 		tcp->tcp_ip6h = NULL;
6427 		tcp->tcp_tcpha = NULL;
6428 	}
6429 
6430 	/* We clear any IP_OPTIONS and extension headers */
6431 	ip_pkt_free(&connp->conn_xmit_ipp);
6432 
6433 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
6434 	DONTCARE(tcp->tcp_ipha);
6435 	DONTCARE(tcp->tcp_ip6h);
6436 	DONTCARE(tcp->tcp_tcpha);
6437 	tcp->tcp_valid_bits = 0;
6438 
6439 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
6440 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
6441 	tcp->tcp_last_rcv_lbolt = 0;
6442 
6443 	tcp->tcp_init_cwnd = 0;
6444 
6445 	tcp->tcp_urp_last_valid = 0;
6446 	tcp->tcp_hard_binding = 0;
6447 
6448 	tcp->tcp_fin_acked = 0;
6449 	tcp->tcp_fin_rcvd = 0;
6450 	tcp->tcp_fin_sent = 0;
6451 	tcp->tcp_ordrel_done = 0;
6452 
6453 	tcp->tcp_detached = 0;
6454 
6455 	tcp->tcp_snd_ws_ok = B_FALSE;
6456 	tcp->tcp_snd_ts_ok = B_FALSE;
6457 	tcp->tcp_zero_win_probe = 0;
6458 
6459 	tcp->tcp_loopback = 0;
6460 	tcp->tcp_localnet = 0;
6461 	tcp->tcp_syn_defense = 0;
6462 	tcp->tcp_set_timer = 0;
6463 
6464 	tcp->tcp_active_open = 0;
6465 	tcp->tcp_rexmit = B_FALSE;
6466 	tcp->tcp_xmit_zc_clean = B_FALSE;
6467 
6468 	tcp->tcp_snd_sack_ok = B_FALSE;
6469 	tcp->tcp_hwcksum = B_FALSE;
6470 
6471 	DONTCARE(tcp->tcp_maxpsz_multiplier);	/* Init in tcp_init_values */
6472 
6473 	tcp->tcp_conn_def_q0 = 0;
6474 	tcp->tcp_ip_forward_progress = B_FALSE;
6475 	tcp->tcp_ecn_ok = B_FALSE;
6476 
6477 	tcp->tcp_cwr = B_FALSE;
6478 	tcp->tcp_ecn_echo_on = B_FALSE;
6479 	tcp->tcp_is_wnd_shrnk = B_FALSE;
6480 
6481 	if (tcp->tcp_sack_info != NULL) {
6482 		if (tcp->tcp_notsack_list != NULL) {
6483 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
6484 			    tcp);
6485 		}
6486 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
6487 		tcp->tcp_sack_info = NULL;
6488 	}
6489 
6490 	tcp->tcp_rcv_ws = 0;
6491 	tcp->tcp_snd_ws = 0;
6492 	tcp->tcp_ts_recent = 0;
6493 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
6494 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
6495 	tcp->tcp_initial_pmtu = 0;
6496 
6497 	ASSERT(tcp->tcp_reass_head == NULL);
6498 	ASSERT(tcp->tcp_reass_tail == NULL);
6499 
6500 	tcp->tcp_cwnd_cnt = 0;
6501 
6502 	ASSERT(tcp->tcp_rcv_list == NULL);
6503 	ASSERT(tcp->tcp_rcv_last_head == NULL);
6504 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
6505 	ASSERT(tcp->tcp_rcv_cnt == 0);
6506 
6507 	DONTCARE(tcp->tcp_cwnd_ssthresh); /* Init in tcp_set_destination */
6508 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
6509 	tcp->tcp_csuna = 0;
6510 
6511 	tcp->tcp_rto = 0;			/* Displayed in MIB */
6512 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
6513 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
6514 	tcp->tcp_rtt_update = 0;
6515 
6516 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6517 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6518 
6519 	tcp->tcp_rack = 0;			/* Displayed in mib */
6520 	tcp->tcp_rack_cnt = 0;
6521 	tcp->tcp_rack_cur_max = 0;
6522 	tcp->tcp_rack_abs_max = 0;
6523 
6524 	tcp->tcp_max_swnd = 0;
6525 
6526 	ASSERT(tcp->tcp_listener == NULL);
6527 
6528 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
6529 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
6530 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
6531 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
6532 
6533 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
6534 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
6535 	PRESERVE(tcp->tcp_conn_req_max);
6536 	PRESERVE(tcp->tcp_conn_req_seqnum);
6537 
6538 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
6539 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
6540 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
6541 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
6542 
6543 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
6544 	ASSERT(tcp->tcp_urp_mp == NULL);
6545 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
6546 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
6547 
6548 	ASSERT(tcp->tcp_eager_next_q == NULL);
6549 	ASSERT(tcp->tcp_eager_last_q == NULL);
6550 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
6551 	    tcp->tcp_eager_prev_q0 == NULL) ||
6552 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
6553 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
6554 
6555 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
6556 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
6557 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
6558 
6559 	tcp->tcp_client_errno = 0;
6560 
6561 	DONTCARE(connp->conn_sum);		/* Init in tcp_init_values */
6562 
6563 	connp->conn_faddr_v6 = ipv6_all_zeros;	/* Displayed in MIB */
6564 
6565 	PRESERVE(connp->conn_bound_addr_v6);
6566 	tcp->tcp_last_sent_len = 0;
6567 	tcp->tcp_dupack_cnt = 0;
6568 
6569 	connp->conn_fport = 0;			/* Displayed in MIB */
6570 	PRESERVE(connp->conn_lport);
6571 
6572 	PRESERVE(tcp->tcp_acceptor_lockp);
6573 
6574 	ASSERT(tcp->tcp_ordrel_mp == NULL);
6575 	PRESERVE(tcp->tcp_acceptor_id);
6576 	DONTCARE(tcp->tcp_ipsec_overhead);
6577 
6578 	PRESERVE(connp->conn_family);
6579 	/* Remove any remnants of mapped address binding */
6580 	if (connp->conn_family == AF_INET6) {
6581 		connp->conn_ipversion = IPV6_VERSION;
6582 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
6583 	} else {
6584 		connp->conn_ipversion = IPV4_VERSION;
6585 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
6586 	}
6587 
6588 	connp->conn_bound_if = 0;
6589 	connp->conn_recv_ancillary.crb_all = 0;
6590 	tcp->tcp_recvifindex = 0;
6591 	tcp->tcp_recvhops = 0;
6592 	tcp->tcp_closed = 0;
6593 	tcp->tcp_cleandeathtag = 0;
6594 	if (tcp->tcp_hopopts != NULL) {
6595 		mi_free(tcp->tcp_hopopts);
6596 		tcp->tcp_hopopts = NULL;
6597 		tcp->tcp_hopoptslen = 0;
6598 	}
6599 	ASSERT(tcp->tcp_hopoptslen == 0);
6600 	if (tcp->tcp_dstopts != NULL) {
6601 		mi_free(tcp->tcp_dstopts);
6602 		tcp->tcp_dstopts = NULL;
6603 		tcp->tcp_dstoptslen = 0;
6604 	}
6605 	ASSERT(tcp->tcp_dstoptslen == 0);
6606 	if (tcp->tcp_rthdrdstopts != NULL) {
6607 		mi_free(tcp->tcp_rthdrdstopts);
6608 		tcp->tcp_rthdrdstopts = NULL;
6609 		tcp->tcp_rthdrdstoptslen = 0;
6610 	}
6611 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
6612 	if (tcp->tcp_rthdr != NULL) {
6613 		mi_free(tcp->tcp_rthdr);
6614 		tcp->tcp_rthdr = NULL;
6615 		tcp->tcp_rthdrlen = 0;
6616 	}
6617 	ASSERT(tcp->tcp_rthdrlen == 0);
6618 
6619 	/* Reset fusion-related fields */
6620 	tcp->tcp_fused = B_FALSE;
6621 	tcp->tcp_unfusable = B_FALSE;
6622 	tcp->tcp_fused_sigurg = B_FALSE;
6623 	tcp->tcp_loopback_peer = NULL;
6624 
6625 	tcp->tcp_lso = B_FALSE;
6626 
6627 	tcp->tcp_in_ack_unsent = 0;
6628 	tcp->tcp_cork = B_FALSE;
6629 	tcp->tcp_tconnind_started = B_FALSE;
6630 
6631 	PRESERVE(tcp->tcp_squeue_bytes);
6632 
6633 	ASSERT(tcp->tcp_kssl_ctx == NULL);
6634 	ASSERT(!tcp->tcp_kssl_pending);
6635 	PRESERVE(tcp->tcp_kssl_ent);
6636 
6637 	tcp->tcp_closemp_used = B_FALSE;
6638 
6639 	PRESERVE(tcp->tcp_rsrv_mp);
6640 	PRESERVE(tcp->tcp_rsrv_mp_lock);
6641 
6642 #ifdef DEBUG
6643 	DONTCARE(tcp->tcmp_stk[0]);
6644 #endif
6645 
6646 	PRESERVE(tcp->tcp_connid);
6647 
6648 
6649 #undef	DONTCARE
6650 #undef	PRESERVE
6651 }
6652 
6653 static void
6654 tcp_init_values(tcp_t *tcp)
6655 {
6656 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6657 	conn_t		*connp = tcp->tcp_connp;
6658 
6659 	ASSERT((connp->conn_family == AF_INET &&
6660 	    connp->conn_ipversion == IPV4_VERSION) ||
6661 	    (connp->conn_family == AF_INET6 &&
6662 	    (connp->conn_ipversion == IPV4_VERSION ||
6663 	    connp->conn_ipversion == IPV6_VERSION)));
6664 
6665 	/*
6666 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
6667 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
6668 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
6669 	 * during first few transmissions of a connection as seen in slow
6670 	 * links.
6671 	 */
6672 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
6673 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
6674 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
6675 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
6676 	    tcps->tcps_conn_grace_period;
6677 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
6678 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
6679 	tcp->tcp_timer_backoff = 0;
6680 	tcp->tcp_ms_we_have_waited = 0;
6681 	tcp->tcp_last_recv_time = ddi_get_lbolt();
6682 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
6683 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
6684 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
6685 
6686 	tcp->tcp_maxpsz_multiplier = tcps->tcps_maxpsz_multiplier;
6687 
6688 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
6689 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
6690 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
6691 	/*
6692 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
6693 	 * passive open.
6694 	 */
6695 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
6696 
6697 	tcp->tcp_naglim = tcps->tcps_naglim_def;
6698 
6699 	/* NOTE:  ISS is now set in tcp_set_destination(). */
6700 
6701 	/* Reset fusion-related fields */
6702 	tcp->tcp_fused = B_FALSE;
6703 	tcp->tcp_unfusable = B_FALSE;
6704 	tcp->tcp_fused_sigurg = B_FALSE;
6705 	tcp->tcp_loopback_peer = NULL;
6706 
6707 	/* We rebuild the header template on the next connect/conn_request */
6708 
6709 	connp->conn_mlp_type = mlptSingle;
6710 
6711 	/*
6712 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
6713 	 * down tcp_rwnd. tcp_set_destination() will set the right value later.
6714 	 */
6715 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
6716 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6717 
6718 	tcp->tcp_cork = B_FALSE;
6719 	/*
6720 	 * Init the tcp_debug option if it wasn't already set.  This value
6721 	 * determines whether TCP
6722 	 * calls strlog() to print out debug messages.  Doing this
6723 	 * initialization here means that this value is not inherited thru
6724 	 * tcp_reinit().
6725 	 */
6726 	if (!connp->conn_debug)
6727 		connp->conn_debug = tcps->tcps_dbg;
6728 
6729 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
6730 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
6731 }
6732 
6733 /* At minimum we need 8 bytes in the TCP header for the lookup */
6734 #define	ICMP_MIN_TCP_HDR	8
6735 
6736 /*
6737  * tcp_icmp_input is called as conn_recvicmp to process ICMP error messages
6738  * passed up by IP. The message is always received on the correct tcp_t.
6739  * Assumes that IP has pulled up everything up to and including the ICMP header.
6740  */
6741 /* ARGSUSED2 */
6742 static void
6743 tcp_icmp_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
6744 {
6745 	conn_t		*connp = (conn_t *)arg1;
6746 	icmph_t		*icmph;
6747 	ipha_t		*ipha;
6748 	int		iph_hdr_length;
6749 	tcpha_t		*tcpha;
6750 	uint32_t	seg_seq;
6751 	tcp_t		*tcp = connp->conn_tcp;
6752 
6753 	/* Assume IP provides aligned packets */
6754 	ASSERT(OK_32PTR(mp->b_rptr));
6755 	ASSERT((MBLKL(mp) >= sizeof (ipha_t)));
6756 
6757 	/*
6758 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
6759 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
6760 	 */
6761 	if (!(ira->ira_flags & IRAF_IS_IPV4)) {
6762 		tcp_icmp_error_ipv6(tcp, mp, ira);
6763 		return;
6764 	}
6765 
6766 	/* Skip past the outer IP and ICMP headers */
6767 	iph_hdr_length = ira->ira_ip_hdr_length;
6768 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
6769 	/*
6770 	 * If we don't have the correct outer IP header length
6771 	 * or if we don't have a complete inner IP header
6772 	 * drop it.
6773 	 */
6774 	if (iph_hdr_length < sizeof (ipha_t) ||
6775 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
6776 noticmpv4:
6777 		freemsg(mp);
6778 		return;
6779 	}
6780 	ipha = (ipha_t *)&icmph[1];
6781 
6782 	/* Skip past the inner IP and find the ULP header */
6783 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
6784 	tcpha = (tcpha_t *)((char *)ipha + iph_hdr_length);
6785 	/*
6786 	 * If we don't have the correct inner IP header length or if the ULP
6787 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
6788 	 * bytes of TCP header, drop it.
6789 	 */
6790 	if (iph_hdr_length < sizeof (ipha_t) ||
6791 	    ipha->ipha_protocol != IPPROTO_TCP ||
6792 	    (uchar_t *)tcpha + ICMP_MIN_TCP_HDR > mp->b_wptr) {
6793 		goto noticmpv4;
6794 	}
6795 
6796 	seg_seq = ntohl(tcpha->tha_seq);
6797 	switch (icmph->icmph_type) {
6798 	case ICMP_DEST_UNREACHABLE:
6799 		switch (icmph->icmph_code) {
6800 		case ICMP_FRAGMENTATION_NEEDED:
6801 			/*
6802 			 * Update Path MTU, then try to send something out.
6803 			 */
6804 			tcp_update_pmtu(tcp, B_TRUE);
6805 			tcp_rexmit_after_error(tcp);
6806 			break;
6807 		case ICMP_PORT_UNREACHABLE:
6808 		case ICMP_PROTOCOL_UNREACHABLE:
6809 			switch (tcp->tcp_state) {
6810 			case TCPS_SYN_SENT:
6811 			case TCPS_SYN_RCVD:
6812 				/*
6813 				 * ICMP can snipe away incipient
6814 				 * TCP connections as long as
6815 				 * seq number is same as initial
6816 				 * send seq number.
6817 				 */
6818 				if (seg_seq == tcp->tcp_iss) {
6819 					(void) tcp_clean_death(tcp,
6820 					    ECONNREFUSED, 6);
6821 				}
6822 				break;
6823 			}
6824 			break;
6825 		case ICMP_HOST_UNREACHABLE:
6826 		case ICMP_NET_UNREACHABLE:
6827 			/* Record the error in case we finally time out. */
6828 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
6829 				tcp->tcp_client_errno = EHOSTUNREACH;
6830 			else
6831 				tcp->tcp_client_errno = ENETUNREACH;
6832 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
6833 				if (tcp->tcp_listener != NULL &&
6834 				    tcp->tcp_listener->tcp_syn_defense) {
6835 					/*
6836 					 * Ditch the half-open connection if we
6837 					 * suspect a SYN attack is under way.
6838 					 */
6839 					(void) tcp_clean_death(tcp,
6840 					    tcp->tcp_client_errno, 7);
6841 				}
6842 			}
6843 			break;
6844 		default:
6845 			break;
6846 		}
6847 		break;
6848 	case ICMP_SOURCE_QUENCH: {
6849 		/*
6850 		 * use a global boolean to control
6851 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
6852 		 * The default is false.
6853 		 */
6854 		if (tcp_icmp_source_quench) {
6855 			/*
6856 			 * Reduce the sending rate as if we got a
6857 			 * retransmit timeout
6858 			 */
6859 			uint32_t npkt;
6860 
6861 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
6862 			    tcp->tcp_mss;
6863 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
6864 			tcp->tcp_cwnd = tcp->tcp_mss;
6865 			tcp->tcp_cwnd_cnt = 0;
6866 		}
6867 		break;
6868 	}
6869 	}
6870 	freemsg(mp);
6871 }
6872 
6873 /*
6874  * CALLED OUTSIDE OF SQUEUE! It can not follow any pointers that tcp might
6875  * change. But it can refer to fields like tcp_suna and tcp_snxt.
6876  *
6877  * Function tcp_verifyicmp is called as conn_verifyicmp to verify the ICMP
6878  * error messages received by IP. The message is always received on the correct
6879  * tcp_t.
6880  */
6881 /* ARGSUSED */
6882 static boolean_t
6883 tcp_verifyicmp(conn_t *connp, void *arg2, icmph_t *icmph, icmp6_t *icmp6,
6884     ip_recv_attr_t *ira)
6885 {
6886 	tcpha_t		*tcpha = (tcpha_t *)arg2;
6887 	uint32_t	seq = ntohl(tcpha->tha_seq);
6888 	tcp_t		*tcp = connp->conn_tcp;
6889 
6890 	/*
6891 	 * TCP sequence number contained in payload of the ICMP error message
6892 	 * should be within the range SND.UNA <= SEG.SEQ < SND.NXT. Otherwise,
6893 	 * the message is either a stale ICMP error, or an attack from the
6894 	 * network. Fail the verification.
6895 	 */
6896 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
6897 		return (B_FALSE);
6898 
6899 	/* For "too big" we also check the ignore flag */
6900 	if (ira->ira_flags & IRAF_IS_IPV4) {
6901 		ASSERT(icmph != NULL);
6902 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
6903 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
6904 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
6905 			return (B_FALSE);
6906 	} else {
6907 		ASSERT(icmp6 != NULL);
6908 		if (icmp6->icmp6_type == ICMP6_PACKET_TOO_BIG &&
6909 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
6910 			return (B_FALSE);
6911 	}
6912 	return (B_TRUE);
6913 }
6914 
6915 /*
6916  * Update the TCP connection according to change of PMTU.
6917  *
6918  * Path MTU might have changed by either increase or decrease, so need to
6919  * adjust the MSS based on the value of ixa_pmtu. No need to handle tiny
6920  * or negative MSS, since tcp_mss_set() will do it.
6921  */
6922 static void
6923 tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only)
6924 {
6925 	uint32_t	pmtu;
6926 	int32_t		mss;
6927 	conn_t		*connp = tcp->tcp_connp;
6928 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
6929 	iaflags_t	ixaflags;
6930 
6931 	if (tcp->tcp_tcps->tcps_ignore_path_mtu)
6932 		return;
6933 
6934 	if (tcp->tcp_state < TCPS_ESTABLISHED)
6935 		return;
6936 
6937 	/*
6938 	 * Always call ip_get_pmtu() to make sure that IP has updated
6939 	 * ixa_flags properly.
6940 	 */
6941 	pmtu = ip_get_pmtu(ixa);
6942 	ixaflags = ixa->ixa_flags;
6943 
6944 	/*
6945 	 * Calculate the MSS by decreasing the PMTU by conn_ht_iphc_len and
6946 	 * IPsec overhead if applied. Make sure to use the most recent
6947 	 * IPsec information.
6948 	 */
6949 	mss = pmtu - connp->conn_ht_iphc_len - conn_ipsec_length(connp);
6950 
6951 	/*
6952 	 * Nothing to change, so just return.
6953 	 */
6954 	if (mss == tcp->tcp_mss)
6955 		return;
6956 
6957 	/*
6958 	 * Currently, for ICMP errors, only PMTU decrease is handled.
6959 	 */
6960 	if (mss > tcp->tcp_mss && decrease_only)
6961 		return;
6962 
6963 	DTRACE_PROBE2(tcp_update_pmtu, int32_t, tcp->tcp_mss, uint32_t, mss);
6964 
6965 	/*
6966 	 * Update ixa_fragsize and ixa_pmtu.
6967 	 */
6968 	ixa->ixa_fragsize = ixa->ixa_pmtu = pmtu;
6969 
6970 	/*
6971 	 * Adjust MSS and all relevant variables.
6972 	 */
6973 	tcp_mss_set(tcp, mss);
6974 
6975 	/*
6976 	 * If the PMTU is below the min size maintained by IP, then ip_get_pmtu
6977 	 * has set IXAF_PMTU_TOO_SMALL and cleared IXAF_PMTU_IPV4_DF. Since TCP
6978 	 * has a (potentially different) min size we do the same. Make sure to
6979 	 * clear IXAF_DONTFRAG, which is used by IP to decide whether to
6980 	 * fragment the packet.
6981 	 *
6982 	 * LSO over IPv6 can not be fragmented. So need to disable LSO
6983 	 * when IPv6 fragmentation is needed.
6984 	 */
6985 	if (mss < tcp->tcp_tcps->tcps_mss_min)
6986 		ixaflags |= IXAF_PMTU_TOO_SMALL;
6987 
6988 	if (ixaflags & IXAF_PMTU_TOO_SMALL)
6989 		ixaflags &= ~(IXAF_DONTFRAG | IXAF_PMTU_IPV4_DF);
6990 
6991 	if ((connp->conn_ipversion == IPV4_VERSION) &&
6992 	    !(ixaflags & IXAF_PMTU_IPV4_DF)) {
6993 		tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
6994 	}
6995 	ixa->ixa_flags = ixaflags;
6996 }
6997 
6998 /*
6999  * Do slow start retransmission after ICMP errors of PMTU changes.
7000  */
7001 static void
7002 tcp_rexmit_after_error(tcp_t *tcp)
7003 {
7004 	/*
7005 	 * All sent data has been acknowledged or no data left to send, just
7006 	 * to return.
7007 	 */
7008 	if (!SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) ||
7009 	    (tcp->tcp_xmit_head == NULL))
7010 		return;
7011 
7012 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (tcp->tcp_unsent == 0))
7013 		tcp->tcp_rexmit_max = tcp->tcp_fss;
7014 	else
7015 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
7016 
7017 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
7018 	tcp->tcp_rexmit = B_TRUE;
7019 	tcp->tcp_dupack_cnt = 0;
7020 	tcp->tcp_snd_burst = TCP_CWND_SS;
7021 	tcp_ss_rexmit(tcp);
7022 }
7023 
7024 /*
7025  * tcp_icmp_error_ipv6 is called from tcp_icmp_input to process ICMPv6
7026  * error messages passed up by IP.
7027  * Assumes that IP has pulled up all the extension headers as well
7028  * as the ICMPv6 header.
7029  */
7030 static void
7031 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, ip_recv_attr_t *ira)
7032 {
7033 	icmp6_t		*icmp6;
7034 	ip6_t		*ip6h;
7035 	uint16_t	iph_hdr_length = ira->ira_ip_hdr_length;
7036 	tcpha_t		*tcpha;
7037 	uint8_t		*nexthdrp;
7038 	uint32_t	seg_seq;
7039 
7040 	/*
7041 	 * Verify that we have a complete IP header.
7042 	 */
7043 	ASSERT((MBLKL(mp) >= sizeof (ip6_t)));
7044 
7045 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
7046 	ip6h = (ip6_t *)&icmp6[1];
7047 	/*
7048 	 * Verify if we have a complete ICMP and inner IP header.
7049 	 */
7050 	if ((uchar_t *)&ip6h[1] > mp->b_wptr) {
7051 noticmpv6:
7052 		freemsg(mp);
7053 		return;
7054 	}
7055 
7056 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
7057 		goto noticmpv6;
7058 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
7059 	/*
7060 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
7061 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
7062 	 * packet.
7063 	 */
7064 	if ((*nexthdrp != IPPROTO_TCP) ||
7065 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
7066 		goto noticmpv6;
7067 	}
7068 
7069 	seg_seq = ntohl(tcpha->tha_seq);
7070 	switch (icmp6->icmp6_type) {
7071 	case ICMP6_PACKET_TOO_BIG:
7072 		/*
7073 		 * Update Path MTU, then try to send something out.
7074 		 */
7075 		tcp_update_pmtu(tcp, B_TRUE);
7076 		tcp_rexmit_after_error(tcp);
7077 		break;
7078 	case ICMP6_DST_UNREACH:
7079 		switch (icmp6->icmp6_code) {
7080 		case ICMP6_DST_UNREACH_NOPORT:
7081 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7082 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7083 			    (seg_seq == tcp->tcp_iss)) {
7084 				(void) tcp_clean_death(tcp,
7085 				    ECONNREFUSED, 8);
7086 			}
7087 			break;
7088 		case ICMP6_DST_UNREACH_ADMIN:
7089 		case ICMP6_DST_UNREACH_NOROUTE:
7090 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
7091 		case ICMP6_DST_UNREACH_ADDR:
7092 			/* Record the error in case we finally time out. */
7093 			tcp->tcp_client_errno = EHOSTUNREACH;
7094 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7095 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7096 			    (seg_seq == tcp->tcp_iss)) {
7097 				if (tcp->tcp_listener != NULL &&
7098 				    tcp->tcp_listener->tcp_syn_defense) {
7099 					/*
7100 					 * Ditch the half-open connection if we
7101 					 * suspect a SYN attack is under way.
7102 					 */
7103 					(void) tcp_clean_death(tcp,
7104 					    tcp->tcp_client_errno, 9);
7105 				}
7106 			}
7107 
7108 
7109 			break;
7110 		default:
7111 			break;
7112 		}
7113 		break;
7114 	case ICMP6_PARAM_PROB:
7115 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
7116 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
7117 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
7118 		    (uchar_t *)nexthdrp) {
7119 			if (tcp->tcp_state == TCPS_SYN_SENT ||
7120 			    tcp->tcp_state == TCPS_SYN_RCVD) {
7121 				(void) tcp_clean_death(tcp,
7122 				    ECONNREFUSED, 10);
7123 			}
7124 			break;
7125 		}
7126 		break;
7127 
7128 	case ICMP6_TIME_EXCEEDED:
7129 	default:
7130 		break;
7131 	}
7132 	freemsg(mp);
7133 }
7134 
7135 /*
7136  * Notify IP that we are having trouble with this connection.  IP should
7137  * make note so it can potentially use a different IRE.
7138  */
7139 static void
7140 tcp_ip_notify(tcp_t *tcp)
7141 {
7142 	conn_t		*connp = tcp->tcp_connp;
7143 	ire_t		*ire;
7144 
7145 	/*
7146 	 * Note: in the case of source routing we want to blow away the
7147 	 * route to the first source route hop.
7148 	 */
7149 	ire = connp->conn_ixa->ixa_ire;
7150 	if (ire != NULL && !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
7151 		if (ire->ire_ipversion == IPV4_VERSION) {
7152 			/*
7153 			 * As per RFC 1122, we send an RTM_LOSING to inform
7154 			 * routing protocols.
7155 			 */
7156 			ip_rts_change(RTM_LOSING, ire->ire_addr,
7157 			    ire->ire_gateway_addr, ire->ire_mask,
7158 			    connp->conn_laddr_v4,  0, 0, 0,
7159 			    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA),
7160 			    ire->ire_ipst);
7161 		}
7162 		(void) ire_no_good(ire);
7163 	}
7164 }
7165 
7166 #pragma inline(tcp_send_data)
7167 
7168 /*
7169  * Timer callback routine for keepalive probe.  We do a fake resend of
7170  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
7171  * check to see if we have heard anything from the other end for the last
7172  * RTO period.  If we have, set the timer to expire for another
7173  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
7174  * RTO << 1 and check again when it expires.  Keep exponentially increasing
7175  * the timeout if we have not heard from the other side.  If for more than
7176  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
7177  * kill the connection unless the keepalive abort threshold is 0.  In
7178  * that case, we will probe "forever."
7179  */
7180 static void
7181 tcp_keepalive_killer(void *arg)
7182 {
7183 	mblk_t	*mp;
7184 	conn_t	*connp = (conn_t *)arg;
7185 	tcp_t  	*tcp = connp->conn_tcp;
7186 	int32_t	firetime;
7187 	int32_t	idletime;
7188 	int32_t	ka_intrvl;
7189 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7190 
7191 	tcp->tcp_ka_tid = 0;
7192 
7193 	if (tcp->tcp_fused)
7194 		return;
7195 
7196 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
7197 	ka_intrvl = tcp->tcp_ka_interval;
7198 
7199 	/*
7200 	 * Keepalive probe should only be sent if the application has not
7201 	 * done a close on the connection.
7202 	 */
7203 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
7204 		return;
7205 	}
7206 	/* Timer fired too early, restart it. */
7207 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
7208 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7209 		    MSEC_TO_TICK(ka_intrvl));
7210 		return;
7211 	}
7212 
7213 	idletime = TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time);
7214 	/*
7215 	 * If we have not heard from the other side for a long
7216 	 * time, kill the connection unless the keepalive abort
7217 	 * threshold is 0.  In that case, we will probe "forever."
7218 	 */
7219 	if (tcp->tcp_ka_abort_thres != 0 &&
7220 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
7221 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
7222 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
7223 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
7224 		return;
7225 	}
7226 
7227 	if (tcp->tcp_snxt == tcp->tcp_suna &&
7228 	    idletime >= ka_intrvl) {
7229 		/* Fake resend of last ACKed byte. */
7230 		mblk_t	*mp1 = allocb(1, BPRI_LO);
7231 
7232 		if (mp1 != NULL) {
7233 			*mp1->b_wptr++ = '\0';
7234 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
7235 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
7236 			freeb(mp1);
7237 			/*
7238 			 * if allocation failed, fall through to start the
7239 			 * timer back.
7240 			 */
7241 			if (mp != NULL) {
7242 				tcp_send_data(tcp, mp);
7243 				BUMP_MIB(&tcps->tcps_mib,
7244 				    tcpTimKeepaliveProbe);
7245 				if (tcp->tcp_ka_last_intrvl != 0) {
7246 					int max;
7247 					/*
7248 					 * We should probe again at least
7249 					 * in ka_intrvl, but not more than
7250 					 * tcp_rexmit_interval_max.
7251 					 */
7252 					max = tcps->tcps_rexmit_interval_max;
7253 					firetime = MIN(ka_intrvl - 1,
7254 					    tcp->tcp_ka_last_intrvl << 1);
7255 					if (firetime > max)
7256 						firetime = max;
7257 				} else {
7258 					firetime = tcp->tcp_rto;
7259 				}
7260 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
7261 				    tcp_keepalive_killer,
7262 				    MSEC_TO_TICK(firetime));
7263 				tcp->tcp_ka_last_intrvl = firetime;
7264 				return;
7265 			}
7266 		}
7267 	} else {
7268 		tcp->tcp_ka_last_intrvl = 0;
7269 	}
7270 
7271 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
7272 	if ((firetime = ka_intrvl - idletime) < 0) {
7273 		firetime = ka_intrvl;
7274 	}
7275 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7276 	    MSEC_TO_TICK(firetime));
7277 }
7278 
7279 int
7280 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
7281 {
7282 	conn_t	*connp = tcp->tcp_connp;
7283 	queue_t	*q = connp->conn_rq;
7284 	int32_t	mss = tcp->tcp_mss;
7285 	int	maxpsz;
7286 
7287 	if (TCP_IS_DETACHED(tcp))
7288 		return (mss);
7289 	if (tcp->tcp_fused) {
7290 		maxpsz = tcp_fuse_maxpsz(tcp);
7291 		mss = INFPSZ;
7292 	} else if (tcp->tcp_maxpsz_multiplier == 0) {
7293 		/*
7294 		 * Set the sd_qn_maxpsz according to the socket send buffer
7295 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
7296 		 * instruct the stream head to copyin user data into contiguous
7297 		 * kernel-allocated buffers without breaking it up into smaller
7298 		 * chunks.  We round up the buffer size to the nearest SMSS.
7299 		 */
7300 		maxpsz = MSS_ROUNDUP(connp->conn_sndbuf, mss);
7301 		if (tcp->tcp_kssl_ctx == NULL)
7302 			mss = INFPSZ;
7303 		else
7304 			mss = SSL3_MAX_RECORD_LEN;
7305 	} else {
7306 		/*
7307 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
7308 		 * (and a multiple of the mss).  This instructs the stream
7309 		 * head to break down larger than SMSS writes into SMSS-
7310 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
7311 		 */
7312 		maxpsz = tcp->tcp_maxpsz_multiplier * mss;
7313 		if (maxpsz > connp->conn_sndbuf / 2) {
7314 			maxpsz = connp->conn_sndbuf / 2;
7315 			/* Round up to nearest mss */
7316 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
7317 		}
7318 	}
7319 
7320 	(void) proto_set_maxpsz(q, connp, maxpsz);
7321 	if (!(IPCL_IS_NONSTR(connp)))
7322 		connp->conn_wq->q_maxpsz = maxpsz;
7323 	if (set_maxblk)
7324 		(void) proto_set_tx_maxblk(q, connp, mss);
7325 	return (mss);
7326 }
7327 
7328 /*
7329  * Extract option values from a tcp header.  We put any found values into the
7330  * tcpopt struct and return a bitmask saying which options were found.
7331  */
7332 static int
7333 tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt)
7334 {
7335 	uchar_t		*endp;
7336 	int		len;
7337 	uint32_t	mss;
7338 	uchar_t		*up = (uchar_t *)tcpha;
7339 	int		found = 0;
7340 	int32_t		sack_len;
7341 	tcp_seq		sack_begin, sack_end;
7342 	tcp_t		*tcp;
7343 
7344 	endp = up + TCP_HDR_LENGTH(tcpha);
7345 	up += TCP_MIN_HEADER_LENGTH;
7346 	while (up < endp) {
7347 		len = endp - up;
7348 		switch (*up) {
7349 		case TCPOPT_EOL:
7350 			break;
7351 
7352 		case TCPOPT_NOP:
7353 			up++;
7354 			continue;
7355 
7356 		case TCPOPT_MAXSEG:
7357 			if (len < TCPOPT_MAXSEG_LEN ||
7358 			    up[1] != TCPOPT_MAXSEG_LEN)
7359 				break;
7360 
7361 			mss = BE16_TO_U16(up+2);
7362 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
7363 			tcpopt->tcp_opt_mss = mss;
7364 			found |= TCP_OPT_MSS_PRESENT;
7365 
7366 			up += TCPOPT_MAXSEG_LEN;
7367 			continue;
7368 
7369 		case TCPOPT_WSCALE:
7370 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
7371 				break;
7372 
7373 			if (up[2] > TCP_MAX_WINSHIFT)
7374 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
7375 			else
7376 				tcpopt->tcp_opt_wscale = up[2];
7377 			found |= TCP_OPT_WSCALE_PRESENT;
7378 
7379 			up += TCPOPT_WS_LEN;
7380 			continue;
7381 
7382 		case TCPOPT_SACK_PERMITTED:
7383 			if (len < TCPOPT_SACK_OK_LEN ||
7384 			    up[1] != TCPOPT_SACK_OK_LEN)
7385 				break;
7386 			found |= TCP_OPT_SACK_OK_PRESENT;
7387 			up += TCPOPT_SACK_OK_LEN;
7388 			continue;
7389 
7390 		case TCPOPT_SACK:
7391 			if (len <= 2 || up[1] <= 2 || len < up[1])
7392 				break;
7393 
7394 			/* If TCP is not interested in SACK blks... */
7395 			if ((tcp = tcpopt->tcp) == NULL) {
7396 				up += up[1];
7397 				continue;
7398 			}
7399 			sack_len = up[1] - TCPOPT_HEADER_LEN;
7400 			up += TCPOPT_HEADER_LEN;
7401 
7402 			/*
7403 			 * If the list is empty, allocate one and assume
7404 			 * nothing is sack'ed.
7405 			 */
7406 			ASSERT(tcp->tcp_sack_info != NULL);
7407 			if (tcp->tcp_notsack_list == NULL) {
7408 				tcp_notsack_update(&(tcp->tcp_notsack_list),
7409 				    tcp->tcp_suna, tcp->tcp_snxt,
7410 				    &(tcp->tcp_num_notsack_blk),
7411 				    &(tcp->tcp_cnt_notsack_list));
7412 
7413 				/*
7414 				 * Make sure tcp_notsack_list is not NULL.
7415 				 * This happens when kmem_alloc(KM_NOSLEEP)
7416 				 * returns NULL.
7417 				 */
7418 				if (tcp->tcp_notsack_list == NULL) {
7419 					up += sack_len;
7420 					continue;
7421 				}
7422 				tcp->tcp_fack = tcp->tcp_suna;
7423 			}
7424 
7425 			while (sack_len > 0) {
7426 				if (up + 8 > endp) {
7427 					up = endp;
7428 					break;
7429 				}
7430 				sack_begin = BE32_TO_U32(up);
7431 				up += 4;
7432 				sack_end = BE32_TO_U32(up);
7433 				up += 4;
7434 				sack_len -= 8;
7435 				/*
7436 				 * Bounds checking.  Make sure the SACK
7437 				 * info is within tcp_suna and tcp_snxt.
7438 				 * If this SACK blk is out of bound, ignore
7439 				 * it but continue to parse the following
7440 				 * blks.
7441 				 */
7442 				if (SEQ_LEQ(sack_end, sack_begin) ||
7443 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
7444 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
7445 					continue;
7446 				}
7447 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
7448 				    sack_begin, sack_end,
7449 				    &(tcp->tcp_num_notsack_blk),
7450 				    &(tcp->tcp_cnt_notsack_list));
7451 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
7452 					tcp->tcp_fack = sack_end;
7453 				}
7454 			}
7455 			found |= TCP_OPT_SACK_PRESENT;
7456 			continue;
7457 
7458 		case TCPOPT_TSTAMP:
7459 			if (len < TCPOPT_TSTAMP_LEN ||
7460 			    up[1] != TCPOPT_TSTAMP_LEN)
7461 				break;
7462 
7463 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
7464 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
7465 
7466 			found |= TCP_OPT_TSTAMP_PRESENT;
7467 
7468 			up += TCPOPT_TSTAMP_LEN;
7469 			continue;
7470 
7471 		default:
7472 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
7473 				break;
7474 			up += up[1];
7475 			continue;
7476 		}
7477 		break;
7478 	}
7479 	return (found);
7480 }
7481 
7482 /*
7483  * Set the MSS associated with a particular tcp based on its current value,
7484  * and a new one passed in. Observe minimums and maximums, and reset other
7485  * state variables that we want to view as multiples of MSS.
7486  *
7487  * The value of MSS could be either increased or descreased.
7488  */
7489 static void
7490 tcp_mss_set(tcp_t *tcp, uint32_t mss)
7491 {
7492 	uint32_t	mss_max;
7493 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7494 	conn_t		*connp = tcp->tcp_connp;
7495 
7496 	if (connp->conn_ipversion == IPV4_VERSION)
7497 		mss_max = tcps->tcps_mss_max_ipv4;
7498 	else
7499 		mss_max = tcps->tcps_mss_max_ipv6;
7500 
7501 	if (mss < tcps->tcps_mss_min)
7502 		mss = tcps->tcps_mss_min;
7503 	if (mss > mss_max)
7504 		mss = mss_max;
7505 	/*
7506 	 * Unless naglim has been set by our client to
7507 	 * a non-mss value, force naglim to track mss.
7508 	 * This can help to aggregate small writes.
7509 	 */
7510 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
7511 		tcp->tcp_naglim = mss;
7512 	/*
7513 	 * TCP should be able to buffer at least 4 MSS data for obvious
7514 	 * performance reason.
7515 	 */
7516 	if ((mss << 2) > connp->conn_sndbuf)
7517 		connp->conn_sndbuf = mss << 2;
7518 
7519 	/*
7520 	 * Set the send lowater to at least twice of MSS.
7521 	 */
7522 	if ((mss << 1) > connp->conn_sndlowat)
7523 		connp->conn_sndlowat = mss << 1;
7524 
7525 	/*
7526 	 * Update tcp_cwnd according to the new value of MSS. Keep the
7527 	 * previous ratio to preserve the transmit rate.
7528 	 */
7529 	tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
7530 	tcp->tcp_cwnd_cnt = 0;
7531 
7532 	tcp->tcp_mss = mss;
7533 	(void) tcp_maxpsz_set(tcp, B_TRUE);
7534 }
7535 
7536 /* For /dev/tcp aka AF_INET open */
7537 static int
7538 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7539 {
7540 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
7541 }
7542 
7543 /* For /dev/tcp6 aka AF_INET6 open */
7544 static int
7545 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7546 {
7547 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
7548 }
7549 
7550 static conn_t *
7551 tcp_create_common(cred_t *credp, boolean_t isv6, boolean_t issocket,
7552     int *errorp)
7553 {
7554 	tcp_t		*tcp = NULL;
7555 	conn_t		*connp;
7556 	zoneid_t	zoneid;
7557 	tcp_stack_t	*tcps;
7558 	squeue_t	*sqp;
7559 
7560 	ASSERT(errorp != NULL);
7561 	/*
7562 	 * Find the proper zoneid and netstack.
7563 	 */
7564 	/*
7565 	 * Special case for install: miniroot needs to be able to
7566 	 * access files via NFS as though it were always in the
7567 	 * global zone.
7568 	 */
7569 	if (credp == kcred && nfs_global_client_only != 0) {
7570 		zoneid = GLOBAL_ZONEID;
7571 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
7572 		    netstack_tcp;
7573 		ASSERT(tcps != NULL);
7574 	} else {
7575 		netstack_t *ns;
7576 
7577 		ns = netstack_find_by_cred(credp);
7578 		ASSERT(ns != NULL);
7579 		tcps = ns->netstack_tcp;
7580 		ASSERT(tcps != NULL);
7581 
7582 		/*
7583 		 * For exclusive stacks we set the zoneid to zero
7584 		 * to make TCP operate as if in the global zone.
7585 		 */
7586 		if (tcps->tcps_netstack->netstack_stackid !=
7587 		    GLOBAL_NETSTACKID)
7588 			zoneid = GLOBAL_ZONEID;
7589 		else
7590 			zoneid = crgetzoneid(credp);
7591 	}
7592 
7593 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
7594 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
7595 	/*
7596 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
7597 	 * so we drop it by one.
7598 	 */
7599 	netstack_rele(tcps->tcps_netstack);
7600 	if (connp == NULL) {
7601 		*errorp = ENOSR;
7602 		return (NULL);
7603 	}
7604 	ASSERT(connp->conn_ixa->ixa_protocol == connp->conn_proto);
7605 
7606 	connp->conn_sqp = sqp;
7607 	connp->conn_initial_sqp = connp->conn_sqp;
7608 	connp->conn_ixa->ixa_sqp = connp->conn_sqp;
7609 	tcp = connp->conn_tcp;
7610 
7611 	/*
7612 	 * Besides asking IP to set the checksum for us, have conn_ip_output
7613 	 * to do the following checks when necessary:
7614 	 *
7615 	 * IXAF_VERIFY_SOURCE: drop packets when our outer source goes invalid
7616 	 * IXAF_VERIFY_PMTU: verify PMTU changes
7617 	 * IXAF_VERIFY_LSO: verify LSO capability changes
7618 	 */
7619 	connp->conn_ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
7620 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO;
7621 
7622 	if (!tcps->tcps_dev_flow_ctl)
7623 		connp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
7624 
7625 	if (isv6) {
7626 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
7627 		connp->conn_ipversion = IPV6_VERSION;
7628 		connp->conn_family = AF_INET6;
7629 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7630 		connp->conn_default_ttl = tcps->tcps_ipv6_hoplimit;
7631 	} else {
7632 		connp->conn_ipversion = IPV4_VERSION;
7633 		connp->conn_family = AF_INET;
7634 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7635 		connp->conn_default_ttl = tcps->tcps_ipv4_ttl;
7636 	}
7637 	connp->conn_xmit_ipp.ipp_unicast_hops = connp->conn_default_ttl;
7638 
7639 	crhold(credp);
7640 	connp->conn_cred = credp;
7641 	connp->conn_cpid = curproc->p_pid;
7642 	connp->conn_open_time = ddi_get_lbolt64();
7643 
7644 	connp->conn_zoneid = zoneid;
7645 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
7646 	connp->conn_ixa->ixa_zoneid = zoneid;
7647 	connp->conn_mlp_type = mlptSingle;
7648 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
7649 	ASSERT(tcp->tcp_tcps == tcps);
7650 
7651 	/*
7652 	 * If the caller has the process-wide flag set, then default to MAC
7653 	 * exempt mode.  This allows read-down to unlabeled hosts.
7654 	 */
7655 	if (getpflags(NET_MAC_AWARE, credp) != 0)
7656 		connp->conn_mac_mode = CONN_MAC_AWARE;
7657 
7658 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
7659 
7660 	if (issocket) {
7661 		tcp->tcp_issocket = 1;
7662 	}
7663 
7664 	connp->conn_rcvbuf = tcps->tcps_recv_hiwat;
7665 	connp->conn_sndbuf = tcps->tcps_xmit_hiwat;
7666 	connp->conn_sndlowat = tcps->tcps_xmit_lowat;
7667 	connp->conn_so_type = SOCK_STREAM;
7668 	connp->conn_wroff = connp->conn_ht_iphc_allocated +
7669 	    tcps->tcps_wroff_xtra;
7670 
7671 	SOCK_CONNID_INIT(tcp->tcp_connid);
7672 	tcp->tcp_state = TCPS_IDLE;
7673 	tcp_init_values(tcp);
7674 	return (connp);
7675 }
7676 
7677 static int
7678 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
7679     boolean_t isv6)
7680 {
7681 	tcp_t		*tcp = NULL;
7682 	conn_t		*connp = NULL;
7683 	int		err;
7684 	vmem_t		*minor_arena = NULL;
7685 	dev_t		conn_dev;
7686 	boolean_t	issocket;
7687 
7688 	if (q->q_ptr != NULL)
7689 		return (0);
7690 
7691 	if (sflag == MODOPEN)
7692 		return (EINVAL);
7693 
7694 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
7695 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
7696 		minor_arena = ip_minor_arena_la;
7697 	} else {
7698 		/*
7699 		 * Either minor numbers in the large arena were exhausted
7700 		 * or a non socket application is doing the open.
7701 		 * Try to allocate from the small arena.
7702 		 */
7703 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
7704 			return (EBUSY);
7705 		}
7706 		minor_arena = ip_minor_arena_sa;
7707 	}
7708 
7709 	ASSERT(minor_arena != NULL);
7710 
7711 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
7712 
7713 	if (flag & SO_FALLBACK) {
7714 		/*
7715 		 * Non streams socket needs a stream to fallback to
7716 		 */
7717 		RD(q)->q_ptr = (void *)conn_dev;
7718 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
7719 		WR(q)->q_ptr = (void *)minor_arena;
7720 		qprocson(q);
7721 		return (0);
7722 	} else if (flag & SO_ACCEPTOR) {
7723 		q->q_qinfo = &tcp_acceptor_rinit;
7724 		/*
7725 		 * the conn_dev and minor_arena will be subsequently used by
7726 		 * tcp_tli_accept() and tcp_tpi_close_accept() to figure out
7727 		 * the minor device number for this connection from the q_ptr.
7728 		 */
7729 		RD(q)->q_ptr = (void *)conn_dev;
7730 		WR(q)->q_qinfo = &tcp_acceptor_winit;
7731 		WR(q)->q_ptr = (void *)minor_arena;
7732 		qprocson(q);
7733 		return (0);
7734 	}
7735 
7736 	issocket = flag & SO_SOCKSTR;
7737 	connp = tcp_create_common(credp, isv6, issocket, &err);
7738 
7739 	if (connp == NULL) {
7740 		inet_minor_free(minor_arena, conn_dev);
7741 		q->q_ptr = WR(q)->q_ptr = NULL;
7742 		return (err);
7743 	}
7744 
7745 	connp->conn_rq = q;
7746 	connp->conn_wq = WR(q);
7747 	q->q_ptr = WR(q)->q_ptr = connp;
7748 
7749 	connp->conn_dev = conn_dev;
7750 	connp->conn_minor_arena = minor_arena;
7751 
7752 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
7753 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
7754 
7755 	tcp = connp->conn_tcp;
7756 
7757 	if (issocket) {
7758 		WR(q)->q_qinfo = &tcp_sock_winit;
7759 	} else {
7760 #ifdef  _ILP32
7761 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
7762 #else
7763 		tcp->tcp_acceptor_id = conn_dev;
7764 #endif  /* _ILP32 */
7765 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
7766 	}
7767 
7768 	/*
7769 	 * Put the ref for TCP. Ref for IP was already put
7770 	 * by ipcl_conn_create. Also Make the conn_t globally
7771 	 * visible to walkers
7772 	 */
7773 	mutex_enter(&connp->conn_lock);
7774 	CONN_INC_REF_LOCKED(connp);
7775 	ASSERT(connp->conn_ref == 2);
7776 	connp->conn_state_flags &= ~CONN_INCIPIENT;
7777 	mutex_exit(&connp->conn_lock);
7778 
7779 	qprocson(q);
7780 	return (0);
7781 }
7782 
7783 /*
7784  * Some TCP options can be "set" by requesting them in the option
7785  * buffer. This is needed for XTI feature test though we do not
7786  * allow it in general. We interpret that this mechanism is more
7787  * applicable to OSI protocols and need not be allowed in general.
7788  * This routine filters out options for which it is not allowed (most)
7789  * and lets through those (few) for which it is. [ The XTI interface
7790  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
7791  * ever implemented will have to be allowed here ].
7792  */
7793 static boolean_t
7794 tcp_allow_connopt_set(int level, int name)
7795 {
7796 
7797 	switch (level) {
7798 	case IPPROTO_TCP:
7799 		switch (name) {
7800 		case TCP_NODELAY:
7801 			return (B_TRUE);
7802 		default:
7803 			return (B_FALSE);
7804 		}
7805 		/*NOTREACHED*/
7806 	default:
7807 		return (B_FALSE);
7808 	}
7809 	/*NOTREACHED*/
7810 }
7811 
7812 /*
7813  * This routine gets default values of certain options whose default
7814  * values are maintained by protocol specific code
7815  */
7816 /* ARGSUSED */
7817 int
7818 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
7819 {
7820 	int32_t	*i1 = (int32_t *)ptr;
7821 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7822 
7823 	switch (level) {
7824 	case IPPROTO_TCP:
7825 		switch (name) {
7826 		case TCP_NOTIFY_THRESHOLD:
7827 			*i1 = tcps->tcps_ip_notify_interval;
7828 			break;
7829 		case TCP_ABORT_THRESHOLD:
7830 			*i1 = tcps->tcps_ip_abort_interval;
7831 			break;
7832 		case TCP_CONN_NOTIFY_THRESHOLD:
7833 			*i1 = tcps->tcps_ip_notify_cinterval;
7834 			break;
7835 		case TCP_CONN_ABORT_THRESHOLD:
7836 			*i1 = tcps->tcps_ip_abort_cinterval;
7837 			break;
7838 		default:
7839 			return (-1);
7840 		}
7841 		break;
7842 	case IPPROTO_IP:
7843 		switch (name) {
7844 		case IP_TTL:
7845 			*i1 = tcps->tcps_ipv4_ttl;
7846 			break;
7847 		default:
7848 			return (-1);
7849 		}
7850 		break;
7851 	case IPPROTO_IPV6:
7852 		switch (name) {
7853 		case IPV6_UNICAST_HOPS:
7854 			*i1 = tcps->tcps_ipv6_hoplimit;
7855 			break;
7856 		default:
7857 			return (-1);
7858 		}
7859 		break;
7860 	default:
7861 		return (-1);
7862 	}
7863 	return (sizeof (int));
7864 }
7865 
7866 /*
7867  * TCP routine to get the values of options.
7868  */
7869 static int
7870 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
7871 {
7872 	int		*i1 = (int *)ptr;
7873 	tcp_t		*tcp = connp->conn_tcp;
7874 	conn_opt_arg_t	coas;
7875 	int		retval;
7876 
7877 	coas.coa_connp = connp;
7878 	coas.coa_ixa = connp->conn_ixa;
7879 	coas.coa_ipp = &connp->conn_xmit_ipp;
7880 	coas.coa_ancillary = B_FALSE;
7881 	coas.coa_changed = 0;
7882 
7883 	switch (level) {
7884 	case SOL_SOCKET:
7885 		switch (name) {
7886 		case SO_SND_COPYAVOID:
7887 			*i1 = tcp->tcp_snd_zcopy_on ?
7888 			    SO_SND_COPYAVOID : 0;
7889 			return (sizeof (int));
7890 		case SO_ACCEPTCONN:
7891 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
7892 			return (sizeof (int));
7893 		}
7894 		break;
7895 	case IPPROTO_TCP:
7896 		switch (name) {
7897 		case TCP_NODELAY:
7898 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
7899 			return (sizeof (int));
7900 		case TCP_MAXSEG:
7901 			*i1 = tcp->tcp_mss;
7902 			return (sizeof (int));
7903 		case TCP_NOTIFY_THRESHOLD:
7904 			*i1 = (int)tcp->tcp_first_timer_threshold;
7905 			return (sizeof (int));
7906 		case TCP_ABORT_THRESHOLD:
7907 			*i1 = tcp->tcp_second_timer_threshold;
7908 			return (sizeof (int));
7909 		case TCP_CONN_NOTIFY_THRESHOLD:
7910 			*i1 = tcp->tcp_first_ctimer_threshold;
7911 			return (sizeof (int));
7912 		case TCP_CONN_ABORT_THRESHOLD:
7913 			*i1 = tcp->tcp_second_ctimer_threshold;
7914 			return (sizeof (int));
7915 		case TCP_INIT_CWND:
7916 			*i1 = tcp->tcp_init_cwnd;
7917 			return (sizeof (int));
7918 		case TCP_KEEPALIVE_THRESHOLD:
7919 			*i1 = tcp->tcp_ka_interval;
7920 			return (sizeof (int));
7921 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
7922 			*i1 = tcp->tcp_ka_abort_thres;
7923 			return (sizeof (int));
7924 		case TCP_CORK:
7925 			*i1 = tcp->tcp_cork;
7926 			return (sizeof (int));
7927 		}
7928 		break;
7929 	case IPPROTO_IP:
7930 		if (connp->conn_family != AF_INET)
7931 			return (-1);
7932 		switch (name) {
7933 		case IP_OPTIONS:
7934 		case T_IP_OPTIONS:
7935 			/* Caller ensures enough space */
7936 			return (ip_opt_get_user(connp, ptr));
7937 		default:
7938 			break;
7939 		}
7940 		break;
7941 
7942 	case IPPROTO_IPV6:
7943 		/*
7944 		 * IPPROTO_IPV6 options are only supported for sockets
7945 		 * that are using IPv6 on the wire.
7946 		 */
7947 		if (connp->conn_ipversion != IPV6_VERSION) {
7948 			return (-1);
7949 		}
7950 		switch (name) {
7951 		case IPV6_PATHMTU:
7952 			if (tcp->tcp_state < TCPS_ESTABLISHED)
7953 				return (-1);
7954 			break;
7955 		}
7956 		break;
7957 	}
7958 	mutex_enter(&connp->conn_lock);
7959 	retval = conn_opt_get(&coas, level, name, ptr);
7960 	mutex_exit(&connp->conn_lock);
7961 	return (retval);
7962 }
7963 
7964 /*
7965  * TCP routine to get the values of options.
7966  */
7967 int
7968 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
7969 {
7970 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
7971 }
7972 
7973 /* returns UNIX error, the optlen is a value-result arg */
7974 int
7975 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
7976     void *optvalp, socklen_t *optlen, cred_t *cr)
7977 {
7978 	conn_t		*connp = (conn_t *)proto_handle;
7979 	squeue_t	*sqp = connp->conn_sqp;
7980 	int		error;
7981 	t_uscalar_t	max_optbuf_len;
7982 	void		*optvalp_buf;
7983 	int		len;
7984 
7985 	ASSERT(connp->conn_upper_handle != NULL);
7986 
7987 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
7988 	    tcp_opt_obj.odb_opt_des_arr,
7989 	    tcp_opt_obj.odb_opt_arr_cnt,
7990 	    B_FALSE, B_TRUE, cr);
7991 	if (error != 0) {
7992 		if (error < 0) {
7993 			error = proto_tlitosyserr(-error);
7994 		}
7995 		return (error);
7996 	}
7997 
7998 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
7999 
8000 	error = squeue_synch_enter(sqp, connp, NULL);
8001 	if (error == ENOMEM) {
8002 		kmem_free(optvalp_buf, max_optbuf_len);
8003 		return (ENOMEM);
8004 	}
8005 
8006 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
8007 	squeue_synch_exit(sqp, connp);
8008 
8009 	if (len == -1) {
8010 		kmem_free(optvalp_buf, max_optbuf_len);
8011 		return (EINVAL);
8012 	}
8013 
8014 	/*
8015 	 * update optlen and copy option value
8016 	 */
8017 	t_uscalar_t size = MIN(len, *optlen);
8018 
8019 	bcopy(optvalp_buf, optvalp, size);
8020 	bcopy(&size, optlen, sizeof (size));
8021 
8022 	kmem_free(optvalp_buf, max_optbuf_len);
8023 	return (0);
8024 }
8025 
8026 /*
8027  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
8028  * Parameters are assumed to be verified by the caller.
8029  */
8030 /* ARGSUSED */
8031 int
8032 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
8033     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8034     void *thisdg_attrs, cred_t *cr)
8035 {
8036 	tcp_t	*tcp = connp->conn_tcp;
8037 	int	*i1 = (int *)invalp;
8038 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
8039 	boolean_t checkonly;
8040 	int	reterr;
8041 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8042 	conn_opt_arg_t	coas;
8043 
8044 	coas.coa_connp = connp;
8045 	coas.coa_ixa = connp->conn_ixa;
8046 	coas.coa_ipp = &connp->conn_xmit_ipp;
8047 	coas.coa_ancillary = B_FALSE;
8048 	coas.coa_changed = 0;
8049 
8050 	switch (optset_context) {
8051 	case SETFN_OPTCOM_CHECKONLY:
8052 		checkonly = B_TRUE;
8053 		/*
8054 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
8055 		 * inlen != 0 implies value supplied and
8056 		 * 	we have to "pretend" to set it.
8057 		 * inlen == 0 implies that there is no
8058 		 * 	value part in T_CHECK request and just validation
8059 		 * done elsewhere should be enough, we just return here.
8060 		 */
8061 		if (inlen == 0) {
8062 			*outlenp = 0;
8063 			return (0);
8064 		}
8065 		break;
8066 	case SETFN_OPTCOM_NEGOTIATE:
8067 		checkonly = B_FALSE;
8068 		break;
8069 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
8070 	case SETFN_CONN_NEGOTIATE:
8071 		checkonly = B_FALSE;
8072 		/*
8073 		 * Negotiating local and "association-related" options
8074 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
8075 		 * primitives is allowed by XTI, but we choose
8076 		 * to not implement this style negotiation for Internet
8077 		 * protocols (We interpret it is a must for OSI world but
8078 		 * optional for Internet protocols) for all options.
8079 		 * [ Will do only for the few options that enable test
8080 		 * suites that our XTI implementation of this feature
8081 		 * works for transports that do allow it ]
8082 		 */
8083 		if (!tcp_allow_connopt_set(level, name)) {
8084 			*outlenp = 0;
8085 			return (EINVAL);
8086 		}
8087 		break;
8088 	default:
8089 		/*
8090 		 * We should never get here
8091 		 */
8092 		*outlenp = 0;
8093 		return (EINVAL);
8094 	}
8095 
8096 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
8097 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
8098 
8099 	/*
8100 	 * For TCP, we should have no ancillary data sent down
8101 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
8102 	 * has to be zero.
8103 	 */
8104 	ASSERT(thisdg_attrs == NULL);
8105 
8106 	/*
8107 	 * For fixed length options, no sanity check
8108 	 * of passed in length is done. It is assumed *_optcom_req()
8109 	 * routines do the right thing.
8110 	 */
8111 	switch (level) {
8112 	case SOL_SOCKET:
8113 		switch (name) {
8114 		case SO_KEEPALIVE:
8115 			if (checkonly) {
8116 				/* check only case */
8117 				break;
8118 			}
8119 
8120 			if (!onoff) {
8121 				if (connp->conn_keepalive) {
8122 					if (tcp->tcp_ka_tid != 0) {
8123 						(void) TCP_TIMER_CANCEL(tcp,
8124 						    tcp->tcp_ka_tid);
8125 						tcp->tcp_ka_tid = 0;
8126 					}
8127 					connp->conn_keepalive = 0;
8128 				}
8129 				break;
8130 			}
8131 			if (!connp->conn_keepalive) {
8132 				/* Crank up the keepalive timer */
8133 				tcp->tcp_ka_last_intrvl = 0;
8134 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8135 				    tcp_keepalive_killer,
8136 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
8137 				connp->conn_keepalive = 1;
8138 			}
8139 			break;
8140 		case SO_SNDBUF: {
8141 			if (*i1 > tcps->tcps_max_buf) {
8142 				*outlenp = 0;
8143 				return (ENOBUFS);
8144 			}
8145 			if (checkonly)
8146 				break;
8147 
8148 			connp->conn_sndbuf = *i1;
8149 			if (tcps->tcps_snd_lowat_fraction != 0) {
8150 				connp->conn_sndlowat = connp->conn_sndbuf /
8151 				    tcps->tcps_snd_lowat_fraction;
8152 			}
8153 			(void) tcp_maxpsz_set(tcp, B_TRUE);
8154 			/*
8155 			 * If we are flow-controlled, recheck the condition.
8156 			 * There are apps that increase SO_SNDBUF size when
8157 			 * flow-controlled (EWOULDBLOCK), and expect the flow
8158 			 * control condition to be lifted right away.
8159 			 */
8160 			mutex_enter(&tcp->tcp_non_sq_lock);
8161 			if (tcp->tcp_flow_stopped &&
8162 			    TCP_UNSENT_BYTES(tcp) < connp->conn_sndbuf) {
8163 				tcp_clrqfull(tcp);
8164 			}
8165 			mutex_exit(&tcp->tcp_non_sq_lock);
8166 			*outlenp = inlen;
8167 			return (0);
8168 		}
8169 		case SO_RCVBUF:
8170 			if (*i1 > tcps->tcps_max_buf) {
8171 				*outlenp = 0;
8172 				return (ENOBUFS);
8173 			}
8174 			/* Silently ignore zero */
8175 			if (!checkonly && *i1 != 0) {
8176 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
8177 				(void) tcp_rwnd_set(tcp, *i1);
8178 			}
8179 			/*
8180 			 * XXX should we return the rwnd here
8181 			 * and tcp_opt_get ?
8182 			 */
8183 			*outlenp = inlen;
8184 			return (0);
8185 		case SO_SND_COPYAVOID:
8186 			if (!checkonly) {
8187 				if (tcp->tcp_loopback ||
8188 				    (tcp->tcp_kssl_ctx != NULL) ||
8189 				    (onoff != 1) || !tcp_zcopy_check(tcp)) {
8190 					*outlenp = 0;
8191 					return (EOPNOTSUPP);
8192 				}
8193 				tcp->tcp_snd_zcopy_aware = 1;
8194 			}
8195 			*outlenp = inlen;
8196 			return (0);
8197 		}
8198 		break;
8199 	case IPPROTO_TCP:
8200 		switch (name) {
8201 		case TCP_NODELAY:
8202 			if (!checkonly)
8203 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
8204 			break;
8205 		case TCP_NOTIFY_THRESHOLD:
8206 			if (!checkonly)
8207 				tcp->tcp_first_timer_threshold = *i1;
8208 			break;
8209 		case TCP_ABORT_THRESHOLD:
8210 			if (!checkonly)
8211 				tcp->tcp_second_timer_threshold = *i1;
8212 			break;
8213 		case TCP_CONN_NOTIFY_THRESHOLD:
8214 			if (!checkonly)
8215 				tcp->tcp_first_ctimer_threshold = *i1;
8216 			break;
8217 		case TCP_CONN_ABORT_THRESHOLD:
8218 			if (!checkonly)
8219 				tcp->tcp_second_ctimer_threshold = *i1;
8220 			break;
8221 		case TCP_RECVDSTADDR:
8222 			if (tcp->tcp_state > TCPS_LISTEN) {
8223 				*outlenp = 0;
8224 				return (EOPNOTSUPP);
8225 			}
8226 			/* Setting done in conn_opt_set */
8227 			break;
8228 		case TCP_INIT_CWND: {
8229 			uint32_t init_cwnd = *((uint32_t *)invalp);
8230 
8231 			if (checkonly)
8232 				break;
8233 
8234 			/*
8235 			 * Only allow socket with network configuration
8236 			 * privilege to set the initial cwnd to be larger
8237 			 * than allowed by RFC 3390.
8238 			 */
8239 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
8240 				tcp->tcp_init_cwnd = init_cwnd;
8241 				break;
8242 			}
8243 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
8244 				*outlenp = 0;
8245 				return (reterr);
8246 			}
8247 			if (init_cwnd > TCP_MAX_INIT_CWND) {
8248 				*outlenp = 0;
8249 				return (EINVAL);
8250 			}
8251 			tcp->tcp_init_cwnd = init_cwnd;
8252 			break;
8253 		}
8254 		case TCP_KEEPALIVE_THRESHOLD:
8255 			if (checkonly)
8256 				break;
8257 
8258 			if (*i1 < tcps->tcps_keepalive_interval_low ||
8259 			    *i1 > tcps->tcps_keepalive_interval_high) {
8260 				*outlenp = 0;
8261 				return (EINVAL);
8262 			}
8263 			if (*i1 != tcp->tcp_ka_interval) {
8264 				tcp->tcp_ka_interval = *i1;
8265 				/*
8266 				 * Check if we need to restart the
8267 				 * keepalive timer.
8268 				 */
8269 				if (tcp->tcp_ka_tid != 0) {
8270 					ASSERT(connp->conn_keepalive);
8271 					(void) TCP_TIMER_CANCEL(tcp,
8272 					    tcp->tcp_ka_tid);
8273 					tcp->tcp_ka_last_intrvl = 0;
8274 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
8275 					    tcp_keepalive_killer,
8276 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
8277 				}
8278 			}
8279 			break;
8280 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8281 			if (!checkonly) {
8282 				if (*i1 <
8283 				    tcps->tcps_keepalive_abort_interval_low ||
8284 				    *i1 >
8285 				    tcps->tcps_keepalive_abort_interval_high) {
8286 					*outlenp = 0;
8287 					return (EINVAL);
8288 				}
8289 				tcp->tcp_ka_abort_thres = *i1;
8290 			}
8291 			break;
8292 		case TCP_CORK:
8293 			if (!checkonly) {
8294 				/*
8295 				 * if tcp->tcp_cork was set and is now
8296 				 * being unset, we have to make sure that
8297 				 * the remaining data gets sent out. Also
8298 				 * unset tcp->tcp_cork so that tcp_wput_data()
8299 				 * can send data even if it is less than mss
8300 				 */
8301 				if (tcp->tcp_cork && onoff == 0 &&
8302 				    tcp->tcp_unsent > 0) {
8303 					tcp->tcp_cork = B_FALSE;
8304 					tcp_wput_data(tcp, NULL, B_FALSE);
8305 				}
8306 				tcp->tcp_cork = onoff;
8307 			}
8308 			break;
8309 		default:
8310 			break;
8311 		}
8312 		break;
8313 	case IPPROTO_IP:
8314 		if (connp->conn_family != AF_INET) {
8315 			*outlenp = 0;
8316 			return (EINVAL);
8317 		}
8318 		switch (name) {
8319 		case IP_SEC_OPT:
8320 			/*
8321 			 * We should not allow policy setting after
8322 			 * we start listening for connections.
8323 			 */
8324 			if (tcp->tcp_state == TCPS_LISTEN) {
8325 				return (EINVAL);
8326 			}
8327 			break;
8328 		}
8329 		break;
8330 	case IPPROTO_IPV6:
8331 		/*
8332 		 * IPPROTO_IPV6 options are only supported for sockets
8333 		 * that are using IPv6 on the wire.
8334 		 */
8335 		if (connp->conn_ipversion != IPV6_VERSION) {
8336 			*outlenp = 0;
8337 			return (EINVAL);
8338 		}
8339 
8340 		switch (name) {
8341 		case IPV6_RECVPKTINFO:
8342 			if (!checkonly) {
8343 				/* Force it to be sent up with the next msg */
8344 				tcp->tcp_recvifindex = 0;
8345 			}
8346 			break;
8347 		case IPV6_RECVTCLASS:
8348 			if (!checkonly) {
8349 				/* Force it to be sent up with the next msg */
8350 				tcp->tcp_recvtclass = 0xffffffffU;
8351 			}
8352 			break;
8353 		case IPV6_RECVHOPLIMIT:
8354 			if (!checkonly) {
8355 				/* Force it to be sent up with the next msg */
8356 				tcp->tcp_recvhops = 0xffffffffU;
8357 			}
8358 			break;
8359 		case IPV6_PKTINFO:
8360 			/* This is an extra check for TCP */
8361 			if (inlen == sizeof (struct in6_pktinfo)) {
8362 				struct in6_pktinfo *pkti;
8363 
8364 				pkti = (struct in6_pktinfo *)invalp;
8365 				/*
8366 				 * RFC 3542 states that ipi6_addr must be
8367 				 * the unspecified address when setting the
8368 				 * IPV6_PKTINFO sticky socket option on a
8369 				 * TCP socket.
8370 				 */
8371 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
8372 					return (EINVAL);
8373 			}
8374 			break;
8375 		case IPV6_SEC_OPT:
8376 			/*
8377 			 * We should not allow policy setting after
8378 			 * we start listening for connections.
8379 			 */
8380 			if (tcp->tcp_state == TCPS_LISTEN) {
8381 				return (EINVAL);
8382 			}
8383 			break;
8384 		}
8385 		break;
8386 	}
8387 	reterr = conn_opt_set(&coas, level, name, inlen, invalp,
8388 	    checkonly, cr);
8389 	if (reterr != 0) {
8390 		*outlenp = 0;
8391 		return (reterr);
8392 	}
8393 
8394 	/*
8395 	 * Common case of OK return with outval same as inval
8396 	 */
8397 	if (invalp != outvalp) {
8398 		/* don't trust bcopy for identical src/dst */
8399 		(void) bcopy(invalp, outvalp, inlen);
8400 	}
8401 	*outlenp = inlen;
8402 
8403 	if (coas.coa_changed & COA_HEADER_CHANGED) {
8404 		reterr = tcp_build_hdrs(tcp);
8405 		if (reterr != 0)
8406 			return (reterr);
8407 	}
8408 	if (coas.coa_changed & COA_ROUTE_CHANGED) {
8409 		in6_addr_t nexthop;
8410 
8411 		/*
8412 		 * If we are connected we re-cache the information.
8413 		 * We ignore errors to preserve BSD behavior.
8414 		 * Note that we don't redo IPsec policy lookup here
8415 		 * since the final destination (or source) didn't change.
8416 		 */
8417 		ip_attr_nexthop(&connp->conn_xmit_ipp, connp->conn_ixa,
8418 		    &connp->conn_faddr_v6, &nexthop);
8419 
8420 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8421 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8422 			(void) ip_attr_connect(connp, connp->conn_ixa,
8423 			    &connp->conn_laddr_v6, &connp->conn_faddr_v6,
8424 			    &nexthop, connp->conn_fport, NULL, NULL,
8425 			    IPDF_VERIFY_DST);
8426 		}
8427 	}
8428 	if ((coas.coa_changed & COA_SNDBUF_CHANGED) && !IPCL_IS_NONSTR(connp)) {
8429 		connp->conn_wq->q_hiwat = connp->conn_sndbuf;
8430 	}
8431 	if (coas.coa_changed & COA_WROFF_CHANGED) {
8432 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8433 		    tcps->tcps_wroff_xtra;
8434 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8435 		    connp->conn_wroff);
8436 	}
8437 	if (coas.coa_changed & COA_OOBINLINE_CHANGED) {
8438 		if (IPCL_IS_NONSTR(connp))
8439 			proto_set_rx_oob_opt(connp, onoff);
8440 	}
8441 	return (0);
8442 }
8443 
8444 /* ARGSUSED */
8445 int
8446 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
8447     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8448     void *thisdg_attrs, cred_t *cr)
8449 {
8450 	conn_t	*connp =  Q_TO_CONN(q);
8451 
8452 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
8453 	    outlenp, outvalp, thisdg_attrs, cr));
8454 }
8455 
8456 int
8457 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8458     const void *optvalp, socklen_t optlen, cred_t *cr)
8459 {
8460 	conn_t		*connp = (conn_t *)proto_handle;
8461 	squeue_t	*sqp = connp->conn_sqp;
8462 	int		error;
8463 
8464 	ASSERT(connp->conn_upper_handle != NULL);
8465 	/*
8466 	 * Entering the squeue synchronously can result in a context switch,
8467 	 * which can cause a rather sever performance degradation. So we try to
8468 	 * handle whatever options we can without entering the squeue.
8469 	 */
8470 	if (level == IPPROTO_TCP) {
8471 		switch (option_name) {
8472 		case TCP_NODELAY:
8473 			if (optlen != sizeof (int32_t))
8474 				return (EINVAL);
8475 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
8476 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
8477 			    connp->conn_tcp->tcp_mss;
8478 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
8479 			return (0);
8480 		default:
8481 			break;
8482 		}
8483 	}
8484 
8485 	error = squeue_synch_enter(sqp, connp, NULL);
8486 	if (error == ENOMEM) {
8487 		return (ENOMEM);
8488 	}
8489 
8490 	error = proto_opt_check(level, option_name, optlen, NULL,
8491 	    tcp_opt_obj.odb_opt_des_arr,
8492 	    tcp_opt_obj.odb_opt_arr_cnt,
8493 	    B_TRUE, B_FALSE, cr);
8494 
8495 	if (error != 0) {
8496 		if (error < 0) {
8497 			error = proto_tlitosyserr(-error);
8498 		}
8499 		squeue_synch_exit(sqp, connp);
8500 		return (error);
8501 	}
8502 
8503 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
8504 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
8505 	    NULL, cr);
8506 	squeue_synch_exit(sqp, connp);
8507 
8508 	ASSERT(error >= 0);
8509 
8510 	return (error);
8511 }
8512 
8513 /*
8514  * Build/update the tcp header template (in conn_ht_iphc) based on
8515  * conn_xmit_ipp. The headers include ip6_t, any extension
8516  * headers, and the maximum size tcp header (to avoid reallocation
8517  * on the fly for additional tcp options).
8518  *
8519  * Assumes the caller has already set conn_{faddr,laddr,fport,lport,flowinfo}.
8520  * Returns failure if can't allocate memory.
8521  */
8522 static int
8523 tcp_build_hdrs(tcp_t *tcp)
8524 {
8525 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8526 	conn_t		*connp = tcp->tcp_connp;
8527 	char		buf[TCP_MAX_HDR_LENGTH];
8528 	uint_t		buflen;
8529 	uint_t		ulplen = TCP_MIN_HEADER_LENGTH;
8530 	uint_t		extralen = TCP_MAX_TCP_OPTIONS_LENGTH;
8531 	tcpha_t		*tcpha;
8532 	uint32_t	cksum;
8533 	int		error;
8534 
8535 	/*
8536 	 * We might be called after the connection is set up, and we might
8537 	 * have TS options already in the TCP header. Thus we  save any
8538 	 * existing tcp header.
8539 	 */
8540 	buflen = connp->conn_ht_ulp_len;
8541 	if (buflen != 0) {
8542 		bcopy(connp->conn_ht_ulp, buf, buflen);
8543 		extralen -= buflen - ulplen;
8544 		ulplen = buflen;
8545 	}
8546 
8547 	/* Grab lock to satisfy ASSERT; TCP is serialized using squeue */
8548 	mutex_enter(&connp->conn_lock);
8549 	error = conn_build_hdr_template(connp, ulplen, extralen,
8550 	    &connp->conn_laddr_v6, &connp->conn_faddr_v6, connp->conn_flowinfo);
8551 	mutex_exit(&connp->conn_lock);
8552 	if (error != 0)
8553 		return (error);
8554 
8555 	/*
8556 	 * Any routing header/option has been massaged. The checksum difference
8557 	 * is stored in conn_sum for later use.
8558 	 */
8559 	tcpha = (tcpha_t *)connp->conn_ht_ulp;
8560 	tcp->tcp_tcpha = tcpha;
8561 
8562 	/* restore any old tcp header */
8563 	if (buflen != 0) {
8564 		bcopy(buf, connp->conn_ht_ulp, buflen);
8565 	} else {
8566 		tcpha->tha_sum = 0;
8567 		tcpha->tha_offset_and_reserved = (5 << 4);
8568 	}
8569 	tcpha->tha_lport = connp->conn_lport;
8570 	tcpha->tha_fport = connp->conn_fport;
8571 
8572 	/*
8573 	 * IP wants our header length in the checksum field to
8574 	 * allow it to perform a single pseudo-header+checksum
8575 	 * calculation on behalf of TCP.
8576 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8577 	 */
8578 	cksum = sizeof (tcpha_t) + connp->conn_sum;
8579 	cksum = (cksum >> 16) + (cksum & 0xFFFF);
8580 	ASSERT(cksum < 0x10000);
8581 	tcpha->tha_sum = htons(cksum);
8582 
8583 	if (connp->conn_ipversion == IPV4_VERSION)
8584 		tcp->tcp_ipha = (ipha_t *)connp->conn_ht_iphc;
8585 	else
8586 		tcp->tcp_ip6h = (ip6_t *)connp->conn_ht_iphc;
8587 
8588 	if (connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra >
8589 	    connp->conn_wroff) {
8590 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8591 		    tcps->tcps_wroff_xtra;
8592 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8593 		    connp->conn_wroff);
8594 	}
8595 	return (0);
8596 }
8597 
8598 /* Get callback routine passed to nd_load by tcp_param_register */
8599 /* ARGSUSED */
8600 static int
8601 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
8602 {
8603 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8604 
8605 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
8606 	return (0);
8607 }
8608 
8609 /*
8610  * Walk through the param array specified registering each element with the
8611  * named dispatch handler.
8612  */
8613 static boolean_t
8614 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
8615 {
8616 	for (; cnt-- > 0; tcppa++) {
8617 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
8618 			if (!nd_load(ndp, tcppa->tcp_param_name,
8619 			    tcp_param_get, tcp_param_set,
8620 			    (caddr_t)tcppa)) {
8621 				nd_free(ndp);
8622 				return (B_FALSE);
8623 			}
8624 		}
8625 	}
8626 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
8627 	    KM_SLEEP);
8628 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
8629 	    sizeof (tcpparam_t));
8630 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
8631 	    tcp_param_get, tcp_param_set_aligned,
8632 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
8633 		nd_free(ndp);
8634 		return (B_FALSE);
8635 	}
8636 	if (!nd_load(ndp, "tcp_extra_priv_ports",
8637 	    tcp_extra_priv_ports_get, NULL, NULL)) {
8638 		nd_free(ndp);
8639 		return (B_FALSE);
8640 	}
8641 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
8642 	    NULL, tcp_extra_priv_ports_add, NULL)) {
8643 		nd_free(ndp);
8644 		return (B_FALSE);
8645 	}
8646 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
8647 	    NULL, tcp_extra_priv_ports_del, NULL)) {
8648 		nd_free(ndp);
8649 		return (B_FALSE);
8650 	}
8651 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
8652 	    tcp_1948_phrase_set, NULL)) {
8653 		nd_free(ndp);
8654 		return (B_FALSE);
8655 	}
8656 	/*
8657 	 * Dummy ndd variables - only to convey obsolescence information
8658 	 * through printing of their name (no get or set routines)
8659 	 * XXX Remove in future releases ?
8660 	 */
8661 	if (!nd_load(ndp,
8662 	    "tcp_close_wait_interval(obsoleted - "
8663 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
8664 		nd_free(ndp);
8665 		return (B_FALSE);
8666 	}
8667 	return (B_TRUE);
8668 }
8669 
8670 /* ndd set routine for tcp_wroff_xtra. */
8671 /* ARGSUSED */
8672 static int
8673 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
8674     cred_t *cr)
8675 {
8676 	long new_value;
8677 	tcpparam_t *tcppa = (tcpparam_t *)cp;
8678 
8679 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8680 	    new_value < tcppa->tcp_param_min ||
8681 	    new_value > tcppa->tcp_param_max) {
8682 		return (EINVAL);
8683 	}
8684 	/*
8685 	 * Need to make sure new_value is a multiple of 4.  If it is not,
8686 	 * round it up.  For future 64 bit requirement, we actually make it
8687 	 * a multiple of 8.
8688 	 */
8689 	if (new_value & 0x7) {
8690 		new_value = (new_value & ~0x7) + 0x8;
8691 	}
8692 	tcppa->tcp_param_val = new_value;
8693 	return (0);
8694 }
8695 
8696 /* Set callback routine passed to nd_load by tcp_param_register */
8697 /* ARGSUSED */
8698 static int
8699 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
8700 {
8701 	long	new_value;
8702 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8703 
8704 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8705 	    new_value < tcppa->tcp_param_min ||
8706 	    new_value > tcppa->tcp_param_max) {
8707 		return (EINVAL);
8708 	}
8709 	tcppa->tcp_param_val = new_value;
8710 	return (0);
8711 }
8712 
8713 /*
8714  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
8715  * is filled, return as much as we can.  The message passed in may be
8716  * multi-part, chained using b_cont.  "start" is the starting sequence
8717  * number for this piece.
8718  */
8719 static mblk_t *
8720 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
8721 {
8722 	uint32_t	end;
8723 	mblk_t		*mp1;
8724 	mblk_t		*mp2;
8725 	mblk_t		*next_mp;
8726 	uint32_t	u1;
8727 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8728 
8729 
8730 	/* Walk through all the new pieces. */
8731 	do {
8732 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
8733 		    (uintptr_t)INT_MAX);
8734 		end = start + (int)(mp->b_wptr - mp->b_rptr);
8735 		next_mp = mp->b_cont;
8736 		if (start == end) {
8737 			/* Empty.  Blast it. */
8738 			freeb(mp);
8739 			continue;
8740 		}
8741 		mp->b_cont = NULL;
8742 		TCP_REASS_SET_SEQ(mp, start);
8743 		TCP_REASS_SET_END(mp, end);
8744 		mp1 = tcp->tcp_reass_tail;
8745 		if (!mp1) {
8746 			tcp->tcp_reass_tail = mp;
8747 			tcp->tcp_reass_head = mp;
8748 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
8749 			UPDATE_MIB(&tcps->tcps_mib,
8750 			    tcpInDataUnorderBytes, end - start);
8751 			continue;
8752 		}
8753 		/* New stuff completely beyond tail? */
8754 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
8755 			/* Link it on end. */
8756 			mp1->b_cont = mp;
8757 			tcp->tcp_reass_tail = mp;
8758 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
8759 			UPDATE_MIB(&tcps->tcps_mib,
8760 			    tcpInDataUnorderBytes, end - start);
8761 			continue;
8762 		}
8763 		mp1 = tcp->tcp_reass_head;
8764 		u1 = TCP_REASS_SEQ(mp1);
8765 		/* New stuff at the front? */
8766 		if (SEQ_LT(start, u1)) {
8767 			/* Yes... Check for overlap. */
8768 			mp->b_cont = mp1;
8769 			tcp->tcp_reass_head = mp;
8770 			tcp_reass_elim_overlap(tcp, mp);
8771 			continue;
8772 		}
8773 		/*
8774 		 * The new piece fits somewhere between the head and tail.
8775 		 * We find our slot, where mp1 precedes us and mp2 trails.
8776 		 */
8777 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
8778 			u1 = TCP_REASS_SEQ(mp2);
8779 			if (SEQ_LEQ(start, u1))
8780 				break;
8781 		}
8782 		/* Link ourselves in */
8783 		mp->b_cont = mp2;
8784 		mp1->b_cont = mp;
8785 
8786 		/* Trim overlap with following mblk(s) first */
8787 		tcp_reass_elim_overlap(tcp, mp);
8788 
8789 		/* Trim overlap with preceding mblk */
8790 		tcp_reass_elim_overlap(tcp, mp1);
8791 
8792 	} while (start = end, mp = next_mp);
8793 	mp1 = tcp->tcp_reass_head;
8794 	/* Anything ready to go? */
8795 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
8796 		return (NULL);
8797 	/* Eat what we can off the queue */
8798 	for (;;) {
8799 		mp = mp1->b_cont;
8800 		end = TCP_REASS_END(mp1);
8801 		TCP_REASS_SET_SEQ(mp1, 0);
8802 		TCP_REASS_SET_END(mp1, 0);
8803 		if (!mp) {
8804 			tcp->tcp_reass_tail = NULL;
8805 			break;
8806 		}
8807 		if (end != TCP_REASS_SEQ(mp)) {
8808 			mp1->b_cont = NULL;
8809 			break;
8810 		}
8811 		mp1 = mp;
8812 	}
8813 	mp1 = tcp->tcp_reass_head;
8814 	tcp->tcp_reass_head = mp;
8815 	return (mp1);
8816 }
8817 
8818 /* Eliminate any overlap that mp may have over later mblks */
8819 static void
8820 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
8821 {
8822 	uint32_t	end;
8823 	mblk_t		*mp1;
8824 	uint32_t	u1;
8825 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8826 
8827 	end = TCP_REASS_END(mp);
8828 	while ((mp1 = mp->b_cont) != NULL) {
8829 		u1 = TCP_REASS_SEQ(mp1);
8830 		if (!SEQ_GT(end, u1))
8831 			break;
8832 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
8833 			mp->b_wptr -= end - u1;
8834 			TCP_REASS_SET_END(mp, u1);
8835 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
8836 			UPDATE_MIB(&tcps->tcps_mib,
8837 			    tcpInDataPartDupBytes, end - u1);
8838 			break;
8839 		}
8840 		mp->b_cont = mp1->b_cont;
8841 		TCP_REASS_SET_SEQ(mp1, 0);
8842 		TCP_REASS_SET_END(mp1, 0);
8843 		freeb(mp1);
8844 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
8845 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
8846 	}
8847 	if (!mp1)
8848 		tcp->tcp_reass_tail = mp;
8849 }
8850 
8851 static uint_t
8852 tcp_rwnd_reopen(tcp_t *tcp)
8853 {
8854 	uint_t ret = 0;
8855 	uint_t thwin;
8856 	conn_t *connp = tcp->tcp_connp;
8857 
8858 	/* Learn the latest rwnd information that we sent to the other side. */
8859 	thwin = ((uint_t)ntohs(tcp->tcp_tcpha->tha_win))
8860 	    << tcp->tcp_rcv_ws;
8861 	/* This is peer's calculated send window (our receive window). */
8862 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
8863 	/*
8864 	 * Increase the receive window to max.  But we need to do receiver
8865 	 * SWS avoidance.  This means that we need to check the increase of
8866 	 * of receive window is at least 1 MSS.
8867 	 */
8868 	if (connp->conn_rcvbuf - thwin >= tcp->tcp_mss) {
8869 		/*
8870 		 * If the window that the other side knows is less than max
8871 		 * deferred acks segments, send an update immediately.
8872 		 */
8873 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
8874 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
8875 			ret = TH_ACK_NEEDED;
8876 		}
8877 		tcp->tcp_rwnd = connp->conn_rcvbuf;
8878 	}
8879 	return (ret);
8880 }
8881 
8882 /*
8883  * Send up all messages queued on tcp_rcv_list.
8884  */
8885 static uint_t
8886 tcp_rcv_drain(tcp_t *tcp)
8887 {
8888 	mblk_t *mp;
8889 	uint_t ret = 0;
8890 #ifdef DEBUG
8891 	uint_t cnt = 0;
8892 #endif
8893 	queue_t	*q = tcp->tcp_connp->conn_rq;
8894 
8895 	/* Can't drain on an eager connection */
8896 	if (tcp->tcp_listener != NULL)
8897 		return (ret);
8898 
8899 	/* Can't be a non-STREAMS connection */
8900 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
8901 
8902 	/* No need for the push timer now. */
8903 	if (tcp->tcp_push_tid != 0) {
8904 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
8905 		tcp->tcp_push_tid = 0;
8906 	}
8907 
8908 	/*
8909 	 * Handle two cases here: we are currently fused or we were
8910 	 * previously fused and have some urgent data to be delivered
8911 	 * upstream.  The latter happens because we either ran out of
8912 	 * memory or were detached and therefore sending the SIGURG was
8913 	 * deferred until this point.  In either case we pass control
8914 	 * over to tcp_fuse_rcv_drain() since it may need to complete
8915 	 * some work.
8916 	 */
8917 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
8918 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
8919 		    tcp->tcp_fused_sigurg_mp != NULL);
8920 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
8921 		    &tcp->tcp_fused_sigurg_mp))
8922 			return (ret);
8923 	}
8924 
8925 	while ((mp = tcp->tcp_rcv_list) != NULL) {
8926 		tcp->tcp_rcv_list = mp->b_next;
8927 		mp->b_next = NULL;
8928 #ifdef DEBUG
8929 		cnt += msgdsize(mp);
8930 #endif
8931 		/* Does this need SSL processing first? */
8932 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
8933 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
8934 			    mblk_t *, mp);
8935 			tcp_kssl_input(tcp, mp, NULL);
8936 			continue;
8937 		}
8938 		putnext(q, mp);
8939 	}
8940 #ifdef DEBUG
8941 	ASSERT(cnt == tcp->tcp_rcv_cnt);
8942 #endif
8943 	tcp->tcp_rcv_last_head = NULL;
8944 	tcp->tcp_rcv_last_tail = NULL;
8945 	tcp->tcp_rcv_cnt = 0;
8946 
8947 	if (canputnext(q))
8948 		return (tcp_rwnd_reopen(tcp));
8949 
8950 	return (ret);
8951 }
8952 
8953 /*
8954  * Queue data on tcp_rcv_list which is a b_next chain.
8955  * tcp_rcv_last_head/tail is the last element of this chain.
8956  * Each element of the chain is a b_cont chain.
8957  *
8958  * M_DATA messages are added to the current element.
8959  * Other messages are added as new (b_next) elements.
8960  */
8961 void
8962 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len, cred_t *cr)
8963 {
8964 	ASSERT(seg_len == msgdsize(mp));
8965 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
8966 
8967 	if (is_system_labeled()) {
8968 		ASSERT(cr != NULL || msg_getcred(mp, NULL) != NULL);
8969 		/*
8970 		 * Provide for protocols above TCP such as RPC. NOPID leaves
8971 		 * db_cpid unchanged.
8972 		 * The cred could have already been set.
8973 		 */
8974 		if (cr != NULL)
8975 			mblk_setcred(mp, cr, NOPID);
8976 	}
8977 
8978 	if (tcp->tcp_rcv_list == NULL) {
8979 		ASSERT(tcp->tcp_rcv_last_head == NULL);
8980 		tcp->tcp_rcv_list = mp;
8981 		tcp->tcp_rcv_last_head = mp;
8982 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
8983 		tcp->tcp_rcv_last_tail->b_cont = mp;
8984 	} else {
8985 		tcp->tcp_rcv_last_head->b_next = mp;
8986 		tcp->tcp_rcv_last_head = mp;
8987 	}
8988 
8989 	while (mp->b_cont)
8990 		mp = mp->b_cont;
8991 
8992 	tcp->tcp_rcv_last_tail = mp;
8993 	tcp->tcp_rcv_cnt += seg_len;
8994 	tcp->tcp_rwnd -= seg_len;
8995 }
8996 
8997 /* The minimum of smoothed mean deviation in RTO calculation. */
8998 #define	TCP_SD_MIN	400
8999 
9000 /*
9001  * Set RTO for this connection.  The formula is from Jacobson and Karels'
9002  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
9003  * are the same as those in Appendix A.2 of that paper.
9004  *
9005  * m = new measurement
9006  * sa = smoothed RTT average (8 * average estimates).
9007  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
9008  */
9009 static void
9010 tcp_set_rto(tcp_t *tcp, clock_t rtt)
9011 {
9012 	long m = TICK_TO_MSEC(rtt);
9013 	clock_t sa = tcp->tcp_rtt_sa;
9014 	clock_t sv = tcp->tcp_rtt_sd;
9015 	clock_t rto;
9016 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9017 
9018 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
9019 	tcp->tcp_rtt_update++;
9020 
9021 	/* tcp_rtt_sa is not 0 means this is a new sample. */
9022 	if (sa != 0) {
9023 		/*
9024 		 * Update average estimator:
9025 		 *	new rtt = 7/8 old rtt + 1/8 Error
9026 		 */
9027 
9028 		/* m is now Error in estimate. */
9029 		m -= sa >> 3;
9030 		if ((sa += m) <= 0) {
9031 			/*
9032 			 * Don't allow the smoothed average to be negative.
9033 			 * We use 0 to denote reinitialization of the
9034 			 * variables.
9035 			 */
9036 			sa = 1;
9037 		}
9038 
9039 		/*
9040 		 * Update deviation estimator:
9041 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
9042 		 */
9043 		if (m < 0)
9044 			m = -m;
9045 		m -= sv >> 2;
9046 		sv += m;
9047 	} else {
9048 		/*
9049 		 * This follows BSD's implementation.  So the reinitialized
9050 		 * RTO is 3 * m.  We cannot go less than 2 because if the
9051 		 * link is bandwidth dominated, doubling the window size
9052 		 * during slow start means doubling the RTT.  We want to be
9053 		 * more conservative when we reinitialize our estimates.  3
9054 		 * is just a convenient number.
9055 		 */
9056 		sa = m << 3;
9057 		sv = m << 1;
9058 	}
9059 	if (sv < TCP_SD_MIN) {
9060 		/*
9061 		 * We do not know that if sa captures the delay ACK
9062 		 * effect as in a long train of segments, a receiver
9063 		 * does not delay its ACKs.  So set the minimum of sv
9064 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
9065 		 * of BSD DATO.  That means the minimum of mean
9066 		 * deviation is 100 ms.
9067 		 *
9068 		 */
9069 		sv = TCP_SD_MIN;
9070 	}
9071 	tcp->tcp_rtt_sa = sa;
9072 	tcp->tcp_rtt_sd = sv;
9073 	/*
9074 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
9075 	 *
9076 	 * Add tcp_rexmit_interval extra in case of extreme environment
9077 	 * where the algorithm fails to work.  The default value of
9078 	 * tcp_rexmit_interval_extra should be 0.
9079 	 *
9080 	 * As we use a finer grained clock than BSD and update
9081 	 * RTO for every ACKs, add in another .25 of RTT to the
9082 	 * deviation of RTO to accomodate burstiness of 1/4 of
9083 	 * window size.
9084 	 */
9085 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
9086 
9087 	if (rto > tcps->tcps_rexmit_interval_max) {
9088 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
9089 	} else if (rto < tcps->tcps_rexmit_interval_min) {
9090 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
9091 	} else {
9092 		tcp->tcp_rto = rto;
9093 	}
9094 
9095 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
9096 	tcp->tcp_timer_backoff = 0;
9097 }
9098 
9099 /*
9100  * tcp_get_seg_mp() is called to get the pointer to a segment in the
9101  * send queue which starts at the given sequence number. If the given
9102  * sequence number is equal to last valid sequence number (tcp_snxt), the
9103  * returned mblk is the last valid mblk, and off is set to the length of
9104  * that mblk.
9105  *
9106  * send queue which starts at the given seq. no.
9107  *
9108  * Parameters:
9109  *	tcp_t *tcp: the tcp instance pointer.
9110  *	uint32_t seq: the starting seq. no of the requested segment.
9111  *	int32_t *off: after the execution, *off will be the offset to
9112  *		the returned mblk which points to the requested seq no.
9113  *		It is the caller's responsibility to send in a non-null off.
9114  *
9115  * Return:
9116  *	A mblk_t pointer pointing to the requested segment in send queue.
9117  */
9118 static mblk_t *
9119 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
9120 {
9121 	int32_t	cnt;
9122 	mblk_t	*mp;
9123 
9124 	/* Defensive coding.  Make sure we don't send incorrect data. */
9125 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
9126 		return (NULL);
9127 
9128 	cnt = seq - tcp->tcp_suna;
9129 	mp = tcp->tcp_xmit_head;
9130 	while (cnt > 0 && mp != NULL) {
9131 		cnt -= mp->b_wptr - mp->b_rptr;
9132 		if (cnt <= 0) {
9133 			cnt += mp->b_wptr - mp->b_rptr;
9134 			break;
9135 		}
9136 		mp = mp->b_cont;
9137 	}
9138 	ASSERT(mp != NULL);
9139 	*off = cnt;
9140 	return (mp);
9141 }
9142 
9143 /*
9144  * This function handles all retransmissions if SACK is enabled for this
9145  * connection.  First it calculates how many segments can be retransmitted
9146  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
9147  * segments.  A segment is eligible if sack_cnt for that segment is greater
9148  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
9149  * all eligible segments, it checks to see if TCP can send some new segments
9150  * (fast recovery).  If it can, set the appropriate flag for tcp_input_data().
9151  *
9152  * Parameters:
9153  *	tcp_t *tcp: the tcp structure of the connection.
9154  *	uint_t *flags: in return, appropriate value will be set for
9155  *	tcp_input_data().
9156  */
9157 static void
9158 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
9159 {
9160 	notsack_blk_t	*notsack_blk;
9161 	int32_t		usable_swnd;
9162 	int32_t		mss;
9163 	uint32_t	seg_len;
9164 	mblk_t		*xmit_mp;
9165 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9166 
9167 	ASSERT(tcp->tcp_sack_info != NULL);
9168 	ASSERT(tcp->tcp_notsack_list != NULL);
9169 	ASSERT(tcp->tcp_rexmit == B_FALSE);
9170 
9171 	/* Defensive coding in case there is a bug... */
9172 	if (tcp->tcp_notsack_list == NULL) {
9173 		return;
9174 	}
9175 	notsack_blk = tcp->tcp_notsack_list;
9176 	mss = tcp->tcp_mss;
9177 
9178 	/*
9179 	 * Limit the num of outstanding data in the network to be
9180 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
9181 	 */
9182 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9183 
9184 	/* At least retransmit 1 MSS of data. */
9185 	if (usable_swnd <= 0) {
9186 		usable_swnd = mss;
9187 	}
9188 
9189 	/* Make sure no new RTT samples will be taken. */
9190 	tcp->tcp_csuna = tcp->tcp_snxt;
9191 
9192 	notsack_blk = tcp->tcp_notsack_list;
9193 	while (usable_swnd > 0) {
9194 		mblk_t		*snxt_mp, *tmp_mp;
9195 		tcp_seq		begin = tcp->tcp_sack_snxt;
9196 		tcp_seq		end;
9197 		int32_t		off;
9198 
9199 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
9200 			if (SEQ_GT(notsack_blk->end, begin) &&
9201 			    (notsack_blk->sack_cnt >=
9202 			    tcps->tcps_dupack_fast_retransmit)) {
9203 				end = notsack_blk->end;
9204 				if (SEQ_LT(begin, notsack_blk->begin)) {
9205 					begin = notsack_blk->begin;
9206 				}
9207 				break;
9208 			}
9209 		}
9210 		/*
9211 		 * All holes are filled.  Manipulate tcp_cwnd to send more
9212 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
9213 		 * set to tcp_cwnd_ssthresh.
9214 		 */
9215 		if (notsack_blk == NULL) {
9216 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9217 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
9218 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
9219 				ASSERT(tcp->tcp_cwnd > 0);
9220 				return;
9221 			} else {
9222 				usable_swnd = usable_swnd / mss;
9223 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
9224 				    MAX(usable_swnd * mss, mss);
9225 				*flags |= TH_XMIT_NEEDED;
9226 				return;
9227 			}
9228 		}
9229 
9230 		/*
9231 		 * Note that we may send more than usable_swnd allows here
9232 		 * because of round off, but no more than 1 MSS of data.
9233 		 */
9234 		seg_len = end - begin;
9235 		if (seg_len > mss)
9236 			seg_len = mss;
9237 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
9238 		ASSERT(snxt_mp != NULL);
9239 		/* This should not happen.  Defensive coding again... */
9240 		if (snxt_mp == NULL) {
9241 			return;
9242 		}
9243 
9244 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
9245 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
9246 		if (xmit_mp == NULL)
9247 			return;
9248 
9249 		usable_swnd -= seg_len;
9250 		tcp->tcp_pipe += seg_len;
9251 		tcp->tcp_sack_snxt = begin + seg_len;
9252 
9253 		tcp_send_data(tcp, xmit_mp);
9254 
9255 		/*
9256 		 * Update the send timestamp to avoid false retransmission.
9257 		 */
9258 		snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9259 
9260 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9261 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
9262 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
9263 		/*
9264 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
9265 		 * This happens when new data sent during fast recovery is
9266 		 * also lost.  If TCP retransmits those new data, it needs
9267 		 * to extend SACK recover phase to avoid starting another
9268 		 * fast retransmit/recovery unnecessarily.
9269 		 */
9270 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
9271 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
9272 		}
9273 	}
9274 }
9275 
9276 /*
9277  * tcp_ss_rexmit() is called to do slow start retransmission after a timeout
9278  * or ICMP errors.
9279  *
9280  * To limit the number of duplicate segments, we limit the number of segment
9281  * to be sent in one time to tcp_snd_burst, the burst variable.
9282  */
9283 static void
9284 tcp_ss_rexmit(tcp_t *tcp)
9285 {
9286 	uint32_t	snxt;
9287 	uint32_t	smax;
9288 	int32_t		win;
9289 	int32_t		mss;
9290 	int32_t		off;
9291 	int32_t		burst = tcp->tcp_snd_burst;
9292 	mblk_t		*snxt_mp;
9293 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9294 
9295 	/*
9296 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
9297 	 * all unack'ed segments.
9298 	 */
9299 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
9300 		smax = tcp->tcp_rexmit_max;
9301 		snxt = tcp->tcp_rexmit_nxt;
9302 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
9303 			snxt = tcp->tcp_suna;
9304 		}
9305 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
9306 		win -= snxt - tcp->tcp_suna;
9307 		mss = tcp->tcp_mss;
9308 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
9309 
9310 		while (SEQ_LT(snxt, smax) && (win > 0) &&
9311 		    (burst > 0) && (snxt_mp != NULL)) {
9312 			mblk_t	*xmit_mp;
9313 			mblk_t	*old_snxt_mp = snxt_mp;
9314 			uint32_t cnt = mss;
9315 
9316 			if (win < cnt) {
9317 				cnt = win;
9318 			}
9319 			if (SEQ_GT(snxt + cnt, smax)) {
9320 				cnt = smax - snxt;
9321 			}
9322 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
9323 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
9324 			if (xmit_mp == NULL)
9325 				return;
9326 
9327 			tcp_send_data(tcp, xmit_mp);
9328 
9329 			snxt += cnt;
9330 			win -= cnt;
9331 			/*
9332 			 * Update the send timestamp to avoid false
9333 			 * retransmission.
9334 			 */
9335 			old_snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9336 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9337 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
9338 
9339 			tcp->tcp_rexmit_nxt = snxt;
9340 			burst--;
9341 		}
9342 		/*
9343 		 * If we have transmitted all we have at the time
9344 		 * we started the retranmission, we can leave
9345 		 * the rest of the job to tcp_wput_data().  But we
9346 		 * need to check the send window first.  If the
9347 		 * win is not 0, go on with tcp_wput_data().
9348 		 */
9349 		if (SEQ_LT(snxt, smax) || win == 0) {
9350 			return;
9351 		}
9352 	}
9353 	/* Only call tcp_wput_data() if there is data to be sent. */
9354 	if (tcp->tcp_unsent) {
9355 		tcp_wput_data(tcp, NULL, B_FALSE);
9356 	}
9357 }
9358 
9359 /*
9360  * Process all TCP option in SYN segment.  Note that this function should
9361  * be called after tcp_set_destination() is called so that the necessary info
9362  * from IRE is already set in the tcp structure.
9363  *
9364  * This function sets up the correct tcp_mss value according to the
9365  * MSS option value and our header size.  It also sets up the window scale
9366  * and timestamp values, and initialize SACK info blocks.  But it does not
9367  * change receive window size after setting the tcp_mss value.  The caller
9368  * should do the appropriate change.
9369  */
9370 void
9371 tcp_process_options(tcp_t *tcp, tcpha_t *tcpha)
9372 {
9373 	int options;
9374 	tcp_opt_t tcpopt;
9375 	uint32_t mss_max;
9376 	char *tmp_tcph;
9377 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9378 	conn_t		*connp = tcp->tcp_connp;
9379 
9380 	tcpopt.tcp = NULL;
9381 	options = tcp_parse_options(tcpha, &tcpopt);
9382 
9383 	/*
9384 	 * Process MSS option.  Note that MSS option value does not account
9385 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
9386 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
9387 	 * IPv6.
9388 	 */
9389 	if (!(options & TCP_OPT_MSS_PRESENT)) {
9390 		if (connp->conn_ipversion == IPV4_VERSION)
9391 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
9392 		else
9393 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
9394 	} else {
9395 		if (connp->conn_ipversion == IPV4_VERSION)
9396 			mss_max = tcps->tcps_mss_max_ipv4;
9397 		else
9398 			mss_max = tcps->tcps_mss_max_ipv6;
9399 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
9400 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
9401 		else if (tcpopt.tcp_opt_mss > mss_max)
9402 			tcpopt.tcp_opt_mss = mss_max;
9403 	}
9404 
9405 	/* Process Window Scale option. */
9406 	if (options & TCP_OPT_WSCALE_PRESENT) {
9407 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
9408 		tcp->tcp_snd_ws_ok = B_TRUE;
9409 	} else {
9410 		tcp->tcp_snd_ws = B_FALSE;
9411 		tcp->tcp_snd_ws_ok = B_FALSE;
9412 		tcp->tcp_rcv_ws = B_FALSE;
9413 	}
9414 
9415 	/* Process Timestamp option. */
9416 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
9417 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
9418 		tmp_tcph = (char *)tcp->tcp_tcpha;
9419 
9420 		tcp->tcp_snd_ts_ok = B_TRUE;
9421 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
9422 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
9423 		ASSERT(OK_32PTR(tmp_tcph));
9424 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
9425 
9426 		/* Fill in our template header with basic timestamp option. */
9427 		tmp_tcph += connp->conn_ht_ulp_len;
9428 		tmp_tcph[0] = TCPOPT_NOP;
9429 		tmp_tcph[1] = TCPOPT_NOP;
9430 		tmp_tcph[2] = TCPOPT_TSTAMP;
9431 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
9432 		connp->conn_ht_iphc_len += TCPOPT_REAL_TS_LEN;
9433 		connp->conn_ht_ulp_len += TCPOPT_REAL_TS_LEN;
9434 		tcp->tcp_tcpha->tha_offset_and_reserved += (3 << 4);
9435 	} else {
9436 		tcp->tcp_snd_ts_ok = B_FALSE;
9437 	}
9438 
9439 	/*
9440 	 * Process SACK options.  If SACK is enabled for this connection,
9441 	 * then allocate the SACK info structure.  Note the following ways
9442 	 * when tcp_snd_sack_ok is set to true.
9443 	 *
9444 	 * For active connection: in tcp_set_destination() called in
9445 	 * tcp_connect().
9446 	 *
9447 	 * For passive connection: in tcp_set_destination() called in
9448 	 * tcp_input_listener().
9449 	 *
9450 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
9451 	 * That check makes sure that if we did not send a SACK OK option,
9452 	 * we will not enable SACK for this connection even though the other
9453 	 * side sends us SACK OK option.  For active connection, the SACK
9454 	 * info structure has already been allocated.  So we need to free
9455 	 * it if SACK is disabled.
9456 	 */
9457 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
9458 	    (tcp->tcp_snd_sack_ok ||
9459 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
9460 		/* This should be true only in the passive case. */
9461 		if (tcp->tcp_sack_info == NULL) {
9462 			ASSERT(TCP_IS_DETACHED(tcp));
9463 			tcp->tcp_sack_info =
9464 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
9465 		}
9466 		if (tcp->tcp_sack_info == NULL) {
9467 			tcp->tcp_snd_sack_ok = B_FALSE;
9468 		} else {
9469 			tcp->tcp_snd_sack_ok = B_TRUE;
9470 			if (tcp->tcp_snd_ts_ok) {
9471 				tcp->tcp_max_sack_blk = 3;
9472 			} else {
9473 				tcp->tcp_max_sack_blk = 4;
9474 			}
9475 		}
9476 	} else {
9477 		/*
9478 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
9479 		 * no SACK info will be used for this
9480 		 * connection.  This assumes that SACK usage
9481 		 * permission is negotiated.  This may need
9482 		 * to be changed once this is clarified.
9483 		 */
9484 		if (tcp->tcp_sack_info != NULL) {
9485 			ASSERT(tcp->tcp_notsack_list == NULL);
9486 			kmem_cache_free(tcp_sack_info_cache,
9487 			    tcp->tcp_sack_info);
9488 			tcp->tcp_sack_info = NULL;
9489 		}
9490 		tcp->tcp_snd_sack_ok = B_FALSE;
9491 	}
9492 
9493 	/*
9494 	 * Now we know the exact TCP/IP header length, subtract
9495 	 * that from tcp_mss to get our side's MSS.
9496 	 */
9497 	tcp->tcp_mss -= connp->conn_ht_iphc_len;
9498 
9499 	/*
9500 	 * Here we assume that the other side's header size will be equal to
9501 	 * our header size.  We calculate the real MSS accordingly.  Need to
9502 	 * take into additional stuffs IPsec puts in.
9503 	 *
9504 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
9505 	 */
9506 	tcpopt.tcp_opt_mss -= connp->conn_ht_iphc_len +
9507 	    tcp->tcp_ipsec_overhead -
9508 	    ((connp->conn_ipversion == IPV4_VERSION ?
9509 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
9510 
9511 	/*
9512 	 * Set MSS to the smaller one of both ends of the connection.
9513 	 * We should not have called tcp_mss_set() before, but our
9514 	 * side of the MSS should have been set to a proper value
9515 	 * by tcp_set_destination().  tcp_mss_set() will also set up the
9516 	 * STREAM head parameters properly.
9517 	 *
9518 	 * If we have a larger-than-16-bit window but the other side
9519 	 * didn't want to do window scale, tcp_rwnd_set() will take
9520 	 * care of that.
9521 	 */
9522 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
9523 
9524 	/*
9525 	 * Initialize tcp_cwnd value. After tcp_mss_set(), tcp_mss has been
9526 	 * updated properly.
9527 	 */
9528 	SET_TCP_INIT_CWND(tcp, tcp->tcp_mss, tcps->tcps_slow_start_initial);
9529 }
9530 
9531 /*
9532  * Sends the T_CONN_IND to the listener. The caller calls this
9533  * functions via squeue to get inside the listener's perimeter
9534  * once the 3 way hand shake is done a T_CONN_IND needs to be
9535  * sent. As an optimization, the caller can call this directly
9536  * if listener's perimeter is same as eager's.
9537  */
9538 /* ARGSUSED */
9539 void
9540 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
9541 {
9542 	conn_t			*lconnp = (conn_t *)arg;
9543 	tcp_t			*listener = lconnp->conn_tcp;
9544 	tcp_t			*tcp;
9545 	struct T_conn_ind	*conn_ind;
9546 	ipaddr_t 		*addr_cache;
9547 	boolean_t		need_send_conn_ind = B_FALSE;
9548 	tcp_stack_t		*tcps = listener->tcp_tcps;
9549 
9550 	/* retrieve the eager */
9551 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
9552 	ASSERT(conn_ind->OPT_offset != 0 &&
9553 	    conn_ind->OPT_length == sizeof (intptr_t));
9554 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
9555 	    conn_ind->OPT_length);
9556 
9557 	/*
9558 	 * TLI/XTI applications will get confused by
9559 	 * sending eager as an option since it violates
9560 	 * the option semantics. So remove the eager as
9561 	 * option since TLI/XTI app doesn't need it anyway.
9562 	 */
9563 	if (!TCP_IS_SOCKET(listener)) {
9564 		conn_ind->OPT_length = 0;
9565 		conn_ind->OPT_offset = 0;
9566 	}
9567 	if (listener->tcp_state != TCPS_LISTEN) {
9568 		/*
9569 		 * If listener has closed, it would have caused a
9570 		 * a cleanup/blowoff to happen for the eager. We
9571 		 * just need to return.
9572 		 */
9573 		freemsg(mp);
9574 		return;
9575 	}
9576 
9577 
9578 	/*
9579 	 * if the conn_req_q is full defer passing up the
9580 	 * T_CONN_IND until space is availabe after t_accept()
9581 	 * processing
9582 	 */
9583 	mutex_enter(&listener->tcp_eager_lock);
9584 
9585 	/*
9586 	 * Take the eager out, if it is in the list of droppable eagers
9587 	 * as we are here because the 3W handshake is over.
9588 	 */
9589 	MAKE_UNDROPPABLE(tcp);
9590 
9591 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
9592 		tcp_t *tail;
9593 
9594 		/*
9595 		 * The eager already has an extra ref put in tcp_input_data
9596 		 * so that it stays till accept comes back even though it
9597 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
9598 		 */
9599 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
9600 		listener->tcp_conn_req_cnt_q0--;
9601 		listener->tcp_conn_req_cnt_q++;
9602 
9603 		/* Move from SYN_RCVD to ESTABLISHED list  */
9604 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9605 		    tcp->tcp_eager_prev_q0;
9606 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9607 		    tcp->tcp_eager_next_q0;
9608 		tcp->tcp_eager_prev_q0 = NULL;
9609 		tcp->tcp_eager_next_q0 = NULL;
9610 
9611 		/*
9612 		 * Insert at end of the queue because sockfs
9613 		 * sends down T_CONN_RES in chronological
9614 		 * order. Leaving the older conn indications
9615 		 * at front of the queue helps reducing search
9616 		 * time.
9617 		 */
9618 		tail = listener->tcp_eager_last_q;
9619 		if (tail != NULL)
9620 			tail->tcp_eager_next_q = tcp;
9621 		else
9622 			listener->tcp_eager_next_q = tcp;
9623 		listener->tcp_eager_last_q = tcp;
9624 		tcp->tcp_eager_next_q = NULL;
9625 		/*
9626 		 * Delay sending up the T_conn_ind until we are
9627 		 * done with the eager. Once we have have sent up
9628 		 * the T_conn_ind, the accept can potentially complete
9629 		 * any time and release the refhold we have on the eager.
9630 		 */
9631 		need_send_conn_ind = B_TRUE;
9632 	} else {
9633 		/*
9634 		 * Defer connection on q0 and set deferred
9635 		 * connection bit true
9636 		 */
9637 		tcp->tcp_conn_def_q0 = B_TRUE;
9638 
9639 		/* take tcp out of q0 ... */
9640 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9641 		    tcp->tcp_eager_next_q0;
9642 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9643 		    tcp->tcp_eager_prev_q0;
9644 
9645 		/* ... and place it at the end of q0 */
9646 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
9647 		tcp->tcp_eager_next_q0 = listener;
9648 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
9649 		listener->tcp_eager_prev_q0 = tcp;
9650 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
9651 	}
9652 
9653 	/* we have timed out before */
9654 	if (tcp->tcp_syn_rcvd_timeout != 0) {
9655 		tcp->tcp_syn_rcvd_timeout = 0;
9656 		listener->tcp_syn_rcvd_timeout--;
9657 		if (listener->tcp_syn_defense &&
9658 		    listener->tcp_syn_rcvd_timeout <=
9659 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
9660 		    10*MINUTES < TICK_TO_MSEC(ddi_get_lbolt64() -
9661 		    listener->tcp_last_rcv_lbolt)) {
9662 			/*
9663 			 * Turn off the defense mode if we
9664 			 * believe the SYN attack is over.
9665 			 */
9666 			listener->tcp_syn_defense = B_FALSE;
9667 			if (listener->tcp_ip_addr_cache) {
9668 				kmem_free((void *)listener->tcp_ip_addr_cache,
9669 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
9670 				listener->tcp_ip_addr_cache = NULL;
9671 			}
9672 		}
9673 	}
9674 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
9675 	if (addr_cache != NULL) {
9676 		/*
9677 		 * We have finished a 3-way handshake with this
9678 		 * remote host. This proves the IP addr is good.
9679 		 * Cache it!
9680 		 */
9681 		addr_cache[IP_ADDR_CACHE_HASH(tcp->tcp_connp->conn_faddr_v4)] =
9682 		    tcp->tcp_connp->conn_faddr_v4;
9683 	}
9684 	mutex_exit(&listener->tcp_eager_lock);
9685 	if (need_send_conn_ind)
9686 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
9687 }
9688 
9689 /*
9690  * Send the newconn notification to ulp. The eager is blown off if the
9691  * notification fails.
9692  */
9693 static void
9694 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
9695 {
9696 	if (IPCL_IS_NONSTR(lconnp)) {
9697 		cred_t	*cr;
9698 		pid_t	cpid = NOPID;
9699 
9700 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
9701 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
9702 		    lconnp->conn_tcp);
9703 
9704 		cr = msg_getcred(mp, &cpid);
9705 
9706 		/* Keep the message around in case of a fallback to TPI */
9707 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
9708 		/*
9709 		 * Notify the ULP about the newconn. It is guaranteed that no
9710 		 * tcp_accept() call will be made for the eager if the
9711 		 * notification fails, so it's safe to blow it off in that
9712 		 * case.
9713 		 *
9714 		 * The upper handle will be assigned when tcp_accept() is
9715 		 * called.
9716 		 */
9717 		if ((*lconnp->conn_upcalls->su_newconn)
9718 		    (lconnp->conn_upper_handle,
9719 		    (sock_lower_handle_t)econnp,
9720 		    &sock_tcp_downcalls, cr, cpid,
9721 		    &econnp->conn_upcalls) == NULL) {
9722 			/* Failed to allocate a socket */
9723 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
9724 			    tcpEstabResets);
9725 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
9726 			    econnp->conn_tcp->tcp_conn_req_seqnum);
9727 		}
9728 	} else {
9729 		putnext(lconnp->conn_rq, mp);
9730 	}
9731 }
9732 
9733 /*
9734  * Handle a packet that has been reclassified by TCP.
9735  * This function drops the ref on connp that the caller had.
9736  */
9737 static void
9738 tcp_reinput(conn_t *connp, mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst)
9739 {
9740 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
9741 
9742 	if (connp->conn_incoming_ifindex != 0 &&
9743 	    connp->conn_incoming_ifindex != ira->ira_ruifindex) {
9744 		freemsg(mp);
9745 		CONN_DEC_REF(connp);
9746 		return;
9747 	}
9748 
9749 	if (CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss) ||
9750 	    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
9751 		ip6_t *ip6h;
9752 		ipha_t *ipha;
9753 
9754 		if (ira->ira_flags & IRAF_IS_IPV4) {
9755 			ipha = (ipha_t *)mp->b_rptr;
9756 			ip6h = NULL;
9757 		} else {
9758 			ipha = NULL;
9759 			ip6h = (ip6_t *)mp->b_rptr;
9760 		}
9761 		mp = ipsec_check_inbound_policy(mp, connp, ipha, ip6h, ira);
9762 		if (mp == NULL) {
9763 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9764 			/* Note that mp is NULL */
9765 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
9766 			CONN_DEC_REF(connp);
9767 			return;
9768 		}
9769 	}
9770 
9771 	if (IPCL_IS_TCP(connp)) {
9772 		/*
9773 		 * do not drain, certain use cases can blow
9774 		 * the stack
9775 		 */
9776 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
9777 		    connp->conn_recv, connp, ira,
9778 		    SQ_NODRAIN, SQTAG_IP_TCP_INPUT);
9779 	} else {
9780 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
9781 		(connp->conn_recv)(connp, mp, NULL,
9782 		    ira);
9783 		CONN_DEC_REF(connp);
9784 	}
9785 
9786 }
9787 
9788 boolean_t tcp_outbound_squeue_switch = B_FALSE;
9789 
9790 /*
9791  * Handle M_DATA messages from IP. Its called directly from IP via
9792  * squeue for received IP packets.
9793  *
9794  * The first argument is always the connp/tcp to which the mp belongs.
9795  * There are no exceptions to this rule. The caller has already put
9796  * a reference on this connp/tcp and once tcp_input_data() returns,
9797  * the squeue will do the refrele.
9798  *
9799  * The TH_SYN for the listener directly go to tcp_input_listener via
9800  * squeue. ICMP errors go directly to tcp_icmp_input().
9801  *
9802  * sqp: NULL = recursive, sqp != NULL means called from squeue
9803  */
9804 void
9805 tcp_input_data(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
9806 {
9807 	int32_t		bytes_acked;
9808 	int32_t		gap;
9809 	mblk_t		*mp1;
9810 	uint_t		flags;
9811 	uint32_t	new_swnd = 0;
9812 	uchar_t		*iphdr;
9813 	uchar_t		*rptr;
9814 	int32_t		rgap;
9815 	uint32_t	seg_ack;
9816 	int		seg_len;
9817 	uint_t		ip_hdr_len;
9818 	uint32_t	seg_seq;
9819 	tcpha_t		*tcpha;
9820 	int		urp;
9821 	tcp_opt_t	tcpopt;
9822 	ip_pkt_t	ipp;
9823 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
9824 	uint32_t	cwnd;
9825 	uint32_t	add;
9826 	int		npkt;
9827 	int		mss;
9828 	conn_t		*connp = (conn_t *)arg;
9829 	squeue_t	*sqp = (squeue_t *)arg2;
9830 	tcp_t		*tcp = connp->conn_tcp;
9831 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9832 
9833 	/*
9834 	 * RST from fused tcp loopback peer should trigger an unfuse.
9835 	 */
9836 	if (tcp->tcp_fused) {
9837 		TCP_STAT(tcps, tcp_fusion_aborted);
9838 		tcp_unfuse(tcp);
9839 	}
9840 
9841 	iphdr = mp->b_rptr;
9842 	rptr = mp->b_rptr;
9843 	ASSERT(OK_32PTR(rptr));
9844 
9845 	ip_hdr_len = ira->ira_ip_hdr_length;
9846 	if (connp->conn_recv_ancillary.crb_all != 0) {
9847 		/*
9848 		 * Record packet information in the ip_pkt_t
9849 		 */
9850 		ipp.ipp_fields = 0;
9851 		if (ira->ira_flags & IRAF_IS_IPV4) {
9852 			(void) ip_find_hdr_v4((ipha_t *)rptr, &ipp,
9853 			    B_FALSE);
9854 		} else {
9855 			uint8_t nexthdrp;
9856 
9857 			/*
9858 			 * IPv6 packets can only be received by applications
9859 			 * that are prepared to receive IPv6 addresses.
9860 			 * The IP fanout must ensure this.
9861 			 */
9862 			ASSERT(connp->conn_family == AF_INET6);
9863 
9864 			(void) ip_find_hdr_v6(mp, (ip6_t *)rptr, B_TRUE, &ipp,
9865 			    &nexthdrp);
9866 			ASSERT(nexthdrp == IPPROTO_TCP);
9867 
9868 			/* Could have caused a pullup? */
9869 			iphdr = mp->b_rptr;
9870 			rptr = mp->b_rptr;
9871 		}
9872 	}
9873 	ASSERT(DB_TYPE(mp) == M_DATA);
9874 	ASSERT(mp->b_next == NULL);
9875 
9876 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
9877 	seg_seq = ntohl(tcpha->tha_seq);
9878 	seg_ack = ntohl(tcpha->tha_ack);
9879 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
9880 	seg_len = (int)(mp->b_wptr - rptr) -
9881 	    (ip_hdr_len + TCP_HDR_LENGTH(tcpha));
9882 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
9883 		do {
9884 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
9885 			    (uintptr_t)INT_MAX);
9886 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
9887 		} while ((mp1 = mp1->b_cont) != NULL &&
9888 		    mp1->b_datap->db_type == M_DATA);
9889 	}
9890 
9891 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
9892 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
9893 		    seg_len, tcpha, ira);
9894 		return;
9895 	}
9896 
9897 	if (sqp != NULL) {
9898 		/*
9899 		 * This is the correct place to update tcp_last_recv_time. Note
9900 		 * that it is also updated for tcp structure that belongs to
9901 		 * global and listener queues which do not really need updating.
9902 		 * But that should not cause any harm.  And it is updated for
9903 		 * all kinds of incoming segments, not only for data segments.
9904 		 */
9905 		tcp->tcp_last_recv_time = LBOLT_FASTPATH;
9906 	}
9907 
9908 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
9909 
9910 	BUMP_LOCAL(tcp->tcp_ibsegs);
9911 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
9912 
9913 	if ((flags & TH_URG) && sqp != NULL) {
9914 		/*
9915 		 * TCP can't handle urgent pointers that arrive before
9916 		 * the connection has been accept()ed since it can't
9917 		 * buffer OOB data.  Discard segment if this happens.
9918 		 *
9919 		 * We can't just rely on a non-null tcp_listener to indicate
9920 		 * that the accept() has completed since unlinking of the
9921 		 * eager and completion of the accept are not atomic.
9922 		 * tcp_detached, when it is not set (B_FALSE) indicates
9923 		 * that the accept() has completed.
9924 		 *
9925 		 * Nor can it reassemble urgent pointers, so discard
9926 		 * if it's not the next segment expected.
9927 		 *
9928 		 * Otherwise, collapse chain into one mblk (discard if
9929 		 * that fails).  This makes sure the headers, retransmitted
9930 		 * data, and new data all are in the same mblk.
9931 		 */
9932 		ASSERT(mp != NULL);
9933 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
9934 			freemsg(mp);
9935 			return;
9936 		}
9937 		/* Update pointers into message */
9938 		iphdr = rptr = mp->b_rptr;
9939 		tcpha = (tcpha_t *)&rptr[ip_hdr_len];
9940 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
9941 			/*
9942 			 * Since we can't handle any data with this urgent
9943 			 * pointer that is out of sequence, we expunge
9944 			 * the data.  This allows us to still register
9945 			 * the urgent mark and generate the M_PCSIG,
9946 			 * which we can do.
9947 			 */
9948 			mp->b_wptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
9949 			seg_len = 0;
9950 		}
9951 	}
9952 
9953 	switch (tcp->tcp_state) {
9954 	case TCPS_SYN_SENT:
9955 		if (connp->conn_final_sqp == NULL &&
9956 		    tcp_outbound_squeue_switch && sqp != NULL) {
9957 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
9958 			connp->conn_final_sqp = sqp;
9959 			if (connp->conn_final_sqp != connp->conn_sqp) {
9960 				DTRACE_PROBE1(conn__final__sqp__switch,
9961 				    conn_t *, connp);
9962 				CONN_INC_REF(connp);
9963 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
9964 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
9965 				    tcp_input_data, connp, ira, ip_squeue_flag,
9966 				    SQTAG_CONNECT_FINISH);
9967 				return;
9968 			}
9969 			DTRACE_PROBE1(conn__final__sqp__same, conn_t *, connp);
9970 		}
9971 		if (flags & TH_ACK) {
9972 			/*
9973 			 * Note that our stack cannot send data before a
9974 			 * connection is established, therefore the
9975 			 * following check is valid.  Otherwise, it has
9976 			 * to be changed.
9977 			 */
9978 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
9979 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
9980 				freemsg(mp);
9981 				if (flags & TH_RST)
9982 					return;
9983 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
9984 				    tcp, seg_ack, 0, TH_RST);
9985 				return;
9986 			}
9987 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
9988 		}
9989 		if (flags & TH_RST) {
9990 			freemsg(mp);
9991 			if (flags & TH_ACK)
9992 				(void) tcp_clean_death(tcp,
9993 				    ECONNREFUSED, 13);
9994 			return;
9995 		}
9996 		if (!(flags & TH_SYN)) {
9997 			freemsg(mp);
9998 			return;
9999 		}
10000 
10001 		/* Process all TCP options. */
10002 		tcp_process_options(tcp, tcpha);
10003 		/*
10004 		 * The following changes our rwnd to be a multiple of the
10005 		 * MIN(peer MSS, our MSS) for performance reason.
10006 		 */
10007 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(connp->conn_rcvbuf,
10008 		    tcp->tcp_mss));
10009 
10010 		/* Is the other end ECN capable? */
10011 		if (tcp->tcp_ecn_ok) {
10012 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
10013 				tcp->tcp_ecn_ok = B_FALSE;
10014 			}
10015 		}
10016 		/*
10017 		 * Clear ECN flags because it may interfere with later
10018 		 * processing.
10019 		 */
10020 		flags &= ~(TH_ECE|TH_CWR);
10021 
10022 		tcp->tcp_irs = seg_seq;
10023 		tcp->tcp_rack = seg_seq;
10024 		tcp->tcp_rnxt = seg_seq + 1;
10025 		tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10026 		if (!TCP_IS_DETACHED(tcp)) {
10027 			/* Allocate room for SACK options if needed. */
10028 			connp->conn_wroff = connp->conn_ht_iphc_len;
10029 			if (tcp->tcp_snd_sack_ok)
10030 				connp->conn_wroff += TCPOPT_MAX_SACK_LEN;
10031 			if (!tcp->tcp_loopback)
10032 				connp->conn_wroff += tcps->tcps_wroff_xtra;
10033 
10034 			(void) proto_set_tx_wroff(connp->conn_rq, connp,
10035 			    connp->conn_wroff);
10036 		}
10037 		if (flags & TH_ACK) {
10038 			/*
10039 			 * If we can't get the confirmation upstream, pretend
10040 			 * we didn't even see this one.
10041 			 *
10042 			 * XXX: how can we pretend we didn't see it if we
10043 			 * have updated rnxt et. al.
10044 			 *
10045 			 * For loopback we defer sending up the T_CONN_CON
10046 			 * until after some checks below.
10047 			 */
10048 			mp1 = NULL;
10049 			/*
10050 			 * tcp_sendmsg() checks tcp_state without entering
10051 			 * the squeue so tcp_state should be updated before
10052 			 * sending up connection confirmation
10053 			 */
10054 			tcp->tcp_state = TCPS_ESTABLISHED;
10055 			if (!tcp_conn_con(tcp, iphdr, mp,
10056 			    tcp->tcp_loopback ? &mp1 : NULL, ira)) {
10057 				tcp->tcp_state = TCPS_SYN_SENT;
10058 				freemsg(mp);
10059 				return;
10060 			}
10061 			/* SYN was acked - making progress */
10062 			tcp->tcp_ip_forward_progress = B_TRUE;
10063 
10064 			/* One for the SYN */
10065 			tcp->tcp_suna = tcp->tcp_iss + 1;
10066 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
10067 
10068 			/*
10069 			 * If SYN was retransmitted, need to reset all
10070 			 * retransmission info.  This is because this
10071 			 * segment will be treated as a dup ACK.
10072 			 */
10073 			if (tcp->tcp_rexmit) {
10074 				tcp->tcp_rexmit = B_FALSE;
10075 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
10076 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
10077 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
10078 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
10079 				tcp->tcp_ms_we_have_waited = 0;
10080 
10081 				/*
10082 				 * Set tcp_cwnd back to 1 MSS, per
10083 				 * recommendation from
10084 				 * draft-floyd-incr-init-win-01.txt,
10085 				 * Increasing TCP's Initial Window.
10086 				 */
10087 				tcp->tcp_cwnd = tcp->tcp_mss;
10088 			}
10089 
10090 			tcp->tcp_swl1 = seg_seq;
10091 			tcp->tcp_swl2 = seg_ack;
10092 
10093 			new_swnd = ntohs(tcpha->tha_win);
10094 			tcp->tcp_swnd = new_swnd;
10095 			if (new_swnd > tcp->tcp_max_swnd)
10096 				tcp->tcp_max_swnd = new_swnd;
10097 
10098 			/*
10099 			 * Always send the three-way handshake ack immediately
10100 			 * in order to make the connection complete as soon as
10101 			 * possible on the accepting host.
10102 			 */
10103 			flags |= TH_ACK_NEEDED;
10104 
10105 			/*
10106 			 * Special case for loopback.  At this point we have
10107 			 * received SYN-ACK from the remote endpoint.  In
10108 			 * order to ensure that both endpoints reach the
10109 			 * fused state prior to any data exchange, the final
10110 			 * ACK needs to be sent before we indicate T_CONN_CON
10111 			 * to the module upstream.
10112 			 */
10113 			if (tcp->tcp_loopback) {
10114 				mblk_t *ack_mp;
10115 
10116 				ASSERT(!tcp->tcp_unfusable);
10117 				ASSERT(mp1 != NULL);
10118 				/*
10119 				 * For loopback, we always get a pure SYN-ACK
10120 				 * and only need to send back the final ACK
10121 				 * with no data (this is because the other
10122 				 * tcp is ours and we don't do T/TCP).  This
10123 				 * final ACK triggers the passive side to
10124 				 * perform fusion in ESTABLISHED state.
10125 				 */
10126 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
10127 					if (tcp->tcp_ack_tid != 0) {
10128 						(void) TCP_TIMER_CANCEL(tcp,
10129 						    tcp->tcp_ack_tid);
10130 						tcp->tcp_ack_tid = 0;
10131 					}
10132 					tcp_send_data(tcp, ack_mp);
10133 					BUMP_LOCAL(tcp->tcp_obsegs);
10134 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
10135 
10136 					if (!IPCL_IS_NONSTR(connp)) {
10137 						/* Send up T_CONN_CON */
10138 						if (ira->ira_cred != NULL) {
10139 							mblk_setcred(mp1,
10140 							    ira->ira_cred,
10141 							    ira->ira_cpid);
10142 						}
10143 						putnext(connp->conn_rq, mp1);
10144 					} else {
10145 						(*connp->conn_upcalls->
10146 						    su_connected)
10147 						    (connp->conn_upper_handle,
10148 						    tcp->tcp_connid,
10149 						    ira->ira_cred,
10150 						    ira->ira_cpid);
10151 						freemsg(mp1);
10152 					}
10153 
10154 					freemsg(mp);
10155 					return;
10156 				}
10157 				/*
10158 				 * Forget fusion; we need to handle more
10159 				 * complex cases below.  Send the deferred
10160 				 * T_CONN_CON message upstream and proceed
10161 				 * as usual.  Mark this tcp as not capable
10162 				 * of fusion.
10163 				 */
10164 				TCP_STAT(tcps, tcp_fusion_unfusable);
10165 				tcp->tcp_unfusable = B_TRUE;
10166 				if (!IPCL_IS_NONSTR(connp)) {
10167 					if (ira->ira_cred != NULL) {
10168 						mblk_setcred(mp1, ira->ira_cred,
10169 						    ira->ira_cpid);
10170 					}
10171 					putnext(connp->conn_rq, mp1);
10172 				} else {
10173 					(*connp->conn_upcalls->su_connected)
10174 					    (connp->conn_upper_handle,
10175 					    tcp->tcp_connid, ira->ira_cred,
10176 					    ira->ira_cpid);
10177 					freemsg(mp1);
10178 				}
10179 			}
10180 
10181 			/*
10182 			 * Check to see if there is data to be sent.  If
10183 			 * yes, set the transmit flag.  Then check to see
10184 			 * if received data processing needs to be done.
10185 			 * If not, go straight to xmit_check.  This short
10186 			 * cut is OK as we don't support T/TCP.
10187 			 */
10188 			if (tcp->tcp_unsent)
10189 				flags |= TH_XMIT_NEEDED;
10190 
10191 			if (seg_len == 0 && !(flags & TH_URG)) {
10192 				freemsg(mp);
10193 				goto xmit_check;
10194 			}
10195 
10196 			flags &= ~TH_SYN;
10197 			seg_seq++;
10198 			break;
10199 		}
10200 		tcp->tcp_state = TCPS_SYN_RCVD;
10201 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
10202 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
10203 		if (mp1 != NULL) {
10204 			tcp_send_data(tcp, mp1);
10205 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
10206 		}
10207 		freemsg(mp);
10208 		return;
10209 	case TCPS_SYN_RCVD:
10210 		if (flags & TH_ACK) {
10211 			/*
10212 			 * In this state, a SYN|ACK packet is either bogus
10213 			 * because the other side must be ACKing our SYN which
10214 			 * indicates it has seen the ACK for their SYN and
10215 			 * shouldn't retransmit it or we're crossing SYNs
10216 			 * on active open.
10217 			 */
10218 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
10219 				freemsg(mp);
10220 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
10221 				    tcp, seg_ack, 0, TH_RST);
10222 				return;
10223 			}
10224 			/*
10225 			 * NOTE: RFC 793 pg. 72 says this should be
10226 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
10227 			 * but that would mean we have an ack that ignored
10228 			 * our SYN.
10229 			 */
10230 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
10231 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10232 				freemsg(mp);
10233 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
10234 				    tcp, seg_ack, 0, TH_RST);
10235 				return;
10236 			}
10237 		}
10238 		break;
10239 	case TCPS_LISTEN:
10240 		/*
10241 		 * Only a TLI listener can come through this path when a
10242 		 * acceptor is going back to be a listener and a packet
10243 		 * for the acceptor hits the classifier. For a socket
10244 		 * listener, this can never happen because a listener
10245 		 * can never accept connection on itself and hence a
10246 		 * socket acceptor can not go back to being a listener.
10247 		 */
10248 		ASSERT(!TCP_IS_SOCKET(tcp));
10249 		/*FALLTHRU*/
10250 	case TCPS_CLOSED:
10251 	case TCPS_BOUND: {
10252 		conn_t	*new_connp;
10253 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
10254 
10255 		/*
10256 		 * Don't accept any input on a closed tcp as this TCP logically
10257 		 * does not exist on the system. Don't proceed further with
10258 		 * this TCP. For instance, this packet could trigger another
10259 		 * close of this tcp which would be disastrous for tcp_refcnt.
10260 		 * tcp_close_detached / tcp_clean_death / tcp_closei_local must
10261 		 * be called at most once on a TCP. In this case we need to
10262 		 * refeed the packet into the classifier and figure out where
10263 		 * the packet should go.
10264 		 */
10265 		new_connp = ipcl_classify(mp, ira, ipst);
10266 		if (new_connp != NULL) {
10267 			/* Drops ref on new_connp */
10268 			tcp_reinput(new_connp, mp, ira, ipst);
10269 			return;
10270 		}
10271 		/* We failed to classify. For now just drop the packet */
10272 		freemsg(mp);
10273 		return;
10274 	}
10275 	case TCPS_IDLE:
10276 		/*
10277 		 * Handle the case where the tcp_clean_death() has happened
10278 		 * on a connection (application hasn't closed yet) but a packet
10279 		 * was already queued on squeue before tcp_clean_death()
10280 		 * was processed. Calling tcp_clean_death() twice on same
10281 		 * connection can result in weird behaviour.
10282 		 */
10283 		freemsg(mp);
10284 		return;
10285 	default:
10286 		break;
10287 	}
10288 
10289 	/*
10290 	 * Already on the correct queue/perimeter.
10291 	 * If this is a detached connection and not an eager
10292 	 * connection hanging off a listener then new data
10293 	 * (past the FIN) will cause a reset.
10294 	 * We do a special check here where it
10295 	 * is out of the main line, rather than check
10296 	 * if we are detached every time we see new
10297 	 * data down below.
10298 	 */
10299 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
10300 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
10301 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
10302 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10303 
10304 		freemsg(mp);
10305 		/*
10306 		 * This could be an SSL closure alert. We're detached so just
10307 		 * acknowledge it this last time.
10308 		 */
10309 		if (tcp->tcp_kssl_ctx != NULL) {
10310 			kssl_release_ctx(tcp->tcp_kssl_ctx);
10311 			tcp->tcp_kssl_ctx = NULL;
10312 
10313 			tcp->tcp_rnxt += seg_len;
10314 			tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10315 			flags |= TH_ACK_NEEDED;
10316 			goto ack_check;
10317 		}
10318 
10319 		tcp_xmit_ctl("new data when detached", tcp,
10320 		    tcp->tcp_snxt, 0, TH_RST);
10321 		(void) tcp_clean_death(tcp, EPROTO, 12);
10322 		return;
10323 	}
10324 
10325 	mp->b_rptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10326 	urp = ntohs(tcpha->tha_urp) - TCP_OLD_URP_INTERPRETATION;
10327 	new_swnd = ntohs(tcpha->tha_win) <<
10328 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
10329 
10330 	if (tcp->tcp_snd_ts_ok) {
10331 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
10332 			/*
10333 			 * This segment is not acceptable.
10334 			 * Drop it and send back an ACK.
10335 			 */
10336 			freemsg(mp);
10337 			flags |= TH_ACK_NEEDED;
10338 			goto ack_check;
10339 		}
10340 	} else if (tcp->tcp_snd_sack_ok) {
10341 		ASSERT(tcp->tcp_sack_info != NULL);
10342 		tcpopt.tcp = tcp;
10343 		/*
10344 		 * SACK info in already updated in tcp_parse_options.  Ignore
10345 		 * all other TCP options...
10346 		 */
10347 		(void) tcp_parse_options(tcpha, &tcpopt);
10348 	}
10349 try_again:;
10350 	mss = tcp->tcp_mss;
10351 	gap = seg_seq - tcp->tcp_rnxt;
10352 	rgap = tcp->tcp_rwnd - (gap + seg_len);
10353 	/*
10354 	 * gap is the amount of sequence space between what we expect to see
10355 	 * and what we got for seg_seq.  A positive value for gap means
10356 	 * something got lost.  A negative value means we got some old stuff.
10357 	 */
10358 	if (gap < 0) {
10359 		/* Old stuff present.  Is the SYN in there? */
10360 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
10361 		    (seg_len != 0)) {
10362 			flags &= ~TH_SYN;
10363 			seg_seq++;
10364 			urp--;
10365 			/* Recompute the gaps after noting the SYN. */
10366 			goto try_again;
10367 		}
10368 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
10369 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
10370 		    (seg_len > -gap ? -gap : seg_len));
10371 		/* Remove the old stuff from seg_len. */
10372 		seg_len += gap;
10373 		/*
10374 		 * Anything left?
10375 		 * Make sure to check for unack'd FIN when rest of data
10376 		 * has been previously ack'd.
10377 		 */
10378 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
10379 			/*
10380 			 * Resets are only valid if they lie within our offered
10381 			 * window.  If the RST bit is set, we just ignore this
10382 			 * segment.
10383 			 */
10384 			if (flags & TH_RST) {
10385 				freemsg(mp);
10386 				return;
10387 			}
10388 
10389 			/*
10390 			 * The arriving of dup data packets indicate that we
10391 			 * may have postponed an ack for too long, or the other
10392 			 * side's RTT estimate is out of shape. Start acking
10393 			 * more often.
10394 			 */
10395 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
10396 			    tcp->tcp_rack_cnt >= 1 &&
10397 			    tcp->tcp_rack_abs_max > 2) {
10398 				tcp->tcp_rack_abs_max--;
10399 			}
10400 			tcp->tcp_rack_cur_max = 1;
10401 
10402 			/*
10403 			 * This segment is "unacceptable".  None of its
10404 			 * sequence space lies within our advertized window.
10405 			 *
10406 			 * Adjust seg_len to the original value for tracing.
10407 			 */
10408 			seg_len -= gap;
10409 			if (connp->conn_debug) {
10410 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
10411 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
10412 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
10413 				    "seg_len %d, rnxt %u, snxt %u, %s",
10414 				    gap, rgap, flags, seg_seq, seg_ack,
10415 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
10416 				    tcp_display(tcp, NULL,
10417 				    DISP_ADDR_AND_PORT));
10418 			}
10419 
10420 			/*
10421 			 * Arrange to send an ACK in response to the
10422 			 * unacceptable segment per RFC 793 page 69. There
10423 			 * is only one small difference between ours and the
10424 			 * acceptability test in the RFC - we accept ACK-only
10425 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
10426 			 * will be generated.
10427 			 *
10428 			 * Note that we have to ACK an ACK-only packet at least
10429 			 * for stacks that send 0-length keep-alives with
10430 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
10431 			 * section 4.2.3.6. As long as we don't ever generate
10432 			 * an unacceptable packet in response to an incoming
10433 			 * packet that is unacceptable, it should not cause
10434 			 * "ACK wars".
10435 			 */
10436 			flags |=  TH_ACK_NEEDED;
10437 
10438 			/*
10439 			 * Continue processing this segment in order to use the
10440 			 * ACK information it contains, but skip all other
10441 			 * sequence-number processing.	Processing the ACK
10442 			 * information is necessary in order to
10443 			 * re-synchronize connections that may have lost
10444 			 * synchronization.
10445 			 *
10446 			 * We clear seg_len and flag fields related to
10447 			 * sequence number processing as they are not
10448 			 * to be trusted for an unacceptable segment.
10449 			 */
10450 			seg_len = 0;
10451 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
10452 			goto process_ack;
10453 		}
10454 
10455 		/* Fix seg_seq, and chew the gap off the front. */
10456 		seg_seq = tcp->tcp_rnxt;
10457 		urp += gap;
10458 		do {
10459 			mblk_t	*mp2;
10460 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10461 			    (uintptr_t)UINT_MAX);
10462 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
10463 			if (gap > 0) {
10464 				mp->b_rptr = mp->b_wptr - gap;
10465 				break;
10466 			}
10467 			mp2 = mp;
10468 			mp = mp->b_cont;
10469 			freeb(mp2);
10470 		} while (gap < 0);
10471 		/*
10472 		 * If the urgent data has already been acknowledged, we
10473 		 * should ignore TH_URG below
10474 		 */
10475 		if (urp < 0)
10476 			flags &= ~TH_URG;
10477 	}
10478 	/*
10479 	 * rgap is the amount of stuff received out of window.  A negative
10480 	 * value is the amount out of window.
10481 	 */
10482 	if (rgap < 0) {
10483 		mblk_t	*mp2;
10484 
10485 		if (tcp->tcp_rwnd == 0) {
10486 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
10487 		} else {
10488 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
10489 			UPDATE_MIB(&tcps->tcps_mib,
10490 			    tcpInDataPastWinBytes, -rgap);
10491 		}
10492 
10493 		/*
10494 		 * seg_len does not include the FIN, so if more than
10495 		 * just the FIN is out of window, we act like we don't
10496 		 * see it.  (If just the FIN is out of window, rgap
10497 		 * will be zero and we will go ahead and acknowledge
10498 		 * the FIN.)
10499 		 */
10500 		flags &= ~TH_FIN;
10501 
10502 		/* Fix seg_len and make sure there is something left. */
10503 		seg_len += rgap;
10504 		if (seg_len <= 0) {
10505 			/*
10506 			 * Resets are only valid if they lie within our offered
10507 			 * window.  If the RST bit is set, we just ignore this
10508 			 * segment.
10509 			 */
10510 			if (flags & TH_RST) {
10511 				freemsg(mp);
10512 				return;
10513 			}
10514 
10515 			/* Per RFC 793, we need to send back an ACK. */
10516 			flags |= TH_ACK_NEEDED;
10517 
10518 			/*
10519 			 * Send SIGURG as soon as possible i.e. even
10520 			 * if the TH_URG was delivered in a window probe
10521 			 * packet (which will be unacceptable).
10522 			 *
10523 			 * We generate a signal if none has been generated
10524 			 * for this connection or if this is a new urgent
10525 			 * byte. Also send a zero-length "unmarked" message
10526 			 * to inform SIOCATMARK that this is not the mark.
10527 			 *
10528 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
10529 			 * is sent up. This plus the check for old data
10530 			 * (gap >= 0) handles the wraparound of the sequence
10531 			 * number space without having to always track the
10532 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
10533 			 * this max in its rcv_up variable).
10534 			 *
10535 			 * This prevents duplicate SIGURGS due to a "late"
10536 			 * zero-window probe when the T_EXDATA_IND has already
10537 			 * been sent up.
10538 			 */
10539 			if ((flags & TH_URG) &&
10540 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
10541 			    tcp->tcp_urp_last))) {
10542 				if (IPCL_IS_NONSTR(connp)) {
10543 					if (!TCP_IS_DETACHED(tcp)) {
10544 						(*connp->conn_upcalls->
10545 						    su_signal_oob)
10546 						    (connp->conn_upper_handle,
10547 						    urp);
10548 					}
10549 				} else {
10550 					mp1 = allocb(0, BPRI_MED);
10551 					if (mp1 == NULL) {
10552 						freemsg(mp);
10553 						return;
10554 					}
10555 					if (!TCP_IS_DETACHED(tcp) &&
10556 					    !putnextctl1(connp->conn_rq,
10557 					    M_PCSIG, SIGURG)) {
10558 						/* Try again on the rexmit. */
10559 						freemsg(mp1);
10560 						freemsg(mp);
10561 						return;
10562 					}
10563 					/*
10564 					 * If the next byte would be the mark
10565 					 * then mark with MARKNEXT else mark
10566 					 * with NOTMARKNEXT.
10567 					 */
10568 					if (gap == 0 && urp == 0)
10569 						mp1->b_flag |= MSGMARKNEXT;
10570 					else
10571 						mp1->b_flag |= MSGNOTMARKNEXT;
10572 					freemsg(tcp->tcp_urp_mark_mp);
10573 					tcp->tcp_urp_mark_mp = mp1;
10574 					flags |= TH_SEND_URP_MARK;
10575 				}
10576 				tcp->tcp_urp_last_valid = B_TRUE;
10577 				tcp->tcp_urp_last = urp + seg_seq;
10578 			}
10579 			/*
10580 			 * If this is a zero window probe, continue to
10581 			 * process the ACK part.  But we need to set seg_len
10582 			 * to 0 to avoid data processing.  Otherwise just
10583 			 * drop the segment and send back an ACK.
10584 			 */
10585 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
10586 				flags &= ~(TH_SYN | TH_URG);
10587 				seg_len = 0;
10588 				goto process_ack;
10589 			} else {
10590 				freemsg(mp);
10591 				goto ack_check;
10592 			}
10593 		}
10594 		/* Pitch out of window stuff off the end. */
10595 		rgap = seg_len;
10596 		mp2 = mp;
10597 		do {
10598 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
10599 			    (uintptr_t)INT_MAX);
10600 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
10601 			if (rgap < 0) {
10602 				mp2->b_wptr += rgap;
10603 				if ((mp1 = mp2->b_cont) != NULL) {
10604 					mp2->b_cont = NULL;
10605 					freemsg(mp1);
10606 				}
10607 				break;
10608 			}
10609 		} while ((mp2 = mp2->b_cont) != NULL);
10610 	}
10611 ok:;
10612 	/*
10613 	 * TCP should check ECN info for segments inside the window only.
10614 	 * Therefore the check should be done here.
10615 	 */
10616 	if (tcp->tcp_ecn_ok) {
10617 		if (flags & TH_CWR) {
10618 			tcp->tcp_ecn_echo_on = B_FALSE;
10619 		}
10620 		/*
10621 		 * Note that both ECN_CE and CWR can be set in the
10622 		 * same segment.  In this case, we once again turn
10623 		 * on ECN_ECHO.
10624 		 */
10625 		if (connp->conn_ipversion == IPV4_VERSION) {
10626 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
10627 
10628 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
10629 				tcp->tcp_ecn_echo_on = B_TRUE;
10630 			}
10631 		} else {
10632 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
10633 
10634 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
10635 			    htonl(IPH_ECN_CE << 20)) {
10636 				tcp->tcp_ecn_echo_on = B_TRUE;
10637 			}
10638 		}
10639 	}
10640 
10641 	/*
10642 	 * Check whether we can update tcp_ts_recent.  This test is
10643 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
10644 	 * Extensions for High Performance: An Update", Internet Draft.
10645 	 */
10646 	if (tcp->tcp_snd_ts_ok &&
10647 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
10648 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
10649 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
10650 		tcp->tcp_last_rcv_lbolt = LBOLT_FASTPATH64;
10651 	}
10652 
10653 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
10654 		/*
10655 		 * FIN in an out of order segment.  We record this in
10656 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
10657 		 * Clear the FIN so that any check on FIN flag will fail.
10658 		 * Remember that FIN also counts in the sequence number
10659 		 * space.  So we need to ack out of order FIN only segments.
10660 		 */
10661 		if (flags & TH_FIN) {
10662 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
10663 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
10664 			flags &= ~TH_FIN;
10665 			flags |= TH_ACK_NEEDED;
10666 		}
10667 		if (seg_len > 0) {
10668 			/* Fill in the SACK blk list. */
10669 			if (tcp->tcp_snd_sack_ok) {
10670 				ASSERT(tcp->tcp_sack_info != NULL);
10671 				tcp_sack_insert(tcp->tcp_sack_list,
10672 				    seg_seq, seg_seq + seg_len,
10673 				    &(tcp->tcp_num_sack_blk));
10674 			}
10675 
10676 			/*
10677 			 * Attempt reassembly and see if we have something
10678 			 * ready to go.
10679 			 */
10680 			mp = tcp_reass(tcp, mp, seg_seq);
10681 			/* Always ack out of order packets */
10682 			flags |= TH_ACK_NEEDED | TH_PUSH;
10683 			if (mp) {
10684 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10685 				    (uintptr_t)INT_MAX);
10686 				seg_len = mp->b_cont ? msgdsize(mp) :
10687 				    (int)(mp->b_wptr - mp->b_rptr);
10688 				seg_seq = tcp->tcp_rnxt;
10689 				/*
10690 				 * A gap is filled and the seq num and len
10691 				 * of the gap match that of a previously
10692 				 * received FIN, put the FIN flag back in.
10693 				 */
10694 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
10695 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
10696 					flags |= TH_FIN;
10697 					tcp->tcp_valid_bits &=
10698 					    ~TCP_OFO_FIN_VALID;
10699 				}
10700 			} else {
10701 				/*
10702 				 * Keep going even with NULL mp.
10703 				 * There may be a useful ACK or something else
10704 				 * we don't want to miss.
10705 				 *
10706 				 * But TCP should not perform fast retransmit
10707 				 * because of the ack number.  TCP uses
10708 				 * seg_len == 0 to determine if it is a pure
10709 				 * ACK.  And this is not a pure ACK.
10710 				 */
10711 				seg_len = 0;
10712 				ofo_seg = B_TRUE;
10713 			}
10714 		}
10715 	} else if (seg_len > 0) {
10716 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
10717 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
10718 		/*
10719 		 * If an out of order FIN was received before, and the seq
10720 		 * num and len of the new segment match that of the FIN,
10721 		 * put the FIN flag back in.
10722 		 */
10723 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
10724 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
10725 			flags |= TH_FIN;
10726 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
10727 		}
10728 	}
10729 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
10730 	if (flags & TH_RST) {
10731 		freemsg(mp);
10732 		switch (tcp->tcp_state) {
10733 		case TCPS_SYN_RCVD:
10734 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
10735 			break;
10736 		case TCPS_ESTABLISHED:
10737 		case TCPS_FIN_WAIT_1:
10738 		case TCPS_FIN_WAIT_2:
10739 		case TCPS_CLOSE_WAIT:
10740 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
10741 			break;
10742 		case TCPS_CLOSING:
10743 		case TCPS_LAST_ACK:
10744 			(void) tcp_clean_death(tcp, 0, 16);
10745 			break;
10746 		default:
10747 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
10748 			(void) tcp_clean_death(tcp, ENXIO, 17);
10749 			break;
10750 		}
10751 		return;
10752 	}
10753 	if (flags & TH_SYN) {
10754 		/*
10755 		 * See RFC 793, Page 71
10756 		 *
10757 		 * The seq number must be in the window as it should
10758 		 * be "fixed" above.  If it is outside window, it should
10759 		 * be already rejected.  Note that we allow seg_seq to be
10760 		 * rnxt + rwnd because we want to accept 0 window probe.
10761 		 */
10762 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
10763 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
10764 		freemsg(mp);
10765 		/*
10766 		 * If the ACK flag is not set, just use our snxt as the
10767 		 * seq number of the RST segment.
10768 		 */
10769 		if (!(flags & TH_ACK)) {
10770 			seg_ack = tcp->tcp_snxt;
10771 		}
10772 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
10773 		    TH_RST|TH_ACK);
10774 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
10775 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
10776 		return;
10777 	}
10778 	/*
10779 	 * urp could be -1 when the urp field in the packet is 0
10780 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
10781 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
10782 	 */
10783 	if (flags & TH_URG && urp >= 0) {
10784 		if (!tcp->tcp_urp_last_valid ||
10785 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
10786 			/*
10787 			 * Non-STREAMS sockets handle the urgent data a litte
10788 			 * differently from STREAMS based sockets. There is no
10789 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
10790 			 * flags to keep SIOCATMARK happy. Instead a
10791 			 * su_signal_oob upcall is made to update the mark.
10792 			 * Neither is a T_EXDATA_IND mblk needed to be
10793 			 * prepended to the urgent data. The urgent data is
10794 			 * delivered using the su_recv upcall, where we set
10795 			 * the MSG_OOB flag to indicate that it is urg data.
10796 			 *
10797 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
10798 			 * are used by non-STREAMS sockets.
10799 			 */
10800 			if (IPCL_IS_NONSTR(connp)) {
10801 				if (!TCP_IS_DETACHED(tcp)) {
10802 					(*connp->conn_upcalls->su_signal_oob)
10803 					    (connp->conn_upper_handle, urp);
10804 				}
10805 			} else {
10806 				/*
10807 				 * If we haven't generated the signal yet for
10808 				 * this urgent pointer value, do it now.  Also,
10809 				 * send up a zero-length M_DATA indicating
10810 				 * whether or not this is the mark. The latter
10811 				 * is not needed when a T_EXDATA_IND is sent up.
10812 				 * However, if there are allocation failures
10813 				 * this code relies on the sender retransmitting
10814 				 * and the socket code for determining the mark
10815 				 * should not block waiting for the peer to
10816 				 * transmit. Thus, for simplicity we always
10817 				 * send up the mark indication.
10818 				 */
10819 				mp1 = allocb(0, BPRI_MED);
10820 				if (mp1 == NULL) {
10821 					freemsg(mp);
10822 					return;
10823 				}
10824 				if (!TCP_IS_DETACHED(tcp) &&
10825 				    !putnextctl1(connp->conn_rq, M_PCSIG,
10826 				    SIGURG)) {
10827 					/* Try again on the rexmit. */
10828 					freemsg(mp1);
10829 					freemsg(mp);
10830 					return;
10831 				}
10832 				/*
10833 				 * Mark with NOTMARKNEXT for now.
10834 				 * The code below will change this to MARKNEXT
10835 				 * if we are at the mark.
10836 				 *
10837 				 * If there are allocation failures (e.g. in
10838 				 * dupmsg below) the next time tcp_rput_data
10839 				 * sees the urgent segment it will send up the
10840 				 * MSGMARKNEXT message.
10841 				 */
10842 				mp1->b_flag |= MSGNOTMARKNEXT;
10843 				freemsg(tcp->tcp_urp_mark_mp);
10844 				tcp->tcp_urp_mark_mp = mp1;
10845 				flags |= TH_SEND_URP_MARK;
10846 #ifdef DEBUG
10847 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
10848 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
10849 				    "last %x, %s",
10850 				    seg_seq, urp, tcp->tcp_urp_last,
10851 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
10852 #endif /* DEBUG */
10853 			}
10854 			tcp->tcp_urp_last_valid = B_TRUE;
10855 			tcp->tcp_urp_last = urp + seg_seq;
10856 		} else if (tcp->tcp_urp_mark_mp != NULL) {
10857 			/*
10858 			 * An allocation failure prevented the previous
10859 			 * tcp_input_data from sending up the allocated
10860 			 * MSG*MARKNEXT message - send it up this time
10861 			 * around.
10862 			 */
10863 			flags |= TH_SEND_URP_MARK;
10864 		}
10865 
10866 		/*
10867 		 * If the urgent byte is in this segment, make sure that it is
10868 		 * all by itself.  This makes it much easier to deal with the
10869 		 * possibility of an allocation failure on the T_exdata_ind.
10870 		 * Note that seg_len is the number of bytes in the segment, and
10871 		 * urp is the offset into the segment of the urgent byte.
10872 		 * urp < seg_len means that the urgent byte is in this segment.
10873 		 */
10874 		if (urp < seg_len) {
10875 			if (seg_len != 1) {
10876 				uint32_t  tmp_rnxt;
10877 				/*
10878 				 * Break it up and feed it back in.
10879 				 * Re-attach the IP header.
10880 				 */
10881 				mp->b_rptr = iphdr;
10882 				if (urp > 0) {
10883 					/*
10884 					 * There is stuff before the urgent
10885 					 * byte.
10886 					 */
10887 					mp1 = dupmsg(mp);
10888 					if (!mp1) {
10889 						/*
10890 						 * Trim from urgent byte on.
10891 						 * The rest will come back.
10892 						 */
10893 						(void) adjmsg(mp,
10894 						    urp - seg_len);
10895 						tcp_input_data(connp,
10896 						    mp, NULL, ira);
10897 						return;
10898 					}
10899 					(void) adjmsg(mp1, urp - seg_len);
10900 					/* Feed this piece back in. */
10901 					tmp_rnxt = tcp->tcp_rnxt;
10902 					tcp_input_data(connp, mp1, NULL, ira);
10903 					/*
10904 					 * If the data passed back in was not
10905 					 * processed (ie: bad ACK) sending
10906 					 * the remainder back in will cause a
10907 					 * loop. In this case, drop the
10908 					 * packet and let the sender try
10909 					 * sending a good packet.
10910 					 */
10911 					if (tmp_rnxt == tcp->tcp_rnxt) {
10912 						freemsg(mp);
10913 						return;
10914 					}
10915 				}
10916 				if (urp != seg_len - 1) {
10917 					uint32_t  tmp_rnxt;
10918 					/*
10919 					 * There is stuff after the urgent
10920 					 * byte.
10921 					 */
10922 					mp1 = dupmsg(mp);
10923 					if (!mp1) {
10924 						/*
10925 						 * Trim everything beyond the
10926 						 * urgent byte.  The rest will
10927 						 * come back.
10928 						 */
10929 						(void) adjmsg(mp,
10930 						    urp + 1 - seg_len);
10931 						tcp_input_data(connp,
10932 						    mp, NULL, ira);
10933 						return;
10934 					}
10935 					(void) adjmsg(mp1, urp + 1 - seg_len);
10936 					tmp_rnxt = tcp->tcp_rnxt;
10937 					tcp_input_data(connp, mp1, NULL, ira);
10938 					/*
10939 					 * If the data passed back in was not
10940 					 * processed (ie: bad ACK) sending
10941 					 * the remainder back in will cause a
10942 					 * loop. In this case, drop the
10943 					 * packet and let the sender try
10944 					 * sending a good packet.
10945 					 */
10946 					if (tmp_rnxt == tcp->tcp_rnxt) {
10947 						freemsg(mp);
10948 						return;
10949 					}
10950 				}
10951 				tcp_input_data(connp, mp, NULL, ira);
10952 				return;
10953 			}
10954 			/*
10955 			 * This segment contains only the urgent byte.  We
10956 			 * have to allocate the T_exdata_ind, if we can.
10957 			 */
10958 			if (IPCL_IS_NONSTR(connp)) {
10959 				int error;
10960 
10961 				(*connp->conn_upcalls->su_recv)
10962 				    (connp->conn_upper_handle, mp, seg_len,
10963 				    MSG_OOB, &error, NULL);
10964 				/*
10965 				 * We should never be in middle of a
10966 				 * fallback, the squeue guarantees that.
10967 				 */
10968 				ASSERT(error != EOPNOTSUPP);
10969 				mp = NULL;
10970 				goto update_ack;
10971 			} else if (!tcp->tcp_urp_mp) {
10972 				struct T_exdata_ind *tei;
10973 				mp1 = allocb(sizeof (struct T_exdata_ind),
10974 				    BPRI_MED);
10975 				if (!mp1) {
10976 					/*
10977 					 * Sigh... It'll be back.
10978 					 * Generate any MSG*MARK message now.
10979 					 */
10980 					freemsg(mp);
10981 					seg_len = 0;
10982 					if (flags & TH_SEND_URP_MARK) {
10983 
10984 
10985 						ASSERT(tcp->tcp_urp_mark_mp);
10986 						tcp->tcp_urp_mark_mp->b_flag &=
10987 						    ~MSGNOTMARKNEXT;
10988 						tcp->tcp_urp_mark_mp->b_flag |=
10989 						    MSGMARKNEXT;
10990 					}
10991 					goto ack_check;
10992 				}
10993 				mp1->b_datap->db_type = M_PROTO;
10994 				tei = (struct T_exdata_ind *)mp1->b_rptr;
10995 				tei->PRIM_type = T_EXDATA_IND;
10996 				tei->MORE_flag = 0;
10997 				mp1->b_wptr = (uchar_t *)&tei[1];
10998 				tcp->tcp_urp_mp = mp1;
10999 #ifdef DEBUG
11000 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11001 				    "tcp_rput: allocated exdata_ind %s",
11002 				    tcp_display(tcp, NULL,
11003 				    DISP_PORT_ONLY));
11004 #endif /* DEBUG */
11005 				/*
11006 				 * There is no need to send a separate MSG*MARK
11007 				 * message since the T_EXDATA_IND will be sent
11008 				 * now.
11009 				 */
11010 				flags &= ~TH_SEND_URP_MARK;
11011 				freemsg(tcp->tcp_urp_mark_mp);
11012 				tcp->tcp_urp_mark_mp = NULL;
11013 			}
11014 			/*
11015 			 * Now we are all set.  On the next putnext upstream,
11016 			 * tcp_urp_mp will be non-NULL and will get prepended
11017 			 * to what has to be this piece containing the urgent
11018 			 * byte.  If for any reason we abort this segment below,
11019 			 * if it comes back, we will have this ready, or it
11020 			 * will get blown off in close.
11021 			 */
11022 		} else if (urp == seg_len) {
11023 			/*
11024 			 * The urgent byte is the next byte after this sequence
11025 			 * number. If this endpoint is non-STREAMS, then there
11026 			 * is nothing to do here since the socket has already
11027 			 * been notified about the urg pointer by the
11028 			 * su_signal_oob call above.
11029 			 *
11030 			 * In case of STREAMS, some more work might be needed.
11031 			 * If there is data it is marked with MSGMARKNEXT and
11032 			 * and any tcp_urp_mark_mp is discarded since it is not
11033 			 * needed. Otherwise, if the code above just allocated
11034 			 * a zero-length tcp_urp_mark_mp message, that message
11035 			 * is tagged with MSGMARKNEXT. Sending up these
11036 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
11037 			 * even though the T_EXDATA_IND will not be sent up
11038 			 * until the urgent byte arrives.
11039 			 */
11040 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
11041 				if (seg_len != 0) {
11042 					flags |= TH_MARKNEXT_NEEDED;
11043 					freemsg(tcp->tcp_urp_mark_mp);
11044 					tcp->tcp_urp_mark_mp = NULL;
11045 					flags &= ~TH_SEND_URP_MARK;
11046 				} else if (tcp->tcp_urp_mark_mp != NULL) {
11047 					flags |= TH_SEND_URP_MARK;
11048 					tcp->tcp_urp_mark_mp->b_flag &=
11049 					    ~MSGNOTMARKNEXT;
11050 					tcp->tcp_urp_mark_mp->b_flag |=
11051 					    MSGMARKNEXT;
11052 				}
11053 			}
11054 #ifdef DEBUG
11055 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11056 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
11057 			    seg_len, flags,
11058 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11059 #endif /* DEBUG */
11060 		}
11061 #ifdef DEBUG
11062 		else {
11063 			/* Data left until we hit mark */
11064 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11065 			    "tcp_rput: URP %d bytes left, %s",
11066 			    urp - seg_len, tcp_display(tcp, NULL,
11067 			    DISP_PORT_ONLY));
11068 		}
11069 #endif /* DEBUG */
11070 	}
11071 
11072 process_ack:
11073 	if (!(flags & TH_ACK)) {
11074 		freemsg(mp);
11075 		goto xmit_check;
11076 	}
11077 	}
11078 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
11079 
11080 	if (bytes_acked > 0)
11081 		tcp->tcp_ip_forward_progress = B_TRUE;
11082 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
11083 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
11084 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
11085 			/* 3-way handshake complete - pass up the T_CONN_IND */
11086 			tcp_t	*listener = tcp->tcp_listener;
11087 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
11088 
11089 			tcp->tcp_tconnind_started = B_TRUE;
11090 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
11091 			/*
11092 			 * We are here means eager is fine but it can
11093 			 * get a TH_RST at any point between now and till
11094 			 * accept completes and disappear. We need to
11095 			 * ensure that reference to eager is valid after
11096 			 * we get out of eager's perimeter. So we do
11097 			 * an extra refhold.
11098 			 */
11099 			CONN_INC_REF(connp);
11100 
11101 			/*
11102 			 * The listener also exists because of the refhold
11103 			 * done in tcp_input_listener. Its possible that it
11104 			 * might have closed. We will check that once we
11105 			 * get inside listeners context.
11106 			 */
11107 			CONN_INC_REF(listener->tcp_connp);
11108 			if (listener->tcp_connp->conn_sqp ==
11109 			    connp->conn_sqp) {
11110 				/*
11111 				 * We optimize by not calling an SQUEUE_ENTER
11112 				 * on the listener since we know that the
11113 				 * listener and eager squeues are the same.
11114 				 * We are able to make this check safely only
11115 				 * because neither the eager nor the listener
11116 				 * can change its squeue. Only an active connect
11117 				 * can change its squeue
11118 				 */
11119 				tcp_send_conn_ind(listener->tcp_connp, mp,
11120 				    listener->tcp_connp->conn_sqp);
11121 				CONN_DEC_REF(listener->tcp_connp);
11122 			} else if (!tcp->tcp_loopback) {
11123 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11124 				    mp, tcp_send_conn_ind,
11125 				    listener->tcp_connp, NULL, SQ_FILL,
11126 				    SQTAG_TCP_CONN_IND);
11127 			} else {
11128 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11129 				    mp, tcp_send_conn_ind,
11130 				    listener->tcp_connp, NULL, SQ_PROCESS,
11131 				    SQTAG_TCP_CONN_IND);
11132 			}
11133 		}
11134 
11135 		/*
11136 		 * We are seeing the final ack in the three way
11137 		 * hand shake of a active open'ed connection
11138 		 * so we must send up a T_CONN_CON
11139 		 *
11140 		 * tcp_sendmsg() checks tcp_state without entering
11141 		 * the squeue so tcp_state should be updated before
11142 		 * sending up connection confirmation.
11143 		 */
11144 		tcp->tcp_state = TCPS_ESTABLISHED;
11145 		if (tcp->tcp_active_open) {
11146 			if (!tcp_conn_con(tcp, iphdr, mp, NULL, ira)) {
11147 				freemsg(mp);
11148 				tcp->tcp_state = TCPS_SYN_RCVD;
11149 				return;
11150 			}
11151 			/*
11152 			 * Don't fuse the loopback endpoints for
11153 			 * simultaneous active opens.
11154 			 */
11155 			if (tcp->tcp_loopback) {
11156 				TCP_STAT(tcps, tcp_fusion_unfusable);
11157 				tcp->tcp_unfusable = B_TRUE;
11158 			}
11159 		}
11160 
11161 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
11162 		bytes_acked--;
11163 		/* SYN was acked - making progress */
11164 		tcp->tcp_ip_forward_progress = B_TRUE;
11165 
11166 		/*
11167 		 * If SYN was retransmitted, need to reset all
11168 		 * retransmission info as this segment will be
11169 		 * treated as a dup ACK.
11170 		 */
11171 		if (tcp->tcp_rexmit) {
11172 			tcp->tcp_rexmit = B_FALSE;
11173 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11174 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
11175 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11176 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11177 			tcp->tcp_ms_we_have_waited = 0;
11178 			tcp->tcp_cwnd = mss;
11179 		}
11180 
11181 		/*
11182 		 * We set the send window to zero here.
11183 		 * This is needed if there is data to be
11184 		 * processed already on the queue.
11185 		 * Later (at swnd_update label), the
11186 		 * "new_swnd > tcp_swnd" condition is satisfied
11187 		 * the XMIT_NEEDED flag is set in the current
11188 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
11189 		 * called if there is already data on queue in
11190 		 * this state.
11191 		 */
11192 		tcp->tcp_swnd = 0;
11193 
11194 		if (new_swnd > tcp->tcp_max_swnd)
11195 			tcp->tcp_max_swnd = new_swnd;
11196 		tcp->tcp_swl1 = seg_seq;
11197 		tcp->tcp_swl2 = seg_ack;
11198 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
11199 
11200 		/* Fuse when both sides are in ESTABLISHED state */
11201 		if (tcp->tcp_loopback && do_tcp_fusion)
11202 			tcp_fuse(tcp, iphdr, tcpha);
11203 
11204 	}
11205 	/* This code follows 4.4BSD-Lite2 mostly. */
11206 	if (bytes_acked < 0)
11207 		goto est;
11208 
11209 	/*
11210 	 * If TCP is ECN capable and the congestion experience bit is
11211 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
11212 	 * done once per window (or more loosely, per RTT).
11213 	 */
11214 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
11215 		tcp->tcp_cwr = B_FALSE;
11216 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
11217 		if (!tcp->tcp_cwr) {
11218 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
11219 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
11220 			tcp->tcp_cwnd = npkt * mss;
11221 			/*
11222 			 * If the cwnd is 0, use the timer to clock out
11223 			 * new segments.  This is required by the ECN spec.
11224 			 */
11225 			if (npkt == 0) {
11226 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11227 				/*
11228 				 * This makes sure that when the ACK comes
11229 				 * back, we will increase tcp_cwnd by 1 MSS.
11230 				 */
11231 				tcp->tcp_cwnd_cnt = 0;
11232 			}
11233 			tcp->tcp_cwr = B_TRUE;
11234 			/*
11235 			 * This marks the end of the current window of in
11236 			 * flight data.  That is why we don't use
11237 			 * tcp_suna + tcp_swnd.  Only data in flight can
11238 			 * provide ECN info.
11239 			 */
11240 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11241 			tcp->tcp_ecn_cwr_sent = B_FALSE;
11242 		}
11243 	}
11244 
11245 	mp1 = tcp->tcp_xmit_head;
11246 	if (bytes_acked == 0) {
11247 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
11248 			int dupack_cnt;
11249 
11250 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
11251 			/*
11252 			 * Fast retransmit.  When we have seen exactly three
11253 			 * identical ACKs while we have unacked data
11254 			 * outstanding we take it as a hint that our peer
11255 			 * dropped something.
11256 			 *
11257 			 * If TCP is retransmitting, don't do fast retransmit.
11258 			 */
11259 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
11260 			    ! tcp->tcp_rexmit) {
11261 				/* Do Limited Transmit */
11262 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
11263 				    tcps->tcps_dupack_fast_retransmit) {
11264 					/*
11265 					 * RFC 3042
11266 					 *
11267 					 * What we need to do is temporarily
11268 					 * increase tcp_cwnd so that new
11269 					 * data can be sent if it is allowed
11270 					 * by the receive window (tcp_rwnd).
11271 					 * tcp_wput_data() will take care of
11272 					 * the rest.
11273 					 *
11274 					 * If the connection is SACK capable,
11275 					 * only do limited xmit when there
11276 					 * is SACK info.
11277 					 *
11278 					 * Note how tcp_cwnd is incremented.
11279 					 * The first dup ACK will increase
11280 					 * it by 1 MSS.  The second dup ACK
11281 					 * will increase it by 2 MSS.  This
11282 					 * means that only 1 new segment will
11283 					 * be sent for each dup ACK.
11284 					 */
11285 					if (tcp->tcp_unsent > 0 &&
11286 					    (!tcp->tcp_snd_sack_ok ||
11287 					    (tcp->tcp_snd_sack_ok &&
11288 					    tcp->tcp_notsack_list != NULL))) {
11289 						tcp->tcp_cwnd += mss <<
11290 						    (tcp->tcp_dupack_cnt - 1);
11291 						flags |= TH_LIMIT_XMIT;
11292 					}
11293 				} else if (dupack_cnt ==
11294 				    tcps->tcps_dupack_fast_retransmit) {
11295 
11296 				/*
11297 				 * If we have reduced tcp_ssthresh
11298 				 * because of ECN, do not reduce it again
11299 				 * unless it is already one window of data
11300 				 * away.  After one window of data, tcp_cwr
11301 				 * should then be cleared.  Note that
11302 				 * for non ECN capable connection, tcp_cwr
11303 				 * should always be false.
11304 				 *
11305 				 * Adjust cwnd since the duplicate
11306 				 * ack indicates that a packet was
11307 				 * dropped (due to congestion.)
11308 				 */
11309 				if (!tcp->tcp_cwr) {
11310 					npkt = ((tcp->tcp_snxt -
11311 					    tcp->tcp_suna) >> 1) / mss;
11312 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
11313 					    mss;
11314 					tcp->tcp_cwnd = (npkt +
11315 					    tcp->tcp_dupack_cnt) * mss;
11316 				}
11317 				if (tcp->tcp_ecn_ok) {
11318 					tcp->tcp_cwr = B_TRUE;
11319 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11320 					tcp->tcp_ecn_cwr_sent = B_FALSE;
11321 				}
11322 
11323 				/*
11324 				 * We do Hoe's algorithm.  Refer to her
11325 				 * paper "Improving the Start-up Behavior
11326 				 * of a Congestion Control Scheme for TCP,"
11327 				 * appeared in SIGCOMM'96.
11328 				 *
11329 				 * Save highest seq no we have sent so far.
11330 				 * Be careful about the invisible FIN byte.
11331 				 */
11332 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
11333 				    (tcp->tcp_unsent == 0)) {
11334 					tcp->tcp_rexmit_max = tcp->tcp_fss;
11335 				} else {
11336 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
11337 				}
11338 
11339 				/*
11340 				 * Do not allow bursty traffic during.
11341 				 * fast recovery.  Refer to Fall and Floyd's
11342 				 * paper "Simulation-based Comparisons of
11343 				 * Tahoe, Reno and SACK TCP" (in CCR?)
11344 				 * This is a best current practise.
11345 				 */
11346 				tcp->tcp_snd_burst = TCP_CWND_SS;
11347 
11348 				/*
11349 				 * For SACK:
11350 				 * Calculate tcp_pipe, which is the
11351 				 * estimated number of bytes in
11352 				 * network.
11353 				 *
11354 				 * tcp_fack is the highest sack'ed seq num
11355 				 * TCP has received.
11356 				 *
11357 				 * tcp_pipe is explained in the above quoted
11358 				 * Fall and Floyd's paper.  tcp_fack is
11359 				 * explained in Mathis and Mahdavi's
11360 				 * "Forward Acknowledgment: Refining TCP
11361 				 * Congestion Control" in SIGCOMM '96.
11362 				 */
11363 				if (tcp->tcp_snd_sack_ok) {
11364 					ASSERT(tcp->tcp_sack_info != NULL);
11365 					if (tcp->tcp_notsack_list != NULL) {
11366 						tcp->tcp_pipe = tcp->tcp_snxt -
11367 						    tcp->tcp_fack;
11368 						tcp->tcp_sack_snxt = seg_ack;
11369 						flags |= TH_NEED_SACK_REXMIT;
11370 					} else {
11371 						/*
11372 						 * Always initialize tcp_pipe
11373 						 * even though we don't have
11374 						 * any SACK info.  If later
11375 						 * we get SACK info and
11376 						 * tcp_pipe is not initialized,
11377 						 * funny things will happen.
11378 						 */
11379 						tcp->tcp_pipe =
11380 						    tcp->tcp_cwnd_ssthresh;
11381 					}
11382 				} else {
11383 					flags |= TH_REXMIT_NEEDED;
11384 				} /* tcp_snd_sack_ok */
11385 
11386 				} else {
11387 					/*
11388 					 * Here we perform congestion
11389 					 * avoidance, but NOT slow start.
11390 					 * This is known as the Fast
11391 					 * Recovery Algorithm.
11392 					 */
11393 					if (tcp->tcp_snd_sack_ok &&
11394 					    tcp->tcp_notsack_list != NULL) {
11395 						flags |= TH_NEED_SACK_REXMIT;
11396 						tcp->tcp_pipe -= mss;
11397 						if (tcp->tcp_pipe < 0)
11398 							tcp->tcp_pipe = 0;
11399 					} else {
11400 					/*
11401 					 * We know that one more packet has
11402 					 * left the pipe thus we can update
11403 					 * cwnd.
11404 					 */
11405 					cwnd = tcp->tcp_cwnd + mss;
11406 					if (cwnd > tcp->tcp_cwnd_max)
11407 						cwnd = tcp->tcp_cwnd_max;
11408 					tcp->tcp_cwnd = cwnd;
11409 					if (tcp->tcp_unsent > 0)
11410 						flags |= TH_XMIT_NEEDED;
11411 					}
11412 				}
11413 			}
11414 		} else if (tcp->tcp_zero_win_probe) {
11415 			/*
11416 			 * If the window has opened, need to arrange
11417 			 * to send additional data.
11418 			 */
11419 			if (new_swnd != 0) {
11420 				/* tcp_suna != tcp_snxt */
11421 				/* Packet contains a window update */
11422 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
11423 				tcp->tcp_zero_win_probe = 0;
11424 				tcp->tcp_timer_backoff = 0;
11425 				tcp->tcp_ms_we_have_waited = 0;
11426 
11427 				/*
11428 				 * Transmit starting with tcp_suna since
11429 				 * the one byte probe is not ack'ed.
11430 				 * If TCP has sent more than one identical
11431 				 * probe, tcp_rexmit will be set.  That means
11432 				 * tcp_ss_rexmit() will send out the one
11433 				 * byte along with new data.  Otherwise,
11434 				 * fake the retransmission.
11435 				 */
11436 				flags |= TH_XMIT_NEEDED;
11437 				if (!tcp->tcp_rexmit) {
11438 					tcp->tcp_rexmit = B_TRUE;
11439 					tcp->tcp_dupack_cnt = 0;
11440 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
11441 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
11442 				}
11443 			}
11444 		}
11445 		goto swnd_update;
11446 	}
11447 
11448 	/*
11449 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
11450 	 * If the ACK value acks something that we have not yet sent, it might
11451 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
11452 	 * other side.
11453 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
11454 	 * state is handled above, so we can always just drop the segment and
11455 	 * send an ACK here.
11456 	 *
11457 	 * In the case where the peer shrinks the window, we see the new window
11458 	 * update, but all the data sent previously is queued up by the peer.
11459 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
11460 	 * number, which was already sent, and within window, is recorded.
11461 	 * tcp_snxt is then updated.
11462 	 *
11463 	 * If the window has previously shrunk, and an ACK for data not yet
11464 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
11465 	 * the ACK is for data within the window at the time the window was
11466 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
11467 	 * the sequence number ACK'ed.
11468 	 *
11469 	 * If the ACK covers all the data sent at the time the window was
11470 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
11471 	 *
11472 	 * Should we send ACKs in response to ACK only segments?
11473 	 */
11474 
11475 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
11476 		if ((tcp->tcp_is_wnd_shrnk) &&
11477 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
11478 			uint32_t data_acked_ahead_snxt;
11479 
11480 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
11481 			tcp_update_xmit_tail(tcp, seg_ack);
11482 			tcp->tcp_unsent -= data_acked_ahead_snxt;
11483 		} else {
11484 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
11485 			/* drop the received segment */
11486 			freemsg(mp);
11487 
11488 			/*
11489 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
11490 			 * greater than 0, check if the number of such
11491 			 * bogus ACks is greater than that count.  If yes,
11492 			 * don't send back any ACK.  This prevents TCP from
11493 			 * getting into an ACK storm if somehow an attacker
11494 			 * successfully spoofs an acceptable segment to our
11495 			 * peer.
11496 			 */
11497 			if (tcp_drop_ack_unsent_cnt > 0 &&
11498 			    ++tcp->tcp_in_ack_unsent >
11499 			    tcp_drop_ack_unsent_cnt) {
11500 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
11501 				return;
11502 			}
11503 			mp = tcp_ack_mp(tcp);
11504 			if (mp != NULL) {
11505 				BUMP_LOCAL(tcp->tcp_obsegs);
11506 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
11507 				tcp_send_data(tcp, mp);
11508 			}
11509 			return;
11510 		}
11511 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
11512 	    tcp->tcp_snxt_shrunk)) {
11513 			tcp->tcp_is_wnd_shrnk = B_FALSE;
11514 	}
11515 
11516 	/*
11517 	 * TCP gets a new ACK, update the notsack'ed list to delete those
11518 	 * blocks that are covered by this ACK.
11519 	 */
11520 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
11521 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
11522 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
11523 	}
11524 
11525 	/*
11526 	 * If we got an ACK after fast retransmit, check to see
11527 	 * if it is a partial ACK.  If it is not and the congestion
11528 	 * window was inflated to account for the other side's
11529 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
11530 	 */
11531 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
11532 		ASSERT(tcp->tcp_rexmit == B_FALSE);
11533 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
11534 			tcp->tcp_dupack_cnt = 0;
11535 			/*
11536 			 * Restore the orig tcp_cwnd_ssthresh after
11537 			 * fast retransmit phase.
11538 			 */
11539 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
11540 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
11541 			}
11542 			tcp->tcp_rexmit_max = seg_ack;
11543 			tcp->tcp_cwnd_cnt = 0;
11544 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11545 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11546 
11547 			/*
11548 			 * Remove all notsack info to avoid confusion with
11549 			 * the next fast retrasnmit/recovery phase.
11550 			 */
11551 			if (tcp->tcp_snd_sack_ok &&
11552 			    tcp->tcp_notsack_list != NULL) {
11553 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
11554 				    tcp);
11555 			}
11556 		} else {
11557 			if (tcp->tcp_snd_sack_ok &&
11558 			    tcp->tcp_notsack_list != NULL) {
11559 				flags |= TH_NEED_SACK_REXMIT;
11560 				tcp->tcp_pipe -= mss;
11561 				if (tcp->tcp_pipe < 0)
11562 					tcp->tcp_pipe = 0;
11563 			} else {
11564 				/*
11565 				 * Hoe's algorithm:
11566 				 *
11567 				 * Retransmit the unack'ed segment and
11568 				 * restart fast recovery.  Note that we
11569 				 * need to scale back tcp_cwnd to the
11570 				 * original value when we started fast
11571 				 * recovery.  This is to prevent overly
11572 				 * aggressive behaviour in sending new
11573 				 * segments.
11574 				 */
11575 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
11576 				    tcps->tcps_dupack_fast_retransmit * mss;
11577 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
11578 				flags |= TH_REXMIT_NEEDED;
11579 			}
11580 		}
11581 	} else {
11582 		tcp->tcp_dupack_cnt = 0;
11583 		if (tcp->tcp_rexmit) {
11584 			/*
11585 			 * TCP is retranmitting.  If the ACK ack's all
11586 			 * outstanding data, update tcp_rexmit_max and
11587 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
11588 			 * to the correct value.
11589 			 *
11590 			 * Note that SEQ_LEQ() is used.  This is to avoid
11591 			 * unnecessary fast retransmit caused by dup ACKs
11592 			 * received when TCP does slow start retransmission
11593 			 * after a time out.  During this phase, TCP may
11594 			 * send out segments which are already received.
11595 			 * This causes dup ACKs to be sent back.
11596 			 */
11597 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
11598 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
11599 					tcp->tcp_rexmit_nxt = seg_ack;
11600 				}
11601 				if (seg_ack != tcp->tcp_rexmit_max) {
11602 					flags |= TH_XMIT_NEEDED;
11603 				}
11604 			} else {
11605 				tcp->tcp_rexmit = B_FALSE;
11606 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11607 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
11608 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11609 			}
11610 			tcp->tcp_ms_we_have_waited = 0;
11611 		}
11612 	}
11613 
11614 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
11615 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
11616 	tcp->tcp_suna = seg_ack;
11617 	if (tcp->tcp_zero_win_probe != 0) {
11618 		tcp->tcp_zero_win_probe = 0;
11619 		tcp->tcp_timer_backoff = 0;
11620 	}
11621 
11622 	/*
11623 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
11624 	 * Note that it cannot be the SYN being ack'ed.  The code flow
11625 	 * will not reach here.
11626 	 */
11627 	if (mp1 == NULL) {
11628 		goto fin_acked;
11629 	}
11630 
11631 	/*
11632 	 * Update the congestion window.
11633 	 *
11634 	 * If TCP is not ECN capable or TCP is ECN capable but the
11635 	 * congestion experience bit is not set, increase the tcp_cwnd as
11636 	 * usual.
11637 	 */
11638 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
11639 		cwnd = tcp->tcp_cwnd;
11640 		add = mss;
11641 
11642 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
11643 			/*
11644 			 * This is to prevent an increase of less than 1 MSS of
11645 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
11646 			 * may send out tinygrams in order to preserve mblk
11647 			 * boundaries.
11648 			 *
11649 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
11650 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
11651 			 * increased by 1 MSS for every RTTs.
11652 			 */
11653 			if (tcp->tcp_cwnd_cnt <= 0) {
11654 				tcp->tcp_cwnd_cnt = cwnd + add;
11655 			} else {
11656 				tcp->tcp_cwnd_cnt -= add;
11657 				add = 0;
11658 			}
11659 		}
11660 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
11661 	}
11662 
11663 	/* See if the latest urgent data has been acknowledged */
11664 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
11665 	    SEQ_GT(seg_ack, tcp->tcp_urg))
11666 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
11667 
11668 	/* Can we update the RTT estimates? */
11669 	if (tcp->tcp_snd_ts_ok) {
11670 		/* Ignore zero timestamp echo-reply. */
11671 		if (tcpopt.tcp_opt_ts_ecr != 0) {
11672 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
11673 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
11674 		}
11675 
11676 		/* If needed, restart the timer. */
11677 		if (tcp->tcp_set_timer == 1) {
11678 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11679 			tcp->tcp_set_timer = 0;
11680 		}
11681 		/*
11682 		 * Update tcp_csuna in case the other side stops sending
11683 		 * us timestamps.
11684 		 */
11685 		tcp->tcp_csuna = tcp->tcp_snxt;
11686 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
11687 		/*
11688 		 * An ACK sequence we haven't seen before, so get the RTT
11689 		 * and update the RTO. But first check if the timestamp is
11690 		 * valid to use.
11691 		 */
11692 		if ((mp1->b_next != NULL) &&
11693 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
11694 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
11695 			    (int32_t)(intptr_t)mp1->b_prev);
11696 		else
11697 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
11698 
11699 		/* Remeber the last sequence to be ACKed */
11700 		tcp->tcp_csuna = seg_ack;
11701 		if (tcp->tcp_set_timer == 1) {
11702 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11703 			tcp->tcp_set_timer = 0;
11704 		}
11705 	} else {
11706 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
11707 	}
11708 
11709 	/* Eat acknowledged bytes off the xmit queue. */
11710 	for (;;) {
11711 		mblk_t	*mp2;
11712 		uchar_t	*wptr;
11713 
11714 		wptr = mp1->b_wptr;
11715 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
11716 		bytes_acked -= (int)(wptr - mp1->b_rptr);
11717 		if (bytes_acked < 0) {
11718 			mp1->b_rptr = wptr + bytes_acked;
11719 			/*
11720 			 * Set a new timestamp if all the bytes timed by the
11721 			 * old timestamp have been ack'ed.
11722 			 */
11723 			if (SEQ_GT(seg_ack,
11724 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
11725 				mp1->b_prev =
11726 				    (mblk_t *)(uintptr_t)LBOLT_FASTPATH;
11727 				mp1->b_next = NULL;
11728 			}
11729 			break;
11730 		}
11731 		mp1->b_next = NULL;
11732 		mp1->b_prev = NULL;
11733 		mp2 = mp1;
11734 		mp1 = mp1->b_cont;
11735 
11736 		/*
11737 		 * This notification is required for some zero-copy
11738 		 * clients to maintain a copy semantic. After the data
11739 		 * is ack'ed, client is safe to modify or reuse the buffer.
11740 		 */
11741 		if (tcp->tcp_snd_zcopy_aware &&
11742 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
11743 			tcp_zcopy_notify(tcp);
11744 		freeb(mp2);
11745 		if (bytes_acked == 0) {
11746 			if (mp1 == NULL) {
11747 				/* Everything is ack'ed, clear the tail. */
11748 				tcp->tcp_xmit_tail = NULL;
11749 				/*
11750 				 * Cancel the timer unless we are still
11751 				 * waiting for an ACK for the FIN packet.
11752 				 */
11753 				if (tcp->tcp_timer_tid != 0 &&
11754 				    tcp->tcp_snxt == tcp->tcp_suna) {
11755 					(void) TCP_TIMER_CANCEL(tcp,
11756 					    tcp->tcp_timer_tid);
11757 					tcp->tcp_timer_tid = 0;
11758 				}
11759 				goto pre_swnd_update;
11760 			}
11761 			if (mp2 != tcp->tcp_xmit_tail)
11762 				break;
11763 			tcp->tcp_xmit_tail = mp1;
11764 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
11765 			    (uintptr_t)INT_MAX);
11766 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
11767 			    mp1->b_rptr);
11768 			break;
11769 		}
11770 		if (mp1 == NULL) {
11771 			/*
11772 			 * More was acked but there is nothing more
11773 			 * outstanding.  This means that the FIN was
11774 			 * just acked or that we're talking to a clown.
11775 			 */
11776 fin_acked:
11777 			ASSERT(tcp->tcp_fin_sent);
11778 			tcp->tcp_xmit_tail = NULL;
11779 			if (tcp->tcp_fin_sent) {
11780 				/* FIN was acked - making progress */
11781 				if (!tcp->tcp_fin_acked)
11782 					tcp->tcp_ip_forward_progress = B_TRUE;
11783 				tcp->tcp_fin_acked = B_TRUE;
11784 				if (tcp->tcp_linger_tid != 0 &&
11785 				    TCP_TIMER_CANCEL(tcp,
11786 				    tcp->tcp_linger_tid) >= 0) {
11787 					tcp_stop_lingering(tcp);
11788 					freemsg(mp);
11789 					mp = NULL;
11790 				}
11791 			} else {
11792 				/*
11793 				 * We should never get here because
11794 				 * we have already checked that the
11795 				 * number of bytes ack'ed should be
11796 				 * smaller than or equal to what we
11797 				 * have sent so far (it is the
11798 				 * acceptability check of the ACK).
11799 				 * We can only get here if the send
11800 				 * queue is corrupted.
11801 				 *
11802 				 * Terminate the connection and
11803 				 * panic the system.  It is better
11804 				 * for us to panic instead of
11805 				 * continuing to avoid other disaster.
11806 				 */
11807 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
11808 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
11809 				panic("Memory corruption "
11810 				    "detected for connection %s.",
11811 				    tcp_display(tcp, NULL,
11812 				    DISP_ADDR_AND_PORT));
11813 				/*NOTREACHED*/
11814 			}
11815 			goto pre_swnd_update;
11816 		}
11817 		ASSERT(mp2 != tcp->tcp_xmit_tail);
11818 	}
11819 	if (tcp->tcp_unsent) {
11820 		flags |= TH_XMIT_NEEDED;
11821 	}
11822 pre_swnd_update:
11823 	tcp->tcp_xmit_head = mp1;
11824 swnd_update:
11825 	/*
11826 	 * The following check is different from most other implementations.
11827 	 * For bi-directional transfer, when segments are dropped, the
11828 	 * "normal" check will not accept a window update in those
11829 	 * retransmitted segemnts.  Failing to do that, TCP may send out
11830 	 * segments which are outside receiver's window.  As TCP accepts
11831 	 * the ack in those retransmitted segments, if the window update in
11832 	 * the same segment is not accepted, TCP will incorrectly calculates
11833 	 * that it can send more segments.  This can create a deadlock
11834 	 * with the receiver if its window becomes zero.
11835 	 */
11836 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
11837 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
11838 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
11839 		/*
11840 		 * The criteria for update is:
11841 		 *
11842 		 * 1. the segment acknowledges some data.  Or
11843 		 * 2. the segment is new, i.e. it has a higher seq num. Or
11844 		 * 3. the segment is not old and the advertised window is
11845 		 * larger than the previous advertised window.
11846 		 */
11847 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
11848 			flags |= TH_XMIT_NEEDED;
11849 		tcp->tcp_swnd = new_swnd;
11850 		if (new_swnd > tcp->tcp_max_swnd)
11851 			tcp->tcp_max_swnd = new_swnd;
11852 		tcp->tcp_swl1 = seg_seq;
11853 		tcp->tcp_swl2 = seg_ack;
11854 	}
11855 est:
11856 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
11857 
11858 		switch (tcp->tcp_state) {
11859 		case TCPS_FIN_WAIT_1:
11860 			if (tcp->tcp_fin_acked) {
11861 				tcp->tcp_state = TCPS_FIN_WAIT_2;
11862 				/*
11863 				 * We implement the non-standard BSD/SunOS
11864 				 * FIN_WAIT_2 flushing algorithm.
11865 				 * If there is no user attached to this
11866 				 * TCP endpoint, then this TCP struct
11867 				 * could hang around forever in FIN_WAIT_2
11868 				 * state if the peer forgets to send us
11869 				 * a FIN.  To prevent this, we wait only
11870 				 * 2*MSL (a convenient time value) for
11871 				 * the FIN to arrive.  If it doesn't show up,
11872 				 * we flush the TCP endpoint.  This algorithm,
11873 				 * though a violation of RFC-793, has worked
11874 				 * for over 10 years in BSD systems.
11875 				 * Note: SunOS 4.x waits 675 seconds before
11876 				 * flushing the FIN_WAIT_2 connection.
11877 				 */
11878 				TCP_TIMER_RESTART(tcp,
11879 				    tcps->tcps_fin_wait_2_flush_interval);
11880 			}
11881 			break;
11882 		case TCPS_FIN_WAIT_2:
11883 			break;	/* Shutdown hook? */
11884 		case TCPS_LAST_ACK:
11885 			freemsg(mp);
11886 			if (tcp->tcp_fin_acked) {
11887 				(void) tcp_clean_death(tcp, 0, 19);
11888 				return;
11889 			}
11890 			goto xmit_check;
11891 		case TCPS_CLOSING:
11892 			if (tcp->tcp_fin_acked) {
11893 				tcp->tcp_state = TCPS_TIME_WAIT;
11894 				/*
11895 				 * Unconditionally clear the exclusive binding
11896 				 * bit so this TIME-WAIT connection won't
11897 				 * interfere with new ones.
11898 				 */
11899 				connp->conn_exclbind = 0;
11900 				if (!TCP_IS_DETACHED(tcp)) {
11901 					TCP_TIMER_RESTART(tcp,
11902 					    tcps->tcps_time_wait_interval);
11903 				} else {
11904 					tcp_time_wait_append(tcp);
11905 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
11906 				}
11907 			}
11908 			/*FALLTHRU*/
11909 		case TCPS_CLOSE_WAIT:
11910 			freemsg(mp);
11911 			goto xmit_check;
11912 		default:
11913 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11914 			break;
11915 		}
11916 	}
11917 	if (flags & TH_FIN) {
11918 		/* Make sure we ack the fin */
11919 		flags |= TH_ACK_NEEDED;
11920 		if (!tcp->tcp_fin_rcvd) {
11921 			tcp->tcp_fin_rcvd = B_TRUE;
11922 			tcp->tcp_rnxt++;
11923 			tcpha = tcp->tcp_tcpha;
11924 			tcpha->tha_ack = htonl(tcp->tcp_rnxt);
11925 
11926 			/*
11927 			 * Generate the ordrel_ind at the end unless we
11928 			 * are an eager guy.
11929 			 * In the eager case tcp_rsrv will do this when run
11930 			 * after tcp_accept is done.
11931 			 */
11932 			if (tcp->tcp_listener == NULL &&
11933 			    !TCP_IS_DETACHED(tcp) && !tcp->tcp_hard_binding)
11934 				flags |= TH_ORDREL_NEEDED;
11935 			switch (tcp->tcp_state) {
11936 			case TCPS_SYN_RCVD:
11937 			case TCPS_ESTABLISHED:
11938 				tcp->tcp_state = TCPS_CLOSE_WAIT;
11939 				/* Keepalive? */
11940 				break;
11941 			case TCPS_FIN_WAIT_1:
11942 				if (!tcp->tcp_fin_acked) {
11943 					tcp->tcp_state = TCPS_CLOSING;
11944 					break;
11945 				}
11946 				/* FALLTHRU */
11947 			case TCPS_FIN_WAIT_2:
11948 				tcp->tcp_state = TCPS_TIME_WAIT;
11949 				/*
11950 				 * Unconditionally clear the exclusive binding
11951 				 * bit so this TIME-WAIT connection won't
11952 				 * interfere with new ones.
11953 				 */
11954 				connp->conn_exclbind = 0;
11955 				if (!TCP_IS_DETACHED(tcp)) {
11956 					TCP_TIMER_RESTART(tcp,
11957 					    tcps->tcps_time_wait_interval);
11958 				} else {
11959 					tcp_time_wait_append(tcp);
11960 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
11961 				}
11962 				if (seg_len) {
11963 					/*
11964 					 * implies data piggybacked on FIN.
11965 					 * break to handle data.
11966 					 */
11967 					break;
11968 				}
11969 				freemsg(mp);
11970 				goto ack_check;
11971 			}
11972 		}
11973 	}
11974 	if (mp == NULL)
11975 		goto xmit_check;
11976 	if (seg_len == 0) {
11977 		freemsg(mp);
11978 		goto xmit_check;
11979 	}
11980 	if (mp->b_rptr == mp->b_wptr) {
11981 		/*
11982 		 * The header has been consumed, so we remove the
11983 		 * zero-length mblk here.
11984 		 */
11985 		mp1 = mp;
11986 		mp = mp->b_cont;
11987 		freeb(mp1);
11988 	}
11989 update_ack:
11990 	tcpha = tcp->tcp_tcpha;
11991 	tcp->tcp_rack_cnt++;
11992 	{
11993 		uint32_t cur_max;
11994 
11995 		cur_max = tcp->tcp_rack_cur_max;
11996 		if (tcp->tcp_rack_cnt >= cur_max) {
11997 			/*
11998 			 * We have more unacked data than we should - send
11999 			 * an ACK now.
12000 			 */
12001 			flags |= TH_ACK_NEEDED;
12002 			cur_max++;
12003 			if (cur_max > tcp->tcp_rack_abs_max)
12004 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
12005 			else
12006 				tcp->tcp_rack_cur_max = cur_max;
12007 		} else if (TCP_IS_DETACHED(tcp)) {
12008 			/* We don't have an ACK timer for detached TCP. */
12009 			flags |= TH_ACK_NEEDED;
12010 		} else if (seg_len < mss) {
12011 			/*
12012 			 * If we get a segment that is less than an mss, and we
12013 			 * already have unacknowledged data, and the amount
12014 			 * unacknowledged is not a multiple of mss, then we
12015 			 * better generate an ACK now.  Otherwise, this may be
12016 			 * the tail piece of a transaction, and we would rather
12017 			 * wait for the response.
12018 			 */
12019 			uint32_t udif;
12020 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
12021 			    (uintptr_t)INT_MAX);
12022 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
12023 			if (udif && (udif % mss))
12024 				flags |= TH_ACK_NEEDED;
12025 			else
12026 				flags |= TH_ACK_TIMER_NEEDED;
12027 		} else {
12028 			/* Start delayed ack timer */
12029 			flags |= TH_ACK_TIMER_NEEDED;
12030 		}
12031 	}
12032 	tcp->tcp_rnxt += seg_len;
12033 	tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12034 
12035 	if (mp == NULL)
12036 		goto xmit_check;
12037 
12038 	/* Update SACK list */
12039 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
12040 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
12041 		    &(tcp->tcp_num_sack_blk));
12042 	}
12043 
12044 	if (tcp->tcp_urp_mp) {
12045 		tcp->tcp_urp_mp->b_cont = mp;
12046 		mp = tcp->tcp_urp_mp;
12047 		tcp->tcp_urp_mp = NULL;
12048 		/* Ready for a new signal. */
12049 		tcp->tcp_urp_last_valid = B_FALSE;
12050 #ifdef DEBUG
12051 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12052 		    "tcp_rput: sending exdata_ind %s",
12053 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12054 #endif /* DEBUG */
12055 	}
12056 
12057 	/*
12058 	 * Check for ancillary data changes compared to last segment.
12059 	 */
12060 	if (connp->conn_recv_ancillary.crb_all != 0) {
12061 		mp = tcp_input_add_ancillary(tcp, mp, &ipp, ira);
12062 		if (mp == NULL)
12063 			return;
12064 	}
12065 
12066 	if (tcp->tcp_listener != NULL || tcp->tcp_hard_binding) {
12067 		/*
12068 		 * Side queue inbound data until the accept happens.
12069 		 * tcp_accept/tcp_rput drains this when the accept happens.
12070 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
12071 		 * T_EXDATA_IND) it is queued on b_next.
12072 		 * XXX Make urgent data use this. Requires:
12073 		 *	Removing tcp_listener check for TH_URG
12074 		 *	Making M_PCPROTO and MARK messages skip the eager case
12075 		 */
12076 
12077 		if (tcp->tcp_kssl_pending) {
12078 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
12079 			    mblk_t *, mp);
12080 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12081 		} else {
12082 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12083 		}
12084 	} else if (IPCL_IS_NONSTR(connp)) {
12085 		/*
12086 		 * Non-STREAMS socket
12087 		 *
12088 		 * Note that no KSSL processing is done here, because
12089 		 * KSSL is not supported for non-STREAMS sockets.
12090 		 */
12091 		boolean_t push = flags & (TH_PUSH|TH_FIN);
12092 		int error;
12093 
12094 		if ((*connp->conn_upcalls->su_recv)(
12095 		    connp->conn_upper_handle,
12096 		    mp, seg_len, 0, &error, &push) <= 0) {
12097 			/*
12098 			 * We should never be in middle of a
12099 			 * fallback, the squeue guarantees that.
12100 			 */
12101 			ASSERT(error != EOPNOTSUPP);
12102 			if (error == ENOSPC)
12103 				tcp->tcp_rwnd -= seg_len;
12104 		} else if (push) {
12105 			/* PUSH bit set and sockfs is not flow controlled */
12106 			flags |= tcp_rwnd_reopen(tcp);
12107 		}
12108 	} else {
12109 		/* STREAMS socket */
12110 		if (mp->b_datap->db_type != M_DATA ||
12111 		    (flags & TH_MARKNEXT_NEEDED)) {
12112 			if (tcp->tcp_rcv_list != NULL) {
12113 				flags |= tcp_rcv_drain(tcp);
12114 			}
12115 			ASSERT(tcp->tcp_rcv_list == NULL ||
12116 			    tcp->tcp_fused_sigurg);
12117 
12118 			if (flags & TH_MARKNEXT_NEEDED) {
12119 #ifdef DEBUG
12120 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12121 				    "tcp_rput: sending MSGMARKNEXT %s",
12122 				    tcp_display(tcp, NULL,
12123 				    DISP_PORT_ONLY));
12124 #endif /* DEBUG */
12125 				mp->b_flag |= MSGMARKNEXT;
12126 				flags &= ~TH_MARKNEXT_NEEDED;
12127 			}
12128 
12129 			/* Does this need SSL processing first? */
12130 			if ((tcp->tcp_kssl_ctx != NULL) &&
12131 			    (DB_TYPE(mp) == M_DATA)) {
12132 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
12133 				    mblk_t *, mp);
12134 				tcp_kssl_input(tcp, mp, ira->ira_cred);
12135 			} else {
12136 				if (is_system_labeled())
12137 					tcp_setcred_data(mp, ira);
12138 
12139 				putnext(connp->conn_rq, mp);
12140 				if (!canputnext(connp->conn_rq))
12141 					tcp->tcp_rwnd -= seg_len;
12142 			}
12143 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
12144 		    (DB_TYPE(mp) == M_DATA)) {
12145 			/* Does this need SSL processing first? */
12146 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
12147 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12148 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
12149 		    tcp->tcp_rcv_cnt + seg_len >= connp->conn_rcvbuf >> 3) {
12150 			if (tcp->tcp_rcv_list != NULL) {
12151 				/*
12152 				 * Enqueue the new segment first and then
12153 				 * call tcp_rcv_drain() to send all data
12154 				 * up.  The other way to do this is to
12155 				 * send all queued data up and then call
12156 				 * putnext() to send the new segment up.
12157 				 * This way can remove the else part later
12158 				 * on.
12159 				 *
12160 				 * We don't do this to avoid one more call to
12161 				 * canputnext() as tcp_rcv_drain() needs to
12162 				 * call canputnext().
12163 				 */
12164 				tcp_rcv_enqueue(tcp, mp, seg_len,
12165 				    ira->ira_cred);
12166 				flags |= tcp_rcv_drain(tcp);
12167 			} else {
12168 				if (is_system_labeled())
12169 					tcp_setcred_data(mp, ira);
12170 
12171 				putnext(connp->conn_rq, mp);
12172 				if (!canputnext(connp->conn_rq))
12173 					tcp->tcp_rwnd -= seg_len;
12174 			}
12175 		} else {
12176 			/*
12177 			 * Enqueue all packets when processing an mblk
12178 			 * from the co queue and also enqueue normal packets.
12179 			 */
12180 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12181 		}
12182 		/*
12183 		 * Make sure the timer is running if we have data waiting
12184 		 * for a push bit. This provides resiliency against
12185 		 * implementations that do not correctly generate push bits.
12186 		 */
12187 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
12188 			/*
12189 			 * The connection may be closed at this point, so don't
12190 			 * do anything for a detached tcp.
12191 			 */
12192 			if (!TCP_IS_DETACHED(tcp))
12193 				tcp->tcp_push_tid = TCP_TIMER(tcp,
12194 				    tcp_push_timer,
12195 				    MSEC_TO_TICK(
12196 				    tcps->tcps_push_timer_interval));
12197 		}
12198 	}
12199 
12200 xmit_check:
12201 	/* Is there anything left to do? */
12202 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12203 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
12204 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
12205 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12206 		goto done;
12207 
12208 	/* Any transmit work to do and a non-zero window? */
12209 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
12210 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
12211 		if (flags & TH_REXMIT_NEEDED) {
12212 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
12213 
12214 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
12215 			if (snd_size > mss)
12216 				snd_size = mss;
12217 			if (snd_size > tcp->tcp_swnd)
12218 				snd_size = tcp->tcp_swnd;
12219 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
12220 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
12221 			    B_TRUE);
12222 
12223 			if (mp1 != NULL) {
12224 				tcp->tcp_xmit_head->b_prev =
12225 				    (mblk_t *)LBOLT_FASTPATH;
12226 				tcp->tcp_csuna = tcp->tcp_snxt;
12227 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12228 				UPDATE_MIB(&tcps->tcps_mib,
12229 				    tcpRetransBytes, snd_size);
12230 				tcp_send_data(tcp, mp1);
12231 			}
12232 		}
12233 		if (flags & TH_NEED_SACK_REXMIT) {
12234 			tcp_sack_rxmit(tcp, &flags);
12235 		}
12236 		/*
12237 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
12238 		 * out new segment.  Note that tcp_rexmit should not be
12239 		 * set, otherwise TH_LIMIT_XMIT should not be set.
12240 		 */
12241 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
12242 			if (!tcp->tcp_rexmit) {
12243 				tcp_wput_data(tcp, NULL, B_FALSE);
12244 			} else {
12245 				tcp_ss_rexmit(tcp);
12246 			}
12247 		}
12248 		/*
12249 		 * Adjust tcp_cwnd back to normal value after sending
12250 		 * new data segments.
12251 		 */
12252 		if (flags & TH_LIMIT_XMIT) {
12253 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
12254 			/*
12255 			 * This will restart the timer.  Restarting the
12256 			 * timer is used to avoid a timeout before the
12257 			 * limited transmitted segment's ACK gets back.
12258 			 */
12259 			if (tcp->tcp_xmit_head != NULL)
12260 				tcp->tcp_xmit_head->b_prev =
12261 				    (mblk_t *)LBOLT_FASTPATH;
12262 		}
12263 
12264 		/* Anything more to do? */
12265 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
12266 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12267 			goto done;
12268 	}
12269 ack_check:
12270 	if (flags & TH_SEND_URP_MARK) {
12271 		ASSERT(tcp->tcp_urp_mark_mp);
12272 		ASSERT(!IPCL_IS_NONSTR(connp));
12273 		/*
12274 		 * Send up any queued data and then send the mark message
12275 		 */
12276 		if (tcp->tcp_rcv_list != NULL) {
12277 			flags |= tcp_rcv_drain(tcp);
12278 
12279 		}
12280 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12281 		mp1 = tcp->tcp_urp_mark_mp;
12282 		tcp->tcp_urp_mark_mp = NULL;
12283 		if (is_system_labeled())
12284 			tcp_setcred_data(mp1, ira);
12285 
12286 		putnext(connp->conn_rq, mp1);
12287 #ifdef DEBUG
12288 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12289 		    "tcp_rput: sending zero-length %s %s",
12290 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
12291 		    "MSGNOTMARKNEXT"),
12292 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12293 #endif /* DEBUG */
12294 		flags &= ~TH_SEND_URP_MARK;
12295 	}
12296 	if (flags & TH_ACK_NEEDED) {
12297 		/*
12298 		 * Time to send an ack for some reason.
12299 		 */
12300 		mp1 = tcp_ack_mp(tcp);
12301 
12302 		if (mp1 != NULL) {
12303 			tcp_send_data(tcp, mp1);
12304 			BUMP_LOCAL(tcp->tcp_obsegs);
12305 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
12306 		}
12307 		if (tcp->tcp_ack_tid != 0) {
12308 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
12309 			tcp->tcp_ack_tid = 0;
12310 		}
12311 	}
12312 	if (flags & TH_ACK_TIMER_NEEDED) {
12313 		/*
12314 		 * Arrange for deferred ACK or push wait timeout.
12315 		 * Start timer if it is not already running.
12316 		 */
12317 		if (tcp->tcp_ack_tid == 0) {
12318 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
12319 			    MSEC_TO_TICK(tcp->tcp_localnet ?
12320 			    (clock_t)tcps->tcps_local_dack_interval :
12321 			    (clock_t)tcps->tcps_deferred_ack_interval));
12322 		}
12323 	}
12324 	if (flags & TH_ORDREL_NEEDED) {
12325 		/*
12326 		 * Send up the ordrel_ind unless we are an eager guy.
12327 		 * In the eager case tcp_rsrv will do this when run
12328 		 * after tcp_accept is done.
12329 		 */
12330 		ASSERT(tcp->tcp_listener == NULL);
12331 		ASSERT(!tcp->tcp_detached);
12332 
12333 		if (IPCL_IS_NONSTR(connp)) {
12334 			ASSERT(tcp->tcp_ordrel_mp == NULL);
12335 			tcp->tcp_ordrel_done = B_TRUE;
12336 			(*connp->conn_upcalls->su_opctl)
12337 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
12338 			goto done;
12339 		}
12340 
12341 		if (tcp->tcp_rcv_list != NULL) {
12342 			/*
12343 			 * Push any mblk(s) enqueued from co processing.
12344 			 */
12345 			flags |= tcp_rcv_drain(tcp);
12346 		}
12347 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12348 
12349 		mp1 = tcp->tcp_ordrel_mp;
12350 		tcp->tcp_ordrel_mp = NULL;
12351 		tcp->tcp_ordrel_done = B_TRUE;
12352 		putnext(connp->conn_rq, mp1);
12353 	}
12354 done:
12355 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12356 }
12357 
12358 /*
12359  * This routine adjusts next-to-send sequence number variables, in the
12360  * case where the reciever has shrunk it's window.
12361  */
12362 static void
12363 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
12364 {
12365 	mblk_t *xmit_tail;
12366 	int32_t offset;
12367 
12368 	tcp->tcp_snxt = snxt;
12369 
12370 	/* Get the mblk, and the offset in it, as per the shrunk window */
12371 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
12372 	ASSERT(xmit_tail != NULL);
12373 	tcp->tcp_xmit_tail = xmit_tail;
12374 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
12375 	    xmit_tail->b_rptr - offset;
12376 }
12377 
12378 /*
12379  * This function does PAWS protection check. Returns B_TRUE if the
12380  * segment passes the PAWS test, else returns B_FALSE.
12381  */
12382 boolean_t
12383 tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp)
12384 {
12385 	uint8_t	flags;
12386 	int	options;
12387 	uint8_t *up;
12388 	conn_t	*connp = tcp->tcp_connp;
12389 
12390 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
12391 	/*
12392 	 * If timestamp option is aligned nicely, get values inline,
12393 	 * otherwise call general routine to parse.  Only do that
12394 	 * if timestamp is the only option.
12395 	 */
12396 	if (TCP_HDR_LENGTH(tcpha) == (uint32_t)TCP_MIN_HEADER_LENGTH +
12397 	    TCPOPT_REAL_TS_LEN &&
12398 	    OK_32PTR((up = ((uint8_t *)tcpha) +
12399 	    TCP_MIN_HEADER_LENGTH)) &&
12400 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
12401 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
12402 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
12403 
12404 		options = TCP_OPT_TSTAMP_PRESENT;
12405 	} else {
12406 		if (tcp->tcp_snd_sack_ok) {
12407 			tcpoptp->tcp = tcp;
12408 		} else {
12409 			tcpoptp->tcp = NULL;
12410 		}
12411 		options = tcp_parse_options(tcpha, tcpoptp);
12412 	}
12413 
12414 	if (options & TCP_OPT_TSTAMP_PRESENT) {
12415 		/*
12416 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
12417 		 * regardless of the timestamp, page 18 RFC 1323.bis.
12418 		 */
12419 		if ((flags & TH_RST) == 0 &&
12420 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
12421 		    tcp->tcp_ts_recent)) {
12422 			if (TSTMP_LT(LBOLT_FASTPATH64,
12423 			    tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) {
12424 				/* This segment is not acceptable. */
12425 				return (B_FALSE);
12426 			} else {
12427 				/*
12428 				 * Connection has been idle for
12429 				 * too long.  Reset the timestamp
12430 				 * and assume the segment is valid.
12431 				 */
12432 				tcp->tcp_ts_recent =
12433 				    tcpoptp->tcp_opt_ts_val;
12434 			}
12435 		}
12436 	} else {
12437 		/*
12438 		 * If we don't get a timestamp on every packet, we
12439 		 * figure we can't really trust 'em, so we stop sending
12440 		 * and parsing them.
12441 		 */
12442 		tcp->tcp_snd_ts_ok = B_FALSE;
12443 
12444 		connp->conn_ht_iphc_len -= TCPOPT_REAL_TS_LEN;
12445 		connp->conn_ht_ulp_len -= TCPOPT_REAL_TS_LEN;
12446 		tcp->tcp_tcpha->tha_offset_and_reserved -= (3 << 4);
12447 		/*
12448 		 * Adjust the tcp_mss and tcp_cwnd accordingly. We avoid
12449 		 * doing a slow start here so as to not to lose on the
12450 		 * transfer rate built up so far.
12451 		 */
12452 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
12453 		if (tcp->tcp_snd_sack_ok) {
12454 			ASSERT(tcp->tcp_sack_info != NULL);
12455 			tcp->tcp_max_sack_blk = 4;
12456 		}
12457 	}
12458 	return (B_TRUE);
12459 }
12460 
12461 /*
12462  * Attach ancillary data to a received TCP segments for the
12463  * ancillary pieces requested by the application that are
12464  * different than they were in the previous data segment.
12465  *
12466  * Save the "current" values once memory allocation is ok so that
12467  * when memory allocation fails we can just wait for the next data segment.
12468  */
12469 static mblk_t *
12470 tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
12471     ip_recv_attr_t *ira)
12472 {
12473 	struct T_optdata_ind *todi;
12474 	int optlen;
12475 	uchar_t *optptr;
12476 	struct T_opthdr *toh;
12477 	crb_t addflag;	/* Which pieces to add */
12478 	mblk_t *mp1;
12479 	conn_t	*connp = tcp->tcp_connp;
12480 
12481 	optlen = 0;
12482 	addflag.crb_all = 0;
12483 	/* If app asked for pktinfo and the index has changed ... */
12484 	if (connp->conn_recv_ancillary.crb_ip_recvpktinfo &&
12485 	    ira->ira_ruifindex != tcp->tcp_recvifindex) {
12486 		optlen += sizeof (struct T_opthdr) +
12487 		    sizeof (struct in6_pktinfo);
12488 		addflag.crb_ip_recvpktinfo = 1;
12489 	}
12490 	/* If app asked for hoplimit and it has changed ... */
12491 	if (connp->conn_recv_ancillary.crb_ipv6_recvhoplimit &&
12492 	    ipp->ipp_hoplimit != tcp->tcp_recvhops) {
12493 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12494 		addflag.crb_ipv6_recvhoplimit = 1;
12495 	}
12496 	/* If app asked for tclass and it has changed ... */
12497 	if (connp->conn_recv_ancillary.crb_ipv6_recvtclass &&
12498 	    ipp->ipp_tclass != tcp->tcp_recvtclass) {
12499 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12500 		addflag.crb_ipv6_recvtclass = 1;
12501 	}
12502 	/*
12503 	 * If app asked for hopbyhop headers and it has changed ...
12504 	 * For security labels, note that (1) security labels can't change on
12505 	 * a connected socket at all, (2) we're connected to at most one peer,
12506 	 * (3) if anything changes, then it must be some other extra option.
12507 	 */
12508 	if (connp->conn_recv_ancillary.crb_ipv6_recvhopopts &&
12509 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
12510 	    (ipp->ipp_fields & IPPF_HOPOPTS),
12511 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
12512 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
12513 		addflag.crb_ipv6_recvhopopts = 1;
12514 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
12515 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
12516 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
12517 			return (mp);
12518 	}
12519 	/* If app asked for dst headers before routing headers ... */
12520 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdrdstopts &&
12521 	    ip_cmpbuf(tcp->tcp_rthdrdstopts, tcp->tcp_rthdrdstoptslen,
12522 	    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12523 	    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen)) {
12524 		optlen += sizeof (struct T_opthdr) +
12525 		    ipp->ipp_rthdrdstoptslen;
12526 		addflag.crb_ipv6_recvrthdrdstopts = 1;
12527 		if (!ip_allocbuf((void **)&tcp->tcp_rthdrdstopts,
12528 		    &tcp->tcp_rthdrdstoptslen,
12529 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12530 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen))
12531 			return (mp);
12532 	}
12533 	/* If app asked for routing headers and it has changed ... */
12534 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdr &&
12535 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
12536 	    (ipp->ipp_fields & IPPF_RTHDR),
12537 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
12538 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
12539 		addflag.crb_ipv6_recvrthdr = 1;
12540 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
12541 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
12542 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
12543 			return (mp);
12544 	}
12545 	/* If app asked for dest headers and it has changed ... */
12546 	if ((connp->conn_recv_ancillary.crb_ipv6_recvdstopts ||
12547 	    connp->conn_recv_ancillary.crb_old_ipv6_recvdstopts) &&
12548 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
12549 	    (ipp->ipp_fields & IPPF_DSTOPTS),
12550 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
12551 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
12552 		addflag.crb_ipv6_recvdstopts = 1;
12553 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
12554 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
12555 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
12556 			return (mp);
12557 	}
12558 
12559 	if (optlen == 0) {
12560 		/* Nothing to add */
12561 		return (mp);
12562 	}
12563 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
12564 	if (mp1 == NULL) {
12565 		/*
12566 		 * Defer sending ancillary data until the next TCP segment
12567 		 * arrives.
12568 		 */
12569 		return (mp);
12570 	}
12571 	mp1->b_cont = mp;
12572 	mp = mp1;
12573 	mp->b_wptr += sizeof (*todi) + optlen;
12574 	mp->b_datap->db_type = M_PROTO;
12575 	todi = (struct T_optdata_ind *)mp->b_rptr;
12576 	todi->PRIM_type = T_OPTDATA_IND;
12577 	todi->DATA_flag = 1;	/* MORE data */
12578 	todi->OPT_length = optlen;
12579 	todi->OPT_offset = sizeof (*todi);
12580 	optptr = (uchar_t *)&todi[1];
12581 	/*
12582 	 * If app asked for pktinfo and the index has changed ...
12583 	 * Note that the local address never changes for the connection.
12584 	 */
12585 	if (addflag.crb_ip_recvpktinfo) {
12586 		struct in6_pktinfo *pkti;
12587 		uint_t ifindex;
12588 
12589 		ifindex = ira->ira_ruifindex;
12590 		toh = (struct T_opthdr *)optptr;
12591 		toh->level = IPPROTO_IPV6;
12592 		toh->name = IPV6_PKTINFO;
12593 		toh->len = sizeof (*toh) + sizeof (*pkti);
12594 		toh->status = 0;
12595 		optptr += sizeof (*toh);
12596 		pkti = (struct in6_pktinfo *)optptr;
12597 		pkti->ipi6_addr = connp->conn_laddr_v6;
12598 		pkti->ipi6_ifindex = ifindex;
12599 		optptr += sizeof (*pkti);
12600 		ASSERT(OK_32PTR(optptr));
12601 		/* Save as "last" value */
12602 		tcp->tcp_recvifindex = ifindex;
12603 	}
12604 	/* If app asked for hoplimit and it has changed ... */
12605 	if (addflag.crb_ipv6_recvhoplimit) {
12606 		toh = (struct T_opthdr *)optptr;
12607 		toh->level = IPPROTO_IPV6;
12608 		toh->name = IPV6_HOPLIMIT;
12609 		toh->len = sizeof (*toh) + sizeof (uint_t);
12610 		toh->status = 0;
12611 		optptr += sizeof (*toh);
12612 		*(uint_t *)optptr = ipp->ipp_hoplimit;
12613 		optptr += sizeof (uint_t);
12614 		ASSERT(OK_32PTR(optptr));
12615 		/* Save as "last" value */
12616 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
12617 	}
12618 	/* If app asked for tclass and it has changed ... */
12619 	if (addflag.crb_ipv6_recvtclass) {
12620 		toh = (struct T_opthdr *)optptr;
12621 		toh->level = IPPROTO_IPV6;
12622 		toh->name = IPV6_TCLASS;
12623 		toh->len = sizeof (*toh) + sizeof (uint_t);
12624 		toh->status = 0;
12625 		optptr += sizeof (*toh);
12626 		*(uint_t *)optptr = ipp->ipp_tclass;
12627 		optptr += sizeof (uint_t);
12628 		ASSERT(OK_32PTR(optptr));
12629 		/* Save as "last" value */
12630 		tcp->tcp_recvtclass = ipp->ipp_tclass;
12631 	}
12632 	if (addflag.crb_ipv6_recvhopopts) {
12633 		toh = (struct T_opthdr *)optptr;
12634 		toh->level = IPPROTO_IPV6;
12635 		toh->name = IPV6_HOPOPTS;
12636 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
12637 		toh->status = 0;
12638 		optptr += sizeof (*toh);
12639 		bcopy((uchar_t *)ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
12640 		optptr += ipp->ipp_hopoptslen;
12641 		ASSERT(OK_32PTR(optptr));
12642 		/* Save as last value */
12643 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
12644 		    (ipp->ipp_fields & IPPF_HOPOPTS),
12645 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
12646 	}
12647 	if (addflag.crb_ipv6_recvrthdrdstopts) {
12648 		toh = (struct T_opthdr *)optptr;
12649 		toh->level = IPPROTO_IPV6;
12650 		toh->name = IPV6_RTHDRDSTOPTS;
12651 		toh->len = sizeof (*toh) + ipp->ipp_rthdrdstoptslen;
12652 		toh->status = 0;
12653 		optptr += sizeof (*toh);
12654 		bcopy(ipp->ipp_rthdrdstopts, optptr, ipp->ipp_rthdrdstoptslen);
12655 		optptr += ipp->ipp_rthdrdstoptslen;
12656 		ASSERT(OK_32PTR(optptr));
12657 		/* Save as last value */
12658 		ip_savebuf((void **)&tcp->tcp_rthdrdstopts,
12659 		    &tcp->tcp_rthdrdstoptslen,
12660 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12661 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
12662 	}
12663 	if (addflag.crb_ipv6_recvrthdr) {
12664 		toh = (struct T_opthdr *)optptr;
12665 		toh->level = IPPROTO_IPV6;
12666 		toh->name = IPV6_RTHDR;
12667 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
12668 		toh->status = 0;
12669 		optptr += sizeof (*toh);
12670 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
12671 		optptr += ipp->ipp_rthdrlen;
12672 		ASSERT(OK_32PTR(optptr));
12673 		/* Save as last value */
12674 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
12675 		    (ipp->ipp_fields & IPPF_RTHDR),
12676 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
12677 	}
12678 	if (addflag.crb_ipv6_recvdstopts) {
12679 		toh = (struct T_opthdr *)optptr;
12680 		toh->level = IPPROTO_IPV6;
12681 		toh->name = IPV6_DSTOPTS;
12682 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
12683 		toh->status = 0;
12684 		optptr += sizeof (*toh);
12685 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
12686 		optptr += ipp->ipp_dstoptslen;
12687 		ASSERT(OK_32PTR(optptr));
12688 		/* Save as last value */
12689 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
12690 		    (ipp->ipp_fields & IPPF_DSTOPTS),
12691 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
12692 	}
12693 	ASSERT(optptr == mp->b_wptr);
12694 	return (mp);
12695 }
12696 
12697 /* ARGSUSED */
12698 static void
12699 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
12700 {
12701 	conn_t	*connp = (conn_t *)arg;
12702 	tcp_t	*tcp = connp->conn_tcp;
12703 	queue_t	*q = connp->conn_rq;
12704 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12705 
12706 	ASSERT(!IPCL_IS_NONSTR(connp));
12707 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
12708 	tcp->tcp_rsrv_mp = mp;
12709 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
12710 
12711 	TCP_STAT(tcps, tcp_rsrv_calls);
12712 
12713 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
12714 		return;
12715 	}
12716 
12717 	if (tcp->tcp_fused) {
12718 		tcp_fuse_backenable(tcp);
12719 		return;
12720 	}
12721 
12722 	if (canputnext(q)) {
12723 		/* Not flow-controlled, open rwnd */
12724 		tcp->tcp_rwnd = connp->conn_rcvbuf;
12725 
12726 		/*
12727 		 * Send back a window update immediately if TCP is above
12728 		 * ESTABLISHED state and the increase of the rcv window
12729 		 * that the other side knows is at least 1 MSS after flow
12730 		 * control is lifted.
12731 		 */
12732 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
12733 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
12734 			tcp_xmit_ctl(NULL, tcp,
12735 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
12736 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
12737 		}
12738 	}
12739 }
12740 
12741 /*
12742  * The read side service routine is called mostly when we get back-enabled as a
12743  * result of flow control relief.  Since we don't actually queue anything in
12744  * TCP, we have no data to send out of here.  What we do is clear the receive
12745  * window, and send out a window update.
12746  */
12747 static void
12748 tcp_rsrv(queue_t *q)
12749 {
12750 	conn_t		*connp = Q_TO_CONN(q);
12751 	tcp_t		*tcp = connp->conn_tcp;
12752 	mblk_t		*mp;
12753 
12754 	/* No code does a putq on the read side */
12755 	ASSERT(q->q_first == NULL);
12756 
12757 	/*
12758 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
12759 	 * been run.  So just return.
12760 	 */
12761 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
12762 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
12763 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
12764 		return;
12765 	}
12766 	tcp->tcp_rsrv_mp = NULL;
12767 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
12768 
12769 	CONN_INC_REF(connp);
12770 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
12771 	    NULL, SQ_PROCESS, SQTAG_TCP_RSRV);
12772 }
12773 
12774 /*
12775  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
12776  * We do not allow the receive window to shrink.  After setting rwnd,
12777  * set the flow control hiwat of the stream.
12778  *
12779  * This function is called in 2 cases:
12780  *
12781  * 1) Before data transfer begins, in tcp_input_listener() for accepting a
12782  *    connection (passive open) and in tcp_input_data() for active connect.
12783  *    This is called after tcp_mss_set() when the desired MSS value is known.
12784  *    This makes sure that our window size is a mutiple of the other side's
12785  *    MSS.
12786  * 2) Handling SO_RCVBUF option.
12787  *
12788  * It is ASSUMED that the requested size is a multiple of the current MSS.
12789  *
12790  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
12791  * user requests so.
12792  */
12793 int
12794 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
12795 {
12796 	uint32_t	mss = tcp->tcp_mss;
12797 	uint32_t	old_max_rwnd;
12798 	uint32_t	max_transmittable_rwnd;
12799 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
12800 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12801 	conn_t		*connp = tcp->tcp_connp;
12802 
12803 	/*
12804 	 * Insist on a receive window that is at least
12805 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
12806 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
12807 	 * and delayed acknowledgement.
12808 	 */
12809 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
12810 
12811 	if (tcp->tcp_fused) {
12812 		size_t sth_hiwat;
12813 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
12814 
12815 		ASSERT(peer_tcp != NULL);
12816 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
12817 		if (!tcp_detached) {
12818 			(void) proto_set_rx_hiwat(connp->conn_rq, connp,
12819 			    sth_hiwat);
12820 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
12821 		}
12822 
12823 		/*
12824 		 * In the fusion case, the maxpsz stream head value of
12825 		 * our peer is set according to its send buffer size
12826 		 * and our receive buffer size; since the latter may
12827 		 * have changed we need to update the peer's maxpsz.
12828 		 */
12829 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
12830 		return (sth_hiwat);
12831 	}
12832 
12833 	if (tcp_detached)
12834 		old_max_rwnd = tcp->tcp_rwnd;
12835 	else
12836 		old_max_rwnd = connp->conn_rcvbuf;
12837 
12838 
12839 	/*
12840 	 * If window size info has already been exchanged, TCP should not
12841 	 * shrink the window.  Shrinking window is doable if done carefully.
12842 	 * We may add that support later.  But so far there is not a real
12843 	 * need to do that.
12844 	 */
12845 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
12846 		/* MSS may have changed, do a round up again. */
12847 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
12848 	}
12849 
12850 	/*
12851 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
12852 	 * can be applied even before the window scale option is decided.
12853 	 */
12854 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
12855 	if (rwnd > max_transmittable_rwnd) {
12856 		rwnd = max_transmittable_rwnd -
12857 		    (max_transmittable_rwnd % mss);
12858 		if (rwnd < mss)
12859 			rwnd = max_transmittable_rwnd;
12860 		/*
12861 		 * If we're over the limit we may have to back down tcp_rwnd.
12862 		 * The increment below won't work for us. So we set all three
12863 		 * here and the increment below will have no effect.
12864 		 */
12865 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
12866 	}
12867 	if (tcp->tcp_localnet) {
12868 		tcp->tcp_rack_abs_max =
12869 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
12870 	} else {
12871 		/*
12872 		 * For a remote host on a different subnet (through a router),
12873 		 * we ack every other packet to be conforming to RFC1122.
12874 		 * tcp_deferred_acks_max is default to 2.
12875 		 */
12876 		tcp->tcp_rack_abs_max =
12877 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
12878 	}
12879 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
12880 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
12881 	else
12882 		tcp->tcp_rack_cur_max = 0;
12883 	/*
12884 	 * Increment the current rwnd by the amount the maximum grew (we
12885 	 * can not overwrite it since we might be in the middle of a
12886 	 * connection.)
12887 	 */
12888 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
12889 	connp->conn_rcvbuf = rwnd;
12890 
12891 	/* Are we already connected? */
12892 	if (tcp->tcp_tcpha != NULL) {
12893 		tcp->tcp_tcpha->tha_win =
12894 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
12895 	}
12896 
12897 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
12898 		tcp->tcp_cwnd_max = rwnd;
12899 
12900 	if (tcp_detached)
12901 		return (rwnd);
12902 
12903 	tcp_set_recv_threshold(tcp, rwnd >> 3);
12904 
12905 	(void) proto_set_rx_hiwat(connp->conn_rq, connp, rwnd);
12906 	return (rwnd);
12907 }
12908 
12909 /*
12910  * Return SNMP stuff in buffer in mpdata.
12911  */
12912 mblk_t *
12913 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
12914 {
12915 	mblk_t			*mpdata;
12916 	mblk_t			*mp_conn_ctl = NULL;
12917 	mblk_t			*mp_conn_tail;
12918 	mblk_t			*mp_attr_ctl = NULL;
12919 	mblk_t			*mp_attr_tail;
12920 	mblk_t			*mp6_conn_ctl = NULL;
12921 	mblk_t			*mp6_conn_tail;
12922 	mblk_t			*mp6_attr_ctl = NULL;
12923 	mblk_t			*mp6_attr_tail;
12924 	struct opthdr		*optp;
12925 	mib2_tcpConnEntry_t	tce;
12926 	mib2_tcp6ConnEntry_t	tce6;
12927 	mib2_transportMLPEntry_t mlp;
12928 	connf_t			*connfp;
12929 	int			i;
12930 	boolean_t 		ispriv;
12931 	zoneid_t 		zoneid;
12932 	int			v4_conn_idx;
12933 	int			v6_conn_idx;
12934 	conn_t			*connp = Q_TO_CONN(q);
12935 	tcp_stack_t		*tcps;
12936 	ip_stack_t		*ipst;
12937 	mblk_t			*mp2ctl;
12938 
12939 	/*
12940 	 * make a copy of the original message
12941 	 */
12942 	mp2ctl = copymsg(mpctl);
12943 
12944 	if (mpctl == NULL ||
12945 	    (mpdata = mpctl->b_cont) == NULL ||
12946 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
12947 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
12948 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
12949 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
12950 		freemsg(mp_conn_ctl);
12951 		freemsg(mp_attr_ctl);
12952 		freemsg(mp6_conn_ctl);
12953 		freemsg(mp6_attr_ctl);
12954 		freemsg(mpctl);
12955 		freemsg(mp2ctl);
12956 		return (NULL);
12957 	}
12958 
12959 	ipst = connp->conn_netstack->netstack_ip;
12960 	tcps = connp->conn_netstack->netstack_tcp;
12961 
12962 	/* build table of connections -- need count in fixed part */
12963 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
12964 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
12965 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
12966 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
12967 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
12968 
12969 	ispriv =
12970 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
12971 	zoneid = Q_TO_CONN(q)->conn_zoneid;
12972 
12973 	v4_conn_idx = v6_conn_idx = 0;
12974 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
12975 
12976 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
12977 		ipst = tcps->tcps_netstack->netstack_ip;
12978 
12979 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
12980 
12981 		connp = NULL;
12982 
12983 		while ((connp =
12984 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
12985 			tcp_t *tcp;
12986 			boolean_t needattr;
12987 
12988 			if (connp->conn_zoneid != zoneid)
12989 				continue;	/* not in this zone */
12990 
12991 			tcp = connp->conn_tcp;
12992 			UPDATE_MIB(&tcps->tcps_mib,
12993 			    tcpHCInSegs, tcp->tcp_ibsegs);
12994 			tcp->tcp_ibsegs = 0;
12995 			UPDATE_MIB(&tcps->tcps_mib,
12996 			    tcpHCOutSegs, tcp->tcp_obsegs);
12997 			tcp->tcp_obsegs = 0;
12998 
12999 			tce6.tcp6ConnState = tce.tcpConnState =
13000 			    tcp_snmp_state(tcp);
13001 			if (tce.tcpConnState == MIB2_TCP_established ||
13002 			    tce.tcpConnState == MIB2_TCP_closeWait)
13003 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
13004 
13005 			needattr = B_FALSE;
13006 			bzero(&mlp, sizeof (mlp));
13007 			if (connp->conn_mlp_type != mlptSingle) {
13008 				if (connp->conn_mlp_type == mlptShared ||
13009 				    connp->conn_mlp_type == mlptBoth)
13010 					mlp.tme_flags |= MIB2_TMEF_SHARED;
13011 				if (connp->conn_mlp_type == mlptPrivate ||
13012 				    connp->conn_mlp_type == mlptBoth)
13013 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
13014 				needattr = B_TRUE;
13015 			}
13016 			if (connp->conn_anon_mlp) {
13017 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
13018 				needattr = B_TRUE;
13019 			}
13020 			switch (connp->conn_mac_mode) {
13021 			case CONN_MAC_DEFAULT:
13022 				break;
13023 			case CONN_MAC_AWARE:
13024 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
13025 				needattr = B_TRUE;
13026 				break;
13027 			case CONN_MAC_IMPLICIT:
13028 				mlp.tme_flags |= MIB2_TMEF_MACIMPLICIT;
13029 				needattr = B_TRUE;
13030 				break;
13031 			}
13032 			if (connp->conn_ixa->ixa_tsl != NULL) {
13033 				ts_label_t *tsl;
13034 
13035 				tsl = connp->conn_ixa->ixa_tsl;
13036 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
13037 				mlp.tme_doi = label2doi(tsl);
13038 				mlp.tme_label = *label2bslabel(tsl);
13039 				needattr = B_TRUE;
13040 			}
13041 
13042 			/* Create a message to report on IPv6 entries */
13043 			if (connp->conn_ipversion == IPV6_VERSION) {
13044 			tce6.tcp6ConnLocalAddress = connp->conn_laddr_v6;
13045 			tce6.tcp6ConnRemAddress = connp->conn_faddr_v6;
13046 			tce6.tcp6ConnLocalPort = ntohs(connp->conn_lport);
13047 			tce6.tcp6ConnRemPort = ntohs(connp->conn_fport);
13048 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET) {
13049 				tce6.tcp6ConnIfIndex =
13050 				    connp->conn_ixa->ixa_scopeid;
13051 			} else {
13052 				tce6.tcp6ConnIfIndex = connp->conn_bound_if;
13053 			}
13054 			/* Don't want just anybody seeing these... */
13055 			if (ispriv) {
13056 				tce6.tcp6ConnEntryInfo.ce_snxt =
13057 				    tcp->tcp_snxt;
13058 				tce6.tcp6ConnEntryInfo.ce_suna =
13059 				    tcp->tcp_suna;
13060 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13061 				    tcp->tcp_rnxt;
13062 				tce6.tcp6ConnEntryInfo.ce_rack =
13063 				    tcp->tcp_rack;
13064 			} else {
13065 				/*
13066 				 * Netstat, unfortunately, uses this to
13067 				 * get send/receive queue sizes.  How to fix?
13068 				 * Why not compute the difference only?
13069 				 */
13070 				tce6.tcp6ConnEntryInfo.ce_snxt =
13071 				    tcp->tcp_snxt - tcp->tcp_suna;
13072 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
13073 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13074 				    tcp->tcp_rnxt - tcp->tcp_rack;
13075 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
13076 			}
13077 
13078 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13079 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13080 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
13081 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
13082 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
13083 
13084 			tce6.tcp6ConnCreationProcess =
13085 			    (connp->conn_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
13086 			    connp->conn_cpid;
13087 			tce6.tcp6ConnCreationTime = connp->conn_open_time;
13088 
13089 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
13090 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
13091 
13092 			mlp.tme_connidx = v6_conn_idx++;
13093 			if (needattr)
13094 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
13095 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
13096 			}
13097 			/*
13098 			 * Create an IPv4 table entry for IPv4 entries and also
13099 			 * for IPv6 entries which are bound to in6addr_any
13100 			 * but don't have IPV6_V6ONLY set.
13101 			 * (i.e. anything an IPv4 peer could connect to)
13102 			 */
13103 			if (connp->conn_ipversion == IPV4_VERSION ||
13104 			    (tcp->tcp_state <= TCPS_LISTEN &&
13105 			    !connp->conn_ipv6_v6only &&
13106 			    IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6))) {
13107 				if (connp->conn_ipversion == IPV6_VERSION) {
13108 					tce.tcpConnRemAddress = INADDR_ANY;
13109 					tce.tcpConnLocalAddress = INADDR_ANY;
13110 				} else {
13111 					tce.tcpConnRemAddress =
13112 					    connp->conn_faddr_v4;
13113 					tce.tcpConnLocalAddress =
13114 					    connp->conn_laddr_v4;
13115 				}
13116 				tce.tcpConnLocalPort = ntohs(connp->conn_lport);
13117 				tce.tcpConnRemPort = ntohs(connp->conn_fport);
13118 				/* Don't want just anybody seeing these... */
13119 				if (ispriv) {
13120 					tce.tcpConnEntryInfo.ce_snxt =
13121 					    tcp->tcp_snxt;
13122 					tce.tcpConnEntryInfo.ce_suna =
13123 					    tcp->tcp_suna;
13124 					tce.tcpConnEntryInfo.ce_rnxt =
13125 					    tcp->tcp_rnxt;
13126 					tce.tcpConnEntryInfo.ce_rack =
13127 					    tcp->tcp_rack;
13128 				} else {
13129 					/*
13130 					 * Netstat, unfortunately, uses this to
13131 					 * get send/receive queue sizes.  How
13132 					 * to fix?
13133 					 * Why not compute the difference only?
13134 					 */
13135 					tce.tcpConnEntryInfo.ce_snxt =
13136 					    tcp->tcp_snxt - tcp->tcp_suna;
13137 					tce.tcpConnEntryInfo.ce_suna = 0;
13138 					tce.tcpConnEntryInfo.ce_rnxt =
13139 					    tcp->tcp_rnxt - tcp->tcp_rack;
13140 					tce.tcpConnEntryInfo.ce_rack = 0;
13141 				}
13142 
13143 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13144 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13145 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
13146 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
13147 				tce.tcpConnEntryInfo.ce_state =
13148 				    tcp->tcp_state;
13149 
13150 				tce.tcpConnCreationProcess =
13151 				    (connp->conn_cpid < 0) ?
13152 				    MIB2_UNKNOWN_PROCESS :
13153 				    connp->conn_cpid;
13154 				tce.tcpConnCreationTime = connp->conn_open_time;
13155 
13156 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
13157 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
13158 
13159 				mlp.tme_connidx = v4_conn_idx++;
13160 				if (needattr)
13161 					(void) snmp_append_data2(
13162 					    mp_attr_ctl->b_cont,
13163 					    &mp_attr_tail, (char *)&mlp,
13164 					    sizeof (mlp));
13165 			}
13166 		}
13167 	}
13168 
13169 	/* fixed length structure for IPv4 and IPv6 counters */
13170 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
13171 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
13172 	    sizeof (mib2_tcp6ConnEntry_t));
13173 	/* synchronize 32- and 64-bit counters */
13174 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
13175 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
13176 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
13177 	optp->level = MIB2_TCP;
13178 	optp->name = 0;
13179 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
13180 	    sizeof (tcps->tcps_mib));
13181 	optp->len = msgdsize(mpdata);
13182 	qreply(q, mpctl);
13183 
13184 	/* table of connections... */
13185 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
13186 	    sizeof (struct T_optmgmt_ack)];
13187 	optp->level = MIB2_TCP;
13188 	optp->name = MIB2_TCP_CONN;
13189 	optp->len = msgdsize(mp_conn_ctl->b_cont);
13190 	qreply(q, mp_conn_ctl);
13191 
13192 	/* table of MLP attributes... */
13193 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
13194 	    sizeof (struct T_optmgmt_ack)];
13195 	optp->level = MIB2_TCP;
13196 	optp->name = EXPER_XPORT_MLP;
13197 	optp->len = msgdsize(mp_attr_ctl->b_cont);
13198 	if (optp->len == 0)
13199 		freemsg(mp_attr_ctl);
13200 	else
13201 		qreply(q, mp_attr_ctl);
13202 
13203 	/* table of IPv6 connections... */
13204 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
13205 	    sizeof (struct T_optmgmt_ack)];
13206 	optp->level = MIB2_TCP6;
13207 	optp->name = MIB2_TCP6_CONN;
13208 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
13209 	qreply(q, mp6_conn_ctl);
13210 
13211 	/* table of IPv6 MLP attributes... */
13212 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
13213 	    sizeof (struct T_optmgmt_ack)];
13214 	optp->level = MIB2_TCP6;
13215 	optp->name = EXPER_XPORT_MLP;
13216 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
13217 	if (optp->len == 0)
13218 		freemsg(mp6_attr_ctl);
13219 	else
13220 		qreply(q, mp6_attr_ctl);
13221 	return (mp2ctl);
13222 }
13223 
13224 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
13225 /* ARGSUSED */
13226 int
13227 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
13228 {
13229 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
13230 
13231 	switch (level) {
13232 	case MIB2_TCP:
13233 		switch (name) {
13234 		case 13:
13235 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
13236 				return (0);
13237 			/* TODO: delete entry defined by tce */
13238 			return (1);
13239 		default:
13240 			return (0);
13241 		}
13242 	default:
13243 		return (1);
13244 	}
13245 }
13246 
13247 /* Translate TCP state to MIB2 TCP state. */
13248 static int
13249 tcp_snmp_state(tcp_t *tcp)
13250 {
13251 	if (tcp == NULL)
13252 		return (0);
13253 
13254 	switch (tcp->tcp_state) {
13255 	case TCPS_CLOSED:
13256 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
13257 	case TCPS_BOUND:
13258 		return (MIB2_TCP_closed);
13259 	case TCPS_LISTEN:
13260 		return (MIB2_TCP_listen);
13261 	case TCPS_SYN_SENT:
13262 		return (MIB2_TCP_synSent);
13263 	case TCPS_SYN_RCVD:
13264 		return (MIB2_TCP_synReceived);
13265 	case TCPS_ESTABLISHED:
13266 		return (MIB2_TCP_established);
13267 	case TCPS_CLOSE_WAIT:
13268 		return (MIB2_TCP_closeWait);
13269 	case TCPS_FIN_WAIT_1:
13270 		return (MIB2_TCP_finWait1);
13271 	case TCPS_CLOSING:
13272 		return (MIB2_TCP_closing);
13273 	case TCPS_LAST_ACK:
13274 		return (MIB2_TCP_lastAck);
13275 	case TCPS_FIN_WAIT_2:
13276 		return (MIB2_TCP_finWait2);
13277 	case TCPS_TIME_WAIT:
13278 		return (MIB2_TCP_timeWait);
13279 	default:
13280 		return (0);
13281 	}
13282 }
13283 
13284 /*
13285  * tcp_timer is the timer service routine.  It handles the retransmission,
13286  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
13287  * from the state of the tcp instance what kind of action needs to be done
13288  * at the time it is called.
13289  */
13290 static void
13291 tcp_timer(void *arg)
13292 {
13293 	mblk_t		*mp;
13294 	clock_t		first_threshold;
13295 	clock_t		second_threshold;
13296 	clock_t		ms;
13297 	uint32_t	mss;
13298 	conn_t		*connp = (conn_t *)arg;
13299 	tcp_t		*tcp = connp->conn_tcp;
13300 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13301 
13302 	tcp->tcp_timer_tid = 0;
13303 
13304 	if (tcp->tcp_fused)
13305 		return;
13306 
13307 	first_threshold =  tcp->tcp_first_timer_threshold;
13308 	second_threshold = tcp->tcp_second_timer_threshold;
13309 	switch (tcp->tcp_state) {
13310 	case TCPS_IDLE:
13311 	case TCPS_BOUND:
13312 	case TCPS_LISTEN:
13313 		return;
13314 	case TCPS_SYN_RCVD: {
13315 		tcp_t	*listener = tcp->tcp_listener;
13316 
13317 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
13318 			/* it's our first timeout */
13319 			tcp->tcp_syn_rcvd_timeout = 1;
13320 			mutex_enter(&listener->tcp_eager_lock);
13321 			listener->tcp_syn_rcvd_timeout++;
13322 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
13323 				/*
13324 				 * Make this eager available for drop if we
13325 				 * need to drop one to accomodate a new
13326 				 * incoming SYN request.
13327 				 */
13328 				MAKE_DROPPABLE(listener, tcp);
13329 			}
13330 			if (!listener->tcp_syn_defense &&
13331 			    (listener->tcp_syn_rcvd_timeout >
13332 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
13333 			    (tcps->tcps_conn_req_max_q0 > 200)) {
13334 				/* We may be under attack. Put on a defense. */
13335 				listener->tcp_syn_defense = B_TRUE;
13336 				cmn_err(CE_WARN, "High TCP connect timeout "
13337 				    "rate! System (port %d) may be under a "
13338 				    "SYN flood attack!",
13339 				    ntohs(listener->tcp_connp->conn_lport));
13340 
13341 				listener->tcp_ip_addr_cache = kmem_zalloc(
13342 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
13343 				    KM_NOSLEEP);
13344 			}
13345 			mutex_exit(&listener->tcp_eager_lock);
13346 		} else if (listener != NULL) {
13347 			mutex_enter(&listener->tcp_eager_lock);
13348 			tcp->tcp_syn_rcvd_timeout++;
13349 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
13350 			    !tcp->tcp_closemp_used) {
13351 				/*
13352 				 * This is our second timeout. Put the tcp in
13353 				 * the list of droppable eagers to allow it to
13354 				 * be dropped, if needed. We don't check
13355 				 * whether tcp_dontdrop is set or not to
13356 				 * protect ourselve from a SYN attack where a
13357 				 * remote host can spoof itself as one of the
13358 				 * good IP source and continue to hold
13359 				 * resources too long.
13360 				 */
13361 				MAKE_DROPPABLE(listener, tcp);
13362 			}
13363 			mutex_exit(&listener->tcp_eager_lock);
13364 		}
13365 	}
13366 		/* FALLTHRU */
13367 	case TCPS_SYN_SENT:
13368 		first_threshold =  tcp->tcp_first_ctimer_threshold;
13369 		second_threshold = tcp->tcp_second_ctimer_threshold;
13370 		break;
13371 	case TCPS_ESTABLISHED:
13372 	case TCPS_FIN_WAIT_1:
13373 	case TCPS_CLOSING:
13374 	case TCPS_CLOSE_WAIT:
13375 	case TCPS_LAST_ACK:
13376 		/* If we have data to rexmit */
13377 		if (tcp->tcp_suna != tcp->tcp_snxt) {
13378 			clock_t	time_to_wait;
13379 
13380 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
13381 			if (!tcp->tcp_xmit_head)
13382 				break;
13383 			time_to_wait = ddi_get_lbolt() -
13384 			    (clock_t)tcp->tcp_xmit_head->b_prev;
13385 			time_to_wait = tcp->tcp_rto -
13386 			    TICK_TO_MSEC(time_to_wait);
13387 			/*
13388 			 * If the timer fires too early, 1 clock tick earlier,
13389 			 * restart the timer.
13390 			 */
13391 			if (time_to_wait > msec_per_tick) {
13392 				TCP_STAT(tcps, tcp_timer_fire_early);
13393 				TCP_TIMER_RESTART(tcp, time_to_wait);
13394 				return;
13395 			}
13396 			/*
13397 			 * When we probe zero windows, we force the swnd open.
13398 			 * If our peer acks with a closed window swnd will be
13399 			 * set to zero by tcp_rput(). As long as we are
13400 			 * receiving acks tcp_rput will
13401 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
13402 			 * first and second interval actions.  NOTE: the timer
13403 			 * interval is allowed to continue its exponential
13404 			 * backoff.
13405 			 */
13406 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
13407 				if (connp->conn_debug) {
13408 					(void) strlog(TCP_MOD_ID, 0, 1,
13409 					    SL_TRACE, "tcp_timer: zero win");
13410 				}
13411 			} else {
13412 				/*
13413 				 * After retransmission, we need to do
13414 				 * slow start.  Set the ssthresh to one
13415 				 * half of current effective window and
13416 				 * cwnd to one MSS.  Also reset
13417 				 * tcp_cwnd_cnt.
13418 				 *
13419 				 * Note that if tcp_ssthresh is reduced because
13420 				 * of ECN, do not reduce it again unless it is
13421 				 * already one window of data away (tcp_cwr
13422 				 * should then be cleared) or this is a
13423 				 * timeout for a retransmitted segment.
13424 				 */
13425 				uint32_t npkt;
13426 
13427 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
13428 					npkt = ((tcp->tcp_timer_backoff ?
13429 					    tcp->tcp_cwnd_ssthresh :
13430 					    tcp->tcp_snxt -
13431 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
13432 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13433 					    tcp->tcp_mss;
13434 				}
13435 				tcp->tcp_cwnd = tcp->tcp_mss;
13436 				tcp->tcp_cwnd_cnt = 0;
13437 				if (tcp->tcp_ecn_ok) {
13438 					tcp->tcp_cwr = B_TRUE;
13439 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13440 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13441 				}
13442 			}
13443 			break;
13444 		}
13445 		/*
13446 		 * We have something to send yet we cannot send.  The
13447 		 * reason can be:
13448 		 *
13449 		 * 1. Zero send window: we need to do zero window probe.
13450 		 * 2. Zero cwnd: because of ECN, we need to "clock out
13451 		 * segments.
13452 		 * 3. SWS avoidance: receiver may have shrunk window,
13453 		 * reset our knowledge.
13454 		 *
13455 		 * Note that condition 2 can happen with either 1 or
13456 		 * 3.  But 1 and 3 are exclusive.
13457 		 */
13458 		if (tcp->tcp_unsent != 0) {
13459 			/*
13460 			 * Should not hold the zero-copy messages for too long.
13461 			 */
13462 			if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13463 				tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13464 				    tcp->tcp_xmit_head, B_TRUE);
13465 
13466 			if (tcp->tcp_cwnd == 0) {
13467 				/*
13468 				 * Set tcp_cwnd to 1 MSS so that a
13469 				 * new segment can be sent out.  We
13470 				 * are "clocking out" new data when
13471 				 * the network is really congested.
13472 				 */
13473 				ASSERT(tcp->tcp_ecn_ok);
13474 				tcp->tcp_cwnd = tcp->tcp_mss;
13475 			}
13476 			if (tcp->tcp_swnd == 0) {
13477 				/* Extend window for zero window probe */
13478 				tcp->tcp_swnd++;
13479 				tcp->tcp_zero_win_probe = B_TRUE;
13480 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
13481 			} else {
13482 				/*
13483 				 * Handle timeout from sender SWS avoidance.
13484 				 * Reset our knowledge of the max send window
13485 				 * since the receiver might have reduced its
13486 				 * receive buffer.  Avoid setting tcp_max_swnd
13487 				 * to one since that will essentially disable
13488 				 * the SWS checks.
13489 				 *
13490 				 * Note that since we don't have a SWS
13491 				 * state variable, if the timeout is set
13492 				 * for ECN but not for SWS, this
13493 				 * code will also be executed.  This is
13494 				 * fine as tcp_max_swnd is updated
13495 				 * constantly and it will not affect
13496 				 * anything.
13497 				 */
13498 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
13499 			}
13500 			tcp_wput_data(tcp, NULL, B_FALSE);
13501 			return;
13502 		}
13503 		/* Is there a FIN that needs to be to re retransmitted? */
13504 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13505 		    !tcp->tcp_fin_acked)
13506 			break;
13507 		/* Nothing to do, return without restarting timer. */
13508 		TCP_STAT(tcps, tcp_timer_fire_miss);
13509 		return;
13510 	case TCPS_FIN_WAIT_2:
13511 		/*
13512 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
13513 		 * We waited some time for for peer's FIN, but it hasn't
13514 		 * arrived.  We flush the connection now to avoid
13515 		 * case where the peer has rebooted.
13516 		 */
13517 		if (TCP_IS_DETACHED(tcp)) {
13518 			(void) tcp_clean_death(tcp, 0, 23);
13519 		} else {
13520 			TCP_TIMER_RESTART(tcp,
13521 			    tcps->tcps_fin_wait_2_flush_interval);
13522 		}
13523 		return;
13524 	case TCPS_TIME_WAIT:
13525 		(void) tcp_clean_death(tcp, 0, 24);
13526 		return;
13527 	default:
13528 		if (connp->conn_debug) {
13529 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
13530 			    "tcp_timer: strange state (%d) %s",
13531 			    tcp->tcp_state, tcp_display(tcp, NULL,
13532 			    DISP_PORT_ONLY));
13533 		}
13534 		return;
13535 	}
13536 
13537 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
13538 		/*
13539 		 * Should not hold the zero-copy messages for too long.
13540 		 */
13541 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13542 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13543 			    tcp->tcp_xmit_head, B_TRUE);
13544 
13545 		/*
13546 		 * For zero window probe, we need to send indefinitely,
13547 		 * unless we have not heard from the other side for some
13548 		 * time...
13549 		 */
13550 		if ((tcp->tcp_zero_win_probe == 0) ||
13551 		    (TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time) >
13552 		    second_threshold)) {
13553 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
13554 			/*
13555 			 * If TCP is in SYN_RCVD state, send back a
13556 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
13557 			 * should be zero in TCPS_SYN_RCVD state.
13558 			 */
13559 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
13560 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
13561 				    "in SYN_RCVD",
13562 				    tcp, tcp->tcp_snxt,
13563 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
13564 			}
13565 			(void) tcp_clean_death(tcp,
13566 			    tcp->tcp_client_errno ?
13567 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
13568 			return;
13569 		} else {
13570 			/*
13571 			 * Set tcp_ms_we_have_waited to second_threshold
13572 			 * so that in next timeout, we will do the above
13573 			 * check (ddi_get_lbolt() - tcp_last_recv_time).
13574 			 * This is also to avoid overflow.
13575 			 *
13576 			 * We don't need to decrement tcp_timer_backoff
13577 			 * to avoid overflow because it will be decremented
13578 			 * later if new timeout value is greater than
13579 			 * tcp_rexmit_interval_max.  In the case when
13580 			 * tcp_rexmit_interval_max is greater than
13581 			 * second_threshold, it means that we will wait
13582 			 * longer than second_threshold to send the next
13583 			 * window probe.
13584 			 */
13585 			tcp->tcp_ms_we_have_waited = second_threshold;
13586 		}
13587 	} else if (ms > first_threshold) {
13588 		/*
13589 		 * Should not hold the zero-copy messages for too long.
13590 		 */
13591 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13592 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13593 			    tcp->tcp_xmit_head, B_TRUE);
13594 
13595 		/*
13596 		 * We have been retransmitting for too long...  The RTT
13597 		 * we calculated is probably incorrect.  Reinitialize it.
13598 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
13599 		 * tcp_rtt_update so that we won't accidentally cache a
13600 		 * bad value.  But only do this if this is not a zero
13601 		 * window probe.
13602 		 */
13603 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
13604 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
13605 			    (tcp->tcp_rtt_sa >> 5);
13606 			tcp->tcp_rtt_sa = 0;
13607 			tcp_ip_notify(tcp);
13608 			tcp->tcp_rtt_update = 0;
13609 		}
13610 	}
13611 	tcp->tcp_timer_backoff++;
13612 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
13613 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
13614 	    tcps->tcps_rexmit_interval_min) {
13615 		/*
13616 		 * This means the original RTO is tcp_rexmit_interval_min.
13617 		 * So we will use tcp_rexmit_interval_min as the RTO value
13618 		 * and do the backoff.
13619 		 */
13620 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
13621 	} else {
13622 		ms <<= tcp->tcp_timer_backoff;
13623 	}
13624 	if (ms > tcps->tcps_rexmit_interval_max) {
13625 		ms = tcps->tcps_rexmit_interval_max;
13626 		/*
13627 		 * ms is at max, decrement tcp_timer_backoff to avoid
13628 		 * overflow.
13629 		 */
13630 		tcp->tcp_timer_backoff--;
13631 	}
13632 	tcp->tcp_ms_we_have_waited += ms;
13633 	if (tcp->tcp_zero_win_probe == 0) {
13634 		tcp->tcp_rto = ms;
13635 	}
13636 	TCP_TIMER_RESTART(tcp, ms);
13637 	/*
13638 	 * This is after a timeout and tcp_rto is backed off.  Set
13639 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
13640 	 * restart the timer with a correct value.
13641 	 */
13642 	tcp->tcp_set_timer = 1;
13643 	mss = tcp->tcp_snxt - tcp->tcp_suna;
13644 	if (mss > tcp->tcp_mss)
13645 		mss = tcp->tcp_mss;
13646 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
13647 		mss = tcp->tcp_swnd;
13648 
13649 	if ((mp = tcp->tcp_xmit_head) != NULL)
13650 		mp->b_prev = (mblk_t *)ddi_get_lbolt();
13651 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
13652 	    B_TRUE);
13653 
13654 	/*
13655 	 * When slow start after retransmission begins, start with
13656 	 * this seq no.  tcp_rexmit_max marks the end of special slow
13657 	 * start phase.  tcp_snd_burst controls how many segments
13658 	 * can be sent because of an ack.
13659 	 */
13660 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13661 	tcp->tcp_snd_burst = TCP_CWND_SS;
13662 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13663 	    (tcp->tcp_unsent == 0)) {
13664 		tcp->tcp_rexmit_max = tcp->tcp_fss;
13665 	} else {
13666 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
13667 	}
13668 	tcp->tcp_rexmit = B_TRUE;
13669 	tcp->tcp_dupack_cnt = 0;
13670 
13671 	/*
13672 	 * Remove all rexmit SACK blk to start from fresh.
13673 	 */
13674 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
13675 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
13676 	if (mp == NULL) {
13677 		return;
13678 	}
13679 
13680 	tcp->tcp_csuna = tcp->tcp_snxt;
13681 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
13682 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
13683 	tcp_send_data(tcp, mp);
13684 
13685 }
13686 
13687 static int
13688 tcp_do_unbind(conn_t *connp)
13689 {
13690 	tcp_t *tcp = connp->conn_tcp;
13691 
13692 	switch (tcp->tcp_state) {
13693 	case TCPS_BOUND:
13694 	case TCPS_LISTEN:
13695 		break;
13696 	default:
13697 		return (-TOUTSTATE);
13698 	}
13699 
13700 	/*
13701 	 * Need to clean up all the eagers since after the unbind, segments
13702 	 * will no longer be delivered to this listener stream.
13703 	 */
13704 	mutex_enter(&tcp->tcp_eager_lock);
13705 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
13706 		tcp_eager_cleanup(tcp, 0);
13707 	}
13708 	mutex_exit(&tcp->tcp_eager_lock);
13709 
13710 	connp->conn_laddr_v6 = ipv6_all_zeros;
13711 	connp->conn_saddr_v6 = ipv6_all_zeros;
13712 	tcp_bind_hash_remove(tcp);
13713 	tcp->tcp_state = TCPS_IDLE;
13714 
13715 	ip_unbind(connp);
13716 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
13717 
13718 	return (0);
13719 }
13720 
13721 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
13722 static void
13723 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
13724 {
13725 	conn_t *connp = tcp->tcp_connp;
13726 	int error;
13727 
13728 	error = tcp_do_unbind(connp);
13729 	if (error > 0) {
13730 		tcp_err_ack(tcp, mp, TSYSERR, error);
13731 	} else if (error < 0) {
13732 		tcp_err_ack(tcp, mp, -error, 0);
13733 	} else {
13734 		/* Send M_FLUSH according to TPI */
13735 		(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
13736 
13737 		mp = mi_tpi_ok_ack_alloc(mp);
13738 		if (mp != NULL)
13739 			putnext(connp->conn_rq, mp);
13740 	}
13741 }
13742 
13743 /*
13744  * Don't let port fall into the privileged range.
13745  * Since the extra privileged ports can be arbitrary we also
13746  * ensure that we exclude those from consideration.
13747  * tcp_g_epriv_ports is not sorted thus we loop over it until
13748  * there are no changes.
13749  *
13750  * Note: No locks are held when inspecting tcp_g_*epriv_ports
13751  * but instead the code relies on:
13752  * - the fact that the address of the array and its size never changes
13753  * - the atomic assignment of the elements of the array
13754  *
13755  * Returns 0 if there are no more ports available.
13756  *
13757  * TS note: skip multilevel ports.
13758  */
13759 static in_port_t
13760 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
13761 {
13762 	int i;
13763 	boolean_t restart = B_FALSE;
13764 	tcp_stack_t *tcps = tcp->tcp_tcps;
13765 
13766 	if (random && tcp_random_anon_port != 0) {
13767 		(void) random_get_pseudo_bytes((uint8_t *)&port,
13768 		    sizeof (in_port_t));
13769 		/*
13770 		 * Unless changed by a sys admin, the smallest anon port
13771 		 * is 32768 and the largest anon port is 65535.  It is
13772 		 * very likely (50%) for the random port to be smaller
13773 		 * than the smallest anon port.  When that happens,
13774 		 * add port % (anon port range) to the smallest anon
13775 		 * port to get the random port.  It should fall into the
13776 		 * valid anon port range.
13777 		 */
13778 		if (port < tcps->tcps_smallest_anon_port) {
13779 			port = tcps->tcps_smallest_anon_port +
13780 			    port % (tcps->tcps_largest_anon_port -
13781 			    tcps->tcps_smallest_anon_port);
13782 		}
13783 	}
13784 
13785 retry:
13786 	if (port < tcps->tcps_smallest_anon_port)
13787 		port = (in_port_t)tcps->tcps_smallest_anon_port;
13788 
13789 	if (port > tcps->tcps_largest_anon_port) {
13790 		if (restart)
13791 			return (0);
13792 		restart = B_TRUE;
13793 		port = (in_port_t)tcps->tcps_smallest_anon_port;
13794 	}
13795 
13796 	if (port < tcps->tcps_smallest_nonpriv_port)
13797 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
13798 
13799 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
13800 		if (port == tcps->tcps_g_epriv_ports[i]) {
13801 			port++;
13802 			/*
13803 			 * Make sure whether the port is in the
13804 			 * valid range.
13805 			 */
13806 			goto retry;
13807 		}
13808 	}
13809 	if (is_system_labeled() &&
13810 	    (i = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred), port,
13811 	    IPPROTO_TCP, B_TRUE)) != 0) {
13812 		port = i;
13813 		goto retry;
13814 	}
13815 	return (port);
13816 }
13817 
13818 /*
13819  * Return the next anonymous port in the privileged port range for
13820  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
13821  * downwards.  This is the same behavior as documented in the userland
13822  * library call rresvport(3N).
13823  *
13824  * TS note: skip multilevel ports.
13825  */
13826 static in_port_t
13827 tcp_get_next_priv_port(const tcp_t *tcp)
13828 {
13829 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
13830 	in_port_t nextport;
13831 	boolean_t restart = B_FALSE;
13832 	tcp_stack_t *tcps = tcp->tcp_tcps;
13833 retry:
13834 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
13835 	    next_priv_port >= IPPORT_RESERVED) {
13836 		next_priv_port = IPPORT_RESERVED - 1;
13837 		if (restart)
13838 			return (0);
13839 		restart = B_TRUE;
13840 	}
13841 	if (is_system_labeled() &&
13842 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred),
13843 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
13844 		next_priv_port = nextport;
13845 		goto retry;
13846 	}
13847 	return (next_priv_port--);
13848 }
13849 
13850 /* The write side r/w procedure. */
13851 
13852 #if CCS_STATS
13853 struct {
13854 	struct {
13855 		int64_t count, bytes;
13856 	} tot, hit;
13857 } wrw_stats;
13858 #endif
13859 
13860 /*
13861  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
13862  * messages.
13863  */
13864 /* ARGSUSED */
13865 static void
13866 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
13867 {
13868 	conn_t	*connp = (conn_t *)arg;
13869 	tcp_t	*tcp = connp->conn_tcp;
13870 
13871 	ASSERT(DB_TYPE(mp) != M_IOCTL);
13872 	/*
13873 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
13874 	 * Once the close starts, streamhead and sockfs will not let any data
13875 	 * packets come down (close ensures that there are no threads using the
13876 	 * queue and no new threads will come down) but since qprocsoff()
13877 	 * hasn't happened yet, a M_FLUSH or some non data message might
13878 	 * get reflected back (in response to our own FLUSHRW) and get
13879 	 * processed after tcp_close() is done. The conn would still be valid
13880 	 * because a ref would have added but we need to check the state
13881 	 * before actually processing the packet.
13882 	 */
13883 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
13884 		freemsg(mp);
13885 		return;
13886 	}
13887 
13888 	switch (DB_TYPE(mp)) {
13889 	case M_IOCDATA:
13890 		tcp_wput_iocdata(tcp, mp);
13891 		break;
13892 	case M_FLUSH:
13893 		tcp_wput_flush(tcp, mp);
13894 		break;
13895 	default:
13896 		ip_wput_nondata(connp->conn_wq, mp);
13897 		break;
13898 	}
13899 }
13900 
13901 /*
13902  * The TCP fast path write put procedure.
13903  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
13904  */
13905 /* ARGSUSED */
13906 void
13907 tcp_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
13908 {
13909 	int		len;
13910 	int		hdrlen;
13911 	int		plen;
13912 	mblk_t		*mp1;
13913 	uchar_t		*rptr;
13914 	uint32_t	snxt;
13915 	tcpha_t		*tcpha;
13916 	struct datab	*db;
13917 	uint32_t	suna;
13918 	uint32_t	mss;
13919 	ipaddr_t	*dst;
13920 	ipaddr_t	*src;
13921 	uint32_t	sum;
13922 	int		usable;
13923 	conn_t		*connp = (conn_t *)arg;
13924 	tcp_t		*tcp = connp->conn_tcp;
13925 	uint32_t	msize;
13926 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13927 	ip_xmit_attr_t	*ixa;
13928 	clock_t		now;
13929 
13930 	/*
13931 	 * Try and ASSERT the minimum possible references on the
13932 	 * conn early enough. Since we are executing on write side,
13933 	 * the connection is obviously not detached and that means
13934 	 * there is a ref each for TCP and IP. Since we are behind
13935 	 * the squeue, the minimum references needed are 3. If the
13936 	 * conn is in classifier hash list, there should be an
13937 	 * extra ref for that (we check both the possibilities).
13938 	 */
13939 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
13940 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
13941 
13942 	ASSERT(DB_TYPE(mp) == M_DATA);
13943 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
13944 
13945 	mutex_enter(&tcp->tcp_non_sq_lock);
13946 	tcp->tcp_squeue_bytes -= msize;
13947 	mutex_exit(&tcp->tcp_non_sq_lock);
13948 
13949 	/* Bypass tcp protocol for fused tcp loopback */
13950 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
13951 		return;
13952 
13953 	mss = tcp->tcp_mss;
13954 	/*
13955 	 * If ZEROCOPY has turned off, try not to send any zero-copy message
13956 	 * down. Do backoff, now.
13957 	 */
13958 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on)
13959 		mp = tcp_zcopy_backoff(tcp, mp, B_FALSE);
13960 
13961 
13962 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
13963 	len = (int)(mp->b_wptr - mp->b_rptr);
13964 
13965 	/*
13966 	 * Criteria for fast path:
13967 	 *
13968 	 *   1. no unsent data
13969 	 *   2. single mblk in request
13970 	 *   3. connection established
13971 	 *   4. data in mblk
13972 	 *   5. len <= mss
13973 	 *   6. no tcp_valid bits
13974 	 */
13975 	if ((tcp->tcp_unsent != 0) ||
13976 	    (tcp->tcp_cork) ||
13977 	    (mp->b_cont != NULL) ||
13978 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
13979 	    (len == 0) ||
13980 	    (len > mss) ||
13981 	    (tcp->tcp_valid_bits != 0)) {
13982 		tcp_wput_data(tcp, mp, B_FALSE);
13983 		return;
13984 	}
13985 
13986 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
13987 	ASSERT(tcp->tcp_fin_sent == 0);
13988 
13989 	/* queue new packet onto retransmission queue */
13990 	if (tcp->tcp_xmit_head == NULL) {
13991 		tcp->tcp_xmit_head = mp;
13992 	} else {
13993 		tcp->tcp_xmit_last->b_cont = mp;
13994 	}
13995 	tcp->tcp_xmit_last = mp;
13996 	tcp->tcp_xmit_tail = mp;
13997 
13998 	/* find out how much we can send */
13999 	/* BEGIN CSTYLED */
14000 	/*
14001 	 *    un-acked	   usable
14002 	 *  |--------------|-----------------|
14003 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
14004 	 */
14005 	/* END CSTYLED */
14006 
14007 	/* start sending from tcp_snxt */
14008 	snxt = tcp->tcp_snxt;
14009 
14010 	/*
14011 	 * Check to see if this connection has been idled for some
14012 	 * time and no ACK is expected.  If it is, we need to slow
14013 	 * start again to get back the connection's "self-clock" as
14014 	 * described in VJ's paper.
14015 	 *
14016 	 * Reinitialize tcp_cwnd after idle.
14017 	 */
14018 	now = LBOLT_FASTPATH;
14019 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
14020 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
14021 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
14022 	}
14023 
14024 	usable = tcp->tcp_swnd;		/* tcp window size */
14025 	if (usable > tcp->tcp_cwnd)
14026 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
14027 	usable -= snxt;		/* subtract stuff already sent */
14028 	suna = tcp->tcp_suna;
14029 	usable += suna;
14030 	/* usable can be < 0 if the congestion window is smaller */
14031 	if (len > usable) {
14032 		/* Can't send complete M_DATA in one shot */
14033 		goto slow;
14034 	}
14035 
14036 	mutex_enter(&tcp->tcp_non_sq_lock);
14037 	if (tcp->tcp_flow_stopped &&
14038 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
14039 		tcp_clrqfull(tcp);
14040 	}
14041 	mutex_exit(&tcp->tcp_non_sq_lock);
14042 
14043 	/*
14044 	 * determine if anything to send (Nagle).
14045 	 *
14046 	 *   1. len < tcp_mss (i.e. small)
14047 	 *   2. unacknowledged data present
14048 	 *   3. len < nagle limit
14049 	 *   4. last packet sent < nagle limit (previous packet sent)
14050 	 */
14051 	if ((len < mss) && (snxt != suna) &&
14052 	    (len < (int)tcp->tcp_naglim) &&
14053 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
14054 		/*
14055 		 * This was the first unsent packet and normally
14056 		 * mss < xmit_hiwater so there is no need to worry
14057 		 * about flow control. The next packet will go
14058 		 * through the flow control check in tcp_wput_data().
14059 		 */
14060 		/* leftover work from above */
14061 		tcp->tcp_unsent = len;
14062 		tcp->tcp_xmit_tail_unsent = len;
14063 
14064 		return;
14065 	}
14066 
14067 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
14068 
14069 	if (snxt == suna) {
14070 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14071 	}
14072 
14073 	/* we have always sent something */
14074 	tcp->tcp_rack_cnt = 0;
14075 
14076 	tcp->tcp_snxt = snxt + len;
14077 	tcp->tcp_rack = tcp->tcp_rnxt;
14078 
14079 	if ((mp1 = dupb(mp)) == 0)
14080 		goto no_memory;
14081 	mp->b_prev = (mblk_t *)(uintptr_t)now;
14082 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
14083 
14084 	/* adjust tcp header information */
14085 	tcpha = tcp->tcp_tcpha;
14086 	tcpha->tha_flags = (TH_ACK|TH_PUSH);
14087 
14088 	sum = len + connp->conn_ht_ulp_len + connp->conn_sum;
14089 	sum = (sum >> 16) + (sum & 0xFFFF);
14090 	tcpha->tha_sum = htons(sum);
14091 
14092 	tcpha->tha_seq = htonl(snxt);
14093 
14094 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
14095 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
14096 	BUMP_LOCAL(tcp->tcp_obsegs);
14097 
14098 	/* Update the latest receive window size in TCP header. */
14099 	tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
14100 
14101 	tcp->tcp_last_sent_len = (ushort_t)len;
14102 
14103 	plen = len + connp->conn_ht_iphc_len;
14104 
14105 	ixa = connp->conn_ixa;
14106 	ixa->ixa_pktlen = plen;
14107 
14108 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
14109 		tcp->tcp_ipha->ipha_length = htons(plen);
14110 	} else {
14111 		tcp->tcp_ip6h->ip6_plen = htons(plen - IPV6_HDR_LEN);
14112 	}
14113 
14114 	/* see if we need to allocate a mblk for the headers */
14115 	hdrlen = connp->conn_ht_iphc_len;
14116 	rptr = mp1->b_rptr - hdrlen;
14117 	db = mp1->b_datap;
14118 	if ((db->db_ref != 2) || rptr < db->db_base ||
14119 	    (!OK_32PTR(rptr))) {
14120 		/* NOTE: we assume allocb returns an OK_32PTR */
14121 		mp = allocb(hdrlen + tcps->tcps_wroff_xtra, BPRI_MED);
14122 		if (!mp) {
14123 			freemsg(mp1);
14124 			goto no_memory;
14125 		}
14126 		mp->b_cont = mp1;
14127 		mp1 = mp;
14128 		/* Leave room for Link Level header */
14129 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
14130 		mp1->b_wptr = &rptr[hdrlen];
14131 	}
14132 	mp1->b_rptr = rptr;
14133 
14134 	/* Fill in the timestamp option. */
14135 	if (tcp->tcp_snd_ts_ok) {
14136 		uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
14137 
14138 		U32_TO_BE32(llbolt,
14139 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
14140 		U32_TO_BE32(tcp->tcp_ts_recent,
14141 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
14142 	} else {
14143 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
14144 	}
14145 
14146 	/* copy header into outgoing packet */
14147 	dst = (ipaddr_t *)rptr;
14148 	src = (ipaddr_t *)connp->conn_ht_iphc;
14149 	dst[0] = src[0];
14150 	dst[1] = src[1];
14151 	dst[2] = src[2];
14152 	dst[3] = src[3];
14153 	dst[4] = src[4];
14154 	dst[5] = src[5];
14155 	dst[6] = src[6];
14156 	dst[7] = src[7];
14157 	dst[8] = src[8];
14158 	dst[9] = src[9];
14159 	if (hdrlen -= 40) {
14160 		hdrlen >>= 2;
14161 		dst += 10;
14162 		src += 10;
14163 		do {
14164 			*dst++ = *src++;
14165 		} while (--hdrlen);
14166 	}
14167 
14168 	/*
14169 	 * Set the ECN info in the TCP header.  Note that this
14170 	 * is not the template header.
14171 	 */
14172 	if (tcp->tcp_ecn_ok) {
14173 		SET_ECT(tcp, rptr);
14174 
14175 		tcpha = (tcpha_t *)(rptr + ixa->ixa_ip_hdr_length);
14176 		if (tcp->tcp_ecn_echo_on)
14177 			tcpha->tha_flags |= TH_ECE;
14178 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
14179 			tcpha->tha_flags |= TH_CWR;
14180 			tcp->tcp_ecn_cwr_sent = B_TRUE;
14181 		}
14182 	}
14183 
14184 	if (tcp->tcp_ip_forward_progress) {
14185 		tcp->tcp_ip_forward_progress = B_FALSE;
14186 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
14187 	} else {
14188 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
14189 	}
14190 	tcp_send_data(tcp, mp1);
14191 	return;
14192 
14193 	/*
14194 	 * If we ran out of memory, we pretend to have sent the packet
14195 	 * and that it was lost on the wire.
14196 	 */
14197 no_memory:
14198 	return;
14199 
14200 slow:
14201 	/* leftover work from above */
14202 	tcp->tcp_unsent = len;
14203 	tcp->tcp_xmit_tail_unsent = len;
14204 	tcp_wput_data(tcp, NULL, B_FALSE);
14205 }
14206 
14207 /*
14208  * This runs at the tail end of accept processing on the squeue of the
14209  * new connection.
14210  */
14211 /* ARGSUSED */
14212 void
14213 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14214 {
14215 	conn_t			*connp = (conn_t *)arg;
14216 	tcp_t			*tcp = connp->conn_tcp;
14217 	queue_t			*q = connp->conn_rq;
14218 	tcp_stack_t		*tcps = tcp->tcp_tcps;
14219 	/* socket options */
14220 	struct sock_proto_props	sopp;
14221 
14222 	/* We should just receive a single mblk that fits a T_discon_ind */
14223 	ASSERT(mp->b_cont == NULL);
14224 
14225 	/*
14226 	 * Drop the eager's ref on the listener, that was placed when
14227 	 * this eager began life in tcp_input_listener.
14228 	 */
14229 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
14230 	if (IPCL_IS_NONSTR(connp)) {
14231 		/* Safe to free conn_ind message */
14232 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
14233 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14234 	}
14235 
14236 	tcp->tcp_detached = B_FALSE;
14237 
14238 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
14239 		/*
14240 		 * Someone blewoff the eager before we could finish
14241 		 * the accept.
14242 		 *
14243 		 * The only reason eager exists it because we put in
14244 		 * a ref on it when conn ind went up. We need to send
14245 		 * a disconnect indication up while the last reference
14246 		 * on the eager will be dropped by the squeue when we
14247 		 * return.
14248 		 */
14249 		ASSERT(tcp->tcp_listener == NULL);
14250 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
14251 			if (IPCL_IS_NONSTR(connp)) {
14252 				ASSERT(tcp->tcp_issocket);
14253 				(*connp->conn_upcalls->su_disconnected)(
14254 				    connp->conn_upper_handle, tcp->tcp_connid,
14255 				    ECONNREFUSED);
14256 				freemsg(mp);
14257 			} else {
14258 				struct	T_discon_ind	*tdi;
14259 
14260 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
14261 				/*
14262 				 * Let us reuse the incoming mblk to avoid
14263 				 * memory allocation failure problems. We know
14264 				 * that the size of the incoming mblk i.e.
14265 				 * stroptions is greater than sizeof
14266 				 * T_discon_ind.
14267 				 */
14268 				ASSERT(DB_REF(mp) == 1);
14269 				ASSERT(MBLKSIZE(mp) >=
14270 				    sizeof (struct T_discon_ind));
14271 
14272 				DB_TYPE(mp) = M_PROTO;
14273 				((union T_primitives *)mp->b_rptr)->type =
14274 				    T_DISCON_IND;
14275 				tdi = (struct T_discon_ind *)mp->b_rptr;
14276 				if (tcp->tcp_issocket) {
14277 					tdi->DISCON_reason = ECONNREFUSED;
14278 					tdi->SEQ_number = 0;
14279 				} else {
14280 					tdi->DISCON_reason = ENOPROTOOPT;
14281 					tdi->SEQ_number =
14282 					    tcp->tcp_conn_req_seqnum;
14283 				}
14284 				mp->b_wptr = mp->b_rptr +
14285 				    sizeof (struct T_discon_ind);
14286 				putnext(q, mp);
14287 			}
14288 		}
14289 		tcp->tcp_hard_binding = B_FALSE;
14290 		return;
14291 	}
14292 
14293 	/*
14294 	 * Set max window size (conn_rcvbuf) of the acceptor.
14295 	 */
14296 	if (tcp->tcp_rcv_list == NULL) {
14297 		/*
14298 		 * Recv queue is empty, tcp_rwnd should not have changed.
14299 		 * That means it should be equal to the listener's tcp_rwnd.
14300 		 */
14301 		connp->conn_rcvbuf = tcp->tcp_rwnd;
14302 	} else {
14303 #ifdef DEBUG
14304 		mblk_t *tmp;
14305 		mblk_t	*mp1;
14306 		uint_t	cnt = 0;
14307 
14308 		mp1 = tcp->tcp_rcv_list;
14309 		while ((tmp = mp1) != NULL) {
14310 			mp1 = tmp->b_next;
14311 			cnt += msgdsize(tmp);
14312 		}
14313 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
14314 #endif
14315 		/* There is some data, add them back to get the max. */
14316 		connp->conn_rcvbuf = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
14317 	}
14318 	/*
14319 	 * This is the first time we run on the correct
14320 	 * queue after tcp_accept. So fix all the q parameters
14321 	 * here.
14322 	 */
14323 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
14324 	sopp.sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
14325 
14326 	sopp.sopp_rxhiwat = tcp->tcp_fused ?
14327 	    tcp_fuse_set_rcv_hiwat(tcp, connp->conn_rcvbuf) :
14328 	    connp->conn_rcvbuf;
14329 
14330 	/*
14331 	 * Determine what write offset value to use depending on SACK and
14332 	 * whether the endpoint is fused or not.
14333 	 */
14334 	if (tcp->tcp_fused) {
14335 		ASSERT(tcp->tcp_loopback);
14336 		ASSERT(tcp->tcp_loopback_peer != NULL);
14337 		/*
14338 		 * For fused tcp loopback, set the stream head's write
14339 		 * offset value to zero since we won't be needing any room
14340 		 * for TCP/IP headers.  This would also improve performance
14341 		 * since it would reduce the amount of work done by kmem.
14342 		 * Non-fused tcp loopback case is handled separately below.
14343 		 */
14344 		sopp.sopp_wroff = 0;
14345 		/*
14346 		 * Update the peer's transmit parameters according to
14347 		 * our recently calculated high water mark value.
14348 		 */
14349 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
14350 	} else if (tcp->tcp_snd_sack_ok) {
14351 		sopp.sopp_wroff = connp->conn_ht_iphc_allocated +
14352 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14353 	} else {
14354 		sopp.sopp_wroff = connp->conn_ht_iphc_len +
14355 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14356 	}
14357 
14358 	/*
14359 	 * If this is endpoint is handling SSL, then reserve extra
14360 	 * offset and space at the end.
14361 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
14362 	 * overriding the previous setting. The extra cost of signing and
14363 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
14364 	 * instead of a single contiguous one by the stream head
14365 	 * largely outweighs the statistical reduction of ACKs, when
14366 	 * applicable. The peer will also save on decryption and verification
14367 	 * costs.
14368 	 */
14369 	if (tcp->tcp_kssl_ctx != NULL) {
14370 		sopp.sopp_wroff += SSL3_WROFFSET;
14371 
14372 		sopp.sopp_flags |= SOCKOPT_TAIL;
14373 		sopp.sopp_tail = SSL3_MAX_TAIL_LEN;
14374 
14375 		sopp.sopp_flags |= SOCKOPT_ZCOPY;
14376 		sopp.sopp_zcopyflag = ZCVMUNSAFE;
14377 
14378 		sopp.sopp_maxblk = SSL3_MAX_RECORD_LEN;
14379 	}
14380 
14381 	/* Send the options up */
14382 	if (IPCL_IS_NONSTR(connp)) {
14383 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14384 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14385 			ASSERT(sopp.sopp_flags & SOCKOPT_ZCOPY);
14386 		}
14387 		if (tcp->tcp_loopback) {
14388 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
14389 			sopp.sopp_loopback = B_TRUE;
14390 		}
14391 		(*connp->conn_upcalls->su_set_proto_props)
14392 		    (connp->conn_upper_handle, &sopp);
14393 		freemsg(mp);
14394 	} else {
14395 		/*
14396 		 * Let us reuse the incoming mblk to avoid
14397 		 * memory allocation failure problems. We know
14398 		 * that the size of the incoming mblk is at least
14399 		 * stroptions
14400 		 */
14401 		struct stroptions *stropt;
14402 
14403 		ASSERT(DB_REF(mp) == 1);
14404 		ASSERT(MBLKSIZE(mp) >= sizeof (struct stroptions));
14405 
14406 		DB_TYPE(mp) = M_SETOPTS;
14407 		stropt = (struct stroptions *)mp->b_rptr;
14408 		mp->b_wptr = mp->b_rptr + sizeof (struct stroptions);
14409 		stropt = (struct stroptions *)mp->b_rptr;
14410 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
14411 		stropt->so_hiwat = sopp.sopp_rxhiwat;
14412 		stropt->so_wroff = sopp.sopp_wroff;
14413 		stropt->so_maxblk = sopp.sopp_maxblk;
14414 
14415 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14416 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14417 
14418 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
14419 			stropt->so_tail = sopp.sopp_tail;
14420 			stropt->so_copyopt = sopp.sopp_zcopyflag;
14421 		}
14422 
14423 		/* Send the options up */
14424 		putnext(q, mp);
14425 	}
14426 
14427 	/*
14428 	 * Pass up any data and/or a fin that has been received.
14429 	 *
14430 	 * Adjust receive window in case it had decreased
14431 	 * (because there is data <=> tcp_rcv_list != NULL)
14432 	 * while the connection was detached. Note that
14433 	 * in case the eager was flow-controlled, w/o this
14434 	 * code, the rwnd may never open up again!
14435 	 */
14436 	if (tcp->tcp_rcv_list != NULL) {
14437 		if (IPCL_IS_NONSTR(connp)) {
14438 			mblk_t *mp;
14439 			int space_left;
14440 			int error;
14441 			boolean_t push = B_TRUE;
14442 
14443 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
14444 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
14445 			    &push) >= 0) {
14446 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14447 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14448 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14449 					tcp_xmit_ctl(NULL,
14450 					    tcp, (tcp->tcp_swnd == 0) ?
14451 					    tcp->tcp_suna : tcp->tcp_snxt,
14452 					    tcp->tcp_rnxt, TH_ACK);
14453 				}
14454 			}
14455 			while ((mp = tcp->tcp_rcv_list) != NULL) {
14456 				push = B_TRUE;
14457 				tcp->tcp_rcv_list = mp->b_next;
14458 				mp->b_next = NULL;
14459 				space_left = (*connp->conn_upcalls->su_recv)
14460 				    (connp->conn_upper_handle, mp, msgdsize(mp),
14461 				    0, &error, &push);
14462 				if (space_left < 0) {
14463 					/*
14464 					 * We should never be in middle of a
14465 					 * fallback, the squeue guarantees that.
14466 					 */
14467 					ASSERT(error != EOPNOTSUPP);
14468 				}
14469 			}
14470 			tcp->tcp_rcv_last_head = NULL;
14471 			tcp->tcp_rcv_last_tail = NULL;
14472 			tcp->tcp_rcv_cnt = 0;
14473 		} else {
14474 			/* We drain directly in case of fused tcp loopback */
14475 
14476 			if (!tcp->tcp_fused && canputnext(q)) {
14477 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14478 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14479 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14480 					tcp_xmit_ctl(NULL,
14481 					    tcp, (tcp->tcp_swnd == 0) ?
14482 					    tcp->tcp_suna : tcp->tcp_snxt,
14483 					    tcp->tcp_rnxt, TH_ACK);
14484 				}
14485 			}
14486 
14487 			(void) tcp_rcv_drain(tcp);
14488 		}
14489 
14490 		/*
14491 		 * For fused tcp loopback, back-enable peer endpoint
14492 		 * if it's currently flow-controlled.
14493 		 */
14494 		if (tcp->tcp_fused) {
14495 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
14496 
14497 			ASSERT(peer_tcp != NULL);
14498 			ASSERT(peer_tcp->tcp_fused);
14499 
14500 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
14501 			if (peer_tcp->tcp_flow_stopped) {
14502 				tcp_clrqfull(peer_tcp);
14503 				TCP_STAT(tcps, tcp_fusion_backenabled);
14504 			}
14505 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
14506 		}
14507 	}
14508 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14509 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
14510 		tcp->tcp_ordrel_done = B_TRUE;
14511 		if (IPCL_IS_NONSTR(connp)) {
14512 			ASSERT(tcp->tcp_ordrel_mp == NULL);
14513 			(*connp->conn_upcalls->su_opctl)(
14514 			    connp->conn_upper_handle,
14515 			    SOCK_OPCTL_SHUT_RECV, 0);
14516 		} else {
14517 			mp = tcp->tcp_ordrel_mp;
14518 			tcp->tcp_ordrel_mp = NULL;
14519 			putnext(q, mp);
14520 		}
14521 	}
14522 	tcp->tcp_hard_binding = B_FALSE;
14523 
14524 	if (connp->conn_keepalive) {
14525 		tcp->tcp_ka_last_intrvl = 0;
14526 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
14527 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
14528 	}
14529 
14530 	/*
14531 	 * At this point, eager is fully established and will
14532 	 * have the following references -
14533 	 *
14534 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
14535 	 * 1 reference for the squeue which will be dropped by the squeue as
14536 	 *	soon as this function returns.
14537 	 * There will be 1 additonal reference for being in classifier
14538 	 *	hash list provided something bad hasn't happened.
14539 	 */
14540 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14541 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14542 }
14543 
14544 /*
14545  * The function called through squeue to get behind listener's perimeter to
14546  * send a deferred conn_ind.
14547  */
14548 /* ARGSUSED */
14549 void
14550 tcp_send_pending(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14551 {
14552 	conn_t	*lconnp = (conn_t *)arg;
14553 	tcp_t *listener = lconnp->conn_tcp;
14554 	struct T_conn_ind *conn_ind;
14555 	tcp_t *tcp;
14556 
14557 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
14558 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
14559 	    conn_ind->OPT_length);
14560 
14561 	if (listener->tcp_state != TCPS_LISTEN) {
14562 		/*
14563 		 * If listener has closed, it would have caused a
14564 		 * a cleanup/blowoff to happen for the eager, so
14565 		 * we don't need to do anything more.
14566 		 */
14567 		freemsg(mp);
14568 		return;
14569 	}
14570 
14571 	tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
14572 }
14573 
14574 /*
14575  * Common to TPI and sockfs accept code.
14576  */
14577 /* ARGSUSED2 */
14578 static int
14579 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
14580 {
14581 	tcp_t *listener, *eager;
14582 	mblk_t *discon_mp;
14583 
14584 	listener = lconnp->conn_tcp;
14585 	ASSERT(listener->tcp_state == TCPS_LISTEN);
14586 	eager = econnp->conn_tcp;
14587 	ASSERT(eager->tcp_listener != NULL);
14588 
14589 	/*
14590 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
14591 	 * use it if something failed.
14592 	 */
14593 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
14594 	    sizeof (struct stroptions)), BPRI_HI);
14595 
14596 	if (discon_mp == NULL) {
14597 		return (-TPROTO);
14598 	}
14599 	eager->tcp_issocket = B_TRUE;
14600 
14601 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
14602 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
14603 	ASSERT(econnp->conn_netstack ==
14604 	    listener->tcp_connp->conn_netstack);
14605 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
14606 
14607 	/* Put the ref for IP */
14608 	CONN_INC_REF(econnp);
14609 
14610 	/*
14611 	 * We should have minimum of 3 references on the conn
14612 	 * at this point. One each for TCP and IP and one for
14613 	 * the T_conn_ind that was sent up when the 3-way handshake
14614 	 * completed. In the normal case we would also have another
14615 	 * reference (making a total of 4) for the conn being in the
14616 	 * classifier hash list. However the eager could have received
14617 	 * an RST subsequently and tcp_closei_local could have removed
14618 	 * the eager from the classifier hash list, hence we can't
14619 	 * assert that reference.
14620 	 */
14621 	ASSERT(econnp->conn_ref >= 3);
14622 
14623 	mutex_enter(&listener->tcp_eager_lock);
14624 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
14625 
14626 		tcp_t *tail;
14627 		tcp_t *tcp;
14628 		mblk_t *mp1;
14629 
14630 		tcp = listener->tcp_eager_prev_q0;
14631 		/*
14632 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
14633 		 * deferred T_conn_ind queue. We need to get to the head
14634 		 * of the queue in order to send up T_conn_ind the same
14635 		 * order as how the 3WHS is completed.
14636 		 */
14637 		while (tcp != listener) {
14638 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
14639 			    !tcp->tcp_kssl_pending)
14640 				break;
14641 			else
14642 				tcp = tcp->tcp_eager_prev_q0;
14643 		}
14644 		/* None of the pending eagers can be sent up now */
14645 		if (tcp == listener)
14646 			goto no_more_eagers;
14647 
14648 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
14649 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14650 		/* Move from q0 to q */
14651 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
14652 		listener->tcp_conn_req_cnt_q0--;
14653 		listener->tcp_conn_req_cnt_q++;
14654 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
14655 		    tcp->tcp_eager_prev_q0;
14656 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
14657 		    tcp->tcp_eager_next_q0;
14658 		tcp->tcp_eager_prev_q0 = NULL;
14659 		tcp->tcp_eager_next_q0 = NULL;
14660 		tcp->tcp_conn_def_q0 = B_FALSE;
14661 
14662 		/* Make sure the tcp isn't in the list of droppables */
14663 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
14664 		    tcp->tcp_eager_prev_drop_q0 == NULL);
14665 
14666 		/*
14667 		 * Insert at end of the queue because sockfs sends
14668 		 * down T_CONN_RES in chronological order. Leaving
14669 		 * the older conn indications at front of the queue
14670 		 * helps reducing search time.
14671 		 */
14672 		tail = listener->tcp_eager_last_q;
14673 		if (tail != NULL) {
14674 			tail->tcp_eager_next_q = tcp;
14675 		} else {
14676 			listener->tcp_eager_next_q = tcp;
14677 		}
14678 		listener->tcp_eager_last_q = tcp;
14679 		tcp->tcp_eager_next_q = NULL;
14680 
14681 		/* Need to get inside the listener perimeter */
14682 		CONN_INC_REF(listener->tcp_connp);
14683 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
14684 		    tcp_send_pending, listener->tcp_connp, NULL, SQ_FILL,
14685 		    SQTAG_TCP_SEND_PENDING);
14686 	}
14687 no_more_eagers:
14688 	tcp_eager_unlink(eager);
14689 	mutex_exit(&listener->tcp_eager_lock);
14690 
14691 	/*
14692 	 * At this point, the eager is detached from the listener
14693 	 * but we still have an extra refs on eager (apart from the
14694 	 * usual tcp references). The ref was placed in tcp_rput_data
14695 	 * before sending the conn_ind in tcp_send_conn_ind.
14696 	 * The ref will be dropped in tcp_accept_finish().
14697 	 */
14698 	SQUEUE_ENTER_ONE(econnp->conn_sqp, discon_mp, tcp_accept_finish,
14699 	    econnp, NULL, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
14700 	return (0);
14701 }
14702 
14703 int
14704 tcp_accept(sock_lower_handle_t lproto_handle,
14705     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
14706     cred_t *cr)
14707 {
14708 	conn_t *lconnp, *econnp;
14709 	tcp_t *listener, *eager;
14710 
14711 	lconnp = (conn_t *)lproto_handle;
14712 	listener = lconnp->conn_tcp;
14713 	ASSERT(listener->tcp_state == TCPS_LISTEN);
14714 	econnp = (conn_t *)eproto_handle;
14715 	eager = econnp->conn_tcp;
14716 	ASSERT(eager->tcp_listener != NULL);
14717 
14718 	/*
14719 	 * It is OK to manipulate these fields outside the eager's squeue
14720 	 * because they will not start being used until tcp_accept_finish
14721 	 * has been called.
14722 	 */
14723 	ASSERT(lconnp->conn_upper_handle != NULL);
14724 	ASSERT(econnp->conn_upper_handle == NULL);
14725 	econnp->conn_upper_handle = sock_handle;
14726 	econnp->conn_upcalls = lconnp->conn_upcalls;
14727 	ASSERT(IPCL_IS_NONSTR(econnp));
14728 	return (tcp_accept_common(lconnp, econnp, cr));
14729 }
14730 
14731 
14732 /*
14733  * This is the STREAMS entry point for T_CONN_RES coming down on
14734  * Acceptor STREAM when  sockfs listener does accept processing.
14735  * Read the block comment on top of tcp_input_listener().
14736  */
14737 void
14738 tcp_tpi_accept(queue_t *q, mblk_t *mp)
14739 {
14740 	queue_t *rq = RD(q);
14741 	struct T_conn_res *conn_res;
14742 	tcp_t *eager;
14743 	tcp_t *listener;
14744 	struct T_ok_ack *ok;
14745 	t_scalar_t PRIM_type;
14746 	conn_t *econnp;
14747 	cred_t *cr;
14748 
14749 	ASSERT(DB_TYPE(mp) == M_PROTO);
14750 
14751 	/*
14752 	 * All Solaris components should pass a db_credp
14753 	 * for this TPI message, hence we ASSERT.
14754 	 * But in case there is some other M_PROTO that looks
14755 	 * like a TPI message sent by some other kernel
14756 	 * component, we check and return an error.
14757 	 */
14758 	cr = msg_getcred(mp, NULL);
14759 	ASSERT(cr != NULL);
14760 	if (cr == NULL) {
14761 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
14762 		if (mp != NULL)
14763 			putnext(rq, mp);
14764 		return;
14765 	}
14766 	conn_res = (struct T_conn_res *)mp->b_rptr;
14767 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
14768 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
14769 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
14770 		if (mp != NULL)
14771 			putnext(rq, mp);
14772 		return;
14773 	}
14774 	switch (conn_res->PRIM_type) {
14775 	case O_T_CONN_RES:
14776 	case T_CONN_RES:
14777 		/*
14778 		 * We pass up an err ack if allocb fails. This will
14779 		 * cause sockfs to issue a T_DISCON_REQ which will cause
14780 		 * tcp_eager_blowoff to be called. sockfs will then call
14781 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
14782 		 * we need to do the allocb up here because we have to
14783 		 * make sure rq->q_qinfo->qi_qclose still points to the
14784 		 * correct function (tcp_tpi_close_accept) in case allocb
14785 		 * fails.
14786 		 */
14787 		bcopy(mp->b_rptr + conn_res->OPT_offset,
14788 		    &eager, conn_res->OPT_length);
14789 		PRIM_type = conn_res->PRIM_type;
14790 		mp->b_datap->db_type = M_PCPROTO;
14791 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
14792 		ok = (struct T_ok_ack *)mp->b_rptr;
14793 		ok->PRIM_type = T_OK_ACK;
14794 		ok->CORRECT_prim = PRIM_type;
14795 		econnp = eager->tcp_connp;
14796 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
14797 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
14798 		econnp->conn_rq = rq;
14799 		econnp->conn_wq = q;
14800 		rq->q_ptr = econnp;
14801 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
14802 		q->q_ptr = econnp;
14803 		q->q_qinfo = &tcp_winit;
14804 		listener = eager->tcp_listener;
14805 
14806 		if (tcp_accept_common(listener->tcp_connp,
14807 		    econnp, cr) < 0) {
14808 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
14809 			if (mp != NULL)
14810 				putnext(rq, mp);
14811 			return;
14812 		}
14813 
14814 		/*
14815 		 * Send the new local address also up to sockfs. There
14816 		 * should already be enough space in the mp that came
14817 		 * down from soaccept().
14818 		 */
14819 		if (econnp->conn_family == AF_INET) {
14820 			sin_t *sin;
14821 
14822 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
14823 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
14824 			sin = (sin_t *)mp->b_wptr;
14825 			mp->b_wptr += sizeof (sin_t);
14826 			sin->sin_family = AF_INET;
14827 			sin->sin_port = econnp->conn_lport;
14828 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
14829 		} else {
14830 			sin6_t *sin6;
14831 
14832 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
14833 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
14834 			sin6 = (sin6_t *)mp->b_wptr;
14835 			mp->b_wptr += sizeof (sin6_t);
14836 			sin6->sin6_family = AF_INET6;
14837 			sin6->sin6_port = econnp->conn_lport;
14838 			sin6->sin6_addr = econnp->conn_laddr_v6;
14839 			if (econnp->conn_ipversion == IPV4_VERSION) {
14840 				sin6->sin6_flowinfo = 0;
14841 			} else {
14842 				ASSERT(eager->tcp_ip6h != NULL);
14843 				sin6->sin6_flowinfo =
14844 				    eager->tcp_ip6h->ip6_vcf &
14845 				    ~IPV6_VERS_AND_FLOW_MASK;
14846 			}
14847 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
14848 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
14849 				sin6->sin6_scope_id =
14850 				    econnp->conn_ixa->ixa_scopeid;
14851 			} else {
14852 				sin6->sin6_scope_id = 0;
14853 			}
14854 			sin6->__sin6_src_id = 0;
14855 		}
14856 
14857 		putnext(rq, mp);
14858 		return;
14859 	default:
14860 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
14861 		if (mp != NULL)
14862 			putnext(rq, mp);
14863 		return;
14864 	}
14865 }
14866 
14867 /*
14868  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
14869  */
14870 static void
14871 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
14872 {
14873 	void	*data;
14874 	mblk_t	*datamp = mp->b_cont;
14875 	conn_t	*connp = Q_TO_CONN(q);
14876 	tcp_t	*tcp = connp->conn_tcp;
14877 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
14878 
14879 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
14880 		cmdp->cb_error = EPROTO;
14881 		qreply(q, mp);
14882 		return;
14883 	}
14884 
14885 	data = datamp->b_rptr;
14886 
14887 	switch (cmdp->cb_cmd) {
14888 	case TI_GETPEERNAME:
14889 		if (tcp->tcp_state < TCPS_SYN_RCVD)
14890 			cmdp->cb_error = ENOTCONN;
14891 		else
14892 			cmdp->cb_error = conn_getpeername(connp, data,
14893 			    &cmdp->cb_len);
14894 		break;
14895 	case TI_GETMYNAME:
14896 		cmdp->cb_error = conn_getsockname(connp, data, &cmdp->cb_len);
14897 		break;
14898 	default:
14899 		cmdp->cb_error = EINVAL;
14900 		break;
14901 	}
14902 
14903 	qreply(q, mp);
14904 }
14905 
14906 void
14907 tcp_wput(queue_t *q, mblk_t *mp)
14908 {
14909 	conn_t	*connp = Q_TO_CONN(q);
14910 	tcp_t	*tcp;
14911 	void (*output_proc)();
14912 	t_scalar_t type;
14913 	uchar_t *rptr;
14914 	struct iocblk	*iocp;
14915 	size_t size;
14916 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
14917 
14918 	ASSERT(connp->conn_ref >= 2);
14919 
14920 	switch (DB_TYPE(mp)) {
14921 	case M_DATA:
14922 		tcp = connp->conn_tcp;
14923 		ASSERT(tcp != NULL);
14924 
14925 		size = msgdsize(mp);
14926 
14927 		mutex_enter(&tcp->tcp_non_sq_lock);
14928 		tcp->tcp_squeue_bytes += size;
14929 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
14930 			tcp_setqfull(tcp);
14931 		}
14932 		mutex_exit(&tcp->tcp_non_sq_lock);
14933 
14934 		CONN_INC_REF(connp);
14935 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
14936 		    NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
14937 		return;
14938 
14939 	case M_CMD:
14940 		tcp_wput_cmdblk(q, mp);
14941 		return;
14942 
14943 	case M_PROTO:
14944 	case M_PCPROTO:
14945 		/*
14946 		 * if it is a snmp message, don't get behind the squeue
14947 		 */
14948 		tcp = connp->conn_tcp;
14949 		rptr = mp->b_rptr;
14950 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
14951 			type = ((union T_primitives *)rptr)->type;
14952 		} else {
14953 			if (connp->conn_debug) {
14954 				(void) strlog(TCP_MOD_ID, 0, 1,
14955 				    SL_ERROR|SL_TRACE,
14956 				    "tcp_wput_proto, dropping one...");
14957 			}
14958 			freemsg(mp);
14959 			return;
14960 		}
14961 		if (type == T_SVR4_OPTMGMT_REQ) {
14962 			/*
14963 			 * All Solaris components should pass a db_credp
14964 			 * for this TPI message, hence we ASSERT.
14965 			 * But in case there is some other M_PROTO that looks
14966 			 * like a TPI message sent by some other kernel
14967 			 * component, we check and return an error.
14968 			 */
14969 			cred_t	*cr = msg_getcred(mp, NULL);
14970 
14971 			ASSERT(cr != NULL);
14972 			if (cr == NULL) {
14973 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
14974 				return;
14975 			}
14976 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
14977 			    cr)) {
14978 				/*
14979 				 * This was a SNMP request
14980 				 */
14981 				return;
14982 			} else {
14983 				output_proc = tcp_wput_proto;
14984 			}
14985 		} else {
14986 			output_proc = tcp_wput_proto;
14987 		}
14988 		break;
14989 	case M_IOCTL:
14990 		/*
14991 		 * Most ioctls can be processed right away without going via
14992 		 * squeues - process them right here. Those that do require
14993 		 * squeue (currently _SIOCSOCKFALLBACK)
14994 		 * are processed by tcp_wput_ioctl().
14995 		 */
14996 		iocp = (struct iocblk *)mp->b_rptr;
14997 		tcp = connp->conn_tcp;
14998 
14999 		switch (iocp->ioc_cmd) {
15000 		case TCP_IOC_ABORT_CONN:
15001 			tcp_ioctl_abort_conn(q, mp);
15002 			return;
15003 		case TI_GETPEERNAME:
15004 		case TI_GETMYNAME:
15005 			mi_copyin(q, mp, NULL,
15006 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
15007 			return;
15008 		case ND_SET:
15009 			/* nd_getset does the necessary checks */
15010 		case ND_GET:
15011 			if (nd_getset(q, tcps->tcps_g_nd, mp)) {
15012 				qreply(q, mp);
15013 				return;
15014 			}
15015 			ip_wput_nondata(q, mp);
15016 			return;
15017 
15018 		default:
15019 			output_proc = tcp_wput_ioctl;
15020 			break;
15021 		}
15022 		break;
15023 	default:
15024 		output_proc = tcp_wput_nondata;
15025 		break;
15026 	}
15027 
15028 	CONN_INC_REF(connp);
15029 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
15030 	    NULL, tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
15031 }
15032 
15033 /*
15034  * Initial STREAMS write side put() procedure for sockets. It tries to
15035  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
15036  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
15037  * are handled by tcp_wput() as usual.
15038  *
15039  * All further messages will also be handled by tcp_wput() because we cannot
15040  * be sure that the above short cut is safe later.
15041  */
15042 static void
15043 tcp_wput_sock(queue_t *wq, mblk_t *mp)
15044 {
15045 	conn_t			*connp = Q_TO_CONN(wq);
15046 	tcp_t			*tcp = connp->conn_tcp;
15047 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
15048 
15049 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
15050 	wq->q_qinfo = &tcp_winit;
15051 
15052 	ASSERT(IPCL_IS_TCP(connp));
15053 	ASSERT(TCP_IS_SOCKET(tcp));
15054 
15055 	if (DB_TYPE(mp) == M_PCPROTO &&
15056 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
15057 	    car->PRIM_type == T_CAPABILITY_REQ) {
15058 		tcp_capability_req(tcp, mp);
15059 		return;
15060 	}
15061 
15062 	tcp_wput(wq, mp);
15063 }
15064 
15065 /* ARGSUSED */
15066 static void
15067 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
15068 {
15069 #ifdef DEBUG
15070 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
15071 #endif
15072 	freemsg(mp);
15073 }
15074 
15075 /*
15076  * Check the usability of ZEROCOPY. It's instead checking the flag set by IP.
15077  */
15078 static boolean_t
15079 tcp_zcopy_check(tcp_t *tcp)
15080 {
15081 	conn_t		*connp = tcp->tcp_connp;
15082 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
15083 	boolean_t	zc_enabled = B_FALSE;
15084 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15085 
15086 	if (do_tcpzcopy == 2)
15087 		zc_enabled = B_TRUE;
15088 	else if ((do_tcpzcopy == 1) && (ixa->ixa_flags & IXAF_ZCOPY_CAPAB))
15089 		zc_enabled = B_TRUE;
15090 
15091 	tcp->tcp_snd_zcopy_on = zc_enabled;
15092 	if (!TCP_IS_DETACHED(tcp)) {
15093 		if (zc_enabled) {
15094 			ixa->ixa_flags |= IXAF_VERIFY_ZCOPY;
15095 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15096 			    ZCVMSAFE);
15097 			TCP_STAT(tcps, tcp_zcopy_on);
15098 		} else {
15099 			ixa->ixa_flags &= ~IXAF_VERIFY_ZCOPY;
15100 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15101 			    ZCVMUNSAFE);
15102 			TCP_STAT(tcps, tcp_zcopy_off);
15103 		}
15104 	}
15105 	return (zc_enabled);
15106 }
15107 
15108 /*
15109  * Backoff from a zero-copy message by copying data to a new allocated
15110  * message and freeing the original desballoca'ed segmapped message.
15111  *
15112  * This function is called by following two callers:
15113  * 1. tcp_timer: fix_xmitlist is set to B_TRUE, because it's safe to free
15114  *    the origial desballoca'ed message and notify sockfs. This is in re-
15115  *    transmit state.
15116  * 2. tcp_output: fix_xmitlist is set to B_FALSE. Flag STRUIO_ZCNOTIFY need
15117  *    to be copied to new message.
15118  */
15119 static mblk_t *
15120 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, boolean_t fix_xmitlist)
15121 {
15122 	mblk_t		*nbp;
15123 	mblk_t		*head = NULL;
15124 	mblk_t		*tail = NULL;
15125 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15126 
15127 	ASSERT(bp != NULL);
15128 	while (bp != NULL) {
15129 		if (IS_VMLOANED_MBLK(bp)) {
15130 			TCP_STAT(tcps, tcp_zcopy_backoff);
15131 			if ((nbp = copyb(bp)) == NULL) {
15132 				tcp->tcp_xmit_zc_clean = B_FALSE;
15133 				if (tail != NULL)
15134 					tail->b_cont = bp;
15135 				return ((head == NULL) ? bp : head);
15136 			}
15137 
15138 			if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
15139 				if (fix_xmitlist)
15140 					tcp_zcopy_notify(tcp);
15141 				else
15142 					nbp->b_datap->db_struioflag |=
15143 					    STRUIO_ZCNOTIFY;
15144 			}
15145 			nbp->b_cont = bp->b_cont;
15146 
15147 			/*
15148 			 * Copy saved information and adjust tcp_xmit_tail
15149 			 * if needed.
15150 			 */
15151 			if (fix_xmitlist) {
15152 				nbp->b_prev = bp->b_prev;
15153 				nbp->b_next = bp->b_next;
15154 
15155 				if (tcp->tcp_xmit_tail == bp)
15156 					tcp->tcp_xmit_tail = nbp;
15157 			}
15158 
15159 			/* Free the original message. */
15160 			bp->b_prev = NULL;
15161 			bp->b_next = NULL;
15162 			freeb(bp);
15163 
15164 			bp = nbp;
15165 		}
15166 
15167 		if (head == NULL) {
15168 			head = bp;
15169 		}
15170 		if (tail == NULL) {
15171 			tail = bp;
15172 		} else {
15173 			tail->b_cont = bp;
15174 			tail = bp;
15175 		}
15176 
15177 		/* Move forward. */
15178 		bp = bp->b_cont;
15179 	}
15180 
15181 	if (fix_xmitlist) {
15182 		tcp->tcp_xmit_last = tail;
15183 		tcp->tcp_xmit_zc_clean = B_TRUE;
15184 	}
15185 
15186 	return (head);
15187 }
15188 
15189 static void
15190 tcp_zcopy_notify(tcp_t *tcp)
15191 {
15192 	struct stdata	*stp;
15193 	conn_t		*connp;
15194 
15195 	if (tcp->tcp_detached)
15196 		return;
15197 	connp = tcp->tcp_connp;
15198 	if (IPCL_IS_NONSTR(connp)) {
15199 		(*connp->conn_upcalls->su_zcopy_notify)
15200 		    (connp->conn_upper_handle);
15201 		return;
15202 	}
15203 	stp = STREAM(connp->conn_rq);
15204 	mutex_enter(&stp->sd_lock);
15205 	stp->sd_flag |= STZCNOTIFY;
15206 	cv_broadcast(&stp->sd_zcopy_wait);
15207 	mutex_exit(&stp->sd_lock);
15208 }
15209 
15210 /*
15211  * Update the TCP connection according to change of LSO capability.
15212  */
15213 static void
15214 tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa)
15215 {
15216 	/*
15217 	 * We check against IPv4 header length to preserve the old behavior
15218 	 * of only enabling LSO when there are no IP options.
15219 	 * But this restriction might not be necessary at all. Before removing
15220 	 * it, need to verify how LSO is handled for source routing case, with
15221 	 * which IP does software checksum.
15222 	 *
15223 	 * For IPv6, whenever any extension header is needed, LSO is supressed.
15224 	 */
15225 	if (ixa->ixa_ip_hdr_length != ((ixa->ixa_flags & IXAF_IS_IPV4) ?
15226 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN))
15227 		return;
15228 
15229 	/*
15230 	 * Either the LSO capability newly became usable, or it has changed.
15231 	 */
15232 	if (ixa->ixa_flags & IXAF_LSO_CAPAB) {
15233 		ill_lso_capab_t	*lsoc = &ixa->ixa_lso_capab;
15234 
15235 		ASSERT(lsoc->ill_lso_max > 0);
15236 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH, lsoc->ill_lso_max);
15237 
15238 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15239 		    boolean_t, B_TRUE, uint32_t, tcp->tcp_lso_max);
15240 
15241 		/*
15242 		 * If LSO to be enabled, notify the STREAM header with larger
15243 		 * data block.
15244 		 */
15245 		if (!tcp->tcp_lso)
15246 			tcp->tcp_maxpsz_multiplier = 0;
15247 
15248 		tcp->tcp_lso = B_TRUE;
15249 		TCP_STAT(tcp->tcp_tcps, tcp_lso_enabled);
15250 	} else { /* LSO capability is not usable any more. */
15251 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15252 		    boolean_t, B_FALSE, uint32_t, tcp->tcp_lso_max);
15253 
15254 		/*
15255 		 * If LSO to be disabled, notify the STREAM header with smaller
15256 		 * data block. And need to restore fragsize to PMTU.
15257 		 */
15258 		if (tcp->tcp_lso) {
15259 			tcp->tcp_maxpsz_multiplier =
15260 			    tcp->tcp_tcps->tcps_maxpsz_multiplier;
15261 			ixa->ixa_fragsize = ixa->ixa_pmtu;
15262 			tcp->tcp_lso = B_FALSE;
15263 			TCP_STAT(tcp->tcp_tcps, tcp_lso_disabled);
15264 		}
15265 	}
15266 
15267 	(void) tcp_maxpsz_set(tcp, B_TRUE);
15268 }
15269 
15270 /*
15271  * Update the TCP connection according to change of ZEROCOPY capability.
15272  */
15273 static void
15274 tcp_update_zcopy(tcp_t *tcp)
15275 {
15276 	conn_t		*connp = tcp->tcp_connp;
15277 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15278 
15279 	if (tcp->tcp_snd_zcopy_on) {
15280 		tcp->tcp_snd_zcopy_on = B_FALSE;
15281 		if (!TCP_IS_DETACHED(tcp)) {
15282 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15283 			    ZCVMUNSAFE);
15284 			TCP_STAT(tcps, tcp_zcopy_off);
15285 		}
15286 	} else {
15287 		tcp->tcp_snd_zcopy_on = B_TRUE;
15288 		if (!TCP_IS_DETACHED(tcp)) {
15289 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15290 			    ZCVMSAFE);
15291 			TCP_STAT(tcps, tcp_zcopy_on);
15292 		}
15293 	}
15294 }
15295 
15296 /*
15297  * Notify function registered with ip_xmit_attr_t. It's called in the squeue
15298  * so it's safe to update the TCP connection.
15299  */
15300 /* ARGSUSED1 */
15301 static void
15302 tcp_notify(void *arg, ip_xmit_attr_t *ixa, ixa_notify_type_t ntype,
15303     ixa_notify_arg_t narg)
15304 {
15305 	tcp_t		*tcp = (tcp_t *)arg;
15306 	conn_t		*connp = tcp->tcp_connp;
15307 
15308 	switch (ntype) {
15309 	case IXAN_LSO:
15310 		tcp_update_lso(tcp, connp->conn_ixa);
15311 		break;
15312 	case IXAN_PMTU:
15313 		tcp_update_pmtu(tcp, B_FALSE);
15314 		break;
15315 	case IXAN_ZCOPY:
15316 		tcp_update_zcopy(tcp);
15317 		break;
15318 	default:
15319 		break;
15320 	}
15321 }
15322 
15323 static void
15324 tcp_send_data(tcp_t *tcp, mblk_t *mp)
15325 {
15326 	conn_t		*connp = tcp->tcp_connp;
15327 
15328 	/*
15329 	 * Check here to avoid sending zero-copy message down to IP when
15330 	 * ZEROCOPY capability has turned off. We only need to deal with
15331 	 * the race condition between sockfs and the notification here.
15332 	 * Since we have tried to backoff the tcp_xmit_head when turning
15333 	 * zero-copy off and new messages in tcp_output(), we simply drop
15334 	 * the dup'ed packet here and let tcp retransmit, if tcp_xmit_zc_clean
15335 	 * is not true.
15336 	 */
15337 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on &&
15338 	    !tcp->tcp_xmit_zc_clean) {
15339 		ip_drop_output("TCP ZC was disabled but not clean", mp, NULL);
15340 		freemsg(mp);
15341 		return;
15342 	}
15343 
15344 	ASSERT(connp->conn_ixa->ixa_notify_cookie == connp->conn_tcp);
15345 	(void) conn_ip_output(mp, connp->conn_ixa);
15346 }
15347 
15348 /*
15349  * This handles the case when the receiver has shrunk its win. Per RFC 1122
15350  * if the receiver shrinks the window, i.e. moves the right window to the
15351  * left, the we should not send new data, but should retransmit normally the
15352  * old unacked data between suna and suna + swnd. We might has sent data
15353  * that is now outside the new window, pretend that we didn't send  it.
15354  */
15355 static void
15356 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
15357 {
15358 	uint32_t	snxt = tcp->tcp_snxt;
15359 
15360 	ASSERT(shrunk_count > 0);
15361 
15362 	if (!tcp->tcp_is_wnd_shrnk) {
15363 		tcp->tcp_snxt_shrunk = snxt;
15364 		tcp->tcp_is_wnd_shrnk = B_TRUE;
15365 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
15366 		tcp->tcp_snxt_shrunk = snxt;
15367 	}
15368 
15369 	/* Pretend we didn't send the data outside the window */
15370 	snxt -= shrunk_count;
15371 
15372 	/* Reset all the values per the now shrunk window */
15373 	tcp_update_xmit_tail(tcp, snxt);
15374 	tcp->tcp_unsent += shrunk_count;
15375 
15376 	/*
15377 	 * If the SACK option is set, delete the entire list of
15378 	 * notsack'ed blocks.
15379 	 */
15380 	if (tcp->tcp_sack_info != NULL) {
15381 		if (tcp->tcp_notsack_list != NULL)
15382 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
15383 	}
15384 
15385 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
15386 		/*
15387 		 * Make sure the timer is running so that we will probe a zero
15388 		 * window.
15389 		 */
15390 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15391 }
15392 
15393 
15394 /*
15395  * The TCP normal data output path.
15396  * NOTE: the logic of the fast path is duplicated from this function.
15397  */
15398 static void
15399 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
15400 {
15401 	int		len;
15402 	mblk_t		*local_time;
15403 	mblk_t		*mp1;
15404 	uint32_t	snxt;
15405 	int		tail_unsent;
15406 	int		tcpstate;
15407 	int		usable = 0;
15408 	mblk_t		*xmit_tail;
15409 	int32_t		mss;
15410 	int32_t		num_sack_blk = 0;
15411 	int32_t		total_hdr_len;
15412 	int32_t		tcp_hdr_len;
15413 	int		rc;
15414 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15415 	conn_t		*connp = tcp->tcp_connp;
15416 	clock_t		now = LBOLT_FASTPATH;
15417 
15418 	tcpstate = tcp->tcp_state;
15419 	if (mp == NULL) {
15420 		/*
15421 		 * tcp_wput_data() with NULL mp should only be called when
15422 		 * there is unsent data.
15423 		 */
15424 		ASSERT(tcp->tcp_unsent > 0);
15425 		/* Really tacky... but we need this for detached closes. */
15426 		len = tcp->tcp_unsent;
15427 		goto data_null;
15428 	}
15429 
15430 #if CCS_STATS
15431 	wrw_stats.tot.count++;
15432 	wrw_stats.tot.bytes += msgdsize(mp);
15433 #endif
15434 	ASSERT(mp->b_datap->db_type == M_DATA);
15435 	/*
15436 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
15437 	 * or before a connection attempt has begun.
15438 	 */
15439 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
15440 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15441 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15442 #ifdef DEBUG
15443 			cmn_err(CE_WARN,
15444 			    "tcp_wput_data: data after ordrel, %s",
15445 			    tcp_display(tcp, NULL,
15446 			    DISP_ADDR_AND_PORT));
15447 #else
15448 			if (connp->conn_debug) {
15449 				(void) strlog(TCP_MOD_ID, 0, 1,
15450 				    SL_TRACE|SL_ERROR,
15451 				    "tcp_wput_data: data after ordrel, %s\n",
15452 				    tcp_display(tcp, NULL,
15453 				    DISP_ADDR_AND_PORT));
15454 			}
15455 #endif /* DEBUG */
15456 		}
15457 		if (tcp->tcp_snd_zcopy_aware &&
15458 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15459 			tcp_zcopy_notify(tcp);
15460 		freemsg(mp);
15461 		mutex_enter(&tcp->tcp_non_sq_lock);
15462 		if (tcp->tcp_flow_stopped &&
15463 		    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
15464 			tcp_clrqfull(tcp);
15465 		}
15466 		mutex_exit(&tcp->tcp_non_sq_lock);
15467 		return;
15468 	}
15469 
15470 	/* Strip empties */
15471 	for (;;) {
15472 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
15473 		    (uintptr_t)INT_MAX);
15474 		len = (int)(mp->b_wptr - mp->b_rptr);
15475 		if (len > 0)
15476 			break;
15477 		mp1 = mp;
15478 		mp = mp->b_cont;
15479 		freeb(mp1);
15480 		if (!mp) {
15481 			return;
15482 		}
15483 	}
15484 
15485 	/* If we are the first on the list ... */
15486 	if (tcp->tcp_xmit_head == NULL) {
15487 		tcp->tcp_xmit_head = mp;
15488 		tcp->tcp_xmit_tail = mp;
15489 		tcp->tcp_xmit_tail_unsent = len;
15490 	} else {
15491 		/* If tiny tx and room in txq tail, pullup to save mblks. */
15492 		struct datab *dp;
15493 
15494 		mp1 = tcp->tcp_xmit_last;
15495 		if (len < tcp_tx_pull_len &&
15496 		    (dp = mp1->b_datap)->db_ref == 1 &&
15497 		    dp->db_lim - mp1->b_wptr >= len) {
15498 			ASSERT(len > 0);
15499 			ASSERT(!mp1->b_cont);
15500 			if (len == 1) {
15501 				*mp1->b_wptr++ = *mp->b_rptr;
15502 			} else {
15503 				bcopy(mp->b_rptr, mp1->b_wptr, len);
15504 				mp1->b_wptr += len;
15505 			}
15506 			if (mp1 == tcp->tcp_xmit_tail)
15507 				tcp->tcp_xmit_tail_unsent += len;
15508 			mp1->b_cont = mp->b_cont;
15509 			if (tcp->tcp_snd_zcopy_aware &&
15510 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15511 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
15512 			freeb(mp);
15513 			mp = mp1;
15514 		} else {
15515 			tcp->tcp_xmit_last->b_cont = mp;
15516 		}
15517 		len += tcp->tcp_unsent;
15518 	}
15519 
15520 	/* Tack on however many more positive length mblks we have */
15521 	if ((mp1 = mp->b_cont) != NULL) {
15522 		do {
15523 			int tlen;
15524 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
15525 			    (uintptr_t)INT_MAX);
15526 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
15527 			if (tlen <= 0) {
15528 				mp->b_cont = mp1->b_cont;
15529 				freeb(mp1);
15530 			} else {
15531 				len += tlen;
15532 				mp = mp1;
15533 			}
15534 		} while ((mp1 = mp->b_cont) != NULL);
15535 	}
15536 	tcp->tcp_xmit_last = mp;
15537 	tcp->tcp_unsent = len;
15538 
15539 	if (urgent)
15540 		usable = 1;
15541 
15542 data_null:
15543 	snxt = tcp->tcp_snxt;
15544 	xmit_tail = tcp->tcp_xmit_tail;
15545 	tail_unsent = tcp->tcp_xmit_tail_unsent;
15546 
15547 	/*
15548 	 * Note that tcp_mss has been adjusted to take into account the
15549 	 * timestamp option if applicable.  Because SACK options do not
15550 	 * appear in every TCP segments and they are of variable lengths,
15551 	 * they cannot be included in tcp_mss.  Thus we need to calculate
15552 	 * the actual segment length when we need to send a segment which
15553 	 * includes SACK options.
15554 	 */
15555 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15556 		int32_t	opt_len;
15557 
15558 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
15559 		    tcp->tcp_num_sack_blk);
15560 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
15561 		    2 + TCPOPT_HEADER_LEN;
15562 		mss = tcp->tcp_mss - opt_len;
15563 		total_hdr_len = connp->conn_ht_iphc_len + opt_len;
15564 		tcp_hdr_len = connp->conn_ht_ulp_len + opt_len;
15565 	} else {
15566 		mss = tcp->tcp_mss;
15567 		total_hdr_len = connp->conn_ht_iphc_len;
15568 		tcp_hdr_len = connp->conn_ht_ulp_len;
15569 	}
15570 
15571 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
15572 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
15573 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
15574 	}
15575 	if (tcpstate == TCPS_SYN_RCVD) {
15576 		/*
15577 		 * The three-way connection establishment handshake is not
15578 		 * complete yet. We want to queue the data for transmission
15579 		 * after entering ESTABLISHED state (RFC793). A jump to
15580 		 * "done" label effectively leaves data on the queue.
15581 		 */
15582 		goto done;
15583 	} else {
15584 		int usable_r;
15585 
15586 		/*
15587 		 * In the special case when cwnd is zero, which can only
15588 		 * happen if the connection is ECN capable, return now.
15589 		 * New segments is sent using tcp_timer().  The timer
15590 		 * is set in tcp_input_data().
15591 		 */
15592 		if (tcp->tcp_cwnd == 0) {
15593 			/*
15594 			 * Note that tcp_cwnd is 0 before 3-way handshake is
15595 			 * finished.
15596 			 */
15597 			ASSERT(tcp->tcp_ecn_ok ||
15598 			    tcp->tcp_state < TCPS_ESTABLISHED);
15599 			return;
15600 		}
15601 
15602 		/* NOTE: trouble if xmitting while SYN not acked? */
15603 		usable_r = snxt - tcp->tcp_suna;
15604 		usable_r = tcp->tcp_swnd - usable_r;
15605 
15606 		/*
15607 		 * Check if the receiver has shrunk the window.  If
15608 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
15609 		 * cannot be set as there is unsent data, so FIN cannot
15610 		 * be sent out.  Otherwise, we need to take into account
15611 		 * of FIN as it consumes an "invisible" sequence number.
15612 		 */
15613 		ASSERT(tcp->tcp_fin_sent == 0);
15614 		if (usable_r < 0) {
15615 			/*
15616 			 * The receiver has shrunk the window and we have sent
15617 			 * -usable_r date beyond the window, re-adjust.
15618 			 *
15619 			 * If TCP window scaling is enabled, there can be
15620 			 * round down error as the advertised receive window
15621 			 * is actually right shifted n bits.  This means that
15622 			 * the lower n bits info is wiped out.  It will look
15623 			 * like the window is shrunk.  Do a check here to
15624 			 * see if the shrunk amount is actually within the
15625 			 * error in window calculation.  If it is, just
15626 			 * return.  Note that this check is inside the
15627 			 * shrunk window check.  This makes sure that even
15628 			 * though tcp_process_shrunk_swnd() is not called,
15629 			 * we will stop further processing.
15630 			 */
15631 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
15632 				tcp_process_shrunk_swnd(tcp, -usable_r);
15633 			}
15634 			return;
15635 		}
15636 
15637 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
15638 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
15639 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
15640 
15641 		/* usable = MIN(usable, unsent) */
15642 		if (usable_r > len)
15643 			usable_r = len;
15644 
15645 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
15646 		if (usable_r > 0) {
15647 			usable = usable_r;
15648 		} else {
15649 			/* Bypass all other unnecessary processing. */
15650 			goto done;
15651 		}
15652 	}
15653 
15654 	local_time = (mblk_t *)now;
15655 
15656 	/*
15657 	 * "Our" Nagle Algorithm.  This is not the same as in the old
15658 	 * BSD.  This is more in line with the true intent of Nagle.
15659 	 *
15660 	 * The conditions are:
15661 	 * 1. The amount of unsent data (or amount of data which can be
15662 	 *    sent, whichever is smaller) is less than Nagle limit.
15663 	 * 2. The last sent size is also less than Nagle limit.
15664 	 * 3. There is unack'ed data.
15665 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
15666 	 *    Nagle algorithm.  This reduces the probability that urgent
15667 	 *    bytes get "merged" together.
15668 	 * 5. The app has not closed the connection.  This eliminates the
15669 	 *    wait time of the receiving side waiting for the last piece of
15670 	 *    (small) data.
15671 	 *
15672 	 * If all are satisified, exit without sending anything.  Note
15673 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
15674 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
15675 	 * 4095).
15676 	 */
15677 	if (usable < (int)tcp->tcp_naglim &&
15678 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
15679 	    snxt != tcp->tcp_suna &&
15680 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
15681 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
15682 		goto done;
15683 	}
15684 
15685 	/*
15686 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
15687 	 * is set, then we have to force TCP not to send partial segment
15688 	 * (smaller than MSS bytes). We are calculating the usable now
15689 	 * based on full mss and will save the rest of remaining data for
15690 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
15691 	 * something to do zero window probe.
15692 	 */
15693 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
15694 		if (usable < mss)
15695 			goto done;
15696 		usable = (usable / mss) * mss;
15697 	}
15698 
15699 	/* Update the latest receive window size in TCP header. */
15700 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
15701 
15702 	/* Send the packet. */
15703 	rc = tcp_send(tcp, mss, total_hdr_len, tcp_hdr_len,
15704 	    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
15705 	    local_time);
15706 
15707 	/* Pretend that all we were trying to send really got sent */
15708 	if (rc < 0 && tail_unsent < 0) {
15709 		do {
15710 			xmit_tail = xmit_tail->b_cont;
15711 			xmit_tail->b_prev = local_time;
15712 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
15713 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
15714 			tail_unsent += (int)(xmit_tail->b_wptr -
15715 			    xmit_tail->b_rptr);
15716 		} while (tail_unsent < 0);
15717 	}
15718 done:;
15719 	tcp->tcp_xmit_tail = xmit_tail;
15720 	tcp->tcp_xmit_tail_unsent = tail_unsent;
15721 	len = tcp->tcp_snxt - snxt;
15722 	if (len) {
15723 		/*
15724 		 * If new data was sent, need to update the notsack
15725 		 * list, which is, afterall, data blocks that have
15726 		 * not been sack'ed by the receiver.  New data is
15727 		 * not sack'ed.
15728 		 */
15729 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
15730 			/* len is a negative value. */
15731 			tcp->tcp_pipe -= len;
15732 			tcp_notsack_update(&(tcp->tcp_notsack_list),
15733 			    tcp->tcp_snxt, snxt,
15734 			    &(tcp->tcp_num_notsack_blk),
15735 			    &(tcp->tcp_cnt_notsack_list));
15736 		}
15737 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
15738 		tcp->tcp_rack = tcp->tcp_rnxt;
15739 		tcp->tcp_rack_cnt = 0;
15740 		if ((snxt + len) == tcp->tcp_suna) {
15741 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15742 		}
15743 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
15744 		/*
15745 		 * Didn't send anything. Make sure the timer is running
15746 		 * so that we will probe a zero window.
15747 		 */
15748 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15749 	}
15750 	/* Note that len is the amount we just sent but with a negative sign */
15751 	tcp->tcp_unsent += len;
15752 	mutex_enter(&tcp->tcp_non_sq_lock);
15753 	if (tcp->tcp_flow_stopped) {
15754 		if (TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
15755 			tcp_clrqfull(tcp);
15756 		}
15757 	} else if (TCP_UNSENT_BYTES(tcp) >= connp->conn_sndbuf) {
15758 		if (!(tcp->tcp_detached))
15759 			tcp_setqfull(tcp);
15760 	}
15761 	mutex_exit(&tcp->tcp_non_sq_lock);
15762 }
15763 
15764 /*
15765  * tcp_fill_header is called by tcp_send() to fill the outgoing TCP header
15766  * with the template header, as well as other options such as time-stamp,
15767  * ECN and/or SACK.
15768  */
15769 static void
15770 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
15771 {
15772 	tcpha_t *tcp_tmpl, *tcpha;
15773 	uint32_t *dst, *src;
15774 	int hdrlen;
15775 	conn_t *connp = tcp->tcp_connp;
15776 
15777 	ASSERT(OK_32PTR(rptr));
15778 
15779 	/* Template header */
15780 	tcp_tmpl = tcp->tcp_tcpha;
15781 
15782 	/* Header of outgoing packet */
15783 	tcpha = (tcpha_t *)(rptr + connp->conn_ixa->ixa_ip_hdr_length);
15784 
15785 	/* dst and src are opaque 32-bit fields, used for copying */
15786 	dst = (uint32_t *)rptr;
15787 	src = (uint32_t *)connp->conn_ht_iphc;
15788 	hdrlen = connp->conn_ht_iphc_len;
15789 
15790 	/* Fill time-stamp option if needed */
15791 	if (tcp->tcp_snd_ts_ok) {
15792 		U32_TO_BE32((uint32_t)now,
15793 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
15794 		U32_TO_BE32(tcp->tcp_ts_recent,
15795 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
15796 	} else {
15797 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
15798 	}
15799 
15800 	/*
15801 	 * Copy the template header; is this really more efficient than
15802 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
15803 	 * but perhaps not for other scenarios.
15804 	 */
15805 	dst[0] = src[0];
15806 	dst[1] = src[1];
15807 	dst[2] = src[2];
15808 	dst[3] = src[3];
15809 	dst[4] = src[4];
15810 	dst[5] = src[5];
15811 	dst[6] = src[6];
15812 	dst[7] = src[7];
15813 	dst[8] = src[8];
15814 	dst[9] = src[9];
15815 	if (hdrlen -= 40) {
15816 		hdrlen >>= 2;
15817 		dst += 10;
15818 		src += 10;
15819 		do {
15820 			*dst++ = *src++;
15821 		} while (--hdrlen);
15822 	}
15823 
15824 	/*
15825 	 * Set the ECN info in the TCP header if it is not a zero
15826 	 * window probe.  Zero window probe is only sent in
15827 	 * tcp_wput_data() and tcp_timer().
15828 	 */
15829 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
15830 		SET_ECT(tcp, rptr);
15831 
15832 		if (tcp->tcp_ecn_echo_on)
15833 			tcpha->tha_flags |= TH_ECE;
15834 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
15835 			tcpha->tha_flags |= TH_CWR;
15836 			tcp->tcp_ecn_cwr_sent = B_TRUE;
15837 		}
15838 	}
15839 
15840 	/* Fill in SACK options */
15841 	if (num_sack_blk > 0) {
15842 		uchar_t *wptr = rptr + connp->conn_ht_iphc_len;
15843 		sack_blk_t *tmp;
15844 		int32_t	i;
15845 
15846 		wptr[0] = TCPOPT_NOP;
15847 		wptr[1] = TCPOPT_NOP;
15848 		wptr[2] = TCPOPT_SACK;
15849 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
15850 		    sizeof (sack_blk_t);
15851 		wptr += TCPOPT_REAL_SACK_LEN;
15852 
15853 		tmp = tcp->tcp_sack_list;
15854 		for (i = 0; i < num_sack_blk; i++) {
15855 			U32_TO_BE32(tmp[i].begin, wptr);
15856 			wptr += sizeof (tcp_seq);
15857 			U32_TO_BE32(tmp[i].end, wptr);
15858 			wptr += sizeof (tcp_seq);
15859 		}
15860 		tcpha->tha_offset_and_reserved +=
15861 		    ((num_sack_blk * 2 + 1) << 4);
15862 	}
15863 }
15864 
15865 /*
15866  * tcp_send() is called by tcp_wput_data() and returns one of the following:
15867  *
15868  * -1 = failed allocation.
15869  *  0 = success; burst count reached, or usable send window is too small,
15870  *      and that we'd rather wait until later before sending again.
15871  */
15872 static int
15873 tcp_send(tcp_t *tcp, const int mss, const int total_hdr_len,
15874     const int tcp_hdr_len, const int num_sack_blk, int *usable,
15875     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time)
15876 {
15877 	int		num_burst_seg = tcp->tcp_snd_burst;
15878 	int		num_lso_seg = 1;
15879 	uint_t		lso_usable;
15880 	boolean_t	do_lso_send = B_FALSE;
15881 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15882 	conn_t		*connp = tcp->tcp_connp;
15883 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
15884 
15885 	/*
15886 	 * Check LSO possibility. The value of tcp->tcp_lso indicates whether
15887 	 * the underlying connection is LSO capable. Will check whether having
15888 	 * enough available data to initiate LSO transmission in the for(){}
15889 	 * loops.
15890 	 */
15891 	if (tcp->tcp_lso && (tcp->tcp_valid_bits & ~TCP_FSS_VALID) == 0)
15892 			do_lso_send = B_TRUE;
15893 
15894 	for (;;) {
15895 		struct datab	*db;
15896 		tcpha_t		*tcpha;
15897 		uint32_t	sum;
15898 		mblk_t		*mp, *mp1;
15899 		uchar_t		*rptr;
15900 		int		len;
15901 
15902 		/*
15903 		 * Burst count reached, return successfully.
15904 		 */
15905 		if (num_burst_seg == 0)
15906 			break;
15907 
15908 		/*
15909 		 * Calculate the maximum payload length we can send at one
15910 		 * time.
15911 		 */
15912 		if (do_lso_send) {
15913 			/*
15914 			 * Check whether be able to to do LSO for the current
15915 			 * available data.
15916 			 */
15917 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
15918 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
15919 				lso_usable = MIN(lso_usable,
15920 				    num_burst_seg * mss);
15921 
15922 				num_lso_seg = lso_usable / mss;
15923 				if (lso_usable % mss) {
15924 					num_lso_seg++;
15925 					tcp->tcp_last_sent_len = (ushort_t)
15926 					    (lso_usable % mss);
15927 				} else {
15928 					tcp->tcp_last_sent_len = (ushort_t)mss;
15929 				}
15930 			} else {
15931 				do_lso_send = B_FALSE;
15932 				num_lso_seg = 1;
15933 				lso_usable = mss;
15934 			}
15935 		}
15936 
15937 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
15938 #ifdef DEBUG
15939 		DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg, boolean_t,
15940 		    do_lso_send);
15941 #endif
15942 		/*
15943 		 * Adjust num_burst_seg here.
15944 		 */
15945 		num_burst_seg -= num_lso_seg;
15946 
15947 		len = mss;
15948 		if (len > *usable) {
15949 			ASSERT(do_lso_send == B_FALSE);
15950 
15951 			len = *usable;
15952 			if (len <= 0) {
15953 				/* Terminate the loop */
15954 				break;	/* success; too small */
15955 			}
15956 			/*
15957 			 * Sender silly-window avoidance.
15958 			 * Ignore this if we are going to send a
15959 			 * zero window probe out.
15960 			 *
15961 			 * TODO: force data into microscopic window?
15962 			 *	==> (!pushed || (unsent > usable))
15963 			 */
15964 			if (len < (tcp->tcp_max_swnd >> 1) &&
15965 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
15966 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
15967 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
15968 				/*
15969 				 * If the retransmit timer is not running
15970 				 * we start it so that we will retransmit
15971 				 * in the case when the receiver has
15972 				 * decremented the window.
15973 				 */
15974 				if (*snxt == tcp->tcp_snxt &&
15975 				    *snxt == tcp->tcp_suna) {
15976 					/*
15977 					 * We are not supposed to send
15978 					 * anything.  So let's wait a little
15979 					 * bit longer before breaking SWS
15980 					 * avoidance.
15981 					 *
15982 					 * What should the value be?
15983 					 * Suggestion: MAX(init rexmit time,
15984 					 * tcp->tcp_rto)
15985 					 */
15986 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15987 				}
15988 				break;	/* success; too small */
15989 			}
15990 		}
15991 
15992 		tcpha = tcp->tcp_tcpha;
15993 
15994 		/*
15995 		 * The reason to adjust len here is that we need to set flags
15996 		 * and calculate checksum.
15997 		 */
15998 		if (do_lso_send)
15999 			len = lso_usable;
16000 
16001 		*usable -= len; /* Approximate - can be adjusted later */
16002 		if (*usable > 0)
16003 			tcpha->tha_flags = TH_ACK;
16004 		else
16005 			tcpha->tha_flags = (TH_ACK | TH_PUSH);
16006 
16007 		/*
16008 		 * Prime pump for IP's checksumming on our behalf.
16009 		 * Include the adjustment for a source route if any.
16010 		 * In case of LSO, the partial pseudo-header checksum should
16011 		 * exclusive TCP length, so zero tha_sum before IP calculate
16012 		 * pseudo-header checksum for partial checksum offload.
16013 		 */
16014 		if (do_lso_send) {
16015 			sum = 0;
16016 		} else {
16017 			sum = len + tcp_hdr_len + connp->conn_sum;
16018 			sum = (sum >> 16) + (sum & 0xFFFF);
16019 		}
16020 		tcpha->tha_sum = htons(sum);
16021 		tcpha->tha_seq = htonl(*snxt);
16022 
16023 		/*
16024 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
16025 		 * set.  For the case when TCP_FSS_VALID is the only valid
16026 		 * bit (normal active close), branch off only when we think
16027 		 * that the FIN flag needs to be set.  Note for this case,
16028 		 * that (snxt + len) may not reflect the actual seg_len,
16029 		 * as len may be further reduced in tcp_xmit_mp().  If len
16030 		 * gets modified, we will end up here again.
16031 		 */
16032 		if (tcp->tcp_valid_bits != 0 &&
16033 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
16034 		    ((*snxt + len) == tcp->tcp_fss))) {
16035 			uchar_t		*prev_rptr;
16036 			uint32_t	prev_snxt = tcp->tcp_snxt;
16037 
16038 			if (*tail_unsent == 0) {
16039 				ASSERT((*xmit_tail)->b_cont != NULL);
16040 				*xmit_tail = (*xmit_tail)->b_cont;
16041 				prev_rptr = (*xmit_tail)->b_rptr;
16042 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
16043 				    (*xmit_tail)->b_rptr);
16044 			} else {
16045 				prev_rptr = (*xmit_tail)->b_rptr;
16046 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
16047 				    *tail_unsent;
16048 			}
16049 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
16050 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
16051 			/* Restore tcp_snxt so we get amount sent right. */
16052 			tcp->tcp_snxt = prev_snxt;
16053 			if (prev_rptr == (*xmit_tail)->b_rptr) {
16054 				/*
16055 				 * If the previous timestamp is still in use,
16056 				 * don't stomp on it.
16057 				 */
16058 				if ((*xmit_tail)->b_next == NULL) {
16059 					(*xmit_tail)->b_prev = local_time;
16060 					(*xmit_tail)->b_next =
16061 					    (mblk_t *)(uintptr_t)(*snxt);
16062 				}
16063 			} else
16064 				(*xmit_tail)->b_rptr = prev_rptr;
16065 
16066 			if (mp == NULL) {
16067 				return (-1);
16068 			}
16069 			mp1 = mp->b_cont;
16070 
16071 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
16072 				tcp->tcp_last_sent_len = (ushort_t)len;
16073 			while (mp1->b_cont) {
16074 				*xmit_tail = (*xmit_tail)->b_cont;
16075 				(*xmit_tail)->b_prev = local_time;
16076 				(*xmit_tail)->b_next =
16077 				    (mblk_t *)(uintptr_t)(*snxt);
16078 				mp1 = mp1->b_cont;
16079 			}
16080 			*snxt += len;
16081 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
16082 			BUMP_LOCAL(tcp->tcp_obsegs);
16083 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16084 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16085 			tcp_send_data(tcp, mp);
16086 			continue;
16087 		}
16088 
16089 		*snxt += len;	/* Adjust later if we don't send all of len */
16090 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16091 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16092 
16093 		if (*tail_unsent) {
16094 			/* Are the bytes above us in flight? */
16095 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
16096 			if (rptr != (*xmit_tail)->b_rptr) {
16097 				*tail_unsent -= len;
16098 				if (len <= mss) /* LSO is unusable */
16099 					tcp->tcp_last_sent_len = (ushort_t)len;
16100 				len += total_hdr_len;
16101 				ixa->ixa_pktlen = len;
16102 
16103 				if (ixa->ixa_flags & IXAF_IS_IPV4) {
16104 					tcp->tcp_ipha->ipha_length = htons(len);
16105 				} else {
16106 					tcp->tcp_ip6h->ip6_plen =
16107 					    htons(len - IPV6_HDR_LEN);
16108 				}
16109 
16110 				mp = dupb(*xmit_tail);
16111 				if (mp == NULL) {
16112 					return (-1);	/* out_of_mem */
16113 				}
16114 				mp->b_rptr = rptr;
16115 				/*
16116 				 * If the old timestamp is no longer in use,
16117 				 * sample a new timestamp now.
16118 				 */
16119 				if ((*xmit_tail)->b_next == NULL) {
16120 					(*xmit_tail)->b_prev = local_time;
16121 					(*xmit_tail)->b_next =
16122 					    (mblk_t *)(uintptr_t)(*snxt-len);
16123 				}
16124 				goto must_alloc;
16125 			}
16126 		} else {
16127 			*xmit_tail = (*xmit_tail)->b_cont;
16128 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
16129 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
16130 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
16131 			    (*xmit_tail)->b_rptr);
16132 		}
16133 
16134 		(*xmit_tail)->b_prev = local_time;
16135 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
16136 
16137 		*tail_unsent -= len;
16138 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
16139 			tcp->tcp_last_sent_len = (ushort_t)len;
16140 
16141 		len += total_hdr_len;
16142 		ixa->ixa_pktlen = len;
16143 
16144 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
16145 			tcp->tcp_ipha->ipha_length = htons(len);
16146 		} else {
16147 			tcp->tcp_ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
16148 		}
16149 
16150 		mp = dupb(*xmit_tail);
16151 		if (mp == NULL) {
16152 			return (-1);	/* out_of_mem */
16153 		}
16154 
16155 		len = total_hdr_len;
16156 		/*
16157 		 * There are four reasons to allocate a new hdr mblk:
16158 		 *  1) The bytes above us are in use by another packet
16159 		 *  2) We don't have good alignment
16160 		 *  3) The mblk is being shared
16161 		 *  4) We don't have enough room for a header
16162 		 */
16163 		rptr = mp->b_rptr - len;
16164 		if (!OK_32PTR(rptr) ||
16165 		    ((db = mp->b_datap), db->db_ref != 2) ||
16166 		    rptr < db->db_base) {
16167 			/* NOTE: we assume allocb returns an OK_32PTR */
16168 
16169 		must_alloc:;
16170 			mp1 = allocb(connp->conn_ht_iphc_allocated +
16171 			    tcps->tcps_wroff_xtra, BPRI_MED);
16172 			if (mp1 == NULL) {
16173 				freemsg(mp);
16174 				return (-1);	/* out_of_mem */
16175 			}
16176 			mp1->b_cont = mp;
16177 			mp = mp1;
16178 			/* Leave room for Link Level header */
16179 			len = total_hdr_len;
16180 			rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
16181 			mp->b_wptr = &rptr[len];
16182 		}
16183 
16184 		/*
16185 		 * Fill in the header using the template header, and add
16186 		 * options such as time-stamp, ECN and/or SACK, as needed.
16187 		 */
16188 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
16189 
16190 		mp->b_rptr = rptr;
16191 
16192 		if (*tail_unsent) {
16193 			int spill = *tail_unsent;
16194 
16195 			mp1 = mp->b_cont;
16196 			if (mp1 == NULL)
16197 				mp1 = mp;
16198 
16199 			/*
16200 			 * If we're a little short, tack on more mblks until
16201 			 * there is no more spillover.
16202 			 */
16203 			while (spill < 0) {
16204 				mblk_t *nmp;
16205 				int nmpsz;
16206 
16207 				nmp = (*xmit_tail)->b_cont;
16208 				nmpsz = MBLKL(nmp);
16209 
16210 				/*
16211 				 * Excess data in mblk; can we split it?
16212 				 * If LSO is enabled for the connection,
16213 				 * keep on splitting as this is a transient
16214 				 * send path.
16215 				 */
16216 				if (!do_lso_send && (spill + nmpsz > 0)) {
16217 					/*
16218 					 * Don't split if stream head was
16219 					 * told to break up larger writes
16220 					 * into smaller ones.
16221 					 */
16222 					if (tcp->tcp_maxpsz_multiplier > 0)
16223 						break;
16224 
16225 					/*
16226 					 * Next mblk is less than SMSS/2
16227 					 * rounded up to nearest 64-byte;
16228 					 * let it get sent as part of the
16229 					 * next segment.
16230 					 */
16231 					if (tcp->tcp_localnet &&
16232 					    !tcp->tcp_cork &&
16233 					    (nmpsz < roundup((mss >> 1), 64)))
16234 						break;
16235 				}
16236 
16237 				*xmit_tail = nmp;
16238 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
16239 				/* Stash for rtt use later */
16240 				(*xmit_tail)->b_prev = local_time;
16241 				(*xmit_tail)->b_next =
16242 				    (mblk_t *)(uintptr_t)(*snxt - len);
16243 				mp1->b_cont = dupb(*xmit_tail);
16244 				mp1 = mp1->b_cont;
16245 
16246 				spill += nmpsz;
16247 				if (mp1 == NULL) {
16248 					*tail_unsent = spill;
16249 					freemsg(mp);
16250 					return (-1);	/* out_of_mem */
16251 				}
16252 			}
16253 
16254 			/* Trim back any surplus on the last mblk */
16255 			if (spill >= 0) {
16256 				mp1->b_wptr -= spill;
16257 				*tail_unsent = spill;
16258 			} else {
16259 				/*
16260 				 * We did not send everything we could in
16261 				 * order to remain within the b_cont limit.
16262 				 */
16263 				*usable -= spill;
16264 				*snxt += spill;
16265 				tcp->tcp_last_sent_len += spill;
16266 				UPDATE_MIB(&tcps->tcps_mib,
16267 				    tcpOutDataBytes, spill);
16268 				/*
16269 				 * Adjust the checksum
16270 				 */
16271 				tcpha = (tcpha_t *)(rptr +
16272 				    ixa->ixa_ip_hdr_length);
16273 				sum += spill;
16274 				sum = (sum >> 16) + (sum & 0xFFFF);
16275 				tcpha->tha_sum = htons(sum);
16276 				if (connp->conn_ipversion == IPV4_VERSION) {
16277 					sum = ntohs(
16278 					    ((ipha_t *)rptr)->ipha_length) +
16279 					    spill;
16280 					((ipha_t *)rptr)->ipha_length =
16281 					    htons(sum);
16282 				} else {
16283 					sum = ntohs(
16284 					    ((ip6_t *)rptr)->ip6_plen) +
16285 					    spill;
16286 					((ip6_t *)rptr)->ip6_plen =
16287 					    htons(sum);
16288 				}
16289 				ixa->ixa_pktlen += spill;
16290 				*tail_unsent = 0;
16291 			}
16292 		}
16293 		if (tcp->tcp_ip_forward_progress) {
16294 			tcp->tcp_ip_forward_progress = B_FALSE;
16295 			ixa->ixa_flags |= IXAF_REACH_CONF;
16296 		} else {
16297 			ixa->ixa_flags &= ~IXAF_REACH_CONF;
16298 		}
16299 
16300 		/*
16301 		 * Append LSO information, both flags and mss, to the mp.
16302 		 */
16303 		if (do_lso_send) {
16304 			lso_info_set(mp, mss, HW_LSO);
16305 			ixa->ixa_fragsize = IP_MAXPACKET;
16306 			ixa->ixa_extra_ident = num_lso_seg - 1;
16307 
16308 			DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg,
16309 			    boolean_t, B_TRUE);
16310 
16311 			tcp_send_data(tcp, mp);
16312 
16313 			/*
16314 			 * Restore values of ixa_fragsize and ixa_extra_ident.
16315 			 */
16316 			ixa->ixa_fragsize = ixa->ixa_pmtu;
16317 			ixa->ixa_extra_ident = 0;
16318 			tcp->tcp_obsegs += num_lso_seg;
16319 			TCP_STAT(tcps, tcp_lso_times);
16320 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
16321 		} else {
16322 			tcp_send_data(tcp, mp);
16323 			BUMP_LOCAL(tcp->tcp_obsegs);
16324 		}
16325 	}
16326 
16327 	return (0);
16328 }
16329 
16330 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
16331 static void
16332 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
16333 {
16334 	uchar_t	fval = *mp->b_rptr;
16335 	mblk_t	*tail;
16336 	conn_t	*connp = tcp->tcp_connp;
16337 	queue_t	*q = connp->conn_wq;
16338 
16339 	/* TODO: How should flush interact with urgent data? */
16340 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
16341 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
16342 		/*
16343 		 * Flush only data that has not yet been put on the wire.  If
16344 		 * we flush data that we have already transmitted, life, as we
16345 		 * know it, may come to an end.
16346 		 */
16347 		tail = tcp->tcp_xmit_tail;
16348 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
16349 		tcp->tcp_xmit_tail_unsent = 0;
16350 		tcp->tcp_unsent = 0;
16351 		if (tail->b_wptr != tail->b_rptr)
16352 			tail = tail->b_cont;
16353 		if (tail) {
16354 			mblk_t **excess = &tcp->tcp_xmit_head;
16355 			for (;;) {
16356 				mblk_t *mp1 = *excess;
16357 				if (mp1 == tail)
16358 					break;
16359 				tcp->tcp_xmit_tail = mp1;
16360 				tcp->tcp_xmit_last = mp1;
16361 				excess = &mp1->b_cont;
16362 			}
16363 			*excess = NULL;
16364 			tcp_close_mpp(&tail);
16365 			if (tcp->tcp_snd_zcopy_aware)
16366 				tcp_zcopy_notify(tcp);
16367 		}
16368 		/*
16369 		 * We have no unsent data, so unsent must be less than
16370 		 * conn_sndlowat, so re-enable flow.
16371 		 */
16372 		mutex_enter(&tcp->tcp_non_sq_lock);
16373 		if (tcp->tcp_flow_stopped) {
16374 			tcp_clrqfull(tcp);
16375 		}
16376 		mutex_exit(&tcp->tcp_non_sq_lock);
16377 	}
16378 	/*
16379 	 * TODO: you can't just flush these, you have to increase rwnd for one
16380 	 * thing.  For another, how should urgent data interact?
16381 	 */
16382 	if (fval & FLUSHR) {
16383 		*mp->b_rptr = fval & ~FLUSHW;
16384 		/* XXX */
16385 		qreply(q, mp);
16386 		return;
16387 	}
16388 	freemsg(mp);
16389 }
16390 
16391 /*
16392  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
16393  * messages.
16394  */
16395 static void
16396 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
16397 {
16398 	mblk_t		*mp1;
16399 	struct iocblk	*iocp = (struct iocblk *)mp->b_rptr;
16400 	STRUCT_HANDLE(strbuf, sb);
16401 	uint_t		addrlen;
16402 	conn_t		*connp = tcp->tcp_connp;
16403 	queue_t 	*q = connp->conn_wq;
16404 
16405 	/* Make sure it is one of ours. */
16406 	switch (iocp->ioc_cmd) {
16407 	case TI_GETMYNAME:
16408 	case TI_GETPEERNAME:
16409 		break;
16410 	default:
16411 		ip_wput_nondata(q, mp);
16412 		return;
16413 	}
16414 	switch (mi_copy_state(q, mp, &mp1)) {
16415 	case -1:
16416 		return;
16417 	case MI_COPY_CASE(MI_COPY_IN, 1):
16418 		break;
16419 	case MI_COPY_CASE(MI_COPY_OUT, 1):
16420 		/* Copy out the strbuf. */
16421 		mi_copyout(q, mp);
16422 		return;
16423 	case MI_COPY_CASE(MI_COPY_OUT, 2):
16424 		/* All done. */
16425 		mi_copy_done(q, mp, 0);
16426 		return;
16427 	default:
16428 		mi_copy_done(q, mp, EPROTO);
16429 		return;
16430 	}
16431 	/* Check alignment of the strbuf */
16432 	if (!OK_32PTR(mp1->b_rptr)) {
16433 		mi_copy_done(q, mp, EINVAL);
16434 		return;
16435 	}
16436 
16437 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
16438 
16439 	if (connp->conn_family == AF_INET)
16440 		addrlen = sizeof (sin_t);
16441 	else
16442 		addrlen = sizeof (sin6_t);
16443 
16444 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
16445 		mi_copy_done(q, mp, EINVAL);
16446 		return;
16447 	}
16448 
16449 	switch (iocp->ioc_cmd) {
16450 	case TI_GETMYNAME:
16451 		break;
16452 	case TI_GETPEERNAME:
16453 		if (tcp->tcp_state < TCPS_SYN_RCVD) {
16454 			mi_copy_done(q, mp, ENOTCONN);
16455 			return;
16456 		}
16457 		break;
16458 	}
16459 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
16460 	if (!mp1)
16461 		return;
16462 
16463 	STRUCT_FSET(sb, len, addrlen);
16464 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
16465 	case TI_GETMYNAME:
16466 		(void) conn_getsockname(connp, (struct sockaddr *)mp1->b_wptr,
16467 		    &addrlen);
16468 		break;
16469 	case TI_GETPEERNAME:
16470 		(void) conn_getpeername(connp, (struct sockaddr *)mp1->b_wptr,
16471 		    &addrlen);
16472 		break;
16473 	}
16474 	mp1->b_wptr += addrlen;
16475 	/* Copy out the address */
16476 	mi_copyout(q, mp);
16477 }
16478 
16479 static void
16480 tcp_use_pure_tpi(tcp_t *tcp)
16481 {
16482 	conn_t		*connp = tcp->tcp_connp;
16483 
16484 #ifdef	_ILP32
16485 	tcp->tcp_acceptor_id = (t_uscalar_t)connp->conn_rq;
16486 #else
16487 	tcp->tcp_acceptor_id = connp->conn_dev;
16488 #endif
16489 	/*
16490 	 * Insert this socket into the acceptor hash.
16491 	 * We might need it for T_CONN_RES message
16492 	 */
16493 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
16494 
16495 	tcp->tcp_issocket = B_FALSE;
16496 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
16497 }
16498 
16499 /*
16500  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
16501  * messages.
16502  */
16503 /* ARGSUSED */
16504 static void
16505 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16506 {
16507 	conn_t 		*connp = (conn_t *)arg;
16508 	tcp_t		*tcp = connp->conn_tcp;
16509 	queue_t		*q = connp->conn_wq;
16510 	struct iocblk	*iocp;
16511 
16512 	ASSERT(DB_TYPE(mp) == M_IOCTL);
16513 	/*
16514 	 * Try and ASSERT the minimum possible references on the
16515 	 * conn early enough. Since we are executing on write side,
16516 	 * the connection is obviously not detached and that means
16517 	 * there is a ref each for TCP and IP. Since we are behind
16518 	 * the squeue, the minimum references needed are 3. If the
16519 	 * conn is in classifier hash list, there should be an
16520 	 * extra ref for that (we check both the possibilities).
16521 	 */
16522 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16523 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16524 
16525 	iocp = (struct iocblk *)mp->b_rptr;
16526 	switch (iocp->ioc_cmd) {
16527 	case _SIOCSOCKFALLBACK:
16528 		/*
16529 		 * Either sockmod is about to be popped and the socket
16530 		 * would now be treated as a plain stream, or a module
16531 		 * is about to be pushed so we could no longer use read-
16532 		 * side synchronous streams for fused loopback tcp.
16533 		 * Drain any queued data and disable direct sockfs
16534 		 * interface from now on.
16535 		 */
16536 		if (!tcp->tcp_issocket) {
16537 			DB_TYPE(mp) = M_IOCNAK;
16538 			iocp->ioc_error = EINVAL;
16539 		} else {
16540 			tcp_use_pure_tpi(tcp);
16541 			DB_TYPE(mp) = M_IOCACK;
16542 			iocp->ioc_error = 0;
16543 		}
16544 		iocp->ioc_count = 0;
16545 		iocp->ioc_rval = 0;
16546 		qreply(q, mp);
16547 		return;
16548 	}
16549 	ip_wput_nondata(q, mp);
16550 }
16551 
16552 /*
16553  * This routine is called by tcp_wput() to handle all TPI requests.
16554  */
16555 /* ARGSUSED */
16556 static void
16557 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16558 {
16559 	conn_t		*connp = (conn_t *)arg;
16560 	tcp_t		*tcp = connp->conn_tcp;
16561 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
16562 	uchar_t		*rptr;
16563 	t_scalar_t	type;
16564 	cred_t		*cr;
16565 
16566 	/*
16567 	 * Try and ASSERT the minimum possible references on the
16568 	 * conn early enough. Since we are executing on write side,
16569 	 * the connection is obviously not detached and that means
16570 	 * there is a ref each for TCP and IP. Since we are behind
16571 	 * the squeue, the minimum references needed are 3. If the
16572 	 * conn is in classifier hash list, there should be an
16573 	 * extra ref for that (we check both the possibilities).
16574 	 */
16575 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16576 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16577 
16578 	rptr = mp->b_rptr;
16579 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
16580 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
16581 		type = ((union T_primitives *)rptr)->type;
16582 		if (type == T_EXDATA_REQ) {
16583 			tcp_output_urgent(connp, mp, arg2, NULL);
16584 		} else if (type != T_DATA_REQ) {
16585 			goto non_urgent_data;
16586 		} else {
16587 			/* TODO: options, flags, ... from user */
16588 			/* Set length to zero for reclamation below */
16589 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
16590 			freeb(mp);
16591 		}
16592 		return;
16593 	} else {
16594 		if (connp->conn_debug) {
16595 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
16596 			    "tcp_wput_proto, dropping one...");
16597 		}
16598 		freemsg(mp);
16599 		return;
16600 	}
16601 
16602 non_urgent_data:
16603 
16604 	switch ((int)tprim->type) {
16605 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
16606 		/*
16607 		 * save the kssl_ent_t from the next block, and convert this
16608 		 * back to a normal bind_req.
16609 		 */
16610 		if (mp->b_cont != NULL) {
16611 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
16612 
16613 			if (tcp->tcp_kssl_ent != NULL) {
16614 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
16615 				    KSSL_NO_PROXY);
16616 				tcp->tcp_kssl_ent = NULL;
16617 			}
16618 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
16619 			    sizeof (kssl_ent_t));
16620 			kssl_hold_ent(tcp->tcp_kssl_ent);
16621 			freemsg(mp->b_cont);
16622 			mp->b_cont = NULL;
16623 		}
16624 		tprim->type = T_BIND_REQ;
16625 
16626 	/* FALLTHROUGH */
16627 	case O_T_BIND_REQ:	/* bind request */
16628 	case T_BIND_REQ:	/* new semantics bind request */
16629 		tcp_tpi_bind(tcp, mp);
16630 		break;
16631 	case T_UNBIND_REQ:	/* unbind request */
16632 		tcp_tpi_unbind(tcp, mp);
16633 		break;
16634 	case O_T_CONN_RES:	/* old connection response XXX */
16635 	case T_CONN_RES:	/* connection response */
16636 		tcp_tli_accept(tcp, mp);
16637 		break;
16638 	case T_CONN_REQ:	/* connection request */
16639 		tcp_tpi_connect(tcp, mp);
16640 		break;
16641 	case T_DISCON_REQ:	/* disconnect request */
16642 		tcp_disconnect(tcp, mp);
16643 		break;
16644 	case T_CAPABILITY_REQ:
16645 		tcp_capability_req(tcp, mp);	/* capability request */
16646 		break;
16647 	case T_INFO_REQ:	/* information request */
16648 		tcp_info_req(tcp, mp);
16649 		break;
16650 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
16651 	case T_OPTMGMT_REQ:
16652 		/*
16653 		 * Note:  no support for snmpcom_req() through new
16654 		 * T_OPTMGMT_REQ. See comments in ip.c
16655 		 */
16656 
16657 		/*
16658 		 * All Solaris components should pass a db_credp
16659 		 * for this TPI message, hence we ASSERT.
16660 		 * But in case there is some other M_PROTO that looks
16661 		 * like a TPI message sent by some other kernel
16662 		 * component, we check and return an error.
16663 		 */
16664 		cr = msg_getcred(mp, NULL);
16665 		ASSERT(cr != NULL);
16666 		if (cr == NULL) {
16667 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
16668 			return;
16669 		}
16670 		/*
16671 		 * If EINPROGRESS is returned, the request has been queued
16672 		 * for subsequent processing by ip_restart_optmgmt(), which
16673 		 * will do the CONN_DEC_REF().
16674 		 */
16675 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
16676 			svr4_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
16677 		} else {
16678 			tpi_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
16679 		}
16680 		break;
16681 
16682 	case T_UNITDATA_REQ:	/* unitdata request */
16683 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
16684 		break;
16685 	case T_ORDREL_REQ:	/* orderly release req */
16686 		freemsg(mp);
16687 
16688 		if (tcp->tcp_fused)
16689 			tcp_unfuse(tcp);
16690 
16691 		if (tcp_xmit_end(tcp) != 0) {
16692 			/*
16693 			 * We were crossing FINs and got a reset from
16694 			 * the other side. Just ignore it.
16695 			 */
16696 			if (connp->conn_debug) {
16697 				(void) strlog(TCP_MOD_ID, 0, 1,
16698 				    SL_ERROR|SL_TRACE,
16699 				    "tcp_wput_proto, T_ORDREL_REQ out of "
16700 				    "state %s",
16701 				    tcp_display(tcp, NULL,
16702 				    DISP_ADDR_AND_PORT));
16703 			}
16704 		}
16705 		break;
16706 	case T_ADDR_REQ:
16707 		tcp_addr_req(tcp, mp);
16708 		break;
16709 	default:
16710 		if (connp->conn_debug) {
16711 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
16712 			    "tcp_wput_proto, bogus TPI msg, type %d",
16713 			    tprim->type);
16714 		}
16715 		/*
16716 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
16717 		 * to recover.
16718 		 */
16719 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
16720 		break;
16721 	}
16722 }
16723 
16724 /*
16725  * The TCP write service routine should never be called...
16726  */
16727 /* ARGSUSED */
16728 static void
16729 tcp_wsrv(queue_t *q)
16730 {
16731 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16732 
16733 	TCP_STAT(tcps, tcp_wsrv_called);
16734 }
16735 
16736 /*
16737  * Send out a control packet on the tcp connection specified.  This routine
16738  * is typically called where we need a simple ACK or RST generated.
16739  */
16740 static void
16741 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
16742 {
16743 	uchar_t		*rptr;
16744 	tcpha_t		*tcpha;
16745 	ipha_t		*ipha = NULL;
16746 	ip6_t		*ip6h = NULL;
16747 	uint32_t	sum;
16748 	int		total_hdr_len;
16749 	int		ip_hdr_len;
16750 	mblk_t		*mp;
16751 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16752 	conn_t		*connp = tcp->tcp_connp;
16753 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
16754 
16755 	/*
16756 	 * Save sum for use in source route later.
16757 	 */
16758 	sum = connp->conn_ht_ulp_len + connp->conn_sum;
16759 	total_hdr_len = connp->conn_ht_iphc_len;
16760 	ip_hdr_len = ixa->ixa_ip_hdr_length;
16761 
16762 	/* If a text string is passed in with the request, pass it to strlog. */
16763 	if (str != NULL && connp->conn_debug) {
16764 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
16765 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
16766 		    str, seq, ack, ctl);
16767 	}
16768 	mp = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
16769 	    BPRI_MED);
16770 	if (mp == NULL) {
16771 		return;
16772 	}
16773 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
16774 	mp->b_rptr = rptr;
16775 	mp->b_wptr = &rptr[total_hdr_len];
16776 	bcopy(connp->conn_ht_iphc, rptr, total_hdr_len);
16777 
16778 	ixa->ixa_pktlen = total_hdr_len;
16779 
16780 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
16781 		ipha = (ipha_t *)rptr;
16782 		ipha->ipha_length = htons(total_hdr_len);
16783 	} else {
16784 		ip6h = (ip6_t *)rptr;
16785 		ip6h->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
16786 	}
16787 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
16788 	tcpha->tha_flags = (uint8_t)ctl;
16789 	if (ctl & TH_RST) {
16790 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
16791 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
16792 		/*
16793 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
16794 		 */
16795 		if (tcp->tcp_snd_ts_ok &&
16796 		    tcp->tcp_state > TCPS_SYN_SENT) {
16797 			mp->b_wptr = &rptr[total_hdr_len - TCPOPT_REAL_TS_LEN];
16798 			*(mp->b_wptr) = TCPOPT_EOL;
16799 
16800 			ixa->ixa_pktlen = total_hdr_len - TCPOPT_REAL_TS_LEN;
16801 
16802 			if (connp->conn_ipversion == IPV4_VERSION) {
16803 				ipha->ipha_length = htons(total_hdr_len -
16804 				    TCPOPT_REAL_TS_LEN);
16805 			} else {
16806 				ip6h->ip6_plen = htons(total_hdr_len -
16807 				    IPV6_HDR_LEN - TCPOPT_REAL_TS_LEN);
16808 			}
16809 			tcpha->tha_offset_and_reserved -= (3 << 4);
16810 			sum -= TCPOPT_REAL_TS_LEN;
16811 		}
16812 	}
16813 	if (ctl & TH_ACK) {
16814 		if (tcp->tcp_snd_ts_ok) {
16815 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
16816 
16817 			U32_TO_BE32(llbolt,
16818 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
16819 			U32_TO_BE32(tcp->tcp_ts_recent,
16820 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
16821 		}
16822 
16823 		/* Update the latest receive window size in TCP header. */
16824 		tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
16825 		tcp->tcp_rack = ack;
16826 		tcp->tcp_rack_cnt = 0;
16827 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
16828 	}
16829 	BUMP_LOCAL(tcp->tcp_obsegs);
16830 	tcpha->tha_seq = htonl(seq);
16831 	tcpha->tha_ack = htonl(ack);
16832 	/*
16833 	 * Include the adjustment for a source route if any.
16834 	 */
16835 	sum = (sum >> 16) + (sum & 0xFFFF);
16836 	tcpha->tha_sum = htons(sum);
16837 	tcp_send_data(tcp, mp);
16838 }
16839 
16840 /*
16841  * If this routine returns B_TRUE, TCP can generate a RST in response
16842  * to a segment.  If it returns B_FALSE, TCP should not respond.
16843  */
16844 static boolean_t
16845 tcp_send_rst_chk(tcp_stack_t *tcps)
16846 {
16847 	clock_t	now;
16848 
16849 	/*
16850 	 * TCP needs to protect itself from generating too many RSTs.
16851 	 * This can be a DoS attack by sending us random segments
16852 	 * soliciting RSTs.
16853 	 *
16854 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
16855 	 * in each 1 second interval.  In this way, TCP still generate
16856 	 * RSTs in normal cases but when under attack, the impact is
16857 	 * limited.
16858 	 */
16859 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
16860 		now = ddi_get_lbolt();
16861 		/* lbolt can wrap around. */
16862 		if ((tcps->tcps_last_rst_intrvl > now) ||
16863 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
16864 		    1*SECONDS)) {
16865 			tcps->tcps_last_rst_intrvl = now;
16866 			tcps->tcps_rst_cnt = 1;
16867 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
16868 			return (B_FALSE);
16869 		}
16870 	}
16871 	return (B_TRUE);
16872 }
16873 
16874 /*
16875  * Generate a reset based on an inbound packet, connp is set by caller
16876  * when RST is in response to an unexpected inbound packet for which
16877  * there is active tcp state in the system.
16878  *
16879  * IPSEC NOTE : Try to send the reply with the same protection as it came
16880  * in.  We have the ip_recv_attr_t which is reversed to form the ip_xmit_attr_t.
16881  * That way the packet will go out at the same level of protection as it
16882  * came in with.
16883  */
16884 static void
16885 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl,
16886     ip_recv_attr_t *ira, ip_stack_t *ipst, conn_t *connp)
16887 {
16888 	ipha_t		*ipha = NULL;
16889 	ip6_t		*ip6h = NULL;
16890 	ushort_t	len;
16891 	tcpha_t		*tcpha;
16892 	int		i;
16893 	ipaddr_t	v4addr;
16894 	in6_addr_t	v6addr;
16895 	netstack_t	*ns = ipst->ips_netstack;
16896 	tcp_stack_t	*tcps = ns->netstack_tcp;
16897 	ip_xmit_attr_t	ixas, *ixa;
16898 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
16899 	boolean_t	need_refrele = B_FALSE;		/* ixa_refrele(ixa) */
16900 	ushort_t	port;
16901 
16902 	if (!tcp_send_rst_chk(tcps)) {
16903 		tcps->tcps_rst_unsent++;
16904 		freemsg(mp);
16905 		return;
16906 	}
16907 
16908 	/*
16909 	 * If connp != NULL we use conn_ixa to keep IP_NEXTHOP and other
16910 	 * options from the listener. In that case the caller must ensure that
16911 	 * we are running on the listener = connp squeue.
16912 	 *
16913 	 * We get a safe copy of conn_ixa so we don't need to restore anything
16914 	 * we or ip_output_simple might change in the ixa.
16915 	 */
16916 	if (connp != NULL) {
16917 		ASSERT(connp->conn_on_sqp);
16918 
16919 		ixa = conn_get_ixa_exclusive(connp);
16920 		if (ixa == NULL) {
16921 			tcps->tcps_rst_unsent++;
16922 			freemsg(mp);
16923 			return;
16924 		}
16925 		need_refrele = B_TRUE;
16926 	} else {
16927 		bzero(&ixas, sizeof (ixas));
16928 		ixa = &ixas;
16929 		/*
16930 		 * IXAF_VERIFY_SOURCE is overkill since we know the
16931 		 * packet was for us.
16932 		 */
16933 		ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE;
16934 		ixa->ixa_protocol = IPPROTO_TCP;
16935 		ixa->ixa_zoneid = ira->ira_zoneid;
16936 		ixa->ixa_ifindex = 0;
16937 		ixa->ixa_ipst = ipst;
16938 		ixa->ixa_cred = kcred;
16939 		ixa->ixa_cpid = NOPID;
16940 	}
16941 
16942 	if (str && tcps->tcps_dbg) {
16943 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
16944 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
16945 		    "flags 0x%x",
16946 		    str, seq, ack, ctl);
16947 	}
16948 	if (mp->b_datap->db_ref != 1) {
16949 		mblk_t *mp1 = copyb(mp);
16950 		freemsg(mp);
16951 		mp = mp1;
16952 		if (mp == NULL)
16953 			goto done;
16954 	} else if (mp->b_cont) {
16955 		freemsg(mp->b_cont);
16956 		mp->b_cont = NULL;
16957 		DB_CKSUMFLAGS(mp) = 0;
16958 	}
16959 	/*
16960 	 * We skip reversing source route here.
16961 	 * (for now we replace all IP options with EOL)
16962 	 */
16963 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
16964 		ipha = (ipha_t *)mp->b_rptr;
16965 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
16966 			mp->b_rptr[i] = IPOPT_EOL;
16967 		/*
16968 		 * Make sure that src address isn't flagrantly invalid.
16969 		 * Not all broadcast address checking for the src address
16970 		 * is possible, since we don't know the netmask of the src
16971 		 * addr.  No check for destination address is done, since
16972 		 * IP will not pass up a packet with a broadcast dest
16973 		 * address to TCP.  Similar checks are done below for IPv6.
16974 		 */
16975 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
16976 		    CLASSD(ipha->ipha_src)) {
16977 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
16978 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
16979 			freemsg(mp);
16980 			goto done;
16981 		}
16982 	} else {
16983 		ip6h = (ip6_t *)mp->b_rptr;
16984 
16985 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
16986 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
16987 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
16988 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
16989 			freemsg(mp);
16990 			goto done;
16991 		}
16992 
16993 		/* Remove any extension headers assuming partial overlay */
16994 		if (ip_hdr_len > IPV6_HDR_LEN) {
16995 			uint8_t *to;
16996 
16997 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
16998 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
16999 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
17000 			ip_hdr_len = IPV6_HDR_LEN;
17001 			ip6h = (ip6_t *)mp->b_rptr;
17002 			ip6h->ip6_nxt = IPPROTO_TCP;
17003 		}
17004 	}
17005 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
17006 	if (tcpha->tha_flags & TH_RST) {
17007 		freemsg(mp);
17008 		goto done;
17009 	}
17010 	tcpha->tha_offset_and_reserved = (5 << 4);
17011 	len = ip_hdr_len + sizeof (tcpha_t);
17012 	mp->b_wptr = &mp->b_rptr[len];
17013 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17014 		ipha->ipha_length = htons(len);
17015 		/* Swap addresses */
17016 		v4addr = ipha->ipha_src;
17017 		ipha->ipha_src = ipha->ipha_dst;
17018 		ipha->ipha_dst = v4addr;
17019 		ipha->ipha_ident = 0;
17020 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
17021 		ixa->ixa_flags |= IXAF_IS_IPV4;
17022 		ixa->ixa_ip_hdr_length = ip_hdr_len;
17023 	} else {
17024 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
17025 		/* Swap addresses */
17026 		v6addr = ip6h->ip6_src;
17027 		ip6h->ip6_src = ip6h->ip6_dst;
17028 		ip6h->ip6_dst = v6addr;
17029 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
17030 		ixa->ixa_flags &= ~IXAF_IS_IPV4;
17031 
17032 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_dst)) {
17033 			ixa->ixa_flags |= IXAF_SCOPEID_SET;
17034 			ixa->ixa_scopeid = ira->ira_ruifindex;
17035 		}
17036 		ixa->ixa_ip_hdr_length = IPV6_HDR_LEN;
17037 	}
17038 	ixa->ixa_pktlen = len;
17039 
17040 	/* Swap the ports */
17041 	port = tcpha->tha_fport;
17042 	tcpha->tha_fport = tcpha->tha_lport;
17043 	tcpha->tha_lport = port;
17044 
17045 	tcpha->tha_ack = htonl(ack);
17046 	tcpha->tha_seq = htonl(seq);
17047 	tcpha->tha_win = 0;
17048 	tcpha->tha_sum = htons(sizeof (tcpha_t));
17049 	tcpha->tha_flags = (uint8_t)ctl;
17050 	if (ctl & TH_RST) {
17051 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17052 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17053 	}
17054 
17055 	/* Discard any old label */
17056 	if (ixa->ixa_free_flags & IXA_FREE_TSL) {
17057 		ASSERT(ixa->ixa_tsl != NULL);
17058 		label_rele(ixa->ixa_tsl);
17059 		ixa->ixa_free_flags &= ~IXA_FREE_TSL;
17060 	}
17061 	ixa->ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
17062 
17063 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
17064 		/*
17065 		 * Apply IPsec based on how IPsec was applied to
17066 		 * the packet that caused the RST.
17067 		 */
17068 		if (!ipsec_in_to_out(ira, ixa, mp, ipha, ip6h)) {
17069 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
17070 			/* Note: mp already consumed and ip_drop_packet done */
17071 			goto done;
17072 		}
17073 	} else {
17074 		/*
17075 		 * This is in clear. The RST message we are building
17076 		 * here should go out in clear, independent of our policy.
17077 		 */
17078 		ixa->ixa_flags |= IXAF_NO_IPSEC;
17079 	}
17080 
17081 	/*
17082 	 * NOTE:  one might consider tracing a TCP packet here, but
17083 	 * this function has no active TCP state and no tcp structure
17084 	 * that has a trace buffer.  If we traced here, we would have
17085 	 * to keep a local trace buffer in tcp_record_trace().
17086 	 */
17087 
17088 	(void) ip_output_simple(mp, ixa);
17089 done:
17090 	ixa_cleanup(ixa);
17091 	if (need_refrele) {
17092 		ASSERT(ixa != &ixas);
17093 		ixa_refrele(ixa);
17094 	}
17095 }
17096 
17097 /*
17098  * Initiate closedown sequence on an active connection.  (May be called as
17099  * writer.)  Return value zero for OK return, non-zero for error return.
17100  */
17101 static int
17102 tcp_xmit_end(tcp_t *tcp)
17103 {
17104 	mblk_t		*mp;
17105 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17106 	iulp_t		uinfo;
17107 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17108 	conn_t		*connp = tcp->tcp_connp;
17109 
17110 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
17111 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
17112 		/*
17113 		 * Invalid state, only states TCPS_SYN_RCVD,
17114 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
17115 		 */
17116 		return (-1);
17117 	}
17118 
17119 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
17120 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
17121 	/*
17122 	 * If there is nothing more unsent, send the FIN now.
17123 	 * Otherwise, it will go out with the last segment.
17124 	 */
17125 	if (tcp->tcp_unsent == 0) {
17126 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
17127 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
17128 
17129 		if (mp) {
17130 			tcp_send_data(tcp, mp);
17131 		} else {
17132 			/*
17133 			 * Couldn't allocate msg.  Pretend we got it out.
17134 			 * Wait for rexmit timeout.
17135 			 */
17136 			tcp->tcp_snxt = tcp->tcp_fss + 1;
17137 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17138 		}
17139 
17140 		/*
17141 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
17142 		 * changed.
17143 		 */
17144 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
17145 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
17146 		}
17147 	} else {
17148 		/*
17149 		 * If tcp->tcp_cork is set, then the data will not get sent,
17150 		 * so we have to check that and unset it first.
17151 		 */
17152 		if (tcp->tcp_cork)
17153 			tcp->tcp_cork = B_FALSE;
17154 		tcp_wput_data(tcp, NULL, B_FALSE);
17155 	}
17156 
17157 	/*
17158 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
17159 	 * is 0, don't update the cache.
17160 	 */
17161 	if (tcps->tcps_rtt_updates == 0 ||
17162 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
17163 		return (0);
17164 
17165 	/*
17166 	 * We do not have a good algorithm to update ssthresh at this time.
17167 	 * So don't do any update.
17168 	 */
17169 	bzero(&uinfo, sizeof (uinfo));
17170 	uinfo.iulp_rtt = tcp->tcp_rtt_sa;
17171 	uinfo.iulp_rtt_sd = tcp->tcp_rtt_sd;
17172 
17173 	/*
17174 	 * Note that uinfo is kept for conn_faddr in the DCE. Could update even
17175 	 * if source routed but we don't.
17176 	 */
17177 	if (connp->conn_ipversion == IPV4_VERSION) {
17178 		if (connp->conn_faddr_v4 !=  tcp->tcp_ipha->ipha_dst) {
17179 			return (0);
17180 		}
17181 		(void) dce_update_uinfo_v4(connp->conn_faddr_v4, &uinfo, ipst);
17182 	} else {
17183 		uint_t ifindex;
17184 
17185 		if (!(IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
17186 		    &tcp->tcp_ip6h->ip6_dst))) {
17187 			return (0);
17188 		}
17189 		ifindex = 0;
17190 		if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_faddr_v6)) {
17191 			ip_xmit_attr_t *ixa = connp->conn_ixa;
17192 
17193 			/*
17194 			 * If we are going to create a DCE we'd better have
17195 			 * an ifindex
17196 			 */
17197 			if (ixa->ixa_nce != NULL) {
17198 				ifindex = ixa->ixa_nce->nce_common->ncec_ill->
17199 				    ill_phyint->phyint_ifindex;
17200 			} else {
17201 				return (0);
17202 			}
17203 		}
17204 
17205 		(void) dce_update_uinfo(&connp->conn_faddr_v6, ifindex, &uinfo,
17206 		    ipst);
17207 	}
17208 	return (0);
17209 }
17210 
17211 /*
17212  * Generate a "no listener here" RST in response to an "unknown" segment.
17213  * connp is set by caller when RST is in response to an unexpected
17214  * inbound packet for which there is active tcp state in the system.
17215  * Note that we are reusing the incoming mp to construct the outgoing RST.
17216  */
17217 void
17218 tcp_xmit_listeners_reset(mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst,
17219     conn_t *connp)
17220 {
17221 	uchar_t		*rptr;
17222 	uint32_t	seg_len;
17223 	tcpha_t		*tcpha;
17224 	uint32_t	seg_seq;
17225 	uint32_t	seg_ack;
17226 	uint_t		flags;
17227 	ipha_t 		*ipha;
17228 	ip6_t 		*ip6h;
17229 	boolean_t	policy_present;
17230 	netstack_t	*ns = ipst->ips_netstack;
17231 	tcp_stack_t	*tcps = ns->netstack_tcp;
17232 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
17233 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17234 
17235 	TCP_STAT(tcps, tcp_no_listener);
17236 
17237 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17238 		policy_present = ipss->ipsec_inbound_v4_policy_present;
17239 		ipha = (ipha_t *)mp->b_rptr;
17240 		ip6h = NULL;
17241 	} else {
17242 		policy_present = ipss->ipsec_inbound_v6_policy_present;
17243 		ipha = NULL;
17244 		ip6h = (ip6_t *)mp->b_rptr;
17245 	}
17246 
17247 	if (policy_present) {
17248 		/*
17249 		 * The conn_t parameter is NULL because we already know
17250 		 * nobody's home.
17251 		 */
17252 		mp = ipsec_check_global_policy(mp, (conn_t *)NULL, ipha, ip6h,
17253 		    ira, ns);
17254 		if (mp == NULL)
17255 			return;
17256 	}
17257 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
17258 		DTRACE_PROBE2(
17259 		    tx__ip__log__error__nolistener__tcp,
17260 		    char *, "Could not reply with RST to mp(1)",
17261 		    mblk_t *, mp);
17262 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
17263 		freemsg(mp);
17264 		return;
17265 	}
17266 
17267 	rptr = mp->b_rptr;
17268 
17269 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17270 	seg_seq = ntohl(tcpha->tha_seq);
17271 	seg_ack = ntohl(tcpha->tha_ack);
17272 	flags = tcpha->tha_flags;
17273 
17274 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcpha) + ip_hdr_len);
17275 	if (flags & TH_RST) {
17276 		freemsg(mp);
17277 	} else if (flags & TH_ACK) {
17278 		tcp_xmit_early_reset("no tcp, reset", mp, seg_ack, 0, TH_RST,
17279 		    ira, ipst, connp);
17280 	} else {
17281 		if (flags & TH_SYN) {
17282 			seg_len++;
17283 		} else {
17284 			/*
17285 			 * Here we violate the RFC.  Note that a normal
17286 			 * TCP will never send a segment without the ACK
17287 			 * flag, except for RST or SYN segment.  This
17288 			 * segment is neither.  Just drop it on the
17289 			 * floor.
17290 			 */
17291 			freemsg(mp);
17292 			tcps->tcps_rst_unsent++;
17293 			return;
17294 		}
17295 
17296 		tcp_xmit_early_reset("no tcp, reset/ack", mp, 0,
17297 		    seg_seq + seg_len, TH_RST | TH_ACK, ira, ipst, connp);
17298 	}
17299 }
17300 
17301 /*
17302  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
17303  * ip and tcp header ready to pass down to IP.  If the mp passed in is
17304  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
17305  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
17306  * otherwise it will dup partial mblks.)
17307  * Otherwise, an appropriate ACK packet will be generated.  This
17308  * routine is not usually called to send new data for the first time.  It
17309  * is mostly called out of the timer for retransmits, and to generate ACKs.
17310  *
17311  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
17312  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
17313  * of the original mblk chain will be returned in *offset and *end_mp.
17314  */
17315 mblk_t *
17316 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
17317     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
17318     boolean_t rexmit)
17319 {
17320 	int	data_length;
17321 	int32_t	off = 0;
17322 	uint_t	flags;
17323 	mblk_t	*mp1;
17324 	mblk_t	*mp2;
17325 	uchar_t	*rptr;
17326 	tcpha_t	*tcpha;
17327 	int32_t	num_sack_blk = 0;
17328 	int32_t	sack_opt_len = 0;
17329 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17330 	conn_t		*connp = tcp->tcp_connp;
17331 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17332 
17333 	/* Allocate for our maximum TCP header + link-level */
17334 	mp1 = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17335 	    BPRI_MED);
17336 	if (!mp1)
17337 		return (NULL);
17338 	data_length = 0;
17339 
17340 	/*
17341 	 * Note that tcp_mss has been adjusted to take into account the
17342 	 * timestamp option if applicable.  Because SACK options do not
17343 	 * appear in every TCP segments and they are of variable lengths,
17344 	 * they cannot be included in tcp_mss.  Thus we need to calculate
17345 	 * the actual segment length when we need to send a segment which
17346 	 * includes SACK options.
17347 	 */
17348 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
17349 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
17350 		    tcp->tcp_num_sack_blk);
17351 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
17352 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
17353 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
17354 			max_to_send -= sack_opt_len;
17355 	}
17356 
17357 	if (offset != NULL) {
17358 		off = *offset;
17359 		/* We use offset as an indicator that end_mp is not NULL. */
17360 		*end_mp = NULL;
17361 	}
17362 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
17363 		/* This could be faster with cooperation from downstream */
17364 		if (mp2 != mp1 && !sendall &&
17365 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
17366 		    max_to_send)
17367 			/*
17368 			 * Don't send the next mblk since the whole mblk
17369 			 * does not fit.
17370 			 */
17371 			break;
17372 		mp2->b_cont = dupb(mp);
17373 		mp2 = mp2->b_cont;
17374 		if (!mp2) {
17375 			freemsg(mp1);
17376 			return (NULL);
17377 		}
17378 		mp2->b_rptr += off;
17379 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
17380 		    (uintptr_t)INT_MAX);
17381 
17382 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
17383 		if (data_length > max_to_send) {
17384 			mp2->b_wptr -= data_length - max_to_send;
17385 			data_length = max_to_send;
17386 			off = mp2->b_wptr - mp->b_rptr;
17387 			break;
17388 		} else {
17389 			off = 0;
17390 		}
17391 	}
17392 	if (offset != NULL) {
17393 		*offset = off;
17394 		*end_mp = mp;
17395 	}
17396 	if (seg_len != NULL) {
17397 		*seg_len = data_length;
17398 	}
17399 
17400 	/* Update the latest receive window size in TCP header. */
17401 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17402 
17403 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
17404 	mp1->b_rptr = rptr;
17405 	mp1->b_wptr = rptr + connp->conn_ht_iphc_len + sack_opt_len;
17406 	bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
17407 	tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
17408 	tcpha->tha_seq = htonl(seq);
17409 
17410 	/*
17411 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
17412 	 * that this function was called from tcp_wput_data. Thus, when called
17413 	 * to retransmit data the setting of the PUSH bit may appear some
17414 	 * what random in that it might get set when it should not. This
17415 	 * should not pose any performance issues.
17416 	 */
17417 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
17418 	    tcp->tcp_unsent == data_length)) {
17419 		flags = TH_ACK | TH_PUSH;
17420 	} else {
17421 		flags = TH_ACK;
17422 	}
17423 
17424 	if (tcp->tcp_ecn_ok) {
17425 		if (tcp->tcp_ecn_echo_on)
17426 			flags |= TH_ECE;
17427 
17428 		/*
17429 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
17430 		 * There is no TCP flow control for non-data segments, and
17431 		 * only data segment is transmitted reliably.
17432 		 */
17433 		if (data_length > 0 && !rexmit) {
17434 			SET_ECT(tcp, rptr);
17435 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17436 				flags |= TH_CWR;
17437 				tcp->tcp_ecn_cwr_sent = B_TRUE;
17438 			}
17439 		}
17440 	}
17441 
17442 	if (tcp->tcp_valid_bits) {
17443 		uint32_t u1;
17444 
17445 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
17446 		    seq == tcp->tcp_iss) {
17447 			uchar_t	*wptr;
17448 
17449 			/*
17450 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
17451 			 * TCP can only be in SYN-SENT, SYN-RCVD or
17452 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
17453 			 * our SYN is not ack'ed but the app closes this
17454 			 * TCP connection.
17455 			 */
17456 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
17457 			    tcp->tcp_state == TCPS_SYN_RCVD ||
17458 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
17459 
17460 			/*
17461 			 * Tack on the MSS option.  It is always needed
17462 			 * for both active and passive open.
17463 			 *
17464 			 * MSS option value should be interface MTU - MIN
17465 			 * TCP/IP header according to RFC 793 as it means
17466 			 * the maximum segment size TCP can receive.  But
17467 			 * to get around some broken middle boxes/end hosts
17468 			 * out there, we allow the option value to be the
17469 			 * same as the MSS option size on the peer side.
17470 			 * In this way, the other side will not send
17471 			 * anything larger than they can receive.
17472 			 *
17473 			 * Note that for SYN_SENT state, the ndd param
17474 			 * tcp_use_smss_as_mss_opt has no effect as we
17475 			 * don't know the peer's MSS option value. So
17476 			 * the only case we need to take care of is in
17477 			 * SYN_RCVD state, which is done later.
17478 			 */
17479 			wptr = mp1->b_wptr;
17480 			wptr[0] = TCPOPT_MAXSEG;
17481 			wptr[1] = TCPOPT_MAXSEG_LEN;
17482 			wptr += 2;
17483 			u1 = tcp->tcp_initial_pmtu -
17484 			    (connp->conn_ipversion == IPV4_VERSION ?
17485 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
17486 			    TCP_MIN_HEADER_LENGTH;
17487 			U16_TO_BE16(u1, wptr);
17488 			mp1->b_wptr = wptr + 2;
17489 			/* Update the offset to cover the additional word */
17490 			tcpha->tha_offset_and_reserved += (1 << 4);
17491 
17492 			/*
17493 			 * Note that the following way of filling in
17494 			 * TCP options are not optimal.  Some NOPs can
17495 			 * be saved.  But there is no need at this time
17496 			 * to optimize it.  When it is needed, we will
17497 			 * do it.
17498 			 */
17499 			switch (tcp->tcp_state) {
17500 			case TCPS_SYN_SENT:
17501 				flags = TH_SYN;
17502 
17503 				if (tcp->tcp_snd_ts_ok) {
17504 					uint32_t llbolt =
17505 					    (uint32_t)LBOLT_FASTPATH;
17506 
17507 					wptr = mp1->b_wptr;
17508 					wptr[0] = TCPOPT_NOP;
17509 					wptr[1] = TCPOPT_NOP;
17510 					wptr[2] = TCPOPT_TSTAMP;
17511 					wptr[3] = TCPOPT_TSTAMP_LEN;
17512 					wptr += 4;
17513 					U32_TO_BE32(llbolt, wptr);
17514 					wptr += 4;
17515 					ASSERT(tcp->tcp_ts_recent == 0);
17516 					U32_TO_BE32(0L, wptr);
17517 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
17518 					tcpha->tha_offset_and_reserved +=
17519 					    (3 << 4);
17520 				}
17521 
17522 				/*
17523 				 * Set up all the bits to tell other side
17524 				 * we are ECN capable.
17525 				 */
17526 				if (tcp->tcp_ecn_ok) {
17527 					flags |= (TH_ECE | TH_CWR);
17528 				}
17529 				break;
17530 			case TCPS_SYN_RCVD:
17531 				flags |= TH_SYN;
17532 
17533 				/*
17534 				 * Reset the MSS option value to be SMSS
17535 				 * We should probably add back the bytes
17536 				 * for timestamp option and IPsec.  We
17537 				 * don't do that as this is a workaround
17538 				 * for broken middle boxes/end hosts, it
17539 				 * is better for us to be more cautious.
17540 				 * They may not take these things into
17541 				 * account in their SMSS calculation.  Thus
17542 				 * the peer's calculated SMSS may be smaller
17543 				 * than what it can be.  This should be OK.
17544 				 */
17545 				if (tcps->tcps_use_smss_as_mss_opt) {
17546 					u1 = tcp->tcp_mss;
17547 					U16_TO_BE16(u1, wptr);
17548 				}
17549 
17550 				/*
17551 				 * If the other side is ECN capable, reply
17552 				 * that we are also ECN capable.
17553 				 */
17554 				if (tcp->tcp_ecn_ok)
17555 					flags |= TH_ECE;
17556 				break;
17557 			default:
17558 				/*
17559 				 * The above ASSERT() makes sure that this
17560 				 * must be FIN-WAIT-1 state.  Our SYN has
17561 				 * not been ack'ed so retransmit it.
17562 				 */
17563 				flags |= TH_SYN;
17564 				break;
17565 			}
17566 
17567 			if (tcp->tcp_snd_ws_ok) {
17568 				wptr = mp1->b_wptr;
17569 				wptr[0] =  TCPOPT_NOP;
17570 				wptr[1] =  TCPOPT_WSCALE;
17571 				wptr[2] =  TCPOPT_WS_LEN;
17572 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
17573 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
17574 				tcpha->tha_offset_and_reserved += (1 << 4);
17575 			}
17576 
17577 			if (tcp->tcp_snd_sack_ok) {
17578 				wptr = mp1->b_wptr;
17579 				wptr[0] = TCPOPT_NOP;
17580 				wptr[1] = TCPOPT_NOP;
17581 				wptr[2] = TCPOPT_SACK_PERMITTED;
17582 				wptr[3] = TCPOPT_SACK_OK_LEN;
17583 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
17584 				tcpha->tha_offset_and_reserved += (1 << 4);
17585 			}
17586 
17587 			/* allocb() of adequate mblk assures space */
17588 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
17589 			    (uintptr_t)INT_MAX);
17590 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
17591 			/*
17592 			 * Get IP set to checksum on our behalf
17593 			 * Include the adjustment for a source route if any.
17594 			 */
17595 			u1 += connp->conn_sum;
17596 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
17597 			tcpha->tha_sum = htons(u1);
17598 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17599 		}
17600 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17601 		    (seq + data_length) == tcp->tcp_fss) {
17602 			if (!tcp->tcp_fin_acked) {
17603 				flags |= TH_FIN;
17604 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17605 			}
17606 			if (!tcp->tcp_fin_sent) {
17607 				tcp->tcp_fin_sent = B_TRUE;
17608 				switch (tcp->tcp_state) {
17609 				case TCPS_SYN_RCVD:
17610 				case TCPS_ESTABLISHED:
17611 					tcp->tcp_state = TCPS_FIN_WAIT_1;
17612 					break;
17613 				case TCPS_CLOSE_WAIT:
17614 					tcp->tcp_state = TCPS_LAST_ACK;
17615 					break;
17616 				}
17617 				if (tcp->tcp_suna == tcp->tcp_snxt)
17618 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17619 				tcp->tcp_snxt = tcp->tcp_fss + 1;
17620 			}
17621 		}
17622 		/*
17623 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
17624 		 * is smaller than seq, u1 will become a very huge value.
17625 		 * So the comparison will fail.  Also note that tcp_urp
17626 		 * should be positive, see RFC 793 page 17.
17627 		 */
17628 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
17629 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
17630 		    u1 < (uint32_t)(64 * 1024)) {
17631 			flags |= TH_URG;
17632 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
17633 			tcpha->tha_urp = htons(u1);
17634 		}
17635 	}
17636 	tcpha->tha_flags = (uchar_t)flags;
17637 	tcp->tcp_rack = tcp->tcp_rnxt;
17638 	tcp->tcp_rack_cnt = 0;
17639 
17640 	if (tcp->tcp_snd_ts_ok) {
17641 		if (tcp->tcp_state != TCPS_SYN_SENT) {
17642 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17643 
17644 			U32_TO_BE32(llbolt,
17645 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17646 			U32_TO_BE32(tcp->tcp_ts_recent,
17647 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17648 		}
17649 	}
17650 
17651 	if (num_sack_blk > 0) {
17652 		uchar_t *wptr = (uchar_t *)tcpha + connp->conn_ht_ulp_len;
17653 		sack_blk_t *tmp;
17654 		int32_t	i;
17655 
17656 		wptr[0] = TCPOPT_NOP;
17657 		wptr[1] = TCPOPT_NOP;
17658 		wptr[2] = TCPOPT_SACK;
17659 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
17660 		    sizeof (sack_blk_t);
17661 		wptr += TCPOPT_REAL_SACK_LEN;
17662 
17663 		tmp = tcp->tcp_sack_list;
17664 		for (i = 0; i < num_sack_blk; i++) {
17665 			U32_TO_BE32(tmp[i].begin, wptr);
17666 			wptr += sizeof (tcp_seq);
17667 			U32_TO_BE32(tmp[i].end, wptr);
17668 			wptr += sizeof (tcp_seq);
17669 		}
17670 		tcpha->tha_offset_and_reserved += ((num_sack_blk * 2 + 1) << 4);
17671 	}
17672 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
17673 	data_length += (int)(mp1->b_wptr - rptr);
17674 
17675 	ixa->ixa_pktlen = data_length;
17676 
17677 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
17678 		((ipha_t *)rptr)->ipha_length = htons(data_length);
17679 	} else {
17680 		ip6_t *ip6 = (ip6_t *)rptr;
17681 
17682 		ip6->ip6_plen = htons(data_length - IPV6_HDR_LEN);
17683 	}
17684 
17685 	/*
17686 	 * Prime pump for IP
17687 	 * Include the adjustment for a source route if any.
17688 	 */
17689 	data_length -= ixa->ixa_ip_hdr_length;
17690 	data_length += connp->conn_sum;
17691 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
17692 	tcpha->tha_sum = htons(data_length);
17693 	if (tcp->tcp_ip_forward_progress) {
17694 		tcp->tcp_ip_forward_progress = B_FALSE;
17695 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
17696 	} else {
17697 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
17698 	}
17699 	return (mp1);
17700 }
17701 
17702 /* This function handles the push timeout. */
17703 void
17704 tcp_push_timer(void *arg)
17705 {
17706 	conn_t	*connp = (conn_t *)arg;
17707 	tcp_t *tcp = connp->conn_tcp;
17708 
17709 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
17710 
17711 	ASSERT(tcp->tcp_listener == NULL);
17712 
17713 	ASSERT(!IPCL_IS_NONSTR(connp));
17714 
17715 	tcp->tcp_push_tid = 0;
17716 
17717 	if (tcp->tcp_rcv_list != NULL &&
17718 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
17719 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
17720 }
17721 
17722 /*
17723  * This function handles delayed ACK timeout.
17724  */
17725 static void
17726 tcp_ack_timer(void *arg)
17727 {
17728 	conn_t	*connp = (conn_t *)arg;
17729 	tcp_t *tcp = connp->conn_tcp;
17730 	mblk_t *mp;
17731 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17732 
17733 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
17734 
17735 	tcp->tcp_ack_tid = 0;
17736 
17737 	if (tcp->tcp_fused)
17738 		return;
17739 
17740 	/*
17741 	 * Do not send ACK if there is no outstanding unack'ed data.
17742 	 */
17743 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
17744 		return;
17745 	}
17746 
17747 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
17748 		/*
17749 		 * Make sure we don't allow deferred ACKs to result in
17750 		 * timer-based ACKing.  If we have held off an ACK
17751 		 * when there was more than an mss here, and the timer
17752 		 * goes off, we have to worry about the possibility
17753 		 * that the sender isn't doing slow-start, or is out
17754 		 * of step with us for some other reason.  We fall
17755 		 * permanently back in the direction of
17756 		 * ACK-every-other-packet as suggested in RFC 1122.
17757 		 */
17758 		if (tcp->tcp_rack_abs_max > 2)
17759 			tcp->tcp_rack_abs_max--;
17760 		tcp->tcp_rack_cur_max = 2;
17761 	}
17762 	mp = tcp_ack_mp(tcp);
17763 
17764 	if (mp != NULL) {
17765 		BUMP_LOCAL(tcp->tcp_obsegs);
17766 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
17767 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
17768 		tcp_send_data(tcp, mp);
17769 	}
17770 }
17771 
17772 
17773 /* Generate an ACK-only (no data) segment for a TCP endpoint */
17774 static mblk_t *
17775 tcp_ack_mp(tcp_t *tcp)
17776 {
17777 	uint32_t	seq_no;
17778 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17779 	conn_t		*connp = tcp->tcp_connp;
17780 
17781 	/*
17782 	 * There are a few cases to be considered while setting the sequence no.
17783 	 * Essentially, we can come here while processing an unacceptable pkt
17784 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
17785 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
17786 	 * If we are here for a zero window probe, stick with suna. In all
17787 	 * other cases, we check if suna + swnd encompasses snxt and set
17788 	 * the sequence number to snxt, if so. If snxt falls outside the
17789 	 * window (the receiver probably shrunk its window), we will go with
17790 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
17791 	 * receiver.
17792 	 */
17793 	if (tcp->tcp_zero_win_probe) {
17794 		seq_no = tcp->tcp_suna;
17795 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
17796 		ASSERT(tcp->tcp_swnd == 0);
17797 		seq_no = tcp->tcp_snxt;
17798 	} else {
17799 		seq_no = SEQ_GT(tcp->tcp_snxt,
17800 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
17801 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
17802 	}
17803 
17804 	if (tcp->tcp_valid_bits) {
17805 		/*
17806 		 * For the complex case where we have to send some
17807 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
17808 		 */
17809 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
17810 		    NULL, B_FALSE));
17811 	} else {
17812 		/* Generate a simple ACK */
17813 		int	data_length;
17814 		uchar_t	*rptr;
17815 		tcpha_t	*tcpha;
17816 		mblk_t	*mp1;
17817 		int32_t	total_hdr_len;
17818 		int32_t	tcp_hdr_len;
17819 		int32_t	num_sack_blk = 0;
17820 		int32_t sack_opt_len;
17821 		ip_xmit_attr_t *ixa = connp->conn_ixa;
17822 
17823 		/*
17824 		 * Allocate space for TCP + IP headers
17825 		 * and link-level header
17826 		 */
17827 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
17828 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
17829 			    tcp->tcp_num_sack_blk);
17830 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
17831 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
17832 			total_hdr_len = connp->conn_ht_iphc_len + sack_opt_len;
17833 			tcp_hdr_len = connp->conn_ht_ulp_len + sack_opt_len;
17834 		} else {
17835 			total_hdr_len = connp->conn_ht_iphc_len;
17836 			tcp_hdr_len = connp->conn_ht_ulp_len;
17837 		}
17838 		mp1 = allocb(total_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
17839 		if (!mp1)
17840 			return (NULL);
17841 
17842 		/* Update the latest receive window size in TCP header. */
17843 		tcp->tcp_tcpha->tha_win =
17844 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17845 		/* copy in prototype TCP + IP header */
17846 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
17847 		mp1->b_rptr = rptr;
17848 		mp1->b_wptr = rptr + total_hdr_len;
17849 		bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
17850 
17851 		tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
17852 
17853 		/* Set the TCP sequence number. */
17854 		tcpha->tha_seq = htonl(seq_no);
17855 
17856 		/* Set up the TCP flag field. */
17857 		tcpha->tha_flags = (uchar_t)TH_ACK;
17858 		if (tcp->tcp_ecn_echo_on)
17859 			tcpha->tha_flags |= TH_ECE;
17860 
17861 		tcp->tcp_rack = tcp->tcp_rnxt;
17862 		tcp->tcp_rack_cnt = 0;
17863 
17864 		/* fill in timestamp option if in use */
17865 		if (tcp->tcp_snd_ts_ok) {
17866 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17867 
17868 			U32_TO_BE32(llbolt,
17869 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17870 			U32_TO_BE32(tcp->tcp_ts_recent,
17871 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17872 		}
17873 
17874 		/* Fill in SACK options */
17875 		if (num_sack_blk > 0) {
17876 			uchar_t *wptr = (uchar_t *)tcpha +
17877 			    connp->conn_ht_ulp_len;
17878 			sack_blk_t *tmp;
17879 			int32_t	i;
17880 
17881 			wptr[0] = TCPOPT_NOP;
17882 			wptr[1] = TCPOPT_NOP;
17883 			wptr[2] = TCPOPT_SACK;
17884 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
17885 			    sizeof (sack_blk_t);
17886 			wptr += TCPOPT_REAL_SACK_LEN;
17887 
17888 			tmp = tcp->tcp_sack_list;
17889 			for (i = 0; i < num_sack_blk; i++) {
17890 				U32_TO_BE32(tmp[i].begin, wptr);
17891 				wptr += sizeof (tcp_seq);
17892 				U32_TO_BE32(tmp[i].end, wptr);
17893 				wptr += sizeof (tcp_seq);
17894 			}
17895 			tcpha->tha_offset_and_reserved +=
17896 			    ((num_sack_blk * 2 + 1) << 4);
17897 		}
17898 
17899 		ixa->ixa_pktlen = total_hdr_len;
17900 
17901 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
17902 			((ipha_t *)rptr)->ipha_length = htons(total_hdr_len);
17903 		} else {
17904 			ip6_t *ip6 = (ip6_t *)rptr;
17905 
17906 			ip6->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
17907 		}
17908 
17909 		/*
17910 		 * Prime pump for checksum calculation in IP.  Include the
17911 		 * adjustment for a source route if any.
17912 		 */
17913 		data_length = tcp_hdr_len + connp->conn_sum;
17914 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
17915 		tcpha->tha_sum = htons(data_length);
17916 
17917 		if (tcp->tcp_ip_forward_progress) {
17918 			tcp->tcp_ip_forward_progress = B_FALSE;
17919 			connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
17920 		} else {
17921 			connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
17922 		}
17923 		return (mp1);
17924 	}
17925 }
17926 
17927 /*
17928  * Hash list insertion routine for tcp_t structures. Each hash bucket
17929  * contains a list of tcp_t entries, and each entry is bound to a unique
17930  * port. If there are multiple tcp_t's that are bound to the same port, then
17931  * one of them will be linked into the hash bucket list, and the rest will
17932  * hang off of that one entry. For each port, entries bound to a specific IP
17933  * address will be inserted before those those bound to INADDR_ANY.
17934  */
17935 static void
17936 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
17937 {
17938 	tcp_t	**tcpp;
17939 	tcp_t	*tcpnext;
17940 	tcp_t	*tcphash;
17941 	conn_t	*connp = tcp->tcp_connp;
17942 	conn_t	*connext;
17943 
17944 	if (tcp->tcp_ptpbhn != NULL) {
17945 		ASSERT(!caller_holds_lock);
17946 		tcp_bind_hash_remove(tcp);
17947 	}
17948 	tcpp = &tbf->tf_tcp;
17949 	if (!caller_holds_lock) {
17950 		mutex_enter(&tbf->tf_lock);
17951 	} else {
17952 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
17953 	}
17954 	tcphash = tcpp[0];
17955 	tcpnext = NULL;
17956 	if (tcphash != NULL) {
17957 		/* Look for an entry using the same port */
17958 		while ((tcphash = tcpp[0]) != NULL &&
17959 		    connp->conn_lport != tcphash->tcp_connp->conn_lport)
17960 			tcpp = &(tcphash->tcp_bind_hash);
17961 
17962 		/* The port was not found, just add to the end */
17963 		if (tcphash == NULL)
17964 			goto insert;
17965 
17966 		/*
17967 		 * OK, there already exists an entry bound to the
17968 		 * same port.
17969 		 *
17970 		 * If the new tcp bound to the INADDR_ANY address
17971 		 * and the first one in the list is not bound to
17972 		 * INADDR_ANY we skip all entries until we find the
17973 		 * first one bound to INADDR_ANY.
17974 		 * This makes sure that applications binding to a
17975 		 * specific address get preference over those binding to
17976 		 * INADDR_ANY.
17977 		 */
17978 		tcpnext = tcphash;
17979 		connext = tcpnext->tcp_connp;
17980 		tcphash = NULL;
17981 		if (V6_OR_V4_INADDR_ANY(connp->conn_bound_addr_v6) &&
17982 		    !V6_OR_V4_INADDR_ANY(connext->conn_bound_addr_v6)) {
17983 			while ((tcpnext = tcpp[0]) != NULL) {
17984 				connext = tcpnext->tcp_connp;
17985 				if (!V6_OR_V4_INADDR_ANY(
17986 				    connext->conn_bound_addr_v6))
17987 					tcpp = &(tcpnext->tcp_bind_hash_port);
17988 				else
17989 					break;
17990 			}
17991 			if (tcpnext != NULL) {
17992 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
17993 				tcphash = tcpnext->tcp_bind_hash;
17994 				if (tcphash != NULL) {
17995 					tcphash->tcp_ptpbhn =
17996 					    &(tcp->tcp_bind_hash);
17997 					tcpnext->tcp_bind_hash = NULL;
17998 				}
17999 			}
18000 		} else {
18001 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18002 			tcphash = tcpnext->tcp_bind_hash;
18003 			if (tcphash != NULL) {
18004 				tcphash->tcp_ptpbhn =
18005 				    &(tcp->tcp_bind_hash);
18006 				tcpnext->tcp_bind_hash = NULL;
18007 			}
18008 		}
18009 	}
18010 insert:
18011 	tcp->tcp_bind_hash_port = tcpnext;
18012 	tcp->tcp_bind_hash = tcphash;
18013 	tcp->tcp_ptpbhn = tcpp;
18014 	tcpp[0] = tcp;
18015 	if (!caller_holds_lock)
18016 		mutex_exit(&tbf->tf_lock);
18017 }
18018 
18019 /*
18020  * Hash list removal routine for tcp_t structures.
18021  */
18022 static void
18023 tcp_bind_hash_remove(tcp_t *tcp)
18024 {
18025 	tcp_t	*tcpnext;
18026 	kmutex_t *lockp;
18027 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18028 	conn_t		*connp = tcp->tcp_connp;
18029 
18030 	if (tcp->tcp_ptpbhn == NULL)
18031 		return;
18032 
18033 	/*
18034 	 * Extract the lock pointer in case there are concurrent
18035 	 * hash_remove's for this instance.
18036 	 */
18037 	ASSERT(connp->conn_lport != 0);
18038 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(
18039 	    connp->conn_lport)].tf_lock;
18040 
18041 	ASSERT(lockp != NULL);
18042 	mutex_enter(lockp);
18043 	if (tcp->tcp_ptpbhn) {
18044 		tcpnext = tcp->tcp_bind_hash_port;
18045 		if (tcpnext != NULL) {
18046 			tcp->tcp_bind_hash_port = NULL;
18047 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18048 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
18049 			if (tcpnext->tcp_bind_hash != NULL) {
18050 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
18051 				    &(tcpnext->tcp_bind_hash);
18052 				tcp->tcp_bind_hash = NULL;
18053 			}
18054 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
18055 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18056 			tcp->tcp_bind_hash = NULL;
18057 		}
18058 		*tcp->tcp_ptpbhn = tcpnext;
18059 		tcp->tcp_ptpbhn = NULL;
18060 	}
18061 	mutex_exit(lockp);
18062 }
18063 
18064 
18065 /*
18066  * Hash list lookup routine for tcp_t structures.
18067  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
18068  */
18069 static tcp_t *
18070 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
18071 {
18072 	tf_t	*tf;
18073 	tcp_t	*tcp;
18074 
18075 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18076 	mutex_enter(&tf->tf_lock);
18077 	for (tcp = tf->tf_tcp; tcp != NULL;
18078 	    tcp = tcp->tcp_acceptor_hash) {
18079 		if (tcp->tcp_acceptor_id == id) {
18080 			CONN_INC_REF(tcp->tcp_connp);
18081 			mutex_exit(&tf->tf_lock);
18082 			return (tcp);
18083 		}
18084 	}
18085 	mutex_exit(&tf->tf_lock);
18086 	return (NULL);
18087 }
18088 
18089 
18090 /*
18091  * Hash list insertion routine for tcp_t structures.
18092  */
18093 void
18094 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
18095 {
18096 	tf_t	*tf;
18097 	tcp_t	**tcpp;
18098 	tcp_t	*tcpnext;
18099 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18100 
18101 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18102 
18103 	if (tcp->tcp_ptpahn != NULL)
18104 		tcp_acceptor_hash_remove(tcp);
18105 	tcpp = &tf->tf_tcp;
18106 	mutex_enter(&tf->tf_lock);
18107 	tcpnext = tcpp[0];
18108 	if (tcpnext)
18109 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
18110 	tcp->tcp_acceptor_hash = tcpnext;
18111 	tcp->tcp_ptpahn = tcpp;
18112 	tcpp[0] = tcp;
18113 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
18114 	mutex_exit(&tf->tf_lock);
18115 }
18116 
18117 /*
18118  * Hash list removal routine for tcp_t structures.
18119  */
18120 static void
18121 tcp_acceptor_hash_remove(tcp_t *tcp)
18122 {
18123 	tcp_t	*tcpnext;
18124 	kmutex_t *lockp;
18125 
18126 	/*
18127 	 * Extract the lock pointer in case there are concurrent
18128 	 * hash_remove's for this instance.
18129 	 */
18130 	lockp = tcp->tcp_acceptor_lockp;
18131 
18132 	if (tcp->tcp_ptpahn == NULL)
18133 		return;
18134 
18135 	ASSERT(lockp != NULL);
18136 	mutex_enter(lockp);
18137 	if (tcp->tcp_ptpahn) {
18138 		tcpnext = tcp->tcp_acceptor_hash;
18139 		if (tcpnext) {
18140 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
18141 			tcp->tcp_acceptor_hash = NULL;
18142 		}
18143 		*tcp->tcp_ptpahn = tcpnext;
18144 		tcp->tcp_ptpahn = NULL;
18145 	}
18146 	mutex_exit(lockp);
18147 	tcp->tcp_acceptor_lockp = NULL;
18148 }
18149 
18150 /*
18151  * Type three generator adapted from the random() function in 4.4 BSD:
18152  */
18153 
18154 /*
18155  * Copyright (c) 1983, 1993
18156  *	The Regents of the University of California.  All rights reserved.
18157  *
18158  * Redistribution and use in source and binary forms, with or without
18159  * modification, are permitted provided that the following conditions
18160  * are met:
18161  * 1. Redistributions of source code must retain the above copyright
18162  *    notice, this list of conditions and the following disclaimer.
18163  * 2. Redistributions in binary form must reproduce the above copyright
18164  *    notice, this list of conditions and the following disclaimer in the
18165  *    documentation and/or other materials provided with the distribution.
18166  * 3. All advertising materials mentioning features or use of this software
18167  *    must display the following acknowledgement:
18168  *	This product includes software developed by the University of
18169  *	California, Berkeley and its contributors.
18170  * 4. Neither the name of the University nor the names of its contributors
18171  *    may be used to endorse or promote products derived from this software
18172  *    without specific prior written permission.
18173  *
18174  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18175  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18176  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18177  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18178  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18179  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
18180  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
18181  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18182  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18183  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
18184  * SUCH DAMAGE.
18185  */
18186 
18187 /* Type 3 -- x**31 + x**3 + 1 */
18188 #define	DEG_3		31
18189 #define	SEP_3		3
18190 
18191 
18192 /* Protected by tcp_random_lock */
18193 static int tcp_randtbl[DEG_3 + 1];
18194 
18195 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
18196 static int *tcp_random_rptr = &tcp_randtbl[1];
18197 
18198 static int *tcp_random_state = &tcp_randtbl[1];
18199 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
18200 
18201 kmutex_t tcp_random_lock;
18202 
18203 void
18204 tcp_random_init(void)
18205 {
18206 	int i;
18207 	hrtime_t hrt;
18208 	time_t wallclock;
18209 	uint64_t result;
18210 
18211 	/*
18212 	 * Use high-res timer and current time for seed.  Gethrtime() returns
18213 	 * a longlong, which may contain resolution down to nanoseconds.
18214 	 * The current time will either be a 32-bit or a 64-bit quantity.
18215 	 * XOR the two together in a 64-bit result variable.
18216 	 * Convert the result to a 32-bit value by multiplying the high-order
18217 	 * 32-bits by the low-order 32-bits.
18218 	 */
18219 
18220 	hrt = gethrtime();
18221 	(void) drv_getparm(TIME, &wallclock);
18222 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
18223 	mutex_enter(&tcp_random_lock);
18224 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
18225 	    (result & 0xffffffff);
18226 
18227 	for (i = 1; i < DEG_3; i++)
18228 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
18229 		    + 12345;
18230 	tcp_random_fptr = &tcp_random_state[SEP_3];
18231 	tcp_random_rptr = &tcp_random_state[0];
18232 	mutex_exit(&tcp_random_lock);
18233 	for (i = 0; i < 10 * DEG_3; i++)
18234 		(void) tcp_random();
18235 }
18236 
18237 /*
18238  * tcp_random: Return a random number in the range [1 - (128K + 1)].
18239  * This range is selected to be approximately centered on TCP_ISS / 2,
18240  * and easy to compute. We get this value by generating a 32-bit random
18241  * number, selecting out the high-order 17 bits, and then adding one so
18242  * that we never return zero.
18243  */
18244 int
18245 tcp_random(void)
18246 {
18247 	int i;
18248 
18249 	mutex_enter(&tcp_random_lock);
18250 	*tcp_random_fptr += *tcp_random_rptr;
18251 
18252 	/*
18253 	 * The high-order bits are more random than the low-order bits,
18254 	 * so we select out the high-order 17 bits and add one so that
18255 	 * we never return zero.
18256 	 */
18257 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
18258 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
18259 		tcp_random_fptr = tcp_random_state;
18260 		++tcp_random_rptr;
18261 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
18262 		tcp_random_rptr = tcp_random_state;
18263 
18264 	mutex_exit(&tcp_random_lock);
18265 	return (i);
18266 }
18267 
18268 static int
18269 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
18270     int *t_errorp, int *sys_errorp)
18271 {
18272 	int error;
18273 	int is_absreq_failure;
18274 	t_scalar_t *opt_lenp;
18275 	t_scalar_t opt_offset;
18276 	int prim_type;
18277 	struct T_conn_req *tcreqp;
18278 	struct T_conn_res *tcresp;
18279 	cred_t *cr;
18280 
18281 	/*
18282 	 * All Solaris components should pass a db_credp
18283 	 * for this TPI message, hence we ASSERT.
18284 	 * But in case there is some other M_PROTO that looks
18285 	 * like a TPI message sent by some other kernel
18286 	 * component, we check and return an error.
18287 	 */
18288 	cr = msg_getcred(mp, NULL);
18289 	ASSERT(cr != NULL);
18290 	if (cr == NULL)
18291 		return (-1);
18292 
18293 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
18294 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
18295 	    prim_type == T_CONN_RES);
18296 
18297 	switch (prim_type) {
18298 	case T_CONN_REQ:
18299 		tcreqp = (struct T_conn_req *)mp->b_rptr;
18300 		opt_offset = tcreqp->OPT_offset;
18301 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
18302 		break;
18303 	case O_T_CONN_RES:
18304 	case T_CONN_RES:
18305 		tcresp = (struct T_conn_res *)mp->b_rptr;
18306 		opt_offset = tcresp->OPT_offset;
18307 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
18308 		break;
18309 	}
18310 
18311 	*t_errorp = 0;
18312 	*sys_errorp = 0;
18313 	*do_disconnectp = 0;
18314 
18315 	error = tpi_optcom_buf(tcp->tcp_connp->conn_wq, mp, opt_lenp,
18316 	    opt_offset, cr, &tcp_opt_obj,
18317 	    NULL, &is_absreq_failure);
18318 
18319 	switch (error) {
18320 	case  0:		/* no error */
18321 		ASSERT(is_absreq_failure == 0);
18322 		return (0);
18323 	case ENOPROTOOPT:
18324 		*t_errorp = TBADOPT;
18325 		break;
18326 	case EACCES:
18327 		*t_errorp = TACCES;
18328 		break;
18329 	default:
18330 		*t_errorp = TSYSERR; *sys_errorp = error;
18331 		break;
18332 	}
18333 	if (is_absreq_failure != 0) {
18334 		/*
18335 		 * The connection request should get the local ack
18336 		 * T_OK_ACK and then a T_DISCON_IND.
18337 		 */
18338 		*do_disconnectp = 1;
18339 	}
18340 	return (-1);
18341 }
18342 
18343 /*
18344  * Split this function out so that if the secret changes, I'm okay.
18345  *
18346  * Initialize the tcp_iss_cookie and tcp_iss_key.
18347  */
18348 
18349 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
18350 
18351 static void
18352 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
18353 {
18354 	struct {
18355 		int32_t current_time;
18356 		uint32_t randnum;
18357 		uint16_t pad;
18358 		uint8_t ether[6];
18359 		uint8_t passwd[PASSWD_SIZE];
18360 	} tcp_iss_cookie;
18361 	time_t t;
18362 
18363 	/*
18364 	 * Start with the current absolute time.
18365 	 */
18366 	(void) drv_getparm(TIME, &t);
18367 	tcp_iss_cookie.current_time = t;
18368 
18369 	/*
18370 	 * XXX - Need a more random number per RFC 1750, not this crap.
18371 	 * OTOH, if what follows is pretty random, then I'm in better shape.
18372 	 */
18373 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
18374 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
18375 
18376 	/*
18377 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
18378 	 * as a good template.
18379 	 */
18380 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
18381 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
18382 
18383 	/*
18384 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
18385 	 */
18386 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
18387 
18388 	/*
18389 	 * See 4010593 if this section becomes a problem again,
18390 	 * but the local ethernet address is useful here.
18391 	 */
18392 	(void) localetheraddr(NULL,
18393 	    (struct ether_addr *)&tcp_iss_cookie.ether);
18394 
18395 	/*
18396 	 * Hash 'em all together.  The MD5Final is called per-connection.
18397 	 */
18398 	mutex_enter(&tcps->tcps_iss_key_lock);
18399 	MD5Init(&tcps->tcps_iss_key);
18400 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
18401 	    sizeof (tcp_iss_cookie));
18402 	mutex_exit(&tcps->tcps_iss_key_lock);
18403 }
18404 
18405 /*
18406  * Set the RFC 1948 pass phrase
18407  */
18408 /* ARGSUSED */
18409 static int
18410 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
18411     cred_t *cr)
18412 {
18413 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18414 
18415 	/*
18416 	 * Basically, value contains a new pass phrase.  Pass it along!
18417 	 */
18418 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
18419 	return (0);
18420 }
18421 
18422 /* ARGSUSED */
18423 static int
18424 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
18425 {
18426 	bzero(buf, sizeof (tcp_sack_info_t));
18427 	return (0);
18428 }
18429 
18430 /*
18431  * Called by IP when IP is loaded into the kernel
18432  */
18433 void
18434 tcp_ddi_g_init(void)
18435 {
18436 	tcp_timercache = kmem_cache_create("tcp_timercache",
18437 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
18438 	    NULL, NULL, NULL, NULL, NULL, 0);
18439 
18440 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
18441 	    sizeof (tcp_sack_info_t), 0,
18442 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
18443 
18444 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
18445 
18446 	/* Initialize the random number generator */
18447 	tcp_random_init();
18448 
18449 	/* A single callback independently of how many netstacks we have */
18450 	ip_squeue_init(tcp_squeue_add);
18451 
18452 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
18453 
18454 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
18455 
18456 	/*
18457 	 * We want to be informed each time a stack is created or
18458 	 * destroyed in the kernel, so we can maintain the
18459 	 * set of tcp_stack_t's.
18460 	 */
18461 	netstack_register(NS_TCP, tcp_stack_init, NULL, tcp_stack_fini);
18462 }
18463 
18464 
18465 #define	INET_NAME	"ip"
18466 
18467 /*
18468  * Initialize the TCP stack instance.
18469  */
18470 static void *
18471 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
18472 {
18473 	tcp_stack_t	*tcps;
18474 	tcpparam_t	*pa;
18475 	int		i;
18476 	int		error = 0;
18477 	major_t		major;
18478 
18479 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
18480 	tcps->tcps_netstack = ns;
18481 
18482 	/* Initialize locks */
18483 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
18484 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
18485 
18486 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
18487 	tcps->tcps_g_epriv_ports[0] = 2049;
18488 	tcps->tcps_g_epriv_ports[1] = 4045;
18489 	tcps->tcps_min_anonpriv_port = 512;
18490 
18491 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
18492 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
18493 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
18494 	    TCP_FANOUT_SIZE, KM_SLEEP);
18495 
18496 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18497 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
18498 		    MUTEX_DEFAULT, NULL);
18499 	}
18500 
18501 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
18502 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
18503 		    MUTEX_DEFAULT, NULL);
18504 	}
18505 
18506 	/* TCP's IPsec code calls the packet dropper. */
18507 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
18508 
18509 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
18510 	tcps->tcps_params = pa;
18511 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18512 
18513 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
18514 	    A_CNT(lcl_tcp_param_arr), tcps);
18515 
18516 	/*
18517 	 * Note: To really walk the device tree you need the devinfo
18518 	 * pointer to your device which is only available after probe/attach.
18519 	 * The following is safe only because it uses ddi_root_node()
18520 	 */
18521 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
18522 	    tcp_opt_obj.odb_opt_arr_cnt);
18523 
18524 	/*
18525 	 * Initialize RFC 1948 secret values.  This will probably be reset once
18526 	 * by the boot scripts.
18527 	 *
18528 	 * Use NULL name, as the name is caught by the new lockstats.
18529 	 *
18530 	 * Initialize with some random, non-guessable string, like the global
18531 	 * T_INFO_ACK.
18532 	 */
18533 
18534 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
18535 	    sizeof (tcp_g_t_info_ack), tcps);
18536 
18537 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
18538 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
18539 
18540 	major = mod_name_to_major(INET_NAME);
18541 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
18542 	ASSERT(error == 0);
18543 	tcps->tcps_ixa_cleanup_mp = allocb_wait(0, BPRI_MED, STR_NOSIG, NULL);
18544 	ASSERT(tcps->tcps_ixa_cleanup_mp != NULL);
18545 	cv_init(&tcps->tcps_ixa_cleanup_cv, NULL, CV_DEFAULT, NULL);
18546 	mutex_init(&tcps->tcps_ixa_cleanup_lock, NULL, MUTEX_DEFAULT, NULL);
18547 
18548 	return (tcps);
18549 }
18550 
18551 /*
18552  * Called when the IP module is about to be unloaded.
18553  */
18554 void
18555 tcp_ddi_g_destroy(void)
18556 {
18557 	tcp_g_kstat_fini(tcp_g_kstat);
18558 	tcp_g_kstat = NULL;
18559 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
18560 
18561 	mutex_destroy(&tcp_random_lock);
18562 
18563 	kmem_cache_destroy(tcp_timercache);
18564 	kmem_cache_destroy(tcp_sack_info_cache);
18565 
18566 	netstack_unregister(NS_TCP);
18567 }
18568 
18569 /*
18570  * Free the TCP stack instance.
18571  */
18572 static void
18573 tcp_stack_fini(netstackid_t stackid, void *arg)
18574 {
18575 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
18576 	int i;
18577 
18578 	freeb(tcps->tcps_ixa_cleanup_mp);
18579 	tcps->tcps_ixa_cleanup_mp = NULL;
18580 	cv_destroy(&tcps->tcps_ixa_cleanup_cv);
18581 	mutex_destroy(&tcps->tcps_ixa_cleanup_lock);
18582 
18583 	nd_free(&tcps->tcps_g_nd);
18584 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18585 	tcps->tcps_params = NULL;
18586 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
18587 	tcps->tcps_wroff_xtra_param = NULL;
18588 
18589 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18590 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
18591 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
18592 	}
18593 
18594 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
18595 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
18596 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
18597 	}
18598 
18599 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
18600 	tcps->tcps_bind_fanout = NULL;
18601 
18602 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
18603 	tcps->tcps_acceptor_fanout = NULL;
18604 
18605 	mutex_destroy(&tcps->tcps_iss_key_lock);
18606 	mutex_destroy(&tcps->tcps_epriv_port_lock);
18607 
18608 	ip_drop_unregister(&tcps->tcps_dropper);
18609 
18610 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
18611 	tcps->tcps_kstat = NULL;
18612 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
18613 
18614 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
18615 	tcps->tcps_mibkp = NULL;
18616 
18617 	ldi_ident_release(tcps->tcps_ldi_ident);
18618 	kmem_free(tcps, sizeof (*tcps));
18619 }
18620 
18621 /*
18622  * Generate ISS, taking into account NDD changes may happen halfway through.
18623  * (If the iss is not zero, set it.)
18624  */
18625 
18626 static void
18627 tcp_iss_init(tcp_t *tcp)
18628 {
18629 	MD5_CTX context;
18630 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
18631 	uint32_t answer[4];
18632 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18633 	conn_t		*connp = tcp->tcp_connp;
18634 
18635 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
18636 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
18637 	switch (tcps->tcps_strong_iss) {
18638 	case 2:
18639 		mutex_enter(&tcps->tcps_iss_key_lock);
18640 		context = tcps->tcps_iss_key;
18641 		mutex_exit(&tcps->tcps_iss_key_lock);
18642 		arg.ports = connp->conn_ports;
18643 		arg.src = connp->conn_laddr_v6;
18644 		arg.dst = connp->conn_faddr_v6;
18645 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
18646 		MD5Final((uchar_t *)answer, &context);
18647 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
18648 		/*
18649 		 * Now that we've hashed into a unique per-connection sequence
18650 		 * space, add a random increment per strong_iss == 1.  So I
18651 		 * guess we'll have to...
18652 		 */
18653 		/* FALLTHRU */
18654 	case 1:
18655 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
18656 		break;
18657 	default:
18658 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
18659 		break;
18660 	}
18661 	tcp->tcp_valid_bits = TCP_ISS_VALID;
18662 	tcp->tcp_fss = tcp->tcp_iss - 1;
18663 	tcp->tcp_suna = tcp->tcp_iss;
18664 	tcp->tcp_snxt = tcp->tcp_iss + 1;
18665 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
18666 	tcp->tcp_csuna = tcp->tcp_snxt;
18667 }
18668 
18669 /*
18670  * Exported routine for extracting active tcp connection status.
18671  *
18672  * This is used by the Solaris Cluster Networking software to
18673  * gather a list of connections that need to be forwarded to
18674  * specific nodes in the cluster when configuration changes occur.
18675  *
18676  * The callback is invoked for each tcp_t structure from all netstacks,
18677  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
18678  * from the netstack with the specified stack_id. Returning
18679  * non-zero from the callback routine terminates the search.
18680  */
18681 int
18682 cl_tcp_walk_list(netstackid_t stack_id,
18683     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
18684 {
18685 	netstack_handle_t nh;
18686 	netstack_t *ns;
18687 	int ret = 0;
18688 
18689 	if (stack_id >= 0) {
18690 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
18691 			return (EINVAL);
18692 
18693 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
18694 		    ns->netstack_tcp);
18695 		netstack_rele(ns);
18696 		return (ret);
18697 	}
18698 
18699 	netstack_next_init(&nh);
18700 	while ((ns = netstack_next(&nh)) != NULL) {
18701 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
18702 		    ns->netstack_tcp);
18703 		netstack_rele(ns);
18704 	}
18705 	netstack_next_fini(&nh);
18706 	return (ret);
18707 }
18708 
18709 static int
18710 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
18711     tcp_stack_t *tcps)
18712 {
18713 	tcp_t *tcp;
18714 	cl_tcp_info_t	cl_tcpi;
18715 	connf_t	*connfp;
18716 	conn_t	*connp;
18717 	int	i;
18718 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18719 
18720 	ASSERT(callback != NULL);
18721 
18722 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
18723 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
18724 		connp = NULL;
18725 
18726 		while ((connp =
18727 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
18728 
18729 			tcp = connp->conn_tcp;
18730 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
18731 			cl_tcpi.cl_tcpi_ipversion = connp->conn_ipversion;
18732 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
18733 			cl_tcpi.cl_tcpi_lport = connp->conn_lport;
18734 			cl_tcpi.cl_tcpi_fport = connp->conn_fport;
18735 			cl_tcpi.cl_tcpi_laddr_v6 = connp->conn_laddr_v6;
18736 			cl_tcpi.cl_tcpi_faddr_v6 = connp->conn_faddr_v6;
18737 
18738 			/*
18739 			 * If the callback returns non-zero
18740 			 * we terminate the traversal.
18741 			 */
18742 			if ((*callback)(&cl_tcpi, arg) != 0) {
18743 				CONN_DEC_REF(tcp->tcp_connp);
18744 				return (1);
18745 			}
18746 		}
18747 	}
18748 
18749 	return (0);
18750 }
18751 
18752 /*
18753  * Macros used for accessing the different types of sockaddr
18754  * structures inside a tcp_ioc_abort_conn_t.
18755  */
18756 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
18757 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
18758 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
18759 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
18760 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
18761 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
18762 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
18763 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
18764 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
18765 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
18766 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
18767 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
18768 
18769 /*
18770  * Return the correct error code to mimic the behavior
18771  * of a connection reset.
18772  */
18773 #define	TCP_AC_GET_ERRCODE(state, err) {	\
18774 		switch ((state)) {		\
18775 		case TCPS_SYN_SENT:		\
18776 		case TCPS_SYN_RCVD:		\
18777 			(err) = ECONNREFUSED;	\
18778 			break;			\
18779 		case TCPS_ESTABLISHED:		\
18780 		case TCPS_FIN_WAIT_1:		\
18781 		case TCPS_FIN_WAIT_2:		\
18782 		case TCPS_CLOSE_WAIT:		\
18783 			(err) = ECONNRESET;	\
18784 			break;			\
18785 		case TCPS_CLOSING:		\
18786 		case TCPS_LAST_ACK:		\
18787 		case TCPS_TIME_WAIT:		\
18788 			(err) = 0;		\
18789 			break;			\
18790 		default:			\
18791 			(err) = ENXIO;		\
18792 		}				\
18793 	}
18794 
18795 /*
18796  * Check if a tcp structure matches the info in acp.
18797  */
18798 #define	TCP_AC_ADDR_MATCH(acp, connp, tcp)			\
18799 	(((acp)->ac_local.ss_family == AF_INET) ?		\
18800 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
18801 	TCP_AC_V4LOCAL((acp)) == (connp)->conn_laddr_v4) &&	\
18802 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
18803 	TCP_AC_V4REMOTE((acp)) == (connp)->conn_faddr_v4) &&	\
18804 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
18805 	TCP_AC_V4LPORT((acp)) == (connp)->conn_lport) &&	\
18806 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
18807 	TCP_AC_V4RPORT((acp)) == (connp)->conn_fport) &&	\
18808 	(acp)->ac_start <= (tcp)->tcp_state &&			\
18809 	(acp)->ac_end >= (tcp)->tcp_state) :			\
18810 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
18811 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
18812 	&(connp)->conn_laddr_v6)) &&				\
18813 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
18814 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
18815 	&(connp)->conn_faddr_v6)) &&				\
18816 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
18817 	TCP_AC_V6LPORT((acp)) == (connp)->conn_lport) &&	\
18818 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
18819 	TCP_AC_V6RPORT((acp)) == (connp)->conn_fport) &&	\
18820 	(acp)->ac_start <= (tcp)->tcp_state &&			\
18821 	(acp)->ac_end >= (tcp)->tcp_state))
18822 
18823 #define	TCP_AC_MATCH(acp, connp, tcp)				\
18824 	(((acp)->ac_zoneid == ALL_ZONES ||			\
18825 	(acp)->ac_zoneid == (connp)->conn_zoneid) ?		\
18826 	TCP_AC_ADDR_MATCH(acp, connp, tcp) : 0)
18827 
18828 /*
18829  * Build a message containing a tcp_ioc_abort_conn_t structure
18830  * which is filled in with information from acp and tp.
18831  */
18832 static mblk_t *
18833 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
18834 {
18835 	mblk_t *mp;
18836 	tcp_ioc_abort_conn_t *tacp;
18837 
18838 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
18839 	if (mp == NULL)
18840 		return (NULL);
18841 
18842 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
18843 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
18844 	    sizeof (uint32_t));
18845 
18846 	tacp->ac_start = acp->ac_start;
18847 	tacp->ac_end = acp->ac_end;
18848 	tacp->ac_zoneid = acp->ac_zoneid;
18849 
18850 	if (acp->ac_local.ss_family == AF_INET) {
18851 		tacp->ac_local.ss_family = AF_INET;
18852 		tacp->ac_remote.ss_family = AF_INET;
18853 		TCP_AC_V4LOCAL(tacp) = tp->tcp_connp->conn_laddr_v4;
18854 		TCP_AC_V4REMOTE(tacp) = tp->tcp_connp->conn_faddr_v4;
18855 		TCP_AC_V4LPORT(tacp) = tp->tcp_connp->conn_lport;
18856 		TCP_AC_V4RPORT(tacp) = tp->tcp_connp->conn_fport;
18857 	} else {
18858 		tacp->ac_local.ss_family = AF_INET6;
18859 		tacp->ac_remote.ss_family = AF_INET6;
18860 		TCP_AC_V6LOCAL(tacp) = tp->tcp_connp->conn_laddr_v6;
18861 		TCP_AC_V6REMOTE(tacp) = tp->tcp_connp->conn_faddr_v6;
18862 		TCP_AC_V6LPORT(tacp) = tp->tcp_connp->conn_lport;
18863 		TCP_AC_V6RPORT(tacp) = tp->tcp_connp->conn_fport;
18864 	}
18865 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
18866 	return (mp);
18867 }
18868 
18869 /*
18870  * Print a tcp_ioc_abort_conn_t structure.
18871  */
18872 static void
18873 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
18874 {
18875 	char lbuf[128];
18876 	char rbuf[128];
18877 	sa_family_t af;
18878 	in_port_t lport, rport;
18879 	ushort_t logflags;
18880 
18881 	af = acp->ac_local.ss_family;
18882 
18883 	if (af == AF_INET) {
18884 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
18885 		    lbuf, 128);
18886 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
18887 		    rbuf, 128);
18888 		lport = ntohs(TCP_AC_V4LPORT(acp));
18889 		rport = ntohs(TCP_AC_V4RPORT(acp));
18890 	} else {
18891 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
18892 		    lbuf, 128);
18893 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
18894 		    rbuf, 128);
18895 		lport = ntohs(TCP_AC_V6LPORT(acp));
18896 		rport = ntohs(TCP_AC_V6RPORT(acp));
18897 	}
18898 
18899 	logflags = SL_TRACE | SL_NOTE;
18900 	/*
18901 	 * Don't print this message to the console if the operation was done
18902 	 * to a non-global zone.
18903 	 */
18904 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
18905 		logflags |= SL_CONSOLE;
18906 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
18907 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
18908 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
18909 	    acp->ac_start, acp->ac_end);
18910 }
18911 
18912 /*
18913  * Called using SQ_FILL when a message built using
18914  * tcp_ioctl_abort_build_msg is put into a queue.
18915  * Note that when we get here there is no wildcard in acp any more.
18916  */
18917 /* ARGSUSED2 */
18918 static void
18919 tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
18920     ip_recv_attr_t *dummy)
18921 {
18922 	conn_t			*connp = (conn_t *)arg;
18923 	tcp_t			*tcp = connp->conn_tcp;
18924 	tcp_ioc_abort_conn_t	*acp;
18925 
18926 	/*
18927 	 * Don't accept any input on a closed tcp as this TCP logically does
18928 	 * not exist on the system. Don't proceed further with this TCP.
18929 	 * For eg. this packet could trigger another close of this tcp
18930 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
18931 	 * tcp_clean_death / tcp_closei_local must be called at most once
18932 	 * on a TCP.
18933 	 */
18934 	if (tcp->tcp_state == TCPS_CLOSED ||
18935 	    tcp->tcp_state == TCPS_BOUND) {
18936 		freemsg(mp);
18937 		return;
18938 	}
18939 
18940 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
18941 	if (tcp->tcp_state <= acp->ac_end) {
18942 		/*
18943 		 * If we get here, we are already on the correct
18944 		 * squeue. This ioctl follows the following path
18945 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
18946 		 * ->tcp_ioctl_abort->squeue_enter (if on a
18947 		 * different squeue)
18948 		 */
18949 		int errcode;
18950 
18951 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
18952 		(void) tcp_clean_death(tcp, errcode, 26);
18953 	}
18954 	freemsg(mp);
18955 }
18956 
18957 /*
18958  * Abort all matching connections on a hash chain.
18959  */
18960 static int
18961 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
18962     boolean_t exact, tcp_stack_t *tcps)
18963 {
18964 	int nmatch, err = 0;
18965 	tcp_t *tcp;
18966 	MBLKP mp, last, listhead = NULL;
18967 	conn_t	*tconnp;
18968 	connf_t	*connfp;
18969 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
18970 
18971 	connfp = &ipst->ips_ipcl_conn_fanout[index];
18972 
18973 startover:
18974 	nmatch = 0;
18975 
18976 	mutex_enter(&connfp->connf_lock);
18977 	for (tconnp = connfp->connf_head; tconnp != NULL;
18978 	    tconnp = tconnp->conn_next) {
18979 		tcp = tconnp->conn_tcp;
18980 		/*
18981 		 * We are missing a check on sin6_scope_id for linklocals here,
18982 		 * but current usage is just for aborting based on zoneid
18983 		 * for shared-IP zones.
18984 		 */
18985 		if (TCP_AC_MATCH(acp, tconnp, tcp)) {
18986 			CONN_INC_REF(tconnp);
18987 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
18988 			if (mp == NULL) {
18989 				err = ENOMEM;
18990 				CONN_DEC_REF(tconnp);
18991 				break;
18992 			}
18993 			mp->b_prev = (mblk_t *)tcp;
18994 
18995 			if (listhead == NULL) {
18996 				listhead = mp;
18997 				last = mp;
18998 			} else {
18999 				last->b_next = mp;
19000 				last = mp;
19001 			}
19002 			nmatch++;
19003 			if (exact)
19004 				break;
19005 		}
19006 
19007 		/* Avoid holding lock for too long. */
19008 		if (nmatch >= 500)
19009 			break;
19010 	}
19011 	mutex_exit(&connfp->connf_lock);
19012 
19013 	/* Pass mp into the correct tcp */
19014 	while ((mp = listhead) != NULL) {
19015 		listhead = listhead->b_next;
19016 		tcp = (tcp_t *)mp->b_prev;
19017 		mp->b_next = mp->b_prev = NULL;
19018 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp,
19019 		    tcp_ioctl_abort_handler, tcp->tcp_connp, NULL,
19020 		    SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
19021 	}
19022 
19023 	*count += nmatch;
19024 	if (nmatch >= 500 && err == 0)
19025 		goto startover;
19026 	return (err);
19027 }
19028 
19029 /*
19030  * Abort all connections that matches the attributes specified in acp.
19031  */
19032 static int
19033 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
19034 {
19035 	sa_family_t af;
19036 	uint32_t  ports;
19037 	uint16_t *pports;
19038 	int err = 0, count = 0;
19039 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
19040 	int index = -1;
19041 	ushort_t logflags;
19042 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19043 
19044 	af = acp->ac_local.ss_family;
19045 
19046 	if (af == AF_INET) {
19047 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
19048 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
19049 			pports = (uint16_t *)&ports;
19050 			pports[1] = TCP_AC_V4LPORT(acp);
19051 			pports[0] = TCP_AC_V4RPORT(acp);
19052 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
19053 		}
19054 	} else {
19055 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
19056 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
19057 			pports = (uint16_t *)&ports;
19058 			pports[1] = TCP_AC_V6LPORT(acp);
19059 			pports[0] = TCP_AC_V6RPORT(acp);
19060 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
19061 		}
19062 	}
19063 
19064 	/*
19065 	 * For cases where remote addr, local port, and remote port are non-
19066 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
19067 	 */
19068 	if (index != -1) {
19069 		err = tcp_ioctl_abort_bucket(acp, index,
19070 		    &count, exact, tcps);
19071 	} else {
19072 		/*
19073 		 * loop through all entries for wildcard case
19074 		 */
19075 		for (index = 0;
19076 		    index < ipst->ips_ipcl_conn_fanout_size;
19077 		    index++) {
19078 			err = tcp_ioctl_abort_bucket(acp, index,
19079 			    &count, exact, tcps);
19080 			if (err != 0)
19081 				break;
19082 		}
19083 	}
19084 
19085 	logflags = SL_TRACE | SL_NOTE;
19086 	/*
19087 	 * Don't print this message to the console if the operation was done
19088 	 * to a non-global zone.
19089 	 */
19090 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19091 		logflags |= SL_CONSOLE;
19092 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
19093 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
19094 	if (err == 0 && count == 0)
19095 		err = ENOENT;
19096 	return (err);
19097 }
19098 
19099 /*
19100  * Process the TCP_IOC_ABORT_CONN ioctl request.
19101  */
19102 static void
19103 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
19104 {
19105 	int	err;
19106 	IOCP    iocp;
19107 	MBLKP   mp1;
19108 	sa_family_t laf, raf;
19109 	tcp_ioc_abort_conn_t *acp;
19110 	zone_t		*zptr;
19111 	conn_t		*connp = Q_TO_CONN(q);
19112 	zoneid_t	zoneid = connp->conn_zoneid;
19113 	tcp_t		*tcp = connp->conn_tcp;
19114 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19115 
19116 	iocp = (IOCP)mp->b_rptr;
19117 
19118 	if ((mp1 = mp->b_cont) == NULL ||
19119 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
19120 		err = EINVAL;
19121 		goto out;
19122 	}
19123 
19124 	/* check permissions */
19125 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19126 		err = EPERM;
19127 		goto out;
19128 	}
19129 
19130 	if (mp1->b_cont != NULL) {
19131 		freemsg(mp1->b_cont);
19132 		mp1->b_cont = NULL;
19133 	}
19134 
19135 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
19136 	laf = acp->ac_local.ss_family;
19137 	raf = acp->ac_remote.ss_family;
19138 
19139 	/* check that a zone with the supplied zoneid exists */
19140 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
19141 		zptr = zone_find_by_id(zoneid);
19142 		if (zptr != NULL) {
19143 			zone_rele(zptr);
19144 		} else {
19145 			err = EINVAL;
19146 			goto out;
19147 		}
19148 	}
19149 
19150 	/*
19151 	 * For exclusive stacks we set the zoneid to zero
19152 	 * to make TCP operate as if in the global zone.
19153 	 */
19154 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
19155 		acp->ac_zoneid = GLOBAL_ZONEID;
19156 
19157 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
19158 	    acp->ac_start > acp->ac_end || laf != raf ||
19159 	    (laf != AF_INET && laf != AF_INET6)) {
19160 		err = EINVAL;
19161 		goto out;
19162 	}
19163 
19164 	tcp_ioctl_abort_dump(acp);
19165 	err = tcp_ioctl_abort(acp, tcps);
19166 
19167 out:
19168 	if (mp1 != NULL) {
19169 		freemsg(mp1);
19170 		mp->b_cont = NULL;
19171 	}
19172 
19173 	if (err != 0)
19174 		miocnak(q, mp, 0, err);
19175 	else
19176 		miocack(q, mp, 0, 0);
19177 }
19178 
19179 /*
19180  * tcp_time_wait_processing() handles processing of incoming packets when
19181  * the tcp is in the TIME_WAIT state.
19182  * A TIME_WAIT tcp that has an associated open TCP stream is never put
19183  * on the time wait list.
19184  */
19185 void
19186 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
19187     uint32_t seg_ack, int seg_len, tcpha_t *tcpha, ip_recv_attr_t *ira)
19188 {
19189 	int32_t		bytes_acked;
19190 	int32_t		gap;
19191 	int32_t		rgap;
19192 	tcp_opt_t	tcpopt;
19193 	uint_t		flags;
19194 	uint32_t	new_swnd = 0;
19195 	conn_t		*nconnp;
19196 	conn_t		*connp = tcp->tcp_connp;
19197 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19198 
19199 	BUMP_LOCAL(tcp->tcp_ibsegs);
19200 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
19201 
19202 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
19203 	new_swnd = ntohs(tcpha->tha_win) <<
19204 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
19205 	if (tcp->tcp_snd_ts_ok) {
19206 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
19207 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19208 			    tcp->tcp_rnxt, TH_ACK);
19209 			goto done;
19210 		}
19211 	}
19212 	gap = seg_seq - tcp->tcp_rnxt;
19213 	rgap = tcp->tcp_rwnd - (gap + seg_len);
19214 	if (gap < 0) {
19215 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
19216 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
19217 		    (seg_len > -gap ? -gap : seg_len));
19218 		seg_len += gap;
19219 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
19220 			if (flags & TH_RST) {
19221 				goto done;
19222 			}
19223 			if ((flags & TH_FIN) && seg_len == -1) {
19224 				/*
19225 				 * When TCP receives a duplicate FIN in
19226 				 * TIME_WAIT state, restart the 2 MSL timer.
19227 				 * See page 73 in RFC 793. Make sure this TCP
19228 				 * is already on the TIME_WAIT list. If not,
19229 				 * just restart the timer.
19230 				 */
19231 				if (TCP_IS_DETACHED(tcp)) {
19232 					if (tcp_time_wait_remove(tcp, NULL) ==
19233 					    B_TRUE) {
19234 						tcp_time_wait_append(tcp);
19235 						TCP_DBGSTAT(tcps,
19236 						    tcp_rput_time_wait);
19237 					}
19238 				} else {
19239 					ASSERT(tcp != NULL);
19240 					TCP_TIMER_RESTART(tcp,
19241 					    tcps->tcps_time_wait_interval);
19242 				}
19243 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19244 				    tcp->tcp_rnxt, TH_ACK);
19245 				goto done;
19246 			}
19247 			flags |=  TH_ACK_NEEDED;
19248 			seg_len = 0;
19249 			goto process_ack;
19250 		}
19251 
19252 		/* Fix seg_seq, and chew the gap off the front. */
19253 		seg_seq = tcp->tcp_rnxt;
19254 	}
19255 
19256 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
19257 		/*
19258 		 * Make sure that when we accept the connection, pick
19259 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
19260 		 * old connection.
19261 		 *
19262 		 * The next ISS generated is equal to tcp_iss_incr_extra
19263 		 * + ISS_INCR/2 + other components depending on the
19264 		 * value of tcp_strong_iss.  We pre-calculate the new
19265 		 * ISS here and compare with tcp_snxt to determine if
19266 		 * we need to make adjustment to tcp_iss_incr_extra.
19267 		 *
19268 		 * The above calculation is ugly and is a
19269 		 * waste of CPU cycles...
19270 		 */
19271 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
19272 		int32_t adj;
19273 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19274 
19275 		switch (tcps->tcps_strong_iss) {
19276 		case 2: {
19277 			/* Add time and MD5 components. */
19278 			uint32_t answer[4];
19279 			struct {
19280 				uint32_t ports;
19281 				in6_addr_t src;
19282 				in6_addr_t dst;
19283 			} arg;
19284 			MD5_CTX context;
19285 
19286 			mutex_enter(&tcps->tcps_iss_key_lock);
19287 			context = tcps->tcps_iss_key;
19288 			mutex_exit(&tcps->tcps_iss_key_lock);
19289 			arg.ports = connp->conn_ports;
19290 			/* We use MAPPED addresses in tcp_iss_init */
19291 			arg.src = connp->conn_laddr_v6;
19292 			arg.dst = connp->conn_faddr_v6;
19293 			MD5Update(&context, (uchar_t *)&arg,
19294 			    sizeof (arg));
19295 			MD5Final((uchar_t *)answer, &context);
19296 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
19297 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
19298 			break;
19299 		}
19300 		case 1:
19301 			/* Add time component and min random (i.e. 1). */
19302 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
19303 			break;
19304 		default:
19305 			/* Add only time component. */
19306 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19307 			break;
19308 		}
19309 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
19310 			/*
19311 			 * New ISS not guaranteed to be ISS_INCR/2
19312 			 * ahead of the current tcp_snxt, so add the
19313 			 * difference to tcp_iss_incr_extra.
19314 			 */
19315 			tcps->tcps_iss_incr_extra += adj;
19316 		}
19317 		/*
19318 		 * If tcp_clean_death() can not perform the task now,
19319 		 * drop the SYN packet and let the other side re-xmit.
19320 		 * Otherwise pass the SYN packet back in, since the
19321 		 * old tcp state has been cleaned up or freed.
19322 		 */
19323 		if (tcp_clean_death(tcp, 0, 27) == -1)
19324 			goto done;
19325 		nconnp = ipcl_classify(mp, ira, ipst);
19326 		if (nconnp != NULL) {
19327 			TCP_STAT(tcps, tcp_time_wait_syn_success);
19328 			/* Drops ref on nconnp */
19329 			tcp_reinput(nconnp, mp, ira, ipst);
19330 			return;
19331 		}
19332 		goto done;
19333 	}
19334 
19335 	/*
19336 	 * rgap is the amount of stuff received out of window.  A negative
19337 	 * value is the amount out of window.
19338 	 */
19339 	if (rgap < 0) {
19340 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
19341 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
19342 		/* Fix seg_len and make sure there is something left. */
19343 		seg_len += rgap;
19344 		if (seg_len <= 0) {
19345 			if (flags & TH_RST) {
19346 				goto done;
19347 			}
19348 			flags |=  TH_ACK_NEEDED;
19349 			seg_len = 0;
19350 			goto process_ack;
19351 		}
19352 	}
19353 	/*
19354 	 * Check whether we can update tcp_ts_recent.  This test is
19355 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
19356 	 * Extensions for High Performance: An Update", Internet Draft.
19357 	 */
19358 	if (tcp->tcp_snd_ts_ok &&
19359 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
19360 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
19361 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
19362 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
19363 	}
19364 
19365 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
19366 		/* Always ack out of order packets */
19367 		flags |= TH_ACK_NEEDED;
19368 		seg_len = 0;
19369 	} else if (seg_len > 0) {
19370 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
19371 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
19372 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
19373 	}
19374 	if (flags & TH_RST) {
19375 		(void) tcp_clean_death(tcp, 0, 28);
19376 		goto done;
19377 	}
19378 	if (flags & TH_SYN) {
19379 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
19380 		    TH_RST|TH_ACK);
19381 		/*
19382 		 * Do not delete the TCP structure if it is in
19383 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
19384 		 */
19385 		goto done;
19386 	}
19387 process_ack:
19388 	if (flags & TH_ACK) {
19389 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
19390 		if (bytes_acked <= 0) {
19391 			if (bytes_acked == 0 && seg_len == 0 &&
19392 			    new_swnd == tcp->tcp_swnd)
19393 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
19394 		} else {
19395 			/* Acks something not sent */
19396 			flags |= TH_ACK_NEEDED;
19397 		}
19398 	}
19399 	if (flags & TH_ACK_NEEDED) {
19400 		/*
19401 		 * Time to send an ack for some reason.
19402 		 */
19403 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19404 		    tcp->tcp_rnxt, TH_ACK);
19405 	}
19406 done:
19407 	freemsg(mp);
19408 }
19409 
19410 /*
19411  * TCP Timers Implementation.
19412  */
19413 timeout_id_t
19414 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
19415 {
19416 	mblk_t *mp;
19417 	tcp_timer_t *tcpt;
19418 	tcp_t *tcp = connp->conn_tcp;
19419 
19420 	ASSERT(connp->conn_sqp != NULL);
19421 
19422 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
19423 
19424 	if (tcp->tcp_timercache == NULL) {
19425 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
19426 	} else {
19427 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
19428 		mp = tcp->tcp_timercache;
19429 		tcp->tcp_timercache = mp->b_next;
19430 		mp->b_next = NULL;
19431 		ASSERT(mp->b_wptr == NULL);
19432 	}
19433 
19434 	CONN_INC_REF(connp);
19435 	tcpt = (tcp_timer_t *)mp->b_rptr;
19436 	tcpt->connp = connp;
19437 	tcpt->tcpt_proc = f;
19438 	/*
19439 	 * TCP timers are normal timeouts. Plus, they do not require more than
19440 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
19441 	 * rounding up the expiration to the next resolution boundary, we can
19442 	 * batch timers in the callout subsystem to make TCP timers more
19443 	 * efficient. The roundup also protects short timers from expiring too
19444 	 * early before they have a chance to be cancelled.
19445 	 */
19446 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
19447 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
19448 
19449 	return ((timeout_id_t)mp);
19450 }
19451 
19452 static void
19453 tcp_timer_callback(void *arg)
19454 {
19455 	mblk_t *mp = (mblk_t *)arg;
19456 	tcp_timer_t *tcpt;
19457 	conn_t	*connp;
19458 
19459 	tcpt = (tcp_timer_t *)mp->b_rptr;
19460 	connp = tcpt->connp;
19461 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
19462 	    NULL, SQ_FILL, SQTAG_TCP_TIMER);
19463 }
19464 
19465 /* ARGSUSED */
19466 static void
19467 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
19468 {
19469 	tcp_timer_t *tcpt;
19470 	conn_t *connp = (conn_t *)arg;
19471 	tcp_t *tcp = connp->conn_tcp;
19472 
19473 	tcpt = (tcp_timer_t *)mp->b_rptr;
19474 	ASSERT(connp == tcpt->connp);
19475 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
19476 
19477 	/*
19478 	 * If the TCP has reached the closed state, don't proceed any
19479 	 * further. This TCP logically does not exist on the system.
19480 	 * tcpt_proc could for example access queues, that have already
19481 	 * been qprocoff'ed off.
19482 	 */
19483 	if (tcp->tcp_state != TCPS_CLOSED) {
19484 		(*tcpt->tcpt_proc)(connp);
19485 	} else {
19486 		tcp->tcp_timer_tid = 0;
19487 	}
19488 	tcp_timer_free(connp->conn_tcp, mp);
19489 }
19490 
19491 /*
19492  * There is potential race with untimeout and the handler firing at the same
19493  * time. The mblock may be freed by the handler while we are trying to use
19494  * it. But since both should execute on the same squeue, this race should not
19495  * occur.
19496  */
19497 clock_t
19498 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
19499 {
19500 	mblk_t	*mp = (mblk_t *)id;
19501 	tcp_timer_t *tcpt;
19502 	clock_t delta;
19503 
19504 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
19505 
19506 	if (mp == NULL)
19507 		return (-1);
19508 
19509 	tcpt = (tcp_timer_t *)mp->b_rptr;
19510 	ASSERT(tcpt->connp == connp);
19511 
19512 	delta = untimeout_default(tcpt->tcpt_tid, 0);
19513 
19514 	if (delta >= 0) {
19515 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
19516 		tcp_timer_free(connp->conn_tcp, mp);
19517 		CONN_DEC_REF(connp);
19518 	}
19519 
19520 	return (delta);
19521 }
19522 
19523 /*
19524  * Allocate space for the timer event. The allocation looks like mblk, but it is
19525  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
19526  *
19527  * Dealing with failures: If we can't allocate from the timer cache we try
19528  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
19529  * points to b_rptr.
19530  * If we can't allocate anything using allocb_tryhard(), we perform a last
19531  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
19532  * save the actual allocation size in b_datap.
19533  */
19534 mblk_t *
19535 tcp_timermp_alloc(int kmflags)
19536 {
19537 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
19538 	    kmflags & ~KM_PANIC);
19539 
19540 	if (mp != NULL) {
19541 		mp->b_next = mp->b_prev = NULL;
19542 		mp->b_rptr = (uchar_t *)(&mp[1]);
19543 		mp->b_wptr = NULL;
19544 		mp->b_datap = NULL;
19545 		mp->b_queue = NULL;
19546 		mp->b_cont = NULL;
19547 	} else if (kmflags & KM_PANIC) {
19548 		/*
19549 		 * Failed to allocate memory for the timer. Try allocating from
19550 		 * dblock caches.
19551 		 */
19552 		/* ipclassifier calls this from a constructor - hence no tcps */
19553 		TCP_G_STAT(tcp_timermp_allocfail);
19554 		mp = allocb_tryhard(sizeof (tcp_timer_t));
19555 		if (mp == NULL) {
19556 			size_t size = 0;
19557 			/*
19558 			 * Memory is really low. Try tryhard allocation.
19559 			 *
19560 			 * ipclassifier calls this from a constructor -
19561 			 * hence no tcps
19562 			 */
19563 			TCP_G_STAT(tcp_timermp_allocdblfail);
19564 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
19565 			    sizeof (tcp_timer_t), &size, kmflags);
19566 			mp->b_rptr = (uchar_t *)(&mp[1]);
19567 			mp->b_next = mp->b_prev = NULL;
19568 			mp->b_wptr = (uchar_t *)-1;
19569 			mp->b_datap = (dblk_t *)size;
19570 			mp->b_queue = NULL;
19571 			mp->b_cont = NULL;
19572 		}
19573 		ASSERT(mp->b_wptr != NULL);
19574 	}
19575 	/* ipclassifier calls this from a constructor - hence no tcps */
19576 	TCP_G_DBGSTAT(tcp_timermp_alloced);
19577 
19578 	return (mp);
19579 }
19580 
19581 /*
19582  * Free per-tcp timer cache.
19583  * It can only contain entries from tcp_timercache.
19584  */
19585 void
19586 tcp_timermp_free(tcp_t *tcp)
19587 {
19588 	mblk_t *mp;
19589 
19590 	while ((mp = tcp->tcp_timercache) != NULL) {
19591 		ASSERT(mp->b_wptr == NULL);
19592 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
19593 		kmem_cache_free(tcp_timercache, mp);
19594 	}
19595 }
19596 
19597 /*
19598  * Free timer event. Put it on the per-tcp timer cache if there is not too many
19599  * events there already (currently at most two events are cached).
19600  * If the event is not allocated from the timer cache, free it right away.
19601  */
19602 static void
19603 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
19604 {
19605 	mblk_t *mp1 = tcp->tcp_timercache;
19606 
19607 	if (mp->b_wptr != NULL) {
19608 		/*
19609 		 * This allocation is not from a timer cache, free it right
19610 		 * away.
19611 		 */
19612 		if (mp->b_wptr != (uchar_t *)-1)
19613 			freeb(mp);
19614 		else
19615 			kmem_free(mp, (size_t)mp->b_datap);
19616 	} else if (mp1 == NULL || mp1->b_next == NULL) {
19617 		/* Cache this timer block for future allocations */
19618 		mp->b_rptr = (uchar_t *)(&mp[1]);
19619 		mp->b_next = mp1;
19620 		tcp->tcp_timercache = mp;
19621 	} else {
19622 		kmem_cache_free(tcp_timercache, mp);
19623 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
19624 	}
19625 }
19626 
19627 /*
19628  * End of TCP Timers implementation.
19629  */
19630 
19631 /*
19632  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
19633  * on the specified backing STREAMS q. Note, the caller may make the
19634  * decision to call based on the tcp_t.tcp_flow_stopped value which
19635  * when check outside the q's lock is only an advisory check ...
19636  */
19637 void
19638 tcp_setqfull(tcp_t *tcp)
19639 {
19640 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19641 	conn_t	*connp = tcp->tcp_connp;
19642 
19643 	if (tcp->tcp_closed)
19644 		return;
19645 
19646 	conn_setqfull(connp, &tcp->tcp_flow_stopped);
19647 	if (tcp->tcp_flow_stopped)
19648 		TCP_STAT(tcps, tcp_flwctl_on);
19649 }
19650 
19651 void
19652 tcp_clrqfull(tcp_t *tcp)
19653 {
19654 	conn_t  *connp = tcp->tcp_connp;
19655 
19656 	if (tcp->tcp_closed)
19657 		return;
19658 	conn_clrqfull(connp, &tcp->tcp_flow_stopped);
19659 }
19660 
19661 /*
19662  * kstats related to squeues i.e. not per IP instance
19663  */
19664 static void *
19665 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
19666 {
19667 	kstat_t *ksp;
19668 
19669 	tcp_g_stat_t template = {
19670 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
19671 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
19672 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
19673 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
19674 	};
19675 
19676 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
19677 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
19678 	    KSTAT_FLAG_VIRTUAL);
19679 
19680 	if (ksp == NULL)
19681 		return (NULL);
19682 
19683 	bcopy(&template, tcp_g_statp, sizeof (template));
19684 	ksp->ks_data = (void *)tcp_g_statp;
19685 
19686 	kstat_install(ksp);
19687 	return (ksp);
19688 }
19689 
19690 static void
19691 tcp_g_kstat_fini(kstat_t *ksp)
19692 {
19693 	if (ksp != NULL) {
19694 		kstat_delete(ksp);
19695 	}
19696 }
19697 
19698 
19699 static void *
19700 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
19701 {
19702 	kstat_t *ksp;
19703 
19704 	tcp_stat_t template = {
19705 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
19706 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
19707 		{ "tcp_time_wait_syn_success",	KSTAT_DATA_UINT64 },
19708 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
19709 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
19710 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
19711 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
19712 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
19713 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
19714 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
19715 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
19716 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
19717 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
19718 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
19719 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
19720 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
19721 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
19722 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
19723 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
19724 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
19725 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
19726 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
19727 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
19728 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
19729 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
19730 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
19731 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
19732 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
19733 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
19734 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
19735 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
19736 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
19737 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
19738 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
19739 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
19740 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
19741 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
19742 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
19743 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
19744 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
19745 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
19746 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
19747 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
19748 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
19749 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
19750 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
19751 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
19752 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
19753 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
19754 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
19755 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
19756 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
19757 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
19758 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
19759 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
19760 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
19761 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
19762 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
19763 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
19764 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
19765 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
19766 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
19767 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
19768 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
19769 	};
19770 
19771 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
19772 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
19773 	    KSTAT_FLAG_VIRTUAL, stackid);
19774 
19775 	if (ksp == NULL)
19776 		return (NULL);
19777 
19778 	bcopy(&template, tcps_statisticsp, sizeof (template));
19779 	ksp->ks_data = (void *)tcps_statisticsp;
19780 	ksp->ks_private = (void *)(uintptr_t)stackid;
19781 
19782 	kstat_install(ksp);
19783 	return (ksp);
19784 }
19785 
19786 static void
19787 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
19788 {
19789 	if (ksp != NULL) {
19790 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
19791 		kstat_delete_netstack(ksp, stackid);
19792 	}
19793 }
19794 
19795 /*
19796  * TCP Kstats implementation
19797  */
19798 static void *
19799 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
19800 {
19801 	kstat_t	*ksp;
19802 
19803 	tcp_named_kstat_t template = {
19804 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
19805 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
19806 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
19807 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
19808 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
19809 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
19810 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
19811 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
19812 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
19813 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
19814 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
19815 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
19816 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
19817 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
19818 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
19819 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
19820 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
19821 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
19822 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
19823 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
19824 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
19825 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
19826 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
19827 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
19828 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
19829 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
19830 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
19831 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
19832 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
19833 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
19834 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
19835 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
19836 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
19837 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
19838 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
19839 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
19840 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
19841 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
19842 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
19843 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
19844 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
19845 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
19846 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
19847 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
19848 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
19849 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
19850 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
19851 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
19852 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
19853 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
19854 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
19855 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
19856 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
19857 	};
19858 
19859 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
19860 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
19861 
19862 	if (ksp == NULL)
19863 		return (NULL);
19864 
19865 	template.rtoAlgorithm.value.ui32 = 4;
19866 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
19867 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
19868 	template.maxConn.value.i32 = -1;
19869 
19870 	bcopy(&template, ksp->ks_data, sizeof (template));
19871 	ksp->ks_update = tcp_kstat_update;
19872 	ksp->ks_private = (void *)(uintptr_t)stackid;
19873 
19874 	kstat_install(ksp);
19875 	return (ksp);
19876 }
19877 
19878 static void
19879 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
19880 {
19881 	if (ksp != NULL) {
19882 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
19883 		kstat_delete_netstack(ksp, stackid);
19884 	}
19885 }
19886 
19887 static int
19888 tcp_kstat_update(kstat_t *kp, int rw)
19889 {
19890 	tcp_named_kstat_t *tcpkp;
19891 	tcp_t		*tcp;
19892 	connf_t		*connfp;
19893 	conn_t		*connp;
19894 	int 		i;
19895 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
19896 	netstack_t	*ns;
19897 	tcp_stack_t	*tcps;
19898 	ip_stack_t	*ipst;
19899 
19900 	if ((kp == NULL) || (kp->ks_data == NULL))
19901 		return (EIO);
19902 
19903 	if (rw == KSTAT_WRITE)
19904 		return (EACCES);
19905 
19906 	ns = netstack_find_by_stackid(stackid);
19907 	if (ns == NULL)
19908 		return (-1);
19909 	tcps = ns->netstack_tcp;
19910 	if (tcps == NULL) {
19911 		netstack_rele(ns);
19912 		return (-1);
19913 	}
19914 
19915 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
19916 
19917 	tcpkp->currEstab.value.ui32 = 0;
19918 
19919 	ipst = ns->netstack_ip;
19920 
19921 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
19922 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
19923 		connp = NULL;
19924 		while ((connp =
19925 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
19926 			tcp = connp->conn_tcp;
19927 			switch (tcp_snmp_state(tcp)) {
19928 			case MIB2_TCP_established:
19929 			case MIB2_TCP_closeWait:
19930 				tcpkp->currEstab.value.ui32++;
19931 				break;
19932 			}
19933 		}
19934 	}
19935 
19936 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
19937 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
19938 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
19939 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
19940 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
19941 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
19942 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
19943 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
19944 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
19945 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
19946 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
19947 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
19948 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
19949 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
19950 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
19951 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
19952 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
19953 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
19954 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
19955 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
19956 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
19957 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
19958 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
19959 	tcpkp->inDataInorderSegs.value.ui32 =
19960 	    tcps->tcps_mib.tcpInDataInorderSegs;
19961 	tcpkp->inDataInorderBytes.value.ui32 =
19962 	    tcps->tcps_mib.tcpInDataInorderBytes;
19963 	tcpkp->inDataUnorderSegs.value.ui32 =
19964 	    tcps->tcps_mib.tcpInDataUnorderSegs;
19965 	tcpkp->inDataUnorderBytes.value.ui32 =
19966 	    tcps->tcps_mib.tcpInDataUnorderBytes;
19967 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
19968 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
19969 	tcpkp->inDataPartDupSegs.value.ui32 =
19970 	    tcps->tcps_mib.tcpInDataPartDupSegs;
19971 	tcpkp->inDataPartDupBytes.value.ui32 =
19972 	    tcps->tcps_mib.tcpInDataPartDupBytes;
19973 	tcpkp->inDataPastWinSegs.value.ui32 =
19974 	    tcps->tcps_mib.tcpInDataPastWinSegs;
19975 	tcpkp->inDataPastWinBytes.value.ui32 =
19976 	    tcps->tcps_mib.tcpInDataPastWinBytes;
19977 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
19978 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
19979 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
19980 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
19981 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
19982 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
19983 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
19984 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
19985 	tcpkp->timKeepaliveProbe.value.ui32 =
19986 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
19987 	tcpkp->timKeepaliveDrop.value.ui32 =
19988 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
19989 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
19990 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
19991 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
19992 	tcpkp->outSackRetransSegs.value.ui32 =
19993 	    tcps->tcps_mib.tcpOutSackRetransSegs;
19994 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
19995 
19996 	netstack_rele(ns);
19997 	return (0);
19998 }
19999 
20000 static int
20001 tcp_squeue_switch(int val)
20002 {
20003 	int rval = SQ_FILL;
20004 
20005 	switch (val) {
20006 	case 1:
20007 		rval = SQ_NODRAIN;
20008 		break;
20009 	case 2:
20010 		rval = SQ_PROCESS;
20011 		break;
20012 	default:
20013 		break;
20014 	}
20015 	return (rval);
20016 }
20017 
20018 /*
20019  * This is called once for each squeue - globally for all stack
20020  * instances.
20021  */
20022 static void
20023 tcp_squeue_add(squeue_t *sqp)
20024 {
20025 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
20026 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
20027 
20028 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
20029 	tcp_time_wait->tcp_time_wait_tid =
20030 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
20031 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
20032 	    CALLOUT_FLAG_ROUNDUP);
20033 	if (tcp_free_list_max_cnt == 0) {
20034 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
20035 		    max_ncpus : boot_max_ncpus);
20036 
20037 		/*
20038 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
20039 		 */
20040 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
20041 		    (tcp_ncpus * sizeof (tcp_t) * 100);
20042 	}
20043 	tcp_time_wait->tcp_free_list_cnt = 0;
20044 }
20045 
20046 /*
20047  * On a labeled system we have some protocols above TCP, such as RPC, which
20048  * appear to assume that every mblk in a chain has a db_credp.
20049  */
20050 static void
20051 tcp_setcred_data(mblk_t *mp, ip_recv_attr_t *ira)
20052 {
20053 	ASSERT(is_system_labeled());
20054 	ASSERT(ira->ira_cred != NULL);
20055 
20056 	while (mp != NULL) {
20057 		mblk_setcred(mp, ira->ira_cred, NOPID);
20058 		mp = mp->b_cont;
20059 	}
20060 }
20061 
20062 static int
20063 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
20064     boolean_t bind_to_req_port_only, cred_t *cr)
20065 {
20066 	in_port_t	mlp_port;
20067 	mlp_type_t 	addrtype, mlptype;
20068 	boolean_t	user_specified;
20069 	in_port_t	allocated_port;
20070 	in_port_t	requested_port = *requested_port_ptr;
20071 	conn_t		*connp = tcp->tcp_connp;
20072 	zone_t		*zone;
20073 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20074 	in6_addr_t	v6addr = connp->conn_laddr_v6;
20075 
20076 	/*
20077 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
20078 	 */
20079 	ASSERT(cr != NULL);
20080 
20081 	/*
20082 	 * Get a valid port (within the anonymous range and should not
20083 	 * be a privileged one) to use if the user has not given a port.
20084 	 * If multiple threads are here, they may all start with
20085 	 * with the same initial port. But, it should be fine as long as
20086 	 * tcp_bindi will ensure that no two threads will be assigned
20087 	 * the same port.
20088 	 *
20089 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
20090 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
20091 	 * unless TCP_ANONPRIVBIND option is set.
20092 	 */
20093 	mlptype = mlptSingle;
20094 	mlp_port = requested_port;
20095 	if (requested_port == 0) {
20096 		requested_port = connp->conn_anon_priv_bind ?
20097 		    tcp_get_next_priv_port(tcp) :
20098 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
20099 		    tcp, B_TRUE);
20100 		if (requested_port == 0) {
20101 			return (-TNOADDR);
20102 		}
20103 		user_specified = B_FALSE;
20104 
20105 		/*
20106 		 * If the user went through one of the RPC interfaces to create
20107 		 * this socket and RPC is MLP in this zone, then give him an
20108 		 * anonymous MLP.
20109 		 */
20110 		if (connp->conn_anon_mlp && is_system_labeled()) {
20111 			zone = crgetzone(cr);
20112 			addrtype = tsol_mlp_addr_type(
20113 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20114 			    IPV6_VERSION, &v6addr,
20115 			    tcps->tcps_netstack->netstack_ip);
20116 			if (addrtype == mlptSingle) {
20117 				return (-TNOADDR);
20118 			}
20119 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20120 			    PMAPPORT, addrtype);
20121 			mlp_port = PMAPPORT;
20122 		}
20123 	} else {
20124 		int i;
20125 		boolean_t priv = B_FALSE;
20126 
20127 		/*
20128 		 * If the requested_port is in the well-known privileged range,
20129 		 * verify that the stream was opened by a privileged user.
20130 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
20131 		 * but instead the code relies on:
20132 		 * - the fact that the address of the array and its size never
20133 		 *   changes
20134 		 * - the atomic assignment of the elements of the array
20135 		 */
20136 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
20137 			priv = B_TRUE;
20138 		} else {
20139 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
20140 				if (requested_port ==
20141 				    tcps->tcps_g_epriv_ports[i]) {
20142 					priv = B_TRUE;
20143 					break;
20144 				}
20145 			}
20146 		}
20147 		if (priv) {
20148 			if (secpolicy_net_privaddr(cr, requested_port,
20149 			    IPPROTO_TCP) != 0) {
20150 				if (connp->conn_debug) {
20151 					(void) strlog(TCP_MOD_ID, 0, 1,
20152 					    SL_ERROR|SL_TRACE,
20153 					    "tcp_bind: no priv for port %d",
20154 					    requested_port);
20155 				}
20156 				return (-TACCES);
20157 			}
20158 		}
20159 		user_specified = B_TRUE;
20160 
20161 		connp = tcp->tcp_connp;
20162 		if (is_system_labeled()) {
20163 			zone = crgetzone(cr);
20164 			addrtype = tsol_mlp_addr_type(
20165 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20166 			    IPV6_VERSION, &v6addr,
20167 			    tcps->tcps_netstack->netstack_ip);
20168 			if (addrtype == mlptSingle) {
20169 				return (-TNOADDR);
20170 			}
20171 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20172 			    requested_port, addrtype);
20173 		}
20174 	}
20175 
20176 	if (mlptype != mlptSingle) {
20177 		if (secpolicy_net_bindmlp(cr) != 0) {
20178 			if (connp->conn_debug) {
20179 				(void) strlog(TCP_MOD_ID, 0, 1,
20180 				    SL_ERROR|SL_TRACE,
20181 				    "tcp_bind: no priv for multilevel port %d",
20182 				    requested_port);
20183 			}
20184 			return (-TACCES);
20185 		}
20186 
20187 		/*
20188 		 * If we're specifically binding a shared IP address and the
20189 		 * port is MLP on shared addresses, then check to see if this
20190 		 * zone actually owns the MLP.  Reject if not.
20191 		 */
20192 		if (mlptype == mlptShared && addrtype == mlptShared) {
20193 			/*
20194 			 * No need to handle exclusive-stack zones since
20195 			 * ALL_ZONES only applies to the shared stack.
20196 			 */
20197 			zoneid_t mlpzone;
20198 
20199 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
20200 			    htons(mlp_port));
20201 			if (connp->conn_zoneid != mlpzone) {
20202 				if (connp->conn_debug) {
20203 					(void) strlog(TCP_MOD_ID, 0, 1,
20204 					    SL_ERROR|SL_TRACE,
20205 					    "tcp_bind: attempt to bind port "
20206 					    "%d on shared addr in zone %d "
20207 					    "(should be %d)",
20208 					    mlp_port, connp->conn_zoneid,
20209 					    mlpzone);
20210 				}
20211 				return (-TACCES);
20212 			}
20213 		}
20214 
20215 		if (!user_specified) {
20216 			int err;
20217 			err = tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20218 			    requested_port, B_TRUE);
20219 			if (err != 0) {
20220 				if (connp->conn_debug) {
20221 					(void) strlog(TCP_MOD_ID, 0, 1,
20222 					    SL_ERROR|SL_TRACE,
20223 					    "tcp_bind: cannot establish anon "
20224 					    "MLP for port %d",
20225 					    requested_port);
20226 				}
20227 				return (err);
20228 			}
20229 			connp->conn_anon_port = B_TRUE;
20230 		}
20231 		connp->conn_mlp_type = mlptype;
20232 	}
20233 
20234 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
20235 	    connp->conn_reuseaddr, B_FALSE, bind_to_req_port_only,
20236 	    user_specified);
20237 
20238 	if (allocated_port == 0) {
20239 		connp->conn_mlp_type = mlptSingle;
20240 		if (connp->conn_anon_port) {
20241 			connp->conn_anon_port = B_FALSE;
20242 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20243 			    requested_port, B_FALSE);
20244 		}
20245 		if (bind_to_req_port_only) {
20246 			if (connp->conn_debug) {
20247 				(void) strlog(TCP_MOD_ID, 0, 1,
20248 				    SL_ERROR|SL_TRACE,
20249 				    "tcp_bind: requested addr busy");
20250 			}
20251 			return (-TADDRBUSY);
20252 		} else {
20253 			/* If we are out of ports, fail the bind. */
20254 			if (connp->conn_debug) {
20255 				(void) strlog(TCP_MOD_ID, 0, 1,
20256 				    SL_ERROR|SL_TRACE,
20257 				    "tcp_bind: out of ports?");
20258 			}
20259 			return (-TNOADDR);
20260 		}
20261 	}
20262 
20263 	/* Pass the allocated port back */
20264 	*requested_port_ptr = allocated_port;
20265 	return (0);
20266 }
20267 
20268 /*
20269  * Check the address and check/pick a local port number.
20270  */
20271 static int
20272 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20273     boolean_t bind_to_req_port_only)
20274 {
20275 	tcp_t	*tcp = connp->conn_tcp;
20276 	sin_t	*sin;
20277 	sin6_t  *sin6;
20278 	in_port_t	requested_port;
20279 	ipaddr_t	v4addr;
20280 	in6_addr_t	v6addr;
20281 	ip_laddr_t	laddr_type = IPVL_UNICAST_UP;	/* INADDR_ANY */
20282 	zoneid_t	zoneid = IPCL_ZONEID(connp);
20283 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
20284 	uint_t		scopeid = 0;
20285 	int		error = 0;
20286 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20287 
20288 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
20289 
20290 	if (tcp->tcp_state == TCPS_BOUND) {
20291 		return (0);
20292 	} else if (tcp->tcp_state > TCPS_BOUND) {
20293 		if (connp->conn_debug) {
20294 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20295 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20296 		}
20297 		return (-TOUTSTATE);
20298 	}
20299 
20300 	ASSERT(sa != NULL && len != 0);
20301 
20302 	if (!OK_32PTR((char *)sa)) {
20303 		if (connp->conn_debug) {
20304 			(void) strlog(TCP_MOD_ID, 0, 1,
20305 			    SL_ERROR|SL_TRACE,
20306 			    "tcp_bind: bad address parameter, "
20307 			    "address %p, len %d",
20308 			    (void *)sa, len);
20309 		}
20310 		return (-TPROTO);
20311 	}
20312 
20313 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
20314 	if (error != 0) {
20315 		return (error);
20316 	}
20317 
20318 	switch (len) {
20319 	case sizeof (sin_t):	/* Complete IPv4 address */
20320 		sin = (sin_t *)sa;
20321 		requested_port = ntohs(sin->sin_port);
20322 		v4addr = sin->sin_addr.s_addr;
20323 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
20324 		if (v4addr != INADDR_ANY) {
20325 			laddr_type = ip_laddr_verify_v4(v4addr, zoneid, ipst,
20326 			    B_FALSE);
20327 		}
20328 		break;
20329 
20330 	case sizeof (sin6_t): /* Complete IPv6 address */
20331 		sin6 = (sin6_t *)sa;
20332 		v6addr = sin6->sin6_addr;
20333 		requested_port = ntohs(sin6->sin6_port);
20334 		if (IN6_IS_ADDR_V4MAPPED(&v6addr)) {
20335 			if (connp->conn_ipv6_v6only)
20336 				return (EADDRNOTAVAIL);
20337 
20338 			IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
20339 			if (v4addr != INADDR_ANY) {
20340 				laddr_type = ip_laddr_verify_v4(v4addr,
20341 				    zoneid, ipst, B_FALSE);
20342 			}
20343 		} else {
20344 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6addr)) {
20345 				if (IN6_IS_ADDR_LINKSCOPE(&v6addr))
20346 					scopeid = sin6->sin6_scope_id;
20347 				laddr_type = ip_laddr_verify_v6(&v6addr,
20348 				    zoneid, ipst, B_FALSE, scopeid);
20349 			}
20350 		}
20351 		break;
20352 
20353 	default:
20354 		if (connp->conn_debug) {
20355 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20356 			    "tcp_bind: bad address length, %d", len);
20357 		}
20358 		return (EAFNOSUPPORT);
20359 		/* return (-TBADADDR); */
20360 	}
20361 
20362 	/* Is the local address a valid unicast address? */
20363 	if (laddr_type == IPVL_BAD)
20364 		return (EADDRNOTAVAIL);
20365 
20366 	connp->conn_bound_addr_v6 = v6addr;
20367 	if (scopeid != 0) {
20368 		ixa->ixa_flags |= IXAF_SCOPEID_SET;
20369 		ixa->ixa_scopeid = scopeid;
20370 		connp->conn_incoming_ifindex = scopeid;
20371 	} else {
20372 		ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
20373 		connp->conn_incoming_ifindex = connp->conn_bound_if;
20374 	}
20375 
20376 	connp->conn_laddr_v6 = v6addr;
20377 	connp->conn_saddr_v6 = v6addr;
20378 
20379 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
20380 
20381 	error = tcp_bind_select_lport(tcp, &requested_port,
20382 	    bind_to_req_port_only, cr);
20383 	if (error != 0) {
20384 		connp->conn_laddr_v6 = ipv6_all_zeros;
20385 		connp->conn_saddr_v6 = ipv6_all_zeros;
20386 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
20387 	}
20388 	return (error);
20389 }
20390 
20391 /*
20392  * Return unix error is tli error is TSYSERR, otherwise return a negative
20393  * tli error.
20394  */
20395 int
20396 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20397     boolean_t bind_to_req_port_only)
20398 {
20399 	int error;
20400 	tcp_t *tcp = connp->conn_tcp;
20401 
20402 	if (tcp->tcp_state >= TCPS_BOUND) {
20403 		if (connp->conn_debug) {
20404 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20405 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20406 		}
20407 		return (-TOUTSTATE);
20408 	}
20409 
20410 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
20411 	if (error != 0)
20412 		return (error);
20413 
20414 	ASSERT(tcp->tcp_state == TCPS_BOUND);
20415 	tcp->tcp_conn_req_max = 0;
20416 	return (0);
20417 }
20418 
20419 int
20420 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
20421     socklen_t len, cred_t *cr)
20422 {
20423 	int 		error;
20424 	conn_t		*connp = (conn_t *)proto_handle;
20425 	squeue_t	*sqp = connp->conn_sqp;
20426 
20427 	/* All Solaris components should pass a cred for this operation. */
20428 	ASSERT(cr != NULL);
20429 
20430 	ASSERT(sqp != NULL);
20431 	ASSERT(connp->conn_upper_handle != NULL);
20432 
20433 	error = squeue_synch_enter(sqp, connp, NULL);
20434 	if (error != 0) {
20435 		/* failed to enter */
20436 		return (ENOSR);
20437 	}
20438 
20439 	/* binding to a NULL address really means unbind */
20440 	if (sa == NULL) {
20441 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
20442 			error = tcp_do_unbind(connp);
20443 		else
20444 			error = EINVAL;
20445 	} else {
20446 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
20447 	}
20448 
20449 	squeue_synch_exit(sqp, connp);
20450 
20451 	if (error < 0) {
20452 		if (error == -TOUTSTATE)
20453 			error = EINVAL;
20454 		else
20455 			error = proto_tlitosyserr(-error);
20456 	}
20457 
20458 	return (error);
20459 }
20460 
20461 /*
20462  * If the return value from this function is positive, it's a UNIX error.
20463  * Otherwise, if it's negative, then the absolute value is a TLI error.
20464  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
20465  */
20466 int
20467 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
20468     cred_t *cr, pid_t pid)
20469 {
20470 	tcp_t		*tcp = connp->conn_tcp;
20471 	sin_t		*sin = (sin_t *)sa;
20472 	sin6_t		*sin6 = (sin6_t *)sa;
20473 	ipaddr_t	*dstaddrp;
20474 	in_port_t	dstport;
20475 	uint_t		srcid;
20476 	int		error;
20477 	uint32_t	mss;
20478 	mblk_t		*syn_mp;
20479 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20480 	int32_t		oldstate;
20481 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20482 
20483 	oldstate = tcp->tcp_state;
20484 
20485 	switch (len) {
20486 	default:
20487 		/*
20488 		 * Should never happen
20489 		 */
20490 		return (EINVAL);
20491 
20492 	case sizeof (sin_t):
20493 		sin = (sin_t *)sa;
20494 		if (sin->sin_port == 0) {
20495 			return (-TBADADDR);
20496 		}
20497 		if (connp->conn_ipv6_v6only) {
20498 			return (EAFNOSUPPORT);
20499 		}
20500 		break;
20501 
20502 	case sizeof (sin6_t):
20503 		sin6 = (sin6_t *)sa;
20504 		if (sin6->sin6_port == 0) {
20505 			return (-TBADADDR);
20506 		}
20507 		break;
20508 	}
20509 	/*
20510 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
20511 	 * make sure that the conn_ipversion is IPV4_VERSION.  We
20512 	 * need to this before we call tcp_bindi() so that the port lookup
20513 	 * code will look for ports in the correct port space (IPv4 and
20514 	 * IPv6 have separate port spaces).
20515 	 */
20516 	if (connp->conn_family == AF_INET6 &&
20517 	    connp->conn_ipversion == IPV6_VERSION &&
20518 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20519 		if (connp->conn_ipv6_v6only)
20520 			return (EADDRNOTAVAIL);
20521 
20522 		connp->conn_ipversion = IPV4_VERSION;
20523 	}
20524 
20525 	switch (tcp->tcp_state) {
20526 	case TCPS_LISTEN:
20527 		/*
20528 		 * Listening sockets are not allowed to issue connect().
20529 		 */
20530 		if (IPCL_IS_NONSTR(connp))
20531 			return (EOPNOTSUPP);
20532 		/* FALLTHRU */
20533 	case TCPS_IDLE:
20534 		/*
20535 		 * We support quick connect, refer to comments in
20536 		 * tcp_connect_*()
20537 		 */
20538 		/* FALLTHRU */
20539 	case TCPS_BOUND:
20540 		break;
20541 	default:
20542 		return (-TOUTSTATE);
20543 	}
20544 
20545 	/*
20546 	 * We update our cred/cpid based on the caller of connect
20547 	 */
20548 	if (connp->conn_cred != cr) {
20549 		crhold(cr);
20550 		crfree(connp->conn_cred);
20551 		connp->conn_cred = cr;
20552 	}
20553 	connp->conn_cpid = pid;
20554 
20555 	/* Cache things in the ixa without any refhold */
20556 	ixa->ixa_cred = cr;
20557 	ixa->ixa_cpid = pid;
20558 	if (is_system_labeled()) {
20559 		/* We need to restart with a label based on the cred */
20560 		ip_xmit_attr_restore_tsl(ixa, ixa->ixa_cred);
20561 	}
20562 
20563 	if (connp->conn_family == AF_INET6) {
20564 		if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20565 			error = tcp_connect_ipv6(tcp, &sin6->sin6_addr,
20566 			    sin6->sin6_port, sin6->sin6_flowinfo,
20567 			    sin6->__sin6_src_id, sin6->sin6_scope_id);
20568 		} else {
20569 			/*
20570 			 * Destination adress is mapped IPv6 address.
20571 			 * Source bound address should be unspecified or
20572 			 * IPv6 mapped address as well.
20573 			 */
20574 			if (!IN6_IS_ADDR_UNSPECIFIED(
20575 			    &connp->conn_bound_addr_v6) &&
20576 			    !IN6_IS_ADDR_V4MAPPED(&connp->conn_bound_addr_v6)) {
20577 				return (EADDRNOTAVAIL);
20578 			}
20579 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
20580 			dstport = sin6->sin6_port;
20581 			srcid = sin6->__sin6_src_id;
20582 			error = tcp_connect_ipv4(tcp, dstaddrp, dstport,
20583 			    srcid);
20584 		}
20585 	} else {
20586 		dstaddrp = &sin->sin_addr.s_addr;
20587 		dstport = sin->sin_port;
20588 		srcid = 0;
20589 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid);
20590 	}
20591 
20592 	if (error != 0)
20593 		goto connect_failed;
20594 
20595 	CL_INET_CONNECT(connp, B_TRUE, error);
20596 	if (error != 0)
20597 		goto connect_failed;
20598 
20599 	/* connect succeeded */
20600 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
20601 	tcp->tcp_active_open = 1;
20602 
20603 	/*
20604 	 * tcp_set_destination() does not adjust for TCP/IP header length.
20605 	 */
20606 	mss = tcp->tcp_mss - connp->conn_ht_iphc_len;
20607 
20608 	/*
20609 	 * Just make sure our rwnd is at least rcvbuf * MSS large, and round up
20610 	 * to the nearest MSS.
20611 	 *
20612 	 * We do the round up here because we need to get the interface MTU
20613 	 * first before we can do the round up.
20614 	 */
20615 	tcp->tcp_rwnd = connp->conn_rcvbuf;
20616 	tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
20617 	    tcps->tcps_recv_hiwat_minmss * mss);
20618 	connp->conn_rcvbuf = tcp->tcp_rwnd;
20619 	tcp_set_ws_value(tcp);
20620 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
20621 	if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
20622 		tcp->tcp_snd_ws_ok = B_TRUE;
20623 
20624 	/*
20625 	 * Set tcp_snd_ts_ok to true
20626 	 * so that tcp_xmit_mp will
20627 	 * include the timestamp
20628 	 * option in the SYN segment.
20629 	 */
20630 	if (tcps->tcps_tstamp_always ||
20631 	    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
20632 		tcp->tcp_snd_ts_ok = B_TRUE;
20633 	}
20634 
20635 	/*
20636 	 * tcp_snd_sack_ok can be set in
20637 	 * tcp_set_destination() if the sack metric
20638 	 * is set.  So check it here also.
20639 	 */
20640 	if (tcps->tcps_sack_permitted == 2 ||
20641 	    tcp->tcp_snd_sack_ok) {
20642 		if (tcp->tcp_sack_info == NULL) {
20643 			tcp->tcp_sack_info = kmem_cache_alloc(
20644 			    tcp_sack_info_cache, KM_SLEEP);
20645 		}
20646 		tcp->tcp_snd_sack_ok = B_TRUE;
20647 	}
20648 
20649 	/*
20650 	 * Should we use ECN?  Note that the current
20651 	 * default value (SunOS 5.9) of tcp_ecn_permitted
20652 	 * is 1.  The reason for doing this is that there
20653 	 * are equipments out there that will drop ECN
20654 	 * enabled IP packets.  Setting it to 1 avoids
20655 	 * compatibility problems.
20656 	 */
20657 	if (tcps->tcps_ecn_permitted == 2)
20658 		tcp->tcp_ecn_ok = B_TRUE;
20659 
20660 	TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20661 	syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
20662 	    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
20663 	if (syn_mp != NULL) {
20664 		/*
20665 		 * We must bump the generation before sending the syn
20666 		 * to ensure that we use the right generation in case
20667 		 * this thread issues a "connected" up call.
20668 		 */
20669 		SOCK_CONNID_BUMP(tcp->tcp_connid);
20670 		tcp_send_data(tcp, syn_mp);
20671 	}
20672 
20673 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
20674 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
20675 	return (0);
20676 
20677 connect_failed:
20678 	connp->conn_faddr_v6 = ipv6_all_zeros;
20679 	connp->conn_fport = 0;
20680 	tcp->tcp_state = oldstate;
20681 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
20682 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
20683 	return (error);
20684 }
20685 
20686 int
20687 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
20688     socklen_t len, sock_connid_t *id, cred_t *cr)
20689 {
20690 	conn_t		*connp = (conn_t *)proto_handle;
20691 	squeue_t	*sqp = connp->conn_sqp;
20692 	int		error;
20693 
20694 	ASSERT(connp->conn_upper_handle != NULL);
20695 
20696 	/* All Solaris components should pass a cred for this operation. */
20697 	ASSERT(cr != NULL);
20698 
20699 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
20700 	if (error != 0) {
20701 		return (error);
20702 	}
20703 
20704 	error = squeue_synch_enter(sqp, connp, NULL);
20705 	if (error != 0) {
20706 		/* failed to enter */
20707 		return (ENOSR);
20708 	}
20709 
20710 	/*
20711 	 * TCP supports quick connect, so no need to do an implicit bind
20712 	 */
20713 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
20714 	if (error == 0) {
20715 		*id = connp->conn_tcp->tcp_connid;
20716 	} else if (error < 0) {
20717 		if (error == -TOUTSTATE) {
20718 			switch (connp->conn_tcp->tcp_state) {
20719 			case TCPS_SYN_SENT:
20720 				error = EALREADY;
20721 				break;
20722 			case TCPS_ESTABLISHED:
20723 				error = EISCONN;
20724 				break;
20725 			case TCPS_LISTEN:
20726 				error = EOPNOTSUPP;
20727 				break;
20728 			default:
20729 				error = EINVAL;
20730 				break;
20731 			}
20732 		} else {
20733 			error = proto_tlitosyserr(-error);
20734 		}
20735 	}
20736 
20737 	if (connp->conn_tcp->tcp_loopback) {
20738 		struct sock_proto_props sopp;
20739 
20740 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
20741 		sopp.sopp_loopback = B_TRUE;
20742 
20743 		(*connp->conn_upcalls->su_set_proto_props)(
20744 		    connp->conn_upper_handle, &sopp);
20745 	}
20746 done:
20747 	squeue_synch_exit(sqp, connp);
20748 
20749 	return ((error == 0) ? EINPROGRESS : error);
20750 }
20751 
20752 /* ARGSUSED */
20753 sock_lower_handle_t
20754 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
20755     uint_t *smodep, int *errorp, int flags, cred_t *credp)
20756 {
20757 	conn_t		*connp;
20758 	boolean_t	isv6 = family == AF_INET6;
20759 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
20760 	    (proto != 0 && proto != IPPROTO_TCP)) {
20761 		*errorp = EPROTONOSUPPORT;
20762 		return (NULL);
20763 	}
20764 
20765 	connp = tcp_create_common(credp, isv6, B_TRUE, errorp);
20766 	if (connp == NULL) {
20767 		return (NULL);
20768 	}
20769 
20770 	/*
20771 	 * Put the ref for TCP. Ref for IP was already put
20772 	 * by ipcl_conn_create. Also Make the conn_t globally
20773 	 * visible to walkers
20774 	 */
20775 	mutex_enter(&connp->conn_lock);
20776 	CONN_INC_REF_LOCKED(connp);
20777 	ASSERT(connp->conn_ref == 2);
20778 	connp->conn_state_flags &= ~CONN_INCIPIENT;
20779 
20780 	connp->conn_flags |= IPCL_NONSTR;
20781 	mutex_exit(&connp->conn_lock);
20782 
20783 	ASSERT(errorp != NULL);
20784 	*errorp = 0;
20785 	*sock_downcalls = &sock_tcp_downcalls;
20786 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
20787 	    SM_SENDFILESUPP;
20788 
20789 	return ((sock_lower_handle_t)connp);
20790 }
20791 
20792 /* ARGSUSED */
20793 void
20794 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
20795     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
20796 {
20797 	conn_t *connp = (conn_t *)proto_handle;
20798 	struct sock_proto_props sopp;
20799 
20800 	ASSERT(connp->conn_upper_handle == NULL);
20801 
20802 	/* All Solaris components should pass a cred for this operation. */
20803 	ASSERT(cr != NULL);
20804 
20805 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
20806 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
20807 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
20808 
20809 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
20810 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
20811 	sopp.sopp_maxpsz = INFPSZ;
20812 	sopp.sopp_maxblk = INFPSZ;
20813 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
20814 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
20815 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
20816 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
20817 	    tcp_rinfo.mi_minpsz;
20818 
20819 	connp->conn_upcalls = sock_upcalls;
20820 	connp->conn_upper_handle = sock_handle;
20821 
20822 	ASSERT(connp->conn_rcvbuf != 0 &&
20823 	    connp->conn_rcvbuf == connp->conn_tcp->tcp_rwnd);
20824 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
20825 }
20826 
20827 /* ARGSUSED */
20828 int
20829 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
20830 {
20831 	conn_t *connp = (conn_t *)proto_handle;
20832 
20833 	ASSERT(connp->conn_upper_handle != NULL);
20834 
20835 	/* All Solaris components should pass a cred for this operation. */
20836 	ASSERT(cr != NULL);
20837 
20838 	tcp_close_common(connp, flags);
20839 
20840 	ip_free_helper_stream(connp);
20841 
20842 	/*
20843 	 * Drop IP's reference on the conn. This is the last reference
20844 	 * on the connp if the state was less than established. If the
20845 	 * connection has gone into timewait state, then we will have
20846 	 * one ref for the TCP and one more ref (total of two) for the
20847 	 * classifier connected hash list (a timewait connections stays
20848 	 * in connected hash till closed).
20849 	 *
20850 	 * We can't assert the references because there might be other
20851 	 * transient reference places because of some walkers or queued
20852 	 * packets in squeue for the timewait state.
20853 	 */
20854 	CONN_DEC_REF(connp);
20855 	return (0);
20856 }
20857 
20858 /* ARGSUSED */
20859 int
20860 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
20861     cred_t *cr)
20862 {
20863 	tcp_t		*tcp;
20864 	uint32_t	msize;
20865 	conn_t *connp = (conn_t *)proto_handle;
20866 	int32_t		tcpstate;
20867 
20868 	/* All Solaris components should pass a cred for this operation. */
20869 	ASSERT(cr != NULL);
20870 
20871 	ASSERT(connp->conn_ref >= 2);
20872 	ASSERT(connp->conn_upper_handle != NULL);
20873 
20874 	if (msg->msg_controllen != 0) {
20875 		freemsg(mp);
20876 		return (EOPNOTSUPP);
20877 	}
20878 
20879 	switch (DB_TYPE(mp)) {
20880 	case M_DATA:
20881 		tcp = connp->conn_tcp;
20882 		ASSERT(tcp != NULL);
20883 
20884 		tcpstate = tcp->tcp_state;
20885 		if (tcpstate < TCPS_ESTABLISHED) {
20886 			freemsg(mp);
20887 			/*
20888 			 * We return ENOTCONN if the endpoint is trying to
20889 			 * connect or has never been connected, and EPIPE if it
20890 			 * has been disconnected. The connection id helps us
20891 			 * distinguish between the last two cases.
20892 			 */
20893 			return ((tcpstate == TCPS_SYN_SENT) ? ENOTCONN :
20894 			    ((tcp->tcp_connid > 0) ? EPIPE : ENOTCONN));
20895 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
20896 			freemsg(mp);
20897 			return (EPIPE);
20898 		}
20899 
20900 		msize = msgdsize(mp);
20901 
20902 		mutex_enter(&tcp->tcp_non_sq_lock);
20903 		tcp->tcp_squeue_bytes += msize;
20904 		/*
20905 		 * Squeue Flow Control
20906 		 */
20907 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
20908 			tcp_setqfull(tcp);
20909 		}
20910 		mutex_exit(&tcp->tcp_non_sq_lock);
20911 
20912 		/*
20913 		 * The application may pass in an address in the msghdr, but
20914 		 * we ignore the address on connection-oriented sockets.
20915 		 * Just like BSD this code does not generate an error for
20916 		 * TCP (a CONNREQUIRED socket) when sending to an address
20917 		 * passed in with sendto/sendmsg. Instead the data is
20918 		 * delivered on the connection as if no address had been
20919 		 * supplied.
20920 		 */
20921 		CONN_INC_REF(connp);
20922 
20923 		if (msg->msg_flags & MSG_OOB) {
20924 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output_urgent,
20925 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
20926 		} else {
20927 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
20928 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
20929 		}
20930 
20931 		return (0);
20932 
20933 	default:
20934 		ASSERT(0);
20935 	}
20936 
20937 	freemsg(mp);
20938 	return (0);
20939 }
20940 
20941 /* ARGSUSED2 */
20942 void
20943 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
20944 {
20945 	int len;
20946 	uint32_t msize;
20947 	conn_t *connp = (conn_t *)arg;
20948 	tcp_t *tcp = connp->conn_tcp;
20949 
20950 	msize = msgdsize(mp);
20951 
20952 	len = msize - 1;
20953 	if (len < 0) {
20954 		freemsg(mp);
20955 		return;
20956 	}
20957 
20958 	/*
20959 	 * Try to force urgent data out on the wire. Even if we have unsent
20960 	 * data this will at least send the urgent flag.
20961 	 * XXX does not handle more flag correctly.
20962 	 */
20963 	len += tcp->tcp_unsent;
20964 	len += tcp->tcp_snxt;
20965 	tcp->tcp_urg = len;
20966 	tcp->tcp_valid_bits |= TCP_URG_VALID;
20967 
20968 	/* Bypass tcp protocol for fused tcp loopback */
20969 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
20970 		return;
20971 
20972 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
20973 	if (DB_TYPE(mp) != M_DATA) {
20974 		mblk_t *mp1 = mp;
20975 		ASSERT(!IPCL_IS_NONSTR(connp));
20976 		mp = mp->b_cont;
20977 		freeb(mp1);
20978 	}
20979 	tcp_wput_data(tcp, mp, B_TRUE);
20980 }
20981 
20982 /* ARGSUSED3 */
20983 int
20984 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
20985     socklen_t *addrlenp, cred_t *cr)
20986 {
20987 	conn_t	*connp = (conn_t *)proto_handle;
20988 	tcp_t	*tcp = connp->conn_tcp;
20989 
20990 	ASSERT(connp->conn_upper_handle != NULL);
20991 	/* All Solaris components should pass a cred for this operation. */
20992 	ASSERT(cr != NULL);
20993 
20994 	ASSERT(tcp != NULL);
20995 	if (tcp->tcp_state < TCPS_SYN_RCVD)
20996 		return (ENOTCONN);
20997 
20998 	return (conn_getpeername(connp, addr, addrlenp));
20999 }
21000 
21001 /* ARGSUSED3 */
21002 int
21003 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21004     socklen_t *addrlenp, cred_t *cr)
21005 {
21006 	conn_t	*connp = (conn_t *)proto_handle;
21007 
21008 	/* All Solaris components should pass a cred for this operation. */
21009 	ASSERT(cr != NULL);
21010 
21011 	ASSERT(connp->conn_upper_handle != NULL);
21012 	return (conn_getsockname(connp, addr, addrlenp));
21013 }
21014 
21015 /*
21016  * tcp_fallback
21017  *
21018  * A direct socket is falling back to using STREAMS. The queue
21019  * that is being passed down was created using tcp_open() with
21020  * the SO_FALLBACK flag set. As a result, the queue is not
21021  * associated with a conn, and the q_ptrs instead contain the
21022  * dev and minor area that should be used.
21023  *
21024  * The 'issocket' flag indicates whether the FireEngine
21025  * optimizations should be used. The common case would be that
21026  * optimizations are enabled, and they might be subsequently
21027  * disabled using the _SIOCSOCKFALLBACK ioctl.
21028  */
21029 
21030 /*
21031  * An active connection is falling back to TPI. Gather all the information
21032  * required by the STREAM head and TPI sonode and send it up.
21033  */
21034 void
21035 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
21036     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
21037 {
21038 	conn_t			*connp = tcp->tcp_connp;
21039 	struct stroptions	*stropt;
21040 	struct T_capability_ack tca;
21041 	struct sockaddr_in6	laddr, faddr;
21042 	socklen_t 		laddrlen, faddrlen;
21043 	short			opts;
21044 	int			error;
21045 	mblk_t			*mp;
21046 
21047 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
21048 	connp->conn_minor_arena = WR(q)->q_ptr;
21049 
21050 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
21051 
21052 	connp->conn_rq = RD(q);
21053 	connp->conn_wq = WR(q);
21054 
21055 	WR(q)->q_qinfo = &tcp_sock_winit;
21056 
21057 	if (!issocket)
21058 		tcp_use_pure_tpi(tcp);
21059 
21060 	/*
21061 	 * free the helper stream
21062 	 */
21063 	ip_free_helper_stream(connp);
21064 
21065 	/*
21066 	 * Notify the STREAM head about options
21067 	 */
21068 	DB_TYPE(stropt_mp) = M_SETOPTS;
21069 	stropt = (struct stroptions *)stropt_mp->b_rptr;
21070 	stropt_mp->b_wptr += sizeof (struct stroptions);
21071 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
21072 
21073 	stropt->so_wroff = connp->conn_ht_iphc_len + (tcp->tcp_loopback ? 0 :
21074 	    tcp->tcp_tcps->tcps_wroff_xtra);
21075 	if (tcp->tcp_snd_sack_ok)
21076 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
21077 	stropt->so_hiwat = connp->conn_rcvbuf;
21078 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
21079 
21080 	putnext(RD(q), stropt_mp);
21081 
21082 	/*
21083 	 * Collect the information needed to sync with the sonode
21084 	 */
21085 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
21086 
21087 	laddrlen = faddrlen = sizeof (sin6_t);
21088 	(void) tcp_getsockname((sock_lower_handle_t)connp,
21089 	    (struct sockaddr *)&laddr, &laddrlen, CRED());
21090 	error = tcp_getpeername((sock_lower_handle_t)connp,
21091 	    (struct sockaddr *)&faddr, &faddrlen, CRED());
21092 	if (error != 0)
21093 		faddrlen = 0;
21094 
21095 	opts = 0;
21096 	if (connp->conn_oobinline)
21097 		opts |= SO_OOBINLINE;
21098 	if (connp->conn_ixa->ixa_flags & IXAF_DONTROUTE)
21099 		opts |= SO_DONTROUTE;
21100 
21101 	/*
21102 	 * Notify the socket that the protocol is now quiescent,
21103 	 * and it's therefore safe move data from the socket
21104 	 * to the stream head.
21105 	 */
21106 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
21107 	    (struct sockaddr *)&laddr, laddrlen,
21108 	    (struct sockaddr *)&faddr, faddrlen, opts);
21109 
21110 	while ((mp = tcp->tcp_rcv_list) != NULL) {
21111 		tcp->tcp_rcv_list = mp->b_next;
21112 		mp->b_next = NULL;
21113 		/* We never do fallback for kernel RPC */
21114 		putnext(q, mp);
21115 	}
21116 	tcp->tcp_rcv_last_head = NULL;
21117 	tcp->tcp_rcv_last_tail = NULL;
21118 	tcp->tcp_rcv_cnt = 0;
21119 }
21120 
21121 /*
21122  * An eager is falling back to TPI. All we have to do is send
21123  * up a T_CONN_IND.
21124  */
21125 void
21126 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
21127 {
21128 	tcp_t *listener = eager->tcp_listener;
21129 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
21130 
21131 	ASSERT(listener != NULL);
21132 	ASSERT(mp != NULL);
21133 
21134 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
21135 
21136 	/*
21137 	 * TLI/XTI applications will get confused by
21138 	 * sending eager as an option since it violates
21139 	 * the option semantics. So remove the eager as
21140 	 * option since TLI/XTI app doesn't need it anyway.
21141 	 */
21142 	if (!direct_sockfs) {
21143 		struct T_conn_ind *conn_ind;
21144 
21145 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
21146 		conn_ind->OPT_length = 0;
21147 		conn_ind->OPT_offset = 0;
21148 	}
21149 
21150 	/*
21151 	 * Sockfs guarantees that the listener will not be closed
21152 	 * during fallback. So we can safely use the listener's queue.
21153 	 */
21154 	putnext(listener->tcp_connp->conn_rq, mp);
21155 }
21156 
21157 int
21158 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
21159     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
21160 {
21161 	tcp_t			*tcp;
21162 	conn_t 			*connp = (conn_t *)proto_handle;
21163 	int			error;
21164 	mblk_t			*stropt_mp;
21165 	mblk_t			*ordrel_mp;
21166 
21167 	tcp = connp->conn_tcp;
21168 
21169 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
21170 	    NULL);
21171 
21172 	/* Pre-allocate the T_ordrel_ind mblk. */
21173 	ASSERT(tcp->tcp_ordrel_mp == NULL);
21174 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
21175 	    STR_NOSIG, NULL);
21176 	ordrel_mp->b_datap->db_type = M_PROTO;
21177 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
21178 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
21179 
21180 	/*
21181 	 * Enter the squeue so that no new packets can come in
21182 	 */
21183 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
21184 	if (error != 0) {
21185 		/* failed to enter, free all the pre-allocated messages. */
21186 		freeb(stropt_mp);
21187 		freeb(ordrel_mp);
21188 		/*
21189 		 * We cannot process the eager, so at least send out a
21190 		 * RST so the peer can reconnect.
21191 		 */
21192 		if (tcp->tcp_listener != NULL) {
21193 			(void) tcp_eager_blowoff(tcp->tcp_listener,
21194 			    tcp->tcp_conn_req_seqnum);
21195 		}
21196 		return (ENOMEM);
21197 	}
21198 
21199 	/*
21200 	 * Both endpoints must be of the same type (either STREAMS or
21201 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
21202 	 * we have to unfuse.
21203 	 */
21204 	if (tcp->tcp_fused)
21205 		tcp_unfuse(tcp);
21206 
21207 	/*
21208 	 * No longer a direct socket
21209 	 */
21210 	connp->conn_flags &= ~IPCL_NONSTR;
21211 	tcp->tcp_ordrel_mp = ordrel_mp;
21212 
21213 	if (tcp->tcp_listener != NULL) {
21214 		/* The eager will deal with opts when accept() is called */
21215 		freeb(stropt_mp);
21216 		tcp_fallback_eager(tcp, direct_sockfs);
21217 	} else {
21218 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
21219 		    quiesced_cb);
21220 	}
21221 
21222 	/*
21223 	 * There should be atleast two ref's (IP + TCP)
21224 	 */
21225 	ASSERT(connp->conn_ref >= 2);
21226 	squeue_synch_exit(connp->conn_sqp, connp);
21227 
21228 	return (0);
21229 }
21230 
21231 /* ARGSUSED */
21232 static void
21233 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21234 {
21235 	conn_t 	*connp = (conn_t *)arg;
21236 	tcp_t	*tcp = connp->conn_tcp;
21237 
21238 	freemsg(mp);
21239 
21240 	if (tcp->tcp_fused)
21241 		tcp_unfuse(tcp);
21242 
21243 	if (tcp_xmit_end(tcp) != 0) {
21244 		/*
21245 		 * We were crossing FINs and got a reset from
21246 		 * the other side. Just ignore it.
21247 		 */
21248 		if (connp->conn_debug) {
21249 			(void) strlog(TCP_MOD_ID, 0, 1,
21250 			    SL_ERROR|SL_TRACE,
21251 			    "tcp_shutdown_output() out of state %s",
21252 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
21253 		}
21254 	}
21255 }
21256 
21257 /* ARGSUSED */
21258 int
21259 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
21260 {
21261 	conn_t  *connp = (conn_t *)proto_handle;
21262 	tcp_t   *tcp = connp->conn_tcp;
21263 
21264 	ASSERT(connp->conn_upper_handle != NULL);
21265 
21266 	/* All Solaris components should pass a cred for this operation. */
21267 	ASSERT(cr != NULL);
21268 
21269 	/*
21270 	 * X/Open requires that we check the connected state.
21271 	 */
21272 	if (tcp->tcp_state < TCPS_SYN_SENT)
21273 		return (ENOTCONN);
21274 
21275 	/* shutdown the send side */
21276 	if (how != SHUT_RD) {
21277 		mblk_t *bp;
21278 
21279 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
21280 		CONN_INC_REF(connp);
21281 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
21282 		    connp, NULL, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
21283 
21284 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21285 		    SOCK_OPCTL_SHUT_SEND, 0);
21286 	}
21287 
21288 	/* shutdown the recv side */
21289 	if (how != SHUT_WR)
21290 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21291 		    SOCK_OPCTL_SHUT_RECV, 0);
21292 
21293 	return (0);
21294 }
21295 
21296 /*
21297  * SOP_LISTEN() calls into tcp_listen().
21298  */
21299 /* ARGSUSED */
21300 int
21301 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
21302 {
21303 	conn_t	*connp = (conn_t *)proto_handle;
21304 	int 	error;
21305 	squeue_t *sqp = connp->conn_sqp;
21306 
21307 	ASSERT(connp->conn_upper_handle != NULL);
21308 
21309 	/* All Solaris components should pass a cred for this operation. */
21310 	ASSERT(cr != NULL);
21311 
21312 	error = squeue_synch_enter(sqp, connp, NULL);
21313 	if (error != 0) {
21314 		/* failed to enter */
21315 		return (ENOBUFS);
21316 	}
21317 
21318 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
21319 	if (error == 0) {
21320 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21321 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
21322 	} else if (error < 0) {
21323 		if (error == -TOUTSTATE)
21324 			error = EINVAL;
21325 		else
21326 			error = proto_tlitosyserr(-error);
21327 	}
21328 	squeue_synch_exit(sqp, connp);
21329 	return (error);
21330 }
21331 
21332 static int
21333 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
21334     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
21335 {
21336 	tcp_t		*tcp = connp->conn_tcp;
21337 	int		error = 0;
21338 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21339 
21340 	/* All Solaris components should pass a cred for this operation. */
21341 	ASSERT(cr != NULL);
21342 
21343 	if (tcp->tcp_state >= TCPS_BOUND) {
21344 		if ((tcp->tcp_state == TCPS_BOUND ||
21345 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
21346 			/*
21347 			 * Handle listen() increasing backlog.
21348 			 * This is more "liberal" then what the TPI spec
21349 			 * requires but is needed to avoid a t_unbind
21350 			 * when handling listen() since the port number
21351 			 * might be "stolen" between the unbind and bind.
21352 			 */
21353 			goto do_listen;
21354 		}
21355 		if (connp->conn_debug) {
21356 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21357 			    "tcp_listen: bad state, %d", tcp->tcp_state);
21358 		}
21359 		return (-TOUTSTATE);
21360 	} else {
21361 		if (sa == NULL) {
21362 			sin6_t	addr;
21363 			sin_t *sin;
21364 			sin6_t *sin6;
21365 
21366 			ASSERT(IPCL_IS_NONSTR(connp));
21367 			/* Do an implicit bind: Request for a generic port. */
21368 			if (connp->conn_family == AF_INET) {
21369 				len = sizeof (sin_t);
21370 				sin = (sin_t *)&addr;
21371 				*sin = sin_null;
21372 				sin->sin_family = AF_INET;
21373 			} else {
21374 				ASSERT(connp->conn_family == AF_INET6);
21375 				len = sizeof (sin6_t);
21376 				sin6 = (sin6_t *)&addr;
21377 				*sin6 = sin6_null;
21378 				sin6->sin6_family = AF_INET6;
21379 			}
21380 			sa = (struct sockaddr *)&addr;
21381 		}
21382 
21383 		error = tcp_bind_check(connp, sa, len, cr,
21384 		    bind_to_req_port_only);
21385 		if (error)
21386 			return (error);
21387 		/* Fall through and do the fanout insertion */
21388 	}
21389 
21390 do_listen:
21391 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
21392 	tcp->tcp_conn_req_max = backlog;
21393 	if (tcp->tcp_conn_req_max) {
21394 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
21395 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
21396 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
21397 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
21398 		/*
21399 		 * If this is a listener, do not reset the eager list
21400 		 * and other stuffs.  Note that we don't check if the
21401 		 * existing eager list meets the new tcp_conn_req_max
21402 		 * requirement.
21403 		 */
21404 		if (tcp->tcp_state != TCPS_LISTEN) {
21405 			tcp->tcp_state = TCPS_LISTEN;
21406 			/* Initialize the chain. Don't need the eager_lock */
21407 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
21408 			tcp->tcp_eager_next_drop_q0 = tcp;
21409 			tcp->tcp_eager_prev_drop_q0 = tcp;
21410 			tcp->tcp_second_ctimer_threshold =
21411 			    tcps->tcps_ip_abort_linterval;
21412 		}
21413 	}
21414 
21415 	/*
21416 	 * We need to make sure that the conn_recv is set to a non-null
21417 	 * value before we insert the conn into the classifier table.
21418 	 * This is to avoid a race with an incoming packet which does an
21419 	 * ipcl_classify().
21420 	 * We initially set it to tcp_input_listener_unbound to try to
21421 	 * pick a good squeue for the listener when the first SYN arrives.
21422 	 * tcp_input_listener_unbound sets it to tcp_input_listener on that
21423 	 * first SYN.
21424 	 */
21425 	connp->conn_recv = tcp_input_listener_unbound;
21426 
21427 	/* Insert the listener in the classifier table */
21428 	error = ip_laddr_fanout_insert(connp);
21429 	if (error != 0) {
21430 		/* Undo the bind - release the port number */
21431 		tcp->tcp_state = TCPS_IDLE;
21432 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
21433 
21434 		connp->conn_laddr_v6 = ipv6_all_zeros;
21435 		connp->conn_saddr_v6 = ipv6_all_zeros;
21436 		connp->conn_ports = 0;
21437 
21438 		if (connp->conn_anon_port) {
21439 			zone_t		*zone;
21440 
21441 			zone = crgetzone(cr);
21442 			connp->conn_anon_port = B_FALSE;
21443 			(void) tsol_mlp_anon(zone, connp->conn_mlp_type,
21444 			    connp->conn_proto, connp->conn_lport, B_FALSE);
21445 		}
21446 		connp->conn_mlp_type = mlptSingle;
21447 
21448 		tcp_bind_hash_remove(tcp);
21449 		return (error);
21450 	}
21451 	return (error);
21452 }
21453 
21454 void
21455 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
21456 {
21457 	conn_t  *connp = (conn_t *)proto_handle;
21458 	tcp_t	*tcp = connp->conn_tcp;
21459 	mblk_t *mp;
21460 	int error;
21461 
21462 	ASSERT(connp->conn_upper_handle != NULL);
21463 
21464 	/*
21465 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
21466 	 * is currently running.
21467 	 */
21468 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21469 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
21470 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
21471 		return;
21472 	}
21473 	tcp->tcp_rsrv_mp = NULL;
21474 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21475 
21476 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
21477 	ASSERT(error == 0);
21478 
21479 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21480 	tcp->tcp_rsrv_mp = mp;
21481 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21482 
21483 	if (tcp->tcp_fused) {
21484 		tcp_fuse_backenable(tcp);
21485 	} else {
21486 		tcp->tcp_rwnd = connp->conn_rcvbuf;
21487 		/*
21488 		 * Send back a window update immediately if TCP is above
21489 		 * ESTABLISHED state and the increase of the rcv window
21490 		 * that the other side knows is at least 1 MSS after flow
21491 		 * control is lifted.
21492 		 */
21493 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
21494 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
21495 			tcp_xmit_ctl(NULL, tcp,
21496 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
21497 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21498 		}
21499 	}
21500 
21501 	squeue_synch_exit(connp->conn_sqp, connp);
21502 }
21503 
21504 /* ARGSUSED */
21505 int
21506 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
21507     int mode, int32_t *rvalp, cred_t *cr)
21508 {
21509 	conn_t  	*connp = (conn_t *)proto_handle;
21510 	int		error;
21511 
21512 	ASSERT(connp->conn_upper_handle != NULL);
21513 
21514 	/* All Solaris components should pass a cred for this operation. */
21515 	ASSERT(cr != NULL);
21516 
21517 	/*
21518 	 * If we don't have a helper stream then create one.
21519 	 * ip_create_helper_stream takes care of locking the conn_t,
21520 	 * so this check for NULL is just a performance optimization.
21521 	 */
21522 	if (connp->conn_helper_info == NULL) {
21523 		tcp_stack_t *tcps = connp->conn_tcp->tcp_tcps;
21524 
21525 		/*
21526 		 * Create a helper stream for non-STREAMS socket.
21527 		 */
21528 		error = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
21529 		if (error != 0) {
21530 			ip0dbg(("tcp_ioctl: create of IP helper stream "
21531 			    "failed %d\n", error));
21532 			return (error);
21533 		}
21534 	}
21535 
21536 	switch (cmd) {
21537 		case ND_SET:
21538 		case ND_GET:
21539 		case _SIOCSOCKFALLBACK:
21540 		case TCP_IOC_ABORT_CONN:
21541 		case TI_GETPEERNAME:
21542 		case TI_GETMYNAME:
21543 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
21544 			    cmd));
21545 			error = EINVAL;
21546 			break;
21547 		default:
21548 			/*
21549 			 * Pass on to IP using helper stream
21550 			 */
21551 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
21552 			    cmd, arg, mode, cr, rvalp);
21553 			break;
21554 	}
21555 	return (error);
21556 }
21557 
21558 sock_downcalls_t sock_tcp_downcalls = {
21559 	tcp_activate,
21560 	tcp_accept,
21561 	tcp_bind,
21562 	tcp_listen,
21563 	tcp_connect,
21564 	tcp_getpeername,
21565 	tcp_getsockname,
21566 	tcp_getsockopt,
21567 	tcp_setsockopt,
21568 	tcp_sendmsg,
21569 	NULL,
21570 	NULL,
21571 	NULL,
21572 	tcp_shutdown,
21573 	tcp_clr_flowctrl,
21574 	tcp_ioctl,
21575 	tcp_close,
21576 };
21577