xref: /titanic_41/usr/src/uts/common/inet/tcp/tcp.c (revision 7a17cfad7ff3427e1ce7ecdbf566e442a7025ec9)
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 /*
547  * Size of acceptor hash list.  It has to be a power of 2 for hashing.
548  */
549 #define	TCP_ACCEPTOR_FANOUT_SIZE		256
550 
551 #ifdef	_ILP32
552 #define	TCP_ACCEPTOR_HASH(accid)					\
553 		(((uint_t)(accid) >> 8) & (TCP_ACCEPTOR_FANOUT_SIZE - 1))
554 #else
555 #define	TCP_ACCEPTOR_HASH(accid)					\
556 		((uint_t)(accid) & (TCP_ACCEPTOR_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  * If there is a limit set on the number of connections allowed per each
565  * listener, the following struct is used to store that counter.  This needs
566  * to be separated from the listener since the listener can go away before
567  * all the connections are gone.  When the struct is allocated, tlc_cnt is set
568  * to 1.  When the listener goes away, tlc_cnt is decremented  by one.  And
569  * the last connection (or the listener) which decrements tlc_cnt to zero
570  * frees the struct.
571  *
572  * tlc_max is the threshold value tcps_conn_listen_port.  It is set when the
573  * tcp_listen_cnt_t is allocated.
574  *
575  * tlc_report_time stores the time when cmn_err() is called to report that the
576  * max has been exceeeded.  Report is done at most once every
577  * TCP_TLC_REPORT_INTERVAL mins for a listener.
578  *
579  * tlc_drop stores the number of connection attempt dropped because the
580  * limit has reached.
581  */
582 typedef struct tcp_listen_cnt_s {
583 	uint32_t	tlc_max;
584 	uint32_t	tlc_cnt;
585 	int64_t		tlc_report_time;
586 	uint32_t	tlc_drop;
587 } tcp_listen_cnt_t;
588 
589 #define	TCP_TLC_REPORT_INTERVAL	(1 * MINUTES)
590 
591 #define	TCP_DECR_LISTEN_CNT(tcp)					\
592 {									\
593 	ASSERT((tcp)->tcp_listen_cnt->tlc_cnt > 0);			\
594 	if (atomic_add_32_nv(&(tcp)->tcp_listen_cnt->tlc_cnt, -1) == 0) \
595 		kmem_free((tcp)->tcp_listen_cnt, sizeof (tcp_listen_cnt_t)); \
596 	(tcp)->tcp_listen_cnt = NULL;					\
597 }
598 
599 /* Minimum number of connections per listener. */
600 uint32_t tcp_min_conn_listener = 2;
601 
602 /*
603  * Linked list struct to store listener connection limit configuration per
604  * IP stack.
605  */
606 typedef struct tcp_listener_s {
607 	in_port_t	tl_port;
608 	uint32_t	tl_ratio;
609 	list_node_t	tl_link;
610 } tcp_listener_t;
611 
612 /*
613  * The shift factor applied to tcp_mss to decide if the peer sends us a
614  * valid initial receive window.  By default, if the peer receive window
615  * is smaller than 1 MSS (shift factor is 0), it is considered as invalid.
616  */
617 uint32_t tcp_init_wnd_shft = 0;
618 
619 /*
620  * When the system is under memory pressure, stack variable tcps_reclaim is
621  * true, we shorten the connection timeout abort interval to tcp_early_abort
622  * seconds.
623  */
624 uint32_t tcp_early_abort = 30;
625 
626 /*
627  * TCP options struct returned from tcp_parse_options.
628  */
629 typedef struct tcp_opt_s {
630 	uint32_t	tcp_opt_mss;
631 	uint32_t	tcp_opt_wscale;
632 	uint32_t	tcp_opt_ts_val;
633 	uint32_t	tcp_opt_ts_ecr;
634 	tcp_t		*tcp;
635 } tcp_opt_t;
636 
637 /*
638  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
639  */
640 
641 #ifdef _BIG_ENDIAN
642 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
643 	(TCPOPT_TSTAMP << 8) | 10)
644 #else
645 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
646 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
647 #endif
648 
649 /*
650  * Flags returned from tcp_parse_options.
651  */
652 #define	TCP_OPT_MSS_PRESENT	1
653 #define	TCP_OPT_WSCALE_PRESENT	2
654 #define	TCP_OPT_TSTAMP_PRESENT	4
655 #define	TCP_OPT_SACK_OK_PRESENT	8
656 #define	TCP_OPT_SACK_PRESENT	16
657 
658 /* TCP option length */
659 #define	TCPOPT_NOP_LEN		1
660 #define	TCPOPT_MAXSEG_LEN	4
661 #define	TCPOPT_WS_LEN		3
662 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
663 #define	TCPOPT_TSTAMP_LEN	10
664 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
665 #define	TCPOPT_SACK_OK_LEN	2
666 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
667 #define	TCPOPT_REAL_SACK_LEN	4
668 #define	TCPOPT_MAX_SACK_LEN	36
669 #define	TCPOPT_HEADER_LEN	2
670 
671 /* TCP cwnd burst factor. */
672 #define	TCP_CWND_INFINITE	65535
673 #define	TCP_CWND_SS		3
674 #define	TCP_CWND_NORMAL		5
675 
676 /* Maximum TCP initial cwin (start/restart). */
677 #define	TCP_MAX_INIT_CWND	8
678 
679 /*
680  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
681  * either tcp_slow_start_initial or tcp_slow_start_after idle
682  * depending on the caller.  If the upper layer has not used the
683  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
684  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
685  * If the upper layer has changed set the tcp_init_cwnd, just use
686  * it to calculate the tcp_cwnd.
687  */
688 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
689 {									\
690 	if ((tcp)->tcp_init_cwnd == 0) {				\
691 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
692 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
693 	} else {							\
694 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
695 	}								\
696 	tcp->tcp_cwnd_cnt = 0;						\
697 }
698 
699 /* TCP Timer control structure */
700 typedef struct tcpt_s {
701 	pfv_t	tcpt_pfv;	/* The routine we are to call */
702 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
703 } tcpt_t;
704 
705 /*
706  * Functions called directly via squeue having a prototype of edesc_t.
707  */
708 void		tcp_input_listener(void *arg, mblk_t *mp, void *arg2,
709     ip_recv_attr_t *ira);
710 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2,
711     ip_recv_attr_t *dummy);
712 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2,
713     ip_recv_attr_t *dummy);
714 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2,
715     ip_recv_attr_t *dummy);
716 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2,
717     ip_recv_attr_t *dummy);
718 void		tcp_input_data(void *arg, mblk_t *mp, void *arg2,
719     ip_recv_attr_t *ira);
720 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2,
721     ip_recv_attr_t *dummy);
722 void		tcp_output(void *arg, mblk_t *mp, void *arg2,
723     ip_recv_attr_t *dummy);
724 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2,
725     ip_recv_attr_t *dummy);
726 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2,
727     ip_recv_attr_t *dummy);
728 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2,
729     ip_recv_attr_t *dummy);
730 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2,
731     ip_recv_attr_t *dummy);
732 static void	tcp_send_synack(void *arg, mblk_t *mp, void *arg2,
733     ip_recv_attr_t *dummy);
734 
735 
736 /* Prototype for TCP functions */
737 static void	tcp_random_init(void);
738 int		tcp_random(void);
739 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
740 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
741 		    tcp_t *eager);
742 static int	tcp_set_destination(tcp_t *tcp);
743 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
744     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
745     boolean_t user_specified);
746 static void	tcp_closei_local(tcp_t *tcp);
747 static void	tcp_close_detached(tcp_t *tcp);
748 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr,
749 		    mblk_t *idmp, mblk_t **defermp, ip_recv_attr_t *ira);
750 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
751 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
752 		    in_port_t dstport, uint_t srcid);
753 static int	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
754 		    in_port_t dstport, uint32_t flowinfo,
755 		    uint_t srcid, uint32_t scope_id);
756 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
757 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
758 static char	*tcp_display(tcp_t *tcp, char *, char);
759 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
760 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
761 static void	tcp_eager_unlink(tcp_t *tcp);
762 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
763 		    int unixerr);
764 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
765 		    int tlierr, int unixerr);
766 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
767 		    cred_t *cr);
768 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
769 		    char *value, caddr_t cp, cred_t *cr);
770 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
771 		    char *value, caddr_t cp, cred_t *cr);
772 static int	tcp_tpistate(tcp_t *tcp);
773 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
774     int caller_holds_lock);
775 static void	tcp_bind_hash_remove(tcp_t *tcp);
776 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
777 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
778 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
779 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
780 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
781 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
782 static void	tcp_init_values(tcp_t *tcp);
783 static void	tcp_ip_notify(tcp_t *tcp);
784 static void	tcp_iss_init(tcp_t *tcp);
785 static void	tcp_keepalive_killer(void *arg);
786 static int	tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt);
787 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
788 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
789 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
790 static boolean_t tcp_allow_connopt_set(int level, int name);
791 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
792 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
793 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
794     tcp_stack_t *);
795 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
796 		    caddr_t cp, cred_t *cr);
797 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
798 		    caddr_t cp, cred_t *cr);
799 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
800 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
801 		    caddr_t cp, cred_t *cr);
802 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
803 static void	tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt);
804 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
805 static void	tcp_reass_timer(void *arg);
806 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
807 static void	tcp_reinit(tcp_t *tcp);
808 static void	tcp_reinit_values(tcp_t *tcp);
809 
810 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
811 static uint_t	tcp_rcv_drain(tcp_t *tcp);
812 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
813 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
814 static void	tcp_ss_rexmit(tcp_t *tcp);
815 static mblk_t	*tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
816     ip_recv_attr_t *);
817 static void	tcp_process_options(tcp_t *, tcpha_t *);
818 static void	tcp_rsrv(queue_t *q);
819 static int	tcp_snmp_state(tcp_t *tcp);
820 static void	tcp_timer(void *arg);
821 static void	tcp_timer_callback(void *);
822 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
823     boolean_t random);
824 static in_port_t tcp_get_next_priv_port(const tcp_t *);
825 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
826 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
827 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
828 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
829 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
830 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
831 static int	tcp_send(tcp_t *tcp, const int mss,
832 		    const int total_hdr_len, const int tcp_hdr_len,
833 		    const int num_sack_blk, int *usable, uint_t *snxt,
834 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time);
835 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
836 		    int num_sack_blk);
837 static void	tcp_wsrv(queue_t *q);
838 static int	tcp_xmit_end(tcp_t *tcp);
839 static void	tcp_ack_timer(void *arg);
840 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
841 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
842 		    uint32_t seq, uint32_t ack, int ctl, ip_recv_attr_t *,
843 		    ip_stack_t *, conn_t *);
844 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
845 		    uint32_t ack, int ctl);
846 static void	tcp_set_rto(tcp_t *, time_t);
847 static void	tcp_icmp_input(void *, mblk_t *, void *, ip_recv_attr_t *);
848 static void	tcp_icmp_error_ipv6(tcp_t *, mblk_t *, ip_recv_attr_t *);
849 static boolean_t tcp_verifyicmp(conn_t *, void *, icmph_t *, icmp6_t *,
850     ip_recv_attr_t *);
851 static int	tcp_build_hdrs(tcp_t *);
852 static void	tcp_time_wait_append(tcp_t *tcp);
853 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
854     uint32_t seg_seq, uint32_t seg_ack, int seg_len, tcpha_t *tcpha,
855     ip_recv_attr_t *ira);
856 boolean_t	tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp);
857 static boolean_t tcp_zcopy_check(tcp_t *);
858 static void	tcp_zcopy_notify(tcp_t *);
859 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, boolean_t);
860 static void	tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa);
861 static void	tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only);
862 static void	tcp_update_zcopy(tcp_t *tcp);
863 static void	tcp_notify(void *, ip_xmit_attr_t *, ixa_notify_type_t,
864     ixa_notify_arg_t);
865 static void	tcp_rexmit_after_error(tcp_t *tcp);
866 static void	tcp_send_data(tcp_t *, mblk_t *);
867 extern mblk_t	*tcp_timermp_alloc(int);
868 extern void	tcp_timermp_free(tcp_t *);
869 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
870 static void	tcp_stop_lingering(tcp_t *tcp);
871 static void	tcp_close_linger_timeout(void *arg);
872 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
873 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
874 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
875 static void	tcp_g_kstat_fini(kstat_t *);
876 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
877 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
878 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
879 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
880 static int	tcp_kstat_update(kstat_t *kp, int rw);
881 static mblk_t	*tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
882     ip_recv_attr_t *ira);
883 static mblk_t	*tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
884     ip_recv_attr_t *ira);
885 static int	tcp_squeue_switch(int);
886 
887 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
888 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
889 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
890 static int	tcp_tpi_close(queue_t *, int);
891 static int	tcp_tpi_close_accept(queue_t *);
892 
893 static void	tcp_squeue_add(squeue_t *);
894 static void	tcp_setcred_data(mblk_t *, ip_recv_attr_t *);
895 
896 extern void	tcp_kssl_input(tcp_t *, mblk_t *, cred_t *);
897 
898 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy);
899 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
900     ip_recv_attr_t *dummy);
901 
902 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
903 	    sock_upper_handle_t, cred_t *);
904 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
905 static int tcp_do_listen(conn_t *, struct sockaddr *, socklen_t, int, cred_t *,
906     boolean_t);
907 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
908     cred_t *, pid_t);
909 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
910     boolean_t);
911 static int tcp_do_unbind(conn_t *);
912 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
913     boolean_t);
914 
915 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_t *);
916 
917 static uint32_t tcp_find_listener_conf(tcp_stack_t *, in_port_t);
918 static int tcp_listener_conf_get(queue_t *, mblk_t *, caddr_t, cred_t *);
919 static int tcp_listener_conf_add(queue_t *, mblk_t *, char *, caddr_t,
920     cred_t *);
921 static int tcp_listener_conf_del(queue_t *, mblk_t *, char *, caddr_t,
922     cred_t *);
923 static void tcp_listener_conf_cleanup(tcp_stack_t *);
924 
925 /*
926  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
927  *
928  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
929  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
930  * (defined in tcp.h) needs to be filled in and passed into the kernel
931  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
932  * structure contains the four-tuple of a TCP connection and a range of TCP
933  * states (specified by ac_start and ac_end). The use of wildcard addresses
934  * and ports is allowed. Connections with a matching four tuple and a state
935  * within the specified range will be aborted. The valid states for the
936  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
937  * inclusive.
938  *
939  * An application which has its connection aborted by this ioctl will receive
940  * an error that is dependent on the connection state at the time of the abort.
941  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
942  * though a RST packet has been received.  If the connection state is equal to
943  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
944  * and all resources associated with the connection will be freed.
945  */
946 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
947 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
948 static void	tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
949     ip_recv_attr_t *dummy);
950 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
951 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
952 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
953     boolean_t, tcp_stack_t *);
954 
955 static struct module_info tcp_rinfo =  {
956 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
957 };
958 
959 static struct module_info tcp_winfo =  {
960 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
961 };
962 
963 /*
964  * Entry points for TCP as a device. The normal case which supports
965  * the TCP functionality.
966  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
967  */
968 struct qinit tcp_rinitv4 = {
969 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
970 };
971 
972 struct qinit tcp_rinitv6 = {
973 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
974 };
975 
976 struct qinit tcp_winit = {
977 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
978 };
979 
980 /* Initial entry point for TCP in socket mode. */
981 struct qinit tcp_sock_winit = {
982 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
983 };
984 
985 /* TCP entry point during fallback */
986 struct qinit tcp_fallback_sock_winit = {
987 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
988 };
989 
990 /*
991  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
992  * an accept. Avoid allocating data structures since eager has already
993  * been created.
994  */
995 struct qinit tcp_acceptor_rinit = {
996 	NULL, (pfi_t)tcp_rsrv, NULL, tcp_tpi_close_accept, NULL, &tcp_winfo
997 };
998 
999 struct qinit tcp_acceptor_winit = {
1000 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1001 };
1002 
1003 /* For AF_INET aka /dev/tcp */
1004 struct streamtab tcpinfov4 = {
1005 	&tcp_rinitv4, &tcp_winit
1006 };
1007 
1008 /* For AF_INET6 aka /dev/tcp6 */
1009 struct streamtab tcpinfov6 = {
1010 	&tcp_rinitv6, &tcp_winit
1011 };
1012 
1013 sock_downcalls_t sock_tcp_downcalls;
1014 
1015 /* Setable only in /etc/system. Move to ndd? */
1016 boolean_t tcp_icmp_source_quench = B_FALSE;
1017 
1018 /*
1019  * Following assumes TPI alignment requirements stay along 32 bit
1020  * boundaries
1021  */
1022 #define	ROUNDUP32(x) \
1023 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1024 
1025 /* Template for response to info request. */
1026 static struct T_info_ack tcp_g_t_info_ack = {
1027 	T_INFO_ACK,		/* PRIM_type */
1028 	0,			/* TSDU_size */
1029 	T_INFINITE,		/* ETSDU_size */
1030 	T_INVALID,		/* CDATA_size */
1031 	T_INVALID,		/* DDATA_size */
1032 	sizeof (sin_t),		/* ADDR_size */
1033 	0,			/* OPT_size - not initialized here */
1034 	TIDUSZ,			/* TIDU_size */
1035 	T_COTS_ORD,		/* SERV_type */
1036 	TCPS_IDLE,		/* CURRENT_state */
1037 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1038 };
1039 
1040 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1041 	T_INFO_ACK,		/* PRIM_type */
1042 	0,			/* TSDU_size */
1043 	T_INFINITE,		/* ETSDU_size */
1044 	T_INVALID,		/* CDATA_size */
1045 	T_INVALID,		/* DDATA_size */
1046 	sizeof (sin6_t),	/* ADDR_size */
1047 	0,			/* OPT_size - not initialized here */
1048 	TIDUSZ,		/* TIDU_size */
1049 	T_COTS_ORD,		/* SERV_type */
1050 	TCPS_IDLE,		/* CURRENT_state */
1051 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1052 };
1053 
1054 #define	MS	1L
1055 #define	SECONDS	(1000 * MS)
1056 #define	MINUTES	(60 * SECONDS)
1057 #define	HOURS	(60 * MINUTES)
1058 #define	DAYS	(24 * HOURS)
1059 
1060 #define	PARAM_MAX (~(uint32_t)0)
1061 
1062 /* Max size IP datagram is 64k - 1 */
1063 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcpha_t)))
1064 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcpha_t)))
1065 /* Max of the above */
1066 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1067 
1068 /* Largest TCP port number */
1069 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1070 
1071 /*
1072  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1073  * layer header.  It has to be a multiple of 4.
1074  */
1075 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1076 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1077 
1078 #define	MB	(1024 * 1024)
1079 
1080 /*
1081  * All of these are alterable, within the min/max values given, at run time.
1082  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1083  * per the TCP spec.
1084  */
1085 /* BEGIN CSTYLED */
1086 static tcpparam_t	lcl_tcp_param_arr[] = {
1087  /*min		max		value		name */
1088  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1089  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1090  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1091  { 1,		1024,		1,		"tcp_conn_req_min" },
1092  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1093  { 128,		(1<<30),	1*MB,		"tcp_cwnd_max" },
1094  { 0,		10,		0,		"tcp_debug" },
1095  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1096  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1097  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1098  { 500*MS,	PARAM_MAX,	5*MINUTES,	"tcp_ip_abort_interval"},
1099  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1100  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1101  { 1,		255,		64,		"tcp_ipv4_ttl"},
1102  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1103  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1104  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1105  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1106  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1107  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1108  { 1*MS,	20*SECONDS,	1*SECONDS,	"tcp_rexmit_interval_initial"},
1109  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1110  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1111  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1112  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1113  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1114  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1115  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1116  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1117  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1118  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1119  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1120  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1121  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1122  { 8192,	(1<<30),	1*MB,		"tcp_max_buf"},
1123 /*
1124  * Question:  What default value should I set for tcp_strong_iss?
1125  */
1126  { 0,		2,		1,		"tcp_strong_iss"},
1127  { 0,		65536,		20,		"tcp_rtt_updates"},
1128  { 0,		1,		1,		"tcp_wscale_always"},
1129  { 0,		1,		0,		"tcp_tstamp_always"},
1130  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1131  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1132  { 0,		16,		2,		"tcp_deferred_acks_max"},
1133  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1134  { 1,		4,		4,		"tcp_slow_start_initial"},
1135  { 0,		2,		2,		"tcp_sack_permitted"},
1136  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1137  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1138  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1139  { 0,		1,		0,		"tcp_rev_src_routes"},
1140  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1141  { 0,		16,		8,		"tcp_local_dacks_max"},
1142  { 0,		2,		1,		"tcp_ecn_permitted"},
1143  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1144  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1145  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1146  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1147  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1148  { 0,		1,		0,		"tcp_dev_flow_ctl"},
1149  { 0,		PARAM_MAX,	100*SECONDS,	"tcp_reass_timeout"}
1150 };
1151 /* END CSTYLED */
1152 
1153 /* Round up the value to the nearest mss. */
1154 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1155 
1156 /*
1157  * Set ECN capable transport (ECT) code point in IP header.
1158  *
1159  * Note that there are 2 ECT code points '01' and '10', which are called
1160  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1161  * point ECT(0) for TCP as described in RFC 2481.
1162  */
1163 #define	SET_ECT(tcp, iph) \
1164 	if ((tcp)->tcp_connp->conn_ipversion == IPV4_VERSION) { \
1165 		/* We need to clear the code point first. */ \
1166 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1167 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1168 	} else { \
1169 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1170 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1171 	}
1172 
1173 /*
1174  * The format argument to pass to tcp_display().
1175  * DISP_PORT_ONLY means that the returned string has only port info.
1176  * DISP_ADDR_AND_PORT means that the returned string also contains the
1177  * remote and local IP address.
1178  */
1179 #define	DISP_PORT_ONLY		1
1180 #define	DISP_ADDR_AND_PORT	2
1181 
1182 #define	IS_VMLOANED_MBLK(mp) \
1183 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1184 
1185 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1186 
1187 /*
1188  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1189  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1190  * determined dynamically during tcp_set_destination(), which is the default.
1191  */
1192 boolean_t tcp_static_maxpsz = B_FALSE;
1193 
1194 /* Setable in /etc/system */
1195 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1196 uint32_t tcp_random_anon_port = 1;
1197 
1198 /*
1199  * To reach to an eager in Q0 which can be dropped due to an incoming
1200  * new SYN request when Q0 is full, a new doubly linked list is
1201  * introduced. This list allows to select an eager from Q0 in O(1) time.
1202  * This is needed to avoid spending too much time walking through the
1203  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1204  * this new list has to be a member of Q0.
1205  * This list is headed by listener's tcp_t. When the list is empty,
1206  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1207  * of listener's tcp_t point to listener's tcp_t itself.
1208  *
1209  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1210  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1211  * These macros do not affect the eager's membership to Q0.
1212  */
1213 
1214 
1215 #define	MAKE_DROPPABLE(listener, eager)					\
1216 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1217 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1218 		    = (eager);						\
1219 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1220 		(eager)->tcp_eager_next_drop_q0 =			\
1221 		    (listener)->tcp_eager_next_drop_q0;			\
1222 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1223 	}
1224 
1225 #define	MAKE_UNDROPPABLE(eager)						\
1226 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1227 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1228 		    = (eager)->tcp_eager_prev_drop_q0;			\
1229 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1230 		    = (eager)->tcp_eager_next_drop_q0;			\
1231 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1232 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1233 	}
1234 
1235 /*
1236  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1237  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1238  * data, TCP will not respond with an ACK.  RFC 793 requires that
1239  * TCP responds with an ACK for such a bogus ACK.  By not following
1240  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1241  * an attacker successfully spoofs an acceptable segment to our
1242  * peer; or when our peer is "confused."
1243  */
1244 uint32_t tcp_drop_ack_unsent_cnt = 10;
1245 
1246 /*
1247  * Hook functions to enable cluster networking
1248  * On non-clustered systems these vectors must always be NULL.
1249  */
1250 
1251 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1252 			    sa_family_t addr_family, uint8_t *laddrp,
1253 			    in_port_t lport, void *args) = NULL;
1254 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1255 			    sa_family_t addr_family, uint8_t *laddrp,
1256 			    in_port_t lport, void *args) = NULL;
1257 
1258 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1259 			    boolean_t is_outgoing,
1260 			    sa_family_t addr_family,
1261 			    uint8_t *laddrp, in_port_t lport,
1262 			    uint8_t *faddrp, in_port_t fport,
1263 			    void *args) = NULL;
1264 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1265 			    sa_family_t addr_family, uint8_t *laddrp,
1266 			    in_port_t lport, uint8_t *faddrp,
1267 			    in_port_t fport, void *args) = NULL;
1268 
1269 
1270 /*
1271  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1272  */
1273 #define	CL_INET_CONNECT(connp, is_outgoing, err) {		\
1274 	(err) = 0;						\
1275 	if (cl_inet_connect2 != NULL) {				\
1276 		/*						\
1277 		 * Running in cluster mode - register active connection	\
1278 		 * information						\
1279 		 */							\
1280 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1281 			if ((connp)->conn_laddr_v4 != 0) {		\
1282 				(err) = (*cl_inet_connect2)(		\
1283 				    (connp)->conn_netstack->netstack_stackid,\
1284 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1285 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1286 				    (in_port_t)(connp)->conn_lport,	\
1287 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1288 				    (in_port_t)(connp)->conn_fport, NULL); \
1289 			}						\
1290 		} else {						\
1291 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1292 			    &(connp)->conn_laddr_v6)) {			\
1293 				(err) = (*cl_inet_connect2)(		\
1294 				    (connp)->conn_netstack->netstack_stackid,\
1295 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1296 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1297 				    (in_port_t)(connp)->conn_lport,	\
1298 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1299 				    (in_port_t)(connp)->conn_fport, NULL); \
1300 			}						\
1301 		}							\
1302 	}								\
1303 }
1304 
1305 #define	CL_INET_DISCONNECT(connp)	{				\
1306 	if (cl_inet_disconnect != NULL) {				\
1307 		/*							\
1308 		 * Running in cluster mode - deregister active		\
1309 		 * connection information				\
1310 		 */							\
1311 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1312 			if ((connp)->conn_laddr_v4 != 0) {		\
1313 				(*cl_inet_disconnect)(			\
1314 				    (connp)->conn_netstack->netstack_stackid,\
1315 				    IPPROTO_TCP, AF_INET,		\
1316 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1317 				    (in_port_t)(connp)->conn_lport,	\
1318 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1319 				    (in_port_t)(connp)->conn_fport, NULL); \
1320 			}						\
1321 		} else {						\
1322 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1323 			    &(connp)->conn_laddr_v6)) {			\
1324 				(*cl_inet_disconnect)(			\
1325 				    (connp)->conn_netstack->netstack_stackid,\
1326 				    IPPROTO_TCP, AF_INET6,		\
1327 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1328 				    (in_port_t)(connp)->conn_lport,	\
1329 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1330 				    (in_port_t)(connp)->conn_fport, NULL); \
1331 			}						\
1332 		}							\
1333 	}								\
1334 }
1335 
1336 /*
1337  * Steps to do when a tcp_t moves to TIME-WAIT state.
1338  *
1339  * This connection is done, we don't need to account for it.  Decrement
1340  * the listener connection counter if needed.
1341  *
1342  * Unconditionally clear the exclusive binding bit so this TIME-WAIT
1343  * connection won't interfere with new ones.
1344  *
1345  * Start the TIME-WAIT timer.  If upper layer has not closed the connection,
1346  * the timer is handled within the context of this tcp_t.  When the timer
1347  * fires, tcp_clean_death() is called.  If upper layer closes the connection
1348  * during this period, tcp_time_wait_append() will be called to add this
1349  * tcp_t to the global TIME-WAIT list.  Note that this means that the
1350  * actual wait time in TIME-WAIT state will be longer than the
1351  * tcps_time_wait_interval since the period before upper layer closes the
1352  * connection is not accounted for when tcp_time_wait_append() is called.
1353  *
1354  * If uppser layer has closed the connection, call tcp_time_wait_append()
1355  * directly.
1356  */
1357 #define	SET_TIME_WAIT(tcps, tcp, connp)				\
1358 {								\
1359 	(tcp)->tcp_state = TCPS_TIME_WAIT;			\
1360 	if ((tcp)->tcp_listen_cnt != NULL)			\
1361 		TCP_DECR_LISTEN_CNT(tcp);			\
1362 	(connp)->conn_exclbind = 0;				\
1363 	if (!TCP_IS_DETACHED(tcp)) {				\
1364 		TCP_TIMER_RESTART(tcp, (tcps)->tcps_time_wait_interval); \
1365 	} else {						\
1366 		tcp_time_wait_append(tcp);			\
1367 		TCP_DBGSTAT(tcps, tcp_rput_time_wait);		\
1368 	}							\
1369 }
1370 
1371 /*
1372  * Cluster networking hook for traversing current connection list.
1373  * This routine is used to extract the current list of live connections
1374  * which must continue to to be dispatched to this node.
1375  */
1376 int cl_tcp_walk_list(netstackid_t stack_id,
1377     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1378 
1379 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1380     void *arg, tcp_stack_t *tcps);
1381 
1382 static void
1383 tcp_set_recv_threshold(tcp_t *tcp, uint32_t new_rcvthresh)
1384 {
1385 	uint32_t default_threshold = SOCKET_RECVHIWATER >> 3;
1386 
1387 	if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
1388 		conn_t *connp = tcp->tcp_connp;
1389 		struct sock_proto_props sopp;
1390 
1391 		/*
1392 		 * only increase rcvthresh upto default_threshold
1393 		 */
1394 		if (new_rcvthresh > default_threshold)
1395 			new_rcvthresh = default_threshold;
1396 
1397 		sopp.sopp_flags = SOCKOPT_RCVTHRESH;
1398 		sopp.sopp_rcvthresh = new_rcvthresh;
1399 
1400 		(*connp->conn_upcalls->su_set_proto_props)
1401 		    (connp->conn_upper_handle, &sopp);
1402 	}
1403 }
1404 /*
1405  * Figure out the value of window scale opton.  Note that the rwnd is
1406  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1407  * We cannot find the scale value and then do a round up of tcp_rwnd
1408  * because the scale value may not be correct after that.
1409  *
1410  * Set the compiler flag to make this function inline.
1411  */
1412 static void
1413 tcp_set_ws_value(tcp_t *tcp)
1414 {
1415 	int i;
1416 	uint32_t rwnd = tcp->tcp_rwnd;
1417 
1418 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1419 	    i++, rwnd >>= 1)
1420 		;
1421 	tcp->tcp_rcv_ws = i;
1422 }
1423 
1424 /*
1425  * Remove a connection from the list of detached TIME_WAIT connections.
1426  * It returns B_FALSE if it can't remove the connection from the list
1427  * as the connection has already been removed from the list due to an
1428  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1429  */
1430 static boolean_t
1431 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1432 {
1433 	boolean_t	locked = B_FALSE;
1434 
1435 	if (tcp_time_wait == NULL) {
1436 		tcp_time_wait = *((tcp_squeue_priv_t **)
1437 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1438 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1439 		locked = B_TRUE;
1440 	} else {
1441 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1442 	}
1443 
1444 	if (tcp->tcp_time_wait_expire == 0) {
1445 		ASSERT(tcp->tcp_time_wait_next == NULL);
1446 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1447 		if (locked)
1448 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1449 		return (B_FALSE);
1450 	}
1451 	ASSERT(TCP_IS_DETACHED(tcp));
1452 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1453 
1454 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1455 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1456 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1457 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1458 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1459 			    NULL;
1460 		} else {
1461 			tcp_time_wait->tcp_time_wait_tail = NULL;
1462 		}
1463 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1464 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1465 		ASSERT(tcp->tcp_time_wait_next == NULL);
1466 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1467 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1468 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1469 	} else {
1470 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1471 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1472 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1473 		    tcp->tcp_time_wait_next;
1474 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1475 		    tcp->tcp_time_wait_prev;
1476 	}
1477 	tcp->tcp_time_wait_next = NULL;
1478 	tcp->tcp_time_wait_prev = NULL;
1479 	tcp->tcp_time_wait_expire = 0;
1480 
1481 	if (locked)
1482 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1483 	return (B_TRUE);
1484 }
1485 
1486 /*
1487  * Add a connection to the list of detached TIME_WAIT connections
1488  * and set its time to expire.
1489  */
1490 static void
1491 tcp_time_wait_append(tcp_t *tcp)
1492 {
1493 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1494 	tcp_squeue_priv_t *tcp_time_wait =
1495 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1496 	    SQPRIVATE_TCP));
1497 
1498 	tcp_timers_stop(tcp);
1499 
1500 	/* Freed above */
1501 	ASSERT(tcp->tcp_timer_tid == 0);
1502 	ASSERT(tcp->tcp_ack_tid == 0);
1503 
1504 	/* must have happened at the time of detaching the tcp */
1505 	ASSERT(tcp->tcp_ptpahn == NULL);
1506 	ASSERT(tcp->tcp_flow_stopped == 0);
1507 	ASSERT(tcp->tcp_time_wait_next == NULL);
1508 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1509 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1510 	ASSERT(tcp->tcp_listener == NULL);
1511 
1512 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1513 	/*
1514 	 * The value computed below in tcp->tcp_time_wait_expire may
1515 	 * appear negative or wrap around. That is ok since our
1516 	 * interest is only in the difference between the current lbolt
1517 	 * value and tcp->tcp_time_wait_expire. But the value should not
1518 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1519 	 * The corresponding comparison in tcp_time_wait_collector() uses
1520 	 * modular arithmetic.
1521 	 */
1522 	tcp->tcp_time_wait_expire +=
1523 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1524 	if (tcp->tcp_time_wait_expire == 0)
1525 		tcp->tcp_time_wait_expire = 1;
1526 
1527 	ASSERT(TCP_IS_DETACHED(tcp));
1528 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1529 	ASSERT(tcp->tcp_time_wait_next == NULL);
1530 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1531 	TCP_DBGSTAT(tcps, tcp_time_wait);
1532 
1533 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1534 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1535 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1536 		tcp_time_wait->tcp_time_wait_head = tcp;
1537 	} else {
1538 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1539 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1540 		    TCPS_TIME_WAIT);
1541 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1542 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1543 	}
1544 	tcp_time_wait->tcp_time_wait_tail = tcp;
1545 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1546 }
1547 
1548 /* ARGSUSED */
1549 void
1550 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1551 {
1552 	conn_t	*connp = (conn_t *)arg;
1553 	tcp_t	*tcp = connp->conn_tcp;
1554 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1555 
1556 	ASSERT(tcp != NULL);
1557 	if (tcp->tcp_state == TCPS_CLOSED) {
1558 		return;
1559 	}
1560 
1561 	ASSERT((connp->conn_family == AF_INET &&
1562 	    connp->conn_ipversion == IPV4_VERSION) ||
1563 	    (connp->conn_family == AF_INET6 &&
1564 	    (connp->conn_ipversion == IPV4_VERSION ||
1565 	    connp->conn_ipversion == IPV6_VERSION)));
1566 	ASSERT(!tcp->tcp_listener);
1567 
1568 	TCP_STAT(tcps, tcp_time_wait_reap);
1569 	ASSERT(TCP_IS_DETACHED(tcp));
1570 
1571 	/*
1572 	 * Because they have no upstream client to rebind or tcp_close()
1573 	 * them later, we axe the connection here and now.
1574 	 */
1575 	tcp_close_detached(tcp);
1576 }
1577 
1578 /*
1579  * Remove cached/latched IPsec references.
1580  */
1581 void
1582 tcp_ipsec_cleanup(tcp_t *tcp)
1583 {
1584 	conn_t		*connp = tcp->tcp_connp;
1585 
1586 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1587 
1588 	if (connp->conn_latch != NULL) {
1589 		IPLATCH_REFRELE(connp->conn_latch);
1590 		connp->conn_latch = NULL;
1591 	}
1592 	if (connp->conn_latch_in_policy != NULL) {
1593 		IPPOL_REFRELE(connp->conn_latch_in_policy);
1594 		connp->conn_latch_in_policy = NULL;
1595 	}
1596 	if (connp->conn_latch_in_action != NULL) {
1597 		IPACT_REFRELE(connp->conn_latch_in_action);
1598 		connp->conn_latch_in_action = NULL;
1599 	}
1600 	if (connp->conn_policy != NULL) {
1601 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1602 		connp->conn_policy = NULL;
1603 	}
1604 }
1605 
1606 /*
1607  * Cleaup before placing on free list.
1608  * Disassociate from the netstack/tcp_stack_t since the freelist
1609  * is per squeue and not per netstack.
1610  */
1611 void
1612 tcp_cleanup(tcp_t *tcp)
1613 {
1614 	mblk_t		*mp;
1615 	tcp_sack_info_t	*tcp_sack_info;
1616 	conn_t		*connp = tcp->tcp_connp;
1617 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1618 	netstack_t	*ns = tcps->tcps_netstack;
1619 	mblk_t		*tcp_rsrv_mp;
1620 
1621 	tcp_bind_hash_remove(tcp);
1622 
1623 	/* Cleanup that which needs the netstack first */
1624 	tcp_ipsec_cleanup(tcp);
1625 	ixa_cleanup(connp->conn_ixa);
1626 
1627 	if (connp->conn_ht_iphc != NULL) {
1628 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
1629 		connp->conn_ht_iphc = NULL;
1630 		connp->conn_ht_iphc_allocated = 0;
1631 		connp->conn_ht_iphc_len = 0;
1632 		connp->conn_ht_ulp = NULL;
1633 		connp->conn_ht_ulp_len = 0;
1634 		tcp->tcp_ipha = NULL;
1635 		tcp->tcp_ip6h = NULL;
1636 		tcp->tcp_tcpha = NULL;
1637 	}
1638 
1639 	/* We clear any IP_OPTIONS and extension headers */
1640 	ip_pkt_free(&connp->conn_xmit_ipp);
1641 
1642 	tcp_free(tcp);
1643 
1644 	/* Release any SSL context */
1645 	if (tcp->tcp_kssl_ent != NULL) {
1646 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1647 		tcp->tcp_kssl_ent = NULL;
1648 	}
1649 
1650 	if (tcp->tcp_kssl_ctx != NULL) {
1651 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1652 		tcp->tcp_kssl_ctx = NULL;
1653 	}
1654 	tcp->tcp_kssl_pending = B_FALSE;
1655 
1656 	/*
1657 	 * Since we will bzero the entire structure, we need to
1658 	 * remove it and reinsert it in global hash list. We
1659 	 * know the walkers can't get to this conn because we
1660 	 * had set CONDEMNED flag earlier and checked reference
1661 	 * under conn_lock so walker won't pick it and when we
1662 	 * go the ipcl_globalhash_remove() below, no walker
1663 	 * can get to it.
1664 	 */
1665 	ipcl_globalhash_remove(connp);
1666 
1667 	/* Save some state */
1668 	mp = tcp->tcp_timercache;
1669 
1670 	tcp_sack_info = tcp->tcp_sack_info;
1671 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1672 
1673 	if (connp->conn_cred != NULL) {
1674 		crfree(connp->conn_cred);
1675 		connp->conn_cred = NULL;
1676 	}
1677 	ipcl_conn_cleanup(connp);
1678 	connp->conn_flags = IPCL_TCPCONN;
1679 
1680 	/*
1681 	 * Now it is safe to decrement the reference counts.
1682 	 * This might be the last reference on the netstack
1683 	 * in which case it will cause the freeing of the IP Instance.
1684 	 */
1685 	connp->conn_netstack = NULL;
1686 	connp->conn_ixa->ixa_ipst = NULL;
1687 	netstack_rele(ns);
1688 	ASSERT(tcps != NULL);
1689 	tcp->tcp_tcps = NULL;
1690 
1691 	bzero(tcp, sizeof (tcp_t));
1692 
1693 	/* restore the state */
1694 	tcp->tcp_timercache = mp;
1695 
1696 	tcp->tcp_sack_info = tcp_sack_info;
1697 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1698 
1699 	tcp->tcp_connp = connp;
1700 
1701 	ASSERT(connp->conn_tcp == tcp);
1702 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1703 	connp->conn_state_flags = CONN_INCIPIENT;
1704 	ASSERT(connp->conn_proto == IPPROTO_TCP);
1705 	ASSERT(connp->conn_ref == 1);
1706 }
1707 
1708 /*
1709  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1710  * is done forwards from the head.
1711  * This walks all stack instances since
1712  * tcp_time_wait remains global across all stacks.
1713  */
1714 /* ARGSUSED */
1715 void
1716 tcp_time_wait_collector(void *arg)
1717 {
1718 	tcp_t *tcp;
1719 	clock_t now;
1720 	mblk_t *mp;
1721 	conn_t *connp;
1722 	kmutex_t *lock;
1723 	boolean_t removed;
1724 
1725 	squeue_t *sqp = (squeue_t *)arg;
1726 	tcp_squeue_priv_t *tcp_time_wait =
1727 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1728 
1729 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1730 	tcp_time_wait->tcp_time_wait_tid = 0;
1731 
1732 	if (tcp_time_wait->tcp_free_list != NULL &&
1733 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1734 		TCP_G_STAT(tcp_freelist_cleanup);
1735 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1736 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1737 			tcp->tcp_time_wait_next = NULL;
1738 			tcp_time_wait->tcp_free_list_cnt--;
1739 			ASSERT(tcp->tcp_tcps == NULL);
1740 			CONN_DEC_REF(tcp->tcp_connp);
1741 		}
1742 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1743 	}
1744 
1745 	/*
1746 	 * In order to reap time waits reliably, we should use a
1747 	 * source of time that is not adjustable by the user -- hence
1748 	 * the call to ddi_get_lbolt().
1749 	 */
1750 	now = ddi_get_lbolt();
1751 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1752 		/*
1753 		 * Compare times using modular arithmetic, since
1754 		 * lbolt can wrapover.
1755 		 */
1756 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1757 			break;
1758 		}
1759 
1760 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1761 		ASSERT(removed);
1762 
1763 		connp = tcp->tcp_connp;
1764 		ASSERT(connp->conn_fanout != NULL);
1765 		lock = &connp->conn_fanout->connf_lock;
1766 		/*
1767 		 * This is essentially a TW reclaim fast path optimization for
1768 		 * performance where the timewait collector checks under the
1769 		 * fanout lock (so that no one else can get access to the
1770 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1771 		 * the classifier hash list. If ref count is indeed 2, we can
1772 		 * just remove the conn under the fanout lock and avoid
1773 		 * cleaning up the conn under the squeue, provided that
1774 		 * clustering callbacks are not enabled. If clustering is
1775 		 * enabled, we need to make the clustering callback before
1776 		 * setting the CONDEMNED flag and after dropping all locks and
1777 		 * so we forego this optimization and fall back to the slow
1778 		 * path. Also please see the comments in tcp_closei_local
1779 		 * regarding the refcnt logic.
1780 		 *
1781 		 * Since we are holding the tcp_time_wait_lock, its better
1782 		 * not to block on the fanout_lock because other connections
1783 		 * can't add themselves to time_wait list. So we do a
1784 		 * tryenter instead of mutex_enter.
1785 		 */
1786 		if (mutex_tryenter(lock)) {
1787 			mutex_enter(&connp->conn_lock);
1788 			if ((connp->conn_ref == 2) &&
1789 			    (cl_inet_disconnect == NULL)) {
1790 				ipcl_hash_remove_locked(connp,
1791 				    connp->conn_fanout);
1792 				/*
1793 				 * Set the CONDEMNED flag now itself so that
1794 				 * the refcnt cannot increase due to any
1795 				 * walker.
1796 				 */
1797 				connp->conn_state_flags |= CONN_CONDEMNED;
1798 				mutex_exit(lock);
1799 				mutex_exit(&connp->conn_lock);
1800 				if (tcp_time_wait->tcp_free_list_cnt <
1801 				    tcp_free_list_max_cnt) {
1802 					/* Add to head of tcp_free_list */
1803 					mutex_exit(
1804 					    &tcp_time_wait->tcp_time_wait_lock);
1805 					tcp_cleanup(tcp);
1806 					ASSERT(connp->conn_latch == NULL);
1807 					ASSERT(connp->conn_policy == NULL);
1808 					ASSERT(tcp->tcp_tcps == NULL);
1809 					ASSERT(connp->conn_netstack == NULL);
1810 
1811 					mutex_enter(
1812 					    &tcp_time_wait->tcp_time_wait_lock);
1813 					tcp->tcp_time_wait_next =
1814 					    tcp_time_wait->tcp_free_list;
1815 					tcp_time_wait->tcp_free_list = tcp;
1816 					tcp_time_wait->tcp_free_list_cnt++;
1817 					continue;
1818 				} else {
1819 					/* Do not add to tcp_free_list */
1820 					mutex_exit(
1821 					    &tcp_time_wait->tcp_time_wait_lock);
1822 					tcp_bind_hash_remove(tcp);
1823 					ixa_cleanup(tcp->tcp_connp->conn_ixa);
1824 					tcp_ipsec_cleanup(tcp);
1825 					CONN_DEC_REF(tcp->tcp_connp);
1826 				}
1827 			} else {
1828 				CONN_INC_REF_LOCKED(connp);
1829 				mutex_exit(lock);
1830 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1831 				mutex_exit(&connp->conn_lock);
1832 				/*
1833 				 * We can reuse the closemp here since conn has
1834 				 * detached (otherwise we wouldn't even be in
1835 				 * time_wait list). tcp_closemp_used can safely
1836 				 * be changed without taking a lock as no other
1837 				 * thread can concurrently access it at this
1838 				 * point in the connection lifecycle.
1839 				 */
1840 
1841 				if (tcp->tcp_closemp.b_prev == NULL)
1842 					tcp->tcp_closemp_used = B_TRUE;
1843 				else
1844 					cmn_err(CE_PANIC,
1845 					    "tcp_timewait_collector: "
1846 					    "concurrent use of tcp_closemp: "
1847 					    "connp %p tcp %p\n", (void *)connp,
1848 					    (void *)tcp);
1849 
1850 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1851 				mp = &tcp->tcp_closemp;
1852 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1853 				    tcp_timewait_output, connp, NULL,
1854 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1855 			}
1856 		} else {
1857 			mutex_enter(&connp->conn_lock);
1858 			CONN_INC_REF_LOCKED(connp);
1859 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1860 			mutex_exit(&connp->conn_lock);
1861 			/*
1862 			 * We can reuse the closemp here since conn has
1863 			 * detached (otherwise we wouldn't even be in
1864 			 * time_wait list). tcp_closemp_used can safely
1865 			 * be changed without taking a lock as no other
1866 			 * thread can concurrently access it at this
1867 			 * point in the connection lifecycle.
1868 			 */
1869 
1870 			if (tcp->tcp_closemp.b_prev == NULL)
1871 				tcp->tcp_closemp_used = B_TRUE;
1872 			else
1873 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1874 				    "concurrent use of tcp_closemp: "
1875 				    "connp %p tcp %p\n", (void *)connp,
1876 				    (void *)tcp);
1877 
1878 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1879 			mp = &tcp->tcp_closemp;
1880 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1881 			    tcp_timewait_output, connp, NULL,
1882 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1883 		}
1884 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1885 	}
1886 
1887 	if (tcp_time_wait->tcp_free_list != NULL)
1888 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1889 
1890 	tcp_time_wait->tcp_time_wait_tid =
1891 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1892 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1893 	    CALLOUT_FLAG_ROUNDUP);
1894 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1895 }
1896 
1897 /*
1898  * Reply to a clients T_CONN_RES TPI message. This function
1899  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1900  * on the acceptor STREAM and processed in tcp_accept_common().
1901  * Read the block comment on top of tcp_input_listener().
1902  */
1903 static void
1904 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1905 {
1906 	tcp_t		*acceptor;
1907 	tcp_t		*eager;
1908 	tcp_t   	*tcp;
1909 	struct T_conn_res	*tcr;
1910 	t_uscalar_t	acceptor_id;
1911 	t_scalar_t	seqnum;
1912 	mblk_t		*discon_mp = NULL;
1913 	mblk_t		*ok_mp;
1914 	mblk_t		*mp1;
1915 	tcp_stack_t	*tcps = listener->tcp_tcps;
1916 	conn_t		*econnp;
1917 
1918 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1919 		tcp_err_ack(listener, mp, TPROTO, 0);
1920 		return;
1921 	}
1922 	tcr = (struct T_conn_res *)mp->b_rptr;
1923 
1924 	/*
1925 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1926 	 * read side queue of the streams device underneath us i.e. the
1927 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1928 	 * look it up in the queue_hash.  Under LP64 it sends down the
1929 	 * minor_t of the accepting endpoint.
1930 	 *
1931 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1932 	 * fanout hash lock is held.
1933 	 * This prevents any thread from entering the acceptor queue from
1934 	 * below (since it has not been hard bound yet i.e. any inbound
1935 	 * packets will arrive on the listener conn_t and
1936 	 * go through the classifier).
1937 	 * The CONN_INC_REF will prevent the acceptor from closing.
1938 	 *
1939 	 * XXX It is still possible for a tli application to send down data
1940 	 * on the accepting stream while another thread calls t_accept.
1941 	 * This should not be a problem for well-behaved applications since
1942 	 * the T_OK_ACK is sent after the queue swapping is completed.
1943 	 *
1944 	 * If the accepting fd is the same as the listening fd, avoid
1945 	 * queue hash lookup since that will return an eager listener in a
1946 	 * already established state.
1947 	 */
1948 	acceptor_id = tcr->ACCEPTOR_id;
1949 	mutex_enter(&listener->tcp_eager_lock);
1950 	if (listener->tcp_acceptor_id == acceptor_id) {
1951 		eager = listener->tcp_eager_next_q;
1952 		/* only count how many T_CONN_INDs so don't count q0 */
1953 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1954 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1955 			mutex_exit(&listener->tcp_eager_lock);
1956 			tcp_err_ack(listener, mp, TBADF, 0);
1957 			return;
1958 		}
1959 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1960 			/* Throw away all the eagers on q0. */
1961 			tcp_eager_cleanup(listener, 1);
1962 		}
1963 		if (listener->tcp_syn_defense) {
1964 			listener->tcp_syn_defense = B_FALSE;
1965 			if (listener->tcp_ip_addr_cache != NULL) {
1966 				kmem_free(listener->tcp_ip_addr_cache,
1967 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1968 				listener->tcp_ip_addr_cache = NULL;
1969 			}
1970 		}
1971 		/*
1972 		 * Transfer tcp_conn_req_max to the eager so that when
1973 		 * a disconnect occurs we can revert the endpoint to the
1974 		 * listen state.
1975 		 */
1976 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1977 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1978 		/*
1979 		 * Get a reference on the acceptor just like the
1980 		 * tcp_acceptor_hash_lookup below.
1981 		 */
1982 		acceptor = listener;
1983 		CONN_INC_REF(acceptor->tcp_connp);
1984 	} else {
1985 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1986 		if (acceptor == NULL) {
1987 			if (listener->tcp_connp->conn_debug) {
1988 				(void) strlog(TCP_MOD_ID, 0, 1,
1989 				    SL_ERROR|SL_TRACE,
1990 				    "tcp_accept: did not find acceptor 0x%x\n",
1991 				    acceptor_id);
1992 			}
1993 			mutex_exit(&listener->tcp_eager_lock);
1994 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1995 			return;
1996 		}
1997 		/*
1998 		 * Verify acceptor state. The acceptable states for an acceptor
1999 		 * include TCPS_IDLE and TCPS_BOUND.
2000 		 */
2001 		switch (acceptor->tcp_state) {
2002 		case TCPS_IDLE:
2003 			/* FALLTHRU */
2004 		case TCPS_BOUND:
2005 			break;
2006 		default:
2007 			CONN_DEC_REF(acceptor->tcp_connp);
2008 			mutex_exit(&listener->tcp_eager_lock);
2009 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2010 			return;
2011 		}
2012 	}
2013 
2014 	/* The listener must be in TCPS_LISTEN */
2015 	if (listener->tcp_state != TCPS_LISTEN) {
2016 		CONN_DEC_REF(acceptor->tcp_connp);
2017 		mutex_exit(&listener->tcp_eager_lock);
2018 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2019 		return;
2020 	}
2021 
2022 	/*
2023 	 * Rendezvous with an eager connection request packet hanging off
2024 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2025 	 * tcp structure when the connection packet arrived in
2026 	 * tcp_input_listener().
2027 	 */
2028 	seqnum = tcr->SEQ_number;
2029 	eager = listener;
2030 	do {
2031 		eager = eager->tcp_eager_next_q;
2032 		if (eager == NULL) {
2033 			CONN_DEC_REF(acceptor->tcp_connp);
2034 			mutex_exit(&listener->tcp_eager_lock);
2035 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2036 			return;
2037 		}
2038 	} while (eager->tcp_conn_req_seqnum != seqnum);
2039 	mutex_exit(&listener->tcp_eager_lock);
2040 
2041 	/*
2042 	 * At this point, both acceptor and listener have 2 ref
2043 	 * that they begin with. Acceptor has one additional ref
2044 	 * we placed in lookup while listener has 3 additional
2045 	 * ref for being behind the squeue (tcp_accept() is
2046 	 * done on listener's squeue); being in classifier hash;
2047 	 * and eager's ref on listener.
2048 	 */
2049 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2050 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2051 
2052 	/*
2053 	 * The eager at this point is set in its own squeue and
2054 	 * could easily have been killed (tcp_accept_finish will
2055 	 * deal with that) because of a TH_RST so we can only
2056 	 * ASSERT for a single ref.
2057 	 */
2058 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2059 
2060 	/*
2061 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
2062 	 * use it if something failed.
2063 	 */
2064 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
2065 	    sizeof (struct stroptions)), BPRI_HI);
2066 	if (discon_mp == NULL) {
2067 		CONN_DEC_REF(acceptor->tcp_connp);
2068 		CONN_DEC_REF(eager->tcp_connp);
2069 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2070 		return;
2071 	}
2072 
2073 	econnp = eager->tcp_connp;
2074 
2075 	/* Hold a copy of mp, in case reallocb fails */
2076 	if ((mp1 = copymsg(mp)) == NULL) {
2077 		CONN_DEC_REF(acceptor->tcp_connp);
2078 		CONN_DEC_REF(eager->tcp_connp);
2079 		freemsg(discon_mp);
2080 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2081 		return;
2082 	}
2083 
2084 	tcr = (struct T_conn_res *)mp1->b_rptr;
2085 
2086 	/*
2087 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2088 	 * which allocates a larger mblk and appends the new
2089 	 * local address to the ok_ack.  The address is copied by
2090 	 * soaccept() for getsockname().
2091 	 */
2092 	{
2093 		int extra;
2094 
2095 		extra = (econnp->conn_family == AF_INET) ?
2096 		    sizeof (sin_t) : sizeof (sin6_t);
2097 
2098 		/*
2099 		 * Try to re-use mp, if possible.  Otherwise, allocate
2100 		 * an mblk and return it as ok_mp.  In any case, mp
2101 		 * is no longer usable upon return.
2102 		 */
2103 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2104 			CONN_DEC_REF(acceptor->tcp_connp);
2105 			CONN_DEC_REF(eager->tcp_connp);
2106 			freemsg(discon_mp);
2107 			/* Original mp has been freed by now, so use mp1 */
2108 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2109 			return;
2110 		}
2111 
2112 		mp = NULL;	/* We should never use mp after this point */
2113 
2114 		switch (extra) {
2115 		case sizeof (sin_t): {
2116 			sin_t *sin = (sin_t *)ok_mp->b_wptr;
2117 
2118 			ok_mp->b_wptr += extra;
2119 			sin->sin_family = AF_INET;
2120 			sin->sin_port = econnp->conn_lport;
2121 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
2122 			break;
2123 		}
2124 		case sizeof (sin6_t): {
2125 			sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2126 
2127 			ok_mp->b_wptr += extra;
2128 			sin6->sin6_family = AF_INET6;
2129 			sin6->sin6_port = econnp->conn_lport;
2130 			sin6->sin6_addr = econnp->conn_laddr_v6;
2131 			sin6->sin6_flowinfo = econnp->conn_flowinfo;
2132 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
2133 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
2134 				sin6->sin6_scope_id =
2135 				    econnp->conn_ixa->ixa_scopeid;
2136 			} else {
2137 				sin6->sin6_scope_id = 0;
2138 			}
2139 			sin6->__sin6_src_id = 0;
2140 			break;
2141 		}
2142 		default:
2143 			break;
2144 		}
2145 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2146 	}
2147 
2148 	/*
2149 	 * If there are no options we know that the T_CONN_RES will
2150 	 * succeed. However, we can't send the T_OK_ACK upstream until
2151 	 * the tcp_accept_swap is done since it would be dangerous to
2152 	 * let the application start using the new fd prior to the swap.
2153 	 */
2154 	tcp_accept_swap(listener, acceptor, eager);
2155 
2156 	/*
2157 	 * tcp_accept_swap unlinks eager from listener but does not drop
2158 	 * the eager's reference on the listener.
2159 	 */
2160 	ASSERT(eager->tcp_listener == NULL);
2161 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2162 
2163 	/*
2164 	 * The eager is now associated with its own queue. Insert in
2165 	 * the hash so that the connection can be reused for a future
2166 	 * T_CONN_RES.
2167 	 */
2168 	tcp_acceptor_hash_insert(acceptor_id, eager);
2169 
2170 	/*
2171 	 * We now do the processing of options with T_CONN_RES.
2172 	 * We delay till now since we wanted to have queue to pass to
2173 	 * option processing routines that points back to the right
2174 	 * instance structure which does not happen until after
2175 	 * tcp_accept_swap().
2176 	 *
2177 	 * Note:
2178 	 * The sanity of the logic here assumes that whatever options
2179 	 * are appropriate to inherit from listner=>eager are done
2180 	 * before this point, and whatever were to be overridden (or not)
2181 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2182 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2183 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2184 	 * This may not be true at this point in time but can be fixed
2185 	 * independently. This option processing code starts with
2186 	 * the instantiated acceptor instance and the final queue at
2187 	 * this point.
2188 	 */
2189 
2190 	if (tcr->OPT_length != 0) {
2191 		/* Options to process */
2192 		int t_error = 0;
2193 		int sys_error = 0;
2194 		int do_disconnect = 0;
2195 
2196 		if (tcp_conprim_opt_process(eager, mp1,
2197 		    &do_disconnect, &t_error, &sys_error) < 0) {
2198 			eager->tcp_accept_error = 1;
2199 			if (do_disconnect) {
2200 				/*
2201 				 * An option failed which does not allow
2202 				 * connection to be accepted.
2203 				 *
2204 				 * We allow T_CONN_RES to succeed and
2205 				 * put a T_DISCON_IND on the eager queue.
2206 				 */
2207 				ASSERT(t_error == 0 && sys_error == 0);
2208 				eager->tcp_send_discon_ind = 1;
2209 			} else {
2210 				ASSERT(t_error != 0);
2211 				freemsg(ok_mp);
2212 				/*
2213 				 * Original mp was either freed or set
2214 				 * to ok_mp above, so use mp1 instead.
2215 				 */
2216 				tcp_err_ack(listener, mp1, t_error, sys_error);
2217 				goto finish;
2218 			}
2219 		}
2220 		/*
2221 		 * Most likely success in setting options (except if
2222 		 * eager->tcp_send_discon_ind set).
2223 		 * mp1 option buffer represented by OPT_length/offset
2224 		 * potentially modified and contains results of setting
2225 		 * options at this point
2226 		 */
2227 	}
2228 
2229 	/* We no longer need mp1, since all options processing has passed */
2230 	freemsg(mp1);
2231 
2232 	putnext(listener->tcp_connp->conn_rq, ok_mp);
2233 
2234 	mutex_enter(&listener->tcp_eager_lock);
2235 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2236 		tcp_t	*tail;
2237 		mblk_t	*conn_ind;
2238 
2239 		/*
2240 		 * This path should not be executed if listener and
2241 		 * acceptor streams are the same.
2242 		 */
2243 		ASSERT(listener != acceptor);
2244 
2245 		tcp = listener->tcp_eager_prev_q0;
2246 		/*
2247 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2248 		 * deferred T_conn_ind queue. We need to get to the head of
2249 		 * the queue in order to send up T_conn_ind the same order as
2250 		 * how the 3WHS is completed.
2251 		 */
2252 		while (tcp != listener) {
2253 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2254 				break;
2255 			else
2256 				tcp = tcp->tcp_eager_prev_q0;
2257 		}
2258 		ASSERT(tcp != listener);
2259 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2260 		ASSERT(conn_ind != NULL);
2261 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2262 
2263 		/* Move from q0 to q */
2264 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2265 		listener->tcp_conn_req_cnt_q0--;
2266 		listener->tcp_conn_req_cnt_q++;
2267 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2268 		    tcp->tcp_eager_prev_q0;
2269 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2270 		    tcp->tcp_eager_next_q0;
2271 		tcp->tcp_eager_prev_q0 = NULL;
2272 		tcp->tcp_eager_next_q0 = NULL;
2273 		tcp->tcp_conn_def_q0 = B_FALSE;
2274 
2275 		/* Make sure the tcp isn't in the list of droppables */
2276 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2277 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2278 
2279 		/*
2280 		 * Insert at end of the queue because sockfs sends
2281 		 * down T_CONN_RES in chronological order. Leaving
2282 		 * the older conn indications at front of the queue
2283 		 * helps reducing search time.
2284 		 */
2285 		tail = listener->tcp_eager_last_q;
2286 		if (tail != NULL)
2287 			tail->tcp_eager_next_q = tcp;
2288 		else
2289 			listener->tcp_eager_next_q = tcp;
2290 		listener->tcp_eager_last_q = tcp;
2291 		tcp->tcp_eager_next_q = NULL;
2292 		mutex_exit(&listener->tcp_eager_lock);
2293 		putnext(tcp->tcp_connp->conn_rq, conn_ind);
2294 	} else {
2295 		mutex_exit(&listener->tcp_eager_lock);
2296 	}
2297 
2298 	/*
2299 	 * Done with the acceptor - free it
2300 	 *
2301 	 * Note: from this point on, no access to listener should be made
2302 	 * as listener can be equal to acceptor.
2303 	 */
2304 finish:
2305 	ASSERT(acceptor->tcp_detached);
2306 	acceptor->tcp_connp->conn_rq = NULL;
2307 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2308 	acceptor->tcp_connp->conn_wq = NULL;
2309 	(void) tcp_clean_death(acceptor, 0, 2);
2310 	CONN_DEC_REF(acceptor->tcp_connp);
2311 
2312 	/*
2313 	 * We pass discon_mp to tcp_accept_finish to get on the right squeue.
2314 	 *
2315 	 * It will update the setting for sockfs/stream head and also take
2316 	 * care of any data that arrived before accept() wad called.
2317 	 * In case we already received a FIN then tcp_accept_finish will send up
2318 	 * the ordrel. It will also send up a window update if the window
2319 	 * has opened up.
2320 	 */
2321 
2322 	/*
2323 	 * XXX: we currently have a problem if XTI application closes the
2324 	 * acceptor stream in between. This problem exists in on10-gate also
2325 	 * and is well know but nothing can be done short of major rewrite
2326 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2327 	 * eager same squeue as listener (we can distinguish non socket
2328 	 * listeners at the time of handling a SYN in tcp_input_listener)
2329 	 * and do most of the work that tcp_accept_finish does here itself
2330 	 * and then get behind the acceptor squeue to access the acceptor
2331 	 * queue.
2332 	 */
2333 	/*
2334 	 * We already have a ref on tcp so no need to do one before squeue_enter
2335 	 */
2336 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, discon_mp,
2337 	    tcp_accept_finish, eager->tcp_connp, NULL, SQ_FILL,
2338 	    SQTAG_TCP_ACCEPT_FINISH);
2339 }
2340 
2341 /*
2342  * Swap information between the eager and acceptor for a TLI/XTI client.
2343  * The sockfs accept is done on the acceptor stream and control goes
2344  * through tcp_tli_accept() and tcp_accept()/tcp_accept_swap() is not
2345  * called. In either case, both the eager and listener are in their own
2346  * perimeter (squeue) and the code has to deal with potential race.
2347  *
2348  * See the block comment on top of tcp_accept() and tcp_tli_accept().
2349  */
2350 static void
2351 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2352 {
2353 	conn_t	*econnp, *aconnp;
2354 
2355 	ASSERT(eager->tcp_connp->conn_rq == listener->tcp_connp->conn_rq);
2356 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2357 	ASSERT(!TCP_IS_SOCKET(acceptor));
2358 	ASSERT(!TCP_IS_SOCKET(eager));
2359 	ASSERT(!TCP_IS_SOCKET(listener));
2360 
2361 	/*
2362 	 * Trusted Extensions may need to use a security label that is
2363 	 * different from the acceptor's label on MLP and MAC-Exempt
2364 	 * sockets. If this is the case, the required security label
2365 	 * already exists in econnp->conn_ixa->ixa_tsl. Since we make the
2366 	 * acceptor stream refer to econnp we atomatically get that label.
2367 	 */
2368 
2369 	acceptor->tcp_detached = B_TRUE;
2370 	/*
2371 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2372 	 * the acceptor id.
2373 	 */
2374 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2375 
2376 	/* remove eager from listen list... */
2377 	mutex_enter(&listener->tcp_eager_lock);
2378 	tcp_eager_unlink(eager);
2379 	ASSERT(eager->tcp_eager_next_q == NULL &&
2380 	    eager->tcp_eager_last_q == NULL);
2381 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2382 	    eager->tcp_eager_prev_q0 == NULL);
2383 	mutex_exit(&listener->tcp_eager_lock);
2384 
2385 	econnp = eager->tcp_connp;
2386 	aconnp = acceptor->tcp_connp;
2387 	econnp->conn_rq = aconnp->conn_rq;
2388 	econnp->conn_wq = aconnp->conn_wq;
2389 	econnp->conn_rq->q_ptr = econnp;
2390 	econnp->conn_wq->q_ptr = econnp;
2391 
2392 	/*
2393 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2394 	 * which might be a different squeue from our peer TCP instance.
2395 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2396 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2397 	 * membar_producer() to ensure that the assignments of conn_rq/conn_wq
2398 	 * above reach global visibility prior to the clearing of tcp_detached.
2399 	 */
2400 	membar_producer();
2401 	eager->tcp_detached = B_FALSE;
2402 
2403 	ASSERT(eager->tcp_ack_tid == 0);
2404 
2405 	econnp->conn_dev = aconnp->conn_dev;
2406 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2407 
2408 	ASSERT(econnp->conn_minor_arena != NULL);
2409 	if (econnp->conn_cred != NULL)
2410 		crfree(econnp->conn_cred);
2411 	econnp->conn_cred = aconnp->conn_cred;
2412 	aconnp->conn_cred = NULL;
2413 	econnp->conn_cpid = aconnp->conn_cpid;
2414 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2415 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2416 
2417 	econnp->conn_zoneid = aconnp->conn_zoneid;
2418 	econnp->conn_allzones = aconnp->conn_allzones;
2419 	econnp->conn_ixa->ixa_zoneid = aconnp->conn_ixa->ixa_zoneid;
2420 
2421 	econnp->conn_mac_mode = aconnp->conn_mac_mode;
2422 	econnp->conn_zone_is_global = aconnp->conn_zone_is_global;
2423 	aconnp->conn_mac_mode = CONN_MAC_DEFAULT;
2424 
2425 	/* Do the IPC initialization */
2426 	CONN_INC_REF(econnp);
2427 
2428 	/* Done with old IPC. Drop its ref on its connp */
2429 	CONN_DEC_REF(aconnp);
2430 }
2431 
2432 
2433 /*
2434  * Adapt to the information, such as rtt and rtt_sd, provided from the
2435  * DCE and IRE maintained by IP.
2436  *
2437  * Checks for multicast and broadcast destination address.
2438  * Returns zero if ok; an errno on failure.
2439  *
2440  * Note that the MSS calculation here is based on the info given in
2441  * the DCE and IRE.  We do not do any calculation based on TCP options.  They
2442  * will be handled in tcp_input_data() when TCP knows which options to use.
2443  *
2444  * Note on how TCP gets its parameters for a connection.
2445  *
2446  * When a tcp_t structure is allocated, it gets all the default parameters.
2447  * In tcp_set_destination(), it gets those metric parameters, like rtt, rtt_sd,
2448  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2449  * default.
2450  *
2451  * An incoming SYN with a multicast or broadcast destination address is dropped
2452  * in ip_fanout_v4/v6.
2453  *
2454  * An incoming SYN with a multicast or broadcast source address is always
2455  * dropped in tcp_set_destination, since IPDF_ALLOW_MCBC is not set in
2456  * conn_connect.
2457  * The same logic in tcp_set_destination also serves to
2458  * reject an attempt to connect to a broadcast or multicast (destination)
2459  * address.
2460  */
2461 static int
2462 tcp_set_destination(tcp_t *tcp)
2463 {
2464 	uint32_t	mss_max;
2465 	uint32_t	mss;
2466 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2467 	conn_t		*connp = tcp->tcp_connp;
2468 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2469 	iulp_t		uinfo;
2470 	int		error;
2471 	uint32_t	flags;
2472 
2473 	flags = IPDF_LSO | IPDF_ZCOPY;
2474 	/*
2475 	 * Make sure we have a dce for the destination to avoid dce_ident
2476 	 * contention for connected sockets.
2477 	 */
2478 	flags |= IPDF_UNIQUE_DCE;
2479 
2480 	if (!tcps->tcps_ignore_path_mtu)
2481 		connp->conn_ixa->ixa_flags |= IXAF_PMTU_DISCOVERY;
2482 
2483 	/* Use conn_lock to satify ASSERT; tcp is already serialized */
2484 	mutex_enter(&connp->conn_lock);
2485 	error = conn_connect(connp, &uinfo, flags);
2486 	mutex_exit(&connp->conn_lock);
2487 	if (error != 0)
2488 		return (error);
2489 
2490 	error = tcp_build_hdrs(tcp);
2491 	if (error != 0)
2492 		return (error);
2493 
2494 	tcp->tcp_localnet = uinfo.iulp_localnet;
2495 
2496 	if (uinfo.iulp_rtt != 0) {
2497 		clock_t	rto;
2498 
2499 		tcp->tcp_rtt_sa = uinfo.iulp_rtt;
2500 		tcp->tcp_rtt_sd = uinfo.iulp_rtt_sd;
2501 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2502 		    tcps->tcps_rexmit_interval_extra +
2503 		    (tcp->tcp_rtt_sa >> 5);
2504 
2505 		if (rto > tcps->tcps_rexmit_interval_max) {
2506 			tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2507 		} else if (rto < tcps->tcps_rexmit_interval_min) {
2508 			tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2509 		} else {
2510 			tcp->tcp_rto = rto;
2511 		}
2512 	}
2513 	if (uinfo.iulp_ssthresh != 0)
2514 		tcp->tcp_cwnd_ssthresh = uinfo.iulp_ssthresh;
2515 	else
2516 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2517 	if (uinfo.iulp_spipe > 0) {
2518 		connp->conn_sndbuf = MIN(uinfo.iulp_spipe,
2519 		    tcps->tcps_max_buf);
2520 		if (tcps->tcps_snd_lowat_fraction != 0) {
2521 			connp->conn_sndlowat = connp->conn_sndbuf /
2522 			    tcps->tcps_snd_lowat_fraction;
2523 		}
2524 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2525 	}
2526 	/*
2527 	 * Note that up till now, acceptor always inherits receive
2528 	 * window from the listener.  But if there is a metrics
2529 	 * associated with a host, we should use that instead of
2530 	 * inheriting it from listener. Thus we need to pass this
2531 	 * info back to the caller.
2532 	 */
2533 	if (uinfo.iulp_rpipe > 0) {
2534 		tcp->tcp_rwnd = MIN(uinfo.iulp_rpipe,
2535 		    tcps->tcps_max_buf);
2536 	}
2537 
2538 	if (uinfo.iulp_rtomax > 0) {
2539 		tcp->tcp_second_timer_threshold =
2540 		    uinfo.iulp_rtomax;
2541 	}
2542 
2543 	/*
2544 	 * Use the metric option settings, iulp_tstamp_ok and
2545 	 * iulp_wscale_ok, only for active open. What this means
2546 	 * is that if the other side uses timestamp or window
2547 	 * scale option, TCP will also use those options. That
2548 	 * is for passive open.  If the application sets a
2549 	 * large window, window scale is enabled regardless of
2550 	 * the value in iulp_wscale_ok.  This is the behavior
2551 	 * since 2.6.  So we keep it.
2552 	 * The only case left in passive open processing is the
2553 	 * check for SACK.
2554 	 * For ECN, it should probably be like SACK.  But the
2555 	 * current value is binary, so we treat it like the other
2556 	 * cases.  The metric only controls active open.For passive
2557 	 * open, the ndd param, tcp_ecn_permitted, controls the
2558 	 * behavior.
2559 	 */
2560 	if (!tcp_detached) {
2561 		/*
2562 		 * The if check means that the following can only
2563 		 * be turned on by the metrics only IRE, but not off.
2564 		 */
2565 		if (uinfo.iulp_tstamp_ok)
2566 			tcp->tcp_snd_ts_ok = B_TRUE;
2567 		if (uinfo.iulp_wscale_ok)
2568 			tcp->tcp_snd_ws_ok = B_TRUE;
2569 		if (uinfo.iulp_sack == 2)
2570 			tcp->tcp_snd_sack_ok = B_TRUE;
2571 		if (uinfo.iulp_ecn_ok)
2572 			tcp->tcp_ecn_ok = B_TRUE;
2573 	} else {
2574 		/*
2575 		 * Passive open.
2576 		 *
2577 		 * As above, the if check means that SACK can only be
2578 		 * turned on by the metric only IRE.
2579 		 */
2580 		if (uinfo.iulp_sack > 0) {
2581 			tcp->tcp_snd_sack_ok = B_TRUE;
2582 		}
2583 	}
2584 
2585 	/*
2586 	 * XXX Note that currently, iulp_mtu can be as small as 68
2587 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2588 	 * length of all those options exceeds 28 bytes.  But because
2589 	 * of the tcp_mss_min check below, we may not have a problem if
2590 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2591 	 * the negative problem still exists.  And the check defeats PMTUd.
2592 	 * In fact, if PMTUd finds that the MSS should be smaller than
2593 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2594 	 * value.
2595 	 *
2596 	 * We do not deal with that now.  All those problems related to
2597 	 * PMTUd will be fixed later.
2598 	 */
2599 	ASSERT(uinfo.iulp_mtu != 0);
2600 	mss = tcp->tcp_initial_pmtu = uinfo.iulp_mtu;
2601 
2602 	/* Sanity check for MSS value. */
2603 	if (connp->conn_ipversion == IPV4_VERSION)
2604 		mss_max = tcps->tcps_mss_max_ipv4;
2605 	else
2606 		mss_max = tcps->tcps_mss_max_ipv6;
2607 
2608 	if (tcp->tcp_ipsec_overhead == 0)
2609 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2610 
2611 	mss -= tcp->tcp_ipsec_overhead;
2612 
2613 	if (mss < tcps->tcps_mss_min)
2614 		mss = tcps->tcps_mss_min;
2615 	if (mss > mss_max)
2616 		mss = mss_max;
2617 
2618 	/* Note that this is the maximum MSS, excluding all options. */
2619 	tcp->tcp_mss = mss;
2620 
2621 	/*
2622 	 * Update the tcp connection with LSO capability.
2623 	 */
2624 	tcp_update_lso(tcp, connp->conn_ixa);
2625 
2626 	/*
2627 	 * Initialize the ISS here now that we have the full connection ID.
2628 	 * The RFC 1948 method of initial sequence number generation requires
2629 	 * knowledge of the full connection ID before setting the ISS.
2630 	 */
2631 	tcp_iss_init(tcp);
2632 
2633 	tcp->tcp_loopback = (uinfo.iulp_loopback | uinfo.iulp_local);
2634 
2635 	/*
2636 	 * Make sure that conn is not marked incipient
2637 	 * for incoming connections. A blind
2638 	 * removal of incipient flag is cheaper than
2639 	 * check and removal.
2640 	 */
2641 	mutex_enter(&connp->conn_lock);
2642 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2643 	mutex_exit(&connp->conn_lock);
2644 	return (0);
2645 }
2646 
2647 static void
2648 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2649 {
2650 	int	error;
2651 	conn_t	*connp = tcp->tcp_connp;
2652 	struct sockaddr	*sa;
2653 	mblk_t  *mp1;
2654 	struct T_bind_req *tbr;
2655 	int	backlog;
2656 	socklen_t	len;
2657 	sin_t	*sin;
2658 	sin6_t	*sin6;
2659 	cred_t		*cr;
2660 
2661 	/*
2662 	 * All Solaris components should pass a db_credp
2663 	 * for this TPI message, hence we ASSERT.
2664 	 * But in case there is some other M_PROTO that looks
2665 	 * like a TPI message sent by some other kernel
2666 	 * component, we check and return an error.
2667 	 */
2668 	cr = msg_getcred(mp, NULL);
2669 	ASSERT(cr != NULL);
2670 	if (cr == NULL) {
2671 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2672 		return;
2673 	}
2674 
2675 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2676 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2677 		if (connp->conn_debug) {
2678 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2679 			    "tcp_tpi_bind: bad req, len %u",
2680 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2681 		}
2682 		tcp_err_ack(tcp, mp, TPROTO, 0);
2683 		return;
2684 	}
2685 	/* Make sure the largest address fits */
2686 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t), 1);
2687 	if (mp1 == NULL) {
2688 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2689 		return;
2690 	}
2691 	mp = mp1;
2692 	tbr = (struct T_bind_req *)mp->b_rptr;
2693 
2694 	backlog = tbr->CONIND_number;
2695 	len = tbr->ADDR_length;
2696 
2697 	switch (len) {
2698 	case 0:		/* request for a generic port */
2699 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2700 		if (connp->conn_family == AF_INET) {
2701 			tbr->ADDR_length = sizeof (sin_t);
2702 			sin = (sin_t *)&tbr[1];
2703 			*sin = sin_null;
2704 			sin->sin_family = AF_INET;
2705 			sa = (struct sockaddr *)sin;
2706 			len = sizeof (sin_t);
2707 			mp->b_wptr = (uchar_t *)&sin[1];
2708 		} else {
2709 			ASSERT(connp->conn_family == AF_INET6);
2710 			tbr->ADDR_length = sizeof (sin6_t);
2711 			sin6 = (sin6_t *)&tbr[1];
2712 			*sin6 = sin6_null;
2713 			sin6->sin6_family = AF_INET6;
2714 			sa = (struct sockaddr *)sin6;
2715 			len = sizeof (sin6_t);
2716 			mp->b_wptr = (uchar_t *)&sin6[1];
2717 		}
2718 		break;
2719 
2720 	case sizeof (sin_t):    /* Complete IPv4 address */
2721 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
2722 		    sizeof (sin_t));
2723 		break;
2724 
2725 	case sizeof (sin6_t): /* Complete IPv6 address */
2726 		sa = (struct sockaddr *)mi_offset_param(mp,
2727 		    tbr->ADDR_offset, sizeof (sin6_t));
2728 		break;
2729 
2730 	default:
2731 		if (connp->conn_debug) {
2732 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2733 			    "tcp_tpi_bind: bad address length, %d",
2734 			    tbr->ADDR_length);
2735 		}
2736 		tcp_err_ack(tcp, mp, TBADADDR, 0);
2737 		return;
2738 	}
2739 
2740 	if (backlog > 0) {
2741 		error = tcp_do_listen(connp, sa, len, backlog, DB_CRED(mp),
2742 		    tbr->PRIM_type != O_T_BIND_REQ);
2743 	} else {
2744 		error = tcp_do_bind(connp, sa, len, DB_CRED(mp),
2745 		    tbr->PRIM_type != O_T_BIND_REQ);
2746 	}
2747 done:
2748 	if (error > 0) {
2749 		tcp_err_ack(tcp, mp, TSYSERR, error);
2750 	} else if (error < 0) {
2751 		tcp_err_ack(tcp, mp, -error, 0);
2752 	} else {
2753 		/*
2754 		 * Update port information as sockfs/tpi needs it for checking
2755 		 */
2756 		if (connp->conn_family == AF_INET) {
2757 			sin = (sin_t *)sa;
2758 			sin->sin_port = connp->conn_lport;
2759 		} else {
2760 			sin6 = (sin6_t *)sa;
2761 			sin6->sin6_port = connp->conn_lport;
2762 		}
2763 		mp->b_datap->db_type = M_PCPROTO;
2764 		tbr->PRIM_type = T_BIND_ACK;
2765 		putnext(connp->conn_rq, mp);
2766 	}
2767 }
2768 
2769 /*
2770  * If the "bind_to_req_port_only" parameter is set, if the requested port
2771  * number is available, return it, If not return 0
2772  *
2773  * If "bind_to_req_port_only" parameter is not set and
2774  * If the requested port number is available, return it.  If not, return
2775  * the first anonymous port we happen across.  If no anonymous ports are
2776  * available, return 0. addr is the requested local address, if any.
2777  *
2778  * In either case, when succeeding update the tcp_t to record the port number
2779  * and insert it in the bind hash table.
2780  *
2781  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
2782  * without setting SO_REUSEADDR. This is needed so that they
2783  * can be viewed as two independent transport protocols.
2784  */
2785 static in_port_t
2786 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
2787     int reuseaddr, boolean_t quick_connect,
2788     boolean_t bind_to_req_port_only, boolean_t user_specified)
2789 {
2790 	/* number of times we have run around the loop */
2791 	int count = 0;
2792 	/* maximum number of times to run around the loop */
2793 	int loopmax;
2794 	conn_t *connp = tcp->tcp_connp;
2795 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2796 
2797 	/*
2798 	 * Lookup for free addresses is done in a loop and "loopmax"
2799 	 * influences how long we spin in the loop
2800 	 */
2801 	if (bind_to_req_port_only) {
2802 		/*
2803 		 * If the requested port is busy, don't bother to look
2804 		 * for a new one. Setting loop maximum count to 1 has
2805 		 * that effect.
2806 		 */
2807 		loopmax = 1;
2808 	} else {
2809 		/*
2810 		 * If the requested port is busy, look for a free one
2811 		 * in the anonymous port range.
2812 		 * Set loopmax appropriately so that one does not look
2813 		 * forever in the case all of the anonymous ports are in use.
2814 		 */
2815 		if (connp->conn_anon_priv_bind) {
2816 			/*
2817 			 * loopmax =
2818 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
2819 			 */
2820 			loopmax = IPPORT_RESERVED -
2821 			    tcps->tcps_min_anonpriv_port;
2822 		} else {
2823 			loopmax = (tcps->tcps_largest_anon_port -
2824 			    tcps->tcps_smallest_anon_port + 1);
2825 		}
2826 	}
2827 	do {
2828 		uint16_t	lport;
2829 		tf_t		*tbf;
2830 		tcp_t		*ltcp;
2831 		conn_t		*lconnp;
2832 
2833 		lport = htons(port);
2834 
2835 		/*
2836 		 * Ensure that the tcp_t is not currently in the bind hash.
2837 		 * Hold the lock on the hash bucket to ensure that
2838 		 * the duplicate check plus the insertion is an atomic
2839 		 * operation.
2840 		 *
2841 		 * This function does an inline lookup on the bind hash list
2842 		 * Make sure that we access only members of tcp_t
2843 		 * and that we don't look at tcp_tcp, since we are not
2844 		 * doing a CONN_INC_REF.
2845 		 */
2846 		tcp_bind_hash_remove(tcp);
2847 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
2848 		mutex_enter(&tbf->tf_lock);
2849 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
2850 		    ltcp = ltcp->tcp_bind_hash) {
2851 			if (lport == ltcp->tcp_connp->conn_lport)
2852 				break;
2853 		}
2854 
2855 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
2856 			boolean_t not_socket;
2857 			boolean_t exclbind;
2858 
2859 			lconnp = ltcp->tcp_connp;
2860 
2861 			/*
2862 			 * On a labeled system, we must treat bindings to ports
2863 			 * on shared IP addresses by sockets with MAC exemption
2864 			 * privilege as being in all zones, as there's
2865 			 * otherwise no way to identify the right receiver.
2866 			 */
2867 			if (!IPCL_BIND_ZONE_MATCH(lconnp, connp))
2868 				continue;
2869 
2870 			/*
2871 			 * If TCP_EXCLBIND is set for either the bound or
2872 			 * binding endpoint, the semantics of bind
2873 			 * is changed according to the following.
2874 			 *
2875 			 * spec = specified address (v4 or v6)
2876 			 * unspec = unspecified address (v4 or v6)
2877 			 * A = specified addresses are different for endpoints
2878 			 *
2879 			 * bound	bind to		allowed
2880 			 * -------------------------------------
2881 			 * unspec	unspec		no
2882 			 * unspec	spec		no
2883 			 * spec		unspec		no
2884 			 * spec		spec		yes if A
2885 			 *
2886 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
2887 			 * as TCP_EXCLBIND, except that zoneid is ignored.
2888 			 *
2889 			 * Note:
2890 			 *
2891 			 * 1. Because of TLI semantics, an endpoint can go
2892 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
2893 			 * TCPS_BOUND, depending on whether it is originally
2894 			 * a listener or not.  That is why we need to check
2895 			 * for states greater than or equal to TCPS_BOUND
2896 			 * here.
2897 			 *
2898 			 * 2. Ideally, we should only check for state equals
2899 			 * to TCPS_LISTEN. And the following check should be
2900 			 * added.
2901 			 *
2902 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
2903 			 *	!reuseaddr || !lconnp->conn_reuseaddr) {
2904 			 *		...
2905 			 * }
2906 			 *
2907 			 * The semantics will be changed to this.  If the
2908 			 * endpoint on the list is in state not equal to
2909 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
2910 			 * set, let the bind succeed.
2911 			 *
2912 			 * Because of (1), we cannot do that for TLI
2913 			 * endpoints.  But we can do that for socket endpoints.
2914 			 * If in future, we can change this going back
2915 			 * semantics, we can use the above check for TLI also.
2916 			 */
2917 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
2918 			    TCP_IS_SOCKET(tcp));
2919 			exclbind = lconnp->conn_exclbind ||
2920 			    connp->conn_exclbind;
2921 
2922 			if ((lconnp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2923 			    (connp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2924 			    (exclbind && (not_socket ||
2925 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
2926 				if (V6_OR_V4_INADDR_ANY(
2927 				    lconnp->conn_bound_addr_v6) ||
2928 				    V6_OR_V4_INADDR_ANY(*laddr) ||
2929 				    IN6_ARE_ADDR_EQUAL(laddr,
2930 				    &lconnp->conn_bound_addr_v6)) {
2931 					break;
2932 				}
2933 				continue;
2934 			}
2935 
2936 			/*
2937 			 * Check ipversion to allow IPv4 and IPv6 sockets to
2938 			 * have disjoint port number spaces, if *_EXCLBIND
2939 			 * is not set and only if the application binds to a
2940 			 * specific port. We use the same autoassigned port
2941 			 * number space for IPv4 and IPv6 sockets.
2942 			 */
2943 			if (connp->conn_ipversion != lconnp->conn_ipversion &&
2944 			    bind_to_req_port_only)
2945 				continue;
2946 
2947 			/*
2948 			 * Ideally, we should make sure that the source
2949 			 * address, remote address, and remote port in the
2950 			 * four tuple for this tcp-connection is unique.
2951 			 * However, trying to find out the local source
2952 			 * address would require too much code duplication
2953 			 * with IP, since IP needs needs to have that code
2954 			 * to support userland TCP implementations.
2955 			 */
2956 			if (quick_connect &&
2957 			    (ltcp->tcp_state > TCPS_LISTEN) &&
2958 			    ((connp->conn_fport != lconnp->conn_fport) ||
2959 			    !IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
2960 			    &lconnp->conn_faddr_v6)))
2961 				continue;
2962 
2963 			if (!reuseaddr) {
2964 				/*
2965 				 * No socket option SO_REUSEADDR.
2966 				 * If existing port is bound to
2967 				 * a non-wildcard IP address
2968 				 * and the requesting stream is
2969 				 * bound to a distinct
2970 				 * different IP addresses
2971 				 * (non-wildcard, also), keep
2972 				 * going.
2973 				 */
2974 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
2975 				    !V6_OR_V4_INADDR_ANY(
2976 				    lconnp->conn_bound_addr_v6) &&
2977 				    !IN6_ARE_ADDR_EQUAL(laddr,
2978 				    &lconnp->conn_bound_addr_v6))
2979 					continue;
2980 				if (ltcp->tcp_state >= TCPS_BOUND) {
2981 					/*
2982 					 * This port is being used and
2983 					 * its state is >= TCPS_BOUND,
2984 					 * so we can't bind to it.
2985 					 */
2986 					break;
2987 				}
2988 			} else {
2989 				/*
2990 				 * socket option SO_REUSEADDR is set on the
2991 				 * binding tcp_t.
2992 				 *
2993 				 * If two streams are bound to
2994 				 * same IP address or both addr
2995 				 * and bound source are wildcards
2996 				 * (INADDR_ANY), we want to stop
2997 				 * searching.
2998 				 * We have found a match of IP source
2999 				 * address and source port, which is
3000 				 * refused regardless of the
3001 				 * SO_REUSEADDR setting, so we break.
3002 				 */
3003 				if (IN6_ARE_ADDR_EQUAL(laddr,
3004 				    &lconnp->conn_bound_addr_v6) &&
3005 				    (ltcp->tcp_state == TCPS_LISTEN ||
3006 				    ltcp->tcp_state == TCPS_BOUND))
3007 					break;
3008 			}
3009 		}
3010 		if (ltcp != NULL) {
3011 			/* The port number is busy */
3012 			mutex_exit(&tbf->tf_lock);
3013 		} else {
3014 			/*
3015 			 * This port is ours. Insert in fanout and mark as
3016 			 * bound to prevent others from getting the port
3017 			 * number.
3018 			 */
3019 			tcp->tcp_state = TCPS_BOUND;
3020 			connp->conn_lport = htons(port);
3021 
3022 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3023 			    connp->conn_lport)] == tbf);
3024 			tcp_bind_hash_insert(tbf, tcp, 1);
3025 
3026 			mutex_exit(&tbf->tf_lock);
3027 
3028 			/*
3029 			 * We don't want tcp_next_port_to_try to "inherit"
3030 			 * a port number supplied by the user in a bind.
3031 			 */
3032 			if (user_specified)
3033 				return (port);
3034 
3035 			/*
3036 			 * This is the only place where tcp_next_port_to_try
3037 			 * is updated. After the update, it may or may not
3038 			 * be in the valid range.
3039 			 */
3040 			if (!connp->conn_anon_priv_bind)
3041 				tcps->tcps_next_port_to_try = port + 1;
3042 			return (port);
3043 		}
3044 
3045 		if (connp->conn_anon_priv_bind) {
3046 			port = tcp_get_next_priv_port(tcp);
3047 		} else {
3048 			if (count == 0 && user_specified) {
3049 				/*
3050 				 * We may have to return an anonymous port. So
3051 				 * get one to start with.
3052 				 */
3053 				port =
3054 				    tcp_update_next_port(
3055 				    tcps->tcps_next_port_to_try,
3056 				    tcp, B_TRUE);
3057 				user_specified = B_FALSE;
3058 			} else {
3059 				port = tcp_update_next_port(port + 1, tcp,
3060 				    B_FALSE);
3061 			}
3062 		}
3063 		if (port == 0)
3064 			break;
3065 
3066 		/*
3067 		 * Don't let this loop run forever in the case where
3068 		 * all of the anonymous ports are in use.
3069 		 */
3070 	} while (++count < loopmax);
3071 	return (0);
3072 }
3073 
3074 /*
3075  * tcp_clean_death / tcp_close_detached must not be called more than once
3076  * on a tcp. Thus every function that potentially calls tcp_clean_death
3077  * must check for the tcp state before calling tcp_clean_death.
3078  * Eg. tcp_input_data, tcp_eager_kill, tcp_clean_death_wrapper,
3079  * tcp_timer_handler, all check for the tcp state.
3080  */
3081 /* ARGSUSED */
3082 void
3083 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
3084     ip_recv_attr_t *dummy)
3085 {
3086 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3087 
3088 	freemsg(mp);
3089 	if (tcp->tcp_state > TCPS_BOUND)
3090 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3091 		    ETIMEDOUT, 5);
3092 }
3093 
3094 /*
3095  * We are dying for some reason.  Try to do it gracefully.  (May be called
3096  * as writer.)
3097  *
3098  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3099  * done by a service procedure).
3100  * TBD - Should the return value distinguish between the tcp_t being
3101  * freed and it being reinitialized?
3102  */
3103 static int
3104 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3105 {
3106 	mblk_t	*mp;
3107 	queue_t	*q;
3108 	conn_t	*connp = tcp->tcp_connp;
3109 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3110 
3111 	TCP_CLD_STAT(tag);
3112 
3113 #if TCP_TAG_CLEAN_DEATH
3114 	tcp->tcp_cleandeathtag = tag;
3115 #endif
3116 
3117 	if (tcp->tcp_fused)
3118 		tcp_unfuse(tcp);
3119 
3120 	if (tcp->tcp_linger_tid != 0 &&
3121 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3122 		tcp_stop_lingering(tcp);
3123 	}
3124 
3125 	ASSERT(tcp != NULL);
3126 	ASSERT((connp->conn_family == AF_INET &&
3127 	    connp->conn_ipversion == IPV4_VERSION) ||
3128 	    (connp->conn_family == AF_INET6 &&
3129 	    (connp->conn_ipversion == IPV4_VERSION ||
3130 	    connp->conn_ipversion == IPV6_VERSION)));
3131 
3132 	if (TCP_IS_DETACHED(tcp)) {
3133 		if (tcp->tcp_hard_binding) {
3134 			/*
3135 			 * Its an eager that we are dealing with. We close the
3136 			 * eager but in case a conn_ind has already gone to the
3137 			 * listener, let tcp_accept_finish() send a discon_ind
3138 			 * to the listener and drop the last reference. If the
3139 			 * listener doesn't even know about the eager i.e. the
3140 			 * conn_ind hasn't gone up, blow away the eager and drop
3141 			 * the last reference as well. If the conn_ind has gone
3142 			 * up, state should be BOUND. tcp_accept_finish
3143 			 * will figure out that the connection has received a
3144 			 * RST and will send a DISCON_IND to the application.
3145 			 */
3146 			tcp_closei_local(tcp);
3147 			if (!tcp->tcp_tconnind_started) {
3148 				CONN_DEC_REF(connp);
3149 			} else {
3150 				tcp->tcp_state = TCPS_BOUND;
3151 			}
3152 		} else {
3153 			tcp_close_detached(tcp);
3154 		}
3155 		return (0);
3156 	}
3157 
3158 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3159 
3160 	/*
3161 	 * The connection is dead.  Decrement listener connection counter if
3162 	 * necessary.
3163 	 */
3164 	if (tcp->tcp_listen_cnt != NULL)
3165 		TCP_DECR_LISTEN_CNT(tcp);
3166 
3167 	q = connp->conn_rq;
3168 
3169 	/* Trash all inbound data */
3170 	if (!IPCL_IS_NONSTR(connp)) {
3171 		ASSERT(q != NULL);
3172 		flushq(q, FLUSHALL);
3173 	}
3174 
3175 	/*
3176 	 * If we are at least part way open and there is error
3177 	 * (err==0 implies no error)
3178 	 * notify our client by a T_DISCON_IND.
3179 	 */
3180 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3181 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3182 		    !TCP_IS_SOCKET(tcp)) {
3183 			/*
3184 			 * Send M_FLUSH according to TPI. Because sockets will
3185 			 * (and must) ignore FLUSHR we do that only for TPI
3186 			 * endpoints and sockets in STREAMS mode.
3187 			 */
3188 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3189 		}
3190 		if (connp->conn_debug) {
3191 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3192 			    "tcp_clean_death: discon err %d", err);
3193 		}
3194 		if (IPCL_IS_NONSTR(connp)) {
3195 			/* Direct socket, use upcall */
3196 			(*connp->conn_upcalls->su_disconnected)(
3197 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3198 		} else {
3199 			mp = mi_tpi_discon_ind(NULL, err, 0);
3200 			if (mp != NULL) {
3201 				putnext(q, mp);
3202 			} else {
3203 				if (connp->conn_debug) {
3204 					(void) strlog(TCP_MOD_ID, 0, 1,
3205 					    SL_ERROR|SL_TRACE,
3206 					    "tcp_clean_death, sending M_ERROR");
3207 				}
3208 				(void) putnextctl1(q, M_ERROR, EPROTO);
3209 			}
3210 		}
3211 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3212 			/* SYN_SENT or SYN_RCVD */
3213 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3214 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3215 			/* ESTABLISHED or CLOSE_WAIT */
3216 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3217 		}
3218 	}
3219 
3220 	tcp_reinit(tcp);
3221 	if (IPCL_IS_NONSTR(connp))
3222 		(void) tcp_do_unbind(connp);
3223 
3224 	return (-1);
3225 }
3226 
3227 /*
3228  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3229  * to expire, stop the wait and finish the close.
3230  */
3231 static void
3232 tcp_stop_lingering(tcp_t *tcp)
3233 {
3234 	clock_t	delta = 0;
3235 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3236 	conn_t		*connp = tcp->tcp_connp;
3237 
3238 	tcp->tcp_linger_tid = 0;
3239 	if (tcp->tcp_state > TCPS_LISTEN) {
3240 		tcp_acceptor_hash_remove(tcp);
3241 		mutex_enter(&tcp->tcp_non_sq_lock);
3242 		if (tcp->tcp_flow_stopped) {
3243 			tcp_clrqfull(tcp);
3244 		}
3245 		mutex_exit(&tcp->tcp_non_sq_lock);
3246 
3247 		if (tcp->tcp_timer_tid != 0) {
3248 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3249 			tcp->tcp_timer_tid = 0;
3250 		}
3251 		/*
3252 		 * Need to cancel those timers which will not be used when
3253 		 * TCP is detached.  This has to be done before the conn_wq
3254 		 * is cleared.
3255 		 */
3256 		tcp_timers_stop(tcp);
3257 
3258 		tcp->tcp_detached = B_TRUE;
3259 		connp->conn_rq = NULL;
3260 		connp->conn_wq = NULL;
3261 
3262 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3263 			tcp_time_wait_append(tcp);
3264 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3265 			goto finish;
3266 		}
3267 
3268 		/*
3269 		 * If delta is zero the timer event wasn't executed and was
3270 		 * successfully canceled. In this case we need to restart it
3271 		 * with the minimal delta possible.
3272 		 */
3273 		if (delta >= 0) {
3274 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3275 			    delta ? delta : 1);
3276 		}
3277 	} else {
3278 		tcp_closei_local(tcp);
3279 		CONN_DEC_REF(connp);
3280 	}
3281 finish:
3282 	/* Signal closing thread that it can complete close */
3283 	mutex_enter(&tcp->tcp_closelock);
3284 	tcp->tcp_detached = B_TRUE;
3285 	connp->conn_rq = NULL;
3286 	connp->conn_wq = NULL;
3287 
3288 	tcp->tcp_closed = 1;
3289 	cv_signal(&tcp->tcp_closecv);
3290 	mutex_exit(&tcp->tcp_closelock);
3291 }
3292 
3293 /*
3294  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3295  * expires.
3296  */
3297 static void
3298 tcp_close_linger_timeout(void *arg)
3299 {
3300 	conn_t	*connp = (conn_t *)arg;
3301 	tcp_t 	*tcp = connp->conn_tcp;
3302 
3303 	tcp->tcp_client_errno = ETIMEDOUT;
3304 	tcp_stop_lingering(tcp);
3305 }
3306 
3307 static void
3308 tcp_close_common(conn_t *connp, int flags)
3309 {
3310 	tcp_t		*tcp = connp->conn_tcp;
3311 	mblk_t 		*mp = &tcp->tcp_closemp;
3312 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3313 	mblk_t		*bp;
3314 
3315 	ASSERT(connp->conn_ref >= 2);
3316 
3317 	/*
3318 	 * Mark the conn as closing. ipsq_pending_mp_add will not
3319 	 * add any mp to the pending mp list, after this conn has
3320 	 * started closing.
3321 	 */
3322 	mutex_enter(&connp->conn_lock);
3323 	connp->conn_state_flags |= CONN_CLOSING;
3324 	if (connp->conn_oper_pending_ill != NULL)
3325 		conn_ioctl_cleanup_reqd = B_TRUE;
3326 	CONN_INC_REF_LOCKED(connp);
3327 	mutex_exit(&connp->conn_lock);
3328 	tcp->tcp_closeflags = (uint8_t)flags;
3329 	ASSERT(connp->conn_ref >= 3);
3330 
3331 	/*
3332 	 * tcp_closemp_used is used below without any protection of a lock
3333 	 * as we don't expect any one else to use it concurrently at this
3334 	 * point otherwise it would be a major defect.
3335 	 */
3336 
3337 	if (mp->b_prev == NULL)
3338 		tcp->tcp_closemp_used = B_TRUE;
3339 	else
3340 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3341 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3342 
3343 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3344 
3345 	/*
3346 	 * Cleanup any queued ioctls here. This must be done before the wq/rq
3347 	 * are re-written by tcp_close_output().
3348 	 */
3349 	if (conn_ioctl_cleanup_reqd)
3350 		conn_ioctl_cleanup(connp);
3351 
3352 	/*
3353 	 * As CONN_CLOSING is set, no further ioctls should be passed down to
3354 	 * IP for this conn (see the guards in tcp_ioctl, tcp_wput_ioctl and
3355 	 * tcp_wput_iocdata). If the ioctl was queued on an ipsq,
3356 	 * conn_ioctl_cleanup should have found it and removed it. If the ioctl
3357 	 * was still in flight at the time, we wait for it here. See comments
3358 	 * for CONN_INC_IOCTLREF in ip.h for details.
3359 	 */
3360 	mutex_enter(&connp->conn_lock);
3361 	while (connp->conn_ioctlref > 0)
3362 		cv_wait(&connp->conn_cv, &connp->conn_lock);
3363 	ASSERT(connp->conn_ioctlref == 0);
3364 	ASSERT(connp->conn_oper_pending_ill == NULL);
3365 	mutex_exit(&connp->conn_lock);
3366 
3367 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3368 	    NULL, tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3369 
3370 	mutex_enter(&tcp->tcp_closelock);
3371 	while (!tcp->tcp_closed) {
3372 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3373 			/*
3374 			 * The cv_wait_sig() was interrupted. We now do the
3375 			 * following:
3376 			 *
3377 			 * 1) If the endpoint was lingering, we allow this
3378 			 * to be interrupted by cancelling the linger timeout
3379 			 * and closing normally.
3380 			 *
3381 			 * 2) Revert to calling cv_wait()
3382 			 *
3383 			 * We revert to using cv_wait() to avoid an
3384 			 * infinite loop which can occur if the calling
3385 			 * thread is higher priority than the squeue worker
3386 			 * thread and is bound to the same cpu.
3387 			 */
3388 			if (connp->conn_linger && connp->conn_lingertime > 0) {
3389 				mutex_exit(&tcp->tcp_closelock);
3390 				/* Entering squeue, bump ref count. */
3391 				CONN_INC_REF(connp);
3392 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3393 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3394 				    tcp_linger_interrupted, connp, NULL,
3395 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3396 				mutex_enter(&tcp->tcp_closelock);
3397 			}
3398 			break;
3399 		}
3400 	}
3401 	while (!tcp->tcp_closed)
3402 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3403 	mutex_exit(&tcp->tcp_closelock);
3404 
3405 	/*
3406 	 * In the case of listener streams that have eagers in the q or q0
3407 	 * we wait for the eagers to drop their reference to us. conn_rq and
3408 	 * conn_wq of the eagers point to our queues. By waiting for the
3409 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3410 	 * up their queue pointers and also dropped their references to us.
3411 	 */
3412 	if (tcp->tcp_wait_for_eagers) {
3413 		mutex_enter(&connp->conn_lock);
3414 		while (connp->conn_ref != 1) {
3415 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3416 		}
3417 		mutex_exit(&connp->conn_lock);
3418 	}
3419 
3420 	connp->conn_cpid = NOPID;
3421 }
3422 
3423 static int
3424 tcp_tpi_close(queue_t *q, int flags)
3425 {
3426 	conn_t		*connp;
3427 
3428 	ASSERT(WR(q)->q_next == NULL);
3429 
3430 	if (flags & SO_FALLBACK) {
3431 		/*
3432 		 * stream is being closed while in fallback
3433 		 * simply free the resources that were allocated
3434 		 */
3435 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3436 		qprocsoff(q);
3437 		goto done;
3438 	}
3439 
3440 	connp = Q_TO_CONN(q);
3441 	/*
3442 	 * We are being closed as /dev/tcp or /dev/tcp6.
3443 	 */
3444 	tcp_close_common(connp, flags);
3445 
3446 	qprocsoff(q);
3447 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3448 
3449 	/*
3450 	 * Drop IP's reference on the conn. This is the last reference
3451 	 * on the connp if the state was less than established. If the
3452 	 * connection has gone into timewait state, then we will have
3453 	 * one ref for the TCP and one more ref (total of two) for the
3454 	 * classifier connected hash list (a timewait connections stays
3455 	 * in connected hash till closed).
3456 	 *
3457 	 * We can't assert the references because there might be other
3458 	 * transient reference places because of some walkers or queued
3459 	 * packets in squeue for the timewait state.
3460 	 */
3461 	CONN_DEC_REF(connp);
3462 done:
3463 	q->q_ptr = WR(q)->q_ptr = NULL;
3464 	return (0);
3465 }
3466 
3467 static int
3468 tcp_tpi_close_accept(queue_t *q)
3469 {
3470 	vmem_t	*minor_arena;
3471 	dev_t	conn_dev;
3472 
3473 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3474 
3475 	/*
3476 	 * We had opened an acceptor STREAM for sockfs which is
3477 	 * now being closed due to some error.
3478 	 */
3479 	qprocsoff(q);
3480 
3481 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3482 	conn_dev = (dev_t)RD(q)->q_ptr;
3483 	ASSERT(minor_arena != NULL);
3484 	ASSERT(conn_dev != 0);
3485 	inet_minor_free(minor_arena, conn_dev);
3486 	q->q_ptr = WR(q)->q_ptr = NULL;
3487 	return (0);
3488 }
3489 
3490 /*
3491  * Called by tcp_close() routine via squeue when lingering is
3492  * interrupted by a signal.
3493  */
3494 
3495 /* ARGSUSED */
3496 static void
3497 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3498 {
3499 	conn_t	*connp = (conn_t *)arg;
3500 	tcp_t	*tcp = connp->conn_tcp;
3501 
3502 	freeb(mp);
3503 	if (tcp->tcp_linger_tid != 0 &&
3504 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3505 		tcp_stop_lingering(tcp);
3506 		tcp->tcp_client_errno = EINTR;
3507 	}
3508 }
3509 
3510 /*
3511  * Called by streams close routine via squeues when our client blows off her
3512  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3513  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3514  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3515  * acked.
3516  *
3517  * NOTE: tcp_close potentially returns error when lingering.
3518  * However, the stream head currently does not pass these errors
3519  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3520  * errors to the application (from tsleep()) and not errors
3521  * like ECONNRESET caused by receiving a reset packet.
3522  */
3523 
3524 /* ARGSUSED */
3525 static void
3526 tcp_close_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3527 {
3528 	char	*msg;
3529 	conn_t	*connp = (conn_t *)arg;
3530 	tcp_t	*tcp = connp->conn_tcp;
3531 	clock_t	delta = 0;
3532 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3533 
3534 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3535 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3536 
3537 	mutex_enter(&tcp->tcp_eager_lock);
3538 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3539 		/* Cleanup for listener */
3540 		tcp_eager_cleanup(tcp, 0);
3541 		tcp->tcp_wait_for_eagers = 1;
3542 	}
3543 	mutex_exit(&tcp->tcp_eager_lock);
3544 
3545 	tcp->tcp_lso = B_FALSE;
3546 
3547 	msg = NULL;
3548 	switch (tcp->tcp_state) {
3549 	case TCPS_CLOSED:
3550 	case TCPS_IDLE:
3551 	case TCPS_BOUND:
3552 	case TCPS_LISTEN:
3553 		break;
3554 	case TCPS_SYN_SENT:
3555 		msg = "tcp_close, during connect";
3556 		break;
3557 	case TCPS_SYN_RCVD:
3558 		/*
3559 		 * Close during the connect 3-way handshake
3560 		 * but here there may or may not be pending data
3561 		 * already on queue. Process almost same as in
3562 		 * the ESTABLISHED state.
3563 		 */
3564 		/* FALLTHRU */
3565 	default:
3566 		if (tcp->tcp_fused)
3567 			tcp_unfuse(tcp);
3568 
3569 		/*
3570 		 * If SO_LINGER has set a zero linger time, abort the
3571 		 * connection with a reset.
3572 		 */
3573 		if (connp->conn_linger && connp->conn_lingertime == 0) {
3574 			msg = "tcp_close, zero lingertime";
3575 			break;
3576 		}
3577 
3578 		/*
3579 		 * Abort connection if there is unread data queued.
3580 		 */
3581 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3582 			msg = "tcp_close, unread data";
3583 			break;
3584 		}
3585 		/*
3586 		 * We have done a qwait() above which could have possibly
3587 		 * drained more messages in turn causing transition to a
3588 		 * different state. Check whether we have to do the rest
3589 		 * of the processing or not.
3590 		 */
3591 		if (tcp->tcp_state <= TCPS_LISTEN)
3592 			break;
3593 
3594 		/*
3595 		 * Transmit the FIN before detaching the tcp_t.
3596 		 * After tcp_detach returns this queue/perimeter
3597 		 * no longer owns the tcp_t thus others can modify it.
3598 		 */
3599 		(void) tcp_xmit_end(tcp);
3600 
3601 		/*
3602 		 * If lingering on close then wait until the fin is acked,
3603 		 * the SO_LINGER time passes, or a reset is sent/received.
3604 		 */
3605 		if (connp->conn_linger && connp->conn_lingertime > 0 &&
3606 		    !(tcp->tcp_fin_acked) &&
3607 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3608 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3609 				tcp->tcp_client_errno = EWOULDBLOCK;
3610 			} else if (tcp->tcp_client_errno == 0) {
3611 
3612 				ASSERT(tcp->tcp_linger_tid == 0);
3613 
3614 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3615 				    tcp_close_linger_timeout,
3616 				    connp->conn_lingertime * hz);
3617 
3618 				/* tcp_close_linger_timeout will finish close */
3619 				if (tcp->tcp_linger_tid == 0)
3620 					tcp->tcp_client_errno = ENOSR;
3621 				else
3622 					return;
3623 			}
3624 
3625 			/*
3626 			 * Check if we need to detach or just close
3627 			 * the instance.
3628 			 */
3629 			if (tcp->tcp_state <= TCPS_LISTEN)
3630 				break;
3631 		}
3632 
3633 		/*
3634 		 * Make sure that no other thread will access the conn_rq of
3635 		 * this instance (through lookups etc.) as conn_rq will go
3636 		 * away shortly.
3637 		 */
3638 		tcp_acceptor_hash_remove(tcp);
3639 
3640 		mutex_enter(&tcp->tcp_non_sq_lock);
3641 		if (tcp->tcp_flow_stopped) {
3642 			tcp_clrqfull(tcp);
3643 		}
3644 		mutex_exit(&tcp->tcp_non_sq_lock);
3645 
3646 		if (tcp->tcp_timer_tid != 0) {
3647 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3648 			tcp->tcp_timer_tid = 0;
3649 		}
3650 		/*
3651 		 * Need to cancel those timers which will not be used when
3652 		 * TCP is detached.  This has to be done before the conn_wq
3653 		 * is set to NULL.
3654 		 */
3655 		tcp_timers_stop(tcp);
3656 
3657 		tcp->tcp_detached = B_TRUE;
3658 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3659 			tcp_time_wait_append(tcp);
3660 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3661 			ASSERT(connp->conn_ref >= 3);
3662 			goto finish;
3663 		}
3664 
3665 		/*
3666 		 * If delta is zero the timer event wasn't executed and was
3667 		 * successfully canceled. In this case we need to restart it
3668 		 * with the minimal delta possible.
3669 		 */
3670 		if (delta >= 0)
3671 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3672 			    delta ? delta : 1);
3673 
3674 		ASSERT(connp->conn_ref >= 3);
3675 		goto finish;
3676 	}
3677 
3678 	/* Detach did not complete. Still need to remove q from stream. */
3679 	if (msg) {
3680 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3681 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3682 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3683 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3684 		    tcp->tcp_state == TCPS_SYN_RCVD)
3685 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3686 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3687 	}
3688 
3689 	tcp_closei_local(tcp);
3690 	CONN_DEC_REF(connp);
3691 	ASSERT(connp->conn_ref >= 2);
3692 
3693 finish:
3694 	mutex_enter(&tcp->tcp_closelock);
3695 	/*
3696 	 * Don't change the queues in the case of a listener that has
3697 	 * eagers in its q or q0. It could surprise the eagers.
3698 	 * Instead wait for the eagers outside the squeue.
3699 	 */
3700 	if (!tcp->tcp_wait_for_eagers) {
3701 		tcp->tcp_detached = B_TRUE;
3702 		connp->conn_rq = NULL;
3703 		connp->conn_wq = NULL;
3704 	}
3705 
3706 	/* Signal tcp_close() to finish closing. */
3707 	tcp->tcp_closed = 1;
3708 	cv_signal(&tcp->tcp_closecv);
3709 	mutex_exit(&tcp->tcp_closelock);
3710 }
3711 
3712 /*
3713  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
3714  * Some stream heads get upset if they see these later on as anything but NULL.
3715  */
3716 static void
3717 tcp_close_mpp(mblk_t **mpp)
3718 {
3719 	mblk_t	*mp;
3720 
3721 	if ((mp = *mpp) != NULL) {
3722 		do {
3723 			mp->b_next = NULL;
3724 			mp->b_prev = NULL;
3725 		} while ((mp = mp->b_cont) != NULL);
3726 
3727 		mp = *mpp;
3728 		*mpp = NULL;
3729 		freemsg(mp);
3730 	}
3731 }
3732 
3733 /* Do detached close. */
3734 static void
3735 tcp_close_detached(tcp_t *tcp)
3736 {
3737 	if (tcp->tcp_fused)
3738 		tcp_unfuse(tcp);
3739 
3740 	/*
3741 	 * Clustering code serializes TCP disconnect callbacks and
3742 	 * cluster tcp list walks by blocking a TCP disconnect callback
3743 	 * if a cluster tcp list walk is in progress. This ensures
3744 	 * accurate accounting of TCPs in the cluster code even though
3745 	 * the TCP list walk itself is not atomic.
3746 	 */
3747 	tcp_closei_local(tcp);
3748 	CONN_DEC_REF(tcp->tcp_connp);
3749 }
3750 
3751 /*
3752  * Stop all TCP timers, and free the timer mblks if requested.
3753  */
3754 void
3755 tcp_timers_stop(tcp_t *tcp)
3756 {
3757 	if (tcp->tcp_timer_tid != 0) {
3758 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3759 		tcp->tcp_timer_tid = 0;
3760 	}
3761 	if (tcp->tcp_ka_tid != 0) {
3762 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
3763 		tcp->tcp_ka_tid = 0;
3764 	}
3765 	if (tcp->tcp_ack_tid != 0) {
3766 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
3767 		tcp->tcp_ack_tid = 0;
3768 	}
3769 	if (tcp->tcp_push_tid != 0) {
3770 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
3771 		tcp->tcp_push_tid = 0;
3772 	}
3773 	if (tcp->tcp_reass_tid != 0) {
3774 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_reass_tid);
3775 		tcp->tcp_reass_tid = 0;
3776 	}
3777 }
3778 
3779 /*
3780  * The tcp_t is going away. Remove it from all lists and set it
3781  * to TCPS_CLOSED. The freeing up of memory is deferred until
3782  * tcp_inactive. This is needed since a thread in tcp_rput might have
3783  * done a CONN_INC_REF on this structure before it was removed from the
3784  * hashes.
3785  */
3786 static void
3787 tcp_closei_local(tcp_t *tcp)
3788 {
3789 	conn_t		*connp = tcp->tcp_connp;
3790 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3791 
3792 	if (!TCP_IS_SOCKET(tcp))
3793 		tcp_acceptor_hash_remove(tcp);
3794 
3795 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
3796 	tcp->tcp_ibsegs = 0;
3797 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
3798 	tcp->tcp_obsegs = 0;
3799 
3800 	/*
3801 	 * If we are an eager connection hanging off a listener that
3802 	 * hasn't formally accepted the connection yet, get off his
3803 	 * list and blow off any data that we have accumulated.
3804 	 */
3805 	if (tcp->tcp_listener != NULL) {
3806 		tcp_t	*listener = tcp->tcp_listener;
3807 		mutex_enter(&listener->tcp_eager_lock);
3808 		/*
3809 		 * tcp_tconnind_started == B_TRUE means that the
3810 		 * conn_ind has already gone to listener. At
3811 		 * this point, eager will be closed but we
3812 		 * leave it in listeners eager list so that
3813 		 * if listener decides to close without doing
3814 		 * accept, we can clean this up. In tcp_tli_accept
3815 		 * we take care of the case of accept on closed
3816 		 * eager.
3817 		 */
3818 		if (!tcp->tcp_tconnind_started) {
3819 			tcp_eager_unlink(tcp);
3820 			mutex_exit(&listener->tcp_eager_lock);
3821 			/*
3822 			 * We don't want to have any pointers to the
3823 			 * listener queue, after we have released our
3824 			 * reference on the listener
3825 			 */
3826 			ASSERT(tcp->tcp_detached);
3827 			connp->conn_rq = NULL;
3828 			connp->conn_wq = NULL;
3829 			CONN_DEC_REF(listener->tcp_connp);
3830 		} else {
3831 			mutex_exit(&listener->tcp_eager_lock);
3832 		}
3833 	}
3834 
3835 	/* Stop all the timers */
3836 	tcp_timers_stop(tcp);
3837 
3838 	if (tcp->tcp_state == TCPS_LISTEN) {
3839 		if (tcp->tcp_ip_addr_cache) {
3840 			kmem_free((void *)tcp->tcp_ip_addr_cache,
3841 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
3842 			tcp->tcp_ip_addr_cache = NULL;
3843 		}
3844 	}
3845 
3846 	/* Decrement listerner connection counter if necessary. */
3847 	if (tcp->tcp_listen_cnt != NULL)
3848 		TCP_DECR_LISTEN_CNT(tcp);
3849 
3850 	mutex_enter(&tcp->tcp_non_sq_lock);
3851 	if (tcp->tcp_flow_stopped)
3852 		tcp_clrqfull(tcp);
3853 	mutex_exit(&tcp->tcp_non_sq_lock);
3854 
3855 	tcp_bind_hash_remove(tcp);
3856 	/*
3857 	 * If the tcp_time_wait_collector (which runs outside the squeue)
3858 	 * is trying to remove this tcp from the time wait list, we will
3859 	 * block in tcp_time_wait_remove while trying to acquire the
3860 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
3861 	 * requires the ipcl_hash_remove to be ordered after the
3862 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
3863 	 */
3864 	if (tcp->tcp_state == TCPS_TIME_WAIT)
3865 		(void) tcp_time_wait_remove(tcp, NULL);
3866 	CL_INET_DISCONNECT(connp);
3867 	ipcl_hash_remove(connp);
3868 	ixa_cleanup(connp->conn_ixa);
3869 
3870 	/*
3871 	 * Mark the conn as CONDEMNED
3872 	 */
3873 	mutex_enter(&connp->conn_lock);
3874 	connp->conn_state_flags |= CONN_CONDEMNED;
3875 	mutex_exit(&connp->conn_lock);
3876 
3877 	ASSERT(tcp->tcp_time_wait_next == NULL);
3878 	ASSERT(tcp->tcp_time_wait_prev == NULL);
3879 	ASSERT(tcp->tcp_time_wait_expire == 0);
3880 	tcp->tcp_state = TCPS_CLOSED;
3881 
3882 	/* Release any SSL context */
3883 	if (tcp->tcp_kssl_ent != NULL) {
3884 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
3885 		tcp->tcp_kssl_ent = NULL;
3886 	}
3887 	if (tcp->tcp_kssl_ctx != NULL) {
3888 		kssl_release_ctx(tcp->tcp_kssl_ctx);
3889 		tcp->tcp_kssl_ctx = NULL;
3890 	}
3891 	tcp->tcp_kssl_pending = B_FALSE;
3892 
3893 	tcp_ipsec_cleanup(tcp);
3894 }
3895 
3896 /*
3897  * tcp is dying (called from ipcl_conn_destroy and error cases).
3898  * Free the tcp_t in either case.
3899  */
3900 void
3901 tcp_free(tcp_t *tcp)
3902 {
3903 	mblk_t		*mp;
3904 	conn_t		*connp = tcp->tcp_connp;
3905 
3906 	ASSERT(tcp != NULL);
3907 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
3908 
3909 	connp->conn_rq = NULL;
3910 	connp->conn_wq = NULL;
3911 
3912 	tcp_close_mpp(&tcp->tcp_xmit_head);
3913 	tcp_close_mpp(&tcp->tcp_reass_head);
3914 	if (tcp->tcp_rcv_list != NULL) {
3915 		/* Free b_next chain */
3916 		tcp_close_mpp(&tcp->tcp_rcv_list);
3917 	}
3918 	if ((mp = tcp->tcp_urp_mp) != NULL) {
3919 		freemsg(mp);
3920 	}
3921 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
3922 		freemsg(mp);
3923 	}
3924 
3925 	if (tcp->tcp_fused_sigurg_mp != NULL) {
3926 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3927 		freeb(tcp->tcp_fused_sigurg_mp);
3928 		tcp->tcp_fused_sigurg_mp = NULL;
3929 	}
3930 
3931 	if (tcp->tcp_ordrel_mp != NULL) {
3932 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3933 		freeb(tcp->tcp_ordrel_mp);
3934 		tcp->tcp_ordrel_mp = NULL;
3935 	}
3936 
3937 	if (tcp->tcp_sack_info != NULL) {
3938 		if (tcp->tcp_notsack_list != NULL) {
3939 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
3940 			    tcp);
3941 		}
3942 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
3943 	}
3944 
3945 	if (tcp->tcp_hopopts != NULL) {
3946 		mi_free(tcp->tcp_hopopts);
3947 		tcp->tcp_hopopts = NULL;
3948 		tcp->tcp_hopoptslen = 0;
3949 	}
3950 	ASSERT(tcp->tcp_hopoptslen == 0);
3951 	if (tcp->tcp_dstopts != NULL) {
3952 		mi_free(tcp->tcp_dstopts);
3953 		tcp->tcp_dstopts = NULL;
3954 		tcp->tcp_dstoptslen = 0;
3955 	}
3956 	ASSERT(tcp->tcp_dstoptslen == 0);
3957 	if (tcp->tcp_rthdrdstopts != NULL) {
3958 		mi_free(tcp->tcp_rthdrdstopts);
3959 		tcp->tcp_rthdrdstopts = NULL;
3960 		tcp->tcp_rthdrdstoptslen = 0;
3961 	}
3962 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
3963 	if (tcp->tcp_rthdr != NULL) {
3964 		mi_free(tcp->tcp_rthdr);
3965 		tcp->tcp_rthdr = NULL;
3966 		tcp->tcp_rthdrlen = 0;
3967 	}
3968 	ASSERT(tcp->tcp_rthdrlen == 0);
3969 
3970 	/*
3971 	 * Following is really a blowing away a union.
3972 	 * It happens to have exactly two members of identical size
3973 	 * the following code is enough.
3974 	 */
3975 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
3976 }
3977 
3978 
3979 /*
3980  * Put a connection confirmation message upstream built from the
3981  * address/flowid information with the conn and iph. Report our success or
3982  * failure.
3983  */
3984 static boolean_t
3985 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, mblk_t *idmp,
3986     mblk_t **defermp, ip_recv_attr_t *ira)
3987 {
3988 	sin_t	sin;
3989 	sin6_t	sin6;
3990 	mblk_t	*mp;
3991 	char	*optp = NULL;
3992 	int	optlen = 0;
3993 	conn_t	*connp = tcp->tcp_connp;
3994 
3995 	if (defermp != NULL)
3996 		*defermp = NULL;
3997 
3998 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
3999 		/*
4000 		 * Return in T_CONN_CON results of option negotiation through
4001 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4002 		 * negotiation, then what is received from remote end needs
4003 		 * to be taken into account but there is no such thing (yet?)
4004 		 * in our TCP/IP.
4005 		 * Note: We do not use mi_offset_param() here as
4006 		 * tcp_opts_conn_req contents do not directly come from
4007 		 * an application and are either generated in kernel or
4008 		 * from user input that was already verified.
4009 		 */
4010 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4011 		optp = (char *)(mp->b_rptr +
4012 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4013 		optlen = (int)
4014 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4015 	}
4016 
4017 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4018 
4019 		/* packet is IPv4 */
4020 		if (connp->conn_family == AF_INET) {
4021 			sin = sin_null;
4022 			sin.sin_addr.s_addr = connp->conn_faddr_v4;
4023 			sin.sin_port = connp->conn_fport;
4024 			sin.sin_family = AF_INET;
4025 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4026 			    (int)sizeof (sin_t), optp, optlen);
4027 		} else {
4028 			sin6 = sin6_null;
4029 			sin6.sin6_addr = connp->conn_faddr_v6;
4030 			sin6.sin6_port = connp->conn_fport;
4031 			sin6.sin6_family = AF_INET6;
4032 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4033 			    (int)sizeof (sin6_t), optp, optlen);
4034 
4035 		}
4036 	} else {
4037 		ip6_t	*ip6h = (ip6_t *)iphdr;
4038 
4039 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4040 		ASSERT(connp->conn_family == AF_INET6);
4041 		sin6 = sin6_null;
4042 		sin6.sin6_addr = connp->conn_faddr_v6;
4043 		sin6.sin6_port = connp->conn_fport;
4044 		sin6.sin6_family = AF_INET6;
4045 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4046 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4047 		    (int)sizeof (sin6_t), optp, optlen);
4048 	}
4049 
4050 	if (!mp)
4051 		return (B_FALSE);
4052 
4053 	mblk_copycred(mp, idmp);
4054 
4055 	if (defermp == NULL) {
4056 		conn_t *connp = tcp->tcp_connp;
4057 		if (IPCL_IS_NONSTR(connp)) {
4058 			(*connp->conn_upcalls->su_connected)
4059 			    (connp->conn_upper_handle, tcp->tcp_connid,
4060 			    ira->ira_cred, ira->ira_cpid);
4061 			freemsg(mp);
4062 		} else {
4063 			if (ira->ira_cred != NULL) {
4064 				/* So that getpeerucred works for TPI sockfs */
4065 				mblk_setcred(mp, ira->ira_cred, ira->ira_cpid);
4066 			}
4067 			putnext(connp->conn_rq, mp);
4068 		}
4069 	} else {
4070 		*defermp = mp;
4071 	}
4072 
4073 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4074 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4075 	return (B_TRUE);
4076 }
4077 
4078 /*
4079  * Defense for the SYN attack -
4080  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4081  *    one from the list of droppable eagers. This list is a subset of q0.
4082  *    see comments before the definition of MAKE_DROPPABLE().
4083  * 2. Don't drop a SYN request before its first timeout. This gives every
4084  *    request at least til the first timeout to complete its 3-way handshake.
4085  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4086  *    requests currently on the queue that has timed out. This will be used
4087  *    as an indicator of whether an attack is under way, so that appropriate
4088  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4089  *    either when eager goes into ESTABLISHED, or gets freed up.)
4090  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4091  *    # of timeout drops back to <= q0len/32 => SYN alert off
4092  */
4093 static boolean_t
4094 tcp_drop_q0(tcp_t *tcp)
4095 {
4096 	tcp_t	*eager;
4097 	mblk_t	*mp;
4098 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4099 
4100 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4101 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4102 
4103 	/* Pick oldest eager from the list of droppable eagers */
4104 	eager = tcp->tcp_eager_prev_drop_q0;
4105 
4106 	/* If list is empty. return B_FALSE */
4107 	if (eager == tcp) {
4108 		return (B_FALSE);
4109 	}
4110 
4111 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4112 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4113 		return (B_FALSE);
4114 
4115 	/*
4116 	 * Take this eager out from the list of droppable eagers since we are
4117 	 * going to drop it.
4118 	 */
4119 	MAKE_UNDROPPABLE(eager);
4120 
4121 	if (tcp->tcp_connp->conn_debug) {
4122 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4123 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4124 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4125 		    tcp->tcp_conn_req_cnt_q0,
4126 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4127 	}
4128 
4129 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4130 
4131 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4132 	CONN_INC_REF(eager->tcp_connp);
4133 
4134 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4135 	    tcp_clean_death_wrapper, eager->tcp_connp, NULL,
4136 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4137 
4138 	return (B_TRUE);
4139 }
4140 
4141 /*
4142  * Handle a SYN on an AF_INET6 socket; can be either IPv4 or IPv6
4143  */
4144 static mblk_t *
4145 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4146     ip_recv_attr_t *ira)
4147 {
4148 	tcp_t 		*ltcp = lconnp->conn_tcp;
4149 	tcp_t		*tcp = connp->conn_tcp;
4150 	mblk_t		*tpi_mp;
4151 	ipha_t		*ipha;
4152 	ip6_t		*ip6h;
4153 	sin6_t 		sin6;
4154 	uint_t		ifindex = ira->ira_ruifindex;
4155 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4156 
4157 	if (ira->ira_flags & IRAF_IS_IPV4) {
4158 		ipha = (ipha_t *)mp->b_rptr;
4159 
4160 		connp->conn_ipversion = IPV4_VERSION;
4161 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4162 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4163 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4164 
4165 		sin6 = sin6_null;
4166 		sin6.sin6_addr = connp->conn_faddr_v6;
4167 		sin6.sin6_port = connp->conn_fport;
4168 		sin6.sin6_family = AF_INET6;
4169 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4170 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4171 
4172 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4173 			sin6_t	sin6d;
4174 
4175 			sin6d = sin6_null;
4176 			sin6d.sin6_addr = connp->conn_laddr_v6;
4177 			sin6d.sin6_port = connp->conn_lport;
4178 			sin6d.sin6_family = AF_INET;
4179 			tpi_mp = mi_tpi_extconn_ind(NULL,
4180 			    (char *)&sin6d, sizeof (sin6_t),
4181 			    (char *)&tcp,
4182 			    (t_scalar_t)sizeof (intptr_t),
4183 			    (char *)&sin6d, sizeof (sin6_t),
4184 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4185 		} else {
4186 			tpi_mp = mi_tpi_conn_ind(NULL,
4187 			    (char *)&sin6, sizeof (sin6_t),
4188 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4189 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4190 		}
4191 	} else {
4192 		ip6h = (ip6_t *)mp->b_rptr;
4193 
4194 		connp->conn_ipversion = IPV6_VERSION;
4195 		connp->conn_laddr_v6 = ip6h->ip6_dst;
4196 		connp->conn_faddr_v6 = ip6h->ip6_src;
4197 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4198 
4199 		sin6 = sin6_null;
4200 		sin6.sin6_addr = connp->conn_faddr_v6;
4201 		sin6.sin6_port = connp->conn_fport;
4202 		sin6.sin6_family = AF_INET6;
4203 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4204 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4205 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4206 
4207 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4208 			/* Pass up the scope_id of remote addr */
4209 			sin6.sin6_scope_id = ifindex;
4210 		} else {
4211 			sin6.sin6_scope_id = 0;
4212 		}
4213 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4214 			sin6_t	sin6d;
4215 
4216 			sin6d = sin6_null;
4217 			sin6.sin6_addr = connp->conn_laddr_v6;
4218 			sin6d.sin6_port = connp->conn_lport;
4219 			sin6d.sin6_family = AF_INET6;
4220 			if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_laddr_v6))
4221 				sin6d.sin6_scope_id = ifindex;
4222 
4223 			tpi_mp = mi_tpi_extconn_ind(NULL,
4224 			    (char *)&sin6d, sizeof (sin6_t),
4225 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4226 			    (char *)&sin6d, sizeof (sin6_t),
4227 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4228 		} else {
4229 			tpi_mp = mi_tpi_conn_ind(NULL,
4230 			    (char *)&sin6, sizeof (sin6_t),
4231 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4232 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4233 		}
4234 	}
4235 
4236 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4237 	return (tpi_mp);
4238 }
4239 
4240 /* Handle a SYN on an AF_INET socket */
4241 mblk_t *
4242 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4243     ip_recv_attr_t *ira)
4244 {
4245 	tcp_t 		*ltcp = lconnp->conn_tcp;
4246 	tcp_t		*tcp = connp->conn_tcp;
4247 	sin_t		sin;
4248 	mblk_t		*tpi_mp = NULL;
4249 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4250 	ipha_t		*ipha;
4251 
4252 	ASSERT(ira->ira_flags & IRAF_IS_IPV4);
4253 	ipha = (ipha_t *)mp->b_rptr;
4254 
4255 	connp->conn_ipversion = IPV4_VERSION;
4256 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4257 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4258 	connp->conn_saddr_v6 = connp->conn_laddr_v6;
4259 
4260 	sin = sin_null;
4261 	sin.sin_addr.s_addr = connp->conn_faddr_v4;
4262 	sin.sin_port = connp->conn_fport;
4263 	sin.sin_family = AF_INET;
4264 	if (lconnp->conn_recv_ancillary.crb_recvdstaddr) {
4265 		sin_t	sind;
4266 
4267 		sind = sin_null;
4268 		sind.sin_addr.s_addr = connp->conn_laddr_v4;
4269 		sind.sin_port = connp->conn_lport;
4270 		sind.sin_family = AF_INET;
4271 		tpi_mp = mi_tpi_extconn_ind(NULL,
4272 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4273 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4274 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4275 	} else {
4276 		tpi_mp = mi_tpi_conn_ind(NULL,
4277 		    (char *)&sin, sizeof (sin_t),
4278 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4279 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4280 	}
4281 
4282 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4283 	return (tpi_mp);
4284 }
4285 
4286 /*
4287  * tcp_get_conn/tcp_free_conn
4288  *
4289  * tcp_get_conn is used to get a clean tcp connection structure.
4290  * It tries to reuse the connections put on the freelist by the
4291  * time_wait_collector failing which it goes to kmem_cache. This
4292  * way has two benefits compared to just allocating from and
4293  * freeing to kmem_cache.
4294  * 1) The time_wait_collector can free (which includes the cleanup)
4295  * outside the squeue. So when the interrupt comes, we have a clean
4296  * connection sitting in the freelist. Obviously, this buys us
4297  * performance.
4298  *
4299  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_input_listener
4300  * has multiple disadvantages - tying up the squeue during alloc.
4301  * But allocating the conn/tcp in IP land is also not the best since
4302  * we can't check the 'q' and 'q0' which are protected by squeue and
4303  * blindly allocate memory which might have to be freed here if we are
4304  * not allowed to accept the connection. By using the freelist and
4305  * putting the conn/tcp back in freelist, we don't pay a penalty for
4306  * allocating memory without checking 'q/q0' and freeing it if we can't
4307  * accept the connection.
4308  *
4309  * Care should be taken to put the conn back in the same squeue's freelist
4310  * from which it was allocated. Best results are obtained if conn is
4311  * allocated from listener's squeue and freed to the same. Time wait
4312  * collector will free up the freelist is the connection ends up sitting
4313  * there for too long.
4314  */
4315 void *
4316 tcp_get_conn(void *arg, tcp_stack_t *tcps)
4317 {
4318 	tcp_t			*tcp = NULL;
4319 	conn_t			*connp = NULL;
4320 	squeue_t		*sqp = (squeue_t *)arg;
4321 	tcp_squeue_priv_t 	*tcp_time_wait;
4322 	netstack_t		*ns;
4323 	mblk_t			*tcp_rsrv_mp = NULL;
4324 
4325 	tcp_time_wait =
4326 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
4327 
4328 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
4329 	tcp = tcp_time_wait->tcp_free_list;
4330 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
4331 	if (tcp != NULL) {
4332 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
4333 		tcp_time_wait->tcp_free_list_cnt--;
4334 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4335 		tcp->tcp_time_wait_next = NULL;
4336 		connp = tcp->tcp_connp;
4337 		connp->conn_flags |= IPCL_REUSED;
4338 
4339 		ASSERT(tcp->tcp_tcps == NULL);
4340 		ASSERT(connp->conn_netstack == NULL);
4341 		ASSERT(tcp->tcp_rsrv_mp != NULL);
4342 		ns = tcps->tcps_netstack;
4343 		netstack_hold(ns);
4344 		connp->conn_netstack = ns;
4345 		connp->conn_ixa->ixa_ipst = ns->netstack_ip;
4346 		tcp->tcp_tcps = tcps;
4347 		ipcl_globalhash_insert(connp);
4348 
4349 		connp->conn_ixa->ixa_notify_cookie = tcp;
4350 		ASSERT(connp->conn_ixa->ixa_notify == tcp_notify);
4351 		connp->conn_recv = tcp_input_data;
4352 		ASSERT(connp->conn_recvicmp == tcp_icmp_input);
4353 		ASSERT(connp->conn_verifyicmp == tcp_verifyicmp);
4354 		return ((void *)connp);
4355 	}
4356 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4357 	/*
4358 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
4359 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
4360 	 */
4361 	tcp_rsrv_mp = allocb(0, BPRI_HI);
4362 	if (tcp_rsrv_mp == NULL)
4363 		return (NULL);
4364 
4365 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
4366 	    tcps->tcps_netstack)) == NULL) {
4367 		freeb(tcp_rsrv_mp);
4368 		return (NULL);
4369 	}
4370 
4371 	tcp = connp->conn_tcp;
4372 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
4373 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
4374 
4375 	tcp->tcp_tcps = tcps;
4376 
4377 	connp->conn_recv = tcp_input_data;
4378 	connp->conn_recvicmp = tcp_icmp_input;
4379 	connp->conn_verifyicmp = tcp_verifyicmp;
4380 
4381 	/*
4382 	 * Register tcp_notify to listen to capability changes detected by IP.
4383 	 * This upcall is made in the context of the call to conn_ip_output
4384 	 * thus it is inside the squeue.
4385 	 */
4386 	connp->conn_ixa->ixa_notify = tcp_notify;
4387 	connp->conn_ixa->ixa_notify_cookie = tcp;
4388 
4389 	return ((void *)connp);
4390 }
4391 
4392 /* BEGIN CSTYLED */
4393 /*
4394  *
4395  * The sockfs ACCEPT path:
4396  * =======================
4397  *
4398  * The eager is now established in its own perimeter as soon as SYN is
4399  * received in tcp_input_listener(). When sockfs receives conn_ind, it
4400  * completes the accept processing on the acceptor STREAM. The sending
4401  * of conn_ind part is common for both sockfs listener and a TLI/XTI
4402  * listener but a TLI/XTI listener completes the accept processing
4403  * on the listener perimeter.
4404  *
4405  * Common control flow for 3 way handshake:
4406  * ----------------------------------------
4407  *
4408  * incoming SYN (listener perimeter)	-> tcp_input_listener()
4409  *
4410  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_input_data()
4411  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
4412  *
4413  * Sockfs ACCEPT Path:
4414  * -------------------
4415  *
4416  * open acceptor stream (tcp_open allocates tcp_tli_accept()
4417  * as STREAM entry point)
4418  *
4419  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_tli_accept()
4420  *
4421  * tcp_tli_accept() extracts the eager and makes the q->q_ptr <-> eager
4422  * association (we are not behind eager's squeue but sockfs is protecting us
4423  * and no one knows about this stream yet. The STREAMS entry point q->q_info
4424  * is changed to point at tcp_wput().
4425  *
4426  * tcp_accept_common() sends any deferred eagers via tcp_send_pending() to
4427  * listener (done on listener's perimeter).
4428  *
4429  * tcp_tli_accept() calls tcp_accept_finish() on eagers perimeter to finish
4430  * accept.
4431  *
4432  * TLI/XTI client ACCEPT path:
4433  * ---------------------------
4434  *
4435  * soaccept() sends T_CONN_RES on the listener STREAM.
4436  *
4437  * tcp_tli_accept() -> tcp_accept_swap() complete the processing and send
4438  * a M_SETOPS mblk to eager perimeter to finish accept (tcp_accept_finish()).
4439  *
4440  * Locks:
4441  * ======
4442  *
4443  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
4444  * and listeners->tcp_eager_next_q.
4445  *
4446  * Referencing:
4447  * ============
4448  *
4449  * 1) We start out in tcp_input_listener by eager placing a ref on
4450  * listener and listener adding eager to listeners->tcp_eager_next_q0.
4451  *
4452  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
4453  * doing so we place a ref on the eager. This ref is finally dropped at the
4454  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
4455  * reference is dropped by the squeue framework.
4456  *
4457  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
4458  *
4459  * The reference must be released by the same entity that added the reference
4460  * In the above scheme, the eager is the entity that adds and releases the
4461  * references. Note that tcp_accept_finish executes in the squeue of the eager
4462  * (albeit after it is attached to the acceptor stream). Though 1. executes
4463  * in the listener's squeue, the eager is nascent at this point and the
4464  * reference can be considered to have been added on behalf of the eager.
4465  *
4466  * Eager getting a Reset or listener closing:
4467  * ==========================================
4468  *
4469  * Once the listener and eager are linked, the listener never does the unlink.
4470  * If the listener needs to close, tcp_eager_cleanup() is called which queues
4471  * a message on all eager perimeter. The eager then does the unlink, clears
4472  * any pointers to the listener's queue and drops the reference to the
4473  * listener. The listener waits in tcp_close outside the squeue until its
4474  * refcount has dropped to 1. This ensures that the listener has waited for
4475  * all eagers to clear their association with the listener.
4476  *
4477  * Similarly, if eager decides to go away, it can unlink itself and close.
4478  * When the T_CONN_RES comes down, we check if eager has closed. Note that
4479  * the reference to eager is still valid because of the extra ref we put
4480  * in tcp_send_conn_ind.
4481  *
4482  * Listener can always locate the eager under the protection
4483  * of the listener->tcp_eager_lock, and then do a refhold
4484  * on the eager during the accept processing.
4485  *
4486  * The acceptor stream accesses the eager in the accept processing
4487  * based on the ref placed on eager before sending T_conn_ind.
4488  * The only entity that can negate this refhold is a listener close
4489  * which is mutually exclusive with an active acceptor stream.
4490  *
4491  * Eager's reference on the listener
4492  * ===================================
4493  *
4494  * If the accept happens (even on a closed eager) the eager drops its
4495  * reference on the listener at the start of tcp_accept_finish. If the
4496  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
4497  * the reference is dropped in tcp_closei_local. If the listener closes,
4498  * the reference is dropped in tcp_eager_kill. In all cases the reference
4499  * is dropped while executing in the eager's context (squeue).
4500  */
4501 /* END CSTYLED */
4502 
4503 /* Process the SYN packet, mp, directed at the listener 'tcp' */
4504 
4505 /*
4506  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
4507  * tcp_input_data will not see any packets for listeners since the listener
4508  * has conn_recv set to tcp_input_listener.
4509  */
4510 /* ARGSUSED */
4511 void
4512 tcp_input_listener(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4513 {
4514 	tcpha_t		*tcpha;
4515 	uint32_t	seg_seq;
4516 	tcp_t		*eager;
4517 	int		err;
4518 	conn_t		*econnp = NULL;
4519 	squeue_t	*new_sqp;
4520 	mblk_t		*mp1;
4521 	uint_t 		ip_hdr_len;
4522 	conn_t		*lconnp = (conn_t *)arg;
4523 	tcp_t		*listener = lconnp->conn_tcp;
4524 	tcp_stack_t	*tcps = listener->tcp_tcps;
4525 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
4526 	uint_t		flags;
4527 	mblk_t		*tpi_mp;
4528 	uint_t		ifindex = ira->ira_ruifindex;
4529 	boolean_t	tlc_set = B_FALSE;
4530 
4531 	ip_hdr_len = ira->ira_ip_hdr_length;
4532 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
4533 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
4534 
4535 	if (!(flags & TH_SYN)) {
4536 		if ((flags & TH_RST) || (flags & TH_URG)) {
4537 			freemsg(mp);
4538 			return;
4539 		}
4540 		if (flags & TH_ACK) {
4541 			/* Note this executes in listener's squeue */
4542 			tcp_xmit_listeners_reset(mp, ira, ipst, lconnp);
4543 			return;
4544 		}
4545 
4546 		freemsg(mp);
4547 		return;
4548 	}
4549 
4550 	if (listener->tcp_state != TCPS_LISTEN)
4551 		goto error2;
4552 
4553 	ASSERT(IPCL_IS_BOUND(lconnp));
4554 
4555 	mutex_enter(&listener->tcp_eager_lock);
4556 
4557 	/*
4558 	 * The system is under memory pressure, so we need to do our part
4559 	 * to relieve the pressure.  So we only accept new request if there
4560 	 * is nothing waiting to be accepted or waiting to complete the 3-way
4561 	 * handshake.  This means that busy listener will not get too many
4562 	 * new requests which they cannot handle in time while non-busy
4563 	 * listener is still functioning properly.
4564 	 */
4565 	if (tcps->tcps_reclaim && (listener->tcp_conn_req_cnt_q > 0 ||
4566 	    listener->tcp_conn_req_cnt_q0 > 0)) {
4567 		mutex_exit(&listener->tcp_eager_lock);
4568 		TCP_STAT(tcps, tcp_listen_mem_drop);
4569 		goto error2;
4570 	}
4571 
4572 	if (listener->tcp_conn_req_cnt_q >= listener->tcp_conn_req_max) {
4573 		mutex_exit(&listener->tcp_eager_lock);
4574 		TCP_STAT(tcps, tcp_listendrop);
4575 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
4576 		if (lconnp->conn_debug) {
4577 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
4578 			    "tcp_input_listener: listen backlog (max=%d) "
4579 			    "overflow (%d pending) on %s",
4580 			    listener->tcp_conn_req_max,
4581 			    listener->tcp_conn_req_cnt_q,
4582 			    tcp_display(listener, NULL, DISP_PORT_ONLY));
4583 		}
4584 		goto error2;
4585 	}
4586 
4587 	if (listener->tcp_conn_req_cnt_q0 >=
4588 	    listener->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
4589 		/*
4590 		 * Q0 is full. Drop a pending half-open req from the queue
4591 		 * to make room for the new SYN req. Also mark the time we
4592 		 * drop a SYN.
4593 		 *
4594 		 * A more aggressive defense against SYN attack will
4595 		 * be to set the "tcp_syn_defense" flag now.
4596 		 */
4597 		TCP_STAT(tcps, tcp_listendropq0);
4598 		listener->tcp_last_rcv_lbolt = ddi_get_lbolt64();
4599 		if (!tcp_drop_q0(listener)) {
4600 			mutex_exit(&listener->tcp_eager_lock);
4601 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
4602 			if (lconnp->conn_debug) {
4603 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4604 				    "tcp_input_listener: listen half-open "
4605 				    "queue (max=%d) full (%d pending) on %s",
4606 				    tcps->tcps_conn_req_max_q0,
4607 				    listener->tcp_conn_req_cnt_q0,
4608 				    tcp_display(listener, NULL,
4609 				    DISP_PORT_ONLY));
4610 			}
4611 			goto error2;
4612 		}
4613 	}
4614 
4615 	/*
4616 	 * Enforce the limit set on the number of connections per listener.
4617 	 * Note that tlc_cnt starts with 1.  So need to add 1 to tlc_max
4618 	 * for comparison.
4619 	 */
4620 	if (listener->tcp_listen_cnt != NULL) {
4621 		tcp_listen_cnt_t *tlc = listener->tcp_listen_cnt;
4622 		int64_t now;
4623 
4624 		if (atomic_add_32_nv(&tlc->tlc_cnt, 1) > tlc->tlc_max + 1) {
4625 			mutex_exit(&listener->tcp_eager_lock);
4626 			now = ddi_get_lbolt64();
4627 			atomic_add_32(&tlc->tlc_cnt, -1);
4628 			TCP_STAT(tcps, tcp_listen_cnt_drop);
4629 			tlc->tlc_drop++;
4630 			if (now - tlc->tlc_report_time >
4631 			    MSEC_TO_TICK(TCP_TLC_REPORT_INTERVAL)) {
4632 				zcmn_err(lconnp->conn_zoneid, CE_WARN,
4633 				    "Listener (port %d) connection max (%u) "
4634 				    "reached: %u attempts dropped total\n",
4635 				    ntohs(listener->tcp_connp->conn_lport),
4636 				    tlc->tlc_max, tlc->tlc_drop);
4637 				tlc->tlc_report_time = now;
4638 			}
4639 			goto error2;
4640 		}
4641 		tlc_set = B_TRUE;
4642 	}
4643 
4644 	mutex_exit(&listener->tcp_eager_lock);
4645 
4646 	/*
4647 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
4648 	 * or based on the ring (for packets from GLD). Otherwise it is
4649 	 * set based on lbolt i.e., a somewhat random number.
4650 	 */
4651 	ASSERT(ira->ira_sqp != NULL);
4652 	new_sqp = ira->ira_sqp;
4653 
4654 	econnp = (conn_t *)tcp_get_conn(arg2, tcps);
4655 	if (econnp == NULL)
4656 		goto error2;
4657 
4658 	ASSERT(econnp->conn_netstack == lconnp->conn_netstack);
4659 	econnp->conn_sqp = new_sqp;
4660 	econnp->conn_initial_sqp = new_sqp;
4661 	econnp->conn_ixa->ixa_sqp = new_sqp;
4662 
4663 	econnp->conn_fport = tcpha->tha_lport;
4664 	econnp->conn_lport = tcpha->tha_fport;
4665 
4666 	err = conn_inherit_parent(lconnp, econnp);
4667 	if (err != 0)
4668 		goto error3;
4669 
4670 	/* We already know the laddr of the new connection is ours */
4671 	econnp->conn_ixa->ixa_src_generation = ipst->ips_src_generation;
4672 
4673 	ASSERT(OK_32PTR(mp->b_rptr));
4674 	ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION ||
4675 	    IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
4676 
4677 	if (lconnp->conn_family == AF_INET) {
4678 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
4679 		tpi_mp = tcp_conn_create_v4(lconnp, econnp, mp, ira);
4680 	} else {
4681 		tpi_mp = tcp_conn_create_v6(lconnp, econnp, mp, ira);
4682 	}
4683 
4684 	if (tpi_mp == NULL)
4685 		goto error3;
4686 
4687 	eager = econnp->conn_tcp;
4688 	eager->tcp_detached = B_TRUE;
4689 	SOCK_CONNID_INIT(eager->tcp_connid);
4690 
4691 	tcp_init_values(eager);
4692 
4693 	ASSERT((econnp->conn_ixa->ixa_flags &
4694 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4695 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO)) ==
4696 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4697 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO));
4698 
4699 	if (!tcps->tcps_dev_flow_ctl)
4700 		econnp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
4701 
4702 	/* Prepare for diffing against previous packets */
4703 	eager->tcp_recvifindex = 0;
4704 	eager->tcp_recvhops = 0xffffffffU;
4705 
4706 	if (!(ira->ira_flags & IRAF_IS_IPV4) && econnp->conn_bound_if == 0) {
4707 		if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_faddr_v6) ||
4708 		    IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6)) {
4709 			econnp->conn_incoming_ifindex = ifindex;
4710 			econnp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
4711 			econnp->conn_ixa->ixa_scopeid = ifindex;
4712 		}
4713 	}
4714 
4715 	if ((ira->ira_flags & (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS)) ==
4716 	    (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS) &&
4717 	    tcps->tcps_rev_src_routes) {
4718 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
4719 		ip_pkt_t *ipp = &econnp->conn_xmit_ipp;
4720 
4721 		/* Source routing option copyover (reverse it) */
4722 		err = ip_find_hdr_v4(ipha, ipp, B_TRUE);
4723 		if (err != 0) {
4724 			freemsg(tpi_mp);
4725 			goto error3;
4726 		}
4727 		ip_pkt_source_route_reverse_v4(ipp);
4728 	}
4729 
4730 	ASSERT(eager->tcp_conn.tcp_eager_conn_ind == NULL);
4731 	ASSERT(!eager->tcp_tconnind_started);
4732 	/*
4733 	 * If the SYN came with a credential, it's a loopback packet or a
4734 	 * labeled packet; attach the credential to the TPI message.
4735 	 */
4736 	if (ira->ira_cred != NULL)
4737 		mblk_setcred(tpi_mp, ira->ira_cred, ira->ira_cpid);
4738 
4739 	eager->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4740 
4741 	/* Inherit the listener's SSL protection state */
4742 	if ((eager->tcp_kssl_ent = listener->tcp_kssl_ent) != NULL) {
4743 		kssl_hold_ent(eager->tcp_kssl_ent);
4744 		eager->tcp_kssl_pending = B_TRUE;
4745 	}
4746 
4747 	/* Inherit the listener's non-STREAMS flag */
4748 	if (IPCL_IS_NONSTR(lconnp)) {
4749 		econnp->conn_flags |= IPCL_NONSTR;
4750 	}
4751 
4752 	ASSERT(eager->tcp_ordrel_mp == NULL);
4753 
4754 	if (!IPCL_IS_NONSTR(econnp)) {
4755 		/*
4756 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
4757 		 * at close time, we will always have that to send up.
4758 		 * Otherwise, we need to do special handling in case the
4759 		 * allocation fails at that time.
4760 		 */
4761 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
4762 			goto error3;
4763 	}
4764 	/*
4765 	 * Now that the IP addresses and ports are setup in econnp we
4766 	 * can do the IPsec policy work.
4767 	 */
4768 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
4769 		if (lconnp->conn_policy != NULL) {
4770 			/*
4771 			 * Inherit the policy from the listener; use
4772 			 * actions from ira
4773 			 */
4774 			if (!ip_ipsec_policy_inherit(econnp, lconnp, ira)) {
4775 				CONN_DEC_REF(econnp);
4776 				freemsg(mp);
4777 				goto error3;
4778 			}
4779 		}
4780 	}
4781 
4782 	/* Inherit various TCP parameters from the listener */
4783 	eager->tcp_naglim = listener->tcp_naglim;
4784 	eager->tcp_first_timer_threshold = listener->tcp_first_timer_threshold;
4785 	eager->tcp_second_timer_threshold =
4786 	    listener->tcp_second_timer_threshold;
4787 	eager->tcp_first_ctimer_threshold =
4788 	    listener->tcp_first_ctimer_threshold;
4789 	eager->tcp_second_ctimer_threshold =
4790 	    listener->tcp_second_ctimer_threshold;
4791 
4792 	/*
4793 	 * tcp_set_destination() may set tcp_rwnd according to the route
4794 	 * metrics. If it does not, the eager's receive window will be set
4795 	 * to the listener's receive window later in this function.
4796 	 */
4797 	eager->tcp_rwnd = 0;
4798 
4799 	/*
4800 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
4801 	 * calling tcp_process_options() which set the initial cwnd.
4802 	 */
4803 	eager->tcp_init_cwnd = listener->tcp_init_cwnd;
4804 
4805 	if (is_system_labeled()) {
4806 		ip_xmit_attr_t *ixa = econnp->conn_ixa;
4807 
4808 		ASSERT(ira->ira_tsl != NULL);
4809 		/* Discard any old label */
4810 		if (ixa->ixa_free_flags & IXA_FREE_TSL) {
4811 			ASSERT(ixa->ixa_tsl != NULL);
4812 			label_rele(ixa->ixa_tsl);
4813 			ixa->ixa_free_flags &= ~IXA_FREE_TSL;
4814 			ixa->ixa_tsl = NULL;
4815 		}
4816 		if ((lconnp->conn_mlp_type != mlptSingle ||
4817 		    lconnp->conn_mac_mode != CONN_MAC_DEFAULT) &&
4818 		    ira->ira_tsl != NULL) {
4819 			/*
4820 			 * If this is an MLP connection or a MAC-Exempt
4821 			 * connection with an unlabeled node, packets are to be
4822 			 * exchanged using the security label of the received
4823 			 * SYN packet instead of the server application's label.
4824 			 * tsol_check_dest called from ip_set_destination
4825 			 * might later update TSF_UNLABELED by replacing
4826 			 * ixa_tsl with a new label.
4827 			 */
4828 			label_hold(ira->ira_tsl);
4829 			ip_xmit_attr_replace_tsl(ixa, ira->ira_tsl);
4830 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
4831 			    econnp, ts_label_t *, ixa->ixa_tsl)
4832 		} else {
4833 			ixa->ixa_tsl = crgetlabel(econnp->conn_cred);
4834 			DTRACE_PROBE2(syn_accept, conn_t *,
4835 			    econnp, ts_label_t *, ixa->ixa_tsl)
4836 		}
4837 		/*
4838 		 * conn_connect() called from tcp_set_destination will verify
4839 		 * the destination is allowed to receive packets at the
4840 		 * security label of the SYN-ACK we are generating. As part of
4841 		 * that, tsol_check_dest() may create a new effective label for
4842 		 * this connection.
4843 		 * Finally conn_connect() will call conn_update_label.
4844 		 * All that remains for TCP to do is to call
4845 		 * conn_build_hdr_template which is done as part of
4846 		 * tcp_set_destination.
4847 		 */
4848 	}
4849 
4850 	/*
4851 	 * Since we will clear tcp_listener before we clear tcp_detached
4852 	 * in the accept code we need tcp_hard_binding aka tcp_accept_inprogress
4853 	 * so we can tell a TCP_DETACHED_NONEAGER apart.
4854 	 */
4855 	eager->tcp_hard_binding = B_TRUE;
4856 
4857 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
4858 	    TCP_BIND_HASH(econnp->conn_lport)], eager, 0);
4859 
4860 	CL_INET_CONNECT(econnp, B_FALSE, err);
4861 	if (err != 0) {
4862 		tcp_bind_hash_remove(eager);
4863 		goto error3;
4864 	}
4865 
4866 	/*
4867 	 * No need to check for multicast destination since ip will only pass
4868 	 * up multicasts to those that have expressed interest
4869 	 * TODO: what about rejecting broadcasts?
4870 	 * Also check that source is not a multicast or broadcast address.
4871 	 */
4872 	eager->tcp_state = TCPS_SYN_RCVD;
4873 	SOCK_CONNID_BUMP(eager->tcp_connid);
4874 
4875 	/*
4876 	 * Adapt our mss, ttl, ... based on the remote address.
4877 	 */
4878 
4879 	if (tcp_set_destination(eager) != 0) {
4880 		BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4881 		/* Undo the bind_hash_insert */
4882 		tcp_bind_hash_remove(eager);
4883 		goto error3;
4884 	}
4885 
4886 	/* Process all TCP options. */
4887 	tcp_process_options(eager, tcpha);
4888 
4889 	/* Is the other end ECN capable? */
4890 	if (tcps->tcps_ecn_permitted >= 1 &&
4891 	    (tcpha->tha_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
4892 		eager->tcp_ecn_ok = B_TRUE;
4893 	}
4894 
4895 	/*
4896 	 * The listener's conn_rcvbuf should be the default window size or a
4897 	 * window size changed via SO_RCVBUF option. First round up the
4898 	 * eager's tcp_rwnd to the nearest MSS. Then find out the window
4899 	 * scale option value if needed. Call tcp_rwnd_set() to finish the
4900 	 * setting.
4901 	 *
4902 	 * Note if there is a rpipe metric associated with the remote host,
4903 	 * we should not inherit receive window size from listener.
4904 	 */
4905 	eager->tcp_rwnd = MSS_ROUNDUP(
4906 	    (eager->tcp_rwnd == 0 ? econnp->conn_rcvbuf :
4907 	    eager->tcp_rwnd), eager->tcp_mss);
4908 	if (eager->tcp_snd_ws_ok)
4909 		tcp_set_ws_value(eager);
4910 	/*
4911 	 * Note that this is the only place tcp_rwnd_set() is called for
4912 	 * accepting a connection.  We need to call it here instead of
4913 	 * after the 3-way handshake because we need to tell the other
4914 	 * side our rwnd in the SYN-ACK segment.
4915 	 */
4916 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
4917 
4918 	ASSERT(eager->tcp_connp->conn_rcvbuf != 0 &&
4919 	    eager->tcp_connp->conn_rcvbuf == eager->tcp_rwnd);
4920 
4921 	ASSERT(econnp->conn_rcvbuf != 0 &&
4922 	    econnp->conn_rcvbuf == eager->tcp_rwnd);
4923 
4924 	/* Put a ref on the listener for the eager. */
4925 	CONN_INC_REF(lconnp);
4926 	mutex_enter(&listener->tcp_eager_lock);
4927 	listener->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
4928 	eager->tcp_eager_next_q0 = listener->tcp_eager_next_q0;
4929 	listener->tcp_eager_next_q0 = eager;
4930 	eager->tcp_eager_prev_q0 = listener;
4931 
4932 	/* Set tcp_listener before adding it to tcp_conn_fanout */
4933 	eager->tcp_listener = listener;
4934 	eager->tcp_saved_listener = listener;
4935 
4936 	/*
4937 	 * Set tcp_listen_cnt so that when the connection is done, the counter
4938 	 * is decremented.
4939 	 */
4940 	eager->tcp_listen_cnt = listener->tcp_listen_cnt;
4941 
4942 	/*
4943 	 * Tag this detached tcp vector for later retrieval
4944 	 * by our listener client in tcp_accept().
4945 	 */
4946 	eager->tcp_conn_req_seqnum = listener->tcp_conn_req_seqnum;
4947 	listener->tcp_conn_req_cnt_q0++;
4948 	if (++listener->tcp_conn_req_seqnum == -1) {
4949 		/*
4950 		 * -1 is "special" and defined in TPI as something
4951 		 * that should never be used in T_CONN_IND
4952 		 */
4953 		++listener->tcp_conn_req_seqnum;
4954 	}
4955 	mutex_exit(&listener->tcp_eager_lock);
4956 
4957 	if (listener->tcp_syn_defense) {
4958 		/* Don't drop the SYN that comes from a good IP source */
4959 		ipaddr_t *addr_cache;
4960 
4961 		addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
4962 		if (addr_cache != NULL && econnp->conn_faddr_v4 ==
4963 		    addr_cache[IP_ADDR_CACHE_HASH(econnp->conn_faddr_v4)]) {
4964 			eager->tcp_dontdrop = B_TRUE;
4965 		}
4966 	}
4967 
4968 	/*
4969 	 * We need to insert the eager in its own perimeter but as soon
4970 	 * as we do that, we expose the eager to the classifier and
4971 	 * should not touch any field outside the eager's perimeter.
4972 	 * So do all the work necessary before inserting the eager
4973 	 * in its own perimeter. Be optimistic that conn_connect()
4974 	 * will succeed but undo everything if it fails.
4975 	 */
4976 	seg_seq = ntohl(tcpha->tha_seq);
4977 	eager->tcp_irs = seg_seq;
4978 	eager->tcp_rack = seg_seq;
4979 	eager->tcp_rnxt = seg_seq + 1;
4980 	eager->tcp_tcpha->tha_ack = htonl(eager->tcp_rnxt);
4981 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
4982 	eager->tcp_state = TCPS_SYN_RCVD;
4983 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
4984 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
4985 	if (mp1 == NULL) {
4986 		/*
4987 		 * Increment the ref count as we are going to
4988 		 * enqueueing an mp in squeue
4989 		 */
4990 		CONN_INC_REF(econnp);
4991 		goto error;
4992 	}
4993 
4994 	/*
4995 	 * We need to start the rto timer. In normal case, we start
4996 	 * the timer after sending the packet on the wire (or at
4997 	 * least believing that packet was sent by waiting for
4998 	 * conn_ip_output() to return). Since this is the first packet
4999 	 * being sent on the wire for the eager, our initial tcp_rto
5000 	 * is at least tcp_rexmit_interval_min which is a fairly
5001 	 * large value to allow the algorithm to adjust slowly to large
5002 	 * fluctuations of RTT during first few transmissions.
5003 	 *
5004 	 * Starting the timer first and then sending the packet in this
5005 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5006 	 * is of the order of several 100ms and starting the timer
5007 	 * first and then sending the packet will result in difference
5008 	 * of few micro seconds.
5009 	 *
5010 	 * Without this optimization, we are forced to hold the fanout
5011 	 * lock across the ipcl_bind_insert() and sending the packet
5012 	 * so that we don't race against an incoming packet (maybe RST)
5013 	 * for this eager.
5014 	 *
5015 	 * It is necessary to acquire an extra reference on the eager
5016 	 * at this point and hold it until after tcp_send_data() to
5017 	 * ensure against an eager close race.
5018 	 */
5019 
5020 	CONN_INC_REF(econnp);
5021 
5022 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5023 
5024 	/*
5025 	 * Insert the eager in its own perimeter now. We are ready to deal
5026 	 * with any packets on eager.
5027 	 */
5028 	if (ipcl_conn_insert(econnp) != 0)
5029 		goto error;
5030 
5031 	ASSERT(econnp->conn_ixa->ixa_notify_cookie == econnp->conn_tcp);
5032 	freemsg(mp);
5033 	/*
5034 	 * Send the SYN-ACK. Use the right squeue so that conn_ixa is
5035 	 * only used by one thread at a time.
5036 	 */
5037 	if (econnp->conn_sqp == lconnp->conn_sqp) {
5038 		(void) conn_ip_output(mp1, econnp->conn_ixa);
5039 		CONN_DEC_REF(econnp);
5040 	} else {
5041 		SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_send_synack,
5042 		    econnp, NULL, SQ_PROCESS, SQTAG_TCP_SEND_SYNACK);
5043 	}
5044 	return;
5045 error:
5046 	freemsg(mp1);
5047 	eager->tcp_closemp_used = B_TRUE;
5048 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5049 	mp1 = &eager->tcp_closemp;
5050 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5051 	    econnp, NULL, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5052 
5053 	/*
5054 	 * If a connection already exists, send the mp to that connections so
5055 	 * that it can be appropriately dealt with.
5056 	 */
5057 	ipst = tcps->tcps_netstack->netstack_ip;
5058 
5059 	if ((econnp = ipcl_classify(mp, ira, ipst)) != NULL) {
5060 		if (!IPCL_IS_CONNECTED(econnp)) {
5061 			/*
5062 			 * Something bad happened. ipcl_conn_insert()
5063 			 * failed because a connection already existed
5064 			 * in connected hash but we can't find it
5065 			 * anymore (someone blew it away). Just
5066 			 * free this message and hopefully remote
5067 			 * will retransmit at which time the SYN can be
5068 			 * treated as a new connection or dealth with
5069 			 * a TH_RST if a connection already exists.
5070 			 */
5071 			CONN_DEC_REF(econnp);
5072 			freemsg(mp);
5073 		} else {
5074 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp, tcp_input_data,
5075 			    econnp, ira, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5076 		}
5077 	} else {
5078 		/* Nobody wants this packet */
5079 		freemsg(mp);
5080 	}
5081 	return;
5082 error3:
5083 	CONN_DEC_REF(econnp);
5084 error2:
5085 	freemsg(mp);
5086 	if (tlc_set)
5087 		atomic_add_32(&listener->tcp_listen_cnt->tlc_cnt, -1);
5088 }
5089 
5090 /* ARGSUSED2 */
5091 void
5092 tcp_send_synack(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5093 {
5094 	conn_t	*econnp = (conn_t *)arg;
5095 	tcp_t	*tcp = econnp->conn_tcp;
5096 
5097 	/* Guard against a RST having blown it away while on the squeue */
5098 	if (tcp->tcp_state == TCPS_CLOSED) {
5099 		freemsg(mp);
5100 		return;
5101 	}
5102 
5103 	(void) conn_ip_output(mp, econnp->conn_ixa);
5104 }
5105 
5106 /*
5107  * In an ideal case of vertical partition in NUMA architecture, its
5108  * beneficial to have the listener and all the incoming connections
5109  * tied to the same squeue. The other constraint is that incoming
5110  * connections should be tied to the squeue attached to interrupted
5111  * CPU for obvious locality reason so this leaves the listener to
5112  * be tied to the same squeue. Our only problem is that when listener
5113  * is binding, the CPU that will get interrupted by the NIC whose
5114  * IP address the listener is binding to is not even known. So
5115  * the code below allows us to change that binding at the time the
5116  * CPU is interrupted by virtue of incoming connection's squeue.
5117  *
5118  * This is usefull only in case of a listener bound to a specific IP
5119  * address. For other kind of listeners, they get bound the
5120  * very first time and there is no attempt to rebind them.
5121  */
5122 void
5123 tcp_input_listener_unbound(void *arg, mblk_t *mp, void *arg2,
5124     ip_recv_attr_t *ira)
5125 {
5126 	conn_t		*connp = (conn_t *)arg;
5127 	squeue_t	*sqp = (squeue_t *)arg2;
5128 	squeue_t	*new_sqp;
5129 	uint32_t	conn_flags;
5130 
5131 	/*
5132 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
5133 	 * or based on the ring (for packets from GLD). Otherwise it is
5134 	 * set based on lbolt i.e., a somewhat random number.
5135 	 */
5136 	ASSERT(ira->ira_sqp != NULL);
5137 	new_sqp = ira->ira_sqp;
5138 
5139 	if (connp->conn_fanout == NULL)
5140 		goto done;
5141 
5142 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5143 		mutex_enter(&connp->conn_fanout->connf_lock);
5144 		mutex_enter(&connp->conn_lock);
5145 		/*
5146 		 * No one from read or write side can access us now
5147 		 * except for already queued packets on this squeue.
5148 		 * But since we haven't changed the squeue yet, they
5149 		 * can't execute. If they are processed after we have
5150 		 * changed the squeue, they are sent back to the
5151 		 * correct squeue down below.
5152 		 * But a listner close can race with processing of
5153 		 * incoming SYN. If incoming SYN processing changes
5154 		 * the squeue then the listener close which is waiting
5155 		 * to enter the squeue would operate on the wrong
5156 		 * squeue. Hence we don't change the squeue here unless
5157 		 * the refcount is exactly the minimum refcount. The
5158 		 * minimum refcount of 4 is counted as - 1 each for
5159 		 * TCP and IP, 1 for being in the classifier hash, and
5160 		 * 1 for the mblk being processed.
5161 		 */
5162 
5163 		if (connp->conn_ref != 4 ||
5164 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5165 			mutex_exit(&connp->conn_lock);
5166 			mutex_exit(&connp->conn_fanout->connf_lock);
5167 			goto done;
5168 		}
5169 		if (connp->conn_sqp != new_sqp) {
5170 			while (connp->conn_sqp != new_sqp)
5171 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5172 			/* No special MT issues for outbound ixa_sqp hint */
5173 			connp->conn_ixa->ixa_sqp = new_sqp;
5174 		}
5175 
5176 		do {
5177 			conn_flags = connp->conn_flags;
5178 			conn_flags |= IPCL_FULLY_BOUND;
5179 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5180 			    conn_flags);
5181 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5182 
5183 		mutex_exit(&connp->conn_fanout->connf_lock);
5184 		mutex_exit(&connp->conn_lock);
5185 
5186 		/*
5187 		 * Assume we have picked a good squeue for the listener. Make
5188 		 * subsequent SYNs not try to change the squeue.
5189 		 */
5190 		connp->conn_recv = tcp_input_listener;
5191 	}
5192 
5193 done:
5194 	if (connp->conn_sqp != sqp) {
5195 		CONN_INC_REF(connp);
5196 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5197 		    ira, SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5198 	} else {
5199 		tcp_input_listener(connp, mp, sqp, ira);
5200 	}
5201 }
5202 
5203 /*
5204  * Successful connect request processing begins when our client passes
5205  * a T_CONN_REQ message into tcp_wput(), which performs function calls into
5206  * IP and the passes a T_OK_ACK (or T_ERROR_ACK upstream).
5207  *
5208  * After various error checks are completed, tcp_tpi_connect() lays
5209  * the target address and port into the composite header template.
5210  * Then we ask IP for information, including a source address if we didn't
5211  * already have one. Finally we prepare to send the SYN packet, and then
5212  * send up the T_OK_ACK reply message.
5213  */
5214 static void
5215 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5216 {
5217 	sin_t		*sin;
5218 	struct T_conn_req	*tcr;
5219 	struct sockaddr	*sa;
5220 	socklen_t	len;
5221 	int		error;
5222 	cred_t		*cr;
5223 	pid_t		cpid;
5224 	conn_t		*connp = tcp->tcp_connp;
5225 	queue_t		*q = connp->conn_wq;
5226 
5227 	/*
5228 	 * All Solaris components should pass a db_credp
5229 	 * for this TPI message, hence we ASSERT.
5230 	 * But in case there is some other M_PROTO that looks
5231 	 * like a TPI message sent by some other kernel
5232 	 * component, we check and return an error.
5233 	 */
5234 	cr = msg_getcred(mp, &cpid);
5235 	ASSERT(cr != NULL);
5236 	if (cr == NULL) {
5237 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5238 		return;
5239 	}
5240 
5241 	tcr = (struct T_conn_req *)mp->b_rptr;
5242 
5243 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5244 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5245 		tcp_err_ack(tcp, mp, TPROTO, 0);
5246 		return;
5247 	}
5248 
5249 	/*
5250 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5251 	 * will always have that to send up.  Otherwise, we need to do
5252 	 * special handling in case the allocation fails at that time.
5253 	 * If the end point is TPI, the tcp_t can be reused and the
5254 	 * tcp_ordrel_mp may be allocated already.
5255 	 */
5256 	if (tcp->tcp_ordrel_mp == NULL) {
5257 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5258 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5259 			return;
5260 		}
5261 	}
5262 
5263 	/*
5264 	 * Determine packet type based on type of address passed in
5265 	 * the request should contain an IPv4 or IPv6 address.
5266 	 * Make sure that address family matches the type of
5267 	 * family of the address passed down.
5268 	 */
5269 	switch (tcr->DEST_length) {
5270 	default:
5271 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5272 		return;
5273 
5274 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5275 		/*
5276 		 * XXX: The check for valid DEST_length was not there
5277 		 * in earlier releases and some buggy
5278 		 * TLI apps (e.g Sybase) got away with not feeding
5279 		 * in sin_zero part of address.
5280 		 * We allow that bug to keep those buggy apps humming.
5281 		 * Test suites require the check on DEST_length.
5282 		 * We construct a new mblk with valid DEST_length
5283 		 * free the original so the rest of the code does
5284 		 * not have to keep track of this special shorter
5285 		 * length address case.
5286 		 */
5287 		mblk_t *nmp;
5288 		struct T_conn_req *ntcr;
5289 		sin_t *nsin;
5290 
5291 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5292 		    tcr->OPT_length, BPRI_HI);
5293 		if (nmp == NULL) {
5294 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5295 			return;
5296 		}
5297 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5298 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5299 		ntcr->PRIM_type = T_CONN_REQ;
5300 		ntcr->DEST_length = sizeof (sin_t);
5301 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5302 
5303 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5304 		*nsin = sin_null;
5305 		/* Get pointer to shorter address to copy from original mp */
5306 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5307 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5308 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5309 			freemsg(nmp);
5310 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5311 			return;
5312 		}
5313 		nsin->sin_family = sin->sin_family;
5314 		nsin->sin_port = sin->sin_port;
5315 		nsin->sin_addr = sin->sin_addr;
5316 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5317 		nmp->b_wptr = (uchar_t *)&nsin[1];
5318 		if (tcr->OPT_length != 0) {
5319 			ntcr->OPT_length = tcr->OPT_length;
5320 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5321 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5322 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5323 			    tcr->OPT_length);
5324 			nmp->b_wptr += tcr->OPT_length;
5325 		}
5326 		freemsg(mp);	/* original mp freed */
5327 		mp = nmp;	/* re-initialize original variables */
5328 		tcr = ntcr;
5329 	}
5330 	/* FALLTHRU */
5331 
5332 	case sizeof (sin_t):
5333 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5334 		    sizeof (sin_t));
5335 		len = sizeof (sin_t);
5336 		break;
5337 
5338 	case sizeof (sin6_t):
5339 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5340 		    sizeof (sin6_t));
5341 		len = sizeof (sin6_t);
5342 		break;
5343 	}
5344 
5345 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
5346 	if (error != 0) {
5347 		tcp_err_ack(tcp, mp, TSYSERR, error);
5348 		return;
5349 	}
5350 
5351 	/*
5352 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5353 	 * should key on their sequence number and cut them loose.
5354 	 */
5355 
5356 	/*
5357 	 * If options passed in, feed it for verification and handling
5358 	 */
5359 	if (tcr->OPT_length != 0) {
5360 		mblk_t	*ok_mp;
5361 		mblk_t	*discon_mp;
5362 		mblk_t  *conn_opts_mp;
5363 		int t_error, sys_error, do_disconnect;
5364 
5365 		conn_opts_mp = NULL;
5366 
5367 		if (tcp_conprim_opt_process(tcp, mp,
5368 		    &do_disconnect, &t_error, &sys_error) < 0) {
5369 			if (do_disconnect) {
5370 				ASSERT(t_error == 0 && sys_error == 0);
5371 				discon_mp = mi_tpi_discon_ind(NULL,
5372 				    ECONNREFUSED, 0);
5373 				if (!discon_mp) {
5374 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5375 					    TSYSERR, ENOMEM);
5376 					return;
5377 				}
5378 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5379 				if (!ok_mp) {
5380 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5381 					    TSYSERR, ENOMEM);
5382 					return;
5383 				}
5384 				qreply(q, ok_mp);
5385 				qreply(q, discon_mp); /* no flush! */
5386 			} else {
5387 				ASSERT(t_error != 0);
5388 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5389 				    sys_error);
5390 			}
5391 			return;
5392 		}
5393 		/*
5394 		 * Success in setting options, the mp option buffer represented
5395 		 * by OPT_length/offset has been potentially modified and
5396 		 * contains results of option processing. We copy it in
5397 		 * another mp to save it for potentially influencing returning
5398 		 * it in T_CONN_CONN.
5399 		 */
5400 		if (tcr->OPT_length != 0) { /* there are resulting options */
5401 			conn_opts_mp = copyb(mp);
5402 			if (!conn_opts_mp) {
5403 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5404 				    TSYSERR, ENOMEM);
5405 				return;
5406 			}
5407 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5408 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5409 			/*
5410 			 * Note:
5411 			 * These resulting option negotiation can include any
5412 			 * end-to-end negotiation options but there no such
5413 			 * thing (yet?) in our TCP/IP.
5414 			 */
5415 		}
5416 	}
5417 
5418 	/* call the non-TPI version */
5419 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
5420 	if (error < 0) {
5421 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
5422 	} else if (error > 0) {
5423 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
5424 	} else {
5425 		mp = mi_tpi_ok_ack_alloc(mp);
5426 	}
5427 
5428 	/*
5429 	 * Note: Code below is the "failure" case
5430 	 */
5431 	/* return error ack and blow away saved option results if any */
5432 connect_failed:
5433 	if (mp != NULL)
5434 		putnext(connp->conn_rq, mp);
5435 	else {
5436 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5437 		    TSYSERR, ENOMEM);
5438 	}
5439 }
5440 
5441 /*
5442  * Handle connect to IPv4 destinations, including connections for AF_INET6
5443  * sockets connecting to IPv4 mapped IPv6 destinations.
5444  * Returns zero if OK, a positive errno, or a negative TLI error.
5445  */
5446 static int
5447 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
5448     uint_t srcid)
5449 {
5450 	ipaddr_t 	dstaddr = *dstaddrp;
5451 	uint16_t 	lport;
5452 	conn_t		*connp = tcp->tcp_connp;
5453 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5454 	int		error;
5455 
5456 	ASSERT(connp->conn_ipversion == IPV4_VERSION);
5457 
5458 	/* Check for attempt to connect to INADDR_ANY */
5459 	if (dstaddr == INADDR_ANY)  {
5460 		/*
5461 		 * SunOS 4.x and 4.3 BSD allow an application
5462 		 * to connect a TCP socket to INADDR_ANY.
5463 		 * When they do this, the kernel picks the
5464 		 * address of one interface and uses it
5465 		 * instead.  The kernel usually ends up
5466 		 * picking the address of the loopback
5467 		 * interface.  This is an undocumented feature.
5468 		 * However, we provide the same thing here
5469 		 * in order to have source and binary
5470 		 * compatibility with SunOS 4.x.
5471 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5472 		 * generate the T_CONN_CON.
5473 		 */
5474 		dstaddr = htonl(INADDR_LOOPBACK);
5475 		*dstaddrp = dstaddr;
5476 	}
5477 
5478 	/* Handle __sin6_src_id if socket not bound to an IP address */
5479 	if (srcid != 0 && connp->conn_laddr_v4 == INADDR_ANY) {
5480 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5481 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5482 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5483 	}
5484 
5485 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &connp->conn_faddr_v6);
5486 	connp->conn_fport = dstport;
5487 
5488 	/*
5489 	 * At this point the remote destination address and remote port fields
5490 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5491 	 * have to see which state tcp was in so we can take appropriate action.
5492 	 */
5493 	if (tcp->tcp_state == TCPS_IDLE) {
5494 		/*
5495 		 * We support a quick connect capability here, allowing
5496 		 * clients to transition directly from IDLE to SYN_SENT
5497 		 * tcp_bindi will pick an unused port, insert the connection
5498 		 * in the bind hash and transition to BOUND state.
5499 		 */
5500 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5501 		    tcp, B_TRUE);
5502 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5503 		    B_FALSE, B_FALSE);
5504 		if (lport == 0)
5505 			return (-TNOADDR);
5506 	}
5507 
5508 	/*
5509 	 * Lookup the route to determine a source address and the uinfo.
5510 	 * Setup TCP parameters based on the metrics/DCE.
5511 	 */
5512 	error = tcp_set_destination(tcp);
5513 	if (error != 0)
5514 		return (error);
5515 
5516 	/*
5517 	 * Don't let an endpoint connect to itself.
5518 	 */
5519 	if (connp->conn_faddr_v4 == connp->conn_laddr_v4 &&
5520 	    connp->conn_fport == connp->conn_lport)
5521 		return (-TBADADDR);
5522 
5523 	tcp->tcp_state = TCPS_SYN_SENT;
5524 
5525 	return (ipcl_conn_insert_v4(connp));
5526 }
5527 
5528 /*
5529  * Handle connect to IPv6 destinations.
5530  * Returns zero if OK, a positive errno, or a negative TLI error.
5531  */
5532 static int
5533 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
5534     uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
5535 {
5536 	uint16_t 	lport;
5537 	conn_t		*connp = tcp->tcp_connp;
5538 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5539 	int		error;
5540 
5541 	ASSERT(connp->conn_family == AF_INET6);
5542 
5543 	/*
5544 	 * If we're here, it means that the destination address is a native
5545 	 * IPv6 address.  Return an error if conn_ipversion is not IPv6.  A
5546 	 * reason why it might not be IPv6 is if the socket was bound to an
5547 	 * IPv4-mapped IPv6 address.
5548 	 */
5549 	if (connp->conn_ipversion != IPV6_VERSION)
5550 		return (-TBADADDR);
5551 
5552 	/*
5553 	 * Interpret a zero destination to mean loopback.
5554 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
5555 	 * generate the T_CONN_CON.
5556 	 */
5557 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp))
5558 		*dstaddrp = ipv6_loopback;
5559 
5560 	/* Handle __sin6_src_id if socket not bound to an IP address */
5561 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6)) {
5562 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5563 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5564 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5565 	}
5566 
5567 	/*
5568 	 * Take care of the scope_id now.
5569 	 */
5570 	if (scope_id != 0 && IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
5571 		connp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
5572 		connp->conn_ixa->ixa_scopeid = scope_id;
5573 	} else {
5574 		connp->conn_ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
5575 	}
5576 
5577 	connp->conn_flowinfo = flowinfo;
5578 	connp->conn_faddr_v6 = *dstaddrp;
5579 	connp->conn_fport = dstport;
5580 
5581 	/*
5582 	 * At this point the remote destination address and remote port fields
5583 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5584 	 * have to see which state tcp was in so we can take appropriate action.
5585 	 */
5586 	if (tcp->tcp_state == TCPS_IDLE) {
5587 		/*
5588 		 * We support a quick connect capability here, allowing
5589 		 * clients to transition directly from IDLE to SYN_SENT
5590 		 * tcp_bindi will pick an unused port, insert the connection
5591 		 * in the bind hash and transition to BOUND state.
5592 		 */
5593 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5594 		    tcp, B_TRUE);
5595 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5596 		    B_FALSE, B_FALSE);
5597 		if (lport == 0)
5598 			return (-TNOADDR);
5599 	}
5600 
5601 	/*
5602 	 * Lookup the route to determine a source address and the uinfo.
5603 	 * Setup TCP parameters based on the metrics/DCE.
5604 	 */
5605 	error = tcp_set_destination(tcp);
5606 	if (error != 0)
5607 		return (error);
5608 
5609 	/*
5610 	 * Don't let an endpoint connect to itself.
5611 	 */
5612 	if (IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6, &connp->conn_laddr_v6) &&
5613 	    connp->conn_fport == connp->conn_lport)
5614 		return (-TBADADDR);
5615 
5616 	tcp->tcp_state = TCPS_SYN_SENT;
5617 
5618 	return (ipcl_conn_insert_v6(connp));
5619 }
5620 
5621 /*
5622  * Disconnect
5623  * Note that unlike other functions this returns a positive tli error
5624  * when it fails; it never returns an errno.
5625  */
5626 static int
5627 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
5628 {
5629 	conn_t		*lconnp;
5630 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5631 	conn_t		*connp = tcp->tcp_connp;
5632 
5633 	/*
5634 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
5635 	 * when the stream is in BOUND state. Do not send a reset,
5636 	 * since the destination IP address is not valid, and it can
5637 	 * be the initialized value of all zeros (broadcast address).
5638 	 */
5639 	if (tcp->tcp_state <= TCPS_BOUND) {
5640 		if (connp->conn_debug) {
5641 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
5642 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
5643 		}
5644 		return (TOUTSTATE);
5645 	}
5646 
5647 
5648 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
5649 
5650 		/*
5651 		 * According to TPI, for non-listeners, ignore seqnum
5652 		 * and disconnect.
5653 		 * Following interpretation of -1 seqnum is historical
5654 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
5655 		 * a valid seqnum should not be -1).
5656 		 *
5657 		 *	-1 means disconnect everything
5658 		 *	regardless even on a listener.
5659 		 */
5660 
5661 		int old_state = tcp->tcp_state;
5662 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
5663 
5664 		/*
5665 		 * The connection can't be on the tcp_time_wait_head list
5666 		 * since it is not detached.
5667 		 */
5668 		ASSERT(tcp->tcp_time_wait_next == NULL);
5669 		ASSERT(tcp->tcp_time_wait_prev == NULL);
5670 		ASSERT(tcp->tcp_time_wait_expire == 0);
5671 		/*
5672 		 * If it used to be a listener, check to make sure no one else
5673 		 * has taken the port before switching back to LISTEN state.
5674 		 */
5675 		if (connp->conn_ipversion == IPV4_VERSION) {
5676 			lconnp = ipcl_lookup_listener_v4(connp->conn_lport,
5677 			    connp->conn_laddr_v4, IPCL_ZONEID(connp), ipst);
5678 		} else {
5679 			uint_t ifindex = 0;
5680 
5681 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)
5682 				ifindex = connp->conn_ixa->ixa_scopeid;
5683 
5684 			/* Allow conn_bound_if listeners? */
5685 			lconnp = ipcl_lookup_listener_v6(connp->conn_lport,
5686 			    &connp->conn_laddr_v6, ifindex, IPCL_ZONEID(connp),
5687 			    ipst);
5688 		}
5689 		if (tcp->tcp_conn_req_max && lconnp == NULL) {
5690 			tcp->tcp_state = TCPS_LISTEN;
5691 		} else if (old_state > TCPS_BOUND) {
5692 			tcp->tcp_conn_req_max = 0;
5693 			tcp->tcp_state = TCPS_BOUND;
5694 
5695 			/*
5696 			 * If this end point is not going to become a listener,
5697 			 * decrement the listener connection count if
5698 			 * necessary.  Note that we do not do this if it is
5699 			 * going to be a listner (the above if case) since
5700 			 * then it may remove the counter struct.
5701 			 */
5702 			if (tcp->tcp_listen_cnt != NULL)
5703 				TCP_DECR_LISTEN_CNT(tcp);
5704 		}
5705 		if (lconnp != NULL)
5706 			CONN_DEC_REF(lconnp);
5707 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
5708 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
5709 		} else if (old_state == TCPS_ESTABLISHED ||
5710 		    old_state == TCPS_CLOSE_WAIT) {
5711 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
5712 		}
5713 
5714 		if (tcp->tcp_fused)
5715 			tcp_unfuse(tcp);
5716 
5717 		mutex_enter(&tcp->tcp_eager_lock);
5718 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
5719 		    (tcp->tcp_conn_req_cnt_q != 0)) {
5720 			tcp_eager_cleanup(tcp, 0);
5721 		}
5722 		mutex_exit(&tcp->tcp_eager_lock);
5723 
5724 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
5725 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
5726 
5727 		tcp_reinit(tcp);
5728 
5729 		return (0);
5730 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
5731 		return (TBADSEQ);
5732 	}
5733 	return (0);
5734 }
5735 
5736 /*
5737  * Our client hereby directs us to reject the connection request
5738  * that tcp_input_listener() marked with 'seqnum'.  Rejection consists
5739  * of sending the appropriate RST, not an ICMP error.
5740  */
5741 static void
5742 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
5743 {
5744 	t_scalar_t seqnum;
5745 	int	error;
5746 	conn_t	*connp = tcp->tcp_connp;
5747 
5748 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5749 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
5750 		tcp_err_ack(tcp, mp, TPROTO, 0);
5751 		return;
5752 	}
5753 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
5754 	error = tcp_disconnect_common(tcp, seqnum);
5755 	if (error != 0)
5756 		tcp_err_ack(tcp, mp, error, 0);
5757 	else {
5758 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
5759 			/* Send M_FLUSH according to TPI */
5760 			(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
5761 		}
5762 		mp = mi_tpi_ok_ack_alloc(mp);
5763 		if (mp != NULL)
5764 			putnext(connp->conn_rq, mp);
5765 	}
5766 }
5767 
5768 /*
5769  * Diagnostic routine used to return a string associated with the tcp state.
5770  * Note that if the caller does not supply a buffer, it will use an internal
5771  * static string.  This means that if multiple threads call this function at
5772  * the same time, output can be corrupted...  Note also that this function
5773  * does not check the size of the supplied buffer.  The caller has to make
5774  * sure that it is big enough.
5775  */
5776 static char *
5777 tcp_display(tcp_t *tcp, char *sup_buf, char format)
5778 {
5779 	char		buf1[30];
5780 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
5781 	char		*buf;
5782 	char		*cp;
5783 	in6_addr_t	local, remote;
5784 	char		local_addrbuf[INET6_ADDRSTRLEN];
5785 	char		remote_addrbuf[INET6_ADDRSTRLEN];
5786 	conn_t		*connp;
5787 
5788 	if (sup_buf != NULL)
5789 		buf = sup_buf;
5790 	else
5791 		buf = priv_buf;
5792 
5793 	if (tcp == NULL)
5794 		return ("NULL_TCP");
5795 
5796 	connp = tcp->tcp_connp;
5797 	switch (tcp->tcp_state) {
5798 	case TCPS_CLOSED:
5799 		cp = "TCP_CLOSED";
5800 		break;
5801 	case TCPS_IDLE:
5802 		cp = "TCP_IDLE";
5803 		break;
5804 	case TCPS_BOUND:
5805 		cp = "TCP_BOUND";
5806 		break;
5807 	case TCPS_LISTEN:
5808 		cp = "TCP_LISTEN";
5809 		break;
5810 	case TCPS_SYN_SENT:
5811 		cp = "TCP_SYN_SENT";
5812 		break;
5813 	case TCPS_SYN_RCVD:
5814 		cp = "TCP_SYN_RCVD";
5815 		break;
5816 	case TCPS_ESTABLISHED:
5817 		cp = "TCP_ESTABLISHED";
5818 		break;
5819 	case TCPS_CLOSE_WAIT:
5820 		cp = "TCP_CLOSE_WAIT";
5821 		break;
5822 	case TCPS_FIN_WAIT_1:
5823 		cp = "TCP_FIN_WAIT_1";
5824 		break;
5825 	case TCPS_CLOSING:
5826 		cp = "TCP_CLOSING";
5827 		break;
5828 	case TCPS_LAST_ACK:
5829 		cp = "TCP_LAST_ACK";
5830 		break;
5831 	case TCPS_FIN_WAIT_2:
5832 		cp = "TCP_FIN_WAIT_2";
5833 		break;
5834 	case TCPS_TIME_WAIT:
5835 		cp = "TCP_TIME_WAIT";
5836 		break;
5837 	default:
5838 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
5839 		cp = buf1;
5840 		break;
5841 	}
5842 	switch (format) {
5843 	case DISP_ADDR_AND_PORT:
5844 		if (connp->conn_ipversion == IPV4_VERSION) {
5845 			/*
5846 			 * Note that we use the remote address in the tcp_b
5847 			 * structure.  This means that it will print out
5848 			 * the real destination address, not the next hop's
5849 			 * address if source routing is used.
5850 			 */
5851 			IN6_IPADDR_TO_V4MAPPED(connp->conn_laddr_v4, &local);
5852 			IN6_IPADDR_TO_V4MAPPED(connp->conn_faddr_v4, &remote);
5853 
5854 		} else {
5855 			local = connp->conn_laddr_v6;
5856 			remote = connp->conn_faddr_v6;
5857 		}
5858 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
5859 		    sizeof (local_addrbuf));
5860 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
5861 		    sizeof (remote_addrbuf));
5862 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
5863 		    local_addrbuf, ntohs(connp->conn_lport), remote_addrbuf,
5864 		    ntohs(connp->conn_fport), cp);
5865 		break;
5866 	case DISP_PORT_ONLY:
5867 	default:
5868 		(void) mi_sprintf(buf, "[%u, %u] %s",
5869 		    ntohs(connp->conn_lport), ntohs(connp->conn_fport), cp);
5870 		break;
5871 	}
5872 
5873 	return (buf);
5874 }
5875 
5876 /*
5877  * Called via squeue to get on to eager's perimeter. It sends a
5878  * TH_RST if eager is in the fanout table. The listener wants the
5879  * eager to disappear either by means of tcp_eager_blowoff() or
5880  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
5881  * called (via squeue) if the eager cannot be inserted in the
5882  * fanout table in tcp_input_listener().
5883  */
5884 /* ARGSUSED */
5885 void
5886 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5887 {
5888 	conn_t	*econnp = (conn_t *)arg;
5889 	tcp_t	*eager = econnp->conn_tcp;
5890 	tcp_t	*listener = eager->tcp_listener;
5891 
5892 	/*
5893 	 * We could be called because listener is closing. Since
5894 	 * the eager was using listener's queue's, we avoid
5895 	 * using the listeners queues from now on.
5896 	 */
5897 	ASSERT(eager->tcp_detached);
5898 	econnp->conn_rq = NULL;
5899 	econnp->conn_wq = NULL;
5900 
5901 	/*
5902 	 * An eager's conn_fanout will be NULL if it's a duplicate
5903 	 * for an existing 4-tuples in the conn fanout table.
5904 	 * We don't want to send an RST out in such case.
5905 	 */
5906 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
5907 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
5908 		    eager, eager->tcp_snxt, 0, TH_RST);
5909 	}
5910 
5911 	/* We are here because listener wants this eager gone */
5912 	if (listener != NULL) {
5913 		mutex_enter(&listener->tcp_eager_lock);
5914 		tcp_eager_unlink(eager);
5915 		if (eager->tcp_tconnind_started) {
5916 			/*
5917 			 * The eager has sent a conn_ind up to the
5918 			 * listener but listener decides to close
5919 			 * instead. We need to drop the extra ref
5920 			 * placed on eager in tcp_input_data() before
5921 			 * sending the conn_ind to listener.
5922 			 */
5923 			CONN_DEC_REF(econnp);
5924 		}
5925 		mutex_exit(&listener->tcp_eager_lock);
5926 		CONN_DEC_REF(listener->tcp_connp);
5927 	}
5928 
5929 	if (eager->tcp_state != TCPS_CLOSED)
5930 		tcp_close_detached(eager);
5931 }
5932 
5933 /*
5934  * Reset any eager connection hanging off this listener marked
5935  * with 'seqnum' and then reclaim it's resources.
5936  */
5937 static boolean_t
5938 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
5939 {
5940 	tcp_t	*eager;
5941 	mblk_t 	*mp;
5942 	tcp_stack_t	*tcps = listener->tcp_tcps;
5943 
5944 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
5945 	eager = listener;
5946 	mutex_enter(&listener->tcp_eager_lock);
5947 	do {
5948 		eager = eager->tcp_eager_next_q;
5949 		if (eager == NULL) {
5950 			mutex_exit(&listener->tcp_eager_lock);
5951 			return (B_FALSE);
5952 		}
5953 	} while (eager->tcp_conn_req_seqnum != seqnum);
5954 
5955 	if (eager->tcp_closemp_used) {
5956 		mutex_exit(&listener->tcp_eager_lock);
5957 		return (B_TRUE);
5958 	}
5959 	eager->tcp_closemp_used = B_TRUE;
5960 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5961 	CONN_INC_REF(eager->tcp_connp);
5962 	mutex_exit(&listener->tcp_eager_lock);
5963 	mp = &eager->tcp_closemp;
5964 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
5965 	    eager->tcp_connp, NULL, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
5966 	return (B_TRUE);
5967 }
5968 
5969 /*
5970  * Reset any eager connection hanging off this listener
5971  * and then reclaim it's resources.
5972  */
5973 static void
5974 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
5975 {
5976 	tcp_t	*eager;
5977 	mblk_t	*mp;
5978 	tcp_stack_t	*tcps = listener->tcp_tcps;
5979 
5980 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
5981 
5982 	if (!q0_only) {
5983 		/* First cleanup q */
5984 		TCP_STAT(tcps, tcp_eager_blowoff_q);
5985 		eager = listener->tcp_eager_next_q;
5986 		while (eager != NULL) {
5987 			if (!eager->tcp_closemp_used) {
5988 				eager->tcp_closemp_used = B_TRUE;
5989 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5990 				CONN_INC_REF(eager->tcp_connp);
5991 				mp = &eager->tcp_closemp;
5992 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
5993 				    tcp_eager_kill, eager->tcp_connp, NULL,
5994 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
5995 			}
5996 			eager = eager->tcp_eager_next_q;
5997 		}
5998 	}
5999 	/* Then cleanup q0 */
6000 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6001 	eager = listener->tcp_eager_next_q0;
6002 	while (eager != listener) {
6003 		if (!eager->tcp_closemp_used) {
6004 			eager->tcp_closemp_used = B_TRUE;
6005 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6006 			CONN_INC_REF(eager->tcp_connp);
6007 			mp = &eager->tcp_closemp;
6008 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6009 			    tcp_eager_kill, eager->tcp_connp, NULL, SQ_FILL,
6010 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6011 		}
6012 		eager = eager->tcp_eager_next_q0;
6013 	}
6014 }
6015 
6016 /*
6017  * If we are an eager connection hanging off a listener that hasn't
6018  * formally accepted the connection yet, get off his list and blow off
6019  * any data that we have accumulated.
6020  */
6021 static void
6022 tcp_eager_unlink(tcp_t *tcp)
6023 {
6024 	tcp_t	*listener = tcp->tcp_listener;
6025 
6026 	ASSERT(listener != NULL);
6027 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6028 	if (tcp->tcp_eager_next_q0 != NULL) {
6029 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6030 
6031 		/* Remove the eager tcp from q0 */
6032 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6033 		    tcp->tcp_eager_prev_q0;
6034 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6035 		    tcp->tcp_eager_next_q0;
6036 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6037 		listener->tcp_conn_req_cnt_q0--;
6038 
6039 		tcp->tcp_eager_next_q0 = NULL;
6040 		tcp->tcp_eager_prev_q0 = NULL;
6041 
6042 		/*
6043 		 * Take the eager out, if it is in the list of droppable
6044 		 * eagers.
6045 		 */
6046 		MAKE_UNDROPPABLE(tcp);
6047 
6048 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6049 			/* we have timed out before */
6050 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6051 			listener->tcp_syn_rcvd_timeout--;
6052 		}
6053 	} else {
6054 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6055 		tcp_t	*prev = NULL;
6056 
6057 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6058 			if (tcpp[0] == tcp) {
6059 				if (listener->tcp_eager_last_q == tcp) {
6060 					/*
6061 					 * If we are unlinking the last
6062 					 * element on the list, adjust
6063 					 * tail pointer. Set tail pointer
6064 					 * to nil when list is empty.
6065 					 */
6066 					ASSERT(tcp->tcp_eager_next_q == NULL);
6067 					if (listener->tcp_eager_last_q ==
6068 					    listener->tcp_eager_next_q) {
6069 						listener->tcp_eager_last_q =
6070 						    NULL;
6071 					} else {
6072 						/*
6073 						 * We won't get here if there
6074 						 * is only one eager in the
6075 						 * list.
6076 						 */
6077 						ASSERT(prev != NULL);
6078 						listener->tcp_eager_last_q =
6079 						    prev;
6080 					}
6081 				}
6082 				tcpp[0] = tcp->tcp_eager_next_q;
6083 				tcp->tcp_eager_next_q = NULL;
6084 				tcp->tcp_eager_last_q = NULL;
6085 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6086 				listener->tcp_conn_req_cnt_q--;
6087 				break;
6088 			}
6089 			prev = tcpp[0];
6090 		}
6091 	}
6092 	tcp->tcp_listener = NULL;
6093 }
6094 
6095 /* Shorthand to generate and send TPI error acks to our client */
6096 static void
6097 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6098 {
6099 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6100 		putnext(tcp->tcp_connp->conn_rq, mp);
6101 }
6102 
6103 /* Shorthand to generate and send TPI error acks to our client */
6104 static void
6105 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6106     int t_error, int sys_error)
6107 {
6108 	struct T_error_ack	*teackp;
6109 
6110 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6111 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6112 		teackp = (struct T_error_ack *)mp->b_rptr;
6113 		teackp->ERROR_prim = primitive;
6114 		teackp->TLI_error = t_error;
6115 		teackp->UNIX_error = sys_error;
6116 		putnext(tcp->tcp_connp->conn_rq, mp);
6117 	}
6118 }
6119 
6120 /*
6121  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6122  * but instead the code relies on:
6123  * - the fact that the address of the array and its size never changes
6124  * - the atomic assignment of the elements of the array
6125  */
6126 /* ARGSUSED */
6127 static int
6128 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6129 {
6130 	int i;
6131 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6132 
6133 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6134 		if (tcps->tcps_g_epriv_ports[i] != 0)
6135 			(void) mi_mpprintf(mp, "%d ",
6136 			    tcps->tcps_g_epriv_ports[i]);
6137 	}
6138 	return (0);
6139 }
6140 
6141 /*
6142  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6143  * threads from changing it at the same time.
6144  */
6145 /* ARGSUSED */
6146 static int
6147 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6148     cred_t *cr)
6149 {
6150 	long	new_value;
6151 	int	i;
6152 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6153 
6154 	/*
6155 	 * Fail the request if the new value does not lie within the
6156 	 * port number limits.
6157 	 */
6158 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6159 	    new_value <= 0 || new_value >= 65536) {
6160 		return (EINVAL);
6161 	}
6162 
6163 	mutex_enter(&tcps->tcps_epriv_port_lock);
6164 	/* Check if the value is already in the list */
6165 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6166 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
6167 			mutex_exit(&tcps->tcps_epriv_port_lock);
6168 			return (EEXIST);
6169 		}
6170 	}
6171 	/* Find an empty slot */
6172 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6173 		if (tcps->tcps_g_epriv_ports[i] == 0)
6174 			break;
6175 	}
6176 	if (i == tcps->tcps_g_num_epriv_ports) {
6177 		mutex_exit(&tcps->tcps_epriv_port_lock);
6178 		return (EOVERFLOW);
6179 	}
6180 	/* Set the new value */
6181 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
6182 	mutex_exit(&tcps->tcps_epriv_port_lock);
6183 	return (0);
6184 }
6185 
6186 /*
6187  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6188  * threads from changing it at the same time.
6189  */
6190 /* ARGSUSED */
6191 static int
6192 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6193     cred_t *cr)
6194 {
6195 	long	new_value;
6196 	int	i;
6197 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6198 
6199 	/*
6200 	 * Fail the request if the new value does not lie within the
6201 	 * port number limits.
6202 	 */
6203 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6204 	    new_value >= 65536) {
6205 		return (EINVAL);
6206 	}
6207 
6208 	mutex_enter(&tcps->tcps_epriv_port_lock);
6209 	/* Check that the value is already in the list */
6210 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6211 		if (tcps->tcps_g_epriv_ports[i] == new_value)
6212 			break;
6213 	}
6214 	if (i == tcps->tcps_g_num_epriv_ports) {
6215 		mutex_exit(&tcps->tcps_epriv_port_lock);
6216 		return (ESRCH);
6217 	}
6218 	/* Clear the value */
6219 	tcps->tcps_g_epriv_ports[i] = 0;
6220 	mutex_exit(&tcps->tcps_epriv_port_lock);
6221 	return (0);
6222 }
6223 
6224 /* Return the TPI/TLI equivalent of our current tcp_state */
6225 static int
6226 tcp_tpistate(tcp_t *tcp)
6227 {
6228 	switch (tcp->tcp_state) {
6229 	case TCPS_IDLE:
6230 		return (TS_UNBND);
6231 	case TCPS_LISTEN:
6232 		/*
6233 		 * Return whether there are outstanding T_CONN_IND waiting
6234 		 * for the matching T_CONN_RES. Therefore don't count q0.
6235 		 */
6236 		if (tcp->tcp_conn_req_cnt_q > 0)
6237 			return (TS_WRES_CIND);
6238 		else
6239 			return (TS_IDLE);
6240 	case TCPS_BOUND:
6241 		return (TS_IDLE);
6242 	case TCPS_SYN_SENT:
6243 		return (TS_WCON_CREQ);
6244 	case TCPS_SYN_RCVD:
6245 		/*
6246 		 * Note: assumption: this has to the active open SYN_RCVD.
6247 		 * The passive instance is detached in SYN_RCVD stage of
6248 		 * incoming connection processing so we cannot get request
6249 		 * for T_info_ack on it.
6250 		 */
6251 		return (TS_WACK_CRES);
6252 	case TCPS_ESTABLISHED:
6253 		return (TS_DATA_XFER);
6254 	case TCPS_CLOSE_WAIT:
6255 		return (TS_WREQ_ORDREL);
6256 	case TCPS_FIN_WAIT_1:
6257 		return (TS_WIND_ORDREL);
6258 	case TCPS_FIN_WAIT_2:
6259 		return (TS_WIND_ORDREL);
6260 
6261 	case TCPS_CLOSING:
6262 	case TCPS_LAST_ACK:
6263 	case TCPS_TIME_WAIT:
6264 	case TCPS_CLOSED:
6265 		/*
6266 		 * Following TS_WACK_DREQ7 is a rendition of "not
6267 		 * yet TS_IDLE" TPI state. There is no best match to any
6268 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6269 		 * choose a value chosen that will map to TLI/XTI level
6270 		 * state of TSTATECHNG (state is process of changing) which
6271 		 * captures what this dummy state represents.
6272 		 */
6273 		return (TS_WACK_DREQ7);
6274 	default:
6275 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6276 		    tcp->tcp_state, tcp_display(tcp, NULL,
6277 		    DISP_PORT_ONLY));
6278 		return (TS_UNBND);
6279 	}
6280 }
6281 
6282 static void
6283 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6284 {
6285 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6286 	conn_t		*connp = tcp->tcp_connp;
6287 
6288 	if (connp->conn_family == AF_INET6)
6289 		*tia = tcp_g_t_info_ack_v6;
6290 	else
6291 		*tia = tcp_g_t_info_ack;
6292 	tia->CURRENT_state = tcp_tpistate(tcp);
6293 	tia->OPT_size = tcp_max_optsize;
6294 	if (tcp->tcp_mss == 0) {
6295 		/* Not yet set - tcp_open does not set mss */
6296 		if (connp->conn_ipversion == IPV4_VERSION)
6297 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
6298 		else
6299 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
6300 	} else {
6301 		tia->TIDU_size = tcp->tcp_mss;
6302 	}
6303 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6304 }
6305 
6306 static void
6307 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
6308     t_uscalar_t cap_bits1)
6309 {
6310 	tcap->CAP_bits1 = 0;
6311 
6312 	if (cap_bits1 & TC1_INFO) {
6313 		tcp_copy_info(&tcap->INFO_ack, tcp);
6314 		tcap->CAP_bits1 |= TC1_INFO;
6315 	}
6316 
6317 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6318 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6319 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6320 	}
6321 
6322 }
6323 
6324 /*
6325  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6326  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6327  * tcp_g_t_info_ack.  The current state of the stream is copied from
6328  * tcp_state.
6329  */
6330 static void
6331 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6332 {
6333 	t_uscalar_t		cap_bits1;
6334 	struct T_capability_ack	*tcap;
6335 
6336 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6337 		freemsg(mp);
6338 		return;
6339 	}
6340 
6341 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6342 
6343 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6344 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6345 	if (mp == NULL)
6346 		return;
6347 
6348 	tcap = (struct T_capability_ack *)mp->b_rptr;
6349 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
6350 
6351 	putnext(tcp->tcp_connp->conn_rq, mp);
6352 }
6353 
6354 /*
6355  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
6356  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
6357  * The current state of the stream is copied from tcp_state.
6358  */
6359 static void
6360 tcp_info_req(tcp_t *tcp, mblk_t *mp)
6361 {
6362 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
6363 	    T_INFO_ACK);
6364 	if (!mp) {
6365 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6366 		return;
6367 	}
6368 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
6369 	putnext(tcp->tcp_connp->conn_rq, mp);
6370 }
6371 
6372 /* Respond to the TPI addr request */
6373 static void
6374 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
6375 {
6376 	struct sockaddr *sa;
6377 	mblk_t	*ackmp;
6378 	struct T_addr_ack *taa;
6379 	conn_t	*connp = tcp->tcp_connp;
6380 	uint_t	addrlen;
6381 
6382 	/* Make it large enough for worst case */
6383 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
6384 	    2 * sizeof (sin6_t), 1);
6385 	if (ackmp == NULL) {
6386 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6387 		return;
6388 	}
6389 
6390 	taa = (struct T_addr_ack *)ackmp->b_rptr;
6391 
6392 	bzero(taa, sizeof (struct T_addr_ack));
6393 	ackmp->b_wptr = (uchar_t *)&taa[1];
6394 
6395 	taa->PRIM_type = T_ADDR_ACK;
6396 	ackmp->b_datap->db_type = M_PCPROTO;
6397 
6398 	if (connp->conn_family == AF_INET)
6399 		addrlen = sizeof (sin_t);
6400 	else
6401 		addrlen = sizeof (sin6_t);
6402 
6403 	/*
6404 	 * Note: Following code assumes 32 bit alignment of basic
6405 	 * data structures like sin_t and struct T_addr_ack.
6406 	 */
6407 	if (tcp->tcp_state >= TCPS_BOUND) {
6408 		/*
6409 		 * Fill in local address first
6410 		 */
6411 		taa->LOCADDR_offset = sizeof (*taa);
6412 		taa->LOCADDR_length = addrlen;
6413 		sa = (struct sockaddr *)&taa[1];
6414 		(void) conn_getsockname(connp, sa, &addrlen);
6415 		ackmp->b_wptr += addrlen;
6416 	}
6417 	if (tcp->tcp_state >= TCPS_SYN_RCVD) {
6418 		/*
6419 		 * Fill in Remote address
6420 		 */
6421 		taa->REMADDR_length = addrlen;
6422 		/* assumed 32-bit alignment */
6423 		taa->REMADDR_offset = taa->LOCADDR_offset + taa->LOCADDR_length;
6424 		sa = (struct sockaddr *)(ackmp->b_rptr + taa->REMADDR_offset);
6425 		(void) conn_getpeername(connp, sa, &addrlen);
6426 		ackmp->b_wptr += addrlen;
6427 	}
6428 	ASSERT(ackmp->b_wptr <= ackmp->b_datap->db_lim);
6429 	putnext(tcp->tcp_connp->conn_rq, ackmp);
6430 }
6431 
6432 /*
6433  * Handle reinitialization of a tcp structure.
6434  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
6435  */
6436 static void
6437 tcp_reinit(tcp_t *tcp)
6438 {
6439 	mblk_t		*mp;
6440 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6441 	conn_t		*connp  = tcp->tcp_connp;
6442 
6443 	TCP_STAT(tcps, tcp_reinit_calls);
6444 
6445 	/* tcp_reinit should never be called for detached tcp_t's */
6446 	ASSERT(tcp->tcp_listener == NULL);
6447 	ASSERT((connp->conn_family == AF_INET &&
6448 	    connp->conn_ipversion == IPV4_VERSION) ||
6449 	    (connp->conn_family == AF_INET6 &&
6450 	    (connp->conn_ipversion == IPV4_VERSION ||
6451 	    connp->conn_ipversion == IPV6_VERSION)));
6452 
6453 	/* Cancel outstanding timers */
6454 	tcp_timers_stop(tcp);
6455 
6456 	/*
6457 	 * Reset everything in the state vector, after updating global
6458 	 * MIB data from instance counters.
6459 	 */
6460 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
6461 	tcp->tcp_ibsegs = 0;
6462 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
6463 	tcp->tcp_obsegs = 0;
6464 
6465 	tcp_close_mpp(&tcp->tcp_xmit_head);
6466 	if (tcp->tcp_snd_zcopy_aware)
6467 		tcp_zcopy_notify(tcp);
6468 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
6469 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
6470 	mutex_enter(&tcp->tcp_non_sq_lock);
6471 	if (tcp->tcp_flow_stopped &&
6472 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
6473 		tcp_clrqfull(tcp);
6474 	}
6475 	mutex_exit(&tcp->tcp_non_sq_lock);
6476 	tcp_close_mpp(&tcp->tcp_reass_head);
6477 	tcp->tcp_reass_tail = NULL;
6478 	if (tcp->tcp_rcv_list != NULL) {
6479 		/* Free b_next chain */
6480 		tcp_close_mpp(&tcp->tcp_rcv_list);
6481 		tcp->tcp_rcv_last_head = NULL;
6482 		tcp->tcp_rcv_last_tail = NULL;
6483 		tcp->tcp_rcv_cnt = 0;
6484 	}
6485 	tcp->tcp_rcv_last_tail = NULL;
6486 
6487 	if ((mp = tcp->tcp_urp_mp) != NULL) {
6488 		freemsg(mp);
6489 		tcp->tcp_urp_mp = NULL;
6490 	}
6491 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
6492 		freemsg(mp);
6493 		tcp->tcp_urp_mark_mp = NULL;
6494 	}
6495 	if (tcp->tcp_fused_sigurg_mp != NULL) {
6496 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6497 		freeb(tcp->tcp_fused_sigurg_mp);
6498 		tcp->tcp_fused_sigurg_mp = NULL;
6499 	}
6500 	if (tcp->tcp_ordrel_mp != NULL) {
6501 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6502 		freeb(tcp->tcp_ordrel_mp);
6503 		tcp->tcp_ordrel_mp = NULL;
6504 	}
6505 
6506 	/*
6507 	 * Following is a union with two members which are
6508 	 * identical types and size so the following cleanup
6509 	 * is enough.
6510 	 */
6511 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
6512 
6513 	CL_INET_DISCONNECT(connp);
6514 
6515 	/*
6516 	 * The connection can't be on the tcp_time_wait_head list
6517 	 * since it is not detached.
6518 	 */
6519 	ASSERT(tcp->tcp_time_wait_next == NULL);
6520 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6521 	ASSERT(tcp->tcp_time_wait_expire == 0);
6522 
6523 	if (tcp->tcp_kssl_pending) {
6524 		tcp->tcp_kssl_pending = B_FALSE;
6525 
6526 		/* Don't reset if the initialized by bind. */
6527 		if (tcp->tcp_kssl_ent != NULL) {
6528 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
6529 			    KSSL_NO_PROXY);
6530 		}
6531 	}
6532 	if (tcp->tcp_kssl_ctx != NULL) {
6533 		kssl_release_ctx(tcp->tcp_kssl_ctx);
6534 		tcp->tcp_kssl_ctx = NULL;
6535 	}
6536 
6537 	/*
6538 	 * Reset/preserve other values
6539 	 */
6540 	tcp_reinit_values(tcp);
6541 	ipcl_hash_remove(connp);
6542 	ixa_cleanup(connp->conn_ixa);
6543 	tcp_ipsec_cleanup(tcp);
6544 
6545 	connp->conn_laddr_v6 = connp->conn_bound_addr_v6;
6546 	connp->conn_saddr_v6 = connp->conn_bound_addr_v6;
6547 
6548 	if (tcp->tcp_conn_req_max != 0) {
6549 		/*
6550 		 * This is the case when a TLI program uses the same
6551 		 * transport end point to accept a connection.  This
6552 		 * makes the TCP both a listener and acceptor.  When
6553 		 * this connection is closed, we need to set the state
6554 		 * back to TCPS_LISTEN.  Make sure that the eager list
6555 		 * is reinitialized.
6556 		 *
6557 		 * Note that this stream is still bound to the four
6558 		 * tuples of the previous connection in IP.  If a new
6559 		 * SYN with different foreign address comes in, IP will
6560 		 * not find it and will send it to the global queue.  In
6561 		 * the global queue, TCP will do a tcp_lookup_listener()
6562 		 * to find this stream.  This works because this stream
6563 		 * is only removed from connected hash.
6564 		 *
6565 		 */
6566 		tcp->tcp_state = TCPS_LISTEN;
6567 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
6568 		tcp->tcp_eager_next_drop_q0 = tcp;
6569 		tcp->tcp_eager_prev_drop_q0 = tcp;
6570 		/*
6571 		 * Initially set conn_recv to tcp_input_listener_unbound to try
6572 		 * to pick a good squeue for the listener when the first SYN
6573 		 * arrives. tcp_input_listener_unbound sets it to
6574 		 * tcp_input_listener on that first SYN.
6575 		 */
6576 		connp->conn_recv = tcp_input_listener_unbound;
6577 
6578 		connp->conn_proto = IPPROTO_TCP;
6579 		connp->conn_faddr_v6 = ipv6_all_zeros;
6580 		connp->conn_fport = 0;
6581 
6582 		(void) ipcl_bind_insert(connp);
6583 	} else {
6584 		tcp->tcp_state = TCPS_BOUND;
6585 	}
6586 
6587 	/*
6588 	 * Initialize to default values
6589 	 */
6590 	tcp_init_values(tcp);
6591 
6592 	ASSERT(tcp->tcp_ptpbhn != NULL);
6593 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6594 	tcp->tcp_mss = connp->conn_ipversion != IPV4_VERSION ?
6595 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
6596 }
6597 
6598 /*
6599  * Force values to zero that need be zero.
6600  * Do not touch values asociated with the BOUND or LISTEN state
6601  * since the connection will end up in that state after the reinit.
6602  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
6603  * structure!
6604  */
6605 static void
6606 tcp_reinit_values(tcp)
6607 	tcp_t *tcp;
6608 {
6609 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6610 	conn_t		*connp = tcp->tcp_connp;
6611 
6612 #ifndef	lint
6613 #define	DONTCARE(x)
6614 #define	PRESERVE(x)
6615 #else
6616 #define	DONTCARE(x)	((x) = (x))
6617 #define	PRESERVE(x)	((x) = (x))
6618 #endif	/* lint */
6619 
6620 	PRESERVE(tcp->tcp_bind_hash_port);
6621 	PRESERVE(tcp->tcp_bind_hash);
6622 	PRESERVE(tcp->tcp_ptpbhn);
6623 	PRESERVE(tcp->tcp_acceptor_hash);
6624 	PRESERVE(tcp->tcp_ptpahn);
6625 
6626 	/* Should be ASSERT NULL on these with new code! */
6627 	ASSERT(tcp->tcp_time_wait_next == NULL);
6628 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6629 	ASSERT(tcp->tcp_time_wait_expire == 0);
6630 	PRESERVE(tcp->tcp_state);
6631 	PRESERVE(connp->conn_rq);
6632 	PRESERVE(connp->conn_wq);
6633 
6634 	ASSERT(tcp->tcp_xmit_head == NULL);
6635 	ASSERT(tcp->tcp_xmit_last == NULL);
6636 	ASSERT(tcp->tcp_unsent == 0);
6637 	ASSERT(tcp->tcp_xmit_tail == NULL);
6638 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
6639 
6640 	tcp->tcp_snxt = 0;			/* Displayed in mib */
6641 	tcp->tcp_suna = 0;			/* Displayed in mib */
6642 	tcp->tcp_swnd = 0;
6643 	DONTCARE(tcp->tcp_cwnd);	/* Init in tcp_process_options */
6644 
6645 	ASSERT(tcp->tcp_ibsegs == 0);
6646 	ASSERT(tcp->tcp_obsegs == 0);
6647 
6648 	if (connp->conn_ht_iphc != NULL) {
6649 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
6650 		connp->conn_ht_iphc = NULL;
6651 		connp->conn_ht_iphc_allocated = 0;
6652 		connp->conn_ht_iphc_len = 0;
6653 		connp->conn_ht_ulp = NULL;
6654 		connp->conn_ht_ulp_len = 0;
6655 		tcp->tcp_ipha = NULL;
6656 		tcp->tcp_ip6h = NULL;
6657 		tcp->tcp_tcpha = NULL;
6658 	}
6659 
6660 	/* We clear any IP_OPTIONS and extension headers */
6661 	ip_pkt_free(&connp->conn_xmit_ipp);
6662 
6663 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
6664 	DONTCARE(tcp->tcp_ipha);
6665 	DONTCARE(tcp->tcp_ip6h);
6666 	DONTCARE(tcp->tcp_tcpha);
6667 	tcp->tcp_valid_bits = 0;
6668 
6669 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
6670 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
6671 	tcp->tcp_last_rcv_lbolt = 0;
6672 
6673 	tcp->tcp_init_cwnd = 0;
6674 
6675 	tcp->tcp_urp_last_valid = 0;
6676 	tcp->tcp_hard_binding = 0;
6677 
6678 	tcp->tcp_fin_acked = 0;
6679 	tcp->tcp_fin_rcvd = 0;
6680 	tcp->tcp_fin_sent = 0;
6681 	tcp->tcp_ordrel_done = 0;
6682 
6683 	tcp->tcp_detached = 0;
6684 
6685 	tcp->tcp_snd_ws_ok = B_FALSE;
6686 	tcp->tcp_snd_ts_ok = B_FALSE;
6687 	tcp->tcp_zero_win_probe = 0;
6688 
6689 	tcp->tcp_loopback = 0;
6690 	tcp->tcp_localnet = 0;
6691 	tcp->tcp_syn_defense = 0;
6692 	tcp->tcp_set_timer = 0;
6693 
6694 	tcp->tcp_active_open = 0;
6695 	tcp->tcp_rexmit = B_FALSE;
6696 	tcp->tcp_xmit_zc_clean = B_FALSE;
6697 
6698 	tcp->tcp_snd_sack_ok = B_FALSE;
6699 	tcp->tcp_hwcksum = B_FALSE;
6700 
6701 	DONTCARE(tcp->tcp_maxpsz_multiplier);	/* Init in tcp_init_values */
6702 
6703 	tcp->tcp_conn_def_q0 = 0;
6704 	tcp->tcp_ip_forward_progress = B_FALSE;
6705 	tcp->tcp_ecn_ok = B_FALSE;
6706 
6707 	tcp->tcp_cwr = B_FALSE;
6708 	tcp->tcp_ecn_echo_on = B_FALSE;
6709 	tcp->tcp_is_wnd_shrnk = B_FALSE;
6710 
6711 	if (tcp->tcp_sack_info != NULL) {
6712 		if (tcp->tcp_notsack_list != NULL) {
6713 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
6714 			    tcp);
6715 		}
6716 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
6717 		tcp->tcp_sack_info = NULL;
6718 	}
6719 
6720 	tcp->tcp_rcv_ws = 0;
6721 	tcp->tcp_snd_ws = 0;
6722 	tcp->tcp_ts_recent = 0;
6723 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
6724 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
6725 	tcp->tcp_initial_pmtu = 0;
6726 
6727 	ASSERT(tcp->tcp_reass_head == NULL);
6728 	ASSERT(tcp->tcp_reass_tail == NULL);
6729 
6730 	tcp->tcp_cwnd_cnt = 0;
6731 
6732 	ASSERT(tcp->tcp_rcv_list == NULL);
6733 	ASSERT(tcp->tcp_rcv_last_head == NULL);
6734 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
6735 	ASSERT(tcp->tcp_rcv_cnt == 0);
6736 
6737 	DONTCARE(tcp->tcp_cwnd_ssthresh); /* Init in tcp_set_destination */
6738 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
6739 	tcp->tcp_csuna = 0;
6740 
6741 	tcp->tcp_rto = 0;			/* Displayed in MIB */
6742 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
6743 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
6744 	tcp->tcp_rtt_update = 0;
6745 
6746 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6747 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6748 
6749 	tcp->tcp_rack = 0;			/* Displayed in mib */
6750 	tcp->tcp_rack_cnt = 0;
6751 	tcp->tcp_rack_cur_max = 0;
6752 	tcp->tcp_rack_abs_max = 0;
6753 
6754 	tcp->tcp_max_swnd = 0;
6755 
6756 	ASSERT(tcp->tcp_listener == NULL);
6757 
6758 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
6759 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
6760 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
6761 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
6762 
6763 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
6764 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
6765 	PRESERVE(tcp->tcp_conn_req_max);
6766 	PRESERVE(tcp->tcp_conn_req_seqnum);
6767 
6768 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
6769 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
6770 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
6771 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
6772 
6773 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
6774 	ASSERT(tcp->tcp_urp_mp == NULL);
6775 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
6776 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
6777 
6778 	ASSERT(tcp->tcp_eager_next_q == NULL);
6779 	ASSERT(tcp->tcp_eager_last_q == NULL);
6780 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
6781 	    tcp->tcp_eager_prev_q0 == NULL) ||
6782 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
6783 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
6784 
6785 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
6786 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
6787 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
6788 
6789 	tcp->tcp_client_errno = 0;
6790 
6791 	DONTCARE(connp->conn_sum);		/* Init in tcp_init_values */
6792 
6793 	connp->conn_faddr_v6 = ipv6_all_zeros;	/* Displayed in MIB */
6794 
6795 	PRESERVE(connp->conn_bound_addr_v6);
6796 	tcp->tcp_last_sent_len = 0;
6797 	tcp->tcp_dupack_cnt = 0;
6798 
6799 	connp->conn_fport = 0;			/* Displayed in MIB */
6800 	PRESERVE(connp->conn_lport);
6801 
6802 	PRESERVE(tcp->tcp_acceptor_lockp);
6803 
6804 	ASSERT(tcp->tcp_ordrel_mp == NULL);
6805 	PRESERVE(tcp->tcp_acceptor_id);
6806 	DONTCARE(tcp->tcp_ipsec_overhead);
6807 
6808 	PRESERVE(connp->conn_family);
6809 	/* Remove any remnants of mapped address binding */
6810 	if (connp->conn_family == AF_INET6) {
6811 		connp->conn_ipversion = IPV6_VERSION;
6812 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
6813 	} else {
6814 		connp->conn_ipversion = IPV4_VERSION;
6815 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
6816 	}
6817 
6818 	connp->conn_bound_if = 0;
6819 	connp->conn_recv_ancillary.crb_all = 0;
6820 	tcp->tcp_recvifindex = 0;
6821 	tcp->tcp_recvhops = 0;
6822 	tcp->tcp_closed = 0;
6823 	tcp->tcp_cleandeathtag = 0;
6824 	if (tcp->tcp_hopopts != NULL) {
6825 		mi_free(tcp->tcp_hopopts);
6826 		tcp->tcp_hopopts = NULL;
6827 		tcp->tcp_hopoptslen = 0;
6828 	}
6829 	ASSERT(tcp->tcp_hopoptslen == 0);
6830 	if (tcp->tcp_dstopts != NULL) {
6831 		mi_free(tcp->tcp_dstopts);
6832 		tcp->tcp_dstopts = NULL;
6833 		tcp->tcp_dstoptslen = 0;
6834 	}
6835 	ASSERT(tcp->tcp_dstoptslen == 0);
6836 	if (tcp->tcp_rthdrdstopts != NULL) {
6837 		mi_free(tcp->tcp_rthdrdstopts);
6838 		tcp->tcp_rthdrdstopts = NULL;
6839 		tcp->tcp_rthdrdstoptslen = 0;
6840 	}
6841 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
6842 	if (tcp->tcp_rthdr != NULL) {
6843 		mi_free(tcp->tcp_rthdr);
6844 		tcp->tcp_rthdr = NULL;
6845 		tcp->tcp_rthdrlen = 0;
6846 	}
6847 	ASSERT(tcp->tcp_rthdrlen == 0);
6848 
6849 	/* Reset fusion-related fields */
6850 	tcp->tcp_fused = B_FALSE;
6851 	tcp->tcp_unfusable = B_FALSE;
6852 	tcp->tcp_fused_sigurg = B_FALSE;
6853 	tcp->tcp_loopback_peer = NULL;
6854 
6855 	tcp->tcp_lso = B_FALSE;
6856 
6857 	tcp->tcp_in_ack_unsent = 0;
6858 	tcp->tcp_cork = B_FALSE;
6859 	tcp->tcp_tconnind_started = B_FALSE;
6860 
6861 	PRESERVE(tcp->tcp_squeue_bytes);
6862 
6863 	ASSERT(tcp->tcp_kssl_ctx == NULL);
6864 	ASSERT(!tcp->tcp_kssl_pending);
6865 	PRESERVE(tcp->tcp_kssl_ent);
6866 
6867 	tcp->tcp_closemp_used = B_FALSE;
6868 
6869 	PRESERVE(tcp->tcp_rsrv_mp);
6870 	PRESERVE(tcp->tcp_rsrv_mp_lock);
6871 
6872 #ifdef DEBUG
6873 	DONTCARE(tcp->tcmp_stk[0]);
6874 #endif
6875 
6876 	PRESERVE(tcp->tcp_connid);
6877 
6878 	ASSERT(tcp->tcp_listen_cnt == NULL);
6879 	ASSERT(tcp->tcp_reass_tid == 0);
6880 
6881 #undef	DONTCARE
6882 #undef	PRESERVE
6883 }
6884 
6885 static void
6886 tcp_init_values(tcp_t *tcp)
6887 {
6888 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6889 	conn_t		*connp = tcp->tcp_connp;
6890 
6891 	ASSERT((connp->conn_family == AF_INET &&
6892 	    connp->conn_ipversion == IPV4_VERSION) ||
6893 	    (connp->conn_family == AF_INET6 &&
6894 	    (connp->conn_ipversion == IPV4_VERSION ||
6895 	    connp->conn_ipversion == IPV6_VERSION)));
6896 
6897 	/*
6898 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
6899 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
6900 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
6901 	 * during first few transmissions of a connection as seen in slow
6902 	 * links.
6903 	 */
6904 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
6905 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
6906 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
6907 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
6908 	    tcps->tcps_conn_grace_period;
6909 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
6910 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
6911 	tcp->tcp_timer_backoff = 0;
6912 	tcp->tcp_ms_we_have_waited = 0;
6913 	tcp->tcp_last_recv_time = ddi_get_lbolt();
6914 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
6915 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
6916 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
6917 
6918 	tcp->tcp_maxpsz_multiplier = tcps->tcps_maxpsz_multiplier;
6919 
6920 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
6921 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
6922 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
6923 	/*
6924 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
6925 	 * passive open.
6926 	 */
6927 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
6928 
6929 	tcp->tcp_naglim = tcps->tcps_naglim_def;
6930 
6931 	/* NOTE:  ISS is now set in tcp_set_destination(). */
6932 
6933 	/* Reset fusion-related fields */
6934 	tcp->tcp_fused = B_FALSE;
6935 	tcp->tcp_unfusable = B_FALSE;
6936 	tcp->tcp_fused_sigurg = B_FALSE;
6937 	tcp->tcp_loopback_peer = NULL;
6938 
6939 	/* We rebuild the header template on the next connect/conn_request */
6940 
6941 	connp->conn_mlp_type = mlptSingle;
6942 
6943 	/*
6944 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
6945 	 * down tcp_rwnd. tcp_set_destination() will set the right value later.
6946 	 */
6947 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
6948 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6949 
6950 	tcp->tcp_cork = B_FALSE;
6951 	/*
6952 	 * Init the tcp_debug option if it wasn't already set.  This value
6953 	 * determines whether TCP
6954 	 * calls strlog() to print out debug messages.  Doing this
6955 	 * initialization here means that this value is not inherited thru
6956 	 * tcp_reinit().
6957 	 */
6958 	if (!connp->conn_debug)
6959 		connp->conn_debug = tcps->tcps_dbg;
6960 
6961 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
6962 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
6963 }
6964 
6965 /* At minimum we need 8 bytes in the TCP header for the lookup */
6966 #define	ICMP_MIN_TCP_HDR	8
6967 
6968 /*
6969  * tcp_icmp_input is called as conn_recvicmp to process ICMP error messages
6970  * passed up by IP. The message is always received on the correct tcp_t.
6971  * Assumes that IP has pulled up everything up to and including the ICMP header.
6972  */
6973 /* ARGSUSED2 */
6974 static void
6975 tcp_icmp_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
6976 {
6977 	conn_t		*connp = (conn_t *)arg1;
6978 	icmph_t		*icmph;
6979 	ipha_t		*ipha;
6980 	int		iph_hdr_length;
6981 	tcpha_t		*tcpha;
6982 	uint32_t	seg_seq;
6983 	tcp_t		*tcp = connp->conn_tcp;
6984 
6985 	/* Assume IP provides aligned packets */
6986 	ASSERT(OK_32PTR(mp->b_rptr));
6987 	ASSERT((MBLKL(mp) >= sizeof (ipha_t)));
6988 
6989 	/*
6990 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
6991 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
6992 	 */
6993 	if (!(ira->ira_flags & IRAF_IS_IPV4)) {
6994 		tcp_icmp_error_ipv6(tcp, mp, ira);
6995 		return;
6996 	}
6997 
6998 	/* Skip past the outer IP and ICMP headers */
6999 	iph_hdr_length = ira->ira_ip_hdr_length;
7000 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
7001 	/*
7002 	 * If we don't have the correct outer IP header length
7003 	 * or if we don't have a complete inner IP header
7004 	 * drop it.
7005 	 */
7006 	if (iph_hdr_length < sizeof (ipha_t) ||
7007 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
7008 noticmpv4:
7009 		freemsg(mp);
7010 		return;
7011 	}
7012 	ipha = (ipha_t *)&icmph[1];
7013 
7014 	/* Skip past the inner IP and find the ULP header */
7015 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
7016 	tcpha = (tcpha_t *)((char *)ipha + iph_hdr_length);
7017 	/*
7018 	 * If we don't have the correct inner IP header length or if the ULP
7019 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
7020 	 * bytes of TCP header, drop it.
7021 	 */
7022 	if (iph_hdr_length < sizeof (ipha_t) ||
7023 	    ipha->ipha_protocol != IPPROTO_TCP ||
7024 	    (uchar_t *)tcpha + ICMP_MIN_TCP_HDR > mp->b_wptr) {
7025 		goto noticmpv4;
7026 	}
7027 
7028 	seg_seq = ntohl(tcpha->tha_seq);
7029 	switch (icmph->icmph_type) {
7030 	case ICMP_DEST_UNREACHABLE:
7031 		switch (icmph->icmph_code) {
7032 		case ICMP_FRAGMENTATION_NEEDED:
7033 			/*
7034 			 * Update Path MTU, then try to send something out.
7035 			 */
7036 			tcp_update_pmtu(tcp, B_TRUE);
7037 			tcp_rexmit_after_error(tcp);
7038 			break;
7039 		case ICMP_PORT_UNREACHABLE:
7040 		case ICMP_PROTOCOL_UNREACHABLE:
7041 			switch (tcp->tcp_state) {
7042 			case TCPS_SYN_SENT:
7043 			case TCPS_SYN_RCVD:
7044 				/*
7045 				 * ICMP can snipe away incipient
7046 				 * TCP connections as long as
7047 				 * seq number is same as initial
7048 				 * send seq number.
7049 				 */
7050 				if (seg_seq == tcp->tcp_iss) {
7051 					(void) tcp_clean_death(tcp,
7052 					    ECONNREFUSED, 6);
7053 				}
7054 				break;
7055 			}
7056 			break;
7057 		case ICMP_HOST_UNREACHABLE:
7058 		case ICMP_NET_UNREACHABLE:
7059 			/* Record the error in case we finally time out. */
7060 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
7061 				tcp->tcp_client_errno = EHOSTUNREACH;
7062 			else
7063 				tcp->tcp_client_errno = ENETUNREACH;
7064 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
7065 				if (tcp->tcp_listener != NULL &&
7066 				    tcp->tcp_listener->tcp_syn_defense) {
7067 					/*
7068 					 * Ditch the half-open connection if we
7069 					 * suspect a SYN attack is under way.
7070 					 */
7071 					(void) tcp_clean_death(tcp,
7072 					    tcp->tcp_client_errno, 7);
7073 				}
7074 			}
7075 			break;
7076 		default:
7077 			break;
7078 		}
7079 		break;
7080 	case ICMP_SOURCE_QUENCH: {
7081 		/*
7082 		 * use a global boolean to control
7083 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
7084 		 * The default is false.
7085 		 */
7086 		if (tcp_icmp_source_quench) {
7087 			/*
7088 			 * Reduce the sending rate as if we got a
7089 			 * retransmit timeout
7090 			 */
7091 			uint32_t npkt;
7092 
7093 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
7094 			    tcp->tcp_mss;
7095 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
7096 			tcp->tcp_cwnd = tcp->tcp_mss;
7097 			tcp->tcp_cwnd_cnt = 0;
7098 		}
7099 		break;
7100 	}
7101 	}
7102 	freemsg(mp);
7103 }
7104 
7105 /*
7106  * CALLED OUTSIDE OF SQUEUE! It can not follow any pointers that tcp might
7107  * change. But it can refer to fields like tcp_suna and tcp_snxt.
7108  *
7109  * Function tcp_verifyicmp is called as conn_verifyicmp to verify the ICMP
7110  * error messages received by IP. The message is always received on the correct
7111  * tcp_t.
7112  */
7113 /* ARGSUSED */
7114 static boolean_t
7115 tcp_verifyicmp(conn_t *connp, void *arg2, icmph_t *icmph, icmp6_t *icmp6,
7116     ip_recv_attr_t *ira)
7117 {
7118 	tcpha_t		*tcpha = (tcpha_t *)arg2;
7119 	uint32_t	seq = ntohl(tcpha->tha_seq);
7120 	tcp_t		*tcp = connp->conn_tcp;
7121 
7122 	/*
7123 	 * TCP sequence number contained in payload of the ICMP error message
7124 	 * should be within the range SND.UNA <= SEG.SEQ < SND.NXT. Otherwise,
7125 	 * the message is either a stale ICMP error, or an attack from the
7126 	 * network. Fail the verification.
7127 	 */
7128 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
7129 		return (B_FALSE);
7130 
7131 	/* For "too big" we also check the ignore flag */
7132 	if (ira->ira_flags & IRAF_IS_IPV4) {
7133 		ASSERT(icmph != NULL);
7134 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
7135 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
7136 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7137 			return (B_FALSE);
7138 	} else {
7139 		ASSERT(icmp6 != NULL);
7140 		if (icmp6->icmp6_type == ICMP6_PACKET_TOO_BIG &&
7141 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7142 			return (B_FALSE);
7143 	}
7144 	return (B_TRUE);
7145 }
7146 
7147 /*
7148  * Update the TCP connection according to change of PMTU.
7149  *
7150  * Path MTU might have changed by either increase or decrease, so need to
7151  * adjust the MSS based on the value of ixa_pmtu. No need to handle tiny
7152  * or negative MSS, since tcp_mss_set() will do it.
7153  */
7154 static void
7155 tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only)
7156 {
7157 	uint32_t	pmtu;
7158 	int32_t		mss;
7159 	conn_t		*connp = tcp->tcp_connp;
7160 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
7161 	iaflags_t	ixaflags;
7162 
7163 	if (tcp->tcp_tcps->tcps_ignore_path_mtu)
7164 		return;
7165 
7166 	if (tcp->tcp_state < TCPS_ESTABLISHED)
7167 		return;
7168 
7169 	/*
7170 	 * Always call ip_get_pmtu() to make sure that IP has updated
7171 	 * ixa_flags properly.
7172 	 */
7173 	pmtu = ip_get_pmtu(ixa);
7174 	ixaflags = ixa->ixa_flags;
7175 
7176 	/*
7177 	 * Calculate the MSS by decreasing the PMTU by conn_ht_iphc_len and
7178 	 * IPsec overhead if applied. Make sure to use the most recent
7179 	 * IPsec information.
7180 	 */
7181 	mss = pmtu - connp->conn_ht_iphc_len - conn_ipsec_length(connp);
7182 
7183 	/*
7184 	 * Nothing to change, so just return.
7185 	 */
7186 	if (mss == tcp->tcp_mss)
7187 		return;
7188 
7189 	/*
7190 	 * Currently, for ICMP errors, only PMTU decrease is handled.
7191 	 */
7192 	if (mss > tcp->tcp_mss && decrease_only)
7193 		return;
7194 
7195 	DTRACE_PROBE2(tcp_update_pmtu, int32_t, tcp->tcp_mss, uint32_t, mss);
7196 
7197 	/*
7198 	 * Update ixa_fragsize and ixa_pmtu.
7199 	 */
7200 	ixa->ixa_fragsize = ixa->ixa_pmtu = pmtu;
7201 
7202 	/*
7203 	 * Adjust MSS and all relevant variables.
7204 	 */
7205 	tcp_mss_set(tcp, mss);
7206 
7207 	/*
7208 	 * If the PMTU is below the min size maintained by IP, then ip_get_pmtu
7209 	 * has set IXAF_PMTU_TOO_SMALL and cleared IXAF_PMTU_IPV4_DF. Since TCP
7210 	 * has a (potentially different) min size we do the same. Make sure to
7211 	 * clear IXAF_DONTFRAG, which is used by IP to decide whether to
7212 	 * fragment the packet.
7213 	 *
7214 	 * LSO over IPv6 can not be fragmented. So need to disable LSO
7215 	 * when IPv6 fragmentation is needed.
7216 	 */
7217 	if (mss < tcp->tcp_tcps->tcps_mss_min)
7218 		ixaflags |= IXAF_PMTU_TOO_SMALL;
7219 
7220 	if (ixaflags & IXAF_PMTU_TOO_SMALL)
7221 		ixaflags &= ~(IXAF_DONTFRAG | IXAF_PMTU_IPV4_DF);
7222 
7223 	if ((connp->conn_ipversion == IPV4_VERSION) &&
7224 	    !(ixaflags & IXAF_PMTU_IPV4_DF)) {
7225 		tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7226 	}
7227 	ixa->ixa_flags = ixaflags;
7228 }
7229 
7230 /*
7231  * Do slow start retransmission after ICMP errors of PMTU changes.
7232  */
7233 static void
7234 tcp_rexmit_after_error(tcp_t *tcp)
7235 {
7236 	/*
7237 	 * All sent data has been acknowledged or no data left to send, just
7238 	 * to return.
7239 	 */
7240 	if (!SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) ||
7241 	    (tcp->tcp_xmit_head == NULL))
7242 		return;
7243 
7244 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (tcp->tcp_unsent == 0))
7245 		tcp->tcp_rexmit_max = tcp->tcp_fss;
7246 	else
7247 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
7248 
7249 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
7250 	tcp->tcp_rexmit = B_TRUE;
7251 	tcp->tcp_dupack_cnt = 0;
7252 	tcp->tcp_snd_burst = TCP_CWND_SS;
7253 	tcp_ss_rexmit(tcp);
7254 }
7255 
7256 /*
7257  * tcp_icmp_error_ipv6 is called from tcp_icmp_input to process ICMPv6
7258  * error messages passed up by IP.
7259  * Assumes that IP has pulled up all the extension headers as well
7260  * as the ICMPv6 header.
7261  */
7262 static void
7263 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, ip_recv_attr_t *ira)
7264 {
7265 	icmp6_t		*icmp6;
7266 	ip6_t		*ip6h;
7267 	uint16_t	iph_hdr_length = ira->ira_ip_hdr_length;
7268 	tcpha_t		*tcpha;
7269 	uint8_t		*nexthdrp;
7270 	uint32_t	seg_seq;
7271 
7272 	/*
7273 	 * Verify that we have a complete IP header.
7274 	 */
7275 	ASSERT((MBLKL(mp) >= sizeof (ip6_t)));
7276 
7277 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
7278 	ip6h = (ip6_t *)&icmp6[1];
7279 	/*
7280 	 * Verify if we have a complete ICMP and inner IP header.
7281 	 */
7282 	if ((uchar_t *)&ip6h[1] > mp->b_wptr) {
7283 noticmpv6:
7284 		freemsg(mp);
7285 		return;
7286 	}
7287 
7288 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
7289 		goto noticmpv6;
7290 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
7291 	/*
7292 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
7293 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
7294 	 * packet.
7295 	 */
7296 	if ((*nexthdrp != IPPROTO_TCP) ||
7297 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
7298 		goto noticmpv6;
7299 	}
7300 
7301 	seg_seq = ntohl(tcpha->tha_seq);
7302 	switch (icmp6->icmp6_type) {
7303 	case ICMP6_PACKET_TOO_BIG:
7304 		/*
7305 		 * Update Path MTU, then try to send something out.
7306 		 */
7307 		tcp_update_pmtu(tcp, B_TRUE);
7308 		tcp_rexmit_after_error(tcp);
7309 		break;
7310 	case ICMP6_DST_UNREACH:
7311 		switch (icmp6->icmp6_code) {
7312 		case ICMP6_DST_UNREACH_NOPORT:
7313 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7314 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7315 			    (seg_seq == tcp->tcp_iss)) {
7316 				(void) tcp_clean_death(tcp,
7317 				    ECONNREFUSED, 8);
7318 			}
7319 			break;
7320 		case ICMP6_DST_UNREACH_ADMIN:
7321 		case ICMP6_DST_UNREACH_NOROUTE:
7322 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
7323 		case ICMP6_DST_UNREACH_ADDR:
7324 			/* Record the error in case we finally time out. */
7325 			tcp->tcp_client_errno = EHOSTUNREACH;
7326 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7327 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7328 			    (seg_seq == tcp->tcp_iss)) {
7329 				if (tcp->tcp_listener != NULL &&
7330 				    tcp->tcp_listener->tcp_syn_defense) {
7331 					/*
7332 					 * Ditch the half-open connection if we
7333 					 * suspect a SYN attack is under way.
7334 					 */
7335 					(void) tcp_clean_death(tcp,
7336 					    tcp->tcp_client_errno, 9);
7337 				}
7338 			}
7339 
7340 
7341 			break;
7342 		default:
7343 			break;
7344 		}
7345 		break;
7346 	case ICMP6_PARAM_PROB:
7347 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
7348 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
7349 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
7350 		    (uchar_t *)nexthdrp) {
7351 			if (tcp->tcp_state == TCPS_SYN_SENT ||
7352 			    tcp->tcp_state == TCPS_SYN_RCVD) {
7353 				(void) tcp_clean_death(tcp,
7354 				    ECONNREFUSED, 10);
7355 			}
7356 			break;
7357 		}
7358 		break;
7359 
7360 	case ICMP6_TIME_EXCEEDED:
7361 	default:
7362 		break;
7363 	}
7364 	freemsg(mp);
7365 }
7366 
7367 /*
7368  * Notify IP that we are having trouble with this connection.  IP should
7369  * make note so it can potentially use a different IRE.
7370  */
7371 static void
7372 tcp_ip_notify(tcp_t *tcp)
7373 {
7374 	conn_t		*connp = tcp->tcp_connp;
7375 	ire_t		*ire;
7376 
7377 	/*
7378 	 * Note: in the case of source routing we want to blow away the
7379 	 * route to the first source route hop.
7380 	 */
7381 	ire = connp->conn_ixa->ixa_ire;
7382 	if (ire != NULL && !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
7383 		if (ire->ire_ipversion == IPV4_VERSION) {
7384 			/*
7385 			 * As per RFC 1122, we send an RTM_LOSING to inform
7386 			 * routing protocols.
7387 			 */
7388 			ip_rts_change(RTM_LOSING, ire->ire_addr,
7389 			    ire->ire_gateway_addr, ire->ire_mask,
7390 			    connp->conn_laddr_v4,  0, 0, 0,
7391 			    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA),
7392 			    ire->ire_ipst);
7393 		}
7394 		(void) ire_no_good(ire);
7395 	}
7396 }
7397 
7398 #pragma inline(tcp_send_data)
7399 
7400 /*
7401  * Timer callback routine for keepalive probe.  We do a fake resend of
7402  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
7403  * check to see if we have heard anything from the other end for the last
7404  * RTO period.  If we have, set the timer to expire for another
7405  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
7406  * RTO << 1 and check again when it expires.  Keep exponentially increasing
7407  * the timeout if we have not heard from the other side.  If for more than
7408  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
7409  * kill the connection unless the keepalive abort threshold is 0.  In
7410  * that case, we will probe "forever."
7411  */
7412 static void
7413 tcp_keepalive_killer(void *arg)
7414 {
7415 	mblk_t	*mp;
7416 	conn_t	*connp = (conn_t *)arg;
7417 	tcp_t  	*tcp = connp->conn_tcp;
7418 	int32_t	firetime;
7419 	int32_t	idletime;
7420 	int32_t	ka_intrvl;
7421 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7422 
7423 	tcp->tcp_ka_tid = 0;
7424 
7425 	if (tcp->tcp_fused)
7426 		return;
7427 
7428 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
7429 	ka_intrvl = tcp->tcp_ka_interval;
7430 
7431 	/*
7432 	 * Keepalive probe should only be sent if the application has not
7433 	 * done a close on the connection.
7434 	 */
7435 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
7436 		return;
7437 	}
7438 	/* Timer fired too early, restart it. */
7439 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
7440 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7441 		    MSEC_TO_TICK(ka_intrvl));
7442 		return;
7443 	}
7444 
7445 	idletime = TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time);
7446 	/*
7447 	 * If we have not heard from the other side for a long
7448 	 * time, kill the connection unless the keepalive abort
7449 	 * threshold is 0.  In that case, we will probe "forever."
7450 	 */
7451 	if (tcp->tcp_ka_abort_thres != 0 &&
7452 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
7453 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
7454 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
7455 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
7456 		return;
7457 	}
7458 
7459 	if (tcp->tcp_snxt == tcp->tcp_suna &&
7460 	    idletime >= ka_intrvl) {
7461 		/* Fake resend of last ACKed byte. */
7462 		mblk_t	*mp1 = allocb(1, BPRI_LO);
7463 
7464 		if (mp1 != NULL) {
7465 			*mp1->b_wptr++ = '\0';
7466 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
7467 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
7468 			freeb(mp1);
7469 			/*
7470 			 * if allocation failed, fall through to start the
7471 			 * timer back.
7472 			 */
7473 			if (mp != NULL) {
7474 				tcp_send_data(tcp, mp);
7475 				BUMP_MIB(&tcps->tcps_mib,
7476 				    tcpTimKeepaliveProbe);
7477 				if (tcp->tcp_ka_last_intrvl != 0) {
7478 					int max;
7479 					/*
7480 					 * We should probe again at least
7481 					 * in ka_intrvl, but not more than
7482 					 * tcp_rexmit_interval_max.
7483 					 */
7484 					max = tcps->tcps_rexmit_interval_max;
7485 					firetime = MIN(ka_intrvl - 1,
7486 					    tcp->tcp_ka_last_intrvl << 1);
7487 					if (firetime > max)
7488 						firetime = max;
7489 				} else {
7490 					firetime = tcp->tcp_rto;
7491 				}
7492 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
7493 				    tcp_keepalive_killer,
7494 				    MSEC_TO_TICK(firetime));
7495 				tcp->tcp_ka_last_intrvl = firetime;
7496 				return;
7497 			}
7498 		}
7499 	} else {
7500 		tcp->tcp_ka_last_intrvl = 0;
7501 	}
7502 
7503 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
7504 	if ((firetime = ka_intrvl - idletime) < 0) {
7505 		firetime = ka_intrvl;
7506 	}
7507 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7508 	    MSEC_TO_TICK(firetime));
7509 }
7510 
7511 int
7512 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
7513 {
7514 	conn_t	*connp = tcp->tcp_connp;
7515 	queue_t	*q = connp->conn_rq;
7516 	int32_t	mss = tcp->tcp_mss;
7517 	int	maxpsz;
7518 
7519 	if (TCP_IS_DETACHED(tcp))
7520 		return (mss);
7521 	if (tcp->tcp_fused) {
7522 		maxpsz = tcp_fuse_maxpsz(tcp);
7523 		mss = INFPSZ;
7524 	} else if (tcp->tcp_maxpsz_multiplier == 0) {
7525 		/*
7526 		 * Set the sd_qn_maxpsz according to the socket send buffer
7527 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
7528 		 * instruct the stream head to copyin user data into contiguous
7529 		 * kernel-allocated buffers without breaking it up into smaller
7530 		 * chunks.  We round up the buffer size to the nearest SMSS.
7531 		 */
7532 		maxpsz = MSS_ROUNDUP(connp->conn_sndbuf, mss);
7533 		if (tcp->tcp_kssl_ctx == NULL)
7534 			mss = INFPSZ;
7535 		else
7536 			mss = SSL3_MAX_RECORD_LEN;
7537 	} else {
7538 		/*
7539 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
7540 		 * (and a multiple of the mss).  This instructs the stream
7541 		 * head to break down larger than SMSS writes into SMSS-
7542 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
7543 		 */
7544 		maxpsz = tcp->tcp_maxpsz_multiplier * mss;
7545 		if (maxpsz > connp->conn_sndbuf / 2) {
7546 			maxpsz = connp->conn_sndbuf / 2;
7547 			/* Round up to nearest mss */
7548 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
7549 		}
7550 	}
7551 
7552 	(void) proto_set_maxpsz(q, connp, maxpsz);
7553 	if (!(IPCL_IS_NONSTR(connp)))
7554 		connp->conn_wq->q_maxpsz = maxpsz;
7555 	if (set_maxblk)
7556 		(void) proto_set_tx_maxblk(q, connp, mss);
7557 	return (mss);
7558 }
7559 
7560 /*
7561  * Extract option values from a tcp header.  We put any found values into the
7562  * tcpopt struct and return a bitmask saying which options were found.
7563  */
7564 static int
7565 tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt)
7566 {
7567 	uchar_t		*endp;
7568 	int		len;
7569 	uint32_t	mss;
7570 	uchar_t		*up = (uchar_t *)tcpha;
7571 	int		found = 0;
7572 	int32_t		sack_len;
7573 	tcp_seq		sack_begin, sack_end;
7574 	tcp_t		*tcp;
7575 
7576 	endp = up + TCP_HDR_LENGTH(tcpha);
7577 	up += TCP_MIN_HEADER_LENGTH;
7578 	while (up < endp) {
7579 		len = endp - up;
7580 		switch (*up) {
7581 		case TCPOPT_EOL:
7582 			break;
7583 
7584 		case TCPOPT_NOP:
7585 			up++;
7586 			continue;
7587 
7588 		case TCPOPT_MAXSEG:
7589 			if (len < TCPOPT_MAXSEG_LEN ||
7590 			    up[1] != TCPOPT_MAXSEG_LEN)
7591 				break;
7592 
7593 			mss = BE16_TO_U16(up+2);
7594 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
7595 			tcpopt->tcp_opt_mss = mss;
7596 			found |= TCP_OPT_MSS_PRESENT;
7597 
7598 			up += TCPOPT_MAXSEG_LEN;
7599 			continue;
7600 
7601 		case TCPOPT_WSCALE:
7602 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
7603 				break;
7604 
7605 			if (up[2] > TCP_MAX_WINSHIFT)
7606 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
7607 			else
7608 				tcpopt->tcp_opt_wscale = up[2];
7609 			found |= TCP_OPT_WSCALE_PRESENT;
7610 
7611 			up += TCPOPT_WS_LEN;
7612 			continue;
7613 
7614 		case TCPOPT_SACK_PERMITTED:
7615 			if (len < TCPOPT_SACK_OK_LEN ||
7616 			    up[1] != TCPOPT_SACK_OK_LEN)
7617 				break;
7618 			found |= TCP_OPT_SACK_OK_PRESENT;
7619 			up += TCPOPT_SACK_OK_LEN;
7620 			continue;
7621 
7622 		case TCPOPT_SACK:
7623 			if (len <= 2 || up[1] <= 2 || len < up[1])
7624 				break;
7625 
7626 			/* If TCP is not interested in SACK blks... */
7627 			if ((tcp = tcpopt->tcp) == NULL) {
7628 				up += up[1];
7629 				continue;
7630 			}
7631 			sack_len = up[1] - TCPOPT_HEADER_LEN;
7632 			up += TCPOPT_HEADER_LEN;
7633 
7634 			/*
7635 			 * If the list is empty, allocate one and assume
7636 			 * nothing is sack'ed.
7637 			 */
7638 			ASSERT(tcp->tcp_sack_info != NULL);
7639 			if (tcp->tcp_notsack_list == NULL) {
7640 				tcp_notsack_update(&(tcp->tcp_notsack_list),
7641 				    tcp->tcp_suna, tcp->tcp_snxt,
7642 				    &(tcp->tcp_num_notsack_blk),
7643 				    &(tcp->tcp_cnt_notsack_list));
7644 
7645 				/*
7646 				 * Make sure tcp_notsack_list is not NULL.
7647 				 * This happens when kmem_alloc(KM_NOSLEEP)
7648 				 * returns NULL.
7649 				 */
7650 				if (tcp->tcp_notsack_list == NULL) {
7651 					up += sack_len;
7652 					continue;
7653 				}
7654 				tcp->tcp_fack = tcp->tcp_suna;
7655 			}
7656 
7657 			while (sack_len > 0) {
7658 				if (up + 8 > endp) {
7659 					up = endp;
7660 					break;
7661 				}
7662 				sack_begin = BE32_TO_U32(up);
7663 				up += 4;
7664 				sack_end = BE32_TO_U32(up);
7665 				up += 4;
7666 				sack_len -= 8;
7667 				/*
7668 				 * Bounds checking.  Make sure the SACK
7669 				 * info is within tcp_suna and tcp_snxt.
7670 				 * If this SACK blk is out of bound, ignore
7671 				 * it but continue to parse the following
7672 				 * blks.
7673 				 */
7674 				if (SEQ_LEQ(sack_end, sack_begin) ||
7675 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
7676 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
7677 					continue;
7678 				}
7679 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
7680 				    sack_begin, sack_end,
7681 				    &(tcp->tcp_num_notsack_blk),
7682 				    &(tcp->tcp_cnt_notsack_list));
7683 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
7684 					tcp->tcp_fack = sack_end;
7685 				}
7686 			}
7687 			found |= TCP_OPT_SACK_PRESENT;
7688 			continue;
7689 
7690 		case TCPOPT_TSTAMP:
7691 			if (len < TCPOPT_TSTAMP_LEN ||
7692 			    up[1] != TCPOPT_TSTAMP_LEN)
7693 				break;
7694 
7695 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
7696 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
7697 
7698 			found |= TCP_OPT_TSTAMP_PRESENT;
7699 
7700 			up += TCPOPT_TSTAMP_LEN;
7701 			continue;
7702 
7703 		default:
7704 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
7705 				break;
7706 			up += up[1];
7707 			continue;
7708 		}
7709 		break;
7710 	}
7711 	return (found);
7712 }
7713 
7714 /*
7715  * Set the MSS associated with a particular tcp based on its current value,
7716  * and a new one passed in. Observe minimums and maximums, and reset other
7717  * state variables that we want to view as multiples of MSS.
7718  *
7719  * The value of MSS could be either increased or descreased.
7720  */
7721 static void
7722 tcp_mss_set(tcp_t *tcp, uint32_t mss)
7723 {
7724 	uint32_t	mss_max;
7725 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7726 	conn_t		*connp = tcp->tcp_connp;
7727 
7728 	if (connp->conn_ipversion == IPV4_VERSION)
7729 		mss_max = tcps->tcps_mss_max_ipv4;
7730 	else
7731 		mss_max = tcps->tcps_mss_max_ipv6;
7732 
7733 	if (mss < tcps->tcps_mss_min)
7734 		mss = tcps->tcps_mss_min;
7735 	if (mss > mss_max)
7736 		mss = mss_max;
7737 	/*
7738 	 * Unless naglim has been set by our client to
7739 	 * a non-mss value, force naglim to track mss.
7740 	 * This can help to aggregate small writes.
7741 	 */
7742 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
7743 		tcp->tcp_naglim = mss;
7744 	/*
7745 	 * TCP should be able to buffer at least 4 MSS data for obvious
7746 	 * performance reason.
7747 	 */
7748 	if ((mss << 2) > connp->conn_sndbuf)
7749 		connp->conn_sndbuf = mss << 2;
7750 
7751 	/*
7752 	 * Set the send lowater to at least twice of MSS.
7753 	 */
7754 	if ((mss << 1) > connp->conn_sndlowat)
7755 		connp->conn_sndlowat = mss << 1;
7756 
7757 	/*
7758 	 * Update tcp_cwnd according to the new value of MSS. Keep the
7759 	 * previous ratio to preserve the transmit rate.
7760 	 */
7761 	tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
7762 	tcp->tcp_cwnd_cnt = 0;
7763 
7764 	tcp->tcp_mss = mss;
7765 	(void) tcp_maxpsz_set(tcp, B_TRUE);
7766 }
7767 
7768 /* For /dev/tcp aka AF_INET open */
7769 static int
7770 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7771 {
7772 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
7773 }
7774 
7775 /* For /dev/tcp6 aka AF_INET6 open */
7776 static int
7777 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7778 {
7779 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
7780 }
7781 
7782 static conn_t *
7783 tcp_create_common(cred_t *credp, boolean_t isv6, boolean_t issocket,
7784     int *errorp)
7785 {
7786 	tcp_t		*tcp = NULL;
7787 	conn_t		*connp;
7788 	zoneid_t	zoneid;
7789 	tcp_stack_t	*tcps;
7790 	squeue_t	*sqp;
7791 
7792 	ASSERT(errorp != NULL);
7793 	/*
7794 	 * Find the proper zoneid and netstack.
7795 	 */
7796 	/*
7797 	 * Special case for install: miniroot needs to be able to
7798 	 * access files via NFS as though it were always in the
7799 	 * global zone.
7800 	 */
7801 	if (credp == kcred && nfs_global_client_only != 0) {
7802 		zoneid = GLOBAL_ZONEID;
7803 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
7804 		    netstack_tcp;
7805 		ASSERT(tcps != NULL);
7806 	} else {
7807 		netstack_t *ns;
7808 
7809 		ns = netstack_find_by_cred(credp);
7810 		ASSERT(ns != NULL);
7811 		tcps = ns->netstack_tcp;
7812 		ASSERT(tcps != NULL);
7813 
7814 		/*
7815 		 * For exclusive stacks we set the zoneid to zero
7816 		 * to make TCP operate as if in the global zone.
7817 		 */
7818 		if (tcps->tcps_netstack->netstack_stackid !=
7819 		    GLOBAL_NETSTACKID)
7820 			zoneid = GLOBAL_ZONEID;
7821 		else
7822 			zoneid = crgetzoneid(credp);
7823 	}
7824 
7825 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
7826 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
7827 	/*
7828 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
7829 	 * so we drop it by one.
7830 	 */
7831 	netstack_rele(tcps->tcps_netstack);
7832 	if (connp == NULL) {
7833 		*errorp = ENOSR;
7834 		return (NULL);
7835 	}
7836 	ASSERT(connp->conn_ixa->ixa_protocol == connp->conn_proto);
7837 
7838 	connp->conn_sqp = sqp;
7839 	connp->conn_initial_sqp = connp->conn_sqp;
7840 	connp->conn_ixa->ixa_sqp = connp->conn_sqp;
7841 	tcp = connp->conn_tcp;
7842 
7843 	/*
7844 	 * Besides asking IP to set the checksum for us, have conn_ip_output
7845 	 * to do the following checks when necessary:
7846 	 *
7847 	 * IXAF_VERIFY_SOURCE: drop packets when our outer source goes invalid
7848 	 * IXAF_VERIFY_PMTU: verify PMTU changes
7849 	 * IXAF_VERIFY_LSO: verify LSO capability changes
7850 	 */
7851 	connp->conn_ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
7852 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO;
7853 
7854 	if (!tcps->tcps_dev_flow_ctl)
7855 		connp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
7856 
7857 	if (isv6) {
7858 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
7859 		connp->conn_ipversion = IPV6_VERSION;
7860 		connp->conn_family = AF_INET6;
7861 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7862 		connp->conn_default_ttl = tcps->tcps_ipv6_hoplimit;
7863 	} else {
7864 		connp->conn_ipversion = IPV4_VERSION;
7865 		connp->conn_family = AF_INET;
7866 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7867 		connp->conn_default_ttl = tcps->tcps_ipv4_ttl;
7868 	}
7869 	connp->conn_xmit_ipp.ipp_unicast_hops = connp->conn_default_ttl;
7870 
7871 	crhold(credp);
7872 	connp->conn_cred = credp;
7873 	connp->conn_cpid = curproc->p_pid;
7874 	connp->conn_open_time = ddi_get_lbolt64();
7875 
7876 	connp->conn_zoneid = zoneid;
7877 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
7878 	connp->conn_ixa->ixa_zoneid = zoneid;
7879 	connp->conn_mlp_type = mlptSingle;
7880 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
7881 	ASSERT(tcp->tcp_tcps == tcps);
7882 
7883 	/*
7884 	 * If the caller has the process-wide flag set, then default to MAC
7885 	 * exempt mode.  This allows read-down to unlabeled hosts.
7886 	 */
7887 	if (getpflags(NET_MAC_AWARE, credp) != 0)
7888 		connp->conn_mac_mode = CONN_MAC_AWARE;
7889 
7890 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
7891 
7892 	if (issocket) {
7893 		tcp->tcp_issocket = 1;
7894 	}
7895 
7896 	connp->conn_rcvbuf = tcps->tcps_recv_hiwat;
7897 	connp->conn_sndbuf = tcps->tcps_xmit_hiwat;
7898 	connp->conn_sndlowat = tcps->tcps_xmit_lowat;
7899 	connp->conn_so_type = SOCK_STREAM;
7900 	connp->conn_wroff = connp->conn_ht_iphc_allocated +
7901 	    tcps->tcps_wroff_xtra;
7902 
7903 	SOCK_CONNID_INIT(tcp->tcp_connid);
7904 	tcp->tcp_state = TCPS_IDLE;
7905 	tcp_init_values(tcp);
7906 	return (connp);
7907 }
7908 
7909 static int
7910 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
7911     boolean_t isv6)
7912 {
7913 	tcp_t		*tcp = NULL;
7914 	conn_t		*connp = NULL;
7915 	int		err;
7916 	vmem_t		*minor_arena = NULL;
7917 	dev_t		conn_dev;
7918 	boolean_t	issocket;
7919 
7920 	if (q->q_ptr != NULL)
7921 		return (0);
7922 
7923 	if (sflag == MODOPEN)
7924 		return (EINVAL);
7925 
7926 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
7927 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
7928 		minor_arena = ip_minor_arena_la;
7929 	} else {
7930 		/*
7931 		 * Either minor numbers in the large arena were exhausted
7932 		 * or a non socket application is doing the open.
7933 		 * Try to allocate from the small arena.
7934 		 */
7935 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
7936 			return (EBUSY);
7937 		}
7938 		minor_arena = ip_minor_arena_sa;
7939 	}
7940 
7941 	ASSERT(minor_arena != NULL);
7942 
7943 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
7944 
7945 	if (flag & SO_FALLBACK) {
7946 		/*
7947 		 * Non streams socket needs a stream to fallback to
7948 		 */
7949 		RD(q)->q_ptr = (void *)conn_dev;
7950 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
7951 		WR(q)->q_ptr = (void *)minor_arena;
7952 		qprocson(q);
7953 		return (0);
7954 	} else if (flag & SO_ACCEPTOR) {
7955 		q->q_qinfo = &tcp_acceptor_rinit;
7956 		/*
7957 		 * the conn_dev and minor_arena will be subsequently used by
7958 		 * tcp_tli_accept() and tcp_tpi_close_accept() to figure out
7959 		 * the minor device number for this connection from the q_ptr.
7960 		 */
7961 		RD(q)->q_ptr = (void *)conn_dev;
7962 		WR(q)->q_qinfo = &tcp_acceptor_winit;
7963 		WR(q)->q_ptr = (void *)minor_arena;
7964 		qprocson(q);
7965 		return (0);
7966 	}
7967 
7968 	issocket = flag & SO_SOCKSTR;
7969 	connp = tcp_create_common(credp, isv6, issocket, &err);
7970 
7971 	if (connp == NULL) {
7972 		inet_minor_free(minor_arena, conn_dev);
7973 		q->q_ptr = WR(q)->q_ptr = NULL;
7974 		return (err);
7975 	}
7976 
7977 	connp->conn_rq = q;
7978 	connp->conn_wq = WR(q);
7979 	q->q_ptr = WR(q)->q_ptr = connp;
7980 
7981 	connp->conn_dev = conn_dev;
7982 	connp->conn_minor_arena = minor_arena;
7983 
7984 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
7985 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
7986 
7987 	tcp = connp->conn_tcp;
7988 
7989 	if (issocket) {
7990 		WR(q)->q_qinfo = &tcp_sock_winit;
7991 	} else {
7992 #ifdef  _ILP32
7993 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
7994 #else
7995 		tcp->tcp_acceptor_id = conn_dev;
7996 #endif  /* _ILP32 */
7997 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
7998 	}
7999 
8000 	/*
8001 	 * Put the ref for TCP. Ref for IP was already put
8002 	 * by ipcl_conn_create. Also Make the conn_t globally
8003 	 * visible to walkers
8004 	 */
8005 	mutex_enter(&connp->conn_lock);
8006 	CONN_INC_REF_LOCKED(connp);
8007 	ASSERT(connp->conn_ref == 2);
8008 	connp->conn_state_flags &= ~CONN_INCIPIENT;
8009 	mutex_exit(&connp->conn_lock);
8010 
8011 	qprocson(q);
8012 	return (0);
8013 }
8014 
8015 /*
8016  * Some TCP options can be "set" by requesting them in the option
8017  * buffer. This is needed for XTI feature test though we do not
8018  * allow it in general. We interpret that this mechanism is more
8019  * applicable to OSI protocols and need not be allowed in general.
8020  * This routine filters out options for which it is not allowed (most)
8021  * and lets through those (few) for which it is. [ The XTI interface
8022  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
8023  * ever implemented will have to be allowed here ].
8024  */
8025 static boolean_t
8026 tcp_allow_connopt_set(int level, int name)
8027 {
8028 
8029 	switch (level) {
8030 	case IPPROTO_TCP:
8031 		switch (name) {
8032 		case TCP_NODELAY:
8033 			return (B_TRUE);
8034 		default:
8035 			return (B_FALSE);
8036 		}
8037 		/*NOTREACHED*/
8038 	default:
8039 		return (B_FALSE);
8040 	}
8041 	/*NOTREACHED*/
8042 }
8043 
8044 /*
8045  * This routine gets default values of certain options whose default
8046  * values are maintained by protocol specific code
8047  */
8048 /* ARGSUSED */
8049 int
8050 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
8051 {
8052 	int32_t	*i1 = (int32_t *)ptr;
8053 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
8054 
8055 	switch (level) {
8056 	case IPPROTO_TCP:
8057 		switch (name) {
8058 		case TCP_NOTIFY_THRESHOLD:
8059 			*i1 = tcps->tcps_ip_notify_interval;
8060 			break;
8061 		case TCP_ABORT_THRESHOLD:
8062 			*i1 = tcps->tcps_ip_abort_interval;
8063 			break;
8064 		case TCP_CONN_NOTIFY_THRESHOLD:
8065 			*i1 = tcps->tcps_ip_notify_cinterval;
8066 			break;
8067 		case TCP_CONN_ABORT_THRESHOLD:
8068 			*i1 = tcps->tcps_ip_abort_cinterval;
8069 			break;
8070 		default:
8071 			return (-1);
8072 		}
8073 		break;
8074 	case IPPROTO_IP:
8075 		switch (name) {
8076 		case IP_TTL:
8077 			*i1 = tcps->tcps_ipv4_ttl;
8078 			break;
8079 		default:
8080 			return (-1);
8081 		}
8082 		break;
8083 	case IPPROTO_IPV6:
8084 		switch (name) {
8085 		case IPV6_UNICAST_HOPS:
8086 			*i1 = tcps->tcps_ipv6_hoplimit;
8087 			break;
8088 		default:
8089 			return (-1);
8090 		}
8091 		break;
8092 	default:
8093 		return (-1);
8094 	}
8095 	return (sizeof (int));
8096 }
8097 
8098 /*
8099  * TCP routine to get the values of options.
8100  */
8101 static int
8102 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
8103 {
8104 	int		*i1 = (int *)ptr;
8105 	tcp_t		*tcp = connp->conn_tcp;
8106 	conn_opt_arg_t	coas;
8107 	int		retval;
8108 
8109 	coas.coa_connp = connp;
8110 	coas.coa_ixa = connp->conn_ixa;
8111 	coas.coa_ipp = &connp->conn_xmit_ipp;
8112 	coas.coa_ancillary = B_FALSE;
8113 	coas.coa_changed = 0;
8114 
8115 	switch (level) {
8116 	case SOL_SOCKET:
8117 		switch (name) {
8118 		case SO_SND_COPYAVOID:
8119 			*i1 = tcp->tcp_snd_zcopy_on ?
8120 			    SO_SND_COPYAVOID : 0;
8121 			return (sizeof (int));
8122 		case SO_ACCEPTCONN:
8123 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
8124 			return (sizeof (int));
8125 		}
8126 		break;
8127 	case IPPROTO_TCP:
8128 		switch (name) {
8129 		case TCP_NODELAY:
8130 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
8131 			return (sizeof (int));
8132 		case TCP_MAXSEG:
8133 			*i1 = tcp->tcp_mss;
8134 			return (sizeof (int));
8135 		case TCP_NOTIFY_THRESHOLD:
8136 			*i1 = (int)tcp->tcp_first_timer_threshold;
8137 			return (sizeof (int));
8138 		case TCP_ABORT_THRESHOLD:
8139 			*i1 = tcp->tcp_second_timer_threshold;
8140 			return (sizeof (int));
8141 		case TCP_CONN_NOTIFY_THRESHOLD:
8142 			*i1 = tcp->tcp_first_ctimer_threshold;
8143 			return (sizeof (int));
8144 		case TCP_CONN_ABORT_THRESHOLD:
8145 			*i1 = tcp->tcp_second_ctimer_threshold;
8146 			return (sizeof (int));
8147 		case TCP_INIT_CWND:
8148 			*i1 = tcp->tcp_init_cwnd;
8149 			return (sizeof (int));
8150 		case TCP_KEEPALIVE_THRESHOLD:
8151 			*i1 = tcp->tcp_ka_interval;
8152 			return (sizeof (int));
8153 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8154 			*i1 = tcp->tcp_ka_abort_thres;
8155 			return (sizeof (int));
8156 		case TCP_CORK:
8157 			*i1 = tcp->tcp_cork;
8158 			return (sizeof (int));
8159 		}
8160 		break;
8161 	case IPPROTO_IP:
8162 		if (connp->conn_family != AF_INET)
8163 			return (-1);
8164 		switch (name) {
8165 		case IP_OPTIONS:
8166 		case T_IP_OPTIONS:
8167 			/* Caller ensures enough space */
8168 			return (ip_opt_get_user(connp, ptr));
8169 		default:
8170 			break;
8171 		}
8172 		break;
8173 
8174 	case IPPROTO_IPV6:
8175 		/*
8176 		 * IPPROTO_IPV6 options are only supported for sockets
8177 		 * that are using IPv6 on the wire.
8178 		 */
8179 		if (connp->conn_ipversion != IPV6_VERSION) {
8180 			return (-1);
8181 		}
8182 		switch (name) {
8183 		case IPV6_PATHMTU:
8184 			if (tcp->tcp_state < TCPS_ESTABLISHED)
8185 				return (-1);
8186 			break;
8187 		}
8188 		break;
8189 	}
8190 	mutex_enter(&connp->conn_lock);
8191 	retval = conn_opt_get(&coas, level, name, ptr);
8192 	mutex_exit(&connp->conn_lock);
8193 	return (retval);
8194 }
8195 
8196 /*
8197  * TCP routine to get the values of options.
8198  */
8199 int
8200 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
8201 {
8202 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
8203 }
8204 
8205 /* returns UNIX error, the optlen is a value-result arg */
8206 int
8207 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8208     void *optvalp, socklen_t *optlen, cred_t *cr)
8209 {
8210 	conn_t		*connp = (conn_t *)proto_handle;
8211 	squeue_t	*sqp = connp->conn_sqp;
8212 	int		error;
8213 	t_uscalar_t	max_optbuf_len;
8214 	void		*optvalp_buf;
8215 	int		len;
8216 
8217 	ASSERT(connp->conn_upper_handle != NULL);
8218 
8219 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
8220 	    tcp_opt_obj.odb_opt_des_arr,
8221 	    tcp_opt_obj.odb_opt_arr_cnt,
8222 	    B_FALSE, B_TRUE, cr);
8223 	if (error != 0) {
8224 		if (error < 0) {
8225 			error = proto_tlitosyserr(-error);
8226 		}
8227 		return (error);
8228 	}
8229 
8230 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
8231 
8232 	error = squeue_synch_enter(sqp, connp, NULL);
8233 	if (error == ENOMEM) {
8234 		kmem_free(optvalp_buf, max_optbuf_len);
8235 		return (ENOMEM);
8236 	}
8237 
8238 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
8239 	squeue_synch_exit(sqp, connp);
8240 
8241 	if (len == -1) {
8242 		kmem_free(optvalp_buf, max_optbuf_len);
8243 		return (EINVAL);
8244 	}
8245 
8246 	/*
8247 	 * update optlen and copy option value
8248 	 */
8249 	t_uscalar_t size = MIN(len, *optlen);
8250 
8251 	bcopy(optvalp_buf, optvalp, size);
8252 	bcopy(&size, optlen, sizeof (size));
8253 
8254 	kmem_free(optvalp_buf, max_optbuf_len);
8255 	return (0);
8256 }
8257 
8258 /*
8259  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
8260  * Parameters are assumed to be verified by the caller.
8261  */
8262 /* ARGSUSED */
8263 int
8264 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
8265     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8266     void *thisdg_attrs, cred_t *cr)
8267 {
8268 	tcp_t	*tcp = connp->conn_tcp;
8269 	int	*i1 = (int *)invalp;
8270 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
8271 	boolean_t checkonly;
8272 	int	reterr;
8273 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8274 	conn_opt_arg_t	coas;
8275 
8276 	coas.coa_connp = connp;
8277 	coas.coa_ixa = connp->conn_ixa;
8278 	coas.coa_ipp = &connp->conn_xmit_ipp;
8279 	coas.coa_ancillary = B_FALSE;
8280 	coas.coa_changed = 0;
8281 
8282 	switch (optset_context) {
8283 	case SETFN_OPTCOM_CHECKONLY:
8284 		checkonly = B_TRUE;
8285 		/*
8286 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
8287 		 * inlen != 0 implies value supplied and
8288 		 * 	we have to "pretend" to set it.
8289 		 * inlen == 0 implies that there is no
8290 		 * 	value part in T_CHECK request and just validation
8291 		 * done elsewhere should be enough, we just return here.
8292 		 */
8293 		if (inlen == 0) {
8294 			*outlenp = 0;
8295 			return (0);
8296 		}
8297 		break;
8298 	case SETFN_OPTCOM_NEGOTIATE:
8299 		checkonly = B_FALSE;
8300 		break;
8301 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
8302 	case SETFN_CONN_NEGOTIATE:
8303 		checkonly = B_FALSE;
8304 		/*
8305 		 * Negotiating local and "association-related" options
8306 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
8307 		 * primitives is allowed by XTI, but we choose
8308 		 * to not implement this style negotiation for Internet
8309 		 * protocols (We interpret it is a must for OSI world but
8310 		 * optional for Internet protocols) for all options.
8311 		 * [ Will do only for the few options that enable test
8312 		 * suites that our XTI implementation of this feature
8313 		 * works for transports that do allow it ]
8314 		 */
8315 		if (!tcp_allow_connopt_set(level, name)) {
8316 			*outlenp = 0;
8317 			return (EINVAL);
8318 		}
8319 		break;
8320 	default:
8321 		/*
8322 		 * We should never get here
8323 		 */
8324 		*outlenp = 0;
8325 		return (EINVAL);
8326 	}
8327 
8328 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
8329 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
8330 
8331 	/*
8332 	 * For TCP, we should have no ancillary data sent down
8333 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
8334 	 * has to be zero.
8335 	 */
8336 	ASSERT(thisdg_attrs == NULL);
8337 
8338 	/*
8339 	 * For fixed length options, no sanity check
8340 	 * of passed in length is done. It is assumed *_optcom_req()
8341 	 * routines do the right thing.
8342 	 */
8343 	switch (level) {
8344 	case SOL_SOCKET:
8345 		switch (name) {
8346 		case SO_KEEPALIVE:
8347 			if (checkonly) {
8348 				/* check only case */
8349 				break;
8350 			}
8351 
8352 			if (!onoff) {
8353 				if (connp->conn_keepalive) {
8354 					if (tcp->tcp_ka_tid != 0) {
8355 						(void) TCP_TIMER_CANCEL(tcp,
8356 						    tcp->tcp_ka_tid);
8357 						tcp->tcp_ka_tid = 0;
8358 					}
8359 					connp->conn_keepalive = 0;
8360 				}
8361 				break;
8362 			}
8363 			if (!connp->conn_keepalive) {
8364 				/* Crank up the keepalive timer */
8365 				tcp->tcp_ka_last_intrvl = 0;
8366 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8367 				    tcp_keepalive_killer,
8368 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
8369 				connp->conn_keepalive = 1;
8370 			}
8371 			break;
8372 		case SO_SNDBUF: {
8373 			if (*i1 > tcps->tcps_max_buf) {
8374 				*outlenp = 0;
8375 				return (ENOBUFS);
8376 			}
8377 			if (checkonly)
8378 				break;
8379 
8380 			connp->conn_sndbuf = *i1;
8381 			if (tcps->tcps_snd_lowat_fraction != 0) {
8382 				connp->conn_sndlowat = connp->conn_sndbuf /
8383 				    tcps->tcps_snd_lowat_fraction;
8384 			}
8385 			(void) tcp_maxpsz_set(tcp, B_TRUE);
8386 			/*
8387 			 * If we are flow-controlled, recheck the condition.
8388 			 * There are apps that increase SO_SNDBUF size when
8389 			 * flow-controlled (EWOULDBLOCK), and expect the flow
8390 			 * control condition to be lifted right away.
8391 			 */
8392 			mutex_enter(&tcp->tcp_non_sq_lock);
8393 			if (tcp->tcp_flow_stopped &&
8394 			    TCP_UNSENT_BYTES(tcp) < connp->conn_sndbuf) {
8395 				tcp_clrqfull(tcp);
8396 			}
8397 			mutex_exit(&tcp->tcp_non_sq_lock);
8398 			*outlenp = inlen;
8399 			return (0);
8400 		}
8401 		case SO_RCVBUF:
8402 			if (*i1 > tcps->tcps_max_buf) {
8403 				*outlenp = 0;
8404 				return (ENOBUFS);
8405 			}
8406 			/* Silently ignore zero */
8407 			if (!checkonly && *i1 != 0) {
8408 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
8409 				(void) tcp_rwnd_set(tcp, *i1);
8410 			}
8411 			/*
8412 			 * XXX should we return the rwnd here
8413 			 * and tcp_opt_get ?
8414 			 */
8415 			*outlenp = inlen;
8416 			return (0);
8417 		case SO_SND_COPYAVOID:
8418 			if (!checkonly) {
8419 				if (tcp->tcp_loopback ||
8420 				    (tcp->tcp_kssl_ctx != NULL) ||
8421 				    (onoff != 1) || !tcp_zcopy_check(tcp)) {
8422 					*outlenp = 0;
8423 					return (EOPNOTSUPP);
8424 				}
8425 				tcp->tcp_snd_zcopy_aware = 1;
8426 			}
8427 			*outlenp = inlen;
8428 			return (0);
8429 		}
8430 		break;
8431 	case IPPROTO_TCP:
8432 		switch (name) {
8433 		case TCP_NODELAY:
8434 			if (!checkonly)
8435 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
8436 			break;
8437 		case TCP_NOTIFY_THRESHOLD:
8438 			if (!checkonly)
8439 				tcp->tcp_first_timer_threshold = *i1;
8440 			break;
8441 		case TCP_ABORT_THRESHOLD:
8442 			if (!checkonly)
8443 				tcp->tcp_second_timer_threshold = *i1;
8444 			break;
8445 		case TCP_CONN_NOTIFY_THRESHOLD:
8446 			if (!checkonly)
8447 				tcp->tcp_first_ctimer_threshold = *i1;
8448 			break;
8449 		case TCP_CONN_ABORT_THRESHOLD:
8450 			if (!checkonly)
8451 				tcp->tcp_second_ctimer_threshold = *i1;
8452 			break;
8453 		case TCP_RECVDSTADDR:
8454 			if (tcp->tcp_state > TCPS_LISTEN) {
8455 				*outlenp = 0;
8456 				return (EOPNOTSUPP);
8457 			}
8458 			/* Setting done in conn_opt_set */
8459 			break;
8460 		case TCP_INIT_CWND: {
8461 			uint32_t init_cwnd = *((uint32_t *)invalp);
8462 
8463 			if (checkonly)
8464 				break;
8465 
8466 			/*
8467 			 * Only allow socket with network configuration
8468 			 * privilege to set the initial cwnd to be larger
8469 			 * than allowed by RFC 3390.
8470 			 */
8471 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
8472 				tcp->tcp_init_cwnd = init_cwnd;
8473 				break;
8474 			}
8475 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
8476 				*outlenp = 0;
8477 				return (reterr);
8478 			}
8479 			if (init_cwnd > TCP_MAX_INIT_CWND) {
8480 				*outlenp = 0;
8481 				return (EINVAL);
8482 			}
8483 			tcp->tcp_init_cwnd = init_cwnd;
8484 			break;
8485 		}
8486 		case TCP_KEEPALIVE_THRESHOLD:
8487 			if (checkonly)
8488 				break;
8489 
8490 			if (*i1 < tcps->tcps_keepalive_interval_low ||
8491 			    *i1 > tcps->tcps_keepalive_interval_high) {
8492 				*outlenp = 0;
8493 				return (EINVAL);
8494 			}
8495 			if (*i1 != tcp->tcp_ka_interval) {
8496 				tcp->tcp_ka_interval = *i1;
8497 				/*
8498 				 * Check if we need to restart the
8499 				 * keepalive timer.
8500 				 */
8501 				if (tcp->tcp_ka_tid != 0) {
8502 					ASSERT(connp->conn_keepalive);
8503 					(void) TCP_TIMER_CANCEL(tcp,
8504 					    tcp->tcp_ka_tid);
8505 					tcp->tcp_ka_last_intrvl = 0;
8506 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
8507 					    tcp_keepalive_killer,
8508 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
8509 				}
8510 			}
8511 			break;
8512 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8513 			if (!checkonly) {
8514 				if (*i1 <
8515 				    tcps->tcps_keepalive_abort_interval_low ||
8516 				    *i1 >
8517 				    tcps->tcps_keepalive_abort_interval_high) {
8518 					*outlenp = 0;
8519 					return (EINVAL);
8520 				}
8521 				tcp->tcp_ka_abort_thres = *i1;
8522 			}
8523 			break;
8524 		case TCP_CORK:
8525 			if (!checkonly) {
8526 				/*
8527 				 * if tcp->tcp_cork was set and is now
8528 				 * being unset, we have to make sure that
8529 				 * the remaining data gets sent out. Also
8530 				 * unset tcp->tcp_cork so that tcp_wput_data()
8531 				 * can send data even if it is less than mss
8532 				 */
8533 				if (tcp->tcp_cork && onoff == 0 &&
8534 				    tcp->tcp_unsent > 0) {
8535 					tcp->tcp_cork = B_FALSE;
8536 					tcp_wput_data(tcp, NULL, B_FALSE);
8537 				}
8538 				tcp->tcp_cork = onoff;
8539 			}
8540 			break;
8541 		default:
8542 			break;
8543 		}
8544 		break;
8545 	case IPPROTO_IP:
8546 		if (connp->conn_family != AF_INET) {
8547 			*outlenp = 0;
8548 			return (EINVAL);
8549 		}
8550 		switch (name) {
8551 		case IP_SEC_OPT:
8552 			/*
8553 			 * We should not allow policy setting after
8554 			 * we start listening for connections.
8555 			 */
8556 			if (tcp->tcp_state == TCPS_LISTEN) {
8557 				return (EINVAL);
8558 			}
8559 			break;
8560 		}
8561 		break;
8562 	case IPPROTO_IPV6:
8563 		/*
8564 		 * IPPROTO_IPV6 options are only supported for sockets
8565 		 * that are using IPv6 on the wire.
8566 		 */
8567 		if (connp->conn_ipversion != IPV6_VERSION) {
8568 			*outlenp = 0;
8569 			return (EINVAL);
8570 		}
8571 
8572 		switch (name) {
8573 		case IPV6_RECVPKTINFO:
8574 			if (!checkonly) {
8575 				/* Force it to be sent up with the next msg */
8576 				tcp->tcp_recvifindex = 0;
8577 			}
8578 			break;
8579 		case IPV6_RECVTCLASS:
8580 			if (!checkonly) {
8581 				/* Force it to be sent up with the next msg */
8582 				tcp->tcp_recvtclass = 0xffffffffU;
8583 			}
8584 			break;
8585 		case IPV6_RECVHOPLIMIT:
8586 			if (!checkonly) {
8587 				/* Force it to be sent up with the next msg */
8588 				tcp->tcp_recvhops = 0xffffffffU;
8589 			}
8590 			break;
8591 		case IPV6_PKTINFO:
8592 			/* This is an extra check for TCP */
8593 			if (inlen == sizeof (struct in6_pktinfo)) {
8594 				struct in6_pktinfo *pkti;
8595 
8596 				pkti = (struct in6_pktinfo *)invalp;
8597 				/*
8598 				 * RFC 3542 states that ipi6_addr must be
8599 				 * the unspecified address when setting the
8600 				 * IPV6_PKTINFO sticky socket option on a
8601 				 * TCP socket.
8602 				 */
8603 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
8604 					return (EINVAL);
8605 			}
8606 			break;
8607 		case IPV6_SEC_OPT:
8608 			/*
8609 			 * We should not allow policy setting after
8610 			 * we start listening for connections.
8611 			 */
8612 			if (tcp->tcp_state == TCPS_LISTEN) {
8613 				return (EINVAL);
8614 			}
8615 			break;
8616 		}
8617 		break;
8618 	}
8619 	reterr = conn_opt_set(&coas, level, name, inlen, invalp,
8620 	    checkonly, cr);
8621 	if (reterr != 0) {
8622 		*outlenp = 0;
8623 		return (reterr);
8624 	}
8625 
8626 	/*
8627 	 * Common case of OK return with outval same as inval
8628 	 */
8629 	if (invalp != outvalp) {
8630 		/* don't trust bcopy for identical src/dst */
8631 		(void) bcopy(invalp, outvalp, inlen);
8632 	}
8633 	*outlenp = inlen;
8634 
8635 	if (coas.coa_changed & COA_HEADER_CHANGED) {
8636 		/* If we are connected we rebuilt the headers */
8637 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8638 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8639 			reterr = tcp_build_hdrs(tcp);
8640 			if (reterr != 0)
8641 				return (reterr);
8642 		}
8643 	}
8644 	if (coas.coa_changed & COA_ROUTE_CHANGED) {
8645 		in6_addr_t nexthop;
8646 
8647 		/*
8648 		 * If we are connected we re-cache the information.
8649 		 * We ignore errors to preserve BSD behavior.
8650 		 * Note that we don't redo IPsec policy lookup here
8651 		 * since the final destination (or source) didn't change.
8652 		 */
8653 		ip_attr_nexthop(&connp->conn_xmit_ipp, connp->conn_ixa,
8654 		    &connp->conn_faddr_v6, &nexthop);
8655 
8656 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8657 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8658 			(void) ip_attr_connect(connp, connp->conn_ixa,
8659 			    &connp->conn_laddr_v6, &connp->conn_faddr_v6,
8660 			    &nexthop, connp->conn_fport, NULL, NULL,
8661 			    IPDF_VERIFY_DST);
8662 		}
8663 	}
8664 	if ((coas.coa_changed & COA_SNDBUF_CHANGED) && !IPCL_IS_NONSTR(connp)) {
8665 		connp->conn_wq->q_hiwat = connp->conn_sndbuf;
8666 	}
8667 	if (coas.coa_changed & COA_WROFF_CHANGED) {
8668 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8669 		    tcps->tcps_wroff_xtra;
8670 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8671 		    connp->conn_wroff);
8672 	}
8673 	if (coas.coa_changed & COA_OOBINLINE_CHANGED) {
8674 		if (IPCL_IS_NONSTR(connp))
8675 			proto_set_rx_oob_opt(connp, onoff);
8676 	}
8677 	return (0);
8678 }
8679 
8680 /* ARGSUSED */
8681 int
8682 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
8683     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8684     void *thisdg_attrs, cred_t *cr)
8685 {
8686 	conn_t	*connp =  Q_TO_CONN(q);
8687 
8688 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
8689 	    outlenp, outvalp, thisdg_attrs, cr));
8690 }
8691 
8692 int
8693 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8694     const void *optvalp, socklen_t optlen, cred_t *cr)
8695 {
8696 	conn_t		*connp = (conn_t *)proto_handle;
8697 	squeue_t	*sqp = connp->conn_sqp;
8698 	int		error;
8699 
8700 	ASSERT(connp->conn_upper_handle != NULL);
8701 	/*
8702 	 * Entering the squeue synchronously can result in a context switch,
8703 	 * which can cause a rather sever performance degradation. So we try to
8704 	 * handle whatever options we can without entering the squeue.
8705 	 */
8706 	if (level == IPPROTO_TCP) {
8707 		switch (option_name) {
8708 		case TCP_NODELAY:
8709 			if (optlen != sizeof (int32_t))
8710 				return (EINVAL);
8711 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
8712 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
8713 			    connp->conn_tcp->tcp_mss;
8714 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
8715 			return (0);
8716 		default:
8717 			break;
8718 		}
8719 	}
8720 
8721 	error = squeue_synch_enter(sqp, connp, NULL);
8722 	if (error == ENOMEM) {
8723 		return (ENOMEM);
8724 	}
8725 
8726 	error = proto_opt_check(level, option_name, optlen, NULL,
8727 	    tcp_opt_obj.odb_opt_des_arr,
8728 	    tcp_opt_obj.odb_opt_arr_cnt,
8729 	    B_TRUE, B_FALSE, cr);
8730 
8731 	if (error != 0) {
8732 		if (error < 0) {
8733 			error = proto_tlitosyserr(-error);
8734 		}
8735 		squeue_synch_exit(sqp, connp);
8736 		return (error);
8737 	}
8738 
8739 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
8740 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
8741 	    NULL, cr);
8742 	squeue_synch_exit(sqp, connp);
8743 
8744 	ASSERT(error >= 0);
8745 
8746 	return (error);
8747 }
8748 
8749 /*
8750  * Build/update the tcp header template (in conn_ht_iphc) based on
8751  * conn_xmit_ipp. The headers include ip6_t, any extension
8752  * headers, and the maximum size tcp header (to avoid reallocation
8753  * on the fly for additional tcp options).
8754  *
8755  * Assumes the caller has already set conn_{faddr,laddr,fport,lport,flowinfo}.
8756  * Returns failure if can't allocate memory.
8757  */
8758 static int
8759 tcp_build_hdrs(tcp_t *tcp)
8760 {
8761 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8762 	conn_t		*connp = tcp->tcp_connp;
8763 	char		buf[TCP_MAX_HDR_LENGTH];
8764 	uint_t		buflen;
8765 	uint_t		ulplen = TCP_MIN_HEADER_LENGTH;
8766 	uint_t		extralen = TCP_MAX_TCP_OPTIONS_LENGTH;
8767 	tcpha_t		*tcpha;
8768 	uint32_t	cksum;
8769 	int		error;
8770 
8771 	/*
8772 	 * We might be called after the connection is set up, and we might
8773 	 * have TS options already in the TCP header. Thus we  save any
8774 	 * existing tcp header.
8775 	 */
8776 	buflen = connp->conn_ht_ulp_len;
8777 	if (buflen != 0) {
8778 		bcopy(connp->conn_ht_ulp, buf, buflen);
8779 		extralen -= buflen - ulplen;
8780 		ulplen = buflen;
8781 	}
8782 
8783 	/* Grab lock to satisfy ASSERT; TCP is serialized using squeue */
8784 	mutex_enter(&connp->conn_lock);
8785 	error = conn_build_hdr_template(connp, ulplen, extralen,
8786 	    &connp->conn_laddr_v6, &connp->conn_faddr_v6, connp->conn_flowinfo);
8787 	mutex_exit(&connp->conn_lock);
8788 	if (error != 0)
8789 		return (error);
8790 
8791 	/*
8792 	 * Any routing header/option has been massaged. The checksum difference
8793 	 * is stored in conn_sum for later use.
8794 	 */
8795 	tcpha = (tcpha_t *)connp->conn_ht_ulp;
8796 	tcp->tcp_tcpha = tcpha;
8797 
8798 	/* restore any old tcp header */
8799 	if (buflen != 0) {
8800 		bcopy(buf, connp->conn_ht_ulp, buflen);
8801 	} else {
8802 		tcpha->tha_sum = 0;
8803 		tcpha->tha_offset_and_reserved = (5 << 4);
8804 		tcpha->tha_lport = connp->conn_lport;
8805 		tcpha->tha_fport = connp->conn_fport;
8806 	}
8807 
8808 	/*
8809 	 * IP wants our header length in the checksum field to
8810 	 * allow it to perform a single pseudo-header+checksum
8811 	 * calculation on behalf of TCP.
8812 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8813 	 */
8814 	cksum = sizeof (tcpha_t) + connp->conn_sum;
8815 	cksum = (cksum >> 16) + (cksum & 0xFFFF);
8816 	ASSERT(cksum < 0x10000);
8817 	tcpha->tha_sum = htons(cksum);
8818 
8819 	if (connp->conn_ipversion == IPV4_VERSION)
8820 		tcp->tcp_ipha = (ipha_t *)connp->conn_ht_iphc;
8821 	else
8822 		tcp->tcp_ip6h = (ip6_t *)connp->conn_ht_iphc;
8823 
8824 	if (connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra >
8825 	    connp->conn_wroff) {
8826 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8827 		    tcps->tcps_wroff_xtra;
8828 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8829 		    connp->conn_wroff);
8830 	}
8831 	return (0);
8832 }
8833 
8834 /* Get callback routine passed to nd_load by tcp_param_register */
8835 /* ARGSUSED */
8836 static int
8837 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
8838 {
8839 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8840 
8841 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
8842 	return (0);
8843 }
8844 
8845 /*
8846  * Walk through the param array specified registering each element with the
8847  * named dispatch handler.
8848  */
8849 static boolean_t
8850 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
8851 {
8852 	for (; cnt-- > 0; tcppa++) {
8853 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
8854 			if (!nd_load(ndp, tcppa->tcp_param_name,
8855 			    tcp_param_get, tcp_param_set,
8856 			    (caddr_t)tcppa)) {
8857 				nd_free(ndp);
8858 				return (B_FALSE);
8859 			}
8860 		}
8861 	}
8862 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
8863 	    KM_SLEEP);
8864 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
8865 	    sizeof (tcpparam_t));
8866 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
8867 	    tcp_param_get, tcp_param_set_aligned,
8868 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
8869 		nd_free(ndp);
8870 		return (B_FALSE);
8871 	}
8872 	if (!nd_load(ndp, "tcp_extra_priv_ports",
8873 	    tcp_extra_priv_ports_get, NULL, NULL)) {
8874 		nd_free(ndp);
8875 		return (B_FALSE);
8876 	}
8877 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
8878 	    NULL, tcp_extra_priv_ports_add, NULL)) {
8879 		nd_free(ndp);
8880 		return (B_FALSE);
8881 	}
8882 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
8883 	    NULL, tcp_extra_priv_ports_del, NULL)) {
8884 		nd_free(ndp);
8885 		return (B_FALSE);
8886 	}
8887 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
8888 	    tcp_1948_phrase_set, NULL)) {
8889 		nd_free(ndp);
8890 		return (B_FALSE);
8891 	}
8892 
8893 
8894 	if (!nd_load(ndp, "tcp_listener_limit_conf",
8895 	    tcp_listener_conf_get, NULL, NULL)) {
8896 		nd_free(ndp);
8897 		return (B_FALSE);
8898 	}
8899 	if (!nd_load(ndp, "tcp_listener_limit_conf_add",
8900 	    NULL, tcp_listener_conf_add, NULL)) {
8901 		nd_free(ndp);
8902 		return (B_FALSE);
8903 	}
8904 	if (!nd_load(ndp, "tcp_listener_limit_conf_del",
8905 	    NULL, tcp_listener_conf_del, NULL)) {
8906 		nd_free(ndp);
8907 		return (B_FALSE);
8908 	}
8909 
8910 	/*
8911 	 * Dummy ndd variables - only to convey obsolescence information
8912 	 * through printing of their name (no get or set routines)
8913 	 * XXX Remove in future releases ?
8914 	 */
8915 	if (!nd_load(ndp,
8916 	    "tcp_close_wait_interval(obsoleted - "
8917 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
8918 		nd_free(ndp);
8919 		return (B_FALSE);
8920 	}
8921 	return (B_TRUE);
8922 }
8923 
8924 /* ndd set routine for tcp_wroff_xtra. */
8925 /* ARGSUSED */
8926 static int
8927 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
8928     cred_t *cr)
8929 {
8930 	long new_value;
8931 	tcpparam_t *tcppa = (tcpparam_t *)cp;
8932 
8933 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8934 	    new_value < tcppa->tcp_param_min ||
8935 	    new_value > tcppa->tcp_param_max) {
8936 		return (EINVAL);
8937 	}
8938 	/*
8939 	 * Need to make sure new_value is a multiple of 4.  If it is not,
8940 	 * round it up.  For future 64 bit requirement, we actually make it
8941 	 * a multiple of 8.
8942 	 */
8943 	if (new_value & 0x7) {
8944 		new_value = (new_value & ~0x7) + 0x8;
8945 	}
8946 	tcppa->tcp_param_val = new_value;
8947 	return (0);
8948 }
8949 
8950 /* Set callback routine passed to nd_load by tcp_param_register */
8951 /* ARGSUSED */
8952 static int
8953 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
8954 {
8955 	long	new_value;
8956 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8957 
8958 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8959 	    new_value < tcppa->tcp_param_min ||
8960 	    new_value > tcppa->tcp_param_max) {
8961 		return (EINVAL);
8962 	}
8963 	tcppa->tcp_param_val = new_value;
8964 	return (0);
8965 }
8966 
8967 static void
8968 tcp_reass_timer(void *arg)
8969 {
8970 	conn_t *connp = (conn_t *)arg;
8971 	tcp_t *tcp = connp->conn_tcp;
8972 
8973 	tcp->tcp_reass_tid = 0;
8974 	if (tcp->tcp_reass_head == NULL)
8975 		return;
8976 	ASSERT(tcp->tcp_reass_tail != NULL);
8977 	tcp_sack_remove(tcp->tcp_sack_list, TCP_REASS_END(tcp->tcp_reass_tail),
8978 	    &tcp->tcp_num_sack_blk);
8979 	tcp_close_mpp(&tcp->tcp_reass_head);
8980 	tcp->tcp_reass_tail = NULL;
8981 }
8982 
8983 /*
8984  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
8985  * is filled, return as much as we can.  The message passed in may be
8986  * multi-part, chained using b_cont.  "start" is the starting sequence
8987  * number for this piece.
8988  */
8989 static mblk_t *
8990 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
8991 {
8992 	uint32_t	end;
8993 	mblk_t		*mp1;
8994 	mblk_t		*mp2;
8995 	mblk_t		*next_mp;
8996 	uint32_t	u1;
8997 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8998 
8999 
9000 	/* Walk through all the new pieces. */
9001 	do {
9002 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
9003 		    (uintptr_t)INT_MAX);
9004 		end = start + (int)(mp->b_wptr - mp->b_rptr);
9005 		next_mp = mp->b_cont;
9006 		if (start == end) {
9007 			/* Empty.  Blast it. */
9008 			freeb(mp);
9009 			continue;
9010 		}
9011 		mp->b_cont = NULL;
9012 		TCP_REASS_SET_SEQ(mp, start);
9013 		TCP_REASS_SET_END(mp, end);
9014 		mp1 = tcp->tcp_reass_tail;
9015 		if (!mp1) {
9016 			tcp->tcp_reass_tail = mp;
9017 			tcp->tcp_reass_head = mp;
9018 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9019 			UPDATE_MIB(&tcps->tcps_mib,
9020 			    tcpInDataUnorderBytes, end - start);
9021 			continue;
9022 		}
9023 		/* New stuff completely beyond tail? */
9024 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
9025 			/* Link it on end. */
9026 			mp1->b_cont = mp;
9027 			tcp->tcp_reass_tail = mp;
9028 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9029 			UPDATE_MIB(&tcps->tcps_mib,
9030 			    tcpInDataUnorderBytes, end - start);
9031 			continue;
9032 		}
9033 		mp1 = tcp->tcp_reass_head;
9034 		u1 = TCP_REASS_SEQ(mp1);
9035 		/* New stuff at the front? */
9036 		if (SEQ_LT(start, u1)) {
9037 			/* Yes... Check for overlap. */
9038 			mp->b_cont = mp1;
9039 			tcp->tcp_reass_head = mp;
9040 			tcp_reass_elim_overlap(tcp, mp);
9041 			continue;
9042 		}
9043 		/*
9044 		 * The new piece fits somewhere between the head and tail.
9045 		 * We find our slot, where mp1 precedes us and mp2 trails.
9046 		 */
9047 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
9048 			u1 = TCP_REASS_SEQ(mp2);
9049 			if (SEQ_LEQ(start, u1))
9050 				break;
9051 		}
9052 		/* Link ourselves in */
9053 		mp->b_cont = mp2;
9054 		mp1->b_cont = mp;
9055 
9056 		/* Trim overlap with following mblk(s) first */
9057 		tcp_reass_elim_overlap(tcp, mp);
9058 
9059 		/* Trim overlap with preceding mblk */
9060 		tcp_reass_elim_overlap(tcp, mp1);
9061 
9062 	} while (start = end, mp = next_mp);
9063 	mp1 = tcp->tcp_reass_head;
9064 	/* Anything ready to go? */
9065 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
9066 		return (NULL);
9067 	/* Eat what we can off the queue */
9068 	for (;;) {
9069 		mp = mp1->b_cont;
9070 		end = TCP_REASS_END(mp1);
9071 		TCP_REASS_SET_SEQ(mp1, 0);
9072 		TCP_REASS_SET_END(mp1, 0);
9073 		if (!mp) {
9074 			tcp->tcp_reass_tail = NULL;
9075 			break;
9076 		}
9077 		if (end != TCP_REASS_SEQ(mp)) {
9078 			mp1->b_cont = NULL;
9079 			break;
9080 		}
9081 		mp1 = mp;
9082 	}
9083 	mp1 = tcp->tcp_reass_head;
9084 	tcp->tcp_reass_head = mp;
9085 	return (mp1);
9086 }
9087 
9088 /* Eliminate any overlap that mp may have over later mblks */
9089 static void
9090 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
9091 {
9092 	uint32_t	end;
9093 	mblk_t		*mp1;
9094 	uint32_t	u1;
9095 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9096 
9097 	end = TCP_REASS_END(mp);
9098 	while ((mp1 = mp->b_cont) != NULL) {
9099 		u1 = TCP_REASS_SEQ(mp1);
9100 		if (!SEQ_GT(end, u1))
9101 			break;
9102 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
9103 			mp->b_wptr -= end - u1;
9104 			TCP_REASS_SET_END(mp, u1);
9105 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
9106 			UPDATE_MIB(&tcps->tcps_mib,
9107 			    tcpInDataPartDupBytes, end - u1);
9108 			break;
9109 		}
9110 		mp->b_cont = mp1->b_cont;
9111 		TCP_REASS_SET_SEQ(mp1, 0);
9112 		TCP_REASS_SET_END(mp1, 0);
9113 		freeb(mp1);
9114 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
9115 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
9116 	}
9117 	if (!mp1)
9118 		tcp->tcp_reass_tail = mp;
9119 }
9120 
9121 static uint_t
9122 tcp_rwnd_reopen(tcp_t *tcp)
9123 {
9124 	uint_t ret = 0;
9125 	uint_t thwin;
9126 	conn_t *connp = tcp->tcp_connp;
9127 
9128 	/* Learn the latest rwnd information that we sent to the other side. */
9129 	thwin = ((uint_t)ntohs(tcp->tcp_tcpha->tha_win))
9130 	    << tcp->tcp_rcv_ws;
9131 	/* This is peer's calculated send window (our receive window). */
9132 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
9133 	/*
9134 	 * Increase the receive window to max.  But we need to do receiver
9135 	 * SWS avoidance.  This means that we need to check the increase of
9136 	 * of receive window is at least 1 MSS.
9137 	 */
9138 	if (connp->conn_rcvbuf - thwin >= tcp->tcp_mss) {
9139 		/*
9140 		 * If the window that the other side knows is less than max
9141 		 * deferred acks segments, send an update immediately.
9142 		 */
9143 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
9144 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
9145 			ret = TH_ACK_NEEDED;
9146 		}
9147 		tcp->tcp_rwnd = connp->conn_rcvbuf;
9148 	}
9149 	return (ret);
9150 }
9151 
9152 /*
9153  * Send up all messages queued on tcp_rcv_list.
9154  */
9155 static uint_t
9156 tcp_rcv_drain(tcp_t *tcp)
9157 {
9158 	mblk_t *mp;
9159 	uint_t ret = 0;
9160 #ifdef DEBUG
9161 	uint_t cnt = 0;
9162 #endif
9163 	queue_t	*q = tcp->tcp_connp->conn_rq;
9164 
9165 	/* Can't drain on an eager connection */
9166 	if (tcp->tcp_listener != NULL)
9167 		return (ret);
9168 
9169 	/* Can't be a non-STREAMS connection */
9170 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
9171 
9172 	/* No need for the push timer now. */
9173 	if (tcp->tcp_push_tid != 0) {
9174 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
9175 		tcp->tcp_push_tid = 0;
9176 	}
9177 
9178 	/*
9179 	 * Handle two cases here: we are currently fused or we were
9180 	 * previously fused and have some urgent data to be delivered
9181 	 * upstream.  The latter happens because we either ran out of
9182 	 * memory or were detached and therefore sending the SIGURG was
9183 	 * deferred until this point.  In either case we pass control
9184 	 * over to tcp_fuse_rcv_drain() since it may need to complete
9185 	 * some work.
9186 	 */
9187 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
9188 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
9189 		    tcp->tcp_fused_sigurg_mp != NULL);
9190 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
9191 		    &tcp->tcp_fused_sigurg_mp))
9192 			return (ret);
9193 	}
9194 
9195 	while ((mp = tcp->tcp_rcv_list) != NULL) {
9196 		tcp->tcp_rcv_list = mp->b_next;
9197 		mp->b_next = NULL;
9198 #ifdef DEBUG
9199 		cnt += msgdsize(mp);
9200 #endif
9201 		/* Does this need SSL processing first? */
9202 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
9203 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
9204 			    mblk_t *, mp);
9205 			tcp_kssl_input(tcp, mp, NULL);
9206 			continue;
9207 		}
9208 		putnext(q, mp);
9209 	}
9210 #ifdef DEBUG
9211 	ASSERT(cnt == tcp->tcp_rcv_cnt);
9212 #endif
9213 	tcp->tcp_rcv_last_head = NULL;
9214 	tcp->tcp_rcv_last_tail = NULL;
9215 	tcp->tcp_rcv_cnt = 0;
9216 
9217 	if (canputnext(q))
9218 		return (tcp_rwnd_reopen(tcp));
9219 
9220 	return (ret);
9221 }
9222 
9223 /*
9224  * Queue data on tcp_rcv_list which is a b_next chain.
9225  * tcp_rcv_last_head/tail is the last element of this chain.
9226  * Each element of the chain is a b_cont chain.
9227  *
9228  * M_DATA messages are added to the current element.
9229  * Other messages are added as new (b_next) elements.
9230  */
9231 void
9232 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len, cred_t *cr)
9233 {
9234 	ASSERT(seg_len == msgdsize(mp));
9235 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
9236 
9237 	if (is_system_labeled()) {
9238 		ASSERT(cr != NULL || msg_getcred(mp, NULL) != NULL);
9239 		/*
9240 		 * Provide for protocols above TCP such as RPC. NOPID leaves
9241 		 * db_cpid unchanged.
9242 		 * The cred could have already been set.
9243 		 */
9244 		if (cr != NULL)
9245 			mblk_setcred(mp, cr, NOPID);
9246 	}
9247 
9248 	if (tcp->tcp_rcv_list == NULL) {
9249 		ASSERT(tcp->tcp_rcv_last_head == NULL);
9250 		tcp->tcp_rcv_list = mp;
9251 		tcp->tcp_rcv_last_head = mp;
9252 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
9253 		tcp->tcp_rcv_last_tail->b_cont = mp;
9254 	} else {
9255 		tcp->tcp_rcv_last_head->b_next = mp;
9256 		tcp->tcp_rcv_last_head = mp;
9257 	}
9258 
9259 	while (mp->b_cont)
9260 		mp = mp->b_cont;
9261 
9262 	tcp->tcp_rcv_last_tail = mp;
9263 	tcp->tcp_rcv_cnt += seg_len;
9264 	tcp->tcp_rwnd -= seg_len;
9265 }
9266 
9267 /* The minimum of smoothed mean deviation in RTO calculation. */
9268 #define	TCP_SD_MIN	400
9269 
9270 /*
9271  * Set RTO for this connection.  The formula is from Jacobson and Karels'
9272  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
9273  * are the same as those in Appendix A.2 of that paper.
9274  *
9275  * m = new measurement
9276  * sa = smoothed RTT average (8 * average estimates).
9277  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
9278  */
9279 static void
9280 tcp_set_rto(tcp_t *tcp, clock_t rtt)
9281 {
9282 	long m = TICK_TO_MSEC(rtt);
9283 	clock_t sa = tcp->tcp_rtt_sa;
9284 	clock_t sv = tcp->tcp_rtt_sd;
9285 	clock_t rto;
9286 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9287 
9288 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
9289 	tcp->tcp_rtt_update++;
9290 
9291 	/* tcp_rtt_sa is not 0 means this is a new sample. */
9292 	if (sa != 0) {
9293 		/*
9294 		 * Update average estimator:
9295 		 *	new rtt = 7/8 old rtt + 1/8 Error
9296 		 */
9297 
9298 		/* m is now Error in estimate. */
9299 		m -= sa >> 3;
9300 		if ((sa += m) <= 0) {
9301 			/*
9302 			 * Don't allow the smoothed average to be negative.
9303 			 * We use 0 to denote reinitialization of the
9304 			 * variables.
9305 			 */
9306 			sa = 1;
9307 		}
9308 
9309 		/*
9310 		 * Update deviation estimator:
9311 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
9312 		 */
9313 		if (m < 0)
9314 			m = -m;
9315 		m -= sv >> 2;
9316 		sv += m;
9317 	} else {
9318 		/*
9319 		 * This follows BSD's implementation.  So the reinitialized
9320 		 * RTO is 3 * m.  We cannot go less than 2 because if the
9321 		 * link is bandwidth dominated, doubling the window size
9322 		 * during slow start means doubling the RTT.  We want to be
9323 		 * more conservative when we reinitialize our estimates.  3
9324 		 * is just a convenient number.
9325 		 */
9326 		sa = m << 3;
9327 		sv = m << 1;
9328 	}
9329 	if (sv < TCP_SD_MIN) {
9330 		/*
9331 		 * We do not know that if sa captures the delay ACK
9332 		 * effect as in a long train of segments, a receiver
9333 		 * does not delay its ACKs.  So set the minimum of sv
9334 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
9335 		 * of BSD DATO.  That means the minimum of mean
9336 		 * deviation is 100 ms.
9337 		 *
9338 		 */
9339 		sv = TCP_SD_MIN;
9340 	}
9341 	tcp->tcp_rtt_sa = sa;
9342 	tcp->tcp_rtt_sd = sv;
9343 	/*
9344 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
9345 	 *
9346 	 * Add tcp_rexmit_interval extra in case of extreme environment
9347 	 * where the algorithm fails to work.  The default value of
9348 	 * tcp_rexmit_interval_extra should be 0.
9349 	 *
9350 	 * As we use a finer grained clock than BSD and update
9351 	 * RTO for every ACKs, add in another .25 of RTT to the
9352 	 * deviation of RTO to accomodate burstiness of 1/4 of
9353 	 * window size.
9354 	 */
9355 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
9356 
9357 	if (rto > tcps->tcps_rexmit_interval_max) {
9358 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
9359 	} else if (rto < tcps->tcps_rexmit_interval_min) {
9360 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
9361 	} else {
9362 		tcp->tcp_rto = rto;
9363 	}
9364 
9365 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
9366 	tcp->tcp_timer_backoff = 0;
9367 }
9368 
9369 /*
9370  * tcp_get_seg_mp() is called to get the pointer to a segment in the
9371  * send queue which starts at the given sequence number. If the given
9372  * sequence number is equal to last valid sequence number (tcp_snxt), the
9373  * returned mblk is the last valid mblk, and off is set to the length of
9374  * that mblk.
9375  *
9376  * send queue which starts at the given seq. no.
9377  *
9378  * Parameters:
9379  *	tcp_t *tcp: the tcp instance pointer.
9380  *	uint32_t seq: the starting seq. no of the requested segment.
9381  *	int32_t *off: after the execution, *off will be the offset to
9382  *		the returned mblk which points to the requested seq no.
9383  *		It is the caller's responsibility to send in a non-null off.
9384  *
9385  * Return:
9386  *	A mblk_t pointer pointing to the requested segment in send queue.
9387  */
9388 static mblk_t *
9389 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
9390 {
9391 	int32_t	cnt;
9392 	mblk_t	*mp;
9393 
9394 	/* Defensive coding.  Make sure we don't send incorrect data. */
9395 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
9396 		return (NULL);
9397 
9398 	cnt = seq - tcp->tcp_suna;
9399 	mp = tcp->tcp_xmit_head;
9400 	while (cnt > 0 && mp != NULL) {
9401 		cnt -= mp->b_wptr - mp->b_rptr;
9402 		if (cnt <= 0) {
9403 			cnt += mp->b_wptr - mp->b_rptr;
9404 			break;
9405 		}
9406 		mp = mp->b_cont;
9407 	}
9408 	ASSERT(mp != NULL);
9409 	*off = cnt;
9410 	return (mp);
9411 }
9412 
9413 /*
9414  * This function handles all retransmissions if SACK is enabled for this
9415  * connection.  First it calculates how many segments can be retransmitted
9416  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
9417  * segments.  A segment is eligible if sack_cnt for that segment is greater
9418  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
9419  * all eligible segments, it checks to see if TCP can send some new segments
9420  * (fast recovery).  If it can, set the appropriate flag for tcp_input_data().
9421  *
9422  * Parameters:
9423  *	tcp_t *tcp: the tcp structure of the connection.
9424  *	uint_t *flags: in return, appropriate value will be set for
9425  *	tcp_input_data().
9426  */
9427 static void
9428 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
9429 {
9430 	notsack_blk_t	*notsack_blk;
9431 	int32_t		usable_swnd;
9432 	int32_t		mss;
9433 	uint32_t	seg_len;
9434 	mblk_t		*xmit_mp;
9435 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9436 
9437 	ASSERT(tcp->tcp_sack_info != NULL);
9438 	ASSERT(tcp->tcp_notsack_list != NULL);
9439 	ASSERT(tcp->tcp_rexmit == B_FALSE);
9440 
9441 	/* Defensive coding in case there is a bug... */
9442 	if (tcp->tcp_notsack_list == NULL) {
9443 		return;
9444 	}
9445 	notsack_blk = tcp->tcp_notsack_list;
9446 	mss = tcp->tcp_mss;
9447 
9448 	/*
9449 	 * Limit the num of outstanding data in the network to be
9450 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
9451 	 */
9452 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9453 
9454 	/* At least retransmit 1 MSS of data. */
9455 	if (usable_swnd <= 0) {
9456 		usable_swnd = mss;
9457 	}
9458 
9459 	/* Make sure no new RTT samples will be taken. */
9460 	tcp->tcp_csuna = tcp->tcp_snxt;
9461 
9462 	notsack_blk = tcp->tcp_notsack_list;
9463 	while (usable_swnd > 0) {
9464 		mblk_t		*snxt_mp, *tmp_mp;
9465 		tcp_seq		begin = tcp->tcp_sack_snxt;
9466 		tcp_seq		end;
9467 		int32_t		off;
9468 
9469 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
9470 			if (SEQ_GT(notsack_blk->end, begin) &&
9471 			    (notsack_blk->sack_cnt >=
9472 			    tcps->tcps_dupack_fast_retransmit)) {
9473 				end = notsack_blk->end;
9474 				if (SEQ_LT(begin, notsack_blk->begin)) {
9475 					begin = notsack_blk->begin;
9476 				}
9477 				break;
9478 			}
9479 		}
9480 		/*
9481 		 * All holes are filled.  Manipulate tcp_cwnd to send more
9482 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
9483 		 * set to tcp_cwnd_ssthresh.
9484 		 */
9485 		if (notsack_blk == NULL) {
9486 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9487 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
9488 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
9489 				ASSERT(tcp->tcp_cwnd > 0);
9490 				return;
9491 			} else {
9492 				usable_swnd = usable_swnd / mss;
9493 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
9494 				    MAX(usable_swnd * mss, mss);
9495 				*flags |= TH_XMIT_NEEDED;
9496 				return;
9497 			}
9498 		}
9499 
9500 		/*
9501 		 * Note that we may send more than usable_swnd allows here
9502 		 * because of round off, but no more than 1 MSS of data.
9503 		 */
9504 		seg_len = end - begin;
9505 		if (seg_len > mss)
9506 			seg_len = mss;
9507 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
9508 		ASSERT(snxt_mp != NULL);
9509 		/* This should not happen.  Defensive coding again... */
9510 		if (snxt_mp == NULL) {
9511 			return;
9512 		}
9513 
9514 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
9515 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
9516 		if (xmit_mp == NULL)
9517 			return;
9518 
9519 		usable_swnd -= seg_len;
9520 		tcp->tcp_pipe += seg_len;
9521 		tcp->tcp_sack_snxt = begin + seg_len;
9522 
9523 		tcp_send_data(tcp, xmit_mp);
9524 
9525 		/*
9526 		 * Update the send timestamp to avoid false retransmission.
9527 		 */
9528 		snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9529 
9530 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9531 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
9532 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
9533 		/*
9534 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
9535 		 * This happens when new data sent during fast recovery is
9536 		 * also lost.  If TCP retransmits those new data, it needs
9537 		 * to extend SACK recover phase to avoid starting another
9538 		 * fast retransmit/recovery unnecessarily.
9539 		 */
9540 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
9541 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
9542 		}
9543 	}
9544 }
9545 
9546 /*
9547  * tcp_ss_rexmit() is called to do slow start retransmission after a timeout
9548  * or ICMP errors.
9549  *
9550  * To limit the number of duplicate segments, we limit the number of segment
9551  * to be sent in one time to tcp_snd_burst, the burst variable.
9552  */
9553 static void
9554 tcp_ss_rexmit(tcp_t *tcp)
9555 {
9556 	uint32_t	snxt;
9557 	uint32_t	smax;
9558 	int32_t		win;
9559 	int32_t		mss;
9560 	int32_t		off;
9561 	int32_t		burst = tcp->tcp_snd_burst;
9562 	mblk_t		*snxt_mp;
9563 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9564 
9565 	/*
9566 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
9567 	 * all unack'ed segments.
9568 	 */
9569 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
9570 		smax = tcp->tcp_rexmit_max;
9571 		snxt = tcp->tcp_rexmit_nxt;
9572 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
9573 			snxt = tcp->tcp_suna;
9574 		}
9575 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
9576 		win -= snxt - tcp->tcp_suna;
9577 		mss = tcp->tcp_mss;
9578 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
9579 
9580 		while (SEQ_LT(snxt, smax) && (win > 0) &&
9581 		    (burst > 0) && (snxt_mp != NULL)) {
9582 			mblk_t	*xmit_mp;
9583 			mblk_t	*old_snxt_mp = snxt_mp;
9584 			uint32_t cnt = mss;
9585 
9586 			if (win < cnt) {
9587 				cnt = win;
9588 			}
9589 			if (SEQ_GT(snxt + cnt, smax)) {
9590 				cnt = smax - snxt;
9591 			}
9592 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
9593 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
9594 			if (xmit_mp == NULL)
9595 				return;
9596 
9597 			tcp_send_data(tcp, xmit_mp);
9598 
9599 			snxt += cnt;
9600 			win -= cnt;
9601 			/*
9602 			 * Update the send timestamp to avoid false
9603 			 * retransmission.
9604 			 */
9605 			old_snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9606 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9607 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
9608 
9609 			tcp->tcp_rexmit_nxt = snxt;
9610 			burst--;
9611 		}
9612 		/*
9613 		 * If we have transmitted all we have at the time
9614 		 * we started the retranmission, we can leave
9615 		 * the rest of the job to tcp_wput_data().  But we
9616 		 * need to check the send window first.  If the
9617 		 * win is not 0, go on with tcp_wput_data().
9618 		 */
9619 		if (SEQ_LT(snxt, smax) || win == 0) {
9620 			return;
9621 		}
9622 	}
9623 	/* Only call tcp_wput_data() if there is data to be sent. */
9624 	if (tcp->tcp_unsent) {
9625 		tcp_wput_data(tcp, NULL, B_FALSE);
9626 	}
9627 }
9628 
9629 /*
9630  * Process all TCP option in SYN segment.  Note that this function should
9631  * be called after tcp_set_destination() is called so that the necessary info
9632  * from IRE is already set in the tcp structure.
9633  *
9634  * This function sets up the correct tcp_mss value according to the
9635  * MSS option value and our header size.  It also sets up the window scale
9636  * and timestamp values, and initialize SACK info blocks.  But it does not
9637  * change receive window size after setting the tcp_mss value.  The caller
9638  * should do the appropriate change.
9639  */
9640 void
9641 tcp_process_options(tcp_t *tcp, tcpha_t *tcpha)
9642 {
9643 	int options;
9644 	tcp_opt_t tcpopt;
9645 	uint32_t mss_max;
9646 	char *tmp_tcph;
9647 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9648 	conn_t		*connp = tcp->tcp_connp;
9649 
9650 	tcpopt.tcp = NULL;
9651 	options = tcp_parse_options(tcpha, &tcpopt);
9652 
9653 	/*
9654 	 * Process MSS option.  Note that MSS option value does not account
9655 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
9656 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
9657 	 * IPv6.
9658 	 */
9659 	if (!(options & TCP_OPT_MSS_PRESENT)) {
9660 		if (connp->conn_ipversion == IPV4_VERSION)
9661 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
9662 		else
9663 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
9664 	} else {
9665 		if (connp->conn_ipversion == IPV4_VERSION)
9666 			mss_max = tcps->tcps_mss_max_ipv4;
9667 		else
9668 			mss_max = tcps->tcps_mss_max_ipv6;
9669 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
9670 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
9671 		else if (tcpopt.tcp_opt_mss > mss_max)
9672 			tcpopt.tcp_opt_mss = mss_max;
9673 	}
9674 
9675 	/* Process Window Scale option. */
9676 	if (options & TCP_OPT_WSCALE_PRESENT) {
9677 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
9678 		tcp->tcp_snd_ws_ok = B_TRUE;
9679 	} else {
9680 		tcp->tcp_snd_ws = B_FALSE;
9681 		tcp->tcp_snd_ws_ok = B_FALSE;
9682 		tcp->tcp_rcv_ws = B_FALSE;
9683 	}
9684 
9685 	/* Process Timestamp option. */
9686 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
9687 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
9688 		tmp_tcph = (char *)tcp->tcp_tcpha;
9689 
9690 		tcp->tcp_snd_ts_ok = B_TRUE;
9691 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
9692 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
9693 		ASSERT(OK_32PTR(tmp_tcph));
9694 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
9695 
9696 		/* Fill in our template header with basic timestamp option. */
9697 		tmp_tcph += connp->conn_ht_ulp_len;
9698 		tmp_tcph[0] = TCPOPT_NOP;
9699 		tmp_tcph[1] = TCPOPT_NOP;
9700 		tmp_tcph[2] = TCPOPT_TSTAMP;
9701 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
9702 		connp->conn_ht_iphc_len += TCPOPT_REAL_TS_LEN;
9703 		connp->conn_ht_ulp_len += TCPOPT_REAL_TS_LEN;
9704 		tcp->tcp_tcpha->tha_offset_and_reserved += (3 << 4);
9705 	} else {
9706 		tcp->tcp_snd_ts_ok = B_FALSE;
9707 	}
9708 
9709 	/*
9710 	 * Process SACK options.  If SACK is enabled for this connection,
9711 	 * then allocate the SACK info structure.  Note the following ways
9712 	 * when tcp_snd_sack_ok is set to true.
9713 	 *
9714 	 * For active connection: in tcp_set_destination() called in
9715 	 * tcp_connect().
9716 	 *
9717 	 * For passive connection: in tcp_set_destination() called in
9718 	 * tcp_input_listener().
9719 	 *
9720 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
9721 	 * That check makes sure that if we did not send a SACK OK option,
9722 	 * we will not enable SACK for this connection even though the other
9723 	 * side sends us SACK OK option.  For active connection, the SACK
9724 	 * info structure has already been allocated.  So we need to free
9725 	 * it if SACK is disabled.
9726 	 */
9727 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
9728 	    (tcp->tcp_snd_sack_ok ||
9729 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
9730 		/* This should be true only in the passive case. */
9731 		if (tcp->tcp_sack_info == NULL) {
9732 			ASSERT(TCP_IS_DETACHED(tcp));
9733 			tcp->tcp_sack_info =
9734 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
9735 		}
9736 		if (tcp->tcp_sack_info == NULL) {
9737 			tcp->tcp_snd_sack_ok = B_FALSE;
9738 		} else {
9739 			tcp->tcp_snd_sack_ok = B_TRUE;
9740 			if (tcp->tcp_snd_ts_ok) {
9741 				tcp->tcp_max_sack_blk = 3;
9742 			} else {
9743 				tcp->tcp_max_sack_blk = 4;
9744 			}
9745 		}
9746 	} else {
9747 		/*
9748 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
9749 		 * no SACK info will be used for this
9750 		 * connection.  This assumes that SACK usage
9751 		 * permission is negotiated.  This may need
9752 		 * to be changed once this is clarified.
9753 		 */
9754 		if (tcp->tcp_sack_info != NULL) {
9755 			ASSERT(tcp->tcp_notsack_list == NULL);
9756 			kmem_cache_free(tcp_sack_info_cache,
9757 			    tcp->tcp_sack_info);
9758 			tcp->tcp_sack_info = NULL;
9759 		}
9760 		tcp->tcp_snd_sack_ok = B_FALSE;
9761 	}
9762 
9763 	/*
9764 	 * Now we know the exact TCP/IP header length, subtract
9765 	 * that from tcp_mss to get our side's MSS.
9766 	 */
9767 	tcp->tcp_mss -= connp->conn_ht_iphc_len;
9768 
9769 	/*
9770 	 * Here we assume that the other side's header size will be equal to
9771 	 * our header size.  We calculate the real MSS accordingly.  Need to
9772 	 * take into additional stuffs IPsec puts in.
9773 	 *
9774 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
9775 	 */
9776 	tcpopt.tcp_opt_mss -= connp->conn_ht_iphc_len +
9777 	    tcp->tcp_ipsec_overhead -
9778 	    ((connp->conn_ipversion == IPV4_VERSION ?
9779 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
9780 
9781 	/*
9782 	 * Set MSS to the smaller one of both ends of the connection.
9783 	 * We should not have called tcp_mss_set() before, but our
9784 	 * side of the MSS should have been set to a proper value
9785 	 * by tcp_set_destination().  tcp_mss_set() will also set up the
9786 	 * STREAM head parameters properly.
9787 	 *
9788 	 * If we have a larger-than-16-bit window but the other side
9789 	 * didn't want to do window scale, tcp_rwnd_set() will take
9790 	 * care of that.
9791 	 */
9792 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
9793 
9794 	/*
9795 	 * Initialize tcp_cwnd value. After tcp_mss_set(), tcp_mss has been
9796 	 * updated properly.
9797 	 */
9798 	SET_TCP_INIT_CWND(tcp, tcp->tcp_mss, tcps->tcps_slow_start_initial);
9799 }
9800 
9801 /*
9802  * Sends the T_CONN_IND to the listener. The caller calls this
9803  * functions via squeue to get inside the listener's perimeter
9804  * once the 3 way hand shake is done a T_CONN_IND needs to be
9805  * sent. As an optimization, the caller can call this directly
9806  * if listener's perimeter is same as eager's.
9807  */
9808 /* ARGSUSED */
9809 void
9810 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
9811 {
9812 	conn_t			*lconnp = (conn_t *)arg;
9813 	tcp_t			*listener = lconnp->conn_tcp;
9814 	tcp_t			*tcp;
9815 	struct T_conn_ind	*conn_ind;
9816 	ipaddr_t 		*addr_cache;
9817 	boolean_t		need_send_conn_ind = B_FALSE;
9818 	tcp_stack_t		*tcps = listener->tcp_tcps;
9819 
9820 	/* retrieve the eager */
9821 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
9822 	ASSERT(conn_ind->OPT_offset != 0 &&
9823 	    conn_ind->OPT_length == sizeof (intptr_t));
9824 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
9825 	    conn_ind->OPT_length);
9826 
9827 	/*
9828 	 * TLI/XTI applications will get confused by
9829 	 * sending eager as an option since it violates
9830 	 * the option semantics. So remove the eager as
9831 	 * option since TLI/XTI app doesn't need it anyway.
9832 	 */
9833 	if (!TCP_IS_SOCKET(listener)) {
9834 		conn_ind->OPT_length = 0;
9835 		conn_ind->OPT_offset = 0;
9836 	}
9837 	if (listener->tcp_state != TCPS_LISTEN) {
9838 		/*
9839 		 * If listener has closed, it would have caused a
9840 		 * a cleanup/blowoff to happen for the eager. We
9841 		 * just need to return.
9842 		 */
9843 		freemsg(mp);
9844 		return;
9845 	}
9846 
9847 
9848 	/*
9849 	 * if the conn_req_q is full defer passing up the
9850 	 * T_CONN_IND until space is availabe after t_accept()
9851 	 * processing
9852 	 */
9853 	mutex_enter(&listener->tcp_eager_lock);
9854 
9855 	/*
9856 	 * Take the eager out, if it is in the list of droppable eagers
9857 	 * as we are here because the 3W handshake is over.
9858 	 */
9859 	MAKE_UNDROPPABLE(tcp);
9860 
9861 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
9862 		tcp_t *tail;
9863 
9864 		/*
9865 		 * The eager already has an extra ref put in tcp_input_data
9866 		 * so that it stays till accept comes back even though it
9867 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
9868 		 */
9869 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
9870 		listener->tcp_conn_req_cnt_q0--;
9871 		listener->tcp_conn_req_cnt_q++;
9872 
9873 		/* Move from SYN_RCVD to ESTABLISHED list  */
9874 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9875 		    tcp->tcp_eager_prev_q0;
9876 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9877 		    tcp->tcp_eager_next_q0;
9878 		tcp->tcp_eager_prev_q0 = NULL;
9879 		tcp->tcp_eager_next_q0 = NULL;
9880 
9881 		/*
9882 		 * Insert at end of the queue because sockfs
9883 		 * sends down T_CONN_RES in chronological
9884 		 * order. Leaving the older conn indications
9885 		 * at front of the queue helps reducing search
9886 		 * time.
9887 		 */
9888 		tail = listener->tcp_eager_last_q;
9889 		if (tail != NULL)
9890 			tail->tcp_eager_next_q = tcp;
9891 		else
9892 			listener->tcp_eager_next_q = tcp;
9893 		listener->tcp_eager_last_q = tcp;
9894 		tcp->tcp_eager_next_q = NULL;
9895 		/*
9896 		 * Delay sending up the T_conn_ind until we are
9897 		 * done with the eager. Once we have have sent up
9898 		 * the T_conn_ind, the accept can potentially complete
9899 		 * any time and release the refhold we have on the eager.
9900 		 */
9901 		need_send_conn_ind = B_TRUE;
9902 	} else {
9903 		/*
9904 		 * Defer connection on q0 and set deferred
9905 		 * connection bit true
9906 		 */
9907 		tcp->tcp_conn_def_q0 = B_TRUE;
9908 
9909 		/* take tcp out of q0 ... */
9910 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9911 		    tcp->tcp_eager_next_q0;
9912 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9913 		    tcp->tcp_eager_prev_q0;
9914 
9915 		/* ... and place it at the end of q0 */
9916 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
9917 		tcp->tcp_eager_next_q0 = listener;
9918 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
9919 		listener->tcp_eager_prev_q0 = tcp;
9920 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
9921 	}
9922 
9923 	/* we have timed out before */
9924 	if (tcp->tcp_syn_rcvd_timeout != 0) {
9925 		tcp->tcp_syn_rcvd_timeout = 0;
9926 		listener->tcp_syn_rcvd_timeout--;
9927 		if (listener->tcp_syn_defense &&
9928 		    listener->tcp_syn_rcvd_timeout <=
9929 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
9930 		    10*MINUTES < TICK_TO_MSEC(ddi_get_lbolt64() -
9931 		    listener->tcp_last_rcv_lbolt)) {
9932 			/*
9933 			 * Turn off the defense mode if we
9934 			 * believe the SYN attack is over.
9935 			 */
9936 			listener->tcp_syn_defense = B_FALSE;
9937 			if (listener->tcp_ip_addr_cache) {
9938 				kmem_free((void *)listener->tcp_ip_addr_cache,
9939 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
9940 				listener->tcp_ip_addr_cache = NULL;
9941 			}
9942 		}
9943 	}
9944 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
9945 	if (addr_cache != NULL) {
9946 		/*
9947 		 * We have finished a 3-way handshake with this
9948 		 * remote host. This proves the IP addr is good.
9949 		 * Cache it!
9950 		 */
9951 		addr_cache[IP_ADDR_CACHE_HASH(tcp->tcp_connp->conn_faddr_v4)] =
9952 		    tcp->tcp_connp->conn_faddr_v4;
9953 	}
9954 	mutex_exit(&listener->tcp_eager_lock);
9955 	if (need_send_conn_ind)
9956 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
9957 }
9958 
9959 /*
9960  * Send the newconn notification to ulp. The eager is blown off if the
9961  * notification fails.
9962  */
9963 static void
9964 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
9965 {
9966 	if (IPCL_IS_NONSTR(lconnp)) {
9967 		cred_t	*cr;
9968 		pid_t	cpid = NOPID;
9969 
9970 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
9971 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
9972 		    lconnp->conn_tcp);
9973 
9974 		cr = msg_getcred(mp, &cpid);
9975 
9976 		/* Keep the message around in case of a fallback to TPI */
9977 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
9978 		/*
9979 		 * Notify the ULP about the newconn. It is guaranteed that no
9980 		 * tcp_accept() call will be made for the eager if the
9981 		 * notification fails, so it's safe to blow it off in that
9982 		 * case.
9983 		 *
9984 		 * The upper handle will be assigned when tcp_accept() is
9985 		 * called.
9986 		 */
9987 		if ((*lconnp->conn_upcalls->su_newconn)
9988 		    (lconnp->conn_upper_handle,
9989 		    (sock_lower_handle_t)econnp,
9990 		    &sock_tcp_downcalls, cr, cpid,
9991 		    &econnp->conn_upcalls) == NULL) {
9992 			/* Failed to allocate a socket */
9993 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
9994 			    tcpEstabResets);
9995 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
9996 			    econnp->conn_tcp->tcp_conn_req_seqnum);
9997 		}
9998 	} else {
9999 		putnext(lconnp->conn_rq, mp);
10000 	}
10001 }
10002 
10003 /*
10004  * Handle a packet that has been reclassified by TCP.
10005  * This function drops the ref on connp that the caller had.
10006  */
10007 static void
10008 tcp_reinput(conn_t *connp, mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst)
10009 {
10010 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
10011 
10012 	if (connp->conn_incoming_ifindex != 0 &&
10013 	    connp->conn_incoming_ifindex != ira->ira_ruifindex) {
10014 		freemsg(mp);
10015 		CONN_DEC_REF(connp);
10016 		return;
10017 	}
10018 
10019 	if (CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss) ||
10020 	    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
10021 		ip6_t *ip6h;
10022 		ipha_t *ipha;
10023 
10024 		if (ira->ira_flags & IRAF_IS_IPV4) {
10025 			ipha = (ipha_t *)mp->b_rptr;
10026 			ip6h = NULL;
10027 		} else {
10028 			ipha = NULL;
10029 			ip6h = (ip6_t *)mp->b_rptr;
10030 		}
10031 		mp = ipsec_check_inbound_policy(mp, connp, ipha, ip6h, ira);
10032 		if (mp == NULL) {
10033 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
10034 			/* Note that mp is NULL */
10035 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
10036 			CONN_DEC_REF(connp);
10037 			return;
10038 		}
10039 	}
10040 
10041 	if (IPCL_IS_TCP(connp)) {
10042 		/*
10043 		 * do not drain, certain use cases can blow
10044 		 * the stack
10045 		 */
10046 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10047 		    connp->conn_recv, connp, ira,
10048 		    SQ_NODRAIN, SQTAG_IP_TCP_INPUT);
10049 	} else {
10050 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
10051 		(connp->conn_recv)(connp, mp, NULL,
10052 		    ira);
10053 		CONN_DEC_REF(connp);
10054 	}
10055 
10056 }
10057 
10058 boolean_t tcp_outbound_squeue_switch = B_FALSE;
10059 
10060 /*
10061  * Handle M_DATA messages from IP. Its called directly from IP via
10062  * squeue for received IP packets.
10063  *
10064  * The first argument is always the connp/tcp to which the mp belongs.
10065  * There are no exceptions to this rule. The caller has already put
10066  * a reference on this connp/tcp and once tcp_input_data() returns,
10067  * the squeue will do the refrele.
10068  *
10069  * The TH_SYN for the listener directly go to tcp_input_listener via
10070  * squeue. ICMP errors go directly to tcp_icmp_input().
10071  *
10072  * sqp: NULL = recursive, sqp != NULL means called from squeue
10073  */
10074 void
10075 tcp_input_data(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
10076 {
10077 	int32_t		bytes_acked;
10078 	int32_t		gap;
10079 	mblk_t		*mp1;
10080 	uint_t		flags;
10081 	uint32_t	new_swnd = 0;
10082 	uchar_t		*iphdr;
10083 	uchar_t		*rptr;
10084 	int32_t		rgap;
10085 	uint32_t	seg_ack;
10086 	int		seg_len;
10087 	uint_t		ip_hdr_len;
10088 	uint32_t	seg_seq;
10089 	tcpha_t		*tcpha;
10090 	int		urp;
10091 	tcp_opt_t	tcpopt;
10092 	ip_pkt_t	ipp;
10093 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
10094 	uint32_t	cwnd;
10095 	uint32_t	add;
10096 	int		npkt;
10097 	int		mss;
10098 	conn_t		*connp = (conn_t *)arg;
10099 	squeue_t	*sqp = (squeue_t *)arg2;
10100 	tcp_t		*tcp = connp->conn_tcp;
10101 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10102 
10103 	/*
10104 	 * RST from fused tcp loopback peer should trigger an unfuse.
10105 	 */
10106 	if (tcp->tcp_fused) {
10107 		TCP_STAT(tcps, tcp_fusion_aborted);
10108 		tcp_unfuse(tcp);
10109 	}
10110 
10111 	iphdr = mp->b_rptr;
10112 	rptr = mp->b_rptr;
10113 	ASSERT(OK_32PTR(rptr));
10114 
10115 	ip_hdr_len = ira->ira_ip_hdr_length;
10116 	if (connp->conn_recv_ancillary.crb_all != 0) {
10117 		/*
10118 		 * Record packet information in the ip_pkt_t
10119 		 */
10120 		ipp.ipp_fields = 0;
10121 		if (ira->ira_flags & IRAF_IS_IPV4) {
10122 			(void) ip_find_hdr_v4((ipha_t *)rptr, &ipp,
10123 			    B_FALSE);
10124 		} else {
10125 			uint8_t nexthdrp;
10126 
10127 			/*
10128 			 * IPv6 packets can only be received by applications
10129 			 * that are prepared to receive IPv6 addresses.
10130 			 * The IP fanout must ensure this.
10131 			 */
10132 			ASSERT(connp->conn_family == AF_INET6);
10133 
10134 			(void) ip_find_hdr_v6(mp, (ip6_t *)rptr, B_TRUE, &ipp,
10135 			    &nexthdrp);
10136 			ASSERT(nexthdrp == IPPROTO_TCP);
10137 
10138 			/* Could have caused a pullup? */
10139 			iphdr = mp->b_rptr;
10140 			rptr = mp->b_rptr;
10141 		}
10142 	}
10143 	ASSERT(DB_TYPE(mp) == M_DATA);
10144 	ASSERT(mp->b_next == NULL);
10145 
10146 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10147 	seg_seq = ntohl(tcpha->tha_seq);
10148 	seg_ack = ntohl(tcpha->tha_ack);
10149 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
10150 	seg_len = (int)(mp->b_wptr - rptr) -
10151 	    (ip_hdr_len + TCP_HDR_LENGTH(tcpha));
10152 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
10153 		do {
10154 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
10155 			    (uintptr_t)INT_MAX);
10156 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
10157 		} while ((mp1 = mp1->b_cont) != NULL &&
10158 		    mp1->b_datap->db_type == M_DATA);
10159 	}
10160 
10161 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
10162 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
10163 		    seg_len, tcpha, ira);
10164 		return;
10165 	}
10166 
10167 	if (sqp != NULL) {
10168 		/*
10169 		 * This is the correct place to update tcp_last_recv_time. Note
10170 		 * that it is also updated for tcp structure that belongs to
10171 		 * global and listener queues which do not really need updating.
10172 		 * But that should not cause any harm.  And it is updated for
10173 		 * all kinds of incoming segments, not only for data segments.
10174 		 */
10175 		tcp->tcp_last_recv_time = LBOLT_FASTPATH;
10176 	}
10177 
10178 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
10179 
10180 	BUMP_LOCAL(tcp->tcp_ibsegs);
10181 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10182 
10183 	if ((flags & TH_URG) && sqp != NULL) {
10184 		/*
10185 		 * TCP can't handle urgent pointers that arrive before
10186 		 * the connection has been accept()ed since it can't
10187 		 * buffer OOB data.  Discard segment if this happens.
10188 		 *
10189 		 * We can't just rely on a non-null tcp_listener to indicate
10190 		 * that the accept() has completed since unlinking of the
10191 		 * eager and completion of the accept are not atomic.
10192 		 * tcp_detached, when it is not set (B_FALSE) indicates
10193 		 * that the accept() has completed.
10194 		 *
10195 		 * Nor can it reassemble urgent pointers, so discard
10196 		 * if it's not the next segment expected.
10197 		 *
10198 		 * Otherwise, collapse chain into one mblk (discard if
10199 		 * that fails).  This makes sure the headers, retransmitted
10200 		 * data, and new data all are in the same mblk.
10201 		 */
10202 		ASSERT(mp != NULL);
10203 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
10204 			freemsg(mp);
10205 			return;
10206 		}
10207 		/* Update pointers into message */
10208 		iphdr = rptr = mp->b_rptr;
10209 		tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10210 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
10211 			/*
10212 			 * Since we can't handle any data with this urgent
10213 			 * pointer that is out of sequence, we expunge
10214 			 * the data.  This allows us to still register
10215 			 * the urgent mark and generate the M_PCSIG,
10216 			 * which we can do.
10217 			 */
10218 			mp->b_wptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10219 			seg_len = 0;
10220 		}
10221 	}
10222 
10223 	switch (tcp->tcp_state) {
10224 	case TCPS_SYN_SENT:
10225 		if (connp->conn_final_sqp == NULL &&
10226 		    tcp_outbound_squeue_switch && sqp != NULL) {
10227 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
10228 			connp->conn_final_sqp = sqp;
10229 			if (connp->conn_final_sqp != connp->conn_sqp) {
10230 				DTRACE_PROBE1(conn__final__sqp__switch,
10231 				    conn_t *, connp);
10232 				CONN_INC_REF(connp);
10233 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
10234 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10235 				    tcp_input_data, connp, ira, ip_squeue_flag,
10236 				    SQTAG_CONNECT_FINISH);
10237 				return;
10238 			}
10239 			DTRACE_PROBE1(conn__final__sqp__same, conn_t *, connp);
10240 		}
10241 		if (flags & TH_ACK) {
10242 			/*
10243 			 * Note that our stack cannot send data before a
10244 			 * connection is established, therefore the
10245 			 * following check is valid.  Otherwise, it has
10246 			 * to be changed.
10247 			 */
10248 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
10249 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10250 				freemsg(mp);
10251 				if (flags & TH_RST)
10252 					return;
10253 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
10254 				    tcp, seg_ack, 0, TH_RST);
10255 				return;
10256 			}
10257 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
10258 		}
10259 		if (flags & TH_RST) {
10260 			freemsg(mp);
10261 			if (flags & TH_ACK)
10262 				(void) tcp_clean_death(tcp,
10263 				    ECONNREFUSED, 13);
10264 			return;
10265 		}
10266 		if (!(flags & TH_SYN)) {
10267 			freemsg(mp);
10268 			return;
10269 		}
10270 
10271 		/* Process all TCP options. */
10272 		tcp_process_options(tcp, tcpha);
10273 		/*
10274 		 * The following changes our rwnd to be a multiple of the
10275 		 * MIN(peer MSS, our MSS) for performance reason.
10276 		 */
10277 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(connp->conn_rcvbuf,
10278 		    tcp->tcp_mss));
10279 
10280 		/* Is the other end ECN capable? */
10281 		if (tcp->tcp_ecn_ok) {
10282 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
10283 				tcp->tcp_ecn_ok = B_FALSE;
10284 			}
10285 		}
10286 		/*
10287 		 * Clear ECN flags because it may interfere with later
10288 		 * processing.
10289 		 */
10290 		flags &= ~(TH_ECE|TH_CWR);
10291 
10292 		tcp->tcp_irs = seg_seq;
10293 		tcp->tcp_rack = seg_seq;
10294 		tcp->tcp_rnxt = seg_seq + 1;
10295 		tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10296 		if (!TCP_IS_DETACHED(tcp)) {
10297 			/* Allocate room for SACK options if needed. */
10298 			connp->conn_wroff = connp->conn_ht_iphc_len;
10299 			if (tcp->tcp_snd_sack_ok)
10300 				connp->conn_wroff += TCPOPT_MAX_SACK_LEN;
10301 			if (!tcp->tcp_loopback)
10302 				connp->conn_wroff += tcps->tcps_wroff_xtra;
10303 
10304 			(void) proto_set_tx_wroff(connp->conn_rq, connp,
10305 			    connp->conn_wroff);
10306 		}
10307 		if (flags & TH_ACK) {
10308 			/*
10309 			 * If we can't get the confirmation upstream, pretend
10310 			 * we didn't even see this one.
10311 			 *
10312 			 * XXX: how can we pretend we didn't see it if we
10313 			 * have updated rnxt et. al.
10314 			 *
10315 			 * For loopback we defer sending up the T_CONN_CON
10316 			 * until after some checks below.
10317 			 */
10318 			mp1 = NULL;
10319 			/*
10320 			 * tcp_sendmsg() checks tcp_state without entering
10321 			 * the squeue so tcp_state should be updated before
10322 			 * sending up connection confirmation
10323 			 */
10324 			tcp->tcp_state = TCPS_ESTABLISHED;
10325 			if (!tcp_conn_con(tcp, iphdr, mp,
10326 			    tcp->tcp_loopback ? &mp1 : NULL, ira)) {
10327 				tcp->tcp_state = TCPS_SYN_SENT;
10328 				freemsg(mp);
10329 				return;
10330 			}
10331 			/* SYN was acked - making progress */
10332 			tcp->tcp_ip_forward_progress = B_TRUE;
10333 
10334 			/* One for the SYN */
10335 			tcp->tcp_suna = tcp->tcp_iss + 1;
10336 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
10337 
10338 			/*
10339 			 * If SYN was retransmitted, need to reset all
10340 			 * retransmission info.  This is because this
10341 			 * segment will be treated as a dup ACK.
10342 			 */
10343 			if (tcp->tcp_rexmit) {
10344 				tcp->tcp_rexmit = B_FALSE;
10345 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
10346 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
10347 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
10348 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
10349 				tcp->tcp_ms_we_have_waited = 0;
10350 
10351 				/*
10352 				 * Set tcp_cwnd back to 1 MSS, per
10353 				 * recommendation from
10354 				 * draft-floyd-incr-init-win-01.txt,
10355 				 * Increasing TCP's Initial Window.
10356 				 */
10357 				tcp->tcp_cwnd = tcp->tcp_mss;
10358 			}
10359 
10360 			tcp->tcp_swl1 = seg_seq;
10361 			tcp->tcp_swl2 = seg_ack;
10362 
10363 			new_swnd = ntohs(tcpha->tha_win);
10364 			tcp->tcp_swnd = new_swnd;
10365 			if (new_swnd > tcp->tcp_max_swnd)
10366 				tcp->tcp_max_swnd = new_swnd;
10367 
10368 			/*
10369 			 * Always send the three-way handshake ack immediately
10370 			 * in order to make the connection complete as soon as
10371 			 * possible on the accepting host.
10372 			 */
10373 			flags |= TH_ACK_NEEDED;
10374 
10375 			/*
10376 			 * Special case for loopback.  At this point we have
10377 			 * received SYN-ACK from the remote endpoint.  In
10378 			 * order to ensure that both endpoints reach the
10379 			 * fused state prior to any data exchange, the final
10380 			 * ACK needs to be sent before we indicate T_CONN_CON
10381 			 * to the module upstream.
10382 			 */
10383 			if (tcp->tcp_loopback) {
10384 				mblk_t *ack_mp;
10385 
10386 				ASSERT(!tcp->tcp_unfusable);
10387 				ASSERT(mp1 != NULL);
10388 				/*
10389 				 * For loopback, we always get a pure SYN-ACK
10390 				 * and only need to send back the final ACK
10391 				 * with no data (this is because the other
10392 				 * tcp is ours and we don't do T/TCP).  This
10393 				 * final ACK triggers the passive side to
10394 				 * perform fusion in ESTABLISHED state.
10395 				 */
10396 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
10397 					if (tcp->tcp_ack_tid != 0) {
10398 						(void) TCP_TIMER_CANCEL(tcp,
10399 						    tcp->tcp_ack_tid);
10400 						tcp->tcp_ack_tid = 0;
10401 					}
10402 					tcp_send_data(tcp, ack_mp);
10403 					BUMP_LOCAL(tcp->tcp_obsegs);
10404 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
10405 
10406 					if (!IPCL_IS_NONSTR(connp)) {
10407 						/* Send up T_CONN_CON */
10408 						if (ira->ira_cred != NULL) {
10409 							mblk_setcred(mp1,
10410 							    ira->ira_cred,
10411 							    ira->ira_cpid);
10412 						}
10413 						putnext(connp->conn_rq, mp1);
10414 					} else {
10415 						(*connp->conn_upcalls->
10416 						    su_connected)
10417 						    (connp->conn_upper_handle,
10418 						    tcp->tcp_connid,
10419 						    ira->ira_cred,
10420 						    ira->ira_cpid);
10421 						freemsg(mp1);
10422 					}
10423 
10424 					freemsg(mp);
10425 					return;
10426 				}
10427 				/*
10428 				 * Forget fusion; we need to handle more
10429 				 * complex cases below.  Send the deferred
10430 				 * T_CONN_CON message upstream and proceed
10431 				 * as usual.  Mark this tcp as not capable
10432 				 * of fusion.
10433 				 */
10434 				TCP_STAT(tcps, tcp_fusion_unfusable);
10435 				tcp->tcp_unfusable = B_TRUE;
10436 				if (!IPCL_IS_NONSTR(connp)) {
10437 					if (ira->ira_cred != NULL) {
10438 						mblk_setcred(mp1, ira->ira_cred,
10439 						    ira->ira_cpid);
10440 					}
10441 					putnext(connp->conn_rq, mp1);
10442 				} else {
10443 					(*connp->conn_upcalls->su_connected)
10444 					    (connp->conn_upper_handle,
10445 					    tcp->tcp_connid, ira->ira_cred,
10446 					    ira->ira_cpid);
10447 					freemsg(mp1);
10448 				}
10449 			}
10450 
10451 			/*
10452 			 * Check to see if there is data to be sent.  If
10453 			 * yes, set the transmit flag.  Then check to see
10454 			 * if received data processing needs to be done.
10455 			 * If not, go straight to xmit_check.  This short
10456 			 * cut is OK as we don't support T/TCP.
10457 			 */
10458 			if (tcp->tcp_unsent)
10459 				flags |= TH_XMIT_NEEDED;
10460 
10461 			if (seg_len == 0 && !(flags & TH_URG)) {
10462 				freemsg(mp);
10463 				goto xmit_check;
10464 			}
10465 
10466 			flags &= ~TH_SYN;
10467 			seg_seq++;
10468 			break;
10469 		}
10470 		tcp->tcp_state = TCPS_SYN_RCVD;
10471 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
10472 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
10473 		if (mp1 != NULL) {
10474 			tcp_send_data(tcp, mp1);
10475 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
10476 		}
10477 		freemsg(mp);
10478 		return;
10479 	case TCPS_SYN_RCVD:
10480 		if (flags & TH_ACK) {
10481 			/*
10482 			 * In this state, a SYN|ACK packet is either bogus
10483 			 * because the other side must be ACKing our SYN which
10484 			 * indicates it has seen the ACK for their SYN and
10485 			 * shouldn't retransmit it or we're crossing SYNs
10486 			 * on active open.
10487 			 */
10488 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
10489 				freemsg(mp);
10490 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
10491 				    tcp, seg_ack, 0, TH_RST);
10492 				return;
10493 			}
10494 			/*
10495 			 * NOTE: RFC 793 pg. 72 says this should be
10496 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
10497 			 * but that would mean we have an ack that ignored
10498 			 * our SYN.
10499 			 */
10500 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
10501 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10502 				freemsg(mp);
10503 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
10504 				    tcp, seg_ack, 0, TH_RST);
10505 				return;
10506 			}
10507 			/*
10508 			 * No sane TCP stack will send such a small window
10509 			 * without receiving any data.  Just drop this invalid
10510 			 * ACK.  We also shorten the abort timeout in case
10511 			 * this is an attack.
10512 			 */
10513 			if ((ntohs(tcpha->tha_win) << tcp->tcp_snd_ws) <
10514 			    (tcp->tcp_mss >> tcp_init_wnd_shft)) {
10515 				freemsg(mp);
10516 				TCP_STAT(tcps, tcp_zwin_ack_syn);
10517 				tcp->tcp_second_ctimer_threshold =
10518 				    tcp_early_abort * SECONDS;
10519 				return;
10520 			}
10521 		}
10522 		break;
10523 	case TCPS_LISTEN:
10524 		/*
10525 		 * Only a TLI listener can come through this path when a
10526 		 * acceptor is going back to be a listener and a packet
10527 		 * for the acceptor hits the classifier. For a socket
10528 		 * listener, this can never happen because a listener
10529 		 * can never accept connection on itself and hence a
10530 		 * socket acceptor can not go back to being a listener.
10531 		 */
10532 		ASSERT(!TCP_IS_SOCKET(tcp));
10533 		/*FALLTHRU*/
10534 	case TCPS_CLOSED:
10535 	case TCPS_BOUND: {
10536 		conn_t	*new_connp;
10537 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
10538 
10539 		/*
10540 		 * Don't accept any input on a closed tcp as this TCP logically
10541 		 * does not exist on the system. Don't proceed further with
10542 		 * this TCP. For instance, this packet could trigger another
10543 		 * close of this tcp which would be disastrous for tcp_refcnt.
10544 		 * tcp_close_detached / tcp_clean_death / tcp_closei_local must
10545 		 * be called at most once on a TCP. In this case we need to
10546 		 * refeed the packet into the classifier and figure out where
10547 		 * the packet should go.
10548 		 */
10549 		new_connp = ipcl_classify(mp, ira, ipst);
10550 		if (new_connp != NULL) {
10551 			/* Drops ref on new_connp */
10552 			tcp_reinput(new_connp, mp, ira, ipst);
10553 			return;
10554 		}
10555 		/* We failed to classify. For now just drop the packet */
10556 		freemsg(mp);
10557 		return;
10558 	}
10559 	case TCPS_IDLE:
10560 		/*
10561 		 * Handle the case where the tcp_clean_death() has happened
10562 		 * on a connection (application hasn't closed yet) but a packet
10563 		 * was already queued on squeue before tcp_clean_death()
10564 		 * was processed. Calling tcp_clean_death() twice on same
10565 		 * connection can result in weird behaviour.
10566 		 */
10567 		freemsg(mp);
10568 		return;
10569 	default:
10570 		break;
10571 	}
10572 
10573 	/*
10574 	 * Already on the correct queue/perimeter.
10575 	 * If this is a detached connection and not an eager
10576 	 * connection hanging off a listener then new data
10577 	 * (past the FIN) will cause a reset.
10578 	 * We do a special check here where it
10579 	 * is out of the main line, rather than check
10580 	 * if we are detached every time we see new
10581 	 * data down below.
10582 	 */
10583 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
10584 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
10585 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
10586 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10587 
10588 		freemsg(mp);
10589 		/*
10590 		 * This could be an SSL closure alert. We're detached so just
10591 		 * acknowledge it this last time.
10592 		 */
10593 		if (tcp->tcp_kssl_ctx != NULL) {
10594 			kssl_release_ctx(tcp->tcp_kssl_ctx);
10595 			tcp->tcp_kssl_ctx = NULL;
10596 
10597 			tcp->tcp_rnxt += seg_len;
10598 			tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10599 			flags |= TH_ACK_NEEDED;
10600 			goto ack_check;
10601 		}
10602 
10603 		tcp_xmit_ctl("new data when detached", tcp,
10604 		    tcp->tcp_snxt, 0, TH_RST);
10605 		(void) tcp_clean_death(tcp, EPROTO, 12);
10606 		return;
10607 	}
10608 
10609 	mp->b_rptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10610 	urp = ntohs(tcpha->tha_urp) - TCP_OLD_URP_INTERPRETATION;
10611 	new_swnd = ntohs(tcpha->tha_win) <<
10612 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
10613 
10614 	if (tcp->tcp_snd_ts_ok) {
10615 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
10616 			/*
10617 			 * This segment is not acceptable.
10618 			 * Drop it and send back an ACK.
10619 			 */
10620 			freemsg(mp);
10621 			flags |= TH_ACK_NEEDED;
10622 			goto ack_check;
10623 		}
10624 	} else if (tcp->tcp_snd_sack_ok) {
10625 		ASSERT(tcp->tcp_sack_info != NULL);
10626 		tcpopt.tcp = tcp;
10627 		/*
10628 		 * SACK info in already updated in tcp_parse_options.  Ignore
10629 		 * all other TCP options...
10630 		 */
10631 		(void) tcp_parse_options(tcpha, &tcpopt);
10632 	}
10633 try_again:;
10634 	mss = tcp->tcp_mss;
10635 	gap = seg_seq - tcp->tcp_rnxt;
10636 	rgap = tcp->tcp_rwnd - (gap + seg_len);
10637 	/*
10638 	 * gap is the amount of sequence space between what we expect to see
10639 	 * and what we got for seg_seq.  A positive value for gap means
10640 	 * something got lost.  A negative value means we got some old stuff.
10641 	 */
10642 	if (gap < 0) {
10643 		/* Old stuff present.  Is the SYN in there? */
10644 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
10645 		    (seg_len != 0)) {
10646 			flags &= ~TH_SYN;
10647 			seg_seq++;
10648 			urp--;
10649 			/* Recompute the gaps after noting the SYN. */
10650 			goto try_again;
10651 		}
10652 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
10653 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
10654 		    (seg_len > -gap ? -gap : seg_len));
10655 		/* Remove the old stuff from seg_len. */
10656 		seg_len += gap;
10657 		/*
10658 		 * Anything left?
10659 		 * Make sure to check for unack'd FIN when rest of data
10660 		 * has been previously ack'd.
10661 		 */
10662 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
10663 			/*
10664 			 * Resets are only valid if they lie within our offered
10665 			 * window.  If the RST bit is set, we just ignore this
10666 			 * segment.
10667 			 */
10668 			if (flags & TH_RST) {
10669 				freemsg(mp);
10670 				return;
10671 			}
10672 
10673 			/*
10674 			 * The arriving of dup data packets indicate that we
10675 			 * may have postponed an ack for too long, or the other
10676 			 * side's RTT estimate is out of shape. Start acking
10677 			 * more often.
10678 			 */
10679 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
10680 			    tcp->tcp_rack_cnt >= 1 &&
10681 			    tcp->tcp_rack_abs_max > 2) {
10682 				tcp->tcp_rack_abs_max--;
10683 			}
10684 			tcp->tcp_rack_cur_max = 1;
10685 
10686 			/*
10687 			 * This segment is "unacceptable".  None of its
10688 			 * sequence space lies within our advertized window.
10689 			 *
10690 			 * Adjust seg_len to the original value for tracing.
10691 			 */
10692 			seg_len -= gap;
10693 			if (connp->conn_debug) {
10694 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
10695 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
10696 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
10697 				    "seg_len %d, rnxt %u, snxt %u, %s",
10698 				    gap, rgap, flags, seg_seq, seg_ack,
10699 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
10700 				    tcp_display(tcp, NULL,
10701 				    DISP_ADDR_AND_PORT));
10702 			}
10703 
10704 			/*
10705 			 * Arrange to send an ACK in response to the
10706 			 * unacceptable segment per RFC 793 page 69. There
10707 			 * is only one small difference between ours and the
10708 			 * acceptability test in the RFC - we accept ACK-only
10709 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
10710 			 * will be generated.
10711 			 *
10712 			 * Note that we have to ACK an ACK-only packet at least
10713 			 * for stacks that send 0-length keep-alives with
10714 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
10715 			 * section 4.2.3.6. As long as we don't ever generate
10716 			 * an unacceptable packet in response to an incoming
10717 			 * packet that is unacceptable, it should not cause
10718 			 * "ACK wars".
10719 			 */
10720 			flags |=  TH_ACK_NEEDED;
10721 
10722 			/*
10723 			 * Continue processing this segment in order to use the
10724 			 * ACK information it contains, but skip all other
10725 			 * sequence-number processing.	Processing the ACK
10726 			 * information is necessary in order to
10727 			 * re-synchronize connections that may have lost
10728 			 * synchronization.
10729 			 *
10730 			 * We clear seg_len and flag fields related to
10731 			 * sequence number processing as they are not
10732 			 * to be trusted for an unacceptable segment.
10733 			 */
10734 			seg_len = 0;
10735 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
10736 			goto process_ack;
10737 		}
10738 
10739 		/* Fix seg_seq, and chew the gap off the front. */
10740 		seg_seq = tcp->tcp_rnxt;
10741 		urp += gap;
10742 		do {
10743 			mblk_t	*mp2;
10744 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10745 			    (uintptr_t)UINT_MAX);
10746 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
10747 			if (gap > 0) {
10748 				mp->b_rptr = mp->b_wptr - gap;
10749 				break;
10750 			}
10751 			mp2 = mp;
10752 			mp = mp->b_cont;
10753 			freeb(mp2);
10754 		} while (gap < 0);
10755 		/*
10756 		 * If the urgent data has already been acknowledged, we
10757 		 * should ignore TH_URG below
10758 		 */
10759 		if (urp < 0)
10760 			flags &= ~TH_URG;
10761 	}
10762 	/*
10763 	 * rgap is the amount of stuff received out of window.  A negative
10764 	 * value is the amount out of window.
10765 	 */
10766 	if (rgap < 0) {
10767 		mblk_t	*mp2;
10768 
10769 		if (tcp->tcp_rwnd == 0) {
10770 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
10771 		} else {
10772 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
10773 			UPDATE_MIB(&tcps->tcps_mib,
10774 			    tcpInDataPastWinBytes, -rgap);
10775 		}
10776 
10777 		/*
10778 		 * seg_len does not include the FIN, so if more than
10779 		 * just the FIN is out of window, we act like we don't
10780 		 * see it.  (If just the FIN is out of window, rgap
10781 		 * will be zero and we will go ahead and acknowledge
10782 		 * the FIN.)
10783 		 */
10784 		flags &= ~TH_FIN;
10785 
10786 		/* Fix seg_len and make sure there is something left. */
10787 		seg_len += rgap;
10788 		if (seg_len <= 0) {
10789 			/*
10790 			 * Resets are only valid if they lie within our offered
10791 			 * window.  If the RST bit is set, we just ignore this
10792 			 * segment.
10793 			 */
10794 			if (flags & TH_RST) {
10795 				freemsg(mp);
10796 				return;
10797 			}
10798 
10799 			/* Per RFC 793, we need to send back an ACK. */
10800 			flags |= TH_ACK_NEEDED;
10801 
10802 			/*
10803 			 * Send SIGURG as soon as possible i.e. even
10804 			 * if the TH_URG was delivered in a window probe
10805 			 * packet (which will be unacceptable).
10806 			 *
10807 			 * We generate a signal if none has been generated
10808 			 * for this connection or if this is a new urgent
10809 			 * byte. Also send a zero-length "unmarked" message
10810 			 * to inform SIOCATMARK that this is not the mark.
10811 			 *
10812 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
10813 			 * is sent up. This plus the check for old data
10814 			 * (gap >= 0) handles the wraparound of the sequence
10815 			 * number space without having to always track the
10816 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
10817 			 * this max in its rcv_up variable).
10818 			 *
10819 			 * This prevents duplicate SIGURGS due to a "late"
10820 			 * zero-window probe when the T_EXDATA_IND has already
10821 			 * been sent up.
10822 			 */
10823 			if ((flags & TH_URG) &&
10824 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
10825 			    tcp->tcp_urp_last))) {
10826 				if (IPCL_IS_NONSTR(connp)) {
10827 					if (!TCP_IS_DETACHED(tcp)) {
10828 						(*connp->conn_upcalls->
10829 						    su_signal_oob)
10830 						    (connp->conn_upper_handle,
10831 						    urp);
10832 					}
10833 				} else {
10834 					mp1 = allocb(0, BPRI_MED);
10835 					if (mp1 == NULL) {
10836 						freemsg(mp);
10837 						return;
10838 					}
10839 					if (!TCP_IS_DETACHED(tcp) &&
10840 					    !putnextctl1(connp->conn_rq,
10841 					    M_PCSIG, SIGURG)) {
10842 						/* Try again on the rexmit. */
10843 						freemsg(mp1);
10844 						freemsg(mp);
10845 						return;
10846 					}
10847 					/*
10848 					 * If the next byte would be the mark
10849 					 * then mark with MARKNEXT else mark
10850 					 * with NOTMARKNEXT.
10851 					 */
10852 					if (gap == 0 && urp == 0)
10853 						mp1->b_flag |= MSGMARKNEXT;
10854 					else
10855 						mp1->b_flag |= MSGNOTMARKNEXT;
10856 					freemsg(tcp->tcp_urp_mark_mp);
10857 					tcp->tcp_urp_mark_mp = mp1;
10858 					flags |= TH_SEND_URP_MARK;
10859 				}
10860 				tcp->tcp_urp_last_valid = B_TRUE;
10861 				tcp->tcp_urp_last = urp + seg_seq;
10862 			}
10863 			/*
10864 			 * If this is a zero window probe, continue to
10865 			 * process the ACK part.  But we need to set seg_len
10866 			 * to 0 to avoid data processing.  Otherwise just
10867 			 * drop the segment and send back an ACK.
10868 			 */
10869 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
10870 				flags &= ~(TH_SYN | TH_URG);
10871 				seg_len = 0;
10872 				goto process_ack;
10873 			} else {
10874 				freemsg(mp);
10875 				goto ack_check;
10876 			}
10877 		}
10878 		/* Pitch out of window stuff off the end. */
10879 		rgap = seg_len;
10880 		mp2 = mp;
10881 		do {
10882 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
10883 			    (uintptr_t)INT_MAX);
10884 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
10885 			if (rgap < 0) {
10886 				mp2->b_wptr += rgap;
10887 				if ((mp1 = mp2->b_cont) != NULL) {
10888 					mp2->b_cont = NULL;
10889 					freemsg(mp1);
10890 				}
10891 				break;
10892 			}
10893 		} while ((mp2 = mp2->b_cont) != NULL);
10894 	}
10895 ok:;
10896 	/*
10897 	 * TCP should check ECN info for segments inside the window only.
10898 	 * Therefore the check should be done here.
10899 	 */
10900 	if (tcp->tcp_ecn_ok) {
10901 		if (flags & TH_CWR) {
10902 			tcp->tcp_ecn_echo_on = B_FALSE;
10903 		}
10904 		/*
10905 		 * Note that both ECN_CE and CWR can be set in the
10906 		 * same segment.  In this case, we once again turn
10907 		 * on ECN_ECHO.
10908 		 */
10909 		if (connp->conn_ipversion == IPV4_VERSION) {
10910 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
10911 
10912 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
10913 				tcp->tcp_ecn_echo_on = B_TRUE;
10914 			}
10915 		} else {
10916 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
10917 
10918 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
10919 			    htonl(IPH_ECN_CE << 20)) {
10920 				tcp->tcp_ecn_echo_on = B_TRUE;
10921 			}
10922 		}
10923 	}
10924 
10925 	/*
10926 	 * Check whether we can update tcp_ts_recent.  This test is
10927 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
10928 	 * Extensions for High Performance: An Update", Internet Draft.
10929 	 */
10930 	if (tcp->tcp_snd_ts_ok &&
10931 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
10932 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
10933 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
10934 		tcp->tcp_last_rcv_lbolt = LBOLT_FASTPATH64;
10935 	}
10936 
10937 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
10938 		/*
10939 		 * FIN in an out of order segment.  We record this in
10940 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
10941 		 * Clear the FIN so that any check on FIN flag will fail.
10942 		 * Remember that FIN also counts in the sequence number
10943 		 * space.  So we need to ack out of order FIN only segments.
10944 		 */
10945 		if (flags & TH_FIN) {
10946 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
10947 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
10948 			flags &= ~TH_FIN;
10949 			flags |= TH_ACK_NEEDED;
10950 		}
10951 		if (seg_len > 0) {
10952 			/* Fill in the SACK blk list. */
10953 			if (tcp->tcp_snd_sack_ok) {
10954 				ASSERT(tcp->tcp_sack_info != NULL);
10955 				tcp_sack_insert(tcp->tcp_sack_list,
10956 				    seg_seq, seg_seq + seg_len,
10957 				    &(tcp->tcp_num_sack_blk));
10958 			}
10959 
10960 			/*
10961 			 * Attempt reassembly and see if we have something
10962 			 * ready to go.
10963 			 */
10964 			mp = tcp_reass(tcp, mp, seg_seq);
10965 			/* Always ack out of order packets */
10966 			flags |= TH_ACK_NEEDED | TH_PUSH;
10967 			if (mp) {
10968 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10969 				    (uintptr_t)INT_MAX);
10970 				seg_len = mp->b_cont ? msgdsize(mp) :
10971 				    (int)(mp->b_wptr - mp->b_rptr);
10972 				seg_seq = tcp->tcp_rnxt;
10973 				/*
10974 				 * A gap is filled and the seq num and len
10975 				 * of the gap match that of a previously
10976 				 * received FIN, put the FIN flag back in.
10977 				 */
10978 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
10979 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
10980 					flags |= TH_FIN;
10981 					tcp->tcp_valid_bits &=
10982 					    ~TCP_OFO_FIN_VALID;
10983 				}
10984 				if (tcp->tcp_reass_tid != 0) {
10985 					(void) TCP_TIMER_CANCEL(tcp,
10986 					    tcp->tcp_reass_tid);
10987 					/*
10988 					 * Restart the timer if there is still
10989 					 * data in the reassembly queue.
10990 					 */
10991 					if (tcp->tcp_reass_head != NULL) {
10992 						tcp->tcp_reass_tid = TCP_TIMER(
10993 						    tcp, tcp_reass_timer,
10994 						    MSEC_TO_TICK(
10995 						    tcps->tcps_reass_timeout));
10996 					} else {
10997 						tcp->tcp_reass_tid = 0;
10998 					}
10999 				}
11000 			} else {
11001 				/*
11002 				 * Keep going even with NULL mp.
11003 				 * There may be a useful ACK or something else
11004 				 * we don't want to miss.
11005 				 *
11006 				 * But TCP should not perform fast retransmit
11007 				 * because of the ack number.  TCP uses
11008 				 * seg_len == 0 to determine if it is a pure
11009 				 * ACK.  And this is not a pure ACK.
11010 				 */
11011 				seg_len = 0;
11012 				ofo_seg = B_TRUE;
11013 
11014 				if (tcps->tcps_reass_timeout != 0 &&
11015 				    tcp->tcp_reass_tid == 0) {
11016 					tcp->tcp_reass_tid = TCP_TIMER(tcp,
11017 					    tcp_reass_timer, MSEC_TO_TICK(
11018 					    tcps->tcps_reass_timeout));
11019 				}
11020 			}
11021 		}
11022 	} else if (seg_len > 0) {
11023 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
11024 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
11025 		/*
11026 		 * If an out of order FIN was received before, and the seq
11027 		 * num and len of the new segment match that of the FIN,
11028 		 * put the FIN flag back in.
11029 		 */
11030 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
11031 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
11032 			flags |= TH_FIN;
11033 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
11034 		}
11035 	}
11036 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
11037 	if (flags & TH_RST) {
11038 		freemsg(mp);
11039 		switch (tcp->tcp_state) {
11040 		case TCPS_SYN_RCVD:
11041 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
11042 			break;
11043 		case TCPS_ESTABLISHED:
11044 		case TCPS_FIN_WAIT_1:
11045 		case TCPS_FIN_WAIT_2:
11046 		case TCPS_CLOSE_WAIT:
11047 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
11048 			break;
11049 		case TCPS_CLOSING:
11050 		case TCPS_LAST_ACK:
11051 			(void) tcp_clean_death(tcp, 0, 16);
11052 			break;
11053 		default:
11054 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11055 			(void) tcp_clean_death(tcp, ENXIO, 17);
11056 			break;
11057 		}
11058 		return;
11059 	}
11060 	if (flags & TH_SYN) {
11061 		/*
11062 		 * See RFC 793, Page 71
11063 		 *
11064 		 * The seq number must be in the window as it should
11065 		 * be "fixed" above.  If it is outside window, it should
11066 		 * be already rejected.  Note that we allow seg_seq to be
11067 		 * rnxt + rwnd because we want to accept 0 window probe.
11068 		 */
11069 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
11070 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
11071 		freemsg(mp);
11072 		/*
11073 		 * If the ACK flag is not set, just use our snxt as the
11074 		 * seq number of the RST segment.
11075 		 */
11076 		if (!(flags & TH_ACK)) {
11077 			seg_ack = tcp->tcp_snxt;
11078 		}
11079 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
11080 		    TH_RST|TH_ACK);
11081 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11082 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
11083 		return;
11084 	}
11085 	/*
11086 	 * urp could be -1 when the urp field in the packet is 0
11087 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
11088 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
11089 	 */
11090 	if (flags & TH_URG && urp >= 0) {
11091 		if (!tcp->tcp_urp_last_valid ||
11092 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
11093 			/*
11094 			 * Non-STREAMS sockets handle the urgent data a litte
11095 			 * differently from STREAMS based sockets. There is no
11096 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
11097 			 * flags to keep SIOCATMARK happy. Instead a
11098 			 * su_signal_oob upcall is made to update the mark.
11099 			 * Neither is a T_EXDATA_IND mblk needed to be
11100 			 * prepended to the urgent data. The urgent data is
11101 			 * delivered using the su_recv upcall, where we set
11102 			 * the MSG_OOB flag to indicate that it is urg data.
11103 			 *
11104 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
11105 			 * are used by non-STREAMS sockets.
11106 			 */
11107 			if (IPCL_IS_NONSTR(connp)) {
11108 				if (!TCP_IS_DETACHED(tcp)) {
11109 					(*connp->conn_upcalls->su_signal_oob)
11110 					    (connp->conn_upper_handle, urp);
11111 				}
11112 			} else {
11113 				/*
11114 				 * If we haven't generated the signal yet for
11115 				 * this urgent pointer value, do it now.  Also,
11116 				 * send up a zero-length M_DATA indicating
11117 				 * whether or not this is the mark. The latter
11118 				 * is not needed when a T_EXDATA_IND is sent up.
11119 				 * However, if there are allocation failures
11120 				 * this code relies on the sender retransmitting
11121 				 * and the socket code for determining the mark
11122 				 * should not block waiting for the peer to
11123 				 * transmit. Thus, for simplicity we always
11124 				 * send up the mark indication.
11125 				 */
11126 				mp1 = allocb(0, BPRI_MED);
11127 				if (mp1 == NULL) {
11128 					freemsg(mp);
11129 					return;
11130 				}
11131 				if (!TCP_IS_DETACHED(tcp) &&
11132 				    !putnextctl1(connp->conn_rq, M_PCSIG,
11133 				    SIGURG)) {
11134 					/* Try again on the rexmit. */
11135 					freemsg(mp1);
11136 					freemsg(mp);
11137 					return;
11138 				}
11139 				/*
11140 				 * Mark with NOTMARKNEXT for now.
11141 				 * The code below will change this to MARKNEXT
11142 				 * if we are at the mark.
11143 				 *
11144 				 * If there are allocation failures (e.g. in
11145 				 * dupmsg below) the next time tcp_input_data
11146 				 * sees the urgent segment it will send up the
11147 				 * MSGMARKNEXT message.
11148 				 */
11149 				mp1->b_flag |= MSGNOTMARKNEXT;
11150 				freemsg(tcp->tcp_urp_mark_mp);
11151 				tcp->tcp_urp_mark_mp = mp1;
11152 				flags |= TH_SEND_URP_MARK;
11153 #ifdef DEBUG
11154 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11155 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
11156 				    "last %x, %s",
11157 				    seg_seq, urp, tcp->tcp_urp_last,
11158 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11159 #endif /* DEBUG */
11160 			}
11161 			tcp->tcp_urp_last_valid = B_TRUE;
11162 			tcp->tcp_urp_last = urp + seg_seq;
11163 		} else if (tcp->tcp_urp_mark_mp != NULL) {
11164 			/*
11165 			 * An allocation failure prevented the previous
11166 			 * tcp_input_data from sending up the allocated
11167 			 * MSG*MARKNEXT message - send it up this time
11168 			 * around.
11169 			 */
11170 			flags |= TH_SEND_URP_MARK;
11171 		}
11172 
11173 		/*
11174 		 * If the urgent byte is in this segment, make sure that it is
11175 		 * all by itself.  This makes it much easier to deal with the
11176 		 * possibility of an allocation failure on the T_exdata_ind.
11177 		 * Note that seg_len is the number of bytes in the segment, and
11178 		 * urp is the offset into the segment of the urgent byte.
11179 		 * urp < seg_len means that the urgent byte is in this segment.
11180 		 */
11181 		if (urp < seg_len) {
11182 			if (seg_len != 1) {
11183 				uint32_t  tmp_rnxt;
11184 				/*
11185 				 * Break it up and feed it back in.
11186 				 * Re-attach the IP header.
11187 				 */
11188 				mp->b_rptr = iphdr;
11189 				if (urp > 0) {
11190 					/*
11191 					 * There is stuff before the urgent
11192 					 * byte.
11193 					 */
11194 					mp1 = dupmsg(mp);
11195 					if (!mp1) {
11196 						/*
11197 						 * Trim from urgent byte on.
11198 						 * The rest will come back.
11199 						 */
11200 						(void) adjmsg(mp,
11201 						    urp - seg_len);
11202 						tcp_input_data(connp,
11203 						    mp, NULL, ira);
11204 						return;
11205 					}
11206 					(void) adjmsg(mp1, urp - seg_len);
11207 					/* Feed this piece back in. */
11208 					tmp_rnxt = tcp->tcp_rnxt;
11209 					tcp_input_data(connp, mp1, NULL, ira);
11210 					/*
11211 					 * If the data passed back in was not
11212 					 * processed (ie: bad ACK) sending
11213 					 * the remainder back in will cause a
11214 					 * loop. In this case, drop the
11215 					 * packet and let the sender try
11216 					 * sending a good packet.
11217 					 */
11218 					if (tmp_rnxt == tcp->tcp_rnxt) {
11219 						freemsg(mp);
11220 						return;
11221 					}
11222 				}
11223 				if (urp != seg_len - 1) {
11224 					uint32_t  tmp_rnxt;
11225 					/*
11226 					 * There is stuff after the urgent
11227 					 * byte.
11228 					 */
11229 					mp1 = dupmsg(mp);
11230 					if (!mp1) {
11231 						/*
11232 						 * Trim everything beyond the
11233 						 * urgent byte.  The rest will
11234 						 * come back.
11235 						 */
11236 						(void) adjmsg(mp,
11237 						    urp + 1 - seg_len);
11238 						tcp_input_data(connp,
11239 						    mp, NULL, ira);
11240 						return;
11241 					}
11242 					(void) adjmsg(mp1, urp + 1 - seg_len);
11243 					tmp_rnxt = tcp->tcp_rnxt;
11244 					tcp_input_data(connp, mp1, NULL, ira);
11245 					/*
11246 					 * If the data passed back in was not
11247 					 * processed (ie: bad ACK) sending
11248 					 * the remainder back in will cause a
11249 					 * loop. In this case, drop the
11250 					 * packet and let the sender try
11251 					 * sending a good packet.
11252 					 */
11253 					if (tmp_rnxt == tcp->tcp_rnxt) {
11254 						freemsg(mp);
11255 						return;
11256 					}
11257 				}
11258 				tcp_input_data(connp, mp, NULL, ira);
11259 				return;
11260 			}
11261 			/*
11262 			 * This segment contains only the urgent byte.  We
11263 			 * have to allocate the T_exdata_ind, if we can.
11264 			 */
11265 			if (IPCL_IS_NONSTR(connp)) {
11266 				int error;
11267 
11268 				(*connp->conn_upcalls->su_recv)
11269 				    (connp->conn_upper_handle, mp, seg_len,
11270 				    MSG_OOB, &error, NULL);
11271 				/*
11272 				 * We should never be in middle of a
11273 				 * fallback, the squeue guarantees that.
11274 				 */
11275 				ASSERT(error != EOPNOTSUPP);
11276 				mp = NULL;
11277 				goto update_ack;
11278 			} else if (!tcp->tcp_urp_mp) {
11279 				struct T_exdata_ind *tei;
11280 				mp1 = allocb(sizeof (struct T_exdata_ind),
11281 				    BPRI_MED);
11282 				if (!mp1) {
11283 					/*
11284 					 * Sigh... It'll be back.
11285 					 * Generate any MSG*MARK message now.
11286 					 */
11287 					freemsg(mp);
11288 					seg_len = 0;
11289 					if (flags & TH_SEND_URP_MARK) {
11290 
11291 
11292 						ASSERT(tcp->tcp_urp_mark_mp);
11293 						tcp->tcp_urp_mark_mp->b_flag &=
11294 						    ~MSGNOTMARKNEXT;
11295 						tcp->tcp_urp_mark_mp->b_flag |=
11296 						    MSGMARKNEXT;
11297 					}
11298 					goto ack_check;
11299 				}
11300 				mp1->b_datap->db_type = M_PROTO;
11301 				tei = (struct T_exdata_ind *)mp1->b_rptr;
11302 				tei->PRIM_type = T_EXDATA_IND;
11303 				tei->MORE_flag = 0;
11304 				mp1->b_wptr = (uchar_t *)&tei[1];
11305 				tcp->tcp_urp_mp = mp1;
11306 #ifdef DEBUG
11307 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11308 				    "tcp_rput: allocated exdata_ind %s",
11309 				    tcp_display(tcp, NULL,
11310 				    DISP_PORT_ONLY));
11311 #endif /* DEBUG */
11312 				/*
11313 				 * There is no need to send a separate MSG*MARK
11314 				 * message since the T_EXDATA_IND will be sent
11315 				 * now.
11316 				 */
11317 				flags &= ~TH_SEND_URP_MARK;
11318 				freemsg(tcp->tcp_urp_mark_mp);
11319 				tcp->tcp_urp_mark_mp = NULL;
11320 			}
11321 			/*
11322 			 * Now we are all set.  On the next putnext upstream,
11323 			 * tcp_urp_mp will be non-NULL and will get prepended
11324 			 * to what has to be this piece containing the urgent
11325 			 * byte.  If for any reason we abort this segment below,
11326 			 * if it comes back, we will have this ready, or it
11327 			 * will get blown off in close.
11328 			 */
11329 		} else if (urp == seg_len) {
11330 			/*
11331 			 * The urgent byte is the next byte after this sequence
11332 			 * number. If this endpoint is non-STREAMS, then there
11333 			 * is nothing to do here since the socket has already
11334 			 * been notified about the urg pointer by the
11335 			 * su_signal_oob call above.
11336 			 *
11337 			 * In case of STREAMS, some more work might be needed.
11338 			 * If there is data it is marked with MSGMARKNEXT and
11339 			 * and any tcp_urp_mark_mp is discarded since it is not
11340 			 * needed. Otherwise, if the code above just allocated
11341 			 * a zero-length tcp_urp_mark_mp message, that message
11342 			 * is tagged with MSGMARKNEXT. Sending up these
11343 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
11344 			 * even though the T_EXDATA_IND will not be sent up
11345 			 * until the urgent byte arrives.
11346 			 */
11347 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
11348 				if (seg_len != 0) {
11349 					flags |= TH_MARKNEXT_NEEDED;
11350 					freemsg(tcp->tcp_urp_mark_mp);
11351 					tcp->tcp_urp_mark_mp = NULL;
11352 					flags &= ~TH_SEND_URP_MARK;
11353 				} else if (tcp->tcp_urp_mark_mp != NULL) {
11354 					flags |= TH_SEND_URP_MARK;
11355 					tcp->tcp_urp_mark_mp->b_flag &=
11356 					    ~MSGNOTMARKNEXT;
11357 					tcp->tcp_urp_mark_mp->b_flag |=
11358 					    MSGMARKNEXT;
11359 				}
11360 			}
11361 #ifdef DEBUG
11362 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11363 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
11364 			    seg_len, flags,
11365 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11366 #endif /* DEBUG */
11367 		}
11368 #ifdef DEBUG
11369 		else {
11370 			/* Data left until we hit mark */
11371 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11372 			    "tcp_rput: URP %d bytes left, %s",
11373 			    urp - seg_len, tcp_display(tcp, NULL,
11374 			    DISP_PORT_ONLY));
11375 		}
11376 #endif /* DEBUG */
11377 	}
11378 
11379 process_ack:
11380 	if (!(flags & TH_ACK)) {
11381 		freemsg(mp);
11382 		goto xmit_check;
11383 	}
11384 	}
11385 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
11386 
11387 	if (bytes_acked > 0)
11388 		tcp->tcp_ip_forward_progress = B_TRUE;
11389 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
11390 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
11391 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
11392 			/* 3-way handshake complete - pass up the T_CONN_IND */
11393 			tcp_t	*listener = tcp->tcp_listener;
11394 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
11395 
11396 			tcp->tcp_tconnind_started = B_TRUE;
11397 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
11398 			/*
11399 			 * We are here means eager is fine but it can
11400 			 * get a TH_RST at any point between now and till
11401 			 * accept completes and disappear. We need to
11402 			 * ensure that reference to eager is valid after
11403 			 * we get out of eager's perimeter. So we do
11404 			 * an extra refhold.
11405 			 */
11406 			CONN_INC_REF(connp);
11407 
11408 			/*
11409 			 * The listener also exists because of the refhold
11410 			 * done in tcp_input_listener. Its possible that it
11411 			 * might have closed. We will check that once we
11412 			 * get inside listeners context.
11413 			 */
11414 			CONN_INC_REF(listener->tcp_connp);
11415 			if (listener->tcp_connp->conn_sqp ==
11416 			    connp->conn_sqp) {
11417 				/*
11418 				 * We optimize by not calling an SQUEUE_ENTER
11419 				 * on the listener since we know that the
11420 				 * listener and eager squeues are the same.
11421 				 * We are able to make this check safely only
11422 				 * because neither the eager nor the listener
11423 				 * can change its squeue. Only an active connect
11424 				 * can change its squeue
11425 				 */
11426 				tcp_send_conn_ind(listener->tcp_connp, mp,
11427 				    listener->tcp_connp->conn_sqp);
11428 				CONN_DEC_REF(listener->tcp_connp);
11429 			} else if (!tcp->tcp_loopback) {
11430 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11431 				    mp, tcp_send_conn_ind,
11432 				    listener->tcp_connp, NULL, SQ_FILL,
11433 				    SQTAG_TCP_CONN_IND);
11434 			} else {
11435 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11436 				    mp, tcp_send_conn_ind,
11437 				    listener->tcp_connp, NULL, SQ_PROCESS,
11438 				    SQTAG_TCP_CONN_IND);
11439 			}
11440 		}
11441 
11442 		/*
11443 		 * We are seeing the final ack in the three way
11444 		 * hand shake of a active open'ed connection
11445 		 * so we must send up a T_CONN_CON
11446 		 *
11447 		 * tcp_sendmsg() checks tcp_state without entering
11448 		 * the squeue so tcp_state should be updated before
11449 		 * sending up connection confirmation.
11450 		 */
11451 		tcp->tcp_state = TCPS_ESTABLISHED;
11452 		if (tcp->tcp_active_open) {
11453 			if (!tcp_conn_con(tcp, iphdr, mp, NULL, ira)) {
11454 				freemsg(mp);
11455 				tcp->tcp_state = TCPS_SYN_RCVD;
11456 				return;
11457 			}
11458 			/*
11459 			 * Don't fuse the loopback endpoints for
11460 			 * simultaneous active opens.
11461 			 */
11462 			if (tcp->tcp_loopback) {
11463 				TCP_STAT(tcps, tcp_fusion_unfusable);
11464 				tcp->tcp_unfusable = B_TRUE;
11465 			}
11466 		}
11467 
11468 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
11469 		bytes_acked--;
11470 		/* SYN was acked - making progress */
11471 		tcp->tcp_ip_forward_progress = B_TRUE;
11472 
11473 		/*
11474 		 * If SYN was retransmitted, need to reset all
11475 		 * retransmission info as this segment will be
11476 		 * treated as a dup ACK.
11477 		 */
11478 		if (tcp->tcp_rexmit) {
11479 			tcp->tcp_rexmit = B_FALSE;
11480 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11481 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
11482 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11483 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11484 			tcp->tcp_ms_we_have_waited = 0;
11485 			tcp->tcp_cwnd = mss;
11486 		}
11487 
11488 		/*
11489 		 * We set the send window to zero here.
11490 		 * This is needed if there is data to be
11491 		 * processed already on the queue.
11492 		 * Later (at swnd_update label), the
11493 		 * "new_swnd > tcp_swnd" condition is satisfied
11494 		 * the XMIT_NEEDED flag is set in the current
11495 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
11496 		 * called if there is already data on queue in
11497 		 * this state.
11498 		 */
11499 		tcp->tcp_swnd = 0;
11500 
11501 		if (new_swnd > tcp->tcp_max_swnd)
11502 			tcp->tcp_max_swnd = new_swnd;
11503 		tcp->tcp_swl1 = seg_seq;
11504 		tcp->tcp_swl2 = seg_ack;
11505 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
11506 
11507 		/* Fuse when both sides are in ESTABLISHED state */
11508 		if (tcp->tcp_loopback && do_tcp_fusion)
11509 			tcp_fuse(tcp, iphdr, tcpha);
11510 
11511 	}
11512 	/* This code follows 4.4BSD-Lite2 mostly. */
11513 	if (bytes_acked < 0)
11514 		goto est;
11515 
11516 	/*
11517 	 * If TCP is ECN capable and the congestion experience bit is
11518 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
11519 	 * done once per window (or more loosely, per RTT).
11520 	 */
11521 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
11522 		tcp->tcp_cwr = B_FALSE;
11523 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
11524 		if (!tcp->tcp_cwr) {
11525 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
11526 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
11527 			tcp->tcp_cwnd = npkt * mss;
11528 			/*
11529 			 * If the cwnd is 0, use the timer to clock out
11530 			 * new segments.  This is required by the ECN spec.
11531 			 */
11532 			if (npkt == 0) {
11533 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11534 				/*
11535 				 * This makes sure that when the ACK comes
11536 				 * back, we will increase tcp_cwnd by 1 MSS.
11537 				 */
11538 				tcp->tcp_cwnd_cnt = 0;
11539 			}
11540 			tcp->tcp_cwr = B_TRUE;
11541 			/*
11542 			 * This marks the end of the current window of in
11543 			 * flight data.  That is why we don't use
11544 			 * tcp_suna + tcp_swnd.  Only data in flight can
11545 			 * provide ECN info.
11546 			 */
11547 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11548 			tcp->tcp_ecn_cwr_sent = B_FALSE;
11549 		}
11550 	}
11551 
11552 	mp1 = tcp->tcp_xmit_head;
11553 	if (bytes_acked == 0) {
11554 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
11555 			int dupack_cnt;
11556 
11557 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
11558 			/*
11559 			 * Fast retransmit.  When we have seen exactly three
11560 			 * identical ACKs while we have unacked data
11561 			 * outstanding we take it as a hint that our peer
11562 			 * dropped something.
11563 			 *
11564 			 * If TCP is retransmitting, don't do fast retransmit.
11565 			 */
11566 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
11567 			    ! tcp->tcp_rexmit) {
11568 				/* Do Limited Transmit */
11569 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
11570 				    tcps->tcps_dupack_fast_retransmit) {
11571 					/*
11572 					 * RFC 3042
11573 					 *
11574 					 * What we need to do is temporarily
11575 					 * increase tcp_cwnd so that new
11576 					 * data can be sent if it is allowed
11577 					 * by the receive window (tcp_rwnd).
11578 					 * tcp_wput_data() will take care of
11579 					 * the rest.
11580 					 *
11581 					 * If the connection is SACK capable,
11582 					 * only do limited xmit when there
11583 					 * is SACK info.
11584 					 *
11585 					 * Note how tcp_cwnd is incremented.
11586 					 * The first dup ACK will increase
11587 					 * it by 1 MSS.  The second dup ACK
11588 					 * will increase it by 2 MSS.  This
11589 					 * means that only 1 new segment will
11590 					 * be sent for each dup ACK.
11591 					 */
11592 					if (tcp->tcp_unsent > 0 &&
11593 					    (!tcp->tcp_snd_sack_ok ||
11594 					    (tcp->tcp_snd_sack_ok &&
11595 					    tcp->tcp_notsack_list != NULL))) {
11596 						tcp->tcp_cwnd += mss <<
11597 						    (tcp->tcp_dupack_cnt - 1);
11598 						flags |= TH_LIMIT_XMIT;
11599 					}
11600 				} else if (dupack_cnt ==
11601 				    tcps->tcps_dupack_fast_retransmit) {
11602 
11603 				/*
11604 				 * If we have reduced tcp_ssthresh
11605 				 * because of ECN, do not reduce it again
11606 				 * unless it is already one window of data
11607 				 * away.  After one window of data, tcp_cwr
11608 				 * should then be cleared.  Note that
11609 				 * for non ECN capable connection, tcp_cwr
11610 				 * should always be false.
11611 				 *
11612 				 * Adjust cwnd since the duplicate
11613 				 * ack indicates that a packet was
11614 				 * dropped (due to congestion.)
11615 				 */
11616 				if (!tcp->tcp_cwr) {
11617 					npkt = ((tcp->tcp_snxt -
11618 					    tcp->tcp_suna) >> 1) / mss;
11619 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
11620 					    mss;
11621 					tcp->tcp_cwnd = (npkt +
11622 					    tcp->tcp_dupack_cnt) * mss;
11623 				}
11624 				if (tcp->tcp_ecn_ok) {
11625 					tcp->tcp_cwr = B_TRUE;
11626 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11627 					tcp->tcp_ecn_cwr_sent = B_FALSE;
11628 				}
11629 
11630 				/*
11631 				 * We do Hoe's algorithm.  Refer to her
11632 				 * paper "Improving the Start-up Behavior
11633 				 * of a Congestion Control Scheme for TCP,"
11634 				 * appeared in SIGCOMM'96.
11635 				 *
11636 				 * Save highest seq no we have sent so far.
11637 				 * Be careful about the invisible FIN byte.
11638 				 */
11639 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
11640 				    (tcp->tcp_unsent == 0)) {
11641 					tcp->tcp_rexmit_max = tcp->tcp_fss;
11642 				} else {
11643 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
11644 				}
11645 
11646 				/*
11647 				 * Do not allow bursty traffic during.
11648 				 * fast recovery.  Refer to Fall and Floyd's
11649 				 * paper "Simulation-based Comparisons of
11650 				 * Tahoe, Reno and SACK TCP" (in CCR?)
11651 				 * This is a best current practise.
11652 				 */
11653 				tcp->tcp_snd_burst = TCP_CWND_SS;
11654 
11655 				/*
11656 				 * For SACK:
11657 				 * Calculate tcp_pipe, which is the
11658 				 * estimated number of bytes in
11659 				 * network.
11660 				 *
11661 				 * tcp_fack is the highest sack'ed seq num
11662 				 * TCP has received.
11663 				 *
11664 				 * tcp_pipe is explained in the above quoted
11665 				 * Fall and Floyd's paper.  tcp_fack is
11666 				 * explained in Mathis and Mahdavi's
11667 				 * "Forward Acknowledgment: Refining TCP
11668 				 * Congestion Control" in SIGCOMM '96.
11669 				 */
11670 				if (tcp->tcp_snd_sack_ok) {
11671 					ASSERT(tcp->tcp_sack_info != NULL);
11672 					if (tcp->tcp_notsack_list != NULL) {
11673 						tcp->tcp_pipe = tcp->tcp_snxt -
11674 						    tcp->tcp_fack;
11675 						tcp->tcp_sack_snxt = seg_ack;
11676 						flags |= TH_NEED_SACK_REXMIT;
11677 					} else {
11678 						/*
11679 						 * Always initialize tcp_pipe
11680 						 * even though we don't have
11681 						 * any SACK info.  If later
11682 						 * we get SACK info and
11683 						 * tcp_pipe is not initialized,
11684 						 * funny things will happen.
11685 						 */
11686 						tcp->tcp_pipe =
11687 						    tcp->tcp_cwnd_ssthresh;
11688 					}
11689 				} else {
11690 					flags |= TH_REXMIT_NEEDED;
11691 				} /* tcp_snd_sack_ok */
11692 
11693 				} else {
11694 					/*
11695 					 * Here we perform congestion
11696 					 * avoidance, but NOT slow start.
11697 					 * This is known as the Fast
11698 					 * Recovery Algorithm.
11699 					 */
11700 					if (tcp->tcp_snd_sack_ok &&
11701 					    tcp->tcp_notsack_list != NULL) {
11702 						flags |= TH_NEED_SACK_REXMIT;
11703 						tcp->tcp_pipe -= mss;
11704 						if (tcp->tcp_pipe < 0)
11705 							tcp->tcp_pipe = 0;
11706 					} else {
11707 					/*
11708 					 * We know that one more packet has
11709 					 * left the pipe thus we can update
11710 					 * cwnd.
11711 					 */
11712 					cwnd = tcp->tcp_cwnd + mss;
11713 					if (cwnd > tcp->tcp_cwnd_max)
11714 						cwnd = tcp->tcp_cwnd_max;
11715 					tcp->tcp_cwnd = cwnd;
11716 					if (tcp->tcp_unsent > 0)
11717 						flags |= TH_XMIT_NEEDED;
11718 					}
11719 				}
11720 			}
11721 		} else if (tcp->tcp_zero_win_probe) {
11722 			/*
11723 			 * If the window has opened, need to arrange
11724 			 * to send additional data.
11725 			 */
11726 			if (new_swnd != 0) {
11727 				/* tcp_suna != tcp_snxt */
11728 				/* Packet contains a window update */
11729 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
11730 				tcp->tcp_zero_win_probe = 0;
11731 				tcp->tcp_timer_backoff = 0;
11732 				tcp->tcp_ms_we_have_waited = 0;
11733 
11734 				/*
11735 				 * Transmit starting with tcp_suna since
11736 				 * the one byte probe is not ack'ed.
11737 				 * If TCP has sent more than one identical
11738 				 * probe, tcp_rexmit will be set.  That means
11739 				 * tcp_ss_rexmit() will send out the one
11740 				 * byte along with new data.  Otherwise,
11741 				 * fake the retransmission.
11742 				 */
11743 				flags |= TH_XMIT_NEEDED;
11744 				if (!tcp->tcp_rexmit) {
11745 					tcp->tcp_rexmit = B_TRUE;
11746 					tcp->tcp_dupack_cnt = 0;
11747 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
11748 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
11749 				}
11750 			}
11751 		}
11752 		goto swnd_update;
11753 	}
11754 
11755 	/*
11756 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
11757 	 * If the ACK value acks something that we have not yet sent, it might
11758 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
11759 	 * other side.
11760 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
11761 	 * state is handled above, so we can always just drop the segment and
11762 	 * send an ACK here.
11763 	 *
11764 	 * In the case where the peer shrinks the window, we see the new window
11765 	 * update, but all the data sent previously is queued up by the peer.
11766 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
11767 	 * number, which was already sent, and within window, is recorded.
11768 	 * tcp_snxt is then updated.
11769 	 *
11770 	 * If the window has previously shrunk, and an ACK for data not yet
11771 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
11772 	 * the ACK is for data within the window at the time the window was
11773 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
11774 	 * the sequence number ACK'ed.
11775 	 *
11776 	 * If the ACK covers all the data sent at the time the window was
11777 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
11778 	 *
11779 	 * Should we send ACKs in response to ACK only segments?
11780 	 */
11781 
11782 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
11783 		if ((tcp->tcp_is_wnd_shrnk) &&
11784 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
11785 			uint32_t data_acked_ahead_snxt;
11786 
11787 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
11788 			tcp_update_xmit_tail(tcp, seg_ack);
11789 			tcp->tcp_unsent -= data_acked_ahead_snxt;
11790 		} else {
11791 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
11792 			/* drop the received segment */
11793 			freemsg(mp);
11794 
11795 			/*
11796 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
11797 			 * greater than 0, check if the number of such
11798 			 * bogus ACks is greater than that count.  If yes,
11799 			 * don't send back any ACK.  This prevents TCP from
11800 			 * getting into an ACK storm if somehow an attacker
11801 			 * successfully spoofs an acceptable segment to our
11802 			 * peer.  If this continues (count > 2 X threshold),
11803 			 * we should abort this connection.
11804 			 */
11805 			if (tcp_drop_ack_unsent_cnt > 0 &&
11806 			    ++tcp->tcp_in_ack_unsent >
11807 			    tcp_drop_ack_unsent_cnt) {
11808 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
11809 				if (tcp->tcp_in_ack_unsent > 2 *
11810 				    tcp_drop_ack_unsent_cnt) {
11811 					(void) tcp_clean_death(tcp, EPROTO, 20);
11812 				}
11813 				return;
11814 			}
11815 			mp = tcp_ack_mp(tcp);
11816 			if (mp != NULL) {
11817 				BUMP_LOCAL(tcp->tcp_obsegs);
11818 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
11819 				tcp_send_data(tcp, mp);
11820 			}
11821 			return;
11822 		}
11823 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
11824 	    tcp->tcp_snxt_shrunk)) {
11825 			tcp->tcp_is_wnd_shrnk = B_FALSE;
11826 	}
11827 
11828 	/*
11829 	 * TCP gets a new ACK, update the notsack'ed list to delete those
11830 	 * blocks that are covered by this ACK.
11831 	 */
11832 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
11833 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
11834 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
11835 	}
11836 
11837 	/*
11838 	 * If we got an ACK after fast retransmit, check to see
11839 	 * if it is a partial ACK.  If it is not and the congestion
11840 	 * window was inflated to account for the other side's
11841 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
11842 	 */
11843 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
11844 		ASSERT(tcp->tcp_rexmit == B_FALSE);
11845 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
11846 			tcp->tcp_dupack_cnt = 0;
11847 			/*
11848 			 * Restore the orig tcp_cwnd_ssthresh after
11849 			 * fast retransmit phase.
11850 			 */
11851 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
11852 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
11853 			}
11854 			tcp->tcp_rexmit_max = seg_ack;
11855 			tcp->tcp_cwnd_cnt = 0;
11856 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11857 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11858 
11859 			/*
11860 			 * Remove all notsack info to avoid confusion with
11861 			 * the next fast retrasnmit/recovery phase.
11862 			 */
11863 			if (tcp->tcp_snd_sack_ok &&
11864 			    tcp->tcp_notsack_list != NULL) {
11865 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
11866 				    tcp);
11867 			}
11868 		} else {
11869 			if (tcp->tcp_snd_sack_ok &&
11870 			    tcp->tcp_notsack_list != NULL) {
11871 				flags |= TH_NEED_SACK_REXMIT;
11872 				tcp->tcp_pipe -= mss;
11873 				if (tcp->tcp_pipe < 0)
11874 					tcp->tcp_pipe = 0;
11875 			} else {
11876 				/*
11877 				 * Hoe's algorithm:
11878 				 *
11879 				 * Retransmit the unack'ed segment and
11880 				 * restart fast recovery.  Note that we
11881 				 * need to scale back tcp_cwnd to the
11882 				 * original value when we started fast
11883 				 * recovery.  This is to prevent overly
11884 				 * aggressive behaviour in sending new
11885 				 * segments.
11886 				 */
11887 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
11888 				    tcps->tcps_dupack_fast_retransmit * mss;
11889 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
11890 				flags |= TH_REXMIT_NEEDED;
11891 			}
11892 		}
11893 	} else {
11894 		tcp->tcp_dupack_cnt = 0;
11895 		if (tcp->tcp_rexmit) {
11896 			/*
11897 			 * TCP is retranmitting.  If the ACK ack's all
11898 			 * outstanding data, update tcp_rexmit_max and
11899 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
11900 			 * to the correct value.
11901 			 *
11902 			 * Note that SEQ_LEQ() is used.  This is to avoid
11903 			 * unnecessary fast retransmit caused by dup ACKs
11904 			 * received when TCP does slow start retransmission
11905 			 * after a time out.  During this phase, TCP may
11906 			 * send out segments which are already received.
11907 			 * This causes dup ACKs to be sent back.
11908 			 */
11909 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
11910 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
11911 					tcp->tcp_rexmit_nxt = seg_ack;
11912 				}
11913 				if (seg_ack != tcp->tcp_rexmit_max) {
11914 					flags |= TH_XMIT_NEEDED;
11915 				}
11916 			} else {
11917 				tcp->tcp_rexmit = B_FALSE;
11918 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11919 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
11920 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11921 			}
11922 			tcp->tcp_ms_we_have_waited = 0;
11923 		}
11924 	}
11925 
11926 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
11927 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
11928 	tcp->tcp_suna = seg_ack;
11929 	if (tcp->tcp_zero_win_probe != 0) {
11930 		tcp->tcp_zero_win_probe = 0;
11931 		tcp->tcp_timer_backoff = 0;
11932 	}
11933 
11934 	/*
11935 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
11936 	 * Note that it cannot be the SYN being ack'ed.  The code flow
11937 	 * will not reach here.
11938 	 */
11939 	if (mp1 == NULL) {
11940 		goto fin_acked;
11941 	}
11942 
11943 	/*
11944 	 * Update the congestion window.
11945 	 *
11946 	 * If TCP is not ECN capable or TCP is ECN capable but the
11947 	 * congestion experience bit is not set, increase the tcp_cwnd as
11948 	 * usual.
11949 	 */
11950 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
11951 		cwnd = tcp->tcp_cwnd;
11952 		add = mss;
11953 
11954 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
11955 			/*
11956 			 * This is to prevent an increase of less than 1 MSS of
11957 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
11958 			 * may send out tinygrams in order to preserve mblk
11959 			 * boundaries.
11960 			 *
11961 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
11962 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
11963 			 * increased by 1 MSS for every RTTs.
11964 			 */
11965 			if (tcp->tcp_cwnd_cnt <= 0) {
11966 				tcp->tcp_cwnd_cnt = cwnd + add;
11967 			} else {
11968 				tcp->tcp_cwnd_cnt -= add;
11969 				add = 0;
11970 			}
11971 		}
11972 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
11973 	}
11974 
11975 	/* See if the latest urgent data has been acknowledged */
11976 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
11977 	    SEQ_GT(seg_ack, tcp->tcp_urg))
11978 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
11979 
11980 	/* Can we update the RTT estimates? */
11981 	if (tcp->tcp_snd_ts_ok) {
11982 		/* Ignore zero timestamp echo-reply. */
11983 		if (tcpopt.tcp_opt_ts_ecr != 0) {
11984 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
11985 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
11986 		}
11987 
11988 		/* If needed, restart the timer. */
11989 		if (tcp->tcp_set_timer == 1) {
11990 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11991 			tcp->tcp_set_timer = 0;
11992 		}
11993 		/*
11994 		 * Update tcp_csuna in case the other side stops sending
11995 		 * us timestamps.
11996 		 */
11997 		tcp->tcp_csuna = tcp->tcp_snxt;
11998 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
11999 		/*
12000 		 * An ACK sequence we haven't seen before, so get the RTT
12001 		 * and update the RTO. But first check if the timestamp is
12002 		 * valid to use.
12003 		 */
12004 		if ((mp1->b_next != NULL) &&
12005 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
12006 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
12007 			    (int32_t)(intptr_t)mp1->b_prev);
12008 		else
12009 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12010 
12011 		/* Remeber the last sequence to be ACKed */
12012 		tcp->tcp_csuna = seg_ack;
12013 		if (tcp->tcp_set_timer == 1) {
12014 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12015 			tcp->tcp_set_timer = 0;
12016 		}
12017 	} else {
12018 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12019 	}
12020 
12021 	/* Eat acknowledged bytes off the xmit queue. */
12022 	for (;;) {
12023 		mblk_t	*mp2;
12024 		uchar_t	*wptr;
12025 
12026 		wptr = mp1->b_wptr;
12027 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
12028 		bytes_acked -= (int)(wptr - mp1->b_rptr);
12029 		if (bytes_acked < 0) {
12030 			mp1->b_rptr = wptr + bytes_acked;
12031 			/*
12032 			 * Set a new timestamp if all the bytes timed by the
12033 			 * old timestamp have been ack'ed.
12034 			 */
12035 			if (SEQ_GT(seg_ack,
12036 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
12037 				mp1->b_prev =
12038 				    (mblk_t *)(uintptr_t)LBOLT_FASTPATH;
12039 				mp1->b_next = NULL;
12040 			}
12041 			break;
12042 		}
12043 		mp1->b_next = NULL;
12044 		mp1->b_prev = NULL;
12045 		mp2 = mp1;
12046 		mp1 = mp1->b_cont;
12047 
12048 		/*
12049 		 * This notification is required for some zero-copy
12050 		 * clients to maintain a copy semantic. After the data
12051 		 * is ack'ed, client is safe to modify or reuse the buffer.
12052 		 */
12053 		if (tcp->tcp_snd_zcopy_aware &&
12054 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
12055 			tcp_zcopy_notify(tcp);
12056 		freeb(mp2);
12057 		if (bytes_acked == 0) {
12058 			if (mp1 == NULL) {
12059 				/* Everything is ack'ed, clear the tail. */
12060 				tcp->tcp_xmit_tail = NULL;
12061 				/*
12062 				 * Cancel the timer unless we are still
12063 				 * waiting for an ACK for the FIN packet.
12064 				 */
12065 				if (tcp->tcp_timer_tid != 0 &&
12066 				    tcp->tcp_snxt == tcp->tcp_suna) {
12067 					(void) TCP_TIMER_CANCEL(tcp,
12068 					    tcp->tcp_timer_tid);
12069 					tcp->tcp_timer_tid = 0;
12070 				}
12071 				goto pre_swnd_update;
12072 			}
12073 			if (mp2 != tcp->tcp_xmit_tail)
12074 				break;
12075 			tcp->tcp_xmit_tail = mp1;
12076 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12077 			    (uintptr_t)INT_MAX);
12078 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
12079 			    mp1->b_rptr);
12080 			break;
12081 		}
12082 		if (mp1 == NULL) {
12083 			/*
12084 			 * More was acked but there is nothing more
12085 			 * outstanding.  This means that the FIN was
12086 			 * just acked or that we're talking to a clown.
12087 			 */
12088 fin_acked:
12089 			ASSERT(tcp->tcp_fin_sent);
12090 			tcp->tcp_xmit_tail = NULL;
12091 			if (tcp->tcp_fin_sent) {
12092 				/* FIN was acked - making progress */
12093 				if (!tcp->tcp_fin_acked)
12094 					tcp->tcp_ip_forward_progress = B_TRUE;
12095 				tcp->tcp_fin_acked = B_TRUE;
12096 				if (tcp->tcp_linger_tid != 0 &&
12097 				    TCP_TIMER_CANCEL(tcp,
12098 				    tcp->tcp_linger_tid) >= 0) {
12099 					tcp_stop_lingering(tcp);
12100 					freemsg(mp);
12101 					mp = NULL;
12102 				}
12103 			} else {
12104 				/*
12105 				 * We should never get here because
12106 				 * we have already checked that the
12107 				 * number of bytes ack'ed should be
12108 				 * smaller than or equal to what we
12109 				 * have sent so far (it is the
12110 				 * acceptability check of the ACK).
12111 				 * We can only get here if the send
12112 				 * queue is corrupted.
12113 				 *
12114 				 * Terminate the connection and
12115 				 * panic the system.  It is better
12116 				 * for us to panic instead of
12117 				 * continuing to avoid other disaster.
12118 				 */
12119 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
12120 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
12121 				panic("Memory corruption "
12122 				    "detected for connection %s.",
12123 				    tcp_display(tcp, NULL,
12124 				    DISP_ADDR_AND_PORT));
12125 				/*NOTREACHED*/
12126 			}
12127 			goto pre_swnd_update;
12128 		}
12129 		ASSERT(mp2 != tcp->tcp_xmit_tail);
12130 	}
12131 	if (tcp->tcp_unsent) {
12132 		flags |= TH_XMIT_NEEDED;
12133 	}
12134 pre_swnd_update:
12135 	tcp->tcp_xmit_head = mp1;
12136 swnd_update:
12137 	/*
12138 	 * The following check is different from most other implementations.
12139 	 * For bi-directional transfer, when segments are dropped, the
12140 	 * "normal" check will not accept a window update in those
12141 	 * retransmitted segemnts.  Failing to do that, TCP may send out
12142 	 * segments which are outside receiver's window.  As TCP accepts
12143 	 * the ack in those retransmitted segments, if the window update in
12144 	 * the same segment is not accepted, TCP will incorrectly calculates
12145 	 * that it can send more segments.  This can create a deadlock
12146 	 * with the receiver if its window becomes zero.
12147 	 */
12148 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
12149 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
12150 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
12151 		/*
12152 		 * The criteria for update is:
12153 		 *
12154 		 * 1. the segment acknowledges some data.  Or
12155 		 * 2. the segment is new, i.e. it has a higher seq num. Or
12156 		 * 3. the segment is not old and the advertised window is
12157 		 * larger than the previous advertised window.
12158 		 */
12159 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
12160 			flags |= TH_XMIT_NEEDED;
12161 		tcp->tcp_swnd = new_swnd;
12162 		if (new_swnd > tcp->tcp_max_swnd)
12163 			tcp->tcp_max_swnd = new_swnd;
12164 		tcp->tcp_swl1 = seg_seq;
12165 		tcp->tcp_swl2 = seg_ack;
12166 	}
12167 est:
12168 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
12169 
12170 		switch (tcp->tcp_state) {
12171 		case TCPS_FIN_WAIT_1:
12172 			if (tcp->tcp_fin_acked) {
12173 				tcp->tcp_state = TCPS_FIN_WAIT_2;
12174 				/*
12175 				 * We implement the non-standard BSD/SunOS
12176 				 * FIN_WAIT_2 flushing algorithm.
12177 				 * If there is no user attached to this
12178 				 * TCP endpoint, then this TCP struct
12179 				 * could hang around forever in FIN_WAIT_2
12180 				 * state if the peer forgets to send us
12181 				 * a FIN.  To prevent this, we wait only
12182 				 * 2*MSL (a convenient time value) for
12183 				 * the FIN to arrive.  If it doesn't show up,
12184 				 * we flush the TCP endpoint.  This algorithm,
12185 				 * though a violation of RFC-793, has worked
12186 				 * for over 10 years in BSD systems.
12187 				 * Note: SunOS 4.x waits 675 seconds before
12188 				 * flushing the FIN_WAIT_2 connection.
12189 				 */
12190 				TCP_TIMER_RESTART(tcp,
12191 				    tcps->tcps_fin_wait_2_flush_interval);
12192 			}
12193 			break;
12194 		case TCPS_FIN_WAIT_2:
12195 			break;	/* Shutdown hook? */
12196 		case TCPS_LAST_ACK:
12197 			freemsg(mp);
12198 			if (tcp->tcp_fin_acked) {
12199 				(void) tcp_clean_death(tcp, 0, 19);
12200 				return;
12201 			}
12202 			goto xmit_check;
12203 		case TCPS_CLOSING:
12204 			if (tcp->tcp_fin_acked)
12205 				SET_TIME_WAIT(tcps, tcp, connp);
12206 			/*FALLTHRU*/
12207 		case TCPS_CLOSE_WAIT:
12208 			freemsg(mp);
12209 			goto xmit_check;
12210 		default:
12211 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12212 			break;
12213 		}
12214 	}
12215 	if (flags & TH_FIN) {
12216 		/* Make sure we ack the fin */
12217 		flags |= TH_ACK_NEEDED;
12218 		if (!tcp->tcp_fin_rcvd) {
12219 			tcp->tcp_fin_rcvd = B_TRUE;
12220 			tcp->tcp_rnxt++;
12221 			tcpha = tcp->tcp_tcpha;
12222 			tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12223 
12224 			/*
12225 			 * Generate the ordrel_ind at the end unless we
12226 			 * are an eager guy.
12227 			 * In the eager case tcp_rsrv will do this when run
12228 			 * after tcp_accept is done.
12229 			 */
12230 			if (tcp->tcp_listener == NULL &&
12231 			    !TCP_IS_DETACHED(tcp) && !tcp->tcp_hard_binding)
12232 				flags |= TH_ORDREL_NEEDED;
12233 			switch (tcp->tcp_state) {
12234 			case TCPS_SYN_RCVD:
12235 			case TCPS_ESTABLISHED:
12236 				tcp->tcp_state = TCPS_CLOSE_WAIT;
12237 				/* Keepalive? */
12238 				break;
12239 			case TCPS_FIN_WAIT_1:
12240 				if (!tcp->tcp_fin_acked) {
12241 					tcp->tcp_state = TCPS_CLOSING;
12242 					break;
12243 				}
12244 				/* FALLTHRU */
12245 			case TCPS_FIN_WAIT_2:
12246 				SET_TIME_WAIT(tcps, tcp, connp);
12247 				if (seg_len) {
12248 					/*
12249 					 * implies data piggybacked on FIN.
12250 					 * break to handle data.
12251 					 */
12252 					break;
12253 				}
12254 				freemsg(mp);
12255 				goto ack_check;
12256 			}
12257 		}
12258 	}
12259 	if (mp == NULL)
12260 		goto xmit_check;
12261 	if (seg_len == 0) {
12262 		freemsg(mp);
12263 		goto xmit_check;
12264 	}
12265 	if (mp->b_rptr == mp->b_wptr) {
12266 		/*
12267 		 * The header has been consumed, so we remove the
12268 		 * zero-length mblk here.
12269 		 */
12270 		mp1 = mp;
12271 		mp = mp->b_cont;
12272 		freeb(mp1);
12273 	}
12274 update_ack:
12275 	tcpha = tcp->tcp_tcpha;
12276 	tcp->tcp_rack_cnt++;
12277 	{
12278 		uint32_t cur_max;
12279 
12280 		cur_max = tcp->tcp_rack_cur_max;
12281 		if (tcp->tcp_rack_cnt >= cur_max) {
12282 			/*
12283 			 * We have more unacked data than we should - send
12284 			 * an ACK now.
12285 			 */
12286 			flags |= TH_ACK_NEEDED;
12287 			cur_max++;
12288 			if (cur_max > tcp->tcp_rack_abs_max)
12289 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
12290 			else
12291 				tcp->tcp_rack_cur_max = cur_max;
12292 		} else if (TCP_IS_DETACHED(tcp)) {
12293 			/* We don't have an ACK timer for detached TCP. */
12294 			flags |= TH_ACK_NEEDED;
12295 		} else if (seg_len < mss) {
12296 			/*
12297 			 * If we get a segment that is less than an mss, and we
12298 			 * already have unacknowledged data, and the amount
12299 			 * unacknowledged is not a multiple of mss, then we
12300 			 * better generate an ACK now.  Otherwise, this may be
12301 			 * the tail piece of a transaction, and we would rather
12302 			 * wait for the response.
12303 			 */
12304 			uint32_t udif;
12305 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
12306 			    (uintptr_t)INT_MAX);
12307 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
12308 			if (udif && (udif % mss))
12309 				flags |= TH_ACK_NEEDED;
12310 			else
12311 				flags |= TH_ACK_TIMER_NEEDED;
12312 		} else {
12313 			/* Start delayed ack timer */
12314 			flags |= TH_ACK_TIMER_NEEDED;
12315 		}
12316 	}
12317 	tcp->tcp_rnxt += seg_len;
12318 	tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12319 
12320 	if (mp == NULL)
12321 		goto xmit_check;
12322 
12323 	/* Update SACK list */
12324 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
12325 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
12326 		    &(tcp->tcp_num_sack_blk));
12327 	}
12328 
12329 	if (tcp->tcp_urp_mp) {
12330 		tcp->tcp_urp_mp->b_cont = mp;
12331 		mp = tcp->tcp_urp_mp;
12332 		tcp->tcp_urp_mp = NULL;
12333 		/* Ready for a new signal. */
12334 		tcp->tcp_urp_last_valid = B_FALSE;
12335 #ifdef DEBUG
12336 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12337 		    "tcp_rput: sending exdata_ind %s",
12338 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12339 #endif /* DEBUG */
12340 	}
12341 
12342 	/*
12343 	 * Check for ancillary data changes compared to last segment.
12344 	 */
12345 	if (connp->conn_recv_ancillary.crb_all != 0) {
12346 		mp = tcp_input_add_ancillary(tcp, mp, &ipp, ira);
12347 		if (mp == NULL)
12348 			return;
12349 	}
12350 
12351 	if (tcp->tcp_listener != NULL || tcp->tcp_hard_binding) {
12352 		/*
12353 		 * Side queue inbound data until the accept happens.
12354 		 * tcp_accept/tcp_rput drains this when the accept happens.
12355 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
12356 		 * T_EXDATA_IND) it is queued on b_next.
12357 		 * XXX Make urgent data use this. Requires:
12358 		 *	Removing tcp_listener check for TH_URG
12359 		 *	Making M_PCPROTO and MARK messages skip the eager case
12360 		 */
12361 
12362 		if (tcp->tcp_kssl_pending) {
12363 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
12364 			    mblk_t *, mp);
12365 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12366 		} else {
12367 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12368 		}
12369 	} else if (IPCL_IS_NONSTR(connp)) {
12370 		/*
12371 		 * Non-STREAMS socket
12372 		 *
12373 		 * Note that no KSSL processing is done here, because
12374 		 * KSSL is not supported for non-STREAMS sockets.
12375 		 */
12376 		boolean_t push = flags & (TH_PUSH|TH_FIN);
12377 		int error;
12378 
12379 		if ((*connp->conn_upcalls->su_recv)(
12380 		    connp->conn_upper_handle,
12381 		    mp, seg_len, 0, &error, &push) <= 0) {
12382 			/*
12383 			 * We should never be in middle of a
12384 			 * fallback, the squeue guarantees that.
12385 			 */
12386 			ASSERT(error != EOPNOTSUPP);
12387 			if (error == ENOSPC)
12388 				tcp->tcp_rwnd -= seg_len;
12389 		} else if (push) {
12390 			/* PUSH bit set and sockfs is not flow controlled */
12391 			flags |= tcp_rwnd_reopen(tcp);
12392 		}
12393 	} else {
12394 		/* STREAMS socket */
12395 		if (mp->b_datap->db_type != M_DATA ||
12396 		    (flags & TH_MARKNEXT_NEEDED)) {
12397 			if (tcp->tcp_rcv_list != NULL) {
12398 				flags |= tcp_rcv_drain(tcp);
12399 			}
12400 			ASSERT(tcp->tcp_rcv_list == NULL ||
12401 			    tcp->tcp_fused_sigurg);
12402 
12403 			if (flags & TH_MARKNEXT_NEEDED) {
12404 #ifdef DEBUG
12405 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12406 				    "tcp_rput: sending MSGMARKNEXT %s",
12407 				    tcp_display(tcp, NULL,
12408 				    DISP_PORT_ONLY));
12409 #endif /* DEBUG */
12410 				mp->b_flag |= MSGMARKNEXT;
12411 				flags &= ~TH_MARKNEXT_NEEDED;
12412 			}
12413 
12414 			/* Does this need SSL processing first? */
12415 			if ((tcp->tcp_kssl_ctx != NULL) &&
12416 			    (DB_TYPE(mp) == M_DATA)) {
12417 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
12418 				    mblk_t *, mp);
12419 				tcp_kssl_input(tcp, mp, ira->ira_cred);
12420 			} else {
12421 				if (is_system_labeled())
12422 					tcp_setcred_data(mp, ira);
12423 
12424 				putnext(connp->conn_rq, mp);
12425 				if (!canputnext(connp->conn_rq))
12426 					tcp->tcp_rwnd -= seg_len;
12427 			}
12428 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
12429 		    (DB_TYPE(mp) == M_DATA)) {
12430 			/* Does this need SSL processing first? */
12431 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
12432 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12433 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
12434 		    tcp->tcp_rcv_cnt + seg_len >= connp->conn_rcvbuf >> 3) {
12435 			if (tcp->tcp_rcv_list != NULL) {
12436 				/*
12437 				 * Enqueue the new segment first and then
12438 				 * call tcp_rcv_drain() to send all data
12439 				 * up.  The other way to do this is to
12440 				 * send all queued data up and then call
12441 				 * putnext() to send the new segment up.
12442 				 * This way can remove the else part later
12443 				 * on.
12444 				 *
12445 				 * We don't do this to avoid one more call to
12446 				 * canputnext() as tcp_rcv_drain() needs to
12447 				 * call canputnext().
12448 				 */
12449 				tcp_rcv_enqueue(tcp, mp, seg_len,
12450 				    ira->ira_cred);
12451 				flags |= tcp_rcv_drain(tcp);
12452 			} else {
12453 				if (is_system_labeled())
12454 					tcp_setcred_data(mp, ira);
12455 
12456 				putnext(connp->conn_rq, mp);
12457 				if (!canputnext(connp->conn_rq))
12458 					tcp->tcp_rwnd -= seg_len;
12459 			}
12460 		} else {
12461 			/*
12462 			 * Enqueue all packets when processing an mblk
12463 			 * from the co queue and also enqueue normal packets.
12464 			 */
12465 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12466 		}
12467 		/*
12468 		 * Make sure the timer is running if we have data waiting
12469 		 * for a push bit. This provides resiliency against
12470 		 * implementations that do not correctly generate push bits.
12471 		 */
12472 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
12473 			/*
12474 			 * The connection may be closed at this point, so don't
12475 			 * do anything for a detached tcp.
12476 			 */
12477 			if (!TCP_IS_DETACHED(tcp))
12478 				tcp->tcp_push_tid = TCP_TIMER(tcp,
12479 				    tcp_push_timer,
12480 				    MSEC_TO_TICK(
12481 				    tcps->tcps_push_timer_interval));
12482 		}
12483 	}
12484 
12485 xmit_check:
12486 	/* Is there anything left to do? */
12487 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12488 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
12489 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
12490 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12491 		goto done;
12492 
12493 	/* Any transmit work to do and a non-zero window? */
12494 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
12495 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
12496 		if (flags & TH_REXMIT_NEEDED) {
12497 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
12498 
12499 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
12500 			if (snd_size > mss)
12501 				snd_size = mss;
12502 			if (snd_size > tcp->tcp_swnd)
12503 				snd_size = tcp->tcp_swnd;
12504 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
12505 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
12506 			    B_TRUE);
12507 
12508 			if (mp1 != NULL) {
12509 				tcp->tcp_xmit_head->b_prev =
12510 				    (mblk_t *)LBOLT_FASTPATH;
12511 				tcp->tcp_csuna = tcp->tcp_snxt;
12512 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12513 				UPDATE_MIB(&tcps->tcps_mib,
12514 				    tcpRetransBytes, snd_size);
12515 				tcp_send_data(tcp, mp1);
12516 			}
12517 		}
12518 		if (flags & TH_NEED_SACK_REXMIT) {
12519 			tcp_sack_rxmit(tcp, &flags);
12520 		}
12521 		/*
12522 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
12523 		 * out new segment.  Note that tcp_rexmit should not be
12524 		 * set, otherwise TH_LIMIT_XMIT should not be set.
12525 		 */
12526 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
12527 			if (!tcp->tcp_rexmit) {
12528 				tcp_wput_data(tcp, NULL, B_FALSE);
12529 			} else {
12530 				tcp_ss_rexmit(tcp);
12531 			}
12532 		}
12533 		/*
12534 		 * Adjust tcp_cwnd back to normal value after sending
12535 		 * new data segments.
12536 		 */
12537 		if (flags & TH_LIMIT_XMIT) {
12538 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
12539 			/*
12540 			 * This will restart the timer.  Restarting the
12541 			 * timer is used to avoid a timeout before the
12542 			 * limited transmitted segment's ACK gets back.
12543 			 */
12544 			if (tcp->tcp_xmit_head != NULL)
12545 				tcp->tcp_xmit_head->b_prev =
12546 				    (mblk_t *)LBOLT_FASTPATH;
12547 		}
12548 
12549 		/* Anything more to do? */
12550 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
12551 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12552 			goto done;
12553 	}
12554 ack_check:
12555 	if (flags & TH_SEND_URP_MARK) {
12556 		ASSERT(tcp->tcp_urp_mark_mp);
12557 		ASSERT(!IPCL_IS_NONSTR(connp));
12558 		/*
12559 		 * Send up any queued data and then send the mark message
12560 		 */
12561 		if (tcp->tcp_rcv_list != NULL) {
12562 			flags |= tcp_rcv_drain(tcp);
12563 
12564 		}
12565 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12566 		mp1 = tcp->tcp_urp_mark_mp;
12567 		tcp->tcp_urp_mark_mp = NULL;
12568 		if (is_system_labeled())
12569 			tcp_setcred_data(mp1, ira);
12570 
12571 		putnext(connp->conn_rq, mp1);
12572 #ifdef DEBUG
12573 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12574 		    "tcp_rput: sending zero-length %s %s",
12575 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
12576 		    "MSGNOTMARKNEXT"),
12577 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12578 #endif /* DEBUG */
12579 		flags &= ~TH_SEND_URP_MARK;
12580 	}
12581 	if (flags & TH_ACK_NEEDED) {
12582 		/*
12583 		 * Time to send an ack for some reason.
12584 		 */
12585 		mp1 = tcp_ack_mp(tcp);
12586 
12587 		if (mp1 != NULL) {
12588 			tcp_send_data(tcp, mp1);
12589 			BUMP_LOCAL(tcp->tcp_obsegs);
12590 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
12591 		}
12592 		if (tcp->tcp_ack_tid != 0) {
12593 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
12594 			tcp->tcp_ack_tid = 0;
12595 		}
12596 	}
12597 	if (flags & TH_ACK_TIMER_NEEDED) {
12598 		/*
12599 		 * Arrange for deferred ACK or push wait timeout.
12600 		 * Start timer if it is not already running.
12601 		 */
12602 		if (tcp->tcp_ack_tid == 0) {
12603 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
12604 			    MSEC_TO_TICK(tcp->tcp_localnet ?
12605 			    (clock_t)tcps->tcps_local_dack_interval :
12606 			    (clock_t)tcps->tcps_deferred_ack_interval));
12607 		}
12608 	}
12609 	if (flags & TH_ORDREL_NEEDED) {
12610 		/*
12611 		 * Send up the ordrel_ind unless we are an eager guy.
12612 		 * In the eager case tcp_rsrv will do this when run
12613 		 * after tcp_accept is done.
12614 		 */
12615 		ASSERT(tcp->tcp_listener == NULL);
12616 		ASSERT(!tcp->tcp_detached);
12617 
12618 		if (IPCL_IS_NONSTR(connp)) {
12619 			ASSERT(tcp->tcp_ordrel_mp == NULL);
12620 			tcp->tcp_ordrel_done = B_TRUE;
12621 			(*connp->conn_upcalls->su_opctl)
12622 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
12623 			goto done;
12624 		}
12625 
12626 		if (tcp->tcp_rcv_list != NULL) {
12627 			/*
12628 			 * Push any mblk(s) enqueued from co processing.
12629 			 */
12630 			flags |= tcp_rcv_drain(tcp);
12631 		}
12632 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12633 
12634 		mp1 = tcp->tcp_ordrel_mp;
12635 		tcp->tcp_ordrel_mp = NULL;
12636 		tcp->tcp_ordrel_done = B_TRUE;
12637 		putnext(connp->conn_rq, mp1);
12638 	}
12639 done:
12640 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12641 }
12642 
12643 /*
12644  * This routine adjusts next-to-send sequence number variables, in the
12645  * case where the reciever has shrunk it's window.
12646  */
12647 static void
12648 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
12649 {
12650 	mblk_t *xmit_tail;
12651 	int32_t offset;
12652 
12653 	tcp->tcp_snxt = snxt;
12654 
12655 	/* Get the mblk, and the offset in it, as per the shrunk window */
12656 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
12657 	ASSERT(xmit_tail != NULL);
12658 	tcp->tcp_xmit_tail = xmit_tail;
12659 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
12660 	    xmit_tail->b_rptr - offset;
12661 }
12662 
12663 /*
12664  * This function does PAWS protection check. Returns B_TRUE if the
12665  * segment passes the PAWS test, else returns B_FALSE.
12666  */
12667 boolean_t
12668 tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp)
12669 {
12670 	uint8_t	flags;
12671 	int	options;
12672 	uint8_t *up;
12673 	conn_t	*connp = tcp->tcp_connp;
12674 
12675 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
12676 	/*
12677 	 * If timestamp option is aligned nicely, get values inline,
12678 	 * otherwise call general routine to parse.  Only do that
12679 	 * if timestamp is the only option.
12680 	 */
12681 	if (TCP_HDR_LENGTH(tcpha) == (uint32_t)TCP_MIN_HEADER_LENGTH +
12682 	    TCPOPT_REAL_TS_LEN &&
12683 	    OK_32PTR((up = ((uint8_t *)tcpha) +
12684 	    TCP_MIN_HEADER_LENGTH)) &&
12685 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
12686 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
12687 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
12688 
12689 		options = TCP_OPT_TSTAMP_PRESENT;
12690 	} else {
12691 		if (tcp->tcp_snd_sack_ok) {
12692 			tcpoptp->tcp = tcp;
12693 		} else {
12694 			tcpoptp->tcp = NULL;
12695 		}
12696 		options = tcp_parse_options(tcpha, tcpoptp);
12697 	}
12698 
12699 	if (options & TCP_OPT_TSTAMP_PRESENT) {
12700 		/*
12701 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
12702 		 * regardless of the timestamp, page 18 RFC 1323.bis.
12703 		 */
12704 		if ((flags & TH_RST) == 0 &&
12705 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
12706 		    tcp->tcp_ts_recent)) {
12707 			if (TSTMP_LT(LBOLT_FASTPATH64,
12708 			    tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) {
12709 				/* This segment is not acceptable. */
12710 				return (B_FALSE);
12711 			} else {
12712 				/*
12713 				 * Connection has been idle for
12714 				 * too long.  Reset the timestamp
12715 				 * and assume the segment is valid.
12716 				 */
12717 				tcp->tcp_ts_recent =
12718 				    tcpoptp->tcp_opt_ts_val;
12719 			}
12720 		}
12721 	} else {
12722 		/*
12723 		 * If we don't get a timestamp on every packet, we
12724 		 * figure we can't really trust 'em, so we stop sending
12725 		 * and parsing them.
12726 		 */
12727 		tcp->tcp_snd_ts_ok = B_FALSE;
12728 
12729 		connp->conn_ht_iphc_len -= TCPOPT_REAL_TS_LEN;
12730 		connp->conn_ht_ulp_len -= TCPOPT_REAL_TS_LEN;
12731 		tcp->tcp_tcpha->tha_offset_and_reserved -= (3 << 4);
12732 		/*
12733 		 * Adjust the tcp_mss and tcp_cwnd accordingly. We avoid
12734 		 * doing a slow start here so as to not to lose on the
12735 		 * transfer rate built up so far.
12736 		 */
12737 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
12738 		if (tcp->tcp_snd_sack_ok) {
12739 			ASSERT(tcp->tcp_sack_info != NULL);
12740 			tcp->tcp_max_sack_blk = 4;
12741 		}
12742 	}
12743 	return (B_TRUE);
12744 }
12745 
12746 /*
12747  * Attach ancillary data to a received TCP segments for the
12748  * ancillary pieces requested by the application that are
12749  * different than they were in the previous data segment.
12750  *
12751  * Save the "current" values once memory allocation is ok so that
12752  * when memory allocation fails we can just wait for the next data segment.
12753  */
12754 static mblk_t *
12755 tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
12756     ip_recv_attr_t *ira)
12757 {
12758 	struct T_optdata_ind *todi;
12759 	int optlen;
12760 	uchar_t *optptr;
12761 	struct T_opthdr *toh;
12762 	crb_t addflag;	/* Which pieces to add */
12763 	mblk_t *mp1;
12764 	conn_t	*connp = tcp->tcp_connp;
12765 
12766 	optlen = 0;
12767 	addflag.crb_all = 0;
12768 	/* If app asked for pktinfo and the index has changed ... */
12769 	if (connp->conn_recv_ancillary.crb_ip_recvpktinfo &&
12770 	    ira->ira_ruifindex != tcp->tcp_recvifindex) {
12771 		optlen += sizeof (struct T_opthdr) +
12772 		    sizeof (struct in6_pktinfo);
12773 		addflag.crb_ip_recvpktinfo = 1;
12774 	}
12775 	/* If app asked for hoplimit and it has changed ... */
12776 	if (connp->conn_recv_ancillary.crb_ipv6_recvhoplimit &&
12777 	    ipp->ipp_hoplimit != tcp->tcp_recvhops) {
12778 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12779 		addflag.crb_ipv6_recvhoplimit = 1;
12780 	}
12781 	/* If app asked for tclass and it has changed ... */
12782 	if (connp->conn_recv_ancillary.crb_ipv6_recvtclass &&
12783 	    ipp->ipp_tclass != tcp->tcp_recvtclass) {
12784 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12785 		addflag.crb_ipv6_recvtclass = 1;
12786 	}
12787 	/*
12788 	 * If app asked for hopbyhop headers and it has changed ...
12789 	 * For security labels, note that (1) security labels can't change on
12790 	 * a connected socket at all, (2) we're connected to at most one peer,
12791 	 * (3) if anything changes, then it must be some other extra option.
12792 	 */
12793 	if (connp->conn_recv_ancillary.crb_ipv6_recvhopopts &&
12794 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
12795 	    (ipp->ipp_fields & IPPF_HOPOPTS),
12796 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
12797 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
12798 		addflag.crb_ipv6_recvhopopts = 1;
12799 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
12800 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
12801 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
12802 			return (mp);
12803 	}
12804 	/* If app asked for dst headers before routing headers ... */
12805 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdrdstopts &&
12806 	    ip_cmpbuf(tcp->tcp_rthdrdstopts, tcp->tcp_rthdrdstoptslen,
12807 	    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12808 	    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen)) {
12809 		optlen += sizeof (struct T_opthdr) +
12810 		    ipp->ipp_rthdrdstoptslen;
12811 		addflag.crb_ipv6_recvrthdrdstopts = 1;
12812 		if (!ip_allocbuf((void **)&tcp->tcp_rthdrdstopts,
12813 		    &tcp->tcp_rthdrdstoptslen,
12814 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12815 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen))
12816 			return (mp);
12817 	}
12818 	/* If app asked for routing headers and it has changed ... */
12819 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdr &&
12820 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
12821 	    (ipp->ipp_fields & IPPF_RTHDR),
12822 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
12823 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
12824 		addflag.crb_ipv6_recvrthdr = 1;
12825 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
12826 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
12827 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
12828 			return (mp);
12829 	}
12830 	/* If app asked for dest headers and it has changed ... */
12831 	if ((connp->conn_recv_ancillary.crb_ipv6_recvdstopts ||
12832 	    connp->conn_recv_ancillary.crb_old_ipv6_recvdstopts) &&
12833 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
12834 	    (ipp->ipp_fields & IPPF_DSTOPTS),
12835 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
12836 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
12837 		addflag.crb_ipv6_recvdstopts = 1;
12838 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
12839 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
12840 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
12841 			return (mp);
12842 	}
12843 
12844 	if (optlen == 0) {
12845 		/* Nothing to add */
12846 		return (mp);
12847 	}
12848 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
12849 	if (mp1 == NULL) {
12850 		/*
12851 		 * Defer sending ancillary data until the next TCP segment
12852 		 * arrives.
12853 		 */
12854 		return (mp);
12855 	}
12856 	mp1->b_cont = mp;
12857 	mp = mp1;
12858 	mp->b_wptr += sizeof (*todi) + optlen;
12859 	mp->b_datap->db_type = M_PROTO;
12860 	todi = (struct T_optdata_ind *)mp->b_rptr;
12861 	todi->PRIM_type = T_OPTDATA_IND;
12862 	todi->DATA_flag = 1;	/* MORE data */
12863 	todi->OPT_length = optlen;
12864 	todi->OPT_offset = sizeof (*todi);
12865 	optptr = (uchar_t *)&todi[1];
12866 	/*
12867 	 * If app asked for pktinfo and the index has changed ...
12868 	 * Note that the local address never changes for the connection.
12869 	 */
12870 	if (addflag.crb_ip_recvpktinfo) {
12871 		struct in6_pktinfo *pkti;
12872 		uint_t ifindex;
12873 
12874 		ifindex = ira->ira_ruifindex;
12875 		toh = (struct T_opthdr *)optptr;
12876 		toh->level = IPPROTO_IPV6;
12877 		toh->name = IPV6_PKTINFO;
12878 		toh->len = sizeof (*toh) + sizeof (*pkti);
12879 		toh->status = 0;
12880 		optptr += sizeof (*toh);
12881 		pkti = (struct in6_pktinfo *)optptr;
12882 		pkti->ipi6_addr = connp->conn_laddr_v6;
12883 		pkti->ipi6_ifindex = ifindex;
12884 		optptr += sizeof (*pkti);
12885 		ASSERT(OK_32PTR(optptr));
12886 		/* Save as "last" value */
12887 		tcp->tcp_recvifindex = ifindex;
12888 	}
12889 	/* If app asked for hoplimit and it has changed ... */
12890 	if (addflag.crb_ipv6_recvhoplimit) {
12891 		toh = (struct T_opthdr *)optptr;
12892 		toh->level = IPPROTO_IPV6;
12893 		toh->name = IPV6_HOPLIMIT;
12894 		toh->len = sizeof (*toh) + sizeof (uint_t);
12895 		toh->status = 0;
12896 		optptr += sizeof (*toh);
12897 		*(uint_t *)optptr = ipp->ipp_hoplimit;
12898 		optptr += sizeof (uint_t);
12899 		ASSERT(OK_32PTR(optptr));
12900 		/* Save as "last" value */
12901 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
12902 	}
12903 	/* If app asked for tclass and it has changed ... */
12904 	if (addflag.crb_ipv6_recvtclass) {
12905 		toh = (struct T_opthdr *)optptr;
12906 		toh->level = IPPROTO_IPV6;
12907 		toh->name = IPV6_TCLASS;
12908 		toh->len = sizeof (*toh) + sizeof (uint_t);
12909 		toh->status = 0;
12910 		optptr += sizeof (*toh);
12911 		*(uint_t *)optptr = ipp->ipp_tclass;
12912 		optptr += sizeof (uint_t);
12913 		ASSERT(OK_32PTR(optptr));
12914 		/* Save as "last" value */
12915 		tcp->tcp_recvtclass = ipp->ipp_tclass;
12916 	}
12917 	if (addflag.crb_ipv6_recvhopopts) {
12918 		toh = (struct T_opthdr *)optptr;
12919 		toh->level = IPPROTO_IPV6;
12920 		toh->name = IPV6_HOPOPTS;
12921 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
12922 		toh->status = 0;
12923 		optptr += sizeof (*toh);
12924 		bcopy((uchar_t *)ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
12925 		optptr += ipp->ipp_hopoptslen;
12926 		ASSERT(OK_32PTR(optptr));
12927 		/* Save as last value */
12928 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
12929 		    (ipp->ipp_fields & IPPF_HOPOPTS),
12930 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
12931 	}
12932 	if (addflag.crb_ipv6_recvrthdrdstopts) {
12933 		toh = (struct T_opthdr *)optptr;
12934 		toh->level = IPPROTO_IPV6;
12935 		toh->name = IPV6_RTHDRDSTOPTS;
12936 		toh->len = sizeof (*toh) + ipp->ipp_rthdrdstoptslen;
12937 		toh->status = 0;
12938 		optptr += sizeof (*toh);
12939 		bcopy(ipp->ipp_rthdrdstopts, optptr, ipp->ipp_rthdrdstoptslen);
12940 		optptr += ipp->ipp_rthdrdstoptslen;
12941 		ASSERT(OK_32PTR(optptr));
12942 		/* Save as last value */
12943 		ip_savebuf((void **)&tcp->tcp_rthdrdstopts,
12944 		    &tcp->tcp_rthdrdstoptslen,
12945 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12946 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
12947 	}
12948 	if (addflag.crb_ipv6_recvrthdr) {
12949 		toh = (struct T_opthdr *)optptr;
12950 		toh->level = IPPROTO_IPV6;
12951 		toh->name = IPV6_RTHDR;
12952 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
12953 		toh->status = 0;
12954 		optptr += sizeof (*toh);
12955 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
12956 		optptr += ipp->ipp_rthdrlen;
12957 		ASSERT(OK_32PTR(optptr));
12958 		/* Save as last value */
12959 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
12960 		    (ipp->ipp_fields & IPPF_RTHDR),
12961 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
12962 	}
12963 	if (addflag.crb_ipv6_recvdstopts) {
12964 		toh = (struct T_opthdr *)optptr;
12965 		toh->level = IPPROTO_IPV6;
12966 		toh->name = IPV6_DSTOPTS;
12967 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
12968 		toh->status = 0;
12969 		optptr += sizeof (*toh);
12970 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
12971 		optptr += ipp->ipp_dstoptslen;
12972 		ASSERT(OK_32PTR(optptr));
12973 		/* Save as last value */
12974 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
12975 		    (ipp->ipp_fields & IPPF_DSTOPTS),
12976 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
12977 	}
12978 	ASSERT(optptr == mp->b_wptr);
12979 	return (mp);
12980 }
12981 
12982 /* ARGSUSED */
12983 static void
12984 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
12985 {
12986 	conn_t	*connp = (conn_t *)arg;
12987 	tcp_t	*tcp = connp->conn_tcp;
12988 	queue_t	*q = connp->conn_rq;
12989 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12990 
12991 	ASSERT(!IPCL_IS_NONSTR(connp));
12992 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
12993 	tcp->tcp_rsrv_mp = mp;
12994 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
12995 
12996 	TCP_STAT(tcps, tcp_rsrv_calls);
12997 
12998 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
12999 		return;
13000 	}
13001 
13002 	if (tcp->tcp_fused) {
13003 		tcp_fuse_backenable(tcp);
13004 		return;
13005 	}
13006 
13007 	if (canputnext(q)) {
13008 		/* Not flow-controlled, open rwnd */
13009 		tcp->tcp_rwnd = connp->conn_rcvbuf;
13010 
13011 		/*
13012 		 * Send back a window update immediately if TCP is above
13013 		 * ESTABLISHED state and the increase of the rcv window
13014 		 * that the other side knows is at least 1 MSS after flow
13015 		 * control is lifted.
13016 		 */
13017 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
13018 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
13019 			tcp_xmit_ctl(NULL, tcp,
13020 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
13021 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
13022 		}
13023 	}
13024 }
13025 
13026 /*
13027  * The read side service routine is called mostly when we get back-enabled as a
13028  * result of flow control relief.  Since we don't actually queue anything in
13029  * TCP, we have no data to send out of here.  What we do is clear the receive
13030  * window, and send out a window update.
13031  */
13032 static void
13033 tcp_rsrv(queue_t *q)
13034 {
13035 	conn_t		*connp = Q_TO_CONN(q);
13036 	tcp_t		*tcp = connp->conn_tcp;
13037 	mblk_t		*mp;
13038 
13039 	/* No code does a putq on the read side */
13040 	ASSERT(q->q_first == NULL);
13041 
13042 	/*
13043 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
13044 	 * been run.  So just return.
13045 	 */
13046 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
13047 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
13048 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
13049 		return;
13050 	}
13051 	tcp->tcp_rsrv_mp = NULL;
13052 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
13053 
13054 	CONN_INC_REF(connp);
13055 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
13056 	    NULL, SQ_PROCESS, SQTAG_TCP_RSRV);
13057 }
13058 
13059 /*
13060  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
13061  * We do not allow the receive window to shrink.  After setting rwnd,
13062  * set the flow control hiwat of the stream.
13063  *
13064  * This function is called in 2 cases:
13065  *
13066  * 1) Before data transfer begins, in tcp_input_listener() for accepting a
13067  *    connection (passive open) and in tcp_input_data() for active connect.
13068  *    This is called after tcp_mss_set() when the desired MSS value is known.
13069  *    This makes sure that our window size is a mutiple of the other side's
13070  *    MSS.
13071  * 2) Handling SO_RCVBUF option.
13072  *
13073  * It is ASSUMED that the requested size is a multiple of the current MSS.
13074  *
13075  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
13076  * user requests so.
13077  */
13078 int
13079 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
13080 {
13081 	uint32_t	mss = tcp->tcp_mss;
13082 	uint32_t	old_max_rwnd;
13083 	uint32_t	max_transmittable_rwnd;
13084 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
13085 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13086 	conn_t		*connp = tcp->tcp_connp;
13087 
13088 	/*
13089 	 * Insist on a receive window that is at least
13090 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
13091 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
13092 	 * and delayed acknowledgement.
13093 	 */
13094 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
13095 
13096 	if (tcp->tcp_fused) {
13097 		size_t sth_hiwat;
13098 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
13099 
13100 		ASSERT(peer_tcp != NULL);
13101 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
13102 		if (!tcp_detached) {
13103 			(void) proto_set_rx_hiwat(connp->conn_rq, connp,
13104 			    sth_hiwat);
13105 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
13106 		}
13107 
13108 		/* Caller could have changed tcp_rwnd; update tha_win */
13109 		if (tcp->tcp_tcpha != NULL) {
13110 			tcp->tcp_tcpha->tha_win =
13111 			    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13112 		}
13113 		if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13114 			tcp->tcp_cwnd_max = rwnd;
13115 
13116 		/*
13117 		 * In the fusion case, the maxpsz stream head value of
13118 		 * our peer is set according to its send buffer size
13119 		 * and our receive buffer size; since the latter may
13120 		 * have changed we need to update the peer's maxpsz.
13121 		 */
13122 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
13123 		return (sth_hiwat);
13124 	}
13125 
13126 	if (tcp_detached)
13127 		old_max_rwnd = tcp->tcp_rwnd;
13128 	else
13129 		old_max_rwnd = connp->conn_rcvbuf;
13130 
13131 
13132 	/*
13133 	 * If window size info has already been exchanged, TCP should not
13134 	 * shrink the window.  Shrinking window is doable if done carefully.
13135 	 * We may add that support later.  But so far there is not a real
13136 	 * need to do that.
13137 	 */
13138 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
13139 		/* MSS may have changed, do a round up again. */
13140 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
13141 	}
13142 
13143 	/*
13144 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
13145 	 * can be applied even before the window scale option is decided.
13146 	 */
13147 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
13148 	if (rwnd > max_transmittable_rwnd) {
13149 		rwnd = max_transmittable_rwnd -
13150 		    (max_transmittable_rwnd % mss);
13151 		if (rwnd < mss)
13152 			rwnd = max_transmittable_rwnd;
13153 		/*
13154 		 * If we're over the limit we may have to back down tcp_rwnd.
13155 		 * The increment below won't work for us. So we set all three
13156 		 * here and the increment below will have no effect.
13157 		 */
13158 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
13159 	}
13160 	if (tcp->tcp_localnet) {
13161 		tcp->tcp_rack_abs_max =
13162 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
13163 	} else {
13164 		/*
13165 		 * For a remote host on a different subnet (through a router),
13166 		 * we ack every other packet to be conforming to RFC1122.
13167 		 * tcp_deferred_acks_max is default to 2.
13168 		 */
13169 		tcp->tcp_rack_abs_max =
13170 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
13171 	}
13172 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
13173 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
13174 	else
13175 		tcp->tcp_rack_cur_max = 0;
13176 	/*
13177 	 * Increment the current rwnd by the amount the maximum grew (we
13178 	 * can not overwrite it since we might be in the middle of a
13179 	 * connection.)
13180 	 */
13181 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
13182 	connp->conn_rcvbuf = rwnd;
13183 
13184 	/* Are we already connected? */
13185 	if (tcp->tcp_tcpha != NULL) {
13186 		tcp->tcp_tcpha->tha_win =
13187 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13188 	}
13189 
13190 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13191 		tcp->tcp_cwnd_max = rwnd;
13192 
13193 	if (tcp_detached)
13194 		return (rwnd);
13195 
13196 	tcp_set_recv_threshold(tcp, rwnd >> 3);
13197 
13198 	(void) proto_set_rx_hiwat(connp->conn_rq, connp, rwnd);
13199 	return (rwnd);
13200 }
13201 
13202 /*
13203  * Return SNMP stuff in buffer in mpdata.
13204  */
13205 mblk_t *
13206 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
13207 {
13208 	mblk_t			*mpdata;
13209 	mblk_t			*mp_conn_ctl = NULL;
13210 	mblk_t			*mp_conn_tail;
13211 	mblk_t			*mp_attr_ctl = NULL;
13212 	mblk_t			*mp_attr_tail;
13213 	mblk_t			*mp6_conn_ctl = NULL;
13214 	mblk_t			*mp6_conn_tail;
13215 	mblk_t			*mp6_attr_ctl = NULL;
13216 	mblk_t			*mp6_attr_tail;
13217 	struct opthdr		*optp;
13218 	mib2_tcpConnEntry_t	tce;
13219 	mib2_tcp6ConnEntry_t	tce6;
13220 	mib2_transportMLPEntry_t mlp;
13221 	connf_t			*connfp;
13222 	int			i;
13223 	boolean_t 		ispriv;
13224 	zoneid_t 		zoneid;
13225 	int			v4_conn_idx;
13226 	int			v6_conn_idx;
13227 	conn_t			*connp = Q_TO_CONN(q);
13228 	tcp_stack_t		*tcps;
13229 	ip_stack_t		*ipst;
13230 	mblk_t			*mp2ctl;
13231 
13232 	/*
13233 	 * make a copy of the original message
13234 	 */
13235 	mp2ctl = copymsg(mpctl);
13236 
13237 	if (mpctl == NULL ||
13238 	    (mpdata = mpctl->b_cont) == NULL ||
13239 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
13240 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
13241 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
13242 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
13243 		freemsg(mp_conn_ctl);
13244 		freemsg(mp_attr_ctl);
13245 		freemsg(mp6_conn_ctl);
13246 		freemsg(mp6_attr_ctl);
13247 		freemsg(mpctl);
13248 		freemsg(mp2ctl);
13249 		return (NULL);
13250 	}
13251 
13252 	ipst = connp->conn_netstack->netstack_ip;
13253 	tcps = connp->conn_netstack->netstack_tcp;
13254 
13255 	/* build table of connections -- need count in fixed part */
13256 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
13257 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
13258 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
13259 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
13260 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
13261 
13262 	ispriv =
13263 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
13264 	zoneid = Q_TO_CONN(q)->conn_zoneid;
13265 
13266 	v4_conn_idx = v6_conn_idx = 0;
13267 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
13268 
13269 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
13270 		ipst = tcps->tcps_netstack->netstack_ip;
13271 
13272 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
13273 
13274 		connp = NULL;
13275 
13276 		while ((connp =
13277 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
13278 			tcp_t *tcp;
13279 			boolean_t needattr;
13280 
13281 			if (connp->conn_zoneid != zoneid)
13282 				continue;	/* not in this zone */
13283 
13284 			tcp = connp->conn_tcp;
13285 			UPDATE_MIB(&tcps->tcps_mib,
13286 			    tcpHCInSegs, tcp->tcp_ibsegs);
13287 			tcp->tcp_ibsegs = 0;
13288 			UPDATE_MIB(&tcps->tcps_mib,
13289 			    tcpHCOutSegs, tcp->tcp_obsegs);
13290 			tcp->tcp_obsegs = 0;
13291 
13292 			tce6.tcp6ConnState = tce.tcpConnState =
13293 			    tcp_snmp_state(tcp);
13294 			if (tce.tcpConnState == MIB2_TCP_established ||
13295 			    tce.tcpConnState == MIB2_TCP_closeWait)
13296 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
13297 
13298 			needattr = B_FALSE;
13299 			bzero(&mlp, sizeof (mlp));
13300 			if (connp->conn_mlp_type != mlptSingle) {
13301 				if (connp->conn_mlp_type == mlptShared ||
13302 				    connp->conn_mlp_type == mlptBoth)
13303 					mlp.tme_flags |= MIB2_TMEF_SHARED;
13304 				if (connp->conn_mlp_type == mlptPrivate ||
13305 				    connp->conn_mlp_type == mlptBoth)
13306 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
13307 				needattr = B_TRUE;
13308 			}
13309 			if (connp->conn_anon_mlp) {
13310 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
13311 				needattr = B_TRUE;
13312 			}
13313 			switch (connp->conn_mac_mode) {
13314 			case CONN_MAC_DEFAULT:
13315 				break;
13316 			case CONN_MAC_AWARE:
13317 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
13318 				needattr = B_TRUE;
13319 				break;
13320 			case CONN_MAC_IMPLICIT:
13321 				mlp.tme_flags |= MIB2_TMEF_MACIMPLICIT;
13322 				needattr = B_TRUE;
13323 				break;
13324 			}
13325 			if (connp->conn_ixa->ixa_tsl != NULL) {
13326 				ts_label_t *tsl;
13327 
13328 				tsl = connp->conn_ixa->ixa_tsl;
13329 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
13330 				mlp.tme_doi = label2doi(tsl);
13331 				mlp.tme_label = *label2bslabel(tsl);
13332 				needattr = B_TRUE;
13333 			}
13334 
13335 			/* Create a message to report on IPv6 entries */
13336 			if (connp->conn_ipversion == IPV6_VERSION) {
13337 			tce6.tcp6ConnLocalAddress = connp->conn_laddr_v6;
13338 			tce6.tcp6ConnRemAddress = connp->conn_faddr_v6;
13339 			tce6.tcp6ConnLocalPort = ntohs(connp->conn_lport);
13340 			tce6.tcp6ConnRemPort = ntohs(connp->conn_fport);
13341 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET) {
13342 				tce6.tcp6ConnIfIndex =
13343 				    connp->conn_ixa->ixa_scopeid;
13344 			} else {
13345 				tce6.tcp6ConnIfIndex = connp->conn_bound_if;
13346 			}
13347 			/* Don't want just anybody seeing these... */
13348 			if (ispriv) {
13349 				tce6.tcp6ConnEntryInfo.ce_snxt =
13350 				    tcp->tcp_snxt;
13351 				tce6.tcp6ConnEntryInfo.ce_suna =
13352 				    tcp->tcp_suna;
13353 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13354 				    tcp->tcp_rnxt;
13355 				tce6.tcp6ConnEntryInfo.ce_rack =
13356 				    tcp->tcp_rack;
13357 			} else {
13358 				/*
13359 				 * Netstat, unfortunately, uses this to
13360 				 * get send/receive queue sizes.  How to fix?
13361 				 * Why not compute the difference only?
13362 				 */
13363 				tce6.tcp6ConnEntryInfo.ce_snxt =
13364 				    tcp->tcp_snxt - tcp->tcp_suna;
13365 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
13366 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13367 				    tcp->tcp_rnxt - tcp->tcp_rack;
13368 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
13369 			}
13370 
13371 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13372 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13373 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
13374 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
13375 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
13376 
13377 			tce6.tcp6ConnCreationProcess =
13378 			    (connp->conn_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
13379 			    connp->conn_cpid;
13380 			tce6.tcp6ConnCreationTime = connp->conn_open_time;
13381 
13382 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
13383 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
13384 
13385 			mlp.tme_connidx = v6_conn_idx++;
13386 			if (needattr)
13387 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
13388 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
13389 			}
13390 			/*
13391 			 * Create an IPv4 table entry for IPv4 entries and also
13392 			 * for IPv6 entries which are bound to in6addr_any
13393 			 * but don't have IPV6_V6ONLY set.
13394 			 * (i.e. anything an IPv4 peer could connect to)
13395 			 */
13396 			if (connp->conn_ipversion == IPV4_VERSION ||
13397 			    (tcp->tcp_state <= TCPS_LISTEN &&
13398 			    !connp->conn_ipv6_v6only &&
13399 			    IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6))) {
13400 				if (connp->conn_ipversion == IPV6_VERSION) {
13401 					tce.tcpConnRemAddress = INADDR_ANY;
13402 					tce.tcpConnLocalAddress = INADDR_ANY;
13403 				} else {
13404 					tce.tcpConnRemAddress =
13405 					    connp->conn_faddr_v4;
13406 					tce.tcpConnLocalAddress =
13407 					    connp->conn_laddr_v4;
13408 				}
13409 				tce.tcpConnLocalPort = ntohs(connp->conn_lport);
13410 				tce.tcpConnRemPort = ntohs(connp->conn_fport);
13411 				/* Don't want just anybody seeing these... */
13412 				if (ispriv) {
13413 					tce.tcpConnEntryInfo.ce_snxt =
13414 					    tcp->tcp_snxt;
13415 					tce.tcpConnEntryInfo.ce_suna =
13416 					    tcp->tcp_suna;
13417 					tce.tcpConnEntryInfo.ce_rnxt =
13418 					    tcp->tcp_rnxt;
13419 					tce.tcpConnEntryInfo.ce_rack =
13420 					    tcp->tcp_rack;
13421 				} else {
13422 					/*
13423 					 * Netstat, unfortunately, uses this to
13424 					 * get send/receive queue sizes.  How
13425 					 * to fix?
13426 					 * Why not compute the difference only?
13427 					 */
13428 					tce.tcpConnEntryInfo.ce_snxt =
13429 					    tcp->tcp_snxt - tcp->tcp_suna;
13430 					tce.tcpConnEntryInfo.ce_suna = 0;
13431 					tce.tcpConnEntryInfo.ce_rnxt =
13432 					    tcp->tcp_rnxt - tcp->tcp_rack;
13433 					tce.tcpConnEntryInfo.ce_rack = 0;
13434 				}
13435 
13436 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13437 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13438 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
13439 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
13440 				tce.tcpConnEntryInfo.ce_state =
13441 				    tcp->tcp_state;
13442 
13443 				tce.tcpConnCreationProcess =
13444 				    (connp->conn_cpid < 0) ?
13445 				    MIB2_UNKNOWN_PROCESS :
13446 				    connp->conn_cpid;
13447 				tce.tcpConnCreationTime = connp->conn_open_time;
13448 
13449 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
13450 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
13451 
13452 				mlp.tme_connidx = v4_conn_idx++;
13453 				if (needattr)
13454 					(void) snmp_append_data2(
13455 					    mp_attr_ctl->b_cont,
13456 					    &mp_attr_tail, (char *)&mlp,
13457 					    sizeof (mlp));
13458 			}
13459 		}
13460 	}
13461 
13462 	/* fixed length structure for IPv4 and IPv6 counters */
13463 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
13464 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
13465 	    sizeof (mib2_tcp6ConnEntry_t));
13466 	/* synchronize 32- and 64-bit counters */
13467 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
13468 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
13469 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
13470 	optp->level = MIB2_TCP;
13471 	optp->name = 0;
13472 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
13473 	    sizeof (tcps->tcps_mib));
13474 	optp->len = msgdsize(mpdata);
13475 	qreply(q, mpctl);
13476 
13477 	/* table of connections... */
13478 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
13479 	    sizeof (struct T_optmgmt_ack)];
13480 	optp->level = MIB2_TCP;
13481 	optp->name = MIB2_TCP_CONN;
13482 	optp->len = msgdsize(mp_conn_ctl->b_cont);
13483 	qreply(q, mp_conn_ctl);
13484 
13485 	/* table of MLP attributes... */
13486 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
13487 	    sizeof (struct T_optmgmt_ack)];
13488 	optp->level = MIB2_TCP;
13489 	optp->name = EXPER_XPORT_MLP;
13490 	optp->len = msgdsize(mp_attr_ctl->b_cont);
13491 	if (optp->len == 0)
13492 		freemsg(mp_attr_ctl);
13493 	else
13494 		qreply(q, mp_attr_ctl);
13495 
13496 	/* table of IPv6 connections... */
13497 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
13498 	    sizeof (struct T_optmgmt_ack)];
13499 	optp->level = MIB2_TCP6;
13500 	optp->name = MIB2_TCP6_CONN;
13501 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
13502 	qreply(q, mp6_conn_ctl);
13503 
13504 	/* table of IPv6 MLP attributes... */
13505 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
13506 	    sizeof (struct T_optmgmt_ack)];
13507 	optp->level = MIB2_TCP6;
13508 	optp->name = EXPER_XPORT_MLP;
13509 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
13510 	if (optp->len == 0)
13511 		freemsg(mp6_attr_ctl);
13512 	else
13513 		qreply(q, mp6_attr_ctl);
13514 	return (mp2ctl);
13515 }
13516 
13517 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
13518 /* ARGSUSED */
13519 int
13520 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
13521 {
13522 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
13523 
13524 	switch (level) {
13525 	case MIB2_TCP:
13526 		switch (name) {
13527 		case 13:
13528 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
13529 				return (0);
13530 			/* TODO: delete entry defined by tce */
13531 			return (1);
13532 		default:
13533 			return (0);
13534 		}
13535 	default:
13536 		return (1);
13537 	}
13538 }
13539 
13540 /* Translate TCP state to MIB2 TCP state. */
13541 static int
13542 tcp_snmp_state(tcp_t *tcp)
13543 {
13544 	if (tcp == NULL)
13545 		return (0);
13546 
13547 	switch (tcp->tcp_state) {
13548 	case TCPS_CLOSED:
13549 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
13550 	case TCPS_BOUND:
13551 		return (MIB2_TCP_closed);
13552 	case TCPS_LISTEN:
13553 		return (MIB2_TCP_listen);
13554 	case TCPS_SYN_SENT:
13555 		return (MIB2_TCP_synSent);
13556 	case TCPS_SYN_RCVD:
13557 		return (MIB2_TCP_synReceived);
13558 	case TCPS_ESTABLISHED:
13559 		return (MIB2_TCP_established);
13560 	case TCPS_CLOSE_WAIT:
13561 		return (MIB2_TCP_closeWait);
13562 	case TCPS_FIN_WAIT_1:
13563 		return (MIB2_TCP_finWait1);
13564 	case TCPS_CLOSING:
13565 		return (MIB2_TCP_closing);
13566 	case TCPS_LAST_ACK:
13567 		return (MIB2_TCP_lastAck);
13568 	case TCPS_FIN_WAIT_2:
13569 		return (MIB2_TCP_finWait2);
13570 	case TCPS_TIME_WAIT:
13571 		return (MIB2_TCP_timeWait);
13572 	default:
13573 		return (0);
13574 	}
13575 }
13576 
13577 /*
13578  * tcp_timer is the timer service routine.  It handles the retransmission,
13579  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
13580  * from the state of the tcp instance what kind of action needs to be done
13581  * at the time it is called.
13582  */
13583 static void
13584 tcp_timer(void *arg)
13585 {
13586 	mblk_t		*mp;
13587 	clock_t		first_threshold;
13588 	clock_t		second_threshold;
13589 	clock_t		ms;
13590 	uint32_t	mss;
13591 	conn_t		*connp = (conn_t *)arg;
13592 	tcp_t		*tcp = connp->conn_tcp;
13593 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13594 
13595 	tcp->tcp_timer_tid = 0;
13596 
13597 	if (tcp->tcp_fused)
13598 		return;
13599 
13600 	first_threshold =  tcp->tcp_first_timer_threshold;
13601 	second_threshold = tcp->tcp_second_timer_threshold;
13602 	switch (tcp->tcp_state) {
13603 	case TCPS_IDLE:
13604 	case TCPS_BOUND:
13605 	case TCPS_LISTEN:
13606 		return;
13607 	case TCPS_SYN_RCVD: {
13608 		tcp_t	*listener = tcp->tcp_listener;
13609 
13610 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
13611 			/* it's our first timeout */
13612 			tcp->tcp_syn_rcvd_timeout = 1;
13613 			mutex_enter(&listener->tcp_eager_lock);
13614 			listener->tcp_syn_rcvd_timeout++;
13615 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
13616 				/*
13617 				 * Make this eager available for drop if we
13618 				 * need to drop one to accomodate a new
13619 				 * incoming SYN request.
13620 				 */
13621 				MAKE_DROPPABLE(listener, tcp);
13622 			}
13623 			if (!listener->tcp_syn_defense &&
13624 			    (listener->tcp_syn_rcvd_timeout >
13625 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
13626 			    (tcps->tcps_conn_req_max_q0 > 200)) {
13627 				/* We may be under attack. Put on a defense. */
13628 				listener->tcp_syn_defense = B_TRUE;
13629 				cmn_err(CE_WARN, "High TCP connect timeout "
13630 				    "rate! System (port %d) may be under a "
13631 				    "SYN flood attack!",
13632 				    ntohs(listener->tcp_connp->conn_lport));
13633 
13634 				listener->tcp_ip_addr_cache = kmem_zalloc(
13635 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
13636 				    KM_NOSLEEP);
13637 			}
13638 			mutex_exit(&listener->tcp_eager_lock);
13639 		} else if (listener != NULL) {
13640 			mutex_enter(&listener->tcp_eager_lock);
13641 			tcp->tcp_syn_rcvd_timeout++;
13642 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
13643 			    !tcp->tcp_closemp_used) {
13644 				/*
13645 				 * This is our second timeout. Put the tcp in
13646 				 * the list of droppable eagers to allow it to
13647 				 * be dropped, if needed. We don't check
13648 				 * whether tcp_dontdrop is set or not to
13649 				 * protect ourselve from a SYN attack where a
13650 				 * remote host can spoof itself as one of the
13651 				 * good IP source and continue to hold
13652 				 * resources too long.
13653 				 */
13654 				MAKE_DROPPABLE(listener, tcp);
13655 			}
13656 			mutex_exit(&listener->tcp_eager_lock);
13657 		}
13658 	}
13659 		/* FALLTHRU */
13660 	case TCPS_SYN_SENT:
13661 		first_threshold =  tcp->tcp_first_ctimer_threshold;
13662 		second_threshold = tcp->tcp_second_ctimer_threshold;
13663 		break;
13664 	case TCPS_ESTABLISHED:
13665 	case TCPS_FIN_WAIT_1:
13666 	case TCPS_CLOSING:
13667 	case TCPS_CLOSE_WAIT:
13668 	case TCPS_LAST_ACK:
13669 		/* If we have data to rexmit */
13670 		if (tcp->tcp_suna != tcp->tcp_snxt) {
13671 			clock_t	time_to_wait;
13672 
13673 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
13674 			if (!tcp->tcp_xmit_head)
13675 				break;
13676 			time_to_wait = ddi_get_lbolt() -
13677 			    (clock_t)tcp->tcp_xmit_head->b_prev;
13678 			time_to_wait = tcp->tcp_rto -
13679 			    TICK_TO_MSEC(time_to_wait);
13680 			/*
13681 			 * If the timer fires too early, 1 clock tick earlier,
13682 			 * restart the timer.
13683 			 */
13684 			if (time_to_wait > msec_per_tick) {
13685 				TCP_STAT(tcps, tcp_timer_fire_early);
13686 				TCP_TIMER_RESTART(tcp, time_to_wait);
13687 				return;
13688 			}
13689 			/*
13690 			 * When we probe zero windows, we force the swnd open.
13691 			 * If our peer acks with a closed window swnd will be
13692 			 * set to zero by tcp_rput(). As long as we are
13693 			 * receiving acks tcp_rput will
13694 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
13695 			 * first and second interval actions.  NOTE: the timer
13696 			 * interval is allowed to continue its exponential
13697 			 * backoff.
13698 			 */
13699 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
13700 				if (connp->conn_debug) {
13701 					(void) strlog(TCP_MOD_ID, 0, 1,
13702 					    SL_TRACE, "tcp_timer: zero win");
13703 				}
13704 			} else {
13705 				/*
13706 				 * After retransmission, we need to do
13707 				 * slow start.  Set the ssthresh to one
13708 				 * half of current effective window and
13709 				 * cwnd to one MSS.  Also reset
13710 				 * tcp_cwnd_cnt.
13711 				 *
13712 				 * Note that if tcp_ssthresh is reduced because
13713 				 * of ECN, do not reduce it again unless it is
13714 				 * already one window of data away (tcp_cwr
13715 				 * should then be cleared) or this is a
13716 				 * timeout for a retransmitted segment.
13717 				 */
13718 				uint32_t npkt;
13719 
13720 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
13721 					npkt = ((tcp->tcp_timer_backoff ?
13722 					    tcp->tcp_cwnd_ssthresh :
13723 					    tcp->tcp_snxt -
13724 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
13725 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13726 					    tcp->tcp_mss;
13727 				}
13728 				tcp->tcp_cwnd = tcp->tcp_mss;
13729 				tcp->tcp_cwnd_cnt = 0;
13730 				if (tcp->tcp_ecn_ok) {
13731 					tcp->tcp_cwr = B_TRUE;
13732 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13733 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13734 				}
13735 			}
13736 			break;
13737 		}
13738 		/*
13739 		 * We have something to send yet we cannot send.  The
13740 		 * reason can be:
13741 		 *
13742 		 * 1. Zero send window: we need to do zero window probe.
13743 		 * 2. Zero cwnd: because of ECN, we need to "clock out
13744 		 * segments.
13745 		 * 3. SWS avoidance: receiver may have shrunk window,
13746 		 * reset our knowledge.
13747 		 *
13748 		 * Note that condition 2 can happen with either 1 or
13749 		 * 3.  But 1 and 3 are exclusive.
13750 		 */
13751 		if (tcp->tcp_unsent != 0) {
13752 			/*
13753 			 * Should not hold the zero-copy messages for too long.
13754 			 */
13755 			if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13756 				tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13757 				    tcp->tcp_xmit_head, B_TRUE);
13758 
13759 			if (tcp->tcp_cwnd == 0) {
13760 				/*
13761 				 * Set tcp_cwnd to 1 MSS so that a
13762 				 * new segment can be sent out.  We
13763 				 * are "clocking out" new data when
13764 				 * the network is really congested.
13765 				 */
13766 				ASSERT(tcp->tcp_ecn_ok);
13767 				tcp->tcp_cwnd = tcp->tcp_mss;
13768 			}
13769 			if (tcp->tcp_swnd == 0) {
13770 				/* Extend window for zero window probe */
13771 				tcp->tcp_swnd++;
13772 				tcp->tcp_zero_win_probe = B_TRUE;
13773 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
13774 			} else {
13775 				/*
13776 				 * Handle timeout from sender SWS avoidance.
13777 				 * Reset our knowledge of the max send window
13778 				 * since the receiver might have reduced its
13779 				 * receive buffer.  Avoid setting tcp_max_swnd
13780 				 * to one since that will essentially disable
13781 				 * the SWS checks.
13782 				 *
13783 				 * Note that since we don't have a SWS
13784 				 * state variable, if the timeout is set
13785 				 * for ECN but not for SWS, this
13786 				 * code will also be executed.  This is
13787 				 * fine as tcp_max_swnd is updated
13788 				 * constantly and it will not affect
13789 				 * anything.
13790 				 */
13791 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
13792 			}
13793 			tcp_wput_data(tcp, NULL, B_FALSE);
13794 			return;
13795 		}
13796 		/* Is there a FIN that needs to be to re retransmitted? */
13797 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13798 		    !tcp->tcp_fin_acked)
13799 			break;
13800 		/* Nothing to do, return without restarting timer. */
13801 		TCP_STAT(tcps, tcp_timer_fire_miss);
13802 		return;
13803 	case TCPS_FIN_WAIT_2:
13804 		/*
13805 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
13806 		 * We waited some time for for peer's FIN, but it hasn't
13807 		 * arrived.  We flush the connection now to avoid
13808 		 * case where the peer has rebooted.
13809 		 */
13810 		if (TCP_IS_DETACHED(tcp)) {
13811 			(void) tcp_clean_death(tcp, 0, 23);
13812 		} else {
13813 			TCP_TIMER_RESTART(tcp,
13814 			    tcps->tcps_fin_wait_2_flush_interval);
13815 		}
13816 		return;
13817 	case TCPS_TIME_WAIT:
13818 		(void) tcp_clean_death(tcp, 0, 24);
13819 		return;
13820 	default:
13821 		if (connp->conn_debug) {
13822 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
13823 			    "tcp_timer: strange state (%d) %s",
13824 			    tcp->tcp_state, tcp_display(tcp, NULL,
13825 			    DISP_PORT_ONLY));
13826 		}
13827 		return;
13828 	}
13829 
13830 	/*
13831 	 * If the system is under memory pressure or the max number of
13832 	 * connections have been established for the listener, be more
13833 	 * aggressive in aborting connections.
13834 	 */
13835 	if (tcps->tcps_reclaim || (tcp->tcp_listen_cnt != NULL &&
13836 	    tcp->tcp_listen_cnt->tlc_cnt > tcp->tcp_listen_cnt->tlc_max)) {
13837 		second_threshold = tcp_early_abort * SECONDS;
13838 	}
13839 
13840 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
13841 		/*
13842 		 * Should not hold the zero-copy messages for too long.
13843 		 */
13844 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13845 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13846 			    tcp->tcp_xmit_head, B_TRUE);
13847 
13848 		/*
13849 		 * For zero window probe, we need to send indefinitely,
13850 		 * unless we have not heard from the other side for some
13851 		 * time...
13852 		 */
13853 		if ((tcp->tcp_zero_win_probe == 0) ||
13854 		    (TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time) >
13855 		    second_threshold)) {
13856 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
13857 			/*
13858 			 * If TCP is in SYN_RCVD state, send back a
13859 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
13860 			 * should be zero in TCPS_SYN_RCVD state.
13861 			 */
13862 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
13863 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
13864 				    "in SYN_RCVD",
13865 				    tcp, tcp->tcp_snxt,
13866 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
13867 			}
13868 			(void) tcp_clean_death(tcp,
13869 			    tcp->tcp_client_errno ?
13870 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
13871 			return;
13872 		} else {
13873 			/*
13874 			 * If the system is under memory pressure, we also
13875 			 * abort connection in zero window probing.
13876 			 */
13877 			if (tcps->tcps_reclaim) {
13878 				(void) tcp_clean_death(tcp,
13879 				    tcp->tcp_client_errno ?
13880 				    tcp->tcp_client_errno : ETIMEDOUT, 25);
13881 				return;
13882 			}
13883 			/*
13884 			 * Set tcp_ms_we_have_waited to second_threshold
13885 			 * so that in next timeout, we will do the above
13886 			 * check (ddi_get_lbolt() - tcp_last_recv_time).
13887 			 * This is also to avoid overflow.
13888 			 *
13889 			 * We don't need to decrement tcp_timer_backoff
13890 			 * to avoid overflow because it will be decremented
13891 			 * later if new timeout value is greater than
13892 			 * tcp_rexmit_interval_max.  In the case when
13893 			 * tcp_rexmit_interval_max is greater than
13894 			 * second_threshold, it means that we will wait
13895 			 * longer than second_threshold to send the next
13896 			 * window probe.
13897 			 */
13898 			tcp->tcp_ms_we_have_waited = second_threshold;
13899 		}
13900 	} else if (ms > first_threshold) {
13901 		/*
13902 		 * Should not hold the zero-copy messages for too long.
13903 		 */
13904 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13905 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13906 			    tcp->tcp_xmit_head, B_TRUE);
13907 
13908 		/*
13909 		 * We have been retransmitting for too long...  The RTT
13910 		 * we calculated is probably incorrect.  Reinitialize it.
13911 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
13912 		 * tcp_rtt_update so that we won't accidentally cache a
13913 		 * bad value.  But only do this if this is not a zero
13914 		 * window probe.
13915 		 */
13916 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
13917 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
13918 			    (tcp->tcp_rtt_sa >> 5);
13919 			tcp->tcp_rtt_sa = 0;
13920 			tcp_ip_notify(tcp);
13921 			tcp->tcp_rtt_update = 0;
13922 		}
13923 	}
13924 	tcp->tcp_timer_backoff++;
13925 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
13926 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
13927 	    tcps->tcps_rexmit_interval_min) {
13928 		/*
13929 		 * This means the original RTO is tcp_rexmit_interval_min.
13930 		 * So we will use tcp_rexmit_interval_min as the RTO value
13931 		 * and do the backoff.
13932 		 */
13933 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
13934 	} else {
13935 		ms <<= tcp->tcp_timer_backoff;
13936 	}
13937 	if (ms > tcps->tcps_rexmit_interval_max) {
13938 		ms = tcps->tcps_rexmit_interval_max;
13939 		/*
13940 		 * ms is at max, decrement tcp_timer_backoff to avoid
13941 		 * overflow.
13942 		 */
13943 		tcp->tcp_timer_backoff--;
13944 	}
13945 	tcp->tcp_ms_we_have_waited += ms;
13946 	if (tcp->tcp_zero_win_probe == 0) {
13947 		tcp->tcp_rto = ms;
13948 	}
13949 	TCP_TIMER_RESTART(tcp, ms);
13950 	/*
13951 	 * This is after a timeout and tcp_rto is backed off.  Set
13952 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
13953 	 * restart the timer with a correct value.
13954 	 */
13955 	tcp->tcp_set_timer = 1;
13956 	mss = tcp->tcp_snxt - tcp->tcp_suna;
13957 	if (mss > tcp->tcp_mss)
13958 		mss = tcp->tcp_mss;
13959 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
13960 		mss = tcp->tcp_swnd;
13961 
13962 	if ((mp = tcp->tcp_xmit_head) != NULL)
13963 		mp->b_prev = (mblk_t *)ddi_get_lbolt();
13964 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
13965 	    B_TRUE);
13966 
13967 	/*
13968 	 * When slow start after retransmission begins, start with
13969 	 * this seq no.  tcp_rexmit_max marks the end of special slow
13970 	 * start phase.  tcp_snd_burst controls how many segments
13971 	 * can be sent because of an ack.
13972 	 */
13973 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13974 	tcp->tcp_snd_burst = TCP_CWND_SS;
13975 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13976 	    (tcp->tcp_unsent == 0)) {
13977 		tcp->tcp_rexmit_max = tcp->tcp_fss;
13978 	} else {
13979 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
13980 	}
13981 	tcp->tcp_rexmit = B_TRUE;
13982 	tcp->tcp_dupack_cnt = 0;
13983 
13984 	/*
13985 	 * Remove all rexmit SACK blk to start from fresh.
13986 	 */
13987 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
13988 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
13989 	if (mp == NULL) {
13990 		return;
13991 	}
13992 
13993 	tcp->tcp_csuna = tcp->tcp_snxt;
13994 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
13995 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
13996 	tcp_send_data(tcp, mp);
13997 
13998 }
13999 
14000 static int
14001 tcp_do_unbind(conn_t *connp)
14002 {
14003 	tcp_t *tcp = connp->conn_tcp;
14004 
14005 	switch (tcp->tcp_state) {
14006 	case TCPS_BOUND:
14007 	case TCPS_LISTEN:
14008 		break;
14009 	default:
14010 		return (-TOUTSTATE);
14011 	}
14012 
14013 	/*
14014 	 * Need to clean up all the eagers since after the unbind, segments
14015 	 * will no longer be delivered to this listener stream.
14016 	 */
14017 	mutex_enter(&tcp->tcp_eager_lock);
14018 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
14019 		tcp_eager_cleanup(tcp, 0);
14020 	}
14021 	mutex_exit(&tcp->tcp_eager_lock);
14022 
14023 	/* Clean up the listener connection counter if necessary. */
14024 	if (tcp->tcp_listen_cnt != NULL)
14025 		TCP_DECR_LISTEN_CNT(tcp);
14026 	connp->conn_laddr_v6 = ipv6_all_zeros;
14027 	connp->conn_saddr_v6 = ipv6_all_zeros;
14028 	tcp_bind_hash_remove(tcp);
14029 	tcp->tcp_state = TCPS_IDLE;
14030 
14031 	ip_unbind(connp);
14032 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
14033 
14034 	return (0);
14035 }
14036 
14037 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
14038 static void
14039 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
14040 {
14041 	conn_t *connp = tcp->tcp_connp;
14042 	int error;
14043 
14044 	error = tcp_do_unbind(connp);
14045 	if (error > 0) {
14046 		tcp_err_ack(tcp, mp, TSYSERR, error);
14047 	} else if (error < 0) {
14048 		tcp_err_ack(tcp, mp, -error, 0);
14049 	} else {
14050 		/* Send M_FLUSH according to TPI */
14051 		(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
14052 
14053 		mp = mi_tpi_ok_ack_alloc(mp);
14054 		if (mp != NULL)
14055 			putnext(connp->conn_rq, mp);
14056 	}
14057 }
14058 
14059 /*
14060  * Don't let port fall into the privileged range.
14061  * Since the extra privileged ports can be arbitrary we also
14062  * ensure that we exclude those from consideration.
14063  * tcp_g_epriv_ports is not sorted thus we loop over it until
14064  * there are no changes.
14065  *
14066  * Note: No locks are held when inspecting tcp_g_*epriv_ports
14067  * but instead the code relies on:
14068  * - the fact that the address of the array and its size never changes
14069  * - the atomic assignment of the elements of the array
14070  *
14071  * Returns 0 if there are no more ports available.
14072  *
14073  * TS note: skip multilevel ports.
14074  */
14075 static in_port_t
14076 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
14077 {
14078 	int i;
14079 	boolean_t restart = B_FALSE;
14080 	tcp_stack_t *tcps = tcp->tcp_tcps;
14081 
14082 	if (random && tcp_random_anon_port != 0) {
14083 		(void) random_get_pseudo_bytes((uint8_t *)&port,
14084 		    sizeof (in_port_t));
14085 		/*
14086 		 * Unless changed by a sys admin, the smallest anon port
14087 		 * is 32768 and the largest anon port is 65535.  It is
14088 		 * very likely (50%) for the random port to be smaller
14089 		 * than the smallest anon port.  When that happens,
14090 		 * add port % (anon port range) to the smallest anon
14091 		 * port to get the random port.  It should fall into the
14092 		 * valid anon port range.
14093 		 */
14094 		if (port < tcps->tcps_smallest_anon_port) {
14095 			port = tcps->tcps_smallest_anon_port +
14096 			    port % (tcps->tcps_largest_anon_port -
14097 			    tcps->tcps_smallest_anon_port);
14098 		}
14099 	}
14100 
14101 retry:
14102 	if (port < tcps->tcps_smallest_anon_port)
14103 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14104 
14105 	if (port > tcps->tcps_largest_anon_port) {
14106 		if (restart)
14107 			return (0);
14108 		restart = B_TRUE;
14109 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14110 	}
14111 
14112 	if (port < tcps->tcps_smallest_nonpriv_port)
14113 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
14114 
14115 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
14116 		if (port == tcps->tcps_g_epriv_ports[i]) {
14117 			port++;
14118 			/*
14119 			 * Make sure whether the port is in the
14120 			 * valid range.
14121 			 */
14122 			goto retry;
14123 		}
14124 	}
14125 	if (is_system_labeled() &&
14126 	    (i = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred), port,
14127 	    IPPROTO_TCP, B_TRUE)) != 0) {
14128 		port = i;
14129 		goto retry;
14130 	}
14131 	return (port);
14132 }
14133 
14134 /*
14135  * Return the next anonymous port in the privileged port range for
14136  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
14137  * downwards.  This is the same behavior as documented in the userland
14138  * library call rresvport(3N).
14139  *
14140  * TS note: skip multilevel ports.
14141  */
14142 static in_port_t
14143 tcp_get_next_priv_port(const tcp_t *tcp)
14144 {
14145 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
14146 	in_port_t nextport;
14147 	boolean_t restart = B_FALSE;
14148 	tcp_stack_t *tcps = tcp->tcp_tcps;
14149 retry:
14150 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
14151 	    next_priv_port >= IPPORT_RESERVED) {
14152 		next_priv_port = IPPORT_RESERVED - 1;
14153 		if (restart)
14154 			return (0);
14155 		restart = B_TRUE;
14156 	}
14157 	if (is_system_labeled() &&
14158 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred),
14159 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
14160 		next_priv_port = nextport;
14161 		goto retry;
14162 	}
14163 	return (next_priv_port--);
14164 }
14165 
14166 /* The write side r/w procedure. */
14167 
14168 #if CCS_STATS
14169 struct {
14170 	struct {
14171 		int64_t count, bytes;
14172 	} tot, hit;
14173 } wrw_stats;
14174 #endif
14175 
14176 /*
14177  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
14178  * messages.
14179  */
14180 /* ARGSUSED */
14181 static void
14182 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14183 {
14184 	conn_t	*connp = (conn_t *)arg;
14185 	tcp_t	*tcp = connp->conn_tcp;
14186 
14187 	ASSERT(DB_TYPE(mp) != M_IOCTL);
14188 	/*
14189 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
14190 	 * Once the close starts, streamhead and sockfs will not let any data
14191 	 * packets come down (close ensures that there are no threads using the
14192 	 * queue and no new threads will come down) but since qprocsoff()
14193 	 * hasn't happened yet, a M_FLUSH or some non data message might
14194 	 * get reflected back (in response to our own FLUSHRW) and get
14195 	 * processed after tcp_close() is done. The conn would still be valid
14196 	 * because a ref would have added but we need to check the state
14197 	 * before actually processing the packet.
14198 	 */
14199 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
14200 		freemsg(mp);
14201 		return;
14202 	}
14203 
14204 	switch (DB_TYPE(mp)) {
14205 	case M_IOCDATA:
14206 		tcp_wput_iocdata(tcp, mp);
14207 		break;
14208 	case M_FLUSH:
14209 		tcp_wput_flush(tcp, mp);
14210 		break;
14211 	default:
14212 		ip_wput_nondata(connp->conn_wq, mp);
14213 		break;
14214 	}
14215 }
14216 
14217 /*
14218  * The TCP fast path write put procedure.
14219  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
14220  */
14221 /* ARGSUSED */
14222 void
14223 tcp_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14224 {
14225 	int		len;
14226 	int		hdrlen;
14227 	int		plen;
14228 	mblk_t		*mp1;
14229 	uchar_t		*rptr;
14230 	uint32_t	snxt;
14231 	tcpha_t		*tcpha;
14232 	struct datab	*db;
14233 	uint32_t	suna;
14234 	uint32_t	mss;
14235 	ipaddr_t	*dst;
14236 	ipaddr_t	*src;
14237 	uint32_t	sum;
14238 	int		usable;
14239 	conn_t		*connp = (conn_t *)arg;
14240 	tcp_t		*tcp = connp->conn_tcp;
14241 	uint32_t	msize;
14242 	tcp_stack_t	*tcps = tcp->tcp_tcps;
14243 	ip_xmit_attr_t	*ixa;
14244 	clock_t		now;
14245 
14246 	/*
14247 	 * Try and ASSERT the minimum possible references on the
14248 	 * conn early enough. Since we are executing on write side,
14249 	 * the connection is obviously not detached and that means
14250 	 * there is a ref each for TCP and IP. Since we are behind
14251 	 * the squeue, the minimum references needed are 3. If the
14252 	 * conn is in classifier hash list, there should be an
14253 	 * extra ref for that (we check both the possibilities).
14254 	 */
14255 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14256 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14257 
14258 	ASSERT(DB_TYPE(mp) == M_DATA);
14259 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
14260 
14261 	mutex_enter(&tcp->tcp_non_sq_lock);
14262 	tcp->tcp_squeue_bytes -= msize;
14263 	mutex_exit(&tcp->tcp_non_sq_lock);
14264 
14265 	/* Bypass tcp protocol for fused tcp loopback */
14266 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
14267 		return;
14268 
14269 	mss = tcp->tcp_mss;
14270 	/*
14271 	 * If ZEROCOPY has turned off, try not to send any zero-copy message
14272 	 * down. Do backoff, now.
14273 	 */
14274 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on)
14275 		mp = tcp_zcopy_backoff(tcp, mp, B_FALSE);
14276 
14277 
14278 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
14279 	len = (int)(mp->b_wptr - mp->b_rptr);
14280 
14281 	/*
14282 	 * Criteria for fast path:
14283 	 *
14284 	 *   1. no unsent data
14285 	 *   2. single mblk in request
14286 	 *   3. connection established
14287 	 *   4. data in mblk
14288 	 *   5. len <= mss
14289 	 *   6. no tcp_valid bits
14290 	 */
14291 	if ((tcp->tcp_unsent != 0) ||
14292 	    (tcp->tcp_cork) ||
14293 	    (mp->b_cont != NULL) ||
14294 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
14295 	    (len == 0) ||
14296 	    (len > mss) ||
14297 	    (tcp->tcp_valid_bits != 0)) {
14298 		tcp_wput_data(tcp, mp, B_FALSE);
14299 		return;
14300 	}
14301 
14302 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
14303 	ASSERT(tcp->tcp_fin_sent == 0);
14304 
14305 	/* queue new packet onto retransmission queue */
14306 	if (tcp->tcp_xmit_head == NULL) {
14307 		tcp->tcp_xmit_head = mp;
14308 	} else {
14309 		tcp->tcp_xmit_last->b_cont = mp;
14310 	}
14311 	tcp->tcp_xmit_last = mp;
14312 	tcp->tcp_xmit_tail = mp;
14313 
14314 	/* find out how much we can send */
14315 	/* BEGIN CSTYLED */
14316 	/*
14317 	 *    un-acked	   usable
14318 	 *  |--------------|-----------------|
14319 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
14320 	 */
14321 	/* END CSTYLED */
14322 
14323 	/* start sending from tcp_snxt */
14324 	snxt = tcp->tcp_snxt;
14325 
14326 	/*
14327 	 * Check to see if this connection has been idled for some
14328 	 * time and no ACK is expected.  If it is, we need to slow
14329 	 * start again to get back the connection's "self-clock" as
14330 	 * described in VJ's paper.
14331 	 *
14332 	 * Reinitialize tcp_cwnd after idle.
14333 	 */
14334 	now = LBOLT_FASTPATH;
14335 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
14336 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
14337 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
14338 	}
14339 
14340 	usable = tcp->tcp_swnd;		/* tcp window size */
14341 	if (usable > tcp->tcp_cwnd)
14342 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
14343 	usable -= snxt;		/* subtract stuff already sent */
14344 	suna = tcp->tcp_suna;
14345 	usable += suna;
14346 	/* usable can be < 0 if the congestion window is smaller */
14347 	if (len > usable) {
14348 		/* Can't send complete M_DATA in one shot */
14349 		goto slow;
14350 	}
14351 
14352 	mutex_enter(&tcp->tcp_non_sq_lock);
14353 	if (tcp->tcp_flow_stopped &&
14354 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
14355 		tcp_clrqfull(tcp);
14356 	}
14357 	mutex_exit(&tcp->tcp_non_sq_lock);
14358 
14359 	/*
14360 	 * determine if anything to send (Nagle).
14361 	 *
14362 	 *   1. len < tcp_mss (i.e. small)
14363 	 *   2. unacknowledged data present
14364 	 *   3. len < nagle limit
14365 	 *   4. last packet sent < nagle limit (previous packet sent)
14366 	 */
14367 	if ((len < mss) && (snxt != suna) &&
14368 	    (len < (int)tcp->tcp_naglim) &&
14369 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
14370 		/*
14371 		 * This was the first unsent packet and normally
14372 		 * mss < xmit_hiwater so there is no need to worry
14373 		 * about flow control. The next packet will go
14374 		 * through the flow control check in tcp_wput_data().
14375 		 */
14376 		/* leftover work from above */
14377 		tcp->tcp_unsent = len;
14378 		tcp->tcp_xmit_tail_unsent = len;
14379 
14380 		return;
14381 	}
14382 
14383 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
14384 
14385 	if (snxt == suna) {
14386 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14387 	}
14388 
14389 	/* we have always sent something */
14390 	tcp->tcp_rack_cnt = 0;
14391 
14392 	tcp->tcp_snxt = snxt + len;
14393 	tcp->tcp_rack = tcp->tcp_rnxt;
14394 
14395 	if ((mp1 = dupb(mp)) == 0)
14396 		goto no_memory;
14397 	mp->b_prev = (mblk_t *)(uintptr_t)now;
14398 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
14399 
14400 	/* adjust tcp header information */
14401 	tcpha = tcp->tcp_tcpha;
14402 	tcpha->tha_flags = (TH_ACK|TH_PUSH);
14403 
14404 	sum = len + connp->conn_ht_ulp_len + connp->conn_sum;
14405 	sum = (sum >> 16) + (sum & 0xFFFF);
14406 	tcpha->tha_sum = htons(sum);
14407 
14408 	tcpha->tha_seq = htonl(snxt);
14409 
14410 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
14411 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
14412 	BUMP_LOCAL(tcp->tcp_obsegs);
14413 
14414 	/* Update the latest receive window size in TCP header. */
14415 	tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
14416 
14417 	tcp->tcp_last_sent_len = (ushort_t)len;
14418 
14419 	plen = len + connp->conn_ht_iphc_len;
14420 
14421 	ixa = connp->conn_ixa;
14422 	ixa->ixa_pktlen = plen;
14423 
14424 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
14425 		tcp->tcp_ipha->ipha_length = htons(plen);
14426 	} else {
14427 		tcp->tcp_ip6h->ip6_plen = htons(plen - IPV6_HDR_LEN);
14428 	}
14429 
14430 	/* see if we need to allocate a mblk for the headers */
14431 	hdrlen = connp->conn_ht_iphc_len;
14432 	rptr = mp1->b_rptr - hdrlen;
14433 	db = mp1->b_datap;
14434 	if ((db->db_ref != 2) || rptr < db->db_base ||
14435 	    (!OK_32PTR(rptr))) {
14436 		/* NOTE: we assume allocb returns an OK_32PTR */
14437 		mp = allocb(hdrlen + tcps->tcps_wroff_xtra, BPRI_MED);
14438 		if (!mp) {
14439 			freemsg(mp1);
14440 			goto no_memory;
14441 		}
14442 		mp->b_cont = mp1;
14443 		mp1 = mp;
14444 		/* Leave room for Link Level header */
14445 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
14446 		mp1->b_wptr = &rptr[hdrlen];
14447 	}
14448 	mp1->b_rptr = rptr;
14449 
14450 	/* Fill in the timestamp option. */
14451 	if (tcp->tcp_snd_ts_ok) {
14452 		uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
14453 
14454 		U32_TO_BE32(llbolt,
14455 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
14456 		U32_TO_BE32(tcp->tcp_ts_recent,
14457 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
14458 	} else {
14459 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
14460 	}
14461 
14462 	/* copy header into outgoing packet */
14463 	dst = (ipaddr_t *)rptr;
14464 	src = (ipaddr_t *)connp->conn_ht_iphc;
14465 	dst[0] = src[0];
14466 	dst[1] = src[1];
14467 	dst[2] = src[2];
14468 	dst[3] = src[3];
14469 	dst[4] = src[4];
14470 	dst[5] = src[5];
14471 	dst[6] = src[6];
14472 	dst[7] = src[7];
14473 	dst[8] = src[8];
14474 	dst[9] = src[9];
14475 	if (hdrlen -= 40) {
14476 		hdrlen >>= 2;
14477 		dst += 10;
14478 		src += 10;
14479 		do {
14480 			*dst++ = *src++;
14481 		} while (--hdrlen);
14482 	}
14483 
14484 	/*
14485 	 * Set the ECN info in the TCP header.  Note that this
14486 	 * is not the template header.
14487 	 */
14488 	if (tcp->tcp_ecn_ok) {
14489 		SET_ECT(tcp, rptr);
14490 
14491 		tcpha = (tcpha_t *)(rptr + ixa->ixa_ip_hdr_length);
14492 		if (tcp->tcp_ecn_echo_on)
14493 			tcpha->tha_flags |= TH_ECE;
14494 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
14495 			tcpha->tha_flags |= TH_CWR;
14496 			tcp->tcp_ecn_cwr_sent = B_TRUE;
14497 		}
14498 	}
14499 
14500 	if (tcp->tcp_ip_forward_progress) {
14501 		tcp->tcp_ip_forward_progress = B_FALSE;
14502 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
14503 	} else {
14504 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
14505 	}
14506 	tcp_send_data(tcp, mp1);
14507 	return;
14508 
14509 	/*
14510 	 * If we ran out of memory, we pretend to have sent the packet
14511 	 * and that it was lost on the wire.
14512 	 */
14513 no_memory:
14514 	return;
14515 
14516 slow:
14517 	/* leftover work from above */
14518 	tcp->tcp_unsent = len;
14519 	tcp->tcp_xmit_tail_unsent = len;
14520 	tcp_wput_data(tcp, NULL, B_FALSE);
14521 }
14522 
14523 /*
14524  * This runs at the tail end of accept processing on the squeue of the
14525  * new connection.
14526  */
14527 /* ARGSUSED */
14528 void
14529 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14530 {
14531 	conn_t			*connp = (conn_t *)arg;
14532 	tcp_t			*tcp = connp->conn_tcp;
14533 	queue_t			*q = connp->conn_rq;
14534 	tcp_stack_t		*tcps = tcp->tcp_tcps;
14535 	/* socket options */
14536 	struct sock_proto_props	sopp;
14537 
14538 	/* We should just receive a single mblk that fits a T_discon_ind */
14539 	ASSERT(mp->b_cont == NULL);
14540 
14541 	/*
14542 	 * Drop the eager's ref on the listener, that was placed when
14543 	 * this eager began life in tcp_input_listener.
14544 	 */
14545 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
14546 	if (IPCL_IS_NONSTR(connp)) {
14547 		/* Safe to free conn_ind message */
14548 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
14549 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14550 	}
14551 
14552 	tcp->tcp_detached = B_FALSE;
14553 
14554 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
14555 		/*
14556 		 * Someone blewoff the eager before we could finish
14557 		 * the accept.
14558 		 *
14559 		 * The only reason eager exists it because we put in
14560 		 * a ref on it when conn ind went up. We need to send
14561 		 * a disconnect indication up while the last reference
14562 		 * on the eager will be dropped by the squeue when we
14563 		 * return.
14564 		 */
14565 		ASSERT(tcp->tcp_listener == NULL);
14566 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
14567 			if (IPCL_IS_NONSTR(connp)) {
14568 				ASSERT(tcp->tcp_issocket);
14569 				(*connp->conn_upcalls->su_disconnected)(
14570 				    connp->conn_upper_handle, tcp->tcp_connid,
14571 				    ECONNREFUSED);
14572 				freemsg(mp);
14573 			} else {
14574 				struct	T_discon_ind	*tdi;
14575 
14576 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
14577 				/*
14578 				 * Let us reuse the incoming mblk to avoid
14579 				 * memory allocation failure problems. We know
14580 				 * that the size of the incoming mblk i.e.
14581 				 * stroptions is greater than sizeof
14582 				 * T_discon_ind.
14583 				 */
14584 				ASSERT(DB_REF(mp) == 1);
14585 				ASSERT(MBLKSIZE(mp) >=
14586 				    sizeof (struct T_discon_ind));
14587 
14588 				DB_TYPE(mp) = M_PROTO;
14589 				((union T_primitives *)mp->b_rptr)->type =
14590 				    T_DISCON_IND;
14591 				tdi = (struct T_discon_ind *)mp->b_rptr;
14592 				if (tcp->tcp_issocket) {
14593 					tdi->DISCON_reason = ECONNREFUSED;
14594 					tdi->SEQ_number = 0;
14595 				} else {
14596 					tdi->DISCON_reason = ENOPROTOOPT;
14597 					tdi->SEQ_number =
14598 					    tcp->tcp_conn_req_seqnum;
14599 				}
14600 				mp->b_wptr = mp->b_rptr +
14601 				    sizeof (struct T_discon_ind);
14602 				putnext(q, mp);
14603 			}
14604 		}
14605 		tcp->tcp_hard_binding = B_FALSE;
14606 		return;
14607 	}
14608 
14609 	/*
14610 	 * This is the first time we run on the correct
14611 	 * queue after tcp_accept. So fix all the q parameters
14612 	 * here.
14613 	 */
14614 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
14615 	sopp.sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
14616 
14617 	sopp.sopp_rxhiwat = tcp->tcp_fused ?
14618 	    tcp_fuse_set_rcv_hiwat(tcp, connp->conn_rcvbuf) :
14619 	    connp->conn_rcvbuf;
14620 
14621 	/*
14622 	 * Determine what write offset value to use depending on SACK and
14623 	 * whether the endpoint is fused or not.
14624 	 */
14625 	if (tcp->tcp_fused) {
14626 		ASSERT(tcp->tcp_loopback);
14627 		ASSERT(tcp->tcp_loopback_peer != NULL);
14628 		/*
14629 		 * For fused tcp loopback, set the stream head's write
14630 		 * offset value to zero since we won't be needing any room
14631 		 * for TCP/IP headers.  This would also improve performance
14632 		 * since it would reduce the amount of work done by kmem.
14633 		 * Non-fused tcp loopback case is handled separately below.
14634 		 */
14635 		sopp.sopp_wroff = 0;
14636 		/*
14637 		 * Update the peer's transmit parameters according to
14638 		 * our recently calculated high water mark value.
14639 		 */
14640 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
14641 	} else if (tcp->tcp_snd_sack_ok) {
14642 		sopp.sopp_wroff = connp->conn_ht_iphc_allocated +
14643 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14644 	} else {
14645 		sopp.sopp_wroff = connp->conn_ht_iphc_len +
14646 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14647 	}
14648 
14649 	/*
14650 	 * If this is endpoint is handling SSL, then reserve extra
14651 	 * offset and space at the end.
14652 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
14653 	 * overriding the previous setting. The extra cost of signing and
14654 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
14655 	 * instead of a single contiguous one by the stream head
14656 	 * largely outweighs the statistical reduction of ACKs, when
14657 	 * applicable. The peer will also save on decryption and verification
14658 	 * costs.
14659 	 */
14660 	if (tcp->tcp_kssl_ctx != NULL) {
14661 		sopp.sopp_wroff += SSL3_WROFFSET;
14662 
14663 		sopp.sopp_flags |= SOCKOPT_TAIL;
14664 		sopp.sopp_tail = SSL3_MAX_TAIL_LEN;
14665 
14666 		sopp.sopp_flags |= SOCKOPT_ZCOPY;
14667 		sopp.sopp_zcopyflag = ZCVMUNSAFE;
14668 
14669 		sopp.sopp_maxblk = SSL3_MAX_RECORD_LEN;
14670 	}
14671 
14672 	/* Send the options up */
14673 	if (IPCL_IS_NONSTR(connp)) {
14674 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14675 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14676 			ASSERT(sopp.sopp_flags & SOCKOPT_ZCOPY);
14677 		}
14678 		if (tcp->tcp_loopback) {
14679 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
14680 			sopp.sopp_loopback = B_TRUE;
14681 		}
14682 		(*connp->conn_upcalls->su_set_proto_props)
14683 		    (connp->conn_upper_handle, &sopp);
14684 		freemsg(mp);
14685 	} else {
14686 		/*
14687 		 * Let us reuse the incoming mblk to avoid
14688 		 * memory allocation failure problems. We know
14689 		 * that the size of the incoming mblk is at least
14690 		 * stroptions
14691 		 */
14692 		struct stroptions *stropt;
14693 
14694 		ASSERT(DB_REF(mp) == 1);
14695 		ASSERT(MBLKSIZE(mp) >= sizeof (struct stroptions));
14696 
14697 		DB_TYPE(mp) = M_SETOPTS;
14698 		stropt = (struct stroptions *)mp->b_rptr;
14699 		mp->b_wptr = mp->b_rptr + sizeof (struct stroptions);
14700 		stropt = (struct stroptions *)mp->b_rptr;
14701 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
14702 		stropt->so_hiwat = sopp.sopp_rxhiwat;
14703 		stropt->so_wroff = sopp.sopp_wroff;
14704 		stropt->so_maxblk = sopp.sopp_maxblk;
14705 
14706 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14707 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14708 
14709 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
14710 			stropt->so_tail = sopp.sopp_tail;
14711 			stropt->so_copyopt = sopp.sopp_zcopyflag;
14712 		}
14713 
14714 		/* Send the options up */
14715 		putnext(q, mp);
14716 	}
14717 
14718 	/*
14719 	 * Pass up any data and/or a fin that has been received.
14720 	 *
14721 	 * Adjust receive window in case it had decreased
14722 	 * (because there is data <=> tcp_rcv_list != NULL)
14723 	 * while the connection was detached. Note that
14724 	 * in case the eager was flow-controlled, w/o this
14725 	 * code, the rwnd may never open up again!
14726 	 */
14727 	if (tcp->tcp_rcv_list != NULL) {
14728 		if (IPCL_IS_NONSTR(connp)) {
14729 			mblk_t *mp;
14730 			int space_left;
14731 			int error;
14732 			boolean_t push = B_TRUE;
14733 
14734 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
14735 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
14736 			    &push) >= 0) {
14737 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14738 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14739 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14740 					tcp_xmit_ctl(NULL,
14741 					    tcp, (tcp->tcp_swnd == 0) ?
14742 					    tcp->tcp_suna : tcp->tcp_snxt,
14743 					    tcp->tcp_rnxt, TH_ACK);
14744 				}
14745 			}
14746 			while ((mp = tcp->tcp_rcv_list) != NULL) {
14747 				push = B_TRUE;
14748 				tcp->tcp_rcv_list = mp->b_next;
14749 				mp->b_next = NULL;
14750 				space_left = (*connp->conn_upcalls->su_recv)
14751 				    (connp->conn_upper_handle, mp, msgdsize(mp),
14752 				    0, &error, &push);
14753 				if (space_left < 0) {
14754 					/*
14755 					 * We should never be in middle of a
14756 					 * fallback, the squeue guarantees that.
14757 					 */
14758 					ASSERT(error != EOPNOTSUPP);
14759 				}
14760 			}
14761 			tcp->tcp_rcv_last_head = NULL;
14762 			tcp->tcp_rcv_last_tail = NULL;
14763 			tcp->tcp_rcv_cnt = 0;
14764 		} else {
14765 			/* We drain directly in case of fused tcp loopback */
14766 
14767 			if (!tcp->tcp_fused && canputnext(q)) {
14768 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14769 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14770 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14771 					tcp_xmit_ctl(NULL,
14772 					    tcp, (tcp->tcp_swnd == 0) ?
14773 					    tcp->tcp_suna : tcp->tcp_snxt,
14774 					    tcp->tcp_rnxt, TH_ACK);
14775 				}
14776 			}
14777 
14778 			(void) tcp_rcv_drain(tcp);
14779 		}
14780 
14781 		/*
14782 		 * For fused tcp loopback, back-enable peer endpoint
14783 		 * if it's currently flow-controlled.
14784 		 */
14785 		if (tcp->tcp_fused) {
14786 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
14787 
14788 			ASSERT(peer_tcp != NULL);
14789 			ASSERT(peer_tcp->tcp_fused);
14790 
14791 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
14792 			if (peer_tcp->tcp_flow_stopped) {
14793 				tcp_clrqfull(peer_tcp);
14794 				TCP_STAT(tcps, tcp_fusion_backenabled);
14795 			}
14796 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
14797 		}
14798 	}
14799 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14800 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
14801 		tcp->tcp_ordrel_done = B_TRUE;
14802 		if (IPCL_IS_NONSTR(connp)) {
14803 			ASSERT(tcp->tcp_ordrel_mp == NULL);
14804 			(*connp->conn_upcalls->su_opctl)(
14805 			    connp->conn_upper_handle,
14806 			    SOCK_OPCTL_SHUT_RECV, 0);
14807 		} else {
14808 			mp = tcp->tcp_ordrel_mp;
14809 			tcp->tcp_ordrel_mp = NULL;
14810 			putnext(q, mp);
14811 		}
14812 	}
14813 	tcp->tcp_hard_binding = B_FALSE;
14814 
14815 	if (connp->conn_keepalive) {
14816 		tcp->tcp_ka_last_intrvl = 0;
14817 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
14818 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
14819 	}
14820 
14821 	/*
14822 	 * At this point, eager is fully established and will
14823 	 * have the following references -
14824 	 *
14825 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
14826 	 * 1 reference for the squeue which will be dropped by the squeue as
14827 	 *	soon as this function returns.
14828 	 * There will be 1 additonal reference for being in classifier
14829 	 *	hash list provided something bad hasn't happened.
14830 	 */
14831 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14832 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14833 }
14834 
14835 /*
14836  * The function called through squeue to get behind listener's perimeter to
14837  * send a deferred conn_ind.
14838  */
14839 /* ARGSUSED */
14840 void
14841 tcp_send_pending(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14842 {
14843 	conn_t	*lconnp = (conn_t *)arg;
14844 	tcp_t *listener = lconnp->conn_tcp;
14845 	struct T_conn_ind *conn_ind;
14846 	tcp_t *tcp;
14847 
14848 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
14849 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
14850 	    conn_ind->OPT_length);
14851 
14852 	if (listener->tcp_state != TCPS_LISTEN) {
14853 		/*
14854 		 * If listener has closed, it would have caused a
14855 		 * a cleanup/blowoff to happen for the eager, so
14856 		 * we don't need to do anything more.
14857 		 */
14858 		freemsg(mp);
14859 		return;
14860 	}
14861 
14862 	tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
14863 }
14864 
14865 /*
14866  * Common to TPI and sockfs accept code.
14867  */
14868 /* ARGSUSED2 */
14869 static int
14870 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
14871 {
14872 	tcp_t *listener, *eager;
14873 	mblk_t *discon_mp;
14874 
14875 	listener = lconnp->conn_tcp;
14876 	ASSERT(listener->tcp_state == TCPS_LISTEN);
14877 	eager = econnp->conn_tcp;
14878 	ASSERT(eager->tcp_listener != NULL);
14879 
14880 	/*
14881 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
14882 	 * use it if something failed.
14883 	 */
14884 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
14885 	    sizeof (struct stroptions)), BPRI_HI);
14886 
14887 	if (discon_mp == NULL) {
14888 		return (-TPROTO);
14889 	}
14890 	eager->tcp_issocket = B_TRUE;
14891 
14892 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
14893 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
14894 	ASSERT(econnp->conn_netstack ==
14895 	    listener->tcp_connp->conn_netstack);
14896 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
14897 
14898 	/* Put the ref for IP */
14899 	CONN_INC_REF(econnp);
14900 
14901 	/*
14902 	 * We should have minimum of 3 references on the conn
14903 	 * at this point. One each for TCP and IP and one for
14904 	 * the T_conn_ind that was sent up when the 3-way handshake
14905 	 * completed. In the normal case we would also have another
14906 	 * reference (making a total of 4) for the conn being in the
14907 	 * classifier hash list. However the eager could have received
14908 	 * an RST subsequently and tcp_closei_local could have removed
14909 	 * the eager from the classifier hash list, hence we can't
14910 	 * assert that reference.
14911 	 */
14912 	ASSERT(econnp->conn_ref >= 3);
14913 
14914 	mutex_enter(&listener->tcp_eager_lock);
14915 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
14916 
14917 		tcp_t *tail;
14918 		tcp_t *tcp;
14919 		mblk_t *mp1;
14920 
14921 		tcp = listener->tcp_eager_prev_q0;
14922 		/*
14923 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
14924 		 * deferred T_conn_ind queue. We need to get to the head
14925 		 * of the queue in order to send up T_conn_ind the same
14926 		 * order as how the 3WHS is completed.
14927 		 */
14928 		while (tcp != listener) {
14929 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
14930 			    !tcp->tcp_kssl_pending)
14931 				break;
14932 			else
14933 				tcp = tcp->tcp_eager_prev_q0;
14934 		}
14935 		/* None of the pending eagers can be sent up now */
14936 		if (tcp == listener)
14937 			goto no_more_eagers;
14938 
14939 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
14940 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14941 		/* Move from q0 to q */
14942 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
14943 		listener->tcp_conn_req_cnt_q0--;
14944 		listener->tcp_conn_req_cnt_q++;
14945 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
14946 		    tcp->tcp_eager_prev_q0;
14947 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
14948 		    tcp->tcp_eager_next_q0;
14949 		tcp->tcp_eager_prev_q0 = NULL;
14950 		tcp->tcp_eager_next_q0 = NULL;
14951 		tcp->tcp_conn_def_q0 = B_FALSE;
14952 
14953 		/* Make sure the tcp isn't in the list of droppables */
14954 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
14955 		    tcp->tcp_eager_prev_drop_q0 == NULL);
14956 
14957 		/*
14958 		 * Insert at end of the queue because sockfs sends
14959 		 * down T_CONN_RES in chronological order. Leaving
14960 		 * the older conn indications at front of the queue
14961 		 * helps reducing search time.
14962 		 */
14963 		tail = listener->tcp_eager_last_q;
14964 		if (tail != NULL) {
14965 			tail->tcp_eager_next_q = tcp;
14966 		} else {
14967 			listener->tcp_eager_next_q = tcp;
14968 		}
14969 		listener->tcp_eager_last_q = tcp;
14970 		tcp->tcp_eager_next_q = NULL;
14971 
14972 		/* Need to get inside the listener perimeter */
14973 		CONN_INC_REF(listener->tcp_connp);
14974 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
14975 		    tcp_send_pending, listener->tcp_connp, NULL, SQ_FILL,
14976 		    SQTAG_TCP_SEND_PENDING);
14977 	}
14978 no_more_eagers:
14979 	tcp_eager_unlink(eager);
14980 	mutex_exit(&listener->tcp_eager_lock);
14981 
14982 	/*
14983 	 * At this point, the eager is detached from the listener
14984 	 * but we still have an extra refs on eager (apart from the
14985 	 * usual tcp references). The ref was placed in tcp_input_data
14986 	 * before sending the conn_ind in tcp_send_conn_ind.
14987 	 * The ref will be dropped in tcp_accept_finish().
14988 	 */
14989 	SQUEUE_ENTER_ONE(econnp->conn_sqp, discon_mp, tcp_accept_finish,
14990 	    econnp, NULL, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
14991 	return (0);
14992 }
14993 
14994 int
14995 tcp_accept(sock_lower_handle_t lproto_handle,
14996     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
14997     cred_t *cr)
14998 {
14999 	conn_t *lconnp, *econnp;
15000 	tcp_t *listener, *eager;
15001 
15002 	lconnp = (conn_t *)lproto_handle;
15003 	listener = lconnp->conn_tcp;
15004 	ASSERT(listener->tcp_state == TCPS_LISTEN);
15005 	econnp = (conn_t *)eproto_handle;
15006 	eager = econnp->conn_tcp;
15007 	ASSERT(eager->tcp_listener != NULL);
15008 
15009 	/*
15010 	 * It is OK to manipulate these fields outside the eager's squeue
15011 	 * because they will not start being used until tcp_accept_finish
15012 	 * has been called.
15013 	 */
15014 	ASSERT(lconnp->conn_upper_handle != NULL);
15015 	ASSERT(econnp->conn_upper_handle == NULL);
15016 	econnp->conn_upper_handle = sock_handle;
15017 	econnp->conn_upcalls = lconnp->conn_upcalls;
15018 	ASSERT(IPCL_IS_NONSTR(econnp));
15019 	return (tcp_accept_common(lconnp, econnp, cr));
15020 }
15021 
15022 
15023 /*
15024  * This is the STREAMS entry point for T_CONN_RES coming down on
15025  * Acceptor STREAM when  sockfs listener does accept processing.
15026  * Read the block comment on top of tcp_input_listener().
15027  */
15028 void
15029 tcp_tpi_accept(queue_t *q, mblk_t *mp)
15030 {
15031 	queue_t *rq = RD(q);
15032 	struct T_conn_res *conn_res;
15033 	tcp_t *eager;
15034 	tcp_t *listener;
15035 	struct T_ok_ack *ok;
15036 	t_scalar_t PRIM_type;
15037 	conn_t *econnp;
15038 	cred_t *cr;
15039 
15040 	ASSERT(DB_TYPE(mp) == M_PROTO);
15041 
15042 	/*
15043 	 * All Solaris components should pass a db_credp
15044 	 * for this TPI message, hence we ASSERT.
15045 	 * But in case there is some other M_PROTO that looks
15046 	 * like a TPI message sent by some other kernel
15047 	 * component, we check and return an error.
15048 	 */
15049 	cr = msg_getcred(mp, NULL);
15050 	ASSERT(cr != NULL);
15051 	if (cr == NULL) {
15052 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
15053 		if (mp != NULL)
15054 			putnext(rq, mp);
15055 		return;
15056 	}
15057 	conn_res = (struct T_conn_res *)mp->b_rptr;
15058 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
15059 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
15060 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15061 		if (mp != NULL)
15062 			putnext(rq, mp);
15063 		return;
15064 	}
15065 	switch (conn_res->PRIM_type) {
15066 	case O_T_CONN_RES:
15067 	case T_CONN_RES:
15068 		/*
15069 		 * We pass up an err ack if allocb fails. This will
15070 		 * cause sockfs to issue a T_DISCON_REQ which will cause
15071 		 * tcp_eager_blowoff to be called. sockfs will then call
15072 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
15073 		 * we need to do the allocb up here because we have to
15074 		 * make sure rq->q_qinfo->qi_qclose still points to the
15075 		 * correct function (tcp_tpi_close_accept) in case allocb
15076 		 * fails.
15077 		 */
15078 		bcopy(mp->b_rptr + conn_res->OPT_offset,
15079 		    &eager, conn_res->OPT_length);
15080 		PRIM_type = conn_res->PRIM_type;
15081 		mp->b_datap->db_type = M_PCPROTO;
15082 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
15083 		ok = (struct T_ok_ack *)mp->b_rptr;
15084 		ok->PRIM_type = T_OK_ACK;
15085 		ok->CORRECT_prim = PRIM_type;
15086 		econnp = eager->tcp_connp;
15087 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
15088 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
15089 		econnp->conn_rq = rq;
15090 		econnp->conn_wq = q;
15091 		rq->q_ptr = econnp;
15092 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
15093 		q->q_ptr = econnp;
15094 		q->q_qinfo = &tcp_winit;
15095 		listener = eager->tcp_listener;
15096 
15097 		if (tcp_accept_common(listener->tcp_connp,
15098 		    econnp, cr) < 0) {
15099 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15100 			if (mp != NULL)
15101 				putnext(rq, mp);
15102 			return;
15103 		}
15104 
15105 		/*
15106 		 * Send the new local address also up to sockfs. There
15107 		 * should already be enough space in the mp that came
15108 		 * down from soaccept().
15109 		 */
15110 		if (econnp->conn_family == AF_INET) {
15111 			sin_t *sin;
15112 
15113 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15114 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
15115 			sin = (sin_t *)mp->b_wptr;
15116 			mp->b_wptr += sizeof (sin_t);
15117 			sin->sin_family = AF_INET;
15118 			sin->sin_port = econnp->conn_lport;
15119 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
15120 		} else {
15121 			sin6_t *sin6;
15122 
15123 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15124 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
15125 			sin6 = (sin6_t *)mp->b_wptr;
15126 			mp->b_wptr += sizeof (sin6_t);
15127 			sin6->sin6_family = AF_INET6;
15128 			sin6->sin6_port = econnp->conn_lport;
15129 			sin6->sin6_addr = econnp->conn_laddr_v6;
15130 			if (econnp->conn_ipversion == IPV4_VERSION)
15131 				sin6->sin6_flowinfo = 0;
15132 			else
15133 				sin6->sin6_flowinfo = econnp->conn_flowinfo;
15134 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
15135 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
15136 				sin6->sin6_scope_id =
15137 				    econnp->conn_ixa->ixa_scopeid;
15138 			} else {
15139 				sin6->sin6_scope_id = 0;
15140 			}
15141 			sin6->__sin6_src_id = 0;
15142 		}
15143 
15144 		putnext(rq, mp);
15145 		return;
15146 	default:
15147 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
15148 		if (mp != NULL)
15149 			putnext(rq, mp);
15150 		return;
15151 	}
15152 }
15153 
15154 /*
15155  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
15156  */
15157 static void
15158 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
15159 {
15160 	void	*data;
15161 	mblk_t	*datamp = mp->b_cont;
15162 	conn_t	*connp = Q_TO_CONN(q);
15163 	tcp_t	*tcp = connp->conn_tcp;
15164 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
15165 
15166 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
15167 		cmdp->cb_error = EPROTO;
15168 		qreply(q, mp);
15169 		return;
15170 	}
15171 
15172 	data = datamp->b_rptr;
15173 
15174 	switch (cmdp->cb_cmd) {
15175 	case TI_GETPEERNAME:
15176 		if (tcp->tcp_state < TCPS_SYN_RCVD)
15177 			cmdp->cb_error = ENOTCONN;
15178 		else
15179 			cmdp->cb_error = conn_getpeername(connp, data,
15180 			    &cmdp->cb_len);
15181 		break;
15182 	case TI_GETMYNAME:
15183 		cmdp->cb_error = conn_getsockname(connp, data, &cmdp->cb_len);
15184 		break;
15185 	default:
15186 		cmdp->cb_error = EINVAL;
15187 		break;
15188 	}
15189 
15190 	qreply(q, mp);
15191 }
15192 
15193 void
15194 tcp_wput(queue_t *q, mblk_t *mp)
15195 {
15196 	conn_t	*connp = Q_TO_CONN(q);
15197 	tcp_t	*tcp;
15198 	void (*output_proc)();
15199 	t_scalar_t type;
15200 	uchar_t *rptr;
15201 	struct iocblk	*iocp;
15202 	size_t size;
15203 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
15204 
15205 	ASSERT(connp->conn_ref >= 2);
15206 
15207 	switch (DB_TYPE(mp)) {
15208 	case M_DATA:
15209 		tcp = connp->conn_tcp;
15210 		ASSERT(tcp != NULL);
15211 
15212 		size = msgdsize(mp);
15213 
15214 		mutex_enter(&tcp->tcp_non_sq_lock);
15215 		tcp->tcp_squeue_bytes += size;
15216 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
15217 			tcp_setqfull(tcp);
15218 		}
15219 		mutex_exit(&tcp->tcp_non_sq_lock);
15220 
15221 		CONN_INC_REF(connp);
15222 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
15223 		    NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
15224 		return;
15225 
15226 	case M_CMD:
15227 		tcp_wput_cmdblk(q, mp);
15228 		return;
15229 
15230 	case M_PROTO:
15231 	case M_PCPROTO:
15232 		/*
15233 		 * if it is a snmp message, don't get behind the squeue
15234 		 */
15235 		tcp = connp->conn_tcp;
15236 		rptr = mp->b_rptr;
15237 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
15238 			type = ((union T_primitives *)rptr)->type;
15239 		} else {
15240 			if (connp->conn_debug) {
15241 				(void) strlog(TCP_MOD_ID, 0, 1,
15242 				    SL_ERROR|SL_TRACE,
15243 				    "tcp_wput_proto, dropping one...");
15244 			}
15245 			freemsg(mp);
15246 			return;
15247 		}
15248 		if (type == T_SVR4_OPTMGMT_REQ) {
15249 			/*
15250 			 * All Solaris components should pass a db_credp
15251 			 * for this TPI message, hence we ASSERT.
15252 			 * But in case there is some other M_PROTO that looks
15253 			 * like a TPI message sent by some other kernel
15254 			 * component, we check and return an error.
15255 			 */
15256 			cred_t	*cr = msg_getcred(mp, NULL);
15257 
15258 			ASSERT(cr != NULL);
15259 			if (cr == NULL) {
15260 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
15261 				return;
15262 			}
15263 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
15264 			    cr)) {
15265 				/*
15266 				 * This was a SNMP request
15267 				 */
15268 				return;
15269 			} else {
15270 				output_proc = tcp_wput_proto;
15271 			}
15272 		} else {
15273 			output_proc = tcp_wput_proto;
15274 		}
15275 		break;
15276 	case M_IOCTL:
15277 		/*
15278 		 * Most ioctls can be processed right away without going via
15279 		 * squeues - process them right here. Those that do require
15280 		 * squeue (currently _SIOCSOCKFALLBACK)
15281 		 * are processed by tcp_wput_ioctl().
15282 		 */
15283 		iocp = (struct iocblk *)mp->b_rptr;
15284 		tcp = connp->conn_tcp;
15285 
15286 		switch (iocp->ioc_cmd) {
15287 		case TCP_IOC_ABORT_CONN:
15288 			tcp_ioctl_abort_conn(q, mp);
15289 			return;
15290 		case TI_GETPEERNAME:
15291 		case TI_GETMYNAME:
15292 			mi_copyin(q, mp, NULL,
15293 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
15294 			return;
15295 		case ND_SET:
15296 			/* nd_getset does the necessary checks */
15297 		case ND_GET:
15298 			if (nd_getset(q, tcps->tcps_g_nd, mp)) {
15299 				qreply(q, mp);
15300 				return;
15301 			}
15302 			CONN_INC_IOCTLREF(connp);
15303 			ip_wput_nondata(q, mp);
15304 			CONN_DEC_IOCTLREF(connp);
15305 			return;
15306 
15307 		default:
15308 			output_proc = tcp_wput_ioctl;
15309 			break;
15310 		}
15311 		break;
15312 	default:
15313 		output_proc = tcp_wput_nondata;
15314 		break;
15315 	}
15316 
15317 	CONN_INC_REF(connp);
15318 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
15319 	    NULL, tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
15320 }
15321 
15322 /*
15323  * Initial STREAMS write side put() procedure for sockets. It tries to
15324  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
15325  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
15326  * are handled by tcp_wput() as usual.
15327  *
15328  * All further messages will also be handled by tcp_wput() because we cannot
15329  * be sure that the above short cut is safe later.
15330  */
15331 static void
15332 tcp_wput_sock(queue_t *wq, mblk_t *mp)
15333 {
15334 	conn_t			*connp = Q_TO_CONN(wq);
15335 	tcp_t			*tcp = connp->conn_tcp;
15336 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
15337 
15338 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
15339 	wq->q_qinfo = &tcp_winit;
15340 
15341 	ASSERT(IPCL_IS_TCP(connp));
15342 	ASSERT(TCP_IS_SOCKET(tcp));
15343 
15344 	if (DB_TYPE(mp) == M_PCPROTO &&
15345 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
15346 	    car->PRIM_type == T_CAPABILITY_REQ) {
15347 		tcp_capability_req(tcp, mp);
15348 		return;
15349 	}
15350 
15351 	tcp_wput(wq, mp);
15352 }
15353 
15354 /* ARGSUSED */
15355 static void
15356 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
15357 {
15358 #ifdef DEBUG
15359 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
15360 #endif
15361 	freemsg(mp);
15362 }
15363 
15364 /*
15365  * Check the usability of ZEROCOPY. It's instead checking the flag set by IP.
15366  */
15367 static boolean_t
15368 tcp_zcopy_check(tcp_t *tcp)
15369 {
15370 	conn_t		*connp = tcp->tcp_connp;
15371 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
15372 	boolean_t	zc_enabled = B_FALSE;
15373 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15374 
15375 	if (do_tcpzcopy == 2)
15376 		zc_enabled = B_TRUE;
15377 	else if ((do_tcpzcopy == 1) && (ixa->ixa_flags & IXAF_ZCOPY_CAPAB))
15378 		zc_enabled = B_TRUE;
15379 
15380 	tcp->tcp_snd_zcopy_on = zc_enabled;
15381 	if (!TCP_IS_DETACHED(tcp)) {
15382 		if (zc_enabled) {
15383 			ixa->ixa_flags |= IXAF_VERIFY_ZCOPY;
15384 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15385 			    ZCVMSAFE);
15386 			TCP_STAT(tcps, tcp_zcopy_on);
15387 		} else {
15388 			ixa->ixa_flags &= ~IXAF_VERIFY_ZCOPY;
15389 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15390 			    ZCVMUNSAFE);
15391 			TCP_STAT(tcps, tcp_zcopy_off);
15392 		}
15393 	}
15394 	return (zc_enabled);
15395 }
15396 
15397 /*
15398  * Backoff from a zero-copy message by copying data to a new allocated
15399  * message and freeing the original desballoca'ed segmapped message.
15400  *
15401  * This function is called by following two callers:
15402  * 1. tcp_timer: fix_xmitlist is set to B_TRUE, because it's safe to free
15403  *    the origial desballoca'ed message and notify sockfs. This is in re-
15404  *    transmit state.
15405  * 2. tcp_output: fix_xmitlist is set to B_FALSE. Flag STRUIO_ZCNOTIFY need
15406  *    to be copied to new message.
15407  */
15408 static mblk_t *
15409 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, boolean_t fix_xmitlist)
15410 {
15411 	mblk_t		*nbp;
15412 	mblk_t		*head = NULL;
15413 	mblk_t		*tail = NULL;
15414 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15415 
15416 	ASSERT(bp != NULL);
15417 	while (bp != NULL) {
15418 		if (IS_VMLOANED_MBLK(bp)) {
15419 			TCP_STAT(tcps, tcp_zcopy_backoff);
15420 			if ((nbp = copyb(bp)) == NULL) {
15421 				tcp->tcp_xmit_zc_clean = B_FALSE;
15422 				if (tail != NULL)
15423 					tail->b_cont = bp;
15424 				return ((head == NULL) ? bp : head);
15425 			}
15426 
15427 			if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
15428 				if (fix_xmitlist)
15429 					tcp_zcopy_notify(tcp);
15430 				else
15431 					nbp->b_datap->db_struioflag |=
15432 					    STRUIO_ZCNOTIFY;
15433 			}
15434 			nbp->b_cont = bp->b_cont;
15435 
15436 			/*
15437 			 * Copy saved information and adjust tcp_xmit_tail
15438 			 * if needed.
15439 			 */
15440 			if (fix_xmitlist) {
15441 				nbp->b_prev = bp->b_prev;
15442 				nbp->b_next = bp->b_next;
15443 
15444 				if (tcp->tcp_xmit_tail == bp)
15445 					tcp->tcp_xmit_tail = nbp;
15446 			}
15447 
15448 			/* Free the original message. */
15449 			bp->b_prev = NULL;
15450 			bp->b_next = NULL;
15451 			freeb(bp);
15452 
15453 			bp = nbp;
15454 		}
15455 
15456 		if (head == NULL) {
15457 			head = bp;
15458 		}
15459 		if (tail == NULL) {
15460 			tail = bp;
15461 		} else {
15462 			tail->b_cont = bp;
15463 			tail = bp;
15464 		}
15465 
15466 		/* Move forward. */
15467 		bp = bp->b_cont;
15468 	}
15469 
15470 	if (fix_xmitlist) {
15471 		tcp->tcp_xmit_last = tail;
15472 		tcp->tcp_xmit_zc_clean = B_TRUE;
15473 	}
15474 
15475 	return (head);
15476 }
15477 
15478 static void
15479 tcp_zcopy_notify(tcp_t *tcp)
15480 {
15481 	struct stdata	*stp;
15482 	conn_t		*connp;
15483 
15484 	if (tcp->tcp_detached)
15485 		return;
15486 	connp = tcp->tcp_connp;
15487 	if (IPCL_IS_NONSTR(connp)) {
15488 		(*connp->conn_upcalls->su_zcopy_notify)
15489 		    (connp->conn_upper_handle);
15490 		return;
15491 	}
15492 	stp = STREAM(connp->conn_rq);
15493 	mutex_enter(&stp->sd_lock);
15494 	stp->sd_flag |= STZCNOTIFY;
15495 	cv_broadcast(&stp->sd_zcopy_wait);
15496 	mutex_exit(&stp->sd_lock);
15497 }
15498 
15499 /*
15500  * Update the TCP connection according to change of LSO capability.
15501  */
15502 static void
15503 tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa)
15504 {
15505 	/*
15506 	 * We check against IPv4 header length to preserve the old behavior
15507 	 * of only enabling LSO when there are no IP options.
15508 	 * But this restriction might not be necessary at all. Before removing
15509 	 * it, need to verify how LSO is handled for source routing case, with
15510 	 * which IP does software checksum.
15511 	 *
15512 	 * For IPv6, whenever any extension header is needed, LSO is supressed.
15513 	 */
15514 	if (ixa->ixa_ip_hdr_length != ((ixa->ixa_flags & IXAF_IS_IPV4) ?
15515 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN))
15516 		return;
15517 
15518 	/*
15519 	 * Either the LSO capability newly became usable, or it has changed.
15520 	 */
15521 	if (ixa->ixa_flags & IXAF_LSO_CAPAB) {
15522 		ill_lso_capab_t	*lsoc = &ixa->ixa_lso_capab;
15523 
15524 		ASSERT(lsoc->ill_lso_max > 0);
15525 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH, lsoc->ill_lso_max);
15526 
15527 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15528 		    boolean_t, B_TRUE, uint32_t, tcp->tcp_lso_max);
15529 
15530 		/*
15531 		 * If LSO to be enabled, notify the STREAM header with larger
15532 		 * data block.
15533 		 */
15534 		if (!tcp->tcp_lso)
15535 			tcp->tcp_maxpsz_multiplier = 0;
15536 
15537 		tcp->tcp_lso = B_TRUE;
15538 		TCP_STAT(tcp->tcp_tcps, tcp_lso_enabled);
15539 	} else { /* LSO capability is not usable any more. */
15540 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15541 		    boolean_t, B_FALSE, uint32_t, tcp->tcp_lso_max);
15542 
15543 		/*
15544 		 * If LSO to be disabled, notify the STREAM header with smaller
15545 		 * data block. And need to restore fragsize to PMTU.
15546 		 */
15547 		if (tcp->tcp_lso) {
15548 			tcp->tcp_maxpsz_multiplier =
15549 			    tcp->tcp_tcps->tcps_maxpsz_multiplier;
15550 			ixa->ixa_fragsize = ixa->ixa_pmtu;
15551 			tcp->tcp_lso = B_FALSE;
15552 			TCP_STAT(tcp->tcp_tcps, tcp_lso_disabled);
15553 		}
15554 	}
15555 
15556 	(void) tcp_maxpsz_set(tcp, B_TRUE);
15557 }
15558 
15559 /*
15560  * Update the TCP connection according to change of ZEROCOPY capability.
15561  */
15562 static void
15563 tcp_update_zcopy(tcp_t *tcp)
15564 {
15565 	conn_t		*connp = tcp->tcp_connp;
15566 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15567 
15568 	if (tcp->tcp_snd_zcopy_on) {
15569 		tcp->tcp_snd_zcopy_on = B_FALSE;
15570 		if (!TCP_IS_DETACHED(tcp)) {
15571 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15572 			    ZCVMUNSAFE);
15573 			TCP_STAT(tcps, tcp_zcopy_off);
15574 		}
15575 	} else {
15576 		tcp->tcp_snd_zcopy_on = B_TRUE;
15577 		if (!TCP_IS_DETACHED(tcp)) {
15578 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15579 			    ZCVMSAFE);
15580 			TCP_STAT(tcps, tcp_zcopy_on);
15581 		}
15582 	}
15583 }
15584 
15585 /*
15586  * Notify function registered with ip_xmit_attr_t. It's called in the squeue
15587  * so it's safe to update the TCP connection.
15588  */
15589 /* ARGSUSED1 */
15590 static void
15591 tcp_notify(void *arg, ip_xmit_attr_t *ixa, ixa_notify_type_t ntype,
15592     ixa_notify_arg_t narg)
15593 {
15594 	tcp_t		*tcp = (tcp_t *)arg;
15595 	conn_t		*connp = tcp->tcp_connp;
15596 
15597 	switch (ntype) {
15598 	case IXAN_LSO:
15599 		tcp_update_lso(tcp, connp->conn_ixa);
15600 		break;
15601 	case IXAN_PMTU:
15602 		tcp_update_pmtu(tcp, B_FALSE);
15603 		break;
15604 	case IXAN_ZCOPY:
15605 		tcp_update_zcopy(tcp);
15606 		break;
15607 	default:
15608 		break;
15609 	}
15610 }
15611 
15612 static void
15613 tcp_send_data(tcp_t *tcp, mblk_t *mp)
15614 {
15615 	conn_t		*connp = tcp->tcp_connp;
15616 
15617 	/*
15618 	 * Check here to avoid sending zero-copy message down to IP when
15619 	 * ZEROCOPY capability has turned off. We only need to deal with
15620 	 * the race condition between sockfs and the notification here.
15621 	 * Since we have tried to backoff the tcp_xmit_head when turning
15622 	 * zero-copy off and new messages in tcp_output(), we simply drop
15623 	 * the dup'ed packet here and let tcp retransmit, if tcp_xmit_zc_clean
15624 	 * is not true.
15625 	 */
15626 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on &&
15627 	    !tcp->tcp_xmit_zc_clean) {
15628 		ip_drop_output("TCP ZC was disabled but not clean", mp, NULL);
15629 		freemsg(mp);
15630 		return;
15631 	}
15632 
15633 	ASSERT(connp->conn_ixa->ixa_notify_cookie == connp->conn_tcp);
15634 	(void) conn_ip_output(mp, connp->conn_ixa);
15635 }
15636 
15637 /*
15638  * This handles the case when the receiver has shrunk its win. Per RFC 1122
15639  * if the receiver shrinks the window, i.e. moves the right window to the
15640  * left, the we should not send new data, but should retransmit normally the
15641  * old unacked data between suna and suna + swnd. We might has sent data
15642  * that is now outside the new window, pretend that we didn't send  it.
15643  */
15644 static void
15645 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
15646 {
15647 	uint32_t	snxt = tcp->tcp_snxt;
15648 
15649 	ASSERT(shrunk_count > 0);
15650 
15651 	if (!tcp->tcp_is_wnd_shrnk) {
15652 		tcp->tcp_snxt_shrunk = snxt;
15653 		tcp->tcp_is_wnd_shrnk = B_TRUE;
15654 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
15655 		tcp->tcp_snxt_shrunk = snxt;
15656 	}
15657 
15658 	/* Pretend we didn't send the data outside the window */
15659 	snxt -= shrunk_count;
15660 
15661 	/* Reset all the values per the now shrunk window */
15662 	tcp_update_xmit_tail(tcp, snxt);
15663 	tcp->tcp_unsent += shrunk_count;
15664 
15665 	/*
15666 	 * If the SACK option is set, delete the entire list of
15667 	 * notsack'ed blocks.
15668 	 */
15669 	if (tcp->tcp_sack_info != NULL) {
15670 		if (tcp->tcp_notsack_list != NULL)
15671 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
15672 	}
15673 
15674 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
15675 		/*
15676 		 * Make sure the timer is running so that we will probe a zero
15677 		 * window.
15678 		 */
15679 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15680 }
15681 
15682 
15683 /*
15684  * The TCP normal data output path.
15685  * NOTE: the logic of the fast path is duplicated from this function.
15686  */
15687 static void
15688 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
15689 {
15690 	int		len;
15691 	mblk_t		*local_time;
15692 	mblk_t		*mp1;
15693 	uint32_t	snxt;
15694 	int		tail_unsent;
15695 	int		tcpstate;
15696 	int		usable = 0;
15697 	mblk_t		*xmit_tail;
15698 	int32_t		mss;
15699 	int32_t		num_sack_blk = 0;
15700 	int32_t		total_hdr_len;
15701 	int32_t		tcp_hdr_len;
15702 	int		rc;
15703 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15704 	conn_t		*connp = tcp->tcp_connp;
15705 	clock_t		now = LBOLT_FASTPATH;
15706 
15707 	tcpstate = tcp->tcp_state;
15708 	if (mp == NULL) {
15709 		/*
15710 		 * tcp_wput_data() with NULL mp should only be called when
15711 		 * there is unsent data.
15712 		 */
15713 		ASSERT(tcp->tcp_unsent > 0);
15714 		/* Really tacky... but we need this for detached closes. */
15715 		len = tcp->tcp_unsent;
15716 		goto data_null;
15717 	}
15718 
15719 #if CCS_STATS
15720 	wrw_stats.tot.count++;
15721 	wrw_stats.tot.bytes += msgdsize(mp);
15722 #endif
15723 	ASSERT(mp->b_datap->db_type == M_DATA);
15724 	/*
15725 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
15726 	 * or before a connection attempt has begun.
15727 	 */
15728 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
15729 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15730 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15731 #ifdef DEBUG
15732 			cmn_err(CE_WARN,
15733 			    "tcp_wput_data: data after ordrel, %s",
15734 			    tcp_display(tcp, NULL,
15735 			    DISP_ADDR_AND_PORT));
15736 #else
15737 			if (connp->conn_debug) {
15738 				(void) strlog(TCP_MOD_ID, 0, 1,
15739 				    SL_TRACE|SL_ERROR,
15740 				    "tcp_wput_data: data after ordrel, %s\n",
15741 				    tcp_display(tcp, NULL,
15742 				    DISP_ADDR_AND_PORT));
15743 			}
15744 #endif /* DEBUG */
15745 		}
15746 		if (tcp->tcp_snd_zcopy_aware &&
15747 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15748 			tcp_zcopy_notify(tcp);
15749 		freemsg(mp);
15750 		mutex_enter(&tcp->tcp_non_sq_lock);
15751 		if (tcp->tcp_flow_stopped &&
15752 		    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
15753 			tcp_clrqfull(tcp);
15754 		}
15755 		mutex_exit(&tcp->tcp_non_sq_lock);
15756 		return;
15757 	}
15758 
15759 	/* Strip empties */
15760 	for (;;) {
15761 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
15762 		    (uintptr_t)INT_MAX);
15763 		len = (int)(mp->b_wptr - mp->b_rptr);
15764 		if (len > 0)
15765 			break;
15766 		mp1 = mp;
15767 		mp = mp->b_cont;
15768 		freeb(mp1);
15769 		if (!mp) {
15770 			return;
15771 		}
15772 	}
15773 
15774 	/* If we are the first on the list ... */
15775 	if (tcp->tcp_xmit_head == NULL) {
15776 		tcp->tcp_xmit_head = mp;
15777 		tcp->tcp_xmit_tail = mp;
15778 		tcp->tcp_xmit_tail_unsent = len;
15779 	} else {
15780 		/* If tiny tx and room in txq tail, pullup to save mblks. */
15781 		struct datab *dp;
15782 
15783 		mp1 = tcp->tcp_xmit_last;
15784 		if (len < tcp_tx_pull_len &&
15785 		    (dp = mp1->b_datap)->db_ref == 1 &&
15786 		    dp->db_lim - mp1->b_wptr >= len) {
15787 			ASSERT(len > 0);
15788 			ASSERT(!mp1->b_cont);
15789 			if (len == 1) {
15790 				*mp1->b_wptr++ = *mp->b_rptr;
15791 			} else {
15792 				bcopy(mp->b_rptr, mp1->b_wptr, len);
15793 				mp1->b_wptr += len;
15794 			}
15795 			if (mp1 == tcp->tcp_xmit_tail)
15796 				tcp->tcp_xmit_tail_unsent += len;
15797 			mp1->b_cont = mp->b_cont;
15798 			if (tcp->tcp_snd_zcopy_aware &&
15799 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15800 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
15801 			freeb(mp);
15802 			mp = mp1;
15803 		} else {
15804 			tcp->tcp_xmit_last->b_cont = mp;
15805 		}
15806 		len += tcp->tcp_unsent;
15807 	}
15808 
15809 	/* Tack on however many more positive length mblks we have */
15810 	if ((mp1 = mp->b_cont) != NULL) {
15811 		do {
15812 			int tlen;
15813 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
15814 			    (uintptr_t)INT_MAX);
15815 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
15816 			if (tlen <= 0) {
15817 				mp->b_cont = mp1->b_cont;
15818 				freeb(mp1);
15819 			} else {
15820 				len += tlen;
15821 				mp = mp1;
15822 			}
15823 		} while ((mp1 = mp->b_cont) != NULL);
15824 	}
15825 	tcp->tcp_xmit_last = mp;
15826 	tcp->tcp_unsent = len;
15827 
15828 	if (urgent)
15829 		usable = 1;
15830 
15831 data_null:
15832 	snxt = tcp->tcp_snxt;
15833 	xmit_tail = tcp->tcp_xmit_tail;
15834 	tail_unsent = tcp->tcp_xmit_tail_unsent;
15835 
15836 	/*
15837 	 * Note that tcp_mss has been adjusted to take into account the
15838 	 * timestamp option if applicable.  Because SACK options do not
15839 	 * appear in every TCP segments and they are of variable lengths,
15840 	 * they cannot be included in tcp_mss.  Thus we need to calculate
15841 	 * the actual segment length when we need to send a segment which
15842 	 * includes SACK options.
15843 	 */
15844 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15845 		int32_t	opt_len;
15846 
15847 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
15848 		    tcp->tcp_num_sack_blk);
15849 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
15850 		    2 + TCPOPT_HEADER_LEN;
15851 		mss = tcp->tcp_mss - opt_len;
15852 		total_hdr_len = connp->conn_ht_iphc_len + opt_len;
15853 		tcp_hdr_len = connp->conn_ht_ulp_len + opt_len;
15854 	} else {
15855 		mss = tcp->tcp_mss;
15856 		total_hdr_len = connp->conn_ht_iphc_len;
15857 		tcp_hdr_len = connp->conn_ht_ulp_len;
15858 	}
15859 
15860 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
15861 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
15862 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
15863 	}
15864 	if (tcpstate == TCPS_SYN_RCVD) {
15865 		/*
15866 		 * The three-way connection establishment handshake is not
15867 		 * complete yet. We want to queue the data for transmission
15868 		 * after entering ESTABLISHED state (RFC793). A jump to
15869 		 * "done" label effectively leaves data on the queue.
15870 		 */
15871 		goto done;
15872 	} else {
15873 		int usable_r;
15874 
15875 		/*
15876 		 * In the special case when cwnd is zero, which can only
15877 		 * happen if the connection is ECN capable, return now.
15878 		 * New segments is sent using tcp_timer().  The timer
15879 		 * is set in tcp_input_data().
15880 		 */
15881 		if (tcp->tcp_cwnd == 0) {
15882 			/*
15883 			 * Note that tcp_cwnd is 0 before 3-way handshake is
15884 			 * finished.
15885 			 */
15886 			ASSERT(tcp->tcp_ecn_ok ||
15887 			    tcp->tcp_state < TCPS_ESTABLISHED);
15888 			return;
15889 		}
15890 
15891 		/* NOTE: trouble if xmitting while SYN not acked? */
15892 		usable_r = snxt - tcp->tcp_suna;
15893 		usable_r = tcp->tcp_swnd - usable_r;
15894 
15895 		/*
15896 		 * Check if the receiver has shrunk the window.  If
15897 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
15898 		 * cannot be set as there is unsent data, so FIN cannot
15899 		 * be sent out.  Otherwise, we need to take into account
15900 		 * of FIN as it consumes an "invisible" sequence number.
15901 		 */
15902 		ASSERT(tcp->tcp_fin_sent == 0);
15903 		if (usable_r < 0) {
15904 			/*
15905 			 * The receiver has shrunk the window and we have sent
15906 			 * -usable_r date beyond the window, re-adjust.
15907 			 *
15908 			 * If TCP window scaling is enabled, there can be
15909 			 * round down error as the advertised receive window
15910 			 * is actually right shifted n bits.  This means that
15911 			 * the lower n bits info is wiped out.  It will look
15912 			 * like the window is shrunk.  Do a check here to
15913 			 * see if the shrunk amount is actually within the
15914 			 * error in window calculation.  If it is, just
15915 			 * return.  Note that this check is inside the
15916 			 * shrunk window check.  This makes sure that even
15917 			 * though tcp_process_shrunk_swnd() is not called,
15918 			 * we will stop further processing.
15919 			 */
15920 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
15921 				tcp_process_shrunk_swnd(tcp, -usable_r);
15922 			}
15923 			return;
15924 		}
15925 
15926 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
15927 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
15928 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
15929 
15930 		/* usable = MIN(usable, unsent) */
15931 		if (usable_r > len)
15932 			usable_r = len;
15933 
15934 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
15935 		if (usable_r > 0) {
15936 			usable = usable_r;
15937 		} else {
15938 			/* Bypass all other unnecessary processing. */
15939 			goto done;
15940 		}
15941 	}
15942 
15943 	local_time = (mblk_t *)now;
15944 
15945 	/*
15946 	 * "Our" Nagle Algorithm.  This is not the same as in the old
15947 	 * BSD.  This is more in line with the true intent of Nagle.
15948 	 *
15949 	 * The conditions are:
15950 	 * 1. The amount of unsent data (or amount of data which can be
15951 	 *    sent, whichever is smaller) is less than Nagle limit.
15952 	 * 2. The last sent size is also less than Nagle limit.
15953 	 * 3. There is unack'ed data.
15954 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
15955 	 *    Nagle algorithm.  This reduces the probability that urgent
15956 	 *    bytes get "merged" together.
15957 	 * 5. The app has not closed the connection.  This eliminates the
15958 	 *    wait time of the receiving side waiting for the last piece of
15959 	 *    (small) data.
15960 	 *
15961 	 * If all are satisified, exit without sending anything.  Note
15962 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
15963 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
15964 	 * 4095).
15965 	 */
15966 	if (usable < (int)tcp->tcp_naglim &&
15967 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
15968 	    snxt != tcp->tcp_suna &&
15969 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
15970 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
15971 		goto done;
15972 	}
15973 
15974 	/*
15975 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
15976 	 * is set, then we have to force TCP not to send partial segment
15977 	 * (smaller than MSS bytes). We are calculating the usable now
15978 	 * based on full mss and will save the rest of remaining data for
15979 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
15980 	 * something to do zero window probe.
15981 	 */
15982 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
15983 		if (usable < mss)
15984 			goto done;
15985 		usable = (usable / mss) * mss;
15986 	}
15987 
15988 	/* Update the latest receive window size in TCP header. */
15989 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
15990 
15991 	/* Send the packet. */
15992 	rc = tcp_send(tcp, mss, total_hdr_len, tcp_hdr_len,
15993 	    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
15994 	    local_time);
15995 
15996 	/* Pretend that all we were trying to send really got sent */
15997 	if (rc < 0 && tail_unsent < 0) {
15998 		do {
15999 			xmit_tail = xmit_tail->b_cont;
16000 			xmit_tail->b_prev = local_time;
16001 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
16002 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
16003 			tail_unsent += (int)(xmit_tail->b_wptr -
16004 			    xmit_tail->b_rptr);
16005 		} while (tail_unsent < 0);
16006 	}
16007 done:;
16008 	tcp->tcp_xmit_tail = xmit_tail;
16009 	tcp->tcp_xmit_tail_unsent = tail_unsent;
16010 	len = tcp->tcp_snxt - snxt;
16011 	if (len) {
16012 		/*
16013 		 * If new data was sent, need to update the notsack
16014 		 * list, which is, afterall, data blocks that have
16015 		 * not been sack'ed by the receiver.  New data is
16016 		 * not sack'ed.
16017 		 */
16018 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16019 			/* len is a negative value. */
16020 			tcp->tcp_pipe -= len;
16021 			tcp_notsack_update(&(tcp->tcp_notsack_list),
16022 			    tcp->tcp_snxt, snxt,
16023 			    &(tcp->tcp_num_notsack_blk),
16024 			    &(tcp->tcp_cnt_notsack_list));
16025 		}
16026 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
16027 		tcp->tcp_rack = tcp->tcp_rnxt;
16028 		tcp->tcp_rack_cnt = 0;
16029 		if ((snxt + len) == tcp->tcp_suna) {
16030 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16031 		}
16032 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
16033 		/*
16034 		 * Didn't send anything. Make sure the timer is running
16035 		 * so that we will probe a zero window.
16036 		 */
16037 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16038 	}
16039 	/* Note that len is the amount we just sent but with a negative sign */
16040 	tcp->tcp_unsent += len;
16041 	mutex_enter(&tcp->tcp_non_sq_lock);
16042 	if (tcp->tcp_flow_stopped) {
16043 		if (TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
16044 			tcp_clrqfull(tcp);
16045 		}
16046 	} else if (TCP_UNSENT_BYTES(tcp) >= connp->conn_sndbuf) {
16047 		if (!(tcp->tcp_detached))
16048 			tcp_setqfull(tcp);
16049 	}
16050 	mutex_exit(&tcp->tcp_non_sq_lock);
16051 }
16052 
16053 /*
16054  * tcp_fill_header is called by tcp_send() to fill the outgoing TCP header
16055  * with the template header, as well as other options such as time-stamp,
16056  * ECN and/or SACK.
16057  */
16058 static void
16059 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
16060 {
16061 	tcpha_t *tcp_tmpl, *tcpha;
16062 	uint32_t *dst, *src;
16063 	int hdrlen;
16064 	conn_t *connp = tcp->tcp_connp;
16065 
16066 	ASSERT(OK_32PTR(rptr));
16067 
16068 	/* Template header */
16069 	tcp_tmpl = tcp->tcp_tcpha;
16070 
16071 	/* Header of outgoing packet */
16072 	tcpha = (tcpha_t *)(rptr + connp->conn_ixa->ixa_ip_hdr_length);
16073 
16074 	/* dst and src are opaque 32-bit fields, used for copying */
16075 	dst = (uint32_t *)rptr;
16076 	src = (uint32_t *)connp->conn_ht_iphc;
16077 	hdrlen = connp->conn_ht_iphc_len;
16078 
16079 	/* Fill time-stamp option if needed */
16080 	if (tcp->tcp_snd_ts_ok) {
16081 		U32_TO_BE32((uint32_t)now,
16082 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
16083 		U32_TO_BE32(tcp->tcp_ts_recent,
16084 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
16085 	} else {
16086 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
16087 	}
16088 
16089 	/*
16090 	 * Copy the template header; is this really more efficient than
16091 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
16092 	 * but perhaps not for other scenarios.
16093 	 */
16094 	dst[0] = src[0];
16095 	dst[1] = src[1];
16096 	dst[2] = src[2];
16097 	dst[3] = src[3];
16098 	dst[4] = src[4];
16099 	dst[5] = src[5];
16100 	dst[6] = src[6];
16101 	dst[7] = src[7];
16102 	dst[8] = src[8];
16103 	dst[9] = src[9];
16104 	if (hdrlen -= 40) {
16105 		hdrlen >>= 2;
16106 		dst += 10;
16107 		src += 10;
16108 		do {
16109 			*dst++ = *src++;
16110 		} while (--hdrlen);
16111 	}
16112 
16113 	/*
16114 	 * Set the ECN info in the TCP header if it is not a zero
16115 	 * window probe.  Zero window probe is only sent in
16116 	 * tcp_wput_data() and tcp_timer().
16117 	 */
16118 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
16119 		SET_ECT(tcp, rptr);
16120 
16121 		if (tcp->tcp_ecn_echo_on)
16122 			tcpha->tha_flags |= TH_ECE;
16123 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16124 			tcpha->tha_flags |= TH_CWR;
16125 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16126 		}
16127 	}
16128 
16129 	/* Fill in SACK options */
16130 	if (num_sack_blk > 0) {
16131 		uchar_t *wptr = rptr + connp->conn_ht_iphc_len;
16132 		sack_blk_t *tmp;
16133 		int32_t	i;
16134 
16135 		wptr[0] = TCPOPT_NOP;
16136 		wptr[1] = TCPOPT_NOP;
16137 		wptr[2] = TCPOPT_SACK;
16138 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
16139 		    sizeof (sack_blk_t);
16140 		wptr += TCPOPT_REAL_SACK_LEN;
16141 
16142 		tmp = tcp->tcp_sack_list;
16143 		for (i = 0; i < num_sack_blk; i++) {
16144 			U32_TO_BE32(tmp[i].begin, wptr);
16145 			wptr += sizeof (tcp_seq);
16146 			U32_TO_BE32(tmp[i].end, wptr);
16147 			wptr += sizeof (tcp_seq);
16148 		}
16149 		tcpha->tha_offset_and_reserved +=
16150 		    ((num_sack_blk * 2 + 1) << 4);
16151 	}
16152 }
16153 
16154 /*
16155  * tcp_send() is called by tcp_wput_data() and returns one of the following:
16156  *
16157  * -1 = failed allocation.
16158  *  0 = success; burst count reached, or usable send window is too small,
16159  *      and that we'd rather wait until later before sending again.
16160  */
16161 static int
16162 tcp_send(tcp_t *tcp, const int mss, const int total_hdr_len,
16163     const int tcp_hdr_len, const int num_sack_blk, int *usable,
16164     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time)
16165 {
16166 	int		num_burst_seg = tcp->tcp_snd_burst;
16167 	int		num_lso_seg = 1;
16168 	uint_t		lso_usable;
16169 	boolean_t	do_lso_send = B_FALSE;
16170 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16171 	conn_t		*connp = tcp->tcp_connp;
16172 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
16173 
16174 	/*
16175 	 * Check LSO possibility. The value of tcp->tcp_lso indicates whether
16176 	 * the underlying connection is LSO capable. Will check whether having
16177 	 * enough available data to initiate LSO transmission in the for(){}
16178 	 * loops.
16179 	 */
16180 	if (tcp->tcp_lso && (tcp->tcp_valid_bits & ~TCP_FSS_VALID) == 0)
16181 		do_lso_send = B_TRUE;
16182 
16183 	for (;;) {
16184 		struct datab	*db;
16185 		tcpha_t		*tcpha;
16186 		uint32_t	sum;
16187 		mblk_t		*mp, *mp1;
16188 		uchar_t		*rptr;
16189 		int		len;
16190 
16191 		/*
16192 		 * Burst count reached, return successfully.
16193 		 */
16194 		if (num_burst_seg == 0)
16195 			break;
16196 
16197 		/*
16198 		 * Calculate the maximum payload length we can send at one
16199 		 * time.
16200 		 */
16201 		if (do_lso_send) {
16202 			/*
16203 			 * Check whether be able to to do LSO for the current
16204 			 * available data.
16205 			 */
16206 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
16207 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
16208 				lso_usable = MIN(lso_usable,
16209 				    num_burst_seg * mss);
16210 
16211 				num_lso_seg = lso_usable / mss;
16212 				if (lso_usable % mss) {
16213 					num_lso_seg++;
16214 					tcp->tcp_last_sent_len = (ushort_t)
16215 					    (lso_usable % mss);
16216 				} else {
16217 					tcp->tcp_last_sent_len = (ushort_t)mss;
16218 				}
16219 			} else {
16220 				do_lso_send = B_FALSE;
16221 				num_lso_seg = 1;
16222 				lso_usable = mss;
16223 			}
16224 		}
16225 
16226 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
16227 #ifdef DEBUG
16228 		DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg, boolean_t,
16229 		    do_lso_send);
16230 #endif
16231 		/*
16232 		 * Adjust num_burst_seg here.
16233 		 */
16234 		num_burst_seg -= num_lso_seg;
16235 
16236 		len = mss;
16237 		if (len > *usable) {
16238 			ASSERT(do_lso_send == B_FALSE);
16239 
16240 			len = *usable;
16241 			if (len <= 0) {
16242 				/* Terminate the loop */
16243 				break;	/* success; too small */
16244 			}
16245 			/*
16246 			 * Sender silly-window avoidance.
16247 			 * Ignore this if we are going to send a
16248 			 * zero window probe out.
16249 			 *
16250 			 * TODO: force data into microscopic window?
16251 			 *	==> (!pushed || (unsent > usable))
16252 			 */
16253 			if (len < (tcp->tcp_max_swnd >> 1) &&
16254 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
16255 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
16256 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
16257 				/*
16258 				 * If the retransmit timer is not running
16259 				 * we start it so that we will retransmit
16260 				 * in the case when the receiver has
16261 				 * decremented the window.
16262 				 */
16263 				if (*snxt == tcp->tcp_snxt &&
16264 				    *snxt == tcp->tcp_suna) {
16265 					/*
16266 					 * We are not supposed to send
16267 					 * anything.  So let's wait a little
16268 					 * bit longer before breaking SWS
16269 					 * avoidance.
16270 					 *
16271 					 * What should the value be?
16272 					 * Suggestion: MAX(init rexmit time,
16273 					 * tcp->tcp_rto)
16274 					 */
16275 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16276 				}
16277 				break;	/* success; too small */
16278 			}
16279 		}
16280 
16281 		tcpha = tcp->tcp_tcpha;
16282 
16283 		/*
16284 		 * The reason to adjust len here is that we need to set flags
16285 		 * and calculate checksum.
16286 		 */
16287 		if (do_lso_send)
16288 			len = lso_usable;
16289 
16290 		*usable -= len; /* Approximate - can be adjusted later */
16291 		if (*usable > 0)
16292 			tcpha->tha_flags = TH_ACK;
16293 		else
16294 			tcpha->tha_flags = (TH_ACK | TH_PUSH);
16295 
16296 		/*
16297 		 * Prime pump for IP's checksumming on our behalf.
16298 		 * Include the adjustment for a source route if any.
16299 		 * In case of LSO, the partial pseudo-header checksum should
16300 		 * exclusive TCP length, so zero tha_sum before IP calculate
16301 		 * pseudo-header checksum for partial checksum offload.
16302 		 */
16303 		if (do_lso_send) {
16304 			sum = 0;
16305 		} else {
16306 			sum = len + tcp_hdr_len + connp->conn_sum;
16307 			sum = (sum >> 16) + (sum & 0xFFFF);
16308 		}
16309 		tcpha->tha_sum = htons(sum);
16310 		tcpha->tha_seq = htonl(*snxt);
16311 
16312 		/*
16313 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
16314 		 * set.  For the case when TCP_FSS_VALID is the only valid
16315 		 * bit (normal active close), branch off only when we think
16316 		 * that the FIN flag needs to be set.  Note for this case,
16317 		 * that (snxt + len) may not reflect the actual seg_len,
16318 		 * as len may be further reduced in tcp_xmit_mp().  If len
16319 		 * gets modified, we will end up here again.
16320 		 */
16321 		if (tcp->tcp_valid_bits != 0 &&
16322 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
16323 		    ((*snxt + len) == tcp->tcp_fss))) {
16324 			uchar_t		*prev_rptr;
16325 			uint32_t	prev_snxt = tcp->tcp_snxt;
16326 
16327 			if (*tail_unsent == 0) {
16328 				ASSERT((*xmit_tail)->b_cont != NULL);
16329 				*xmit_tail = (*xmit_tail)->b_cont;
16330 				prev_rptr = (*xmit_tail)->b_rptr;
16331 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
16332 				    (*xmit_tail)->b_rptr);
16333 			} else {
16334 				prev_rptr = (*xmit_tail)->b_rptr;
16335 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
16336 				    *tail_unsent;
16337 			}
16338 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
16339 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
16340 			/* Restore tcp_snxt so we get amount sent right. */
16341 			tcp->tcp_snxt = prev_snxt;
16342 			if (prev_rptr == (*xmit_tail)->b_rptr) {
16343 				/*
16344 				 * If the previous timestamp is still in use,
16345 				 * don't stomp on it.
16346 				 */
16347 				if ((*xmit_tail)->b_next == NULL) {
16348 					(*xmit_tail)->b_prev = local_time;
16349 					(*xmit_tail)->b_next =
16350 					    (mblk_t *)(uintptr_t)(*snxt);
16351 				}
16352 			} else
16353 				(*xmit_tail)->b_rptr = prev_rptr;
16354 
16355 			if (mp == NULL) {
16356 				return (-1);
16357 			}
16358 			mp1 = mp->b_cont;
16359 
16360 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
16361 				tcp->tcp_last_sent_len = (ushort_t)len;
16362 			while (mp1->b_cont) {
16363 				*xmit_tail = (*xmit_tail)->b_cont;
16364 				(*xmit_tail)->b_prev = local_time;
16365 				(*xmit_tail)->b_next =
16366 				    (mblk_t *)(uintptr_t)(*snxt);
16367 				mp1 = mp1->b_cont;
16368 			}
16369 			*snxt += len;
16370 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
16371 			BUMP_LOCAL(tcp->tcp_obsegs);
16372 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16373 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16374 			tcp_send_data(tcp, mp);
16375 			continue;
16376 		}
16377 
16378 		*snxt += len;	/* Adjust later if we don't send all of len */
16379 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16380 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16381 
16382 		if (*tail_unsent) {
16383 			/* Are the bytes above us in flight? */
16384 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
16385 			if (rptr != (*xmit_tail)->b_rptr) {
16386 				*tail_unsent -= len;
16387 				if (len <= mss) /* LSO is unusable */
16388 					tcp->tcp_last_sent_len = (ushort_t)len;
16389 				len += total_hdr_len;
16390 				ixa->ixa_pktlen = len;
16391 
16392 				if (ixa->ixa_flags & IXAF_IS_IPV4) {
16393 					tcp->tcp_ipha->ipha_length = htons(len);
16394 				} else {
16395 					tcp->tcp_ip6h->ip6_plen =
16396 					    htons(len - IPV6_HDR_LEN);
16397 				}
16398 
16399 				mp = dupb(*xmit_tail);
16400 				if (mp == NULL) {
16401 					return (-1);	/* out_of_mem */
16402 				}
16403 				mp->b_rptr = rptr;
16404 				/*
16405 				 * If the old timestamp is no longer in use,
16406 				 * sample a new timestamp now.
16407 				 */
16408 				if ((*xmit_tail)->b_next == NULL) {
16409 					(*xmit_tail)->b_prev = local_time;
16410 					(*xmit_tail)->b_next =
16411 					    (mblk_t *)(uintptr_t)(*snxt-len);
16412 				}
16413 				goto must_alloc;
16414 			}
16415 		} else {
16416 			*xmit_tail = (*xmit_tail)->b_cont;
16417 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
16418 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
16419 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
16420 			    (*xmit_tail)->b_rptr);
16421 		}
16422 
16423 		(*xmit_tail)->b_prev = local_time;
16424 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
16425 
16426 		*tail_unsent -= len;
16427 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
16428 			tcp->tcp_last_sent_len = (ushort_t)len;
16429 
16430 		len += total_hdr_len;
16431 		ixa->ixa_pktlen = len;
16432 
16433 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
16434 			tcp->tcp_ipha->ipha_length = htons(len);
16435 		} else {
16436 			tcp->tcp_ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
16437 		}
16438 
16439 		mp = dupb(*xmit_tail);
16440 		if (mp == NULL) {
16441 			return (-1);	/* out_of_mem */
16442 		}
16443 
16444 		len = total_hdr_len;
16445 		/*
16446 		 * There are four reasons to allocate a new hdr mblk:
16447 		 *  1) The bytes above us are in use by another packet
16448 		 *  2) We don't have good alignment
16449 		 *  3) The mblk is being shared
16450 		 *  4) We don't have enough room for a header
16451 		 */
16452 		rptr = mp->b_rptr - len;
16453 		if (!OK_32PTR(rptr) ||
16454 		    ((db = mp->b_datap), db->db_ref != 2) ||
16455 		    rptr < db->db_base) {
16456 			/* NOTE: we assume allocb returns an OK_32PTR */
16457 
16458 		must_alloc:;
16459 			mp1 = allocb(connp->conn_ht_iphc_allocated +
16460 			    tcps->tcps_wroff_xtra, BPRI_MED);
16461 			if (mp1 == NULL) {
16462 				freemsg(mp);
16463 				return (-1);	/* out_of_mem */
16464 			}
16465 			mp1->b_cont = mp;
16466 			mp = mp1;
16467 			/* Leave room for Link Level header */
16468 			len = total_hdr_len;
16469 			rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
16470 			mp->b_wptr = &rptr[len];
16471 		}
16472 
16473 		/*
16474 		 * Fill in the header using the template header, and add
16475 		 * options such as time-stamp, ECN and/or SACK, as needed.
16476 		 */
16477 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
16478 
16479 		mp->b_rptr = rptr;
16480 
16481 		if (*tail_unsent) {
16482 			int spill = *tail_unsent;
16483 
16484 			mp1 = mp->b_cont;
16485 			if (mp1 == NULL)
16486 				mp1 = mp;
16487 
16488 			/*
16489 			 * If we're a little short, tack on more mblks until
16490 			 * there is no more spillover.
16491 			 */
16492 			while (spill < 0) {
16493 				mblk_t *nmp;
16494 				int nmpsz;
16495 
16496 				nmp = (*xmit_tail)->b_cont;
16497 				nmpsz = MBLKL(nmp);
16498 
16499 				/*
16500 				 * Excess data in mblk; can we split it?
16501 				 * If LSO is enabled for the connection,
16502 				 * keep on splitting as this is a transient
16503 				 * send path.
16504 				 */
16505 				if (!do_lso_send && (spill + nmpsz > 0)) {
16506 					/*
16507 					 * Don't split if stream head was
16508 					 * told to break up larger writes
16509 					 * into smaller ones.
16510 					 */
16511 					if (tcp->tcp_maxpsz_multiplier > 0)
16512 						break;
16513 
16514 					/*
16515 					 * Next mblk is less than SMSS/2
16516 					 * rounded up to nearest 64-byte;
16517 					 * let it get sent as part of the
16518 					 * next segment.
16519 					 */
16520 					if (tcp->tcp_localnet &&
16521 					    !tcp->tcp_cork &&
16522 					    (nmpsz < roundup((mss >> 1), 64)))
16523 						break;
16524 				}
16525 
16526 				*xmit_tail = nmp;
16527 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
16528 				/* Stash for rtt use later */
16529 				(*xmit_tail)->b_prev = local_time;
16530 				(*xmit_tail)->b_next =
16531 				    (mblk_t *)(uintptr_t)(*snxt - len);
16532 				mp1->b_cont = dupb(*xmit_tail);
16533 				mp1 = mp1->b_cont;
16534 
16535 				spill += nmpsz;
16536 				if (mp1 == NULL) {
16537 					*tail_unsent = spill;
16538 					freemsg(mp);
16539 					return (-1);	/* out_of_mem */
16540 				}
16541 			}
16542 
16543 			/* Trim back any surplus on the last mblk */
16544 			if (spill >= 0) {
16545 				mp1->b_wptr -= spill;
16546 				*tail_unsent = spill;
16547 			} else {
16548 				/*
16549 				 * We did not send everything we could in
16550 				 * order to remain within the b_cont limit.
16551 				 */
16552 				*usable -= spill;
16553 				*snxt += spill;
16554 				tcp->tcp_last_sent_len += spill;
16555 				UPDATE_MIB(&tcps->tcps_mib,
16556 				    tcpOutDataBytes, spill);
16557 				/*
16558 				 * Adjust the checksum
16559 				 */
16560 				tcpha = (tcpha_t *)(rptr +
16561 				    ixa->ixa_ip_hdr_length);
16562 				sum += spill;
16563 				sum = (sum >> 16) + (sum & 0xFFFF);
16564 				tcpha->tha_sum = htons(sum);
16565 				if (connp->conn_ipversion == IPV4_VERSION) {
16566 					sum = ntohs(
16567 					    ((ipha_t *)rptr)->ipha_length) +
16568 					    spill;
16569 					((ipha_t *)rptr)->ipha_length =
16570 					    htons(sum);
16571 				} else {
16572 					sum = ntohs(
16573 					    ((ip6_t *)rptr)->ip6_plen) +
16574 					    spill;
16575 					((ip6_t *)rptr)->ip6_plen =
16576 					    htons(sum);
16577 				}
16578 				ixa->ixa_pktlen += spill;
16579 				*tail_unsent = 0;
16580 			}
16581 		}
16582 		if (tcp->tcp_ip_forward_progress) {
16583 			tcp->tcp_ip_forward_progress = B_FALSE;
16584 			ixa->ixa_flags |= IXAF_REACH_CONF;
16585 		} else {
16586 			ixa->ixa_flags &= ~IXAF_REACH_CONF;
16587 		}
16588 
16589 		/*
16590 		 * Append LSO information, both flags and mss, to the mp.
16591 		 */
16592 		if (do_lso_send) {
16593 			lso_info_set(mp, mss, HW_LSO);
16594 			ixa->ixa_fragsize = IP_MAXPACKET;
16595 			ixa->ixa_extra_ident = num_lso_seg - 1;
16596 
16597 			DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg,
16598 			    boolean_t, B_TRUE);
16599 
16600 			tcp_send_data(tcp, mp);
16601 
16602 			/*
16603 			 * Restore values of ixa_fragsize and ixa_extra_ident.
16604 			 */
16605 			ixa->ixa_fragsize = ixa->ixa_pmtu;
16606 			ixa->ixa_extra_ident = 0;
16607 			tcp->tcp_obsegs += num_lso_seg;
16608 			TCP_STAT(tcps, tcp_lso_times);
16609 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
16610 		} else {
16611 			tcp_send_data(tcp, mp);
16612 			BUMP_LOCAL(tcp->tcp_obsegs);
16613 		}
16614 	}
16615 
16616 	return (0);
16617 }
16618 
16619 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
16620 static void
16621 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
16622 {
16623 	uchar_t	fval = *mp->b_rptr;
16624 	mblk_t	*tail;
16625 	conn_t	*connp = tcp->tcp_connp;
16626 	queue_t	*q = connp->conn_wq;
16627 
16628 	/* TODO: How should flush interact with urgent data? */
16629 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
16630 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
16631 		/*
16632 		 * Flush only data that has not yet been put on the wire.  If
16633 		 * we flush data that we have already transmitted, life, as we
16634 		 * know it, may come to an end.
16635 		 */
16636 		tail = tcp->tcp_xmit_tail;
16637 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
16638 		tcp->tcp_xmit_tail_unsent = 0;
16639 		tcp->tcp_unsent = 0;
16640 		if (tail->b_wptr != tail->b_rptr)
16641 			tail = tail->b_cont;
16642 		if (tail) {
16643 			mblk_t **excess = &tcp->tcp_xmit_head;
16644 			for (;;) {
16645 				mblk_t *mp1 = *excess;
16646 				if (mp1 == tail)
16647 					break;
16648 				tcp->tcp_xmit_tail = mp1;
16649 				tcp->tcp_xmit_last = mp1;
16650 				excess = &mp1->b_cont;
16651 			}
16652 			*excess = NULL;
16653 			tcp_close_mpp(&tail);
16654 			if (tcp->tcp_snd_zcopy_aware)
16655 				tcp_zcopy_notify(tcp);
16656 		}
16657 		/*
16658 		 * We have no unsent data, so unsent must be less than
16659 		 * conn_sndlowat, so re-enable flow.
16660 		 */
16661 		mutex_enter(&tcp->tcp_non_sq_lock);
16662 		if (tcp->tcp_flow_stopped) {
16663 			tcp_clrqfull(tcp);
16664 		}
16665 		mutex_exit(&tcp->tcp_non_sq_lock);
16666 	}
16667 	/*
16668 	 * TODO: you can't just flush these, you have to increase rwnd for one
16669 	 * thing.  For another, how should urgent data interact?
16670 	 */
16671 	if (fval & FLUSHR) {
16672 		*mp->b_rptr = fval & ~FLUSHW;
16673 		/* XXX */
16674 		qreply(q, mp);
16675 		return;
16676 	}
16677 	freemsg(mp);
16678 }
16679 
16680 /*
16681  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
16682  * messages.
16683  */
16684 static void
16685 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
16686 {
16687 	mblk_t		*mp1;
16688 	struct iocblk	*iocp = (struct iocblk *)mp->b_rptr;
16689 	STRUCT_HANDLE(strbuf, sb);
16690 	uint_t		addrlen;
16691 	conn_t		*connp = tcp->tcp_connp;
16692 	queue_t 	*q = connp->conn_wq;
16693 
16694 	/* Make sure it is one of ours. */
16695 	switch (iocp->ioc_cmd) {
16696 	case TI_GETMYNAME:
16697 	case TI_GETPEERNAME:
16698 		break;
16699 	default:
16700 		/*
16701 		 * If the conn is closing, then error the ioctl here. Otherwise
16702 		 * use the CONN_IOCTLREF_* macros to hold off tcp_close until
16703 		 * we're done here. We also need to decrement the ioctlref which
16704 		 * was bumped in either tcp_ioctl or tcp_wput_ioctl.
16705 		 */
16706 		mutex_enter(&connp->conn_lock);
16707 		if (connp->conn_state_flags & CONN_CLOSING) {
16708 			mutex_exit(&connp->conn_lock);
16709 			iocp = (struct iocblk *)mp->b_rptr;
16710 			iocp->ioc_error = EINVAL;
16711 			mp->b_datap->db_type = M_IOCNAK;
16712 			iocp->ioc_count = 0;
16713 			qreply(q, mp);
16714 			return;
16715 		}
16716 
16717 		CONN_INC_IOCTLREF_LOCKED(connp);
16718 		ip_wput_nondata(q, mp);
16719 		CONN_DEC_IOCTLREF(connp);
16720 		return;
16721 	}
16722 	switch (mi_copy_state(q, mp, &mp1)) {
16723 	case -1:
16724 		return;
16725 	case MI_COPY_CASE(MI_COPY_IN, 1):
16726 		break;
16727 	case MI_COPY_CASE(MI_COPY_OUT, 1):
16728 		/* Copy out the strbuf. */
16729 		mi_copyout(q, mp);
16730 		return;
16731 	case MI_COPY_CASE(MI_COPY_OUT, 2):
16732 		/* All done. */
16733 		mi_copy_done(q, mp, 0);
16734 		return;
16735 	default:
16736 		mi_copy_done(q, mp, EPROTO);
16737 		return;
16738 	}
16739 	/* Check alignment of the strbuf */
16740 	if (!OK_32PTR(mp1->b_rptr)) {
16741 		mi_copy_done(q, mp, EINVAL);
16742 		return;
16743 	}
16744 
16745 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
16746 
16747 	if (connp->conn_family == AF_INET)
16748 		addrlen = sizeof (sin_t);
16749 	else
16750 		addrlen = sizeof (sin6_t);
16751 
16752 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
16753 		mi_copy_done(q, mp, EINVAL);
16754 		return;
16755 	}
16756 
16757 	switch (iocp->ioc_cmd) {
16758 	case TI_GETMYNAME:
16759 		break;
16760 	case TI_GETPEERNAME:
16761 		if (tcp->tcp_state < TCPS_SYN_RCVD) {
16762 			mi_copy_done(q, mp, ENOTCONN);
16763 			return;
16764 		}
16765 		break;
16766 	}
16767 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
16768 	if (!mp1)
16769 		return;
16770 
16771 	STRUCT_FSET(sb, len, addrlen);
16772 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
16773 	case TI_GETMYNAME:
16774 		(void) conn_getsockname(connp, (struct sockaddr *)mp1->b_wptr,
16775 		    &addrlen);
16776 		break;
16777 	case TI_GETPEERNAME:
16778 		(void) conn_getpeername(connp, (struct sockaddr *)mp1->b_wptr,
16779 		    &addrlen);
16780 		break;
16781 	}
16782 	mp1->b_wptr += addrlen;
16783 	/* Copy out the address */
16784 	mi_copyout(q, mp);
16785 }
16786 
16787 static void
16788 tcp_use_pure_tpi(tcp_t *tcp)
16789 {
16790 	conn_t		*connp = tcp->tcp_connp;
16791 
16792 #ifdef	_ILP32
16793 	tcp->tcp_acceptor_id = (t_uscalar_t)connp->conn_rq;
16794 #else
16795 	tcp->tcp_acceptor_id = connp->conn_dev;
16796 #endif
16797 	/*
16798 	 * Insert this socket into the acceptor hash.
16799 	 * We might need it for T_CONN_RES message
16800 	 */
16801 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
16802 
16803 	tcp->tcp_issocket = B_FALSE;
16804 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
16805 }
16806 
16807 /*
16808  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
16809  * messages.
16810  */
16811 /* ARGSUSED */
16812 static void
16813 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16814 {
16815 	conn_t 		*connp = (conn_t *)arg;
16816 	tcp_t		*tcp = connp->conn_tcp;
16817 	queue_t		*q = connp->conn_wq;
16818 	struct iocblk	*iocp;
16819 
16820 	ASSERT(DB_TYPE(mp) == M_IOCTL);
16821 	/*
16822 	 * Try and ASSERT the minimum possible references on the
16823 	 * conn early enough. Since we are executing on write side,
16824 	 * the connection is obviously not detached and that means
16825 	 * there is a ref each for TCP and IP. Since we are behind
16826 	 * the squeue, the minimum references needed are 3. If the
16827 	 * conn is in classifier hash list, there should be an
16828 	 * extra ref for that (we check both the possibilities).
16829 	 */
16830 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16831 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16832 
16833 	iocp = (struct iocblk *)mp->b_rptr;
16834 	switch (iocp->ioc_cmd) {
16835 	case _SIOCSOCKFALLBACK:
16836 		/*
16837 		 * Either sockmod is about to be popped and the socket
16838 		 * would now be treated as a plain stream, or a module
16839 		 * is about to be pushed so we could no longer use read-
16840 		 * side synchronous streams for fused loopback tcp.
16841 		 * Drain any queued data and disable direct sockfs
16842 		 * interface from now on.
16843 		 */
16844 		if (!tcp->tcp_issocket) {
16845 			DB_TYPE(mp) = M_IOCNAK;
16846 			iocp->ioc_error = EINVAL;
16847 		} else {
16848 			tcp_use_pure_tpi(tcp);
16849 			DB_TYPE(mp) = M_IOCACK;
16850 			iocp->ioc_error = 0;
16851 		}
16852 		iocp->ioc_count = 0;
16853 		iocp->ioc_rval = 0;
16854 		qreply(q, mp);
16855 		return;
16856 	}
16857 
16858 	/*
16859 	 * If the conn is closing, then error the ioctl here. Otherwise bump the
16860 	 * conn_ioctlref to hold off tcp_close until we're done here.
16861 	 */
16862 	mutex_enter(&(connp)->conn_lock);
16863 	if ((connp)->conn_state_flags & CONN_CLOSING) {
16864 		mutex_exit(&(connp)->conn_lock);
16865 		iocp->ioc_error = EINVAL;
16866 		mp->b_datap->db_type = M_IOCNAK;
16867 		iocp->ioc_count = 0;
16868 		qreply(q, mp);
16869 		return;
16870 	}
16871 
16872 	CONN_INC_IOCTLREF_LOCKED(connp);
16873 	ip_wput_nondata(q, mp);
16874 	CONN_DEC_IOCTLREF(connp);
16875 }
16876 
16877 /*
16878  * This routine is called by tcp_wput() to handle all TPI requests.
16879  */
16880 /* ARGSUSED */
16881 static void
16882 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16883 {
16884 	conn_t		*connp = (conn_t *)arg;
16885 	tcp_t		*tcp = connp->conn_tcp;
16886 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
16887 	uchar_t		*rptr;
16888 	t_scalar_t	type;
16889 	cred_t		*cr;
16890 
16891 	/*
16892 	 * Try and ASSERT the minimum possible references on the
16893 	 * conn early enough. Since we are executing on write side,
16894 	 * the connection is obviously not detached and that means
16895 	 * there is a ref each for TCP and IP. Since we are behind
16896 	 * the squeue, the minimum references needed are 3. If the
16897 	 * conn is in classifier hash list, there should be an
16898 	 * extra ref for that (we check both the possibilities).
16899 	 */
16900 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16901 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16902 
16903 	rptr = mp->b_rptr;
16904 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
16905 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
16906 		type = ((union T_primitives *)rptr)->type;
16907 		if (type == T_EXDATA_REQ) {
16908 			tcp_output_urgent(connp, mp, arg2, NULL);
16909 		} else if (type != T_DATA_REQ) {
16910 			goto non_urgent_data;
16911 		} else {
16912 			/* TODO: options, flags, ... from user */
16913 			/* Set length to zero for reclamation below */
16914 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
16915 			freeb(mp);
16916 		}
16917 		return;
16918 	} else {
16919 		if (connp->conn_debug) {
16920 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
16921 			    "tcp_wput_proto, dropping one...");
16922 		}
16923 		freemsg(mp);
16924 		return;
16925 	}
16926 
16927 non_urgent_data:
16928 
16929 	switch ((int)tprim->type) {
16930 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
16931 		/*
16932 		 * save the kssl_ent_t from the next block, and convert this
16933 		 * back to a normal bind_req.
16934 		 */
16935 		if (mp->b_cont != NULL) {
16936 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
16937 
16938 			if (tcp->tcp_kssl_ent != NULL) {
16939 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
16940 				    KSSL_NO_PROXY);
16941 				tcp->tcp_kssl_ent = NULL;
16942 			}
16943 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
16944 			    sizeof (kssl_ent_t));
16945 			kssl_hold_ent(tcp->tcp_kssl_ent);
16946 			freemsg(mp->b_cont);
16947 			mp->b_cont = NULL;
16948 		}
16949 		tprim->type = T_BIND_REQ;
16950 
16951 	/* FALLTHROUGH */
16952 	case O_T_BIND_REQ:	/* bind request */
16953 	case T_BIND_REQ:	/* new semantics bind request */
16954 		tcp_tpi_bind(tcp, mp);
16955 		break;
16956 	case T_UNBIND_REQ:	/* unbind request */
16957 		tcp_tpi_unbind(tcp, mp);
16958 		break;
16959 	case O_T_CONN_RES:	/* old connection response XXX */
16960 	case T_CONN_RES:	/* connection response */
16961 		tcp_tli_accept(tcp, mp);
16962 		break;
16963 	case T_CONN_REQ:	/* connection request */
16964 		tcp_tpi_connect(tcp, mp);
16965 		break;
16966 	case T_DISCON_REQ:	/* disconnect request */
16967 		tcp_disconnect(tcp, mp);
16968 		break;
16969 	case T_CAPABILITY_REQ:
16970 		tcp_capability_req(tcp, mp);	/* capability request */
16971 		break;
16972 	case T_INFO_REQ:	/* information request */
16973 		tcp_info_req(tcp, mp);
16974 		break;
16975 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
16976 	case T_OPTMGMT_REQ:
16977 		/*
16978 		 * Note:  no support for snmpcom_req() through new
16979 		 * T_OPTMGMT_REQ. See comments in ip.c
16980 		 */
16981 
16982 		/*
16983 		 * All Solaris components should pass a db_credp
16984 		 * for this TPI message, hence we ASSERT.
16985 		 * But in case there is some other M_PROTO that looks
16986 		 * like a TPI message sent by some other kernel
16987 		 * component, we check and return an error.
16988 		 */
16989 		cr = msg_getcred(mp, NULL);
16990 		ASSERT(cr != NULL);
16991 		if (cr == NULL) {
16992 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
16993 			return;
16994 		}
16995 		/*
16996 		 * If EINPROGRESS is returned, the request has been queued
16997 		 * for subsequent processing by ip_restart_optmgmt(), which
16998 		 * will do the CONN_DEC_REF().
16999 		 */
17000 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
17001 			svr4_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17002 		} else {
17003 			tpi_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17004 		}
17005 		break;
17006 
17007 	case T_UNITDATA_REQ:	/* unitdata request */
17008 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17009 		break;
17010 	case T_ORDREL_REQ:	/* orderly release req */
17011 		freemsg(mp);
17012 
17013 		if (tcp->tcp_fused)
17014 			tcp_unfuse(tcp);
17015 
17016 		if (tcp_xmit_end(tcp) != 0) {
17017 			/*
17018 			 * We were crossing FINs and got a reset from
17019 			 * the other side. Just ignore it.
17020 			 */
17021 			if (connp->conn_debug) {
17022 				(void) strlog(TCP_MOD_ID, 0, 1,
17023 				    SL_ERROR|SL_TRACE,
17024 				    "tcp_wput_proto, T_ORDREL_REQ out of "
17025 				    "state %s",
17026 				    tcp_display(tcp, NULL,
17027 				    DISP_ADDR_AND_PORT));
17028 			}
17029 		}
17030 		break;
17031 	case T_ADDR_REQ:
17032 		tcp_addr_req(tcp, mp);
17033 		break;
17034 	default:
17035 		if (connp->conn_debug) {
17036 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
17037 			    "tcp_wput_proto, bogus TPI msg, type %d",
17038 			    tprim->type);
17039 		}
17040 		/*
17041 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
17042 		 * to recover.
17043 		 */
17044 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17045 		break;
17046 	}
17047 }
17048 
17049 /*
17050  * The TCP write service routine should never be called...
17051  */
17052 /* ARGSUSED */
17053 static void
17054 tcp_wsrv(queue_t *q)
17055 {
17056 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17057 
17058 	TCP_STAT(tcps, tcp_wsrv_called);
17059 }
17060 
17061 /*
17062  * Send out a control packet on the tcp connection specified.  This routine
17063  * is typically called where we need a simple ACK or RST generated.
17064  */
17065 static void
17066 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
17067 {
17068 	uchar_t		*rptr;
17069 	tcpha_t		*tcpha;
17070 	ipha_t		*ipha = NULL;
17071 	ip6_t		*ip6h = NULL;
17072 	uint32_t	sum;
17073 	int		total_hdr_len;
17074 	int		ip_hdr_len;
17075 	mblk_t		*mp;
17076 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17077 	conn_t		*connp = tcp->tcp_connp;
17078 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17079 
17080 	/*
17081 	 * Save sum for use in source route later.
17082 	 */
17083 	sum = connp->conn_ht_ulp_len + connp->conn_sum;
17084 	total_hdr_len = connp->conn_ht_iphc_len;
17085 	ip_hdr_len = ixa->ixa_ip_hdr_length;
17086 
17087 	/* If a text string is passed in with the request, pass it to strlog. */
17088 	if (str != NULL && connp->conn_debug) {
17089 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17090 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
17091 		    str, seq, ack, ctl);
17092 	}
17093 	mp = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17094 	    BPRI_MED);
17095 	if (mp == NULL) {
17096 		return;
17097 	}
17098 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
17099 	mp->b_rptr = rptr;
17100 	mp->b_wptr = &rptr[total_hdr_len];
17101 	bcopy(connp->conn_ht_iphc, rptr, total_hdr_len);
17102 
17103 	ixa->ixa_pktlen = total_hdr_len;
17104 
17105 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
17106 		ipha = (ipha_t *)rptr;
17107 		ipha->ipha_length = htons(total_hdr_len);
17108 	} else {
17109 		ip6h = (ip6_t *)rptr;
17110 		ip6h->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
17111 	}
17112 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17113 	tcpha->tha_flags = (uint8_t)ctl;
17114 	if (ctl & TH_RST) {
17115 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17116 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17117 		/*
17118 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
17119 		 */
17120 		if (tcp->tcp_snd_ts_ok &&
17121 		    tcp->tcp_state > TCPS_SYN_SENT) {
17122 			mp->b_wptr = &rptr[total_hdr_len - TCPOPT_REAL_TS_LEN];
17123 			*(mp->b_wptr) = TCPOPT_EOL;
17124 
17125 			ixa->ixa_pktlen = total_hdr_len - TCPOPT_REAL_TS_LEN;
17126 
17127 			if (connp->conn_ipversion == IPV4_VERSION) {
17128 				ipha->ipha_length = htons(total_hdr_len -
17129 				    TCPOPT_REAL_TS_LEN);
17130 			} else {
17131 				ip6h->ip6_plen = htons(total_hdr_len -
17132 				    IPV6_HDR_LEN - TCPOPT_REAL_TS_LEN);
17133 			}
17134 			tcpha->tha_offset_and_reserved -= (3 << 4);
17135 			sum -= TCPOPT_REAL_TS_LEN;
17136 		}
17137 	}
17138 	if (ctl & TH_ACK) {
17139 		if (tcp->tcp_snd_ts_ok) {
17140 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17141 
17142 			U32_TO_BE32(llbolt,
17143 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17144 			U32_TO_BE32(tcp->tcp_ts_recent,
17145 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17146 		}
17147 
17148 		/* Update the latest receive window size in TCP header. */
17149 		tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17150 		/* Track what we sent to the peer */
17151 		tcp->tcp_tcpha->tha_win = tcpha->tha_win;
17152 		tcp->tcp_rack = ack;
17153 		tcp->tcp_rack_cnt = 0;
17154 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
17155 	}
17156 	BUMP_LOCAL(tcp->tcp_obsegs);
17157 	tcpha->tha_seq = htonl(seq);
17158 	tcpha->tha_ack = htonl(ack);
17159 	/*
17160 	 * Include the adjustment for a source route if any.
17161 	 */
17162 	sum = (sum >> 16) + (sum & 0xFFFF);
17163 	tcpha->tha_sum = htons(sum);
17164 	tcp_send_data(tcp, mp);
17165 }
17166 
17167 /*
17168  * If this routine returns B_TRUE, TCP can generate a RST in response
17169  * to a segment.  If it returns B_FALSE, TCP should not respond.
17170  */
17171 static boolean_t
17172 tcp_send_rst_chk(tcp_stack_t *tcps)
17173 {
17174 	int64_t	now;
17175 
17176 	/*
17177 	 * TCP needs to protect itself from generating too many RSTs.
17178 	 * This can be a DoS attack by sending us random segments
17179 	 * soliciting RSTs.
17180 	 *
17181 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
17182 	 * in each 1 second interval.  In this way, TCP still generate
17183 	 * RSTs in normal cases but when under attack, the impact is
17184 	 * limited.
17185 	 */
17186 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
17187 		now = ddi_get_lbolt64();
17188 		if (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
17189 		    1*SECONDS) {
17190 			tcps->tcps_last_rst_intrvl = now;
17191 			tcps->tcps_rst_cnt = 1;
17192 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
17193 			return (B_FALSE);
17194 		}
17195 	}
17196 	return (B_TRUE);
17197 }
17198 
17199 /*
17200  * Generate a reset based on an inbound packet, connp is set by caller
17201  * when RST is in response to an unexpected inbound packet for which
17202  * there is active tcp state in the system.
17203  *
17204  * IPSEC NOTE : Try to send the reply with the same protection as it came
17205  * in.  We have the ip_recv_attr_t which is reversed to form the ip_xmit_attr_t.
17206  * That way the packet will go out at the same level of protection as it
17207  * came in with.
17208  */
17209 static void
17210 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl,
17211     ip_recv_attr_t *ira, ip_stack_t *ipst, conn_t *connp)
17212 {
17213 	ipha_t		*ipha = NULL;
17214 	ip6_t		*ip6h = NULL;
17215 	ushort_t	len;
17216 	tcpha_t		*tcpha;
17217 	int		i;
17218 	ipaddr_t	v4addr;
17219 	in6_addr_t	v6addr;
17220 	netstack_t	*ns = ipst->ips_netstack;
17221 	tcp_stack_t	*tcps = ns->netstack_tcp;
17222 	ip_xmit_attr_t	ixas, *ixa;
17223 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17224 	boolean_t	need_refrele = B_FALSE;		/* ixa_refrele(ixa) */
17225 	ushort_t	port;
17226 
17227 	if (!tcp_send_rst_chk(tcps)) {
17228 		TCP_STAT(tcps, tcp_rst_unsent);
17229 		freemsg(mp);
17230 		return;
17231 	}
17232 
17233 	/*
17234 	 * If connp != NULL we use conn_ixa to keep IP_NEXTHOP and other
17235 	 * options from the listener. In that case the caller must ensure that
17236 	 * we are running on the listener = connp squeue.
17237 	 *
17238 	 * We get a safe copy of conn_ixa so we don't need to restore anything
17239 	 * we or ip_output_simple might change in the ixa.
17240 	 */
17241 	if (connp != NULL) {
17242 		ASSERT(connp->conn_on_sqp);
17243 
17244 		ixa = conn_get_ixa_exclusive(connp);
17245 		if (ixa == NULL) {
17246 			TCP_STAT(tcps, tcp_rst_unsent);
17247 			freemsg(mp);
17248 			return;
17249 		}
17250 		need_refrele = B_TRUE;
17251 	} else {
17252 		bzero(&ixas, sizeof (ixas));
17253 		ixa = &ixas;
17254 		/*
17255 		 * IXAF_VERIFY_SOURCE is overkill since we know the
17256 		 * packet was for us.
17257 		 */
17258 		ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE;
17259 		ixa->ixa_protocol = IPPROTO_TCP;
17260 		ixa->ixa_zoneid = ira->ira_zoneid;
17261 		ixa->ixa_ifindex = 0;
17262 		ixa->ixa_ipst = ipst;
17263 		ixa->ixa_cred = kcred;
17264 		ixa->ixa_cpid = NOPID;
17265 	}
17266 
17267 	if (str && tcps->tcps_dbg) {
17268 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17269 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
17270 		    "flags 0x%x",
17271 		    str, seq, ack, ctl);
17272 	}
17273 	if (mp->b_datap->db_ref != 1) {
17274 		mblk_t *mp1 = copyb(mp);
17275 		freemsg(mp);
17276 		mp = mp1;
17277 		if (mp == NULL)
17278 			goto done;
17279 	} else if (mp->b_cont) {
17280 		freemsg(mp->b_cont);
17281 		mp->b_cont = NULL;
17282 		DB_CKSUMFLAGS(mp) = 0;
17283 	}
17284 	/*
17285 	 * We skip reversing source route here.
17286 	 * (for now we replace all IP options with EOL)
17287 	 */
17288 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17289 		ipha = (ipha_t *)mp->b_rptr;
17290 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
17291 			mp->b_rptr[i] = IPOPT_EOL;
17292 		/*
17293 		 * Make sure that src address isn't flagrantly invalid.
17294 		 * Not all broadcast address checking for the src address
17295 		 * is possible, since we don't know the netmask of the src
17296 		 * addr.  No check for destination address is done, since
17297 		 * IP will not pass up a packet with a broadcast dest
17298 		 * address to TCP.  Similar checks are done below for IPv6.
17299 		 */
17300 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
17301 		    CLASSD(ipha->ipha_src)) {
17302 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
17303 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17304 			freemsg(mp);
17305 			goto done;
17306 		}
17307 	} else {
17308 		ip6h = (ip6_t *)mp->b_rptr;
17309 
17310 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
17311 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
17312 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
17313 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17314 			freemsg(mp);
17315 			goto done;
17316 		}
17317 
17318 		/* Remove any extension headers assuming partial overlay */
17319 		if (ip_hdr_len > IPV6_HDR_LEN) {
17320 			uint8_t *to;
17321 
17322 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
17323 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
17324 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
17325 			ip_hdr_len = IPV6_HDR_LEN;
17326 			ip6h = (ip6_t *)mp->b_rptr;
17327 			ip6h->ip6_nxt = IPPROTO_TCP;
17328 		}
17329 	}
17330 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
17331 	if (tcpha->tha_flags & TH_RST) {
17332 		freemsg(mp);
17333 		goto done;
17334 	}
17335 	tcpha->tha_offset_and_reserved = (5 << 4);
17336 	len = ip_hdr_len + sizeof (tcpha_t);
17337 	mp->b_wptr = &mp->b_rptr[len];
17338 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17339 		ipha->ipha_length = htons(len);
17340 		/* Swap addresses */
17341 		v4addr = ipha->ipha_src;
17342 		ipha->ipha_src = ipha->ipha_dst;
17343 		ipha->ipha_dst = v4addr;
17344 		ipha->ipha_ident = 0;
17345 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
17346 		ixa->ixa_flags |= IXAF_IS_IPV4;
17347 		ixa->ixa_ip_hdr_length = ip_hdr_len;
17348 	} else {
17349 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
17350 		/* Swap addresses */
17351 		v6addr = ip6h->ip6_src;
17352 		ip6h->ip6_src = ip6h->ip6_dst;
17353 		ip6h->ip6_dst = v6addr;
17354 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
17355 		ixa->ixa_flags &= ~IXAF_IS_IPV4;
17356 
17357 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_dst)) {
17358 			ixa->ixa_flags |= IXAF_SCOPEID_SET;
17359 			ixa->ixa_scopeid = ira->ira_ruifindex;
17360 		}
17361 		ixa->ixa_ip_hdr_length = IPV6_HDR_LEN;
17362 	}
17363 	ixa->ixa_pktlen = len;
17364 
17365 	/* Swap the ports */
17366 	port = tcpha->tha_fport;
17367 	tcpha->tha_fport = tcpha->tha_lport;
17368 	tcpha->tha_lport = port;
17369 
17370 	tcpha->tha_ack = htonl(ack);
17371 	tcpha->tha_seq = htonl(seq);
17372 	tcpha->tha_win = 0;
17373 	tcpha->tha_sum = htons(sizeof (tcpha_t));
17374 	tcpha->tha_flags = (uint8_t)ctl;
17375 	if (ctl & TH_RST) {
17376 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17377 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17378 	}
17379 
17380 	/* Discard any old label */
17381 	if (ixa->ixa_free_flags & IXA_FREE_TSL) {
17382 		ASSERT(ixa->ixa_tsl != NULL);
17383 		label_rele(ixa->ixa_tsl);
17384 		ixa->ixa_free_flags &= ~IXA_FREE_TSL;
17385 	}
17386 	ixa->ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
17387 
17388 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
17389 		/*
17390 		 * Apply IPsec based on how IPsec was applied to
17391 		 * the packet that caused the RST.
17392 		 */
17393 		if (!ipsec_in_to_out(ira, ixa, mp, ipha, ip6h)) {
17394 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
17395 			/* Note: mp already consumed and ip_drop_packet done */
17396 			goto done;
17397 		}
17398 	} else {
17399 		/*
17400 		 * This is in clear. The RST message we are building
17401 		 * here should go out in clear, independent of our policy.
17402 		 */
17403 		ixa->ixa_flags |= IXAF_NO_IPSEC;
17404 	}
17405 
17406 	/*
17407 	 * NOTE:  one might consider tracing a TCP packet here, but
17408 	 * this function has no active TCP state and no tcp structure
17409 	 * that has a trace buffer.  If we traced here, we would have
17410 	 * to keep a local trace buffer in tcp_record_trace().
17411 	 */
17412 
17413 	(void) ip_output_simple(mp, ixa);
17414 done:
17415 	ixa_cleanup(ixa);
17416 	if (need_refrele) {
17417 		ASSERT(ixa != &ixas);
17418 		ixa_refrele(ixa);
17419 	}
17420 }
17421 
17422 /*
17423  * Initiate closedown sequence on an active connection.  (May be called as
17424  * writer.)  Return value zero for OK return, non-zero for error return.
17425  */
17426 static int
17427 tcp_xmit_end(tcp_t *tcp)
17428 {
17429 	mblk_t		*mp;
17430 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17431 	iulp_t		uinfo;
17432 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17433 	conn_t		*connp = tcp->tcp_connp;
17434 
17435 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
17436 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
17437 		/*
17438 		 * Invalid state, only states TCPS_SYN_RCVD,
17439 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
17440 		 */
17441 		return (-1);
17442 	}
17443 
17444 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
17445 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
17446 	/*
17447 	 * If there is nothing more unsent, send the FIN now.
17448 	 * Otherwise, it will go out with the last segment.
17449 	 */
17450 	if (tcp->tcp_unsent == 0) {
17451 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
17452 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
17453 
17454 		if (mp) {
17455 			tcp_send_data(tcp, mp);
17456 		} else {
17457 			/*
17458 			 * Couldn't allocate msg.  Pretend we got it out.
17459 			 * Wait for rexmit timeout.
17460 			 */
17461 			tcp->tcp_snxt = tcp->tcp_fss + 1;
17462 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17463 		}
17464 
17465 		/*
17466 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
17467 		 * changed.
17468 		 */
17469 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
17470 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
17471 		}
17472 	} else {
17473 		/*
17474 		 * If tcp->tcp_cork is set, then the data will not get sent,
17475 		 * so we have to check that and unset it first.
17476 		 */
17477 		if (tcp->tcp_cork)
17478 			tcp->tcp_cork = B_FALSE;
17479 		tcp_wput_data(tcp, NULL, B_FALSE);
17480 	}
17481 
17482 	/*
17483 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
17484 	 * is 0, don't update the cache.
17485 	 */
17486 	if (tcps->tcps_rtt_updates == 0 ||
17487 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
17488 		return (0);
17489 
17490 	/*
17491 	 * We do not have a good algorithm to update ssthresh at this time.
17492 	 * So don't do any update.
17493 	 */
17494 	bzero(&uinfo, sizeof (uinfo));
17495 	uinfo.iulp_rtt = tcp->tcp_rtt_sa;
17496 	uinfo.iulp_rtt_sd = tcp->tcp_rtt_sd;
17497 
17498 	/*
17499 	 * Note that uinfo is kept for conn_faddr in the DCE. Could update even
17500 	 * if source routed but we don't.
17501 	 */
17502 	if (connp->conn_ipversion == IPV4_VERSION) {
17503 		if (connp->conn_faddr_v4 !=  tcp->tcp_ipha->ipha_dst) {
17504 			return (0);
17505 		}
17506 		(void) dce_update_uinfo_v4(connp->conn_faddr_v4, &uinfo, ipst);
17507 	} else {
17508 		uint_t ifindex;
17509 
17510 		if (!(IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
17511 		    &tcp->tcp_ip6h->ip6_dst))) {
17512 			return (0);
17513 		}
17514 		ifindex = 0;
17515 		if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_faddr_v6)) {
17516 			ip_xmit_attr_t *ixa = connp->conn_ixa;
17517 
17518 			/*
17519 			 * If we are going to create a DCE we'd better have
17520 			 * an ifindex
17521 			 */
17522 			if (ixa->ixa_nce != NULL) {
17523 				ifindex = ixa->ixa_nce->nce_common->ncec_ill->
17524 				    ill_phyint->phyint_ifindex;
17525 			} else {
17526 				return (0);
17527 			}
17528 		}
17529 
17530 		(void) dce_update_uinfo(&connp->conn_faddr_v6, ifindex, &uinfo,
17531 		    ipst);
17532 	}
17533 	return (0);
17534 }
17535 
17536 /*
17537  * Generate a "no listener here" RST in response to an "unknown" segment.
17538  * connp is set by caller when RST is in response to an unexpected
17539  * inbound packet for which there is active tcp state in the system.
17540  * Note that we are reusing the incoming mp to construct the outgoing RST.
17541  */
17542 void
17543 tcp_xmit_listeners_reset(mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst,
17544     conn_t *connp)
17545 {
17546 	uchar_t		*rptr;
17547 	uint32_t	seg_len;
17548 	tcpha_t		*tcpha;
17549 	uint32_t	seg_seq;
17550 	uint32_t	seg_ack;
17551 	uint_t		flags;
17552 	ipha_t 		*ipha;
17553 	ip6_t 		*ip6h;
17554 	boolean_t	policy_present;
17555 	netstack_t	*ns = ipst->ips_netstack;
17556 	tcp_stack_t	*tcps = ns->netstack_tcp;
17557 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
17558 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17559 
17560 	TCP_STAT(tcps, tcp_no_listener);
17561 
17562 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17563 		policy_present = ipss->ipsec_inbound_v4_policy_present;
17564 		ipha = (ipha_t *)mp->b_rptr;
17565 		ip6h = NULL;
17566 	} else {
17567 		policy_present = ipss->ipsec_inbound_v6_policy_present;
17568 		ipha = NULL;
17569 		ip6h = (ip6_t *)mp->b_rptr;
17570 	}
17571 
17572 	if (policy_present) {
17573 		/*
17574 		 * The conn_t parameter is NULL because we already know
17575 		 * nobody's home.
17576 		 */
17577 		mp = ipsec_check_global_policy(mp, (conn_t *)NULL, ipha, ip6h,
17578 		    ira, ns);
17579 		if (mp == NULL)
17580 			return;
17581 	}
17582 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
17583 		DTRACE_PROBE2(
17584 		    tx__ip__log__error__nolistener__tcp,
17585 		    char *, "Could not reply with RST to mp(1)",
17586 		    mblk_t *, mp);
17587 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
17588 		freemsg(mp);
17589 		return;
17590 	}
17591 
17592 	rptr = mp->b_rptr;
17593 
17594 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17595 	seg_seq = ntohl(tcpha->tha_seq);
17596 	seg_ack = ntohl(tcpha->tha_ack);
17597 	flags = tcpha->tha_flags;
17598 
17599 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcpha) + ip_hdr_len);
17600 	if (flags & TH_RST) {
17601 		freemsg(mp);
17602 	} else if (flags & TH_ACK) {
17603 		tcp_xmit_early_reset("no tcp, reset", mp, seg_ack, 0, TH_RST,
17604 		    ira, ipst, connp);
17605 	} else {
17606 		if (flags & TH_SYN) {
17607 			seg_len++;
17608 		} else {
17609 			/*
17610 			 * Here we violate the RFC.  Note that a normal
17611 			 * TCP will never send a segment without the ACK
17612 			 * flag, except for RST or SYN segment.  This
17613 			 * segment is neither.  Just drop it on the
17614 			 * floor.
17615 			 */
17616 			freemsg(mp);
17617 			TCP_STAT(tcps, tcp_rst_unsent);
17618 			return;
17619 		}
17620 
17621 		tcp_xmit_early_reset("no tcp, reset/ack", mp, 0,
17622 		    seg_seq + seg_len, TH_RST | TH_ACK, ira, ipst, connp);
17623 	}
17624 }
17625 
17626 /*
17627  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
17628  * ip and tcp header ready to pass down to IP.  If the mp passed in is
17629  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
17630  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
17631  * otherwise it will dup partial mblks.)
17632  * Otherwise, an appropriate ACK packet will be generated.  This
17633  * routine is not usually called to send new data for the first time.  It
17634  * is mostly called out of the timer for retransmits, and to generate ACKs.
17635  *
17636  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
17637  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
17638  * of the original mblk chain will be returned in *offset and *end_mp.
17639  */
17640 mblk_t *
17641 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
17642     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
17643     boolean_t rexmit)
17644 {
17645 	int	data_length;
17646 	int32_t	off = 0;
17647 	uint_t	flags;
17648 	mblk_t	*mp1;
17649 	mblk_t	*mp2;
17650 	uchar_t	*rptr;
17651 	tcpha_t	*tcpha;
17652 	int32_t	num_sack_blk = 0;
17653 	int32_t	sack_opt_len = 0;
17654 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17655 	conn_t		*connp = tcp->tcp_connp;
17656 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17657 
17658 	/* Allocate for our maximum TCP header + link-level */
17659 	mp1 = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17660 	    BPRI_MED);
17661 	if (!mp1)
17662 		return (NULL);
17663 	data_length = 0;
17664 
17665 	/*
17666 	 * Note that tcp_mss has been adjusted to take into account the
17667 	 * timestamp option if applicable.  Because SACK options do not
17668 	 * appear in every TCP segments and they are of variable lengths,
17669 	 * they cannot be included in tcp_mss.  Thus we need to calculate
17670 	 * the actual segment length when we need to send a segment which
17671 	 * includes SACK options.
17672 	 */
17673 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
17674 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
17675 		    tcp->tcp_num_sack_blk);
17676 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
17677 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
17678 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
17679 			max_to_send -= sack_opt_len;
17680 	}
17681 
17682 	if (offset != NULL) {
17683 		off = *offset;
17684 		/* We use offset as an indicator that end_mp is not NULL. */
17685 		*end_mp = NULL;
17686 	}
17687 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
17688 		/* This could be faster with cooperation from downstream */
17689 		if (mp2 != mp1 && !sendall &&
17690 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
17691 		    max_to_send)
17692 			/*
17693 			 * Don't send the next mblk since the whole mblk
17694 			 * does not fit.
17695 			 */
17696 			break;
17697 		mp2->b_cont = dupb(mp);
17698 		mp2 = mp2->b_cont;
17699 		if (!mp2) {
17700 			freemsg(mp1);
17701 			return (NULL);
17702 		}
17703 		mp2->b_rptr += off;
17704 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
17705 		    (uintptr_t)INT_MAX);
17706 
17707 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
17708 		if (data_length > max_to_send) {
17709 			mp2->b_wptr -= data_length - max_to_send;
17710 			data_length = max_to_send;
17711 			off = mp2->b_wptr - mp->b_rptr;
17712 			break;
17713 		} else {
17714 			off = 0;
17715 		}
17716 	}
17717 	if (offset != NULL) {
17718 		*offset = off;
17719 		*end_mp = mp;
17720 	}
17721 	if (seg_len != NULL) {
17722 		*seg_len = data_length;
17723 	}
17724 
17725 	/* Update the latest receive window size in TCP header. */
17726 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17727 
17728 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
17729 	mp1->b_rptr = rptr;
17730 	mp1->b_wptr = rptr + connp->conn_ht_iphc_len + sack_opt_len;
17731 	bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
17732 	tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
17733 	tcpha->tha_seq = htonl(seq);
17734 
17735 	/*
17736 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
17737 	 * that this function was called from tcp_wput_data. Thus, when called
17738 	 * to retransmit data the setting of the PUSH bit may appear some
17739 	 * what random in that it might get set when it should not. This
17740 	 * should not pose any performance issues.
17741 	 */
17742 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
17743 	    tcp->tcp_unsent == data_length)) {
17744 		flags = TH_ACK | TH_PUSH;
17745 	} else {
17746 		flags = TH_ACK;
17747 	}
17748 
17749 	if (tcp->tcp_ecn_ok) {
17750 		if (tcp->tcp_ecn_echo_on)
17751 			flags |= TH_ECE;
17752 
17753 		/*
17754 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
17755 		 * There is no TCP flow control for non-data segments, and
17756 		 * only data segment is transmitted reliably.
17757 		 */
17758 		if (data_length > 0 && !rexmit) {
17759 			SET_ECT(tcp, rptr);
17760 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17761 				flags |= TH_CWR;
17762 				tcp->tcp_ecn_cwr_sent = B_TRUE;
17763 			}
17764 		}
17765 	}
17766 
17767 	if (tcp->tcp_valid_bits) {
17768 		uint32_t u1;
17769 
17770 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
17771 		    seq == tcp->tcp_iss) {
17772 			uchar_t	*wptr;
17773 
17774 			/*
17775 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
17776 			 * TCP can only be in SYN-SENT, SYN-RCVD or
17777 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
17778 			 * our SYN is not ack'ed but the app closes this
17779 			 * TCP connection.
17780 			 */
17781 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
17782 			    tcp->tcp_state == TCPS_SYN_RCVD ||
17783 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
17784 
17785 			/*
17786 			 * Tack on the MSS option.  It is always needed
17787 			 * for both active and passive open.
17788 			 *
17789 			 * MSS option value should be interface MTU - MIN
17790 			 * TCP/IP header according to RFC 793 as it means
17791 			 * the maximum segment size TCP can receive.  But
17792 			 * to get around some broken middle boxes/end hosts
17793 			 * out there, we allow the option value to be the
17794 			 * same as the MSS option size on the peer side.
17795 			 * In this way, the other side will not send
17796 			 * anything larger than they can receive.
17797 			 *
17798 			 * Note that for SYN_SENT state, the ndd param
17799 			 * tcp_use_smss_as_mss_opt has no effect as we
17800 			 * don't know the peer's MSS option value. So
17801 			 * the only case we need to take care of is in
17802 			 * SYN_RCVD state, which is done later.
17803 			 */
17804 			wptr = mp1->b_wptr;
17805 			wptr[0] = TCPOPT_MAXSEG;
17806 			wptr[1] = TCPOPT_MAXSEG_LEN;
17807 			wptr += 2;
17808 			u1 = tcp->tcp_initial_pmtu -
17809 			    (connp->conn_ipversion == IPV4_VERSION ?
17810 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
17811 			    TCP_MIN_HEADER_LENGTH;
17812 			U16_TO_BE16(u1, wptr);
17813 			mp1->b_wptr = wptr + 2;
17814 			/* Update the offset to cover the additional word */
17815 			tcpha->tha_offset_and_reserved += (1 << 4);
17816 
17817 			/*
17818 			 * Note that the following way of filling in
17819 			 * TCP options are not optimal.  Some NOPs can
17820 			 * be saved.  But there is no need at this time
17821 			 * to optimize it.  When it is needed, we will
17822 			 * do it.
17823 			 */
17824 			switch (tcp->tcp_state) {
17825 			case TCPS_SYN_SENT:
17826 				flags = TH_SYN;
17827 
17828 				if (tcp->tcp_snd_ts_ok) {
17829 					uint32_t llbolt =
17830 					    (uint32_t)LBOLT_FASTPATH;
17831 
17832 					wptr = mp1->b_wptr;
17833 					wptr[0] = TCPOPT_NOP;
17834 					wptr[1] = TCPOPT_NOP;
17835 					wptr[2] = TCPOPT_TSTAMP;
17836 					wptr[3] = TCPOPT_TSTAMP_LEN;
17837 					wptr += 4;
17838 					U32_TO_BE32(llbolt, wptr);
17839 					wptr += 4;
17840 					ASSERT(tcp->tcp_ts_recent == 0);
17841 					U32_TO_BE32(0L, wptr);
17842 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
17843 					tcpha->tha_offset_and_reserved +=
17844 					    (3 << 4);
17845 				}
17846 
17847 				/*
17848 				 * Set up all the bits to tell other side
17849 				 * we are ECN capable.
17850 				 */
17851 				if (tcp->tcp_ecn_ok) {
17852 					flags |= (TH_ECE | TH_CWR);
17853 				}
17854 				break;
17855 			case TCPS_SYN_RCVD:
17856 				flags |= TH_SYN;
17857 
17858 				/*
17859 				 * Reset the MSS option value to be SMSS
17860 				 * We should probably add back the bytes
17861 				 * for timestamp option and IPsec.  We
17862 				 * don't do that as this is a workaround
17863 				 * for broken middle boxes/end hosts, it
17864 				 * is better for us to be more cautious.
17865 				 * They may not take these things into
17866 				 * account in their SMSS calculation.  Thus
17867 				 * the peer's calculated SMSS may be smaller
17868 				 * than what it can be.  This should be OK.
17869 				 */
17870 				if (tcps->tcps_use_smss_as_mss_opt) {
17871 					u1 = tcp->tcp_mss;
17872 					U16_TO_BE16(u1, wptr);
17873 				}
17874 
17875 				/*
17876 				 * If the other side is ECN capable, reply
17877 				 * that we are also ECN capable.
17878 				 */
17879 				if (tcp->tcp_ecn_ok)
17880 					flags |= TH_ECE;
17881 				break;
17882 			default:
17883 				/*
17884 				 * The above ASSERT() makes sure that this
17885 				 * must be FIN-WAIT-1 state.  Our SYN has
17886 				 * not been ack'ed so retransmit it.
17887 				 */
17888 				flags |= TH_SYN;
17889 				break;
17890 			}
17891 
17892 			if (tcp->tcp_snd_ws_ok) {
17893 				wptr = mp1->b_wptr;
17894 				wptr[0] =  TCPOPT_NOP;
17895 				wptr[1] =  TCPOPT_WSCALE;
17896 				wptr[2] =  TCPOPT_WS_LEN;
17897 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
17898 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
17899 				tcpha->tha_offset_and_reserved += (1 << 4);
17900 			}
17901 
17902 			if (tcp->tcp_snd_sack_ok) {
17903 				wptr = mp1->b_wptr;
17904 				wptr[0] = TCPOPT_NOP;
17905 				wptr[1] = TCPOPT_NOP;
17906 				wptr[2] = TCPOPT_SACK_PERMITTED;
17907 				wptr[3] = TCPOPT_SACK_OK_LEN;
17908 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
17909 				tcpha->tha_offset_and_reserved += (1 << 4);
17910 			}
17911 
17912 			/* allocb() of adequate mblk assures space */
17913 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
17914 			    (uintptr_t)INT_MAX);
17915 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
17916 			/*
17917 			 * Get IP set to checksum on our behalf
17918 			 * Include the adjustment for a source route if any.
17919 			 */
17920 			u1 += connp->conn_sum;
17921 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
17922 			tcpha->tha_sum = htons(u1);
17923 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17924 		}
17925 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17926 		    (seq + data_length) == tcp->tcp_fss) {
17927 			if (!tcp->tcp_fin_acked) {
17928 				flags |= TH_FIN;
17929 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17930 			}
17931 			if (!tcp->tcp_fin_sent) {
17932 				tcp->tcp_fin_sent = B_TRUE;
17933 				switch (tcp->tcp_state) {
17934 				case TCPS_SYN_RCVD:
17935 				case TCPS_ESTABLISHED:
17936 					tcp->tcp_state = TCPS_FIN_WAIT_1;
17937 					break;
17938 				case TCPS_CLOSE_WAIT:
17939 					tcp->tcp_state = TCPS_LAST_ACK;
17940 					break;
17941 				}
17942 				if (tcp->tcp_suna == tcp->tcp_snxt)
17943 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17944 				tcp->tcp_snxt = tcp->tcp_fss + 1;
17945 			}
17946 		}
17947 		/*
17948 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
17949 		 * is smaller than seq, u1 will become a very huge value.
17950 		 * So the comparison will fail.  Also note that tcp_urp
17951 		 * should be positive, see RFC 793 page 17.
17952 		 */
17953 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
17954 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
17955 		    u1 < (uint32_t)(64 * 1024)) {
17956 			flags |= TH_URG;
17957 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
17958 			tcpha->tha_urp = htons(u1);
17959 		}
17960 	}
17961 	tcpha->tha_flags = (uchar_t)flags;
17962 	tcp->tcp_rack = tcp->tcp_rnxt;
17963 	tcp->tcp_rack_cnt = 0;
17964 
17965 	if (tcp->tcp_snd_ts_ok) {
17966 		if (tcp->tcp_state != TCPS_SYN_SENT) {
17967 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17968 
17969 			U32_TO_BE32(llbolt,
17970 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17971 			U32_TO_BE32(tcp->tcp_ts_recent,
17972 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17973 		}
17974 	}
17975 
17976 	if (num_sack_blk > 0) {
17977 		uchar_t *wptr = (uchar_t *)tcpha + connp->conn_ht_ulp_len;
17978 		sack_blk_t *tmp;
17979 		int32_t	i;
17980 
17981 		wptr[0] = TCPOPT_NOP;
17982 		wptr[1] = TCPOPT_NOP;
17983 		wptr[2] = TCPOPT_SACK;
17984 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
17985 		    sizeof (sack_blk_t);
17986 		wptr += TCPOPT_REAL_SACK_LEN;
17987 
17988 		tmp = tcp->tcp_sack_list;
17989 		for (i = 0; i < num_sack_blk; i++) {
17990 			U32_TO_BE32(tmp[i].begin, wptr);
17991 			wptr += sizeof (tcp_seq);
17992 			U32_TO_BE32(tmp[i].end, wptr);
17993 			wptr += sizeof (tcp_seq);
17994 		}
17995 		tcpha->tha_offset_and_reserved += ((num_sack_blk * 2 + 1) << 4);
17996 	}
17997 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
17998 	data_length += (int)(mp1->b_wptr - rptr);
17999 
18000 	ixa->ixa_pktlen = data_length;
18001 
18002 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
18003 		((ipha_t *)rptr)->ipha_length = htons(data_length);
18004 	} else {
18005 		ip6_t *ip6 = (ip6_t *)rptr;
18006 
18007 		ip6->ip6_plen = htons(data_length - IPV6_HDR_LEN);
18008 	}
18009 
18010 	/*
18011 	 * Prime pump for IP
18012 	 * Include the adjustment for a source route if any.
18013 	 */
18014 	data_length -= ixa->ixa_ip_hdr_length;
18015 	data_length += connp->conn_sum;
18016 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
18017 	tcpha->tha_sum = htons(data_length);
18018 	if (tcp->tcp_ip_forward_progress) {
18019 		tcp->tcp_ip_forward_progress = B_FALSE;
18020 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18021 	} else {
18022 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18023 	}
18024 	return (mp1);
18025 }
18026 
18027 /* This function handles the push timeout. */
18028 void
18029 tcp_push_timer(void *arg)
18030 {
18031 	conn_t	*connp = (conn_t *)arg;
18032 	tcp_t *tcp = connp->conn_tcp;
18033 
18034 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
18035 
18036 	ASSERT(tcp->tcp_listener == NULL);
18037 
18038 	ASSERT(!IPCL_IS_NONSTR(connp));
18039 
18040 	tcp->tcp_push_tid = 0;
18041 
18042 	if (tcp->tcp_rcv_list != NULL &&
18043 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
18044 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
18045 }
18046 
18047 /*
18048  * This function handles delayed ACK timeout.
18049  */
18050 static void
18051 tcp_ack_timer(void *arg)
18052 {
18053 	conn_t	*connp = (conn_t *)arg;
18054 	tcp_t *tcp = connp->conn_tcp;
18055 	mblk_t *mp;
18056 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18057 
18058 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
18059 
18060 	tcp->tcp_ack_tid = 0;
18061 
18062 	if (tcp->tcp_fused)
18063 		return;
18064 
18065 	/*
18066 	 * Do not send ACK if there is no outstanding unack'ed data.
18067 	 */
18068 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
18069 		return;
18070 	}
18071 
18072 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
18073 		/*
18074 		 * Make sure we don't allow deferred ACKs to result in
18075 		 * timer-based ACKing.  If we have held off an ACK
18076 		 * when there was more than an mss here, and the timer
18077 		 * goes off, we have to worry about the possibility
18078 		 * that the sender isn't doing slow-start, or is out
18079 		 * of step with us for some other reason.  We fall
18080 		 * permanently back in the direction of
18081 		 * ACK-every-other-packet as suggested in RFC 1122.
18082 		 */
18083 		if (tcp->tcp_rack_abs_max > 2)
18084 			tcp->tcp_rack_abs_max--;
18085 		tcp->tcp_rack_cur_max = 2;
18086 	}
18087 	mp = tcp_ack_mp(tcp);
18088 
18089 	if (mp != NULL) {
18090 		BUMP_LOCAL(tcp->tcp_obsegs);
18091 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
18092 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
18093 		tcp_send_data(tcp, mp);
18094 	}
18095 }
18096 
18097 
18098 /* Generate an ACK-only (no data) segment for a TCP endpoint */
18099 static mblk_t *
18100 tcp_ack_mp(tcp_t *tcp)
18101 {
18102 	uint32_t	seq_no;
18103 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18104 	conn_t		*connp = tcp->tcp_connp;
18105 
18106 	/*
18107 	 * There are a few cases to be considered while setting the sequence no.
18108 	 * Essentially, we can come here while processing an unacceptable pkt
18109 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
18110 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
18111 	 * If we are here for a zero window probe, stick with suna. In all
18112 	 * other cases, we check if suna + swnd encompasses snxt and set
18113 	 * the sequence number to snxt, if so. If snxt falls outside the
18114 	 * window (the receiver probably shrunk its window), we will go with
18115 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
18116 	 * receiver.
18117 	 */
18118 	if (tcp->tcp_zero_win_probe) {
18119 		seq_no = tcp->tcp_suna;
18120 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
18121 		ASSERT(tcp->tcp_swnd == 0);
18122 		seq_no = tcp->tcp_snxt;
18123 	} else {
18124 		seq_no = SEQ_GT(tcp->tcp_snxt,
18125 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
18126 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
18127 	}
18128 
18129 	if (tcp->tcp_valid_bits) {
18130 		/*
18131 		 * For the complex case where we have to send some
18132 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
18133 		 */
18134 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
18135 		    NULL, B_FALSE));
18136 	} else {
18137 		/* Generate a simple ACK */
18138 		int	data_length;
18139 		uchar_t	*rptr;
18140 		tcpha_t	*tcpha;
18141 		mblk_t	*mp1;
18142 		int32_t	total_hdr_len;
18143 		int32_t	tcp_hdr_len;
18144 		int32_t	num_sack_blk = 0;
18145 		int32_t sack_opt_len;
18146 		ip_xmit_attr_t *ixa = connp->conn_ixa;
18147 
18148 		/*
18149 		 * Allocate space for TCP + IP headers
18150 		 * and link-level header
18151 		 */
18152 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18153 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18154 			    tcp->tcp_num_sack_blk);
18155 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
18156 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
18157 			total_hdr_len = connp->conn_ht_iphc_len + sack_opt_len;
18158 			tcp_hdr_len = connp->conn_ht_ulp_len + sack_opt_len;
18159 		} else {
18160 			total_hdr_len = connp->conn_ht_iphc_len;
18161 			tcp_hdr_len = connp->conn_ht_ulp_len;
18162 		}
18163 		mp1 = allocb(total_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
18164 		if (!mp1)
18165 			return (NULL);
18166 
18167 		/* Update the latest receive window size in TCP header. */
18168 		tcp->tcp_tcpha->tha_win =
18169 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
18170 		/* copy in prototype TCP + IP header */
18171 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
18172 		mp1->b_rptr = rptr;
18173 		mp1->b_wptr = rptr + total_hdr_len;
18174 		bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
18175 
18176 		tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
18177 
18178 		/* Set the TCP sequence number. */
18179 		tcpha->tha_seq = htonl(seq_no);
18180 
18181 		/* Set up the TCP flag field. */
18182 		tcpha->tha_flags = (uchar_t)TH_ACK;
18183 		if (tcp->tcp_ecn_echo_on)
18184 			tcpha->tha_flags |= TH_ECE;
18185 
18186 		tcp->tcp_rack = tcp->tcp_rnxt;
18187 		tcp->tcp_rack_cnt = 0;
18188 
18189 		/* fill in timestamp option if in use */
18190 		if (tcp->tcp_snd_ts_ok) {
18191 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
18192 
18193 			U32_TO_BE32(llbolt,
18194 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
18195 			U32_TO_BE32(tcp->tcp_ts_recent,
18196 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
18197 		}
18198 
18199 		/* Fill in SACK options */
18200 		if (num_sack_blk > 0) {
18201 			uchar_t *wptr = (uchar_t *)tcpha +
18202 			    connp->conn_ht_ulp_len;
18203 			sack_blk_t *tmp;
18204 			int32_t	i;
18205 
18206 			wptr[0] = TCPOPT_NOP;
18207 			wptr[1] = TCPOPT_NOP;
18208 			wptr[2] = TCPOPT_SACK;
18209 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18210 			    sizeof (sack_blk_t);
18211 			wptr += TCPOPT_REAL_SACK_LEN;
18212 
18213 			tmp = tcp->tcp_sack_list;
18214 			for (i = 0; i < num_sack_blk; i++) {
18215 				U32_TO_BE32(tmp[i].begin, wptr);
18216 				wptr += sizeof (tcp_seq);
18217 				U32_TO_BE32(tmp[i].end, wptr);
18218 				wptr += sizeof (tcp_seq);
18219 			}
18220 			tcpha->tha_offset_and_reserved +=
18221 			    ((num_sack_blk * 2 + 1) << 4);
18222 		}
18223 
18224 		ixa->ixa_pktlen = total_hdr_len;
18225 
18226 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
18227 			((ipha_t *)rptr)->ipha_length = htons(total_hdr_len);
18228 		} else {
18229 			ip6_t *ip6 = (ip6_t *)rptr;
18230 
18231 			ip6->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
18232 		}
18233 
18234 		/*
18235 		 * Prime pump for checksum calculation in IP.  Include the
18236 		 * adjustment for a source route if any.
18237 		 */
18238 		data_length = tcp_hdr_len + connp->conn_sum;
18239 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
18240 		tcpha->tha_sum = htons(data_length);
18241 
18242 		if (tcp->tcp_ip_forward_progress) {
18243 			tcp->tcp_ip_forward_progress = B_FALSE;
18244 			connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18245 		} else {
18246 			connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18247 		}
18248 		return (mp1);
18249 	}
18250 }
18251 
18252 /*
18253  * Hash list insertion routine for tcp_t structures. Each hash bucket
18254  * contains a list of tcp_t entries, and each entry is bound to a unique
18255  * port. If there are multiple tcp_t's that are bound to the same port, then
18256  * one of them will be linked into the hash bucket list, and the rest will
18257  * hang off of that one entry. For each port, entries bound to a specific IP
18258  * address will be inserted before those those bound to INADDR_ANY.
18259  */
18260 static void
18261 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
18262 {
18263 	tcp_t	**tcpp;
18264 	tcp_t	*tcpnext;
18265 	tcp_t	*tcphash;
18266 	conn_t	*connp = tcp->tcp_connp;
18267 	conn_t	*connext;
18268 
18269 	if (tcp->tcp_ptpbhn != NULL) {
18270 		ASSERT(!caller_holds_lock);
18271 		tcp_bind_hash_remove(tcp);
18272 	}
18273 	tcpp = &tbf->tf_tcp;
18274 	if (!caller_holds_lock) {
18275 		mutex_enter(&tbf->tf_lock);
18276 	} else {
18277 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
18278 	}
18279 	tcphash = tcpp[0];
18280 	tcpnext = NULL;
18281 	if (tcphash != NULL) {
18282 		/* Look for an entry using the same port */
18283 		while ((tcphash = tcpp[0]) != NULL &&
18284 		    connp->conn_lport != tcphash->tcp_connp->conn_lport)
18285 			tcpp = &(tcphash->tcp_bind_hash);
18286 
18287 		/* The port was not found, just add to the end */
18288 		if (tcphash == NULL)
18289 			goto insert;
18290 
18291 		/*
18292 		 * OK, there already exists an entry bound to the
18293 		 * same port.
18294 		 *
18295 		 * If the new tcp bound to the INADDR_ANY address
18296 		 * and the first one in the list is not bound to
18297 		 * INADDR_ANY we skip all entries until we find the
18298 		 * first one bound to INADDR_ANY.
18299 		 * This makes sure that applications binding to a
18300 		 * specific address get preference over those binding to
18301 		 * INADDR_ANY.
18302 		 */
18303 		tcpnext = tcphash;
18304 		connext = tcpnext->tcp_connp;
18305 		tcphash = NULL;
18306 		if (V6_OR_V4_INADDR_ANY(connp->conn_bound_addr_v6) &&
18307 		    !V6_OR_V4_INADDR_ANY(connext->conn_bound_addr_v6)) {
18308 			while ((tcpnext = tcpp[0]) != NULL) {
18309 				connext = tcpnext->tcp_connp;
18310 				if (!V6_OR_V4_INADDR_ANY(
18311 				    connext->conn_bound_addr_v6))
18312 					tcpp = &(tcpnext->tcp_bind_hash_port);
18313 				else
18314 					break;
18315 			}
18316 			if (tcpnext != NULL) {
18317 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18318 				tcphash = tcpnext->tcp_bind_hash;
18319 				if (tcphash != NULL) {
18320 					tcphash->tcp_ptpbhn =
18321 					    &(tcp->tcp_bind_hash);
18322 					tcpnext->tcp_bind_hash = NULL;
18323 				}
18324 			}
18325 		} else {
18326 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18327 			tcphash = tcpnext->tcp_bind_hash;
18328 			if (tcphash != NULL) {
18329 				tcphash->tcp_ptpbhn =
18330 				    &(tcp->tcp_bind_hash);
18331 				tcpnext->tcp_bind_hash = NULL;
18332 			}
18333 		}
18334 	}
18335 insert:
18336 	tcp->tcp_bind_hash_port = tcpnext;
18337 	tcp->tcp_bind_hash = tcphash;
18338 	tcp->tcp_ptpbhn = tcpp;
18339 	tcpp[0] = tcp;
18340 	if (!caller_holds_lock)
18341 		mutex_exit(&tbf->tf_lock);
18342 }
18343 
18344 /*
18345  * Hash list removal routine for tcp_t structures.
18346  */
18347 static void
18348 tcp_bind_hash_remove(tcp_t *tcp)
18349 {
18350 	tcp_t	*tcpnext;
18351 	kmutex_t *lockp;
18352 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18353 	conn_t		*connp = tcp->tcp_connp;
18354 
18355 	if (tcp->tcp_ptpbhn == NULL)
18356 		return;
18357 
18358 	/*
18359 	 * Extract the lock pointer in case there are concurrent
18360 	 * hash_remove's for this instance.
18361 	 */
18362 	ASSERT(connp->conn_lport != 0);
18363 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(
18364 	    connp->conn_lport)].tf_lock;
18365 
18366 	ASSERT(lockp != NULL);
18367 	mutex_enter(lockp);
18368 	if (tcp->tcp_ptpbhn) {
18369 		tcpnext = tcp->tcp_bind_hash_port;
18370 		if (tcpnext != NULL) {
18371 			tcp->tcp_bind_hash_port = NULL;
18372 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18373 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
18374 			if (tcpnext->tcp_bind_hash != NULL) {
18375 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
18376 				    &(tcpnext->tcp_bind_hash);
18377 				tcp->tcp_bind_hash = NULL;
18378 			}
18379 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
18380 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18381 			tcp->tcp_bind_hash = NULL;
18382 		}
18383 		*tcp->tcp_ptpbhn = tcpnext;
18384 		tcp->tcp_ptpbhn = NULL;
18385 	}
18386 	mutex_exit(lockp);
18387 }
18388 
18389 
18390 /*
18391  * Hash list lookup routine for tcp_t structures.
18392  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
18393  */
18394 static tcp_t *
18395 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
18396 {
18397 	tf_t	*tf;
18398 	tcp_t	*tcp;
18399 
18400 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18401 	mutex_enter(&tf->tf_lock);
18402 	for (tcp = tf->tf_tcp; tcp != NULL;
18403 	    tcp = tcp->tcp_acceptor_hash) {
18404 		if (tcp->tcp_acceptor_id == id) {
18405 			CONN_INC_REF(tcp->tcp_connp);
18406 			mutex_exit(&tf->tf_lock);
18407 			return (tcp);
18408 		}
18409 	}
18410 	mutex_exit(&tf->tf_lock);
18411 	return (NULL);
18412 }
18413 
18414 
18415 /*
18416  * Hash list insertion routine for tcp_t structures.
18417  */
18418 void
18419 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
18420 {
18421 	tf_t	*tf;
18422 	tcp_t	**tcpp;
18423 	tcp_t	*tcpnext;
18424 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18425 
18426 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18427 
18428 	if (tcp->tcp_ptpahn != NULL)
18429 		tcp_acceptor_hash_remove(tcp);
18430 	tcpp = &tf->tf_tcp;
18431 	mutex_enter(&tf->tf_lock);
18432 	tcpnext = tcpp[0];
18433 	if (tcpnext)
18434 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
18435 	tcp->tcp_acceptor_hash = tcpnext;
18436 	tcp->tcp_ptpahn = tcpp;
18437 	tcpp[0] = tcp;
18438 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
18439 	mutex_exit(&tf->tf_lock);
18440 }
18441 
18442 /*
18443  * Hash list removal routine for tcp_t structures.
18444  */
18445 static void
18446 tcp_acceptor_hash_remove(tcp_t *tcp)
18447 {
18448 	tcp_t	*tcpnext;
18449 	kmutex_t *lockp;
18450 
18451 	/*
18452 	 * Extract the lock pointer in case there are concurrent
18453 	 * hash_remove's for this instance.
18454 	 */
18455 	lockp = tcp->tcp_acceptor_lockp;
18456 
18457 	if (tcp->tcp_ptpahn == NULL)
18458 		return;
18459 
18460 	ASSERT(lockp != NULL);
18461 	mutex_enter(lockp);
18462 	if (tcp->tcp_ptpahn) {
18463 		tcpnext = tcp->tcp_acceptor_hash;
18464 		if (tcpnext) {
18465 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
18466 			tcp->tcp_acceptor_hash = NULL;
18467 		}
18468 		*tcp->tcp_ptpahn = tcpnext;
18469 		tcp->tcp_ptpahn = NULL;
18470 	}
18471 	mutex_exit(lockp);
18472 	tcp->tcp_acceptor_lockp = NULL;
18473 }
18474 
18475 /*
18476  * Type three generator adapted from the random() function in 4.4 BSD:
18477  */
18478 
18479 /*
18480  * Copyright (c) 1983, 1993
18481  *	The Regents of the University of California.  All rights reserved.
18482  *
18483  * Redistribution and use in source and binary forms, with or without
18484  * modification, are permitted provided that the following conditions
18485  * are met:
18486  * 1. Redistributions of source code must retain the above copyright
18487  *    notice, this list of conditions and the following disclaimer.
18488  * 2. Redistributions in binary form must reproduce the above copyright
18489  *    notice, this list of conditions and the following disclaimer in the
18490  *    documentation and/or other materials provided with the distribution.
18491  * 3. All advertising materials mentioning features or use of this software
18492  *    must display the following acknowledgement:
18493  *	This product includes software developed by the University of
18494  *	California, Berkeley and its contributors.
18495  * 4. Neither the name of the University nor the names of its contributors
18496  *    may be used to endorse or promote products derived from this software
18497  *    without specific prior written permission.
18498  *
18499  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18500  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18501  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18502  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18503  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18504  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
18505  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
18506  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18507  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18508  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
18509  * SUCH DAMAGE.
18510  */
18511 
18512 /* Type 3 -- x**31 + x**3 + 1 */
18513 #define	DEG_3		31
18514 #define	SEP_3		3
18515 
18516 
18517 /* Protected by tcp_random_lock */
18518 static int tcp_randtbl[DEG_3 + 1];
18519 
18520 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
18521 static int *tcp_random_rptr = &tcp_randtbl[1];
18522 
18523 static int *tcp_random_state = &tcp_randtbl[1];
18524 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
18525 
18526 kmutex_t tcp_random_lock;
18527 
18528 void
18529 tcp_random_init(void)
18530 {
18531 	int i;
18532 	hrtime_t hrt;
18533 	time_t wallclock;
18534 	uint64_t result;
18535 
18536 	/*
18537 	 * Use high-res timer and current time for seed.  Gethrtime() returns
18538 	 * a longlong, which may contain resolution down to nanoseconds.
18539 	 * The current time will either be a 32-bit or a 64-bit quantity.
18540 	 * XOR the two together in a 64-bit result variable.
18541 	 * Convert the result to a 32-bit value by multiplying the high-order
18542 	 * 32-bits by the low-order 32-bits.
18543 	 */
18544 
18545 	hrt = gethrtime();
18546 	(void) drv_getparm(TIME, &wallclock);
18547 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
18548 	mutex_enter(&tcp_random_lock);
18549 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
18550 	    (result & 0xffffffff);
18551 
18552 	for (i = 1; i < DEG_3; i++)
18553 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
18554 		    + 12345;
18555 	tcp_random_fptr = &tcp_random_state[SEP_3];
18556 	tcp_random_rptr = &tcp_random_state[0];
18557 	mutex_exit(&tcp_random_lock);
18558 	for (i = 0; i < 10 * DEG_3; i++)
18559 		(void) tcp_random();
18560 }
18561 
18562 /*
18563  * tcp_random: Return a random number in the range [1 - (128K + 1)].
18564  * This range is selected to be approximately centered on TCP_ISS / 2,
18565  * and easy to compute. We get this value by generating a 32-bit random
18566  * number, selecting out the high-order 17 bits, and then adding one so
18567  * that we never return zero.
18568  */
18569 int
18570 tcp_random(void)
18571 {
18572 	int i;
18573 
18574 	mutex_enter(&tcp_random_lock);
18575 	*tcp_random_fptr += *tcp_random_rptr;
18576 
18577 	/*
18578 	 * The high-order bits are more random than the low-order bits,
18579 	 * so we select out the high-order 17 bits and add one so that
18580 	 * we never return zero.
18581 	 */
18582 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
18583 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
18584 		tcp_random_fptr = tcp_random_state;
18585 		++tcp_random_rptr;
18586 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
18587 		tcp_random_rptr = tcp_random_state;
18588 
18589 	mutex_exit(&tcp_random_lock);
18590 	return (i);
18591 }
18592 
18593 static int
18594 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
18595     int *t_errorp, int *sys_errorp)
18596 {
18597 	int error;
18598 	int is_absreq_failure;
18599 	t_scalar_t *opt_lenp;
18600 	t_scalar_t opt_offset;
18601 	int prim_type;
18602 	struct T_conn_req *tcreqp;
18603 	struct T_conn_res *tcresp;
18604 	cred_t *cr;
18605 
18606 	/*
18607 	 * All Solaris components should pass a db_credp
18608 	 * for this TPI message, hence we ASSERT.
18609 	 * But in case there is some other M_PROTO that looks
18610 	 * like a TPI message sent by some other kernel
18611 	 * component, we check and return an error.
18612 	 */
18613 	cr = msg_getcred(mp, NULL);
18614 	ASSERT(cr != NULL);
18615 	if (cr == NULL)
18616 		return (-1);
18617 
18618 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
18619 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
18620 	    prim_type == T_CONN_RES);
18621 
18622 	switch (prim_type) {
18623 	case T_CONN_REQ:
18624 		tcreqp = (struct T_conn_req *)mp->b_rptr;
18625 		opt_offset = tcreqp->OPT_offset;
18626 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
18627 		break;
18628 	case O_T_CONN_RES:
18629 	case T_CONN_RES:
18630 		tcresp = (struct T_conn_res *)mp->b_rptr;
18631 		opt_offset = tcresp->OPT_offset;
18632 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
18633 		break;
18634 	}
18635 
18636 	*t_errorp = 0;
18637 	*sys_errorp = 0;
18638 	*do_disconnectp = 0;
18639 
18640 	error = tpi_optcom_buf(tcp->tcp_connp->conn_wq, mp, opt_lenp,
18641 	    opt_offset, cr, &tcp_opt_obj,
18642 	    NULL, &is_absreq_failure);
18643 
18644 	switch (error) {
18645 	case  0:		/* no error */
18646 		ASSERT(is_absreq_failure == 0);
18647 		return (0);
18648 	case ENOPROTOOPT:
18649 		*t_errorp = TBADOPT;
18650 		break;
18651 	case EACCES:
18652 		*t_errorp = TACCES;
18653 		break;
18654 	default:
18655 		*t_errorp = TSYSERR; *sys_errorp = error;
18656 		break;
18657 	}
18658 	if (is_absreq_failure != 0) {
18659 		/*
18660 		 * The connection request should get the local ack
18661 		 * T_OK_ACK and then a T_DISCON_IND.
18662 		 */
18663 		*do_disconnectp = 1;
18664 	}
18665 	return (-1);
18666 }
18667 
18668 /*
18669  * Split this function out so that if the secret changes, I'm okay.
18670  *
18671  * Initialize the tcp_iss_cookie and tcp_iss_key.
18672  */
18673 
18674 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
18675 
18676 static void
18677 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
18678 {
18679 	struct {
18680 		int32_t current_time;
18681 		uint32_t randnum;
18682 		uint16_t pad;
18683 		uint8_t ether[6];
18684 		uint8_t passwd[PASSWD_SIZE];
18685 	} tcp_iss_cookie;
18686 	time_t t;
18687 
18688 	/*
18689 	 * Start with the current absolute time.
18690 	 */
18691 	(void) drv_getparm(TIME, &t);
18692 	tcp_iss_cookie.current_time = t;
18693 
18694 	/*
18695 	 * XXX - Need a more random number per RFC 1750, not this crap.
18696 	 * OTOH, if what follows is pretty random, then I'm in better shape.
18697 	 */
18698 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
18699 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
18700 
18701 	/*
18702 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
18703 	 * as a good template.
18704 	 */
18705 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
18706 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
18707 
18708 	/*
18709 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
18710 	 */
18711 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
18712 
18713 	/*
18714 	 * See 4010593 if this section becomes a problem again,
18715 	 * but the local ethernet address is useful here.
18716 	 */
18717 	(void) localetheraddr(NULL,
18718 	    (struct ether_addr *)&tcp_iss_cookie.ether);
18719 
18720 	/*
18721 	 * Hash 'em all together.  The MD5Final is called per-connection.
18722 	 */
18723 	mutex_enter(&tcps->tcps_iss_key_lock);
18724 	MD5Init(&tcps->tcps_iss_key);
18725 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
18726 	    sizeof (tcp_iss_cookie));
18727 	mutex_exit(&tcps->tcps_iss_key_lock);
18728 }
18729 
18730 /*
18731  * Set the RFC 1948 pass phrase
18732  */
18733 /* ARGSUSED */
18734 static int
18735 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
18736     cred_t *cr)
18737 {
18738 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18739 
18740 	/*
18741 	 * Basically, value contains a new pass phrase.  Pass it along!
18742 	 */
18743 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
18744 	return (0);
18745 }
18746 
18747 /* ARGSUSED */
18748 static int
18749 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
18750 {
18751 	bzero(buf, sizeof (tcp_sack_info_t));
18752 	return (0);
18753 }
18754 
18755 /*
18756  * Called by IP when IP is loaded into the kernel
18757  */
18758 void
18759 tcp_ddi_g_init(void)
18760 {
18761 	tcp_timercache = kmem_cache_create("tcp_timercache",
18762 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
18763 	    NULL, NULL, NULL, NULL, NULL, 0);
18764 
18765 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
18766 	    sizeof (tcp_sack_info_t), 0,
18767 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
18768 
18769 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
18770 
18771 	/* Initialize the random number generator */
18772 	tcp_random_init();
18773 
18774 	/* A single callback independently of how many netstacks we have */
18775 	ip_squeue_init(tcp_squeue_add);
18776 
18777 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
18778 
18779 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
18780 
18781 	/*
18782 	 * We want to be informed each time a stack is created or
18783 	 * destroyed in the kernel, so we can maintain the
18784 	 * set of tcp_stack_t's.
18785 	 */
18786 	netstack_register(NS_TCP, tcp_stack_init, NULL, tcp_stack_fini);
18787 }
18788 
18789 
18790 #define	INET_NAME	"ip"
18791 
18792 /*
18793  * Initialize the TCP stack instance.
18794  */
18795 static void *
18796 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
18797 {
18798 	tcp_stack_t	*tcps;
18799 	tcpparam_t	*pa;
18800 	int		i;
18801 	int		error = 0;
18802 	major_t		major;
18803 
18804 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
18805 	tcps->tcps_netstack = ns;
18806 
18807 	/* Initialize locks */
18808 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
18809 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
18810 
18811 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
18812 	tcps->tcps_g_epriv_ports[0] = 2049;
18813 	tcps->tcps_g_epriv_ports[1] = 4045;
18814 	tcps->tcps_min_anonpriv_port = 512;
18815 
18816 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
18817 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
18818 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
18819 	    TCP_ACCEPTOR_FANOUT_SIZE, KM_SLEEP);
18820 
18821 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18822 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
18823 		    MUTEX_DEFAULT, NULL);
18824 	}
18825 
18826 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18827 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
18828 		    MUTEX_DEFAULT, NULL);
18829 	}
18830 
18831 	/* TCP's IPsec code calls the packet dropper. */
18832 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
18833 
18834 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
18835 	tcps->tcps_params = pa;
18836 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18837 
18838 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
18839 	    A_CNT(lcl_tcp_param_arr), tcps);
18840 
18841 	/*
18842 	 * Note: To really walk the device tree you need the devinfo
18843 	 * pointer to your device which is only available after probe/attach.
18844 	 * The following is safe only because it uses ddi_root_node()
18845 	 */
18846 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
18847 	    tcp_opt_obj.odb_opt_arr_cnt);
18848 
18849 	/*
18850 	 * Initialize RFC 1948 secret values.  This will probably be reset once
18851 	 * by the boot scripts.
18852 	 *
18853 	 * Use NULL name, as the name is caught by the new lockstats.
18854 	 *
18855 	 * Initialize with some random, non-guessable string, like the global
18856 	 * T_INFO_ACK.
18857 	 */
18858 
18859 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
18860 	    sizeof (tcp_g_t_info_ack), tcps);
18861 
18862 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
18863 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
18864 
18865 	major = mod_name_to_major(INET_NAME);
18866 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
18867 	ASSERT(error == 0);
18868 	tcps->tcps_ixa_cleanup_mp = allocb_wait(0, BPRI_MED, STR_NOSIG, NULL);
18869 	ASSERT(tcps->tcps_ixa_cleanup_mp != NULL);
18870 	cv_init(&tcps->tcps_ixa_cleanup_cv, NULL, CV_DEFAULT, NULL);
18871 	mutex_init(&tcps->tcps_ixa_cleanup_lock, NULL, MUTEX_DEFAULT, NULL);
18872 
18873 	mutex_init(&tcps->tcps_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
18874 	tcps->tcps_reclaim = B_FALSE;
18875 	tcps->tcps_reclaim_tid = 0;
18876 	tcps->tcps_reclaim_period = tcps->tcps_rexmit_interval_max * 3;
18877 
18878 	mutex_init(&tcps->tcps_listener_conf_lock, NULL, MUTEX_DEFAULT, NULL);
18879 	list_create(&tcps->tcps_listener_conf, sizeof (tcp_listener_t),
18880 	    offsetof(tcp_listener_t, tl_link));
18881 
18882 	return (tcps);
18883 }
18884 
18885 /*
18886  * Called when the IP module is about to be unloaded.
18887  */
18888 void
18889 tcp_ddi_g_destroy(void)
18890 {
18891 	tcp_g_kstat_fini(tcp_g_kstat);
18892 	tcp_g_kstat = NULL;
18893 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
18894 
18895 	mutex_destroy(&tcp_random_lock);
18896 
18897 	kmem_cache_destroy(tcp_timercache);
18898 	kmem_cache_destroy(tcp_sack_info_cache);
18899 
18900 	netstack_unregister(NS_TCP);
18901 }
18902 
18903 /*
18904  * Free the TCP stack instance.
18905  */
18906 static void
18907 tcp_stack_fini(netstackid_t stackid, void *arg)
18908 {
18909 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
18910 	int i;
18911 
18912 	freeb(tcps->tcps_ixa_cleanup_mp);
18913 	tcps->tcps_ixa_cleanup_mp = NULL;
18914 	cv_destroy(&tcps->tcps_ixa_cleanup_cv);
18915 	mutex_destroy(&tcps->tcps_ixa_cleanup_lock);
18916 
18917 	if (tcps->tcps_reclaim_tid != 0)
18918 		(void) untimeout(tcps->tcps_reclaim_tid);
18919 	mutex_destroy(&tcps->tcps_reclaim_lock);
18920 
18921 	tcp_listener_conf_cleanup(tcps);
18922 
18923 	nd_free(&tcps->tcps_g_nd);
18924 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18925 	tcps->tcps_params = NULL;
18926 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
18927 	tcps->tcps_wroff_xtra_param = NULL;
18928 
18929 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18930 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
18931 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
18932 	}
18933 
18934 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18935 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
18936 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
18937 	}
18938 
18939 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
18940 	tcps->tcps_bind_fanout = NULL;
18941 
18942 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) *
18943 	    TCP_ACCEPTOR_FANOUT_SIZE);
18944 	tcps->tcps_acceptor_fanout = NULL;
18945 
18946 	mutex_destroy(&tcps->tcps_iss_key_lock);
18947 	mutex_destroy(&tcps->tcps_epriv_port_lock);
18948 
18949 	ip_drop_unregister(&tcps->tcps_dropper);
18950 
18951 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
18952 	tcps->tcps_kstat = NULL;
18953 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
18954 
18955 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
18956 	tcps->tcps_mibkp = NULL;
18957 
18958 	ldi_ident_release(tcps->tcps_ldi_ident);
18959 	kmem_free(tcps, sizeof (*tcps));
18960 }
18961 
18962 /*
18963  * Generate ISS, taking into account NDD changes may happen halfway through.
18964  * (If the iss is not zero, set it.)
18965  */
18966 
18967 static void
18968 tcp_iss_init(tcp_t *tcp)
18969 {
18970 	MD5_CTX context;
18971 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
18972 	uint32_t answer[4];
18973 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18974 	conn_t		*connp = tcp->tcp_connp;
18975 
18976 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
18977 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
18978 	switch (tcps->tcps_strong_iss) {
18979 	case 2:
18980 		mutex_enter(&tcps->tcps_iss_key_lock);
18981 		context = tcps->tcps_iss_key;
18982 		mutex_exit(&tcps->tcps_iss_key_lock);
18983 		arg.ports = connp->conn_ports;
18984 		arg.src = connp->conn_laddr_v6;
18985 		arg.dst = connp->conn_faddr_v6;
18986 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
18987 		MD5Final((uchar_t *)answer, &context);
18988 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
18989 		/*
18990 		 * Now that we've hashed into a unique per-connection sequence
18991 		 * space, add a random increment per strong_iss == 1.  So I
18992 		 * guess we'll have to...
18993 		 */
18994 		/* FALLTHRU */
18995 	case 1:
18996 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
18997 		break;
18998 	default:
18999 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19000 		break;
19001 	}
19002 	tcp->tcp_valid_bits = TCP_ISS_VALID;
19003 	tcp->tcp_fss = tcp->tcp_iss - 1;
19004 	tcp->tcp_suna = tcp->tcp_iss;
19005 	tcp->tcp_snxt = tcp->tcp_iss + 1;
19006 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
19007 	tcp->tcp_csuna = tcp->tcp_snxt;
19008 }
19009 
19010 /*
19011  * Exported routine for extracting active tcp connection status.
19012  *
19013  * This is used by the Solaris Cluster Networking software to
19014  * gather a list of connections that need to be forwarded to
19015  * specific nodes in the cluster when configuration changes occur.
19016  *
19017  * The callback is invoked for each tcp_t structure from all netstacks,
19018  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
19019  * from the netstack with the specified stack_id. Returning
19020  * non-zero from the callback routine terminates the search.
19021  */
19022 int
19023 cl_tcp_walk_list(netstackid_t stack_id,
19024     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
19025 {
19026 	netstack_handle_t nh;
19027 	netstack_t *ns;
19028 	int ret = 0;
19029 
19030 	if (stack_id >= 0) {
19031 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
19032 			return (EINVAL);
19033 
19034 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19035 		    ns->netstack_tcp);
19036 		netstack_rele(ns);
19037 		return (ret);
19038 	}
19039 
19040 	netstack_next_init(&nh);
19041 	while ((ns = netstack_next(&nh)) != NULL) {
19042 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19043 		    ns->netstack_tcp);
19044 		netstack_rele(ns);
19045 	}
19046 	netstack_next_fini(&nh);
19047 	return (ret);
19048 }
19049 
19050 static int
19051 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
19052     tcp_stack_t *tcps)
19053 {
19054 	tcp_t *tcp;
19055 	cl_tcp_info_t	cl_tcpi;
19056 	connf_t	*connfp;
19057 	conn_t	*connp;
19058 	int	i;
19059 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19060 
19061 	ASSERT(callback != NULL);
19062 
19063 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
19064 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
19065 		connp = NULL;
19066 
19067 		while ((connp =
19068 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
19069 
19070 			tcp = connp->conn_tcp;
19071 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
19072 			cl_tcpi.cl_tcpi_ipversion = connp->conn_ipversion;
19073 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
19074 			cl_tcpi.cl_tcpi_lport = connp->conn_lport;
19075 			cl_tcpi.cl_tcpi_fport = connp->conn_fport;
19076 			cl_tcpi.cl_tcpi_laddr_v6 = connp->conn_laddr_v6;
19077 			cl_tcpi.cl_tcpi_faddr_v6 = connp->conn_faddr_v6;
19078 
19079 			/*
19080 			 * If the callback returns non-zero
19081 			 * we terminate the traversal.
19082 			 */
19083 			if ((*callback)(&cl_tcpi, arg) != 0) {
19084 				CONN_DEC_REF(tcp->tcp_connp);
19085 				return (1);
19086 			}
19087 		}
19088 	}
19089 
19090 	return (0);
19091 }
19092 
19093 /*
19094  * Macros used for accessing the different types of sockaddr
19095  * structures inside a tcp_ioc_abort_conn_t.
19096  */
19097 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
19098 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
19099 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
19100 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
19101 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
19102 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
19103 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
19104 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
19105 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
19106 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
19107 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
19108 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
19109 
19110 /*
19111  * Return the correct error code to mimic the behavior
19112  * of a connection reset.
19113  */
19114 #define	TCP_AC_GET_ERRCODE(state, err) {	\
19115 		switch ((state)) {		\
19116 		case TCPS_SYN_SENT:		\
19117 		case TCPS_SYN_RCVD:		\
19118 			(err) = ECONNREFUSED;	\
19119 			break;			\
19120 		case TCPS_ESTABLISHED:		\
19121 		case TCPS_FIN_WAIT_1:		\
19122 		case TCPS_FIN_WAIT_2:		\
19123 		case TCPS_CLOSE_WAIT:		\
19124 			(err) = ECONNRESET;	\
19125 			break;			\
19126 		case TCPS_CLOSING:		\
19127 		case TCPS_LAST_ACK:		\
19128 		case TCPS_TIME_WAIT:		\
19129 			(err) = 0;		\
19130 			break;			\
19131 		default:			\
19132 			(err) = ENXIO;		\
19133 		}				\
19134 	}
19135 
19136 /*
19137  * Check if a tcp structure matches the info in acp.
19138  */
19139 #define	TCP_AC_ADDR_MATCH(acp, connp, tcp)			\
19140 	(((acp)->ac_local.ss_family == AF_INET) ?		\
19141 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
19142 	TCP_AC_V4LOCAL((acp)) == (connp)->conn_laddr_v4) &&	\
19143 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
19144 	TCP_AC_V4REMOTE((acp)) == (connp)->conn_faddr_v4) &&	\
19145 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
19146 	TCP_AC_V4LPORT((acp)) == (connp)->conn_lport) &&	\
19147 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
19148 	TCP_AC_V4RPORT((acp)) == (connp)->conn_fport) &&	\
19149 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19150 	(acp)->ac_end >= (tcp)->tcp_state) :			\
19151 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
19152 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
19153 	&(connp)->conn_laddr_v6)) &&				\
19154 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
19155 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
19156 	&(connp)->conn_faddr_v6)) &&				\
19157 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
19158 	TCP_AC_V6LPORT((acp)) == (connp)->conn_lport) &&	\
19159 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
19160 	TCP_AC_V6RPORT((acp)) == (connp)->conn_fport) &&	\
19161 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19162 	(acp)->ac_end >= (tcp)->tcp_state))
19163 
19164 #define	TCP_AC_MATCH(acp, connp, tcp)				\
19165 	(((acp)->ac_zoneid == ALL_ZONES ||			\
19166 	(acp)->ac_zoneid == (connp)->conn_zoneid) ?		\
19167 	TCP_AC_ADDR_MATCH(acp, connp, tcp) : 0)
19168 
19169 /*
19170  * Build a message containing a tcp_ioc_abort_conn_t structure
19171  * which is filled in with information from acp and tp.
19172  */
19173 static mblk_t *
19174 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
19175 {
19176 	mblk_t *mp;
19177 	tcp_ioc_abort_conn_t *tacp;
19178 
19179 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
19180 	if (mp == NULL)
19181 		return (NULL);
19182 
19183 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
19184 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
19185 	    sizeof (uint32_t));
19186 
19187 	tacp->ac_start = acp->ac_start;
19188 	tacp->ac_end = acp->ac_end;
19189 	tacp->ac_zoneid = acp->ac_zoneid;
19190 
19191 	if (acp->ac_local.ss_family == AF_INET) {
19192 		tacp->ac_local.ss_family = AF_INET;
19193 		tacp->ac_remote.ss_family = AF_INET;
19194 		TCP_AC_V4LOCAL(tacp) = tp->tcp_connp->conn_laddr_v4;
19195 		TCP_AC_V4REMOTE(tacp) = tp->tcp_connp->conn_faddr_v4;
19196 		TCP_AC_V4LPORT(tacp) = tp->tcp_connp->conn_lport;
19197 		TCP_AC_V4RPORT(tacp) = tp->tcp_connp->conn_fport;
19198 	} else {
19199 		tacp->ac_local.ss_family = AF_INET6;
19200 		tacp->ac_remote.ss_family = AF_INET6;
19201 		TCP_AC_V6LOCAL(tacp) = tp->tcp_connp->conn_laddr_v6;
19202 		TCP_AC_V6REMOTE(tacp) = tp->tcp_connp->conn_faddr_v6;
19203 		TCP_AC_V6LPORT(tacp) = tp->tcp_connp->conn_lport;
19204 		TCP_AC_V6RPORT(tacp) = tp->tcp_connp->conn_fport;
19205 	}
19206 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
19207 	return (mp);
19208 }
19209 
19210 /*
19211  * Print a tcp_ioc_abort_conn_t structure.
19212  */
19213 static void
19214 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
19215 {
19216 	char lbuf[128];
19217 	char rbuf[128];
19218 	sa_family_t af;
19219 	in_port_t lport, rport;
19220 	ushort_t logflags;
19221 
19222 	af = acp->ac_local.ss_family;
19223 
19224 	if (af == AF_INET) {
19225 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
19226 		    lbuf, 128);
19227 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
19228 		    rbuf, 128);
19229 		lport = ntohs(TCP_AC_V4LPORT(acp));
19230 		rport = ntohs(TCP_AC_V4RPORT(acp));
19231 	} else {
19232 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
19233 		    lbuf, 128);
19234 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
19235 		    rbuf, 128);
19236 		lport = ntohs(TCP_AC_V6LPORT(acp));
19237 		rport = ntohs(TCP_AC_V6RPORT(acp));
19238 	}
19239 
19240 	logflags = SL_TRACE | SL_NOTE;
19241 	/*
19242 	 * Don't print this message to the console if the operation was done
19243 	 * to a non-global zone.
19244 	 */
19245 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19246 		logflags |= SL_CONSOLE;
19247 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
19248 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
19249 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
19250 	    acp->ac_start, acp->ac_end);
19251 }
19252 
19253 /*
19254  * Called using SQ_FILL when a message built using
19255  * tcp_ioctl_abort_build_msg is put into a queue.
19256  * Note that when we get here there is no wildcard in acp any more.
19257  */
19258 /* ARGSUSED2 */
19259 static void
19260 tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
19261     ip_recv_attr_t *dummy)
19262 {
19263 	conn_t			*connp = (conn_t *)arg;
19264 	tcp_t			*tcp = connp->conn_tcp;
19265 	tcp_ioc_abort_conn_t	*acp;
19266 
19267 	/*
19268 	 * Don't accept any input on a closed tcp as this TCP logically does
19269 	 * not exist on the system. Don't proceed further with this TCP.
19270 	 * For eg. this packet could trigger another close of this tcp
19271 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
19272 	 * tcp_clean_death / tcp_closei_local must be called at most once
19273 	 * on a TCP.
19274 	 */
19275 	if (tcp->tcp_state == TCPS_CLOSED ||
19276 	    tcp->tcp_state == TCPS_BOUND) {
19277 		freemsg(mp);
19278 		return;
19279 	}
19280 
19281 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
19282 	if (tcp->tcp_state <= acp->ac_end) {
19283 		/*
19284 		 * If we get here, we are already on the correct
19285 		 * squeue. This ioctl follows the following path
19286 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
19287 		 * ->tcp_ioctl_abort->squeue_enter (if on a
19288 		 * different squeue)
19289 		 */
19290 		int errcode;
19291 
19292 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
19293 		(void) tcp_clean_death(tcp, errcode, 26);
19294 	}
19295 	freemsg(mp);
19296 }
19297 
19298 /*
19299  * Abort all matching connections on a hash chain.
19300  */
19301 static int
19302 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
19303     boolean_t exact, tcp_stack_t *tcps)
19304 {
19305 	int nmatch, err = 0;
19306 	tcp_t *tcp;
19307 	MBLKP mp, last, listhead = NULL;
19308 	conn_t	*tconnp;
19309 	connf_t	*connfp;
19310 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19311 
19312 	connfp = &ipst->ips_ipcl_conn_fanout[index];
19313 
19314 startover:
19315 	nmatch = 0;
19316 
19317 	mutex_enter(&connfp->connf_lock);
19318 	for (tconnp = connfp->connf_head; tconnp != NULL;
19319 	    tconnp = tconnp->conn_next) {
19320 		tcp = tconnp->conn_tcp;
19321 		/*
19322 		 * We are missing a check on sin6_scope_id for linklocals here,
19323 		 * but current usage is just for aborting based on zoneid
19324 		 * for shared-IP zones.
19325 		 */
19326 		if (TCP_AC_MATCH(acp, tconnp, tcp)) {
19327 			CONN_INC_REF(tconnp);
19328 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
19329 			if (mp == NULL) {
19330 				err = ENOMEM;
19331 				CONN_DEC_REF(tconnp);
19332 				break;
19333 			}
19334 			mp->b_prev = (mblk_t *)tcp;
19335 
19336 			if (listhead == NULL) {
19337 				listhead = mp;
19338 				last = mp;
19339 			} else {
19340 				last->b_next = mp;
19341 				last = mp;
19342 			}
19343 			nmatch++;
19344 			if (exact)
19345 				break;
19346 		}
19347 
19348 		/* Avoid holding lock for too long. */
19349 		if (nmatch >= 500)
19350 			break;
19351 	}
19352 	mutex_exit(&connfp->connf_lock);
19353 
19354 	/* Pass mp into the correct tcp */
19355 	while ((mp = listhead) != NULL) {
19356 		listhead = listhead->b_next;
19357 		tcp = (tcp_t *)mp->b_prev;
19358 		mp->b_next = mp->b_prev = NULL;
19359 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp,
19360 		    tcp_ioctl_abort_handler, tcp->tcp_connp, NULL,
19361 		    SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
19362 	}
19363 
19364 	*count += nmatch;
19365 	if (nmatch >= 500 && err == 0)
19366 		goto startover;
19367 	return (err);
19368 }
19369 
19370 /*
19371  * Abort all connections that matches the attributes specified in acp.
19372  */
19373 static int
19374 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
19375 {
19376 	sa_family_t af;
19377 	uint32_t  ports;
19378 	uint16_t *pports;
19379 	int err = 0, count = 0;
19380 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
19381 	int index = -1;
19382 	ushort_t logflags;
19383 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19384 
19385 	af = acp->ac_local.ss_family;
19386 
19387 	if (af == AF_INET) {
19388 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
19389 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
19390 			pports = (uint16_t *)&ports;
19391 			pports[1] = TCP_AC_V4LPORT(acp);
19392 			pports[0] = TCP_AC_V4RPORT(acp);
19393 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
19394 		}
19395 	} else {
19396 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
19397 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
19398 			pports = (uint16_t *)&ports;
19399 			pports[1] = TCP_AC_V6LPORT(acp);
19400 			pports[0] = TCP_AC_V6RPORT(acp);
19401 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
19402 		}
19403 	}
19404 
19405 	/*
19406 	 * For cases where remote addr, local port, and remote port are non-
19407 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
19408 	 */
19409 	if (index != -1) {
19410 		err = tcp_ioctl_abort_bucket(acp, index,
19411 		    &count, exact, tcps);
19412 	} else {
19413 		/*
19414 		 * loop through all entries for wildcard case
19415 		 */
19416 		for (index = 0;
19417 		    index < ipst->ips_ipcl_conn_fanout_size;
19418 		    index++) {
19419 			err = tcp_ioctl_abort_bucket(acp, index,
19420 			    &count, exact, tcps);
19421 			if (err != 0)
19422 				break;
19423 		}
19424 	}
19425 
19426 	logflags = SL_TRACE | SL_NOTE;
19427 	/*
19428 	 * Don't print this message to the console if the operation was done
19429 	 * to a non-global zone.
19430 	 */
19431 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19432 		logflags |= SL_CONSOLE;
19433 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
19434 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
19435 	if (err == 0 && count == 0)
19436 		err = ENOENT;
19437 	return (err);
19438 }
19439 
19440 /*
19441  * Process the TCP_IOC_ABORT_CONN ioctl request.
19442  */
19443 static void
19444 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
19445 {
19446 	int	err;
19447 	IOCP    iocp;
19448 	MBLKP   mp1;
19449 	sa_family_t laf, raf;
19450 	tcp_ioc_abort_conn_t *acp;
19451 	zone_t		*zptr;
19452 	conn_t		*connp = Q_TO_CONN(q);
19453 	zoneid_t	zoneid = connp->conn_zoneid;
19454 	tcp_t		*tcp = connp->conn_tcp;
19455 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19456 
19457 	iocp = (IOCP)mp->b_rptr;
19458 
19459 	if ((mp1 = mp->b_cont) == NULL ||
19460 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
19461 		err = EINVAL;
19462 		goto out;
19463 	}
19464 
19465 	/* check permissions */
19466 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19467 		err = EPERM;
19468 		goto out;
19469 	}
19470 
19471 	if (mp1->b_cont != NULL) {
19472 		freemsg(mp1->b_cont);
19473 		mp1->b_cont = NULL;
19474 	}
19475 
19476 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
19477 	laf = acp->ac_local.ss_family;
19478 	raf = acp->ac_remote.ss_family;
19479 
19480 	/* check that a zone with the supplied zoneid exists */
19481 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
19482 		zptr = zone_find_by_id(zoneid);
19483 		if (zptr != NULL) {
19484 			zone_rele(zptr);
19485 		} else {
19486 			err = EINVAL;
19487 			goto out;
19488 		}
19489 	}
19490 
19491 	/*
19492 	 * For exclusive stacks we set the zoneid to zero
19493 	 * to make TCP operate as if in the global zone.
19494 	 */
19495 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
19496 		acp->ac_zoneid = GLOBAL_ZONEID;
19497 
19498 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
19499 	    acp->ac_start > acp->ac_end || laf != raf ||
19500 	    (laf != AF_INET && laf != AF_INET6)) {
19501 		err = EINVAL;
19502 		goto out;
19503 	}
19504 
19505 	tcp_ioctl_abort_dump(acp);
19506 	err = tcp_ioctl_abort(acp, tcps);
19507 
19508 out:
19509 	if (mp1 != NULL) {
19510 		freemsg(mp1);
19511 		mp->b_cont = NULL;
19512 	}
19513 
19514 	if (err != 0)
19515 		miocnak(q, mp, 0, err);
19516 	else
19517 		miocack(q, mp, 0, 0);
19518 }
19519 
19520 /*
19521  * tcp_time_wait_processing() handles processing of incoming packets when
19522  * the tcp is in the TIME_WAIT state.
19523  * A TIME_WAIT tcp that has an associated open TCP stream is never put
19524  * on the time wait list.
19525  */
19526 void
19527 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
19528     uint32_t seg_ack, int seg_len, tcpha_t *tcpha, ip_recv_attr_t *ira)
19529 {
19530 	int32_t		bytes_acked;
19531 	int32_t		gap;
19532 	int32_t		rgap;
19533 	tcp_opt_t	tcpopt;
19534 	uint_t		flags;
19535 	uint32_t	new_swnd = 0;
19536 	conn_t		*nconnp;
19537 	conn_t		*connp = tcp->tcp_connp;
19538 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19539 
19540 	BUMP_LOCAL(tcp->tcp_ibsegs);
19541 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
19542 
19543 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
19544 	new_swnd = ntohs(tcpha->tha_win) <<
19545 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
19546 	if (tcp->tcp_snd_ts_ok) {
19547 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
19548 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19549 			    tcp->tcp_rnxt, TH_ACK);
19550 			goto done;
19551 		}
19552 	}
19553 	gap = seg_seq - tcp->tcp_rnxt;
19554 	rgap = tcp->tcp_rwnd - (gap + seg_len);
19555 	if (gap < 0) {
19556 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
19557 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
19558 		    (seg_len > -gap ? -gap : seg_len));
19559 		seg_len += gap;
19560 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
19561 			if (flags & TH_RST) {
19562 				goto done;
19563 			}
19564 			if ((flags & TH_FIN) && seg_len == -1) {
19565 				/*
19566 				 * When TCP receives a duplicate FIN in
19567 				 * TIME_WAIT state, restart the 2 MSL timer.
19568 				 * See page 73 in RFC 793. Make sure this TCP
19569 				 * is already on the TIME_WAIT list. If not,
19570 				 * just restart the timer.
19571 				 */
19572 				if (TCP_IS_DETACHED(tcp)) {
19573 					if (tcp_time_wait_remove(tcp, NULL) ==
19574 					    B_TRUE) {
19575 						tcp_time_wait_append(tcp);
19576 						TCP_DBGSTAT(tcps,
19577 						    tcp_rput_time_wait);
19578 					}
19579 				} else {
19580 					ASSERT(tcp != NULL);
19581 					TCP_TIMER_RESTART(tcp,
19582 					    tcps->tcps_time_wait_interval);
19583 				}
19584 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19585 				    tcp->tcp_rnxt, TH_ACK);
19586 				goto done;
19587 			}
19588 			flags |=  TH_ACK_NEEDED;
19589 			seg_len = 0;
19590 			goto process_ack;
19591 		}
19592 
19593 		/* Fix seg_seq, and chew the gap off the front. */
19594 		seg_seq = tcp->tcp_rnxt;
19595 	}
19596 
19597 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
19598 		/*
19599 		 * Make sure that when we accept the connection, pick
19600 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
19601 		 * old connection.
19602 		 *
19603 		 * The next ISS generated is equal to tcp_iss_incr_extra
19604 		 * + ISS_INCR/2 + other components depending on the
19605 		 * value of tcp_strong_iss.  We pre-calculate the new
19606 		 * ISS here and compare with tcp_snxt to determine if
19607 		 * we need to make adjustment to tcp_iss_incr_extra.
19608 		 *
19609 		 * The above calculation is ugly and is a
19610 		 * waste of CPU cycles...
19611 		 */
19612 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
19613 		int32_t adj;
19614 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19615 
19616 		switch (tcps->tcps_strong_iss) {
19617 		case 2: {
19618 			/* Add time and MD5 components. */
19619 			uint32_t answer[4];
19620 			struct {
19621 				uint32_t ports;
19622 				in6_addr_t src;
19623 				in6_addr_t dst;
19624 			} arg;
19625 			MD5_CTX context;
19626 
19627 			mutex_enter(&tcps->tcps_iss_key_lock);
19628 			context = tcps->tcps_iss_key;
19629 			mutex_exit(&tcps->tcps_iss_key_lock);
19630 			arg.ports = connp->conn_ports;
19631 			/* We use MAPPED addresses in tcp_iss_init */
19632 			arg.src = connp->conn_laddr_v6;
19633 			arg.dst = connp->conn_faddr_v6;
19634 			MD5Update(&context, (uchar_t *)&arg,
19635 			    sizeof (arg));
19636 			MD5Final((uchar_t *)answer, &context);
19637 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
19638 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
19639 			break;
19640 		}
19641 		case 1:
19642 			/* Add time component and min random (i.e. 1). */
19643 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
19644 			break;
19645 		default:
19646 			/* Add only time component. */
19647 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19648 			break;
19649 		}
19650 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
19651 			/*
19652 			 * New ISS not guaranteed to be ISS_INCR/2
19653 			 * ahead of the current tcp_snxt, so add the
19654 			 * difference to tcp_iss_incr_extra.
19655 			 */
19656 			tcps->tcps_iss_incr_extra += adj;
19657 		}
19658 		/*
19659 		 * If tcp_clean_death() can not perform the task now,
19660 		 * drop the SYN packet and let the other side re-xmit.
19661 		 * Otherwise pass the SYN packet back in, since the
19662 		 * old tcp state has been cleaned up or freed.
19663 		 */
19664 		if (tcp_clean_death(tcp, 0, 27) == -1)
19665 			goto done;
19666 		nconnp = ipcl_classify(mp, ira, ipst);
19667 		if (nconnp != NULL) {
19668 			TCP_STAT(tcps, tcp_time_wait_syn_success);
19669 			/* Drops ref on nconnp */
19670 			tcp_reinput(nconnp, mp, ira, ipst);
19671 			return;
19672 		}
19673 		goto done;
19674 	}
19675 
19676 	/*
19677 	 * rgap is the amount of stuff received out of window.  A negative
19678 	 * value is the amount out of window.
19679 	 */
19680 	if (rgap < 0) {
19681 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
19682 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
19683 		/* Fix seg_len and make sure there is something left. */
19684 		seg_len += rgap;
19685 		if (seg_len <= 0) {
19686 			if (flags & TH_RST) {
19687 				goto done;
19688 			}
19689 			flags |=  TH_ACK_NEEDED;
19690 			seg_len = 0;
19691 			goto process_ack;
19692 		}
19693 	}
19694 	/*
19695 	 * Check whether we can update tcp_ts_recent.  This test is
19696 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
19697 	 * Extensions for High Performance: An Update", Internet Draft.
19698 	 */
19699 	if (tcp->tcp_snd_ts_ok &&
19700 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
19701 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
19702 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
19703 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
19704 	}
19705 
19706 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
19707 		/* Always ack out of order packets */
19708 		flags |= TH_ACK_NEEDED;
19709 		seg_len = 0;
19710 	} else if (seg_len > 0) {
19711 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
19712 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
19713 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
19714 	}
19715 	if (flags & TH_RST) {
19716 		(void) tcp_clean_death(tcp, 0, 28);
19717 		goto done;
19718 	}
19719 	if (flags & TH_SYN) {
19720 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
19721 		    TH_RST|TH_ACK);
19722 		/*
19723 		 * Do not delete the TCP structure if it is in
19724 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
19725 		 */
19726 		goto done;
19727 	}
19728 process_ack:
19729 	if (flags & TH_ACK) {
19730 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
19731 		if (bytes_acked <= 0) {
19732 			if (bytes_acked == 0 && seg_len == 0 &&
19733 			    new_swnd == tcp->tcp_swnd)
19734 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
19735 		} else {
19736 			/* Acks something not sent */
19737 			flags |= TH_ACK_NEEDED;
19738 		}
19739 	}
19740 	if (flags & TH_ACK_NEEDED) {
19741 		/*
19742 		 * Time to send an ack for some reason.
19743 		 */
19744 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19745 		    tcp->tcp_rnxt, TH_ACK);
19746 	}
19747 done:
19748 	freemsg(mp);
19749 }
19750 
19751 /*
19752  * TCP Timers Implementation.
19753  */
19754 timeout_id_t
19755 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
19756 {
19757 	mblk_t *mp;
19758 	tcp_timer_t *tcpt;
19759 	tcp_t *tcp = connp->conn_tcp;
19760 
19761 	ASSERT(connp->conn_sqp != NULL);
19762 
19763 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
19764 
19765 	if (tcp->tcp_timercache == NULL) {
19766 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
19767 	} else {
19768 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
19769 		mp = tcp->tcp_timercache;
19770 		tcp->tcp_timercache = mp->b_next;
19771 		mp->b_next = NULL;
19772 		ASSERT(mp->b_wptr == NULL);
19773 	}
19774 
19775 	CONN_INC_REF(connp);
19776 	tcpt = (tcp_timer_t *)mp->b_rptr;
19777 	tcpt->connp = connp;
19778 	tcpt->tcpt_proc = f;
19779 	/*
19780 	 * TCP timers are normal timeouts. Plus, they do not require more than
19781 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
19782 	 * rounding up the expiration to the next resolution boundary, we can
19783 	 * batch timers in the callout subsystem to make TCP timers more
19784 	 * efficient. The roundup also protects short timers from expiring too
19785 	 * early before they have a chance to be cancelled.
19786 	 */
19787 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
19788 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
19789 
19790 	return ((timeout_id_t)mp);
19791 }
19792 
19793 static void
19794 tcp_timer_callback(void *arg)
19795 {
19796 	mblk_t *mp = (mblk_t *)arg;
19797 	tcp_timer_t *tcpt;
19798 	conn_t	*connp;
19799 
19800 	tcpt = (tcp_timer_t *)mp->b_rptr;
19801 	connp = tcpt->connp;
19802 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
19803 	    NULL, SQ_FILL, SQTAG_TCP_TIMER);
19804 }
19805 
19806 /* ARGSUSED */
19807 static void
19808 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
19809 {
19810 	tcp_timer_t *tcpt;
19811 	conn_t *connp = (conn_t *)arg;
19812 	tcp_t *tcp = connp->conn_tcp;
19813 
19814 	tcpt = (tcp_timer_t *)mp->b_rptr;
19815 	ASSERT(connp == tcpt->connp);
19816 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
19817 
19818 	/*
19819 	 * If the TCP has reached the closed state, don't proceed any
19820 	 * further. This TCP logically does not exist on the system.
19821 	 * tcpt_proc could for example access queues, that have already
19822 	 * been qprocoff'ed off.
19823 	 */
19824 	if (tcp->tcp_state != TCPS_CLOSED) {
19825 		(*tcpt->tcpt_proc)(connp);
19826 	} else {
19827 		tcp->tcp_timer_tid = 0;
19828 	}
19829 	tcp_timer_free(connp->conn_tcp, mp);
19830 }
19831 
19832 /*
19833  * There is potential race with untimeout and the handler firing at the same
19834  * time. The mblock may be freed by the handler while we are trying to use
19835  * it. But since both should execute on the same squeue, this race should not
19836  * occur.
19837  */
19838 clock_t
19839 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
19840 {
19841 	mblk_t	*mp = (mblk_t *)id;
19842 	tcp_timer_t *tcpt;
19843 	clock_t delta;
19844 
19845 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
19846 
19847 	if (mp == NULL)
19848 		return (-1);
19849 
19850 	tcpt = (tcp_timer_t *)mp->b_rptr;
19851 	ASSERT(tcpt->connp == connp);
19852 
19853 	delta = untimeout_default(tcpt->tcpt_tid, 0);
19854 
19855 	if (delta >= 0) {
19856 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
19857 		tcp_timer_free(connp->conn_tcp, mp);
19858 		CONN_DEC_REF(connp);
19859 	}
19860 
19861 	return (delta);
19862 }
19863 
19864 /*
19865  * Allocate space for the timer event. The allocation looks like mblk, but it is
19866  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
19867  *
19868  * Dealing with failures: If we can't allocate from the timer cache we try
19869  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
19870  * points to b_rptr.
19871  * If we can't allocate anything using allocb_tryhard(), we perform a last
19872  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
19873  * save the actual allocation size in b_datap.
19874  */
19875 mblk_t *
19876 tcp_timermp_alloc(int kmflags)
19877 {
19878 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
19879 	    kmflags & ~KM_PANIC);
19880 
19881 	if (mp != NULL) {
19882 		mp->b_next = mp->b_prev = NULL;
19883 		mp->b_rptr = (uchar_t *)(&mp[1]);
19884 		mp->b_wptr = NULL;
19885 		mp->b_datap = NULL;
19886 		mp->b_queue = NULL;
19887 		mp->b_cont = NULL;
19888 	} else if (kmflags & KM_PANIC) {
19889 		/*
19890 		 * Failed to allocate memory for the timer. Try allocating from
19891 		 * dblock caches.
19892 		 */
19893 		/* ipclassifier calls this from a constructor - hence no tcps */
19894 		TCP_G_STAT(tcp_timermp_allocfail);
19895 		mp = allocb_tryhard(sizeof (tcp_timer_t));
19896 		if (mp == NULL) {
19897 			size_t size = 0;
19898 			/*
19899 			 * Memory is really low. Try tryhard allocation.
19900 			 *
19901 			 * ipclassifier calls this from a constructor -
19902 			 * hence no tcps
19903 			 */
19904 			TCP_G_STAT(tcp_timermp_allocdblfail);
19905 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
19906 			    sizeof (tcp_timer_t), &size, kmflags);
19907 			mp->b_rptr = (uchar_t *)(&mp[1]);
19908 			mp->b_next = mp->b_prev = NULL;
19909 			mp->b_wptr = (uchar_t *)-1;
19910 			mp->b_datap = (dblk_t *)size;
19911 			mp->b_queue = NULL;
19912 			mp->b_cont = NULL;
19913 		}
19914 		ASSERT(mp->b_wptr != NULL);
19915 	}
19916 	/* ipclassifier calls this from a constructor - hence no tcps */
19917 	TCP_G_DBGSTAT(tcp_timermp_alloced);
19918 
19919 	return (mp);
19920 }
19921 
19922 /*
19923  * Free per-tcp timer cache.
19924  * It can only contain entries from tcp_timercache.
19925  */
19926 void
19927 tcp_timermp_free(tcp_t *tcp)
19928 {
19929 	mblk_t *mp;
19930 
19931 	while ((mp = tcp->tcp_timercache) != NULL) {
19932 		ASSERT(mp->b_wptr == NULL);
19933 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
19934 		kmem_cache_free(tcp_timercache, mp);
19935 	}
19936 }
19937 
19938 /*
19939  * Free timer event. Put it on the per-tcp timer cache if there is not too many
19940  * events there already (currently at most two events are cached).
19941  * If the event is not allocated from the timer cache, free it right away.
19942  */
19943 static void
19944 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
19945 {
19946 	mblk_t *mp1 = tcp->tcp_timercache;
19947 
19948 	if (mp->b_wptr != NULL) {
19949 		/*
19950 		 * This allocation is not from a timer cache, free it right
19951 		 * away.
19952 		 */
19953 		if (mp->b_wptr != (uchar_t *)-1)
19954 			freeb(mp);
19955 		else
19956 			kmem_free(mp, (size_t)mp->b_datap);
19957 	} else if (mp1 == NULL || mp1->b_next == NULL) {
19958 		/* Cache this timer block for future allocations */
19959 		mp->b_rptr = (uchar_t *)(&mp[1]);
19960 		mp->b_next = mp1;
19961 		tcp->tcp_timercache = mp;
19962 	} else {
19963 		kmem_cache_free(tcp_timercache, mp);
19964 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
19965 	}
19966 }
19967 
19968 /*
19969  * End of TCP Timers implementation.
19970  */
19971 
19972 /*
19973  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
19974  * on the specified backing STREAMS q. Note, the caller may make the
19975  * decision to call based on the tcp_t.tcp_flow_stopped value which
19976  * when check outside the q's lock is only an advisory check ...
19977  */
19978 void
19979 tcp_setqfull(tcp_t *tcp)
19980 {
19981 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19982 	conn_t	*connp = tcp->tcp_connp;
19983 
19984 	if (tcp->tcp_closed)
19985 		return;
19986 
19987 	conn_setqfull(connp, &tcp->tcp_flow_stopped);
19988 	if (tcp->tcp_flow_stopped)
19989 		TCP_STAT(tcps, tcp_flwctl_on);
19990 }
19991 
19992 void
19993 tcp_clrqfull(tcp_t *tcp)
19994 {
19995 	conn_t  *connp = tcp->tcp_connp;
19996 
19997 	if (tcp->tcp_closed)
19998 		return;
19999 	conn_clrqfull(connp, &tcp->tcp_flow_stopped);
20000 }
20001 
20002 /*
20003  * kstats related to squeues i.e. not per IP instance
20004  */
20005 static void *
20006 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
20007 {
20008 	kstat_t *ksp;
20009 
20010 	tcp_g_stat_t template = {
20011 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
20012 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
20013 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
20014 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
20015 	};
20016 
20017 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
20018 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20019 	    KSTAT_FLAG_VIRTUAL);
20020 
20021 	if (ksp == NULL)
20022 		return (NULL);
20023 
20024 	bcopy(&template, tcp_g_statp, sizeof (template));
20025 	ksp->ks_data = (void *)tcp_g_statp;
20026 
20027 	kstat_install(ksp);
20028 	return (ksp);
20029 }
20030 
20031 static void
20032 tcp_g_kstat_fini(kstat_t *ksp)
20033 {
20034 	if (ksp != NULL) {
20035 		kstat_delete(ksp);
20036 	}
20037 }
20038 
20039 
20040 static void *
20041 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
20042 {
20043 	kstat_t *ksp;
20044 
20045 	tcp_stat_t template = {
20046 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
20047 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
20048 		{ "tcp_time_wait_syn_success",	KSTAT_DATA_UINT64 },
20049 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
20050 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
20051 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
20052 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
20053 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
20054 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
20055 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
20056 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
20057 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
20058 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
20059 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
20060 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
20061 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
20062 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
20063 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
20064 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
20065 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
20066 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
20067 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
20068 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
20069 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
20070 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
20071 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
20072 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
20073 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
20074 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
20075 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
20076 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
20077 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
20078 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
20079 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
20080 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
20081 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
20082 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
20083 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
20084 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
20085 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
20086 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
20087 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
20088 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
20089 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
20090 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
20091 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
20092 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
20093 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
20094 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
20095 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
20096 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
20097 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
20098 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
20099 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
20100 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
20101 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
20102 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
20103 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
20104 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
20105 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
20106 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
20107 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
20108 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
20109 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
20110 		{ "tcp_listen_cnt_drop",	KSTAT_DATA_UINT64 },
20111 		{ "tcp_listen_mem_drop",	KSTAT_DATA_UINT64 },
20112 		{ "tcp_zwin_ack_syn",		KSTAT_DATA_UINT64 },
20113 		{ "tcp_rst_unsent",		KSTAT_DATA_UINT64 }
20114 	};
20115 
20116 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
20117 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20118 	    KSTAT_FLAG_VIRTUAL, stackid);
20119 
20120 	if (ksp == NULL)
20121 		return (NULL);
20122 
20123 	bcopy(&template, tcps_statisticsp, sizeof (template));
20124 	ksp->ks_data = (void *)tcps_statisticsp;
20125 	ksp->ks_private = (void *)(uintptr_t)stackid;
20126 
20127 	kstat_install(ksp);
20128 	return (ksp);
20129 }
20130 
20131 static void
20132 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
20133 {
20134 	if (ksp != NULL) {
20135 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20136 		kstat_delete_netstack(ksp, stackid);
20137 	}
20138 }
20139 
20140 /*
20141  * TCP Kstats implementation
20142  */
20143 static void *
20144 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
20145 {
20146 	kstat_t	*ksp;
20147 
20148 	tcp_named_kstat_t template = {
20149 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
20150 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
20151 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
20152 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
20153 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
20154 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
20155 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
20156 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
20157 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
20158 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
20159 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
20160 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
20161 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
20162 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
20163 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
20164 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
20165 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
20166 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
20167 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
20168 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
20169 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
20170 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
20171 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
20172 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
20173 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
20174 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
20175 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
20176 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
20177 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
20178 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
20179 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
20180 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
20181 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
20182 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
20183 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
20184 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
20185 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
20186 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
20187 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
20188 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
20189 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
20190 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
20191 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
20192 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
20193 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
20194 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
20195 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
20196 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
20197 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
20198 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
20199 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
20200 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
20201 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
20202 	};
20203 
20204 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
20205 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
20206 
20207 	if (ksp == NULL)
20208 		return (NULL);
20209 
20210 	template.rtoAlgorithm.value.ui32 = 4;
20211 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
20212 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
20213 	template.maxConn.value.i32 = -1;
20214 
20215 	bcopy(&template, ksp->ks_data, sizeof (template));
20216 	ksp->ks_update = tcp_kstat_update;
20217 	ksp->ks_private = (void *)(uintptr_t)stackid;
20218 
20219 	kstat_install(ksp);
20220 	return (ksp);
20221 }
20222 
20223 static void
20224 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
20225 {
20226 	if (ksp != NULL) {
20227 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20228 		kstat_delete_netstack(ksp, stackid);
20229 	}
20230 }
20231 
20232 static int
20233 tcp_kstat_update(kstat_t *kp, int rw)
20234 {
20235 	tcp_named_kstat_t *tcpkp;
20236 	tcp_t		*tcp;
20237 	connf_t		*connfp;
20238 	conn_t		*connp;
20239 	int 		i;
20240 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
20241 	netstack_t	*ns;
20242 	tcp_stack_t	*tcps;
20243 	ip_stack_t	*ipst;
20244 
20245 	if ((kp == NULL) || (kp->ks_data == NULL))
20246 		return (EIO);
20247 
20248 	if (rw == KSTAT_WRITE)
20249 		return (EACCES);
20250 
20251 	ns = netstack_find_by_stackid(stackid);
20252 	if (ns == NULL)
20253 		return (-1);
20254 	tcps = ns->netstack_tcp;
20255 	if (tcps == NULL) {
20256 		netstack_rele(ns);
20257 		return (-1);
20258 	}
20259 
20260 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
20261 
20262 	tcpkp->currEstab.value.ui32 = 0;
20263 
20264 	ipst = ns->netstack_ip;
20265 
20266 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
20267 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
20268 		connp = NULL;
20269 		while ((connp =
20270 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
20271 			tcp = connp->conn_tcp;
20272 			switch (tcp_snmp_state(tcp)) {
20273 			case MIB2_TCP_established:
20274 			case MIB2_TCP_closeWait:
20275 				tcpkp->currEstab.value.ui32++;
20276 				break;
20277 			}
20278 		}
20279 	}
20280 
20281 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
20282 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
20283 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
20284 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
20285 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
20286 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
20287 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
20288 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
20289 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
20290 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
20291 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
20292 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
20293 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
20294 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
20295 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
20296 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
20297 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
20298 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
20299 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
20300 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
20301 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
20302 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
20303 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
20304 	tcpkp->inDataInorderSegs.value.ui32 =
20305 	    tcps->tcps_mib.tcpInDataInorderSegs;
20306 	tcpkp->inDataInorderBytes.value.ui32 =
20307 	    tcps->tcps_mib.tcpInDataInorderBytes;
20308 	tcpkp->inDataUnorderSegs.value.ui32 =
20309 	    tcps->tcps_mib.tcpInDataUnorderSegs;
20310 	tcpkp->inDataUnorderBytes.value.ui32 =
20311 	    tcps->tcps_mib.tcpInDataUnorderBytes;
20312 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
20313 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
20314 	tcpkp->inDataPartDupSegs.value.ui32 =
20315 	    tcps->tcps_mib.tcpInDataPartDupSegs;
20316 	tcpkp->inDataPartDupBytes.value.ui32 =
20317 	    tcps->tcps_mib.tcpInDataPartDupBytes;
20318 	tcpkp->inDataPastWinSegs.value.ui32 =
20319 	    tcps->tcps_mib.tcpInDataPastWinSegs;
20320 	tcpkp->inDataPastWinBytes.value.ui32 =
20321 	    tcps->tcps_mib.tcpInDataPastWinBytes;
20322 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
20323 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
20324 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
20325 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
20326 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
20327 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
20328 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
20329 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
20330 	tcpkp->timKeepaliveProbe.value.ui32 =
20331 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
20332 	tcpkp->timKeepaliveDrop.value.ui32 =
20333 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
20334 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
20335 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
20336 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
20337 	tcpkp->outSackRetransSegs.value.ui32 =
20338 	    tcps->tcps_mib.tcpOutSackRetransSegs;
20339 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
20340 
20341 	netstack_rele(ns);
20342 	return (0);
20343 }
20344 
20345 static int
20346 tcp_squeue_switch(int val)
20347 {
20348 	int rval = SQ_FILL;
20349 
20350 	switch (val) {
20351 	case 1:
20352 		rval = SQ_NODRAIN;
20353 		break;
20354 	case 2:
20355 		rval = SQ_PROCESS;
20356 		break;
20357 	default:
20358 		break;
20359 	}
20360 	return (rval);
20361 }
20362 
20363 /*
20364  * This is called once for each squeue - globally for all stack
20365  * instances.
20366  */
20367 static void
20368 tcp_squeue_add(squeue_t *sqp)
20369 {
20370 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
20371 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
20372 
20373 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
20374 	tcp_time_wait->tcp_time_wait_tid =
20375 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
20376 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
20377 	    CALLOUT_FLAG_ROUNDUP);
20378 	if (tcp_free_list_max_cnt == 0) {
20379 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
20380 		    max_ncpus : boot_max_ncpus);
20381 
20382 		/*
20383 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
20384 		 */
20385 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
20386 		    (tcp_ncpus * sizeof (tcp_t) * 100);
20387 	}
20388 	tcp_time_wait->tcp_free_list_cnt = 0;
20389 }
20390 
20391 /*
20392  * On a labeled system we have some protocols above TCP, such as RPC, which
20393  * appear to assume that every mblk in a chain has a db_credp.
20394  */
20395 static void
20396 tcp_setcred_data(mblk_t *mp, ip_recv_attr_t *ira)
20397 {
20398 	ASSERT(is_system_labeled());
20399 	ASSERT(ira->ira_cred != NULL);
20400 
20401 	while (mp != NULL) {
20402 		mblk_setcred(mp, ira->ira_cred, NOPID);
20403 		mp = mp->b_cont;
20404 	}
20405 }
20406 
20407 static int
20408 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
20409     boolean_t bind_to_req_port_only, cred_t *cr)
20410 {
20411 	in_port_t	mlp_port;
20412 	mlp_type_t 	addrtype, mlptype;
20413 	boolean_t	user_specified;
20414 	in_port_t	allocated_port;
20415 	in_port_t	requested_port = *requested_port_ptr;
20416 	conn_t		*connp = tcp->tcp_connp;
20417 	zone_t		*zone;
20418 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20419 	in6_addr_t	v6addr = connp->conn_laddr_v6;
20420 
20421 	/*
20422 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
20423 	 */
20424 	ASSERT(cr != NULL);
20425 
20426 	/*
20427 	 * Get a valid port (within the anonymous range and should not
20428 	 * be a privileged one) to use if the user has not given a port.
20429 	 * If multiple threads are here, they may all start with
20430 	 * with the same initial port. But, it should be fine as long as
20431 	 * tcp_bindi will ensure that no two threads will be assigned
20432 	 * the same port.
20433 	 *
20434 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
20435 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
20436 	 * unless TCP_ANONPRIVBIND option is set.
20437 	 */
20438 	mlptype = mlptSingle;
20439 	mlp_port = requested_port;
20440 	if (requested_port == 0) {
20441 		requested_port = connp->conn_anon_priv_bind ?
20442 		    tcp_get_next_priv_port(tcp) :
20443 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
20444 		    tcp, B_TRUE);
20445 		if (requested_port == 0) {
20446 			return (-TNOADDR);
20447 		}
20448 		user_specified = B_FALSE;
20449 
20450 		/*
20451 		 * If the user went through one of the RPC interfaces to create
20452 		 * this socket and RPC is MLP in this zone, then give him an
20453 		 * anonymous MLP.
20454 		 */
20455 		if (connp->conn_anon_mlp && is_system_labeled()) {
20456 			zone = crgetzone(cr);
20457 			addrtype = tsol_mlp_addr_type(
20458 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20459 			    IPV6_VERSION, &v6addr,
20460 			    tcps->tcps_netstack->netstack_ip);
20461 			if (addrtype == mlptSingle) {
20462 				return (-TNOADDR);
20463 			}
20464 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20465 			    PMAPPORT, addrtype);
20466 			mlp_port = PMAPPORT;
20467 		}
20468 	} else {
20469 		int i;
20470 		boolean_t priv = B_FALSE;
20471 
20472 		/*
20473 		 * If the requested_port is in the well-known privileged range,
20474 		 * verify that the stream was opened by a privileged user.
20475 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
20476 		 * but instead the code relies on:
20477 		 * - the fact that the address of the array and its size never
20478 		 *   changes
20479 		 * - the atomic assignment of the elements of the array
20480 		 */
20481 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
20482 			priv = B_TRUE;
20483 		} else {
20484 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
20485 				if (requested_port ==
20486 				    tcps->tcps_g_epriv_ports[i]) {
20487 					priv = B_TRUE;
20488 					break;
20489 				}
20490 			}
20491 		}
20492 		if (priv) {
20493 			if (secpolicy_net_privaddr(cr, requested_port,
20494 			    IPPROTO_TCP) != 0) {
20495 				if (connp->conn_debug) {
20496 					(void) strlog(TCP_MOD_ID, 0, 1,
20497 					    SL_ERROR|SL_TRACE,
20498 					    "tcp_bind: no priv for port %d",
20499 					    requested_port);
20500 				}
20501 				return (-TACCES);
20502 			}
20503 		}
20504 		user_specified = B_TRUE;
20505 
20506 		connp = tcp->tcp_connp;
20507 		if (is_system_labeled()) {
20508 			zone = crgetzone(cr);
20509 			addrtype = tsol_mlp_addr_type(
20510 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20511 			    IPV6_VERSION, &v6addr,
20512 			    tcps->tcps_netstack->netstack_ip);
20513 			if (addrtype == mlptSingle) {
20514 				return (-TNOADDR);
20515 			}
20516 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20517 			    requested_port, addrtype);
20518 		}
20519 	}
20520 
20521 	if (mlptype != mlptSingle) {
20522 		if (secpolicy_net_bindmlp(cr) != 0) {
20523 			if (connp->conn_debug) {
20524 				(void) strlog(TCP_MOD_ID, 0, 1,
20525 				    SL_ERROR|SL_TRACE,
20526 				    "tcp_bind: no priv for multilevel port %d",
20527 				    requested_port);
20528 			}
20529 			return (-TACCES);
20530 		}
20531 
20532 		/*
20533 		 * If we're specifically binding a shared IP address and the
20534 		 * port is MLP on shared addresses, then check to see if this
20535 		 * zone actually owns the MLP.  Reject if not.
20536 		 */
20537 		if (mlptype == mlptShared && addrtype == mlptShared) {
20538 			/*
20539 			 * No need to handle exclusive-stack zones since
20540 			 * ALL_ZONES only applies to the shared stack.
20541 			 */
20542 			zoneid_t mlpzone;
20543 
20544 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
20545 			    htons(mlp_port));
20546 			if (connp->conn_zoneid != mlpzone) {
20547 				if (connp->conn_debug) {
20548 					(void) strlog(TCP_MOD_ID, 0, 1,
20549 					    SL_ERROR|SL_TRACE,
20550 					    "tcp_bind: attempt to bind port "
20551 					    "%d on shared addr in zone %d "
20552 					    "(should be %d)",
20553 					    mlp_port, connp->conn_zoneid,
20554 					    mlpzone);
20555 				}
20556 				return (-TACCES);
20557 			}
20558 		}
20559 
20560 		if (!user_specified) {
20561 			int err;
20562 			err = tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20563 			    requested_port, B_TRUE);
20564 			if (err != 0) {
20565 				if (connp->conn_debug) {
20566 					(void) strlog(TCP_MOD_ID, 0, 1,
20567 					    SL_ERROR|SL_TRACE,
20568 					    "tcp_bind: cannot establish anon "
20569 					    "MLP for port %d",
20570 					    requested_port);
20571 				}
20572 				return (err);
20573 			}
20574 			connp->conn_anon_port = B_TRUE;
20575 		}
20576 		connp->conn_mlp_type = mlptype;
20577 	}
20578 
20579 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
20580 	    connp->conn_reuseaddr, B_FALSE, bind_to_req_port_only,
20581 	    user_specified);
20582 
20583 	if (allocated_port == 0) {
20584 		connp->conn_mlp_type = mlptSingle;
20585 		if (connp->conn_anon_port) {
20586 			connp->conn_anon_port = B_FALSE;
20587 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20588 			    requested_port, B_FALSE);
20589 		}
20590 		if (bind_to_req_port_only) {
20591 			if (connp->conn_debug) {
20592 				(void) strlog(TCP_MOD_ID, 0, 1,
20593 				    SL_ERROR|SL_TRACE,
20594 				    "tcp_bind: requested addr busy");
20595 			}
20596 			return (-TADDRBUSY);
20597 		} else {
20598 			/* If we are out of ports, fail the bind. */
20599 			if (connp->conn_debug) {
20600 				(void) strlog(TCP_MOD_ID, 0, 1,
20601 				    SL_ERROR|SL_TRACE,
20602 				    "tcp_bind: out of ports?");
20603 			}
20604 			return (-TNOADDR);
20605 		}
20606 	}
20607 
20608 	/* Pass the allocated port back */
20609 	*requested_port_ptr = allocated_port;
20610 	return (0);
20611 }
20612 
20613 /*
20614  * Check the address and check/pick a local port number.
20615  */
20616 static int
20617 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20618     boolean_t bind_to_req_port_only)
20619 {
20620 	tcp_t	*tcp = connp->conn_tcp;
20621 	sin_t	*sin;
20622 	sin6_t  *sin6;
20623 	in_port_t	requested_port;
20624 	ipaddr_t	v4addr;
20625 	in6_addr_t	v6addr;
20626 	ip_laddr_t	laddr_type = IPVL_UNICAST_UP;	/* INADDR_ANY */
20627 	zoneid_t	zoneid = IPCL_ZONEID(connp);
20628 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
20629 	uint_t		scopeid = 0;
20630 	int		error = 0;
20631 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20632 
20633 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
20634 
20635 	if (tcp->tcp_state == TCPS_BOUND) {
20636 		return (0);
20637 	} else if (tcp->tcp_state > TCPS_BOUND) {
20638 		if (connp->conn_debug) {
20639 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20640 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20641 		}
20642 		return (-TOUTSTATE);
20643 	}
20644 
20645 	ASSERT(sa != NULL && len != 0);
20646 
20647 	if (!OK_32PTR((char *)sa)) {
20648 		if (connp->conn_debug) {
20649 			(void) strlog(TCP_MOD_ID, 0, 1,
20650 			    SL_ERROR|SL_TRACE,
20651 			    "tcp_bind: bad address parameter, "
20652 			    "address %p, len %d",
20653 			    (void *)sa, len);
20654 		}
20655 		return (-TPROTO);
20656 	}
20657 
20658 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
20659 	if (error != 0) {
20660 		return (error);
20661 	}
20662 
20663 	switch (len) {
20664 	case sizeof (sin_t):	/* Complete IPv4 address */
20665 		sin = (sin_t *)sa;
20666 		requested_port = ntohs(sin->sin_port);
20667 		v4addr = sin->sin_addr.s_addr;
20668 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
20669 		if (v4addr != INADDR_ANY) {
20670 			laddr_type = ip_laddr_verify_v4(v4addr, zoneid, ipst,
20671 			    B_FALSE);
20672 		}
20673 		break;
20674 
20675 	case sizeof (sin6_t): /* Complete IPv6 address */
20676 		sin6 = (sin6_t *)sa;
20677 		v6addr = sin6->sin6_addr;
20678 		requested_port = ntohs(sin6->sin6_port);
20679 		if (IN6_IS_ADDR_V4MAPPED(&v6addr)) {
20680 			if (connp->conn_ipv6_v6only)
20681 				return (EADDRNOTAVAIL);
20682 
20683 			IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
20684 			if (v4addr != INADDR_ANY) {
20685 				laddr_type = ip_laddr_verify_v4(v4addr,
20686 				    zoneid, ipst, B_FALSE);
20687 			}
20688 		} else {
20689 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6addr)) {
20690 				if (IN6_IS_ADDR_LINKSCOPE(&v6addr))
20691 					scopeid = sin6->sin6_scope_id;
20692 				laddr_type = ip_laddr_verify_v6(&v6addr,
20693 				    zoneid, ipst, B_FALSE, scopeid);
20694 			}
20695 		}
20696 		break;
20697 
20698 	default:
20699 		if (connp->conn_debug) {
20700 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20701 			    "tcp_bind: bad address length, %d", len);
20702 		}
20703 		return (EAFNOSUPPORT);
20704 		/* return (-TBADADDR); */
20705 	}
20706 
20707 	/* Is the local address a valid unicast address? */
20708 	if (laddr_type == IPVL_BAD)
20709 		return (EADDRNOTAVAIL);
20710 
20711 	connp->conn_bound_addr_v6 = v6addr;
20712 	if (scopeid != 0) {
20713 		ixa->ixa_flags |= IXAF_SCOPEID_SET;
20714 		ixa->ixa_scopeid = scopeid;
20715 		connp->conn_incoming_ifindex = scopeid;
20716 	} else {
20717 		ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
20718 		connp->conn_incoming_ifindex = connp->conn_bound_if;
20719 	}
20720 
20721 	connp->conn_laddr_v6 = v6addr;
20722 	connp->conn_saddr_v6 = v6addr;
20723 
20724 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
20725 
20726 	error = tcp_bind_select_lport(tcp, &requested_port,
20727 	    bind_to_req_port_only, cr);
20728 	if (error != 0) {
20729 		connp->conn_laddr_v6 = ipv6_all_zeros;
20730 		connp->conn_saddr_v6 = ipv6_all_zeros;
20731 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
20732 	}
20733 	return (error);
20734 }
20735 
20736 /*
20737  * Return unix error is tli error is TSYSERR, otherwise return a negative
20738  * tli error.
20739  */
20740 int
20741 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20742     boolean_t bind_to_req_port_only)
20743 {
20744 	int error;
20745 	tcp_t *tcp = connp->conn_tcp;
20746 
20747 	if (tcp->tcp_state >= TCPS_BOUND) {
20748 		if (connp->conn_debug) {
20749 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20750 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20751 		}
20752 		return (-TOUTSTATE);
20753 	}
20754 
20755 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
20756 	if (error != 0)
20757 		return (error);
20758 
20759 	ASSERT(tcp->tcp_state == TCPS_BOUND);
20760 	tcp->tcp_conn_req_max = 0;
20761 	return (0);
20762 }
20763 
20764 int
20765 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
20766     socklen_t len, cred_t *cr)
20767 {
20768 	int 		error;
20769 	conn_t		*connp = (conn_t *)proto_handle;
20770 	squeue_t	*sqp = connp->conn_sqp;
20771 
20772 	/* All Solaris components should pass a cred for this operation. */
20773 	ASSERT(cr != NULL);
20774 
20775 	ASSERT(sqp != NULL);
20776 	ASSERT(connp->conn_upper_handle != NULL);
20777 
20778 	error = squeue_synch_enter(sqp, connp, NULL);
20779 	if (error != 0) {
20780 		/* failed to enter */
20781 		return (ENOSR);
20782 	}
20783 
20784 	/* binding to a NULL address really means unbind */
20785 	if (sa == NULL) {
20786 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
20787 			error = tcp_do_unbind(connp);
20788 		else
20789 			error = EINVAL;
20790 	} else {
20791 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
20792 	}
20793 
20794 	squeue_synch_exit(sqp, connp);
20795 
20796 	if (error < 0) {
20797 		if (error == -TOUTSTATE)
20798 			error = EINVAL;
20799 		else
20800 			error = proto_tlitosyserr(-error);
20801 	}
20802 
20803 	return (error);
20804 }
20805 
20806 /*
20807  * If the return value from this function is positive, it's a UNIX error.
20808  * Otherwise, if it's negative, then the absolute value is a TLI error.
20809  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
20810  */
20811 int
20812 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
20813     cred_t *cr, pid_t pid)
20814 {
20815 	tcp_t		*tcp = connp->conn_tcp;
20816 	sin_t		*sin = (sin_t *)sa;
20817 	sin6_t		*sin6 = (sin6_t *)sa;
20818 	ipaddr_t	*dstaddrp;
20819 	in_port_t	dstport;
20820 	uint_t		srcid;
20821 	int		error;
20822 	uint32_t	mss;
20823 	mblk_t		*syn_mp;
20824 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20825 	int32_t		oldstate;
20826 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20827 
20828 	oldstate = tcp->tcp_state;
20829 
20830 	switch (len) {
20831 	default:
20832 		/*
20833 		 * Should never happen
20834 		 */
20835 		return (EINVAL);
20836 
20837 	case sizeof (sin_t):
20838 		sin = (sin_t *)sa;
20839 		if (sin->sin_port == 0) {
20840 			return (-TBADADDR);
20841 		}
20842 		if (connp->conn_ipv6_v6only) {
20843 			return (EAFNOSUPPORT);
20844 		}
20845 		break;
20846 
20847 	case sizeof (sin6_t):
20848 		sin6 = (sin6_t *)sa;
20849 		if (sin6->sin6_port == 0) {
20850 			return (-TBADADDR);
20851 		}
20852 		break;
20853 	}
20854 	/*
20855 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
20856 	 * make sure that the conn_ipversion is IPV4_VERSION.  We
20857 	 * need to this before we call tcp_bindi() so that the port lookup
20858 	 * code will look for ports in the correct port space (IPv4 and
20859 	 * IPv6 have separate port spaces).
20860 	 */
20861 	if (connp->conn_family == AF_INET6 &&
20862 	    connp->conn_ipversion == IPV6_VERSION &&
20863 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20864 		if (connp->conn_ipv6_v6only)
20865 			return (EADDRNOTAVAIL);
20866 
20867 		connp->conn_ipversion = IPV4_VERSION;
20868 	}
20869 
20870 	switch (tcp->tcp_state) {
20871 	case TCPS_LISTEN:
20872 		/*
20873 		 * Listening sockets are not allowed to issue connect().
20874 		 */
20875 		if (IPCL_IS_NONSTR(connp))
20876 			return (EOPNOTSUPP);
20877 		/* FALLTHRU */
20878 	case TCPS_IDLE:
20879 		/*
20880 		 * We support quick connect, refer to comments in
20881 		 * tcp_connect_*()
20882 		 */
20883 		/* FALLTHRU */
20884 	case TCPS_BOUND:
20885 		break;
20886 	default:
20887 		return (-TOUTSTATE);
20888 	}
20889 
20890 	/*
20891 	 * We update our cred/cpid based on the caller of connect
20892 	 */
20893 	if (connp->conn_cred != cr) {
20894 		crhold(cr);
20895 		crfree(connp->conn_cred);
20896 		connp->conn_cred = cr;
20897 	}
20898 	connp->conn_cpid = pid;
20899 
20900 	/* Cache things in the ixa without any refhold */
20901 	ixa->ixa_cred = cr;
20902 	ixa->ixa_cpid = pid;
20903 	if (is_system_labeled()) {
20904 		/* We need to restart with a label based on the cred */
20905 		ip_xmit_attr_restore_tsl(ixa, ixa->ixa_cred);
20906 	}
20907 
20908 	if (connp->conn_family == AF_INET6) {
20909 		if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20910 			error = tcp_connect_ipv6(tcp, &sin6->sin6_addr,
20911 			    sin6->sin6_port, sin6->sin6_flowinfo,
20912 			    sin6->__sin6_src_id, sin6->sin6_scope_id);
20913 		} else {
20914 			/*
20915 			 * Destination adress is mapped IPv6 address.
20916 			 * Source bound address should be unspecified or
20917 			 * IPv6 mapped address as well.
20918 			 */
20919 			if (!IN6_IS_ADDR_UNSPECIFIED(
20920 			    &connp->conn_bound_addr_v6) &&
20921 			    !IN6_IS_ADDR_V4MAPPED(&connp->conn_bound_addr_v6)) {
20922 				return (EADDRNOTAVAIL);
20923 			}
20924 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
20925 			dstport = sin6->sin6_port;
20926 			srcid = sin6->__sin6_src_id;
20927 			error = tcp_connect_ipv4(tcp, dstaddrp, dstport,
20928 			    srcid);
20929 		}
20930 	} else {
20931 		dstaddrp = &sin->sin_addr.s_addr;
20932 		dstport = sin->sin_port;
20933 		srcid = 0;
20934 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid);
20935 	}
20936 
20937 	if (error != 0)
20938 		goto connect_failed;
20939 
20940 	CL_INET_CONNECT(connp, B_TRUE, error);
20941 	if (error != 0)
20942 		goto connect_failed;
20943 
20944 	/* connect succeeded */
20945 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
20946 	tcp->tcp_active_open = 1;
20947 
20948 	/*
20949 	 * tcp_set_destination() does not adjust for TCP/IP header length.
20950 	 */
20951 	mss = tcp->tcp_mss - connp->conn_ht_iphc_len;
20952 
20953 	/*
20954 	 * Just make sure our rwnd is at least rcvbuf * MSS large, and round up
20955 	 * to the nearest MSS.
20956 	 *
20957 	 * We do the round up here because we need to get the interface MTU
20958 	 * first before we can do the round up.
20959 	 */
20960 	tcp->tcp_rwnd = connp->conn_rcvbuf;
20961 	tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
20962 	    tcps->tcps_recv_hiwat_minmss * mss);
20963 	connp->conn_rcvbuf = tcp->tcp_rwnd;
20964 	tcp_set_ws_value(tcp);
20965 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
20966 	if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
20967 		tcp->tcp_snd_ws_ok = B_TRUE;
20968 
20969 	/*
20970 	 * Set tcp_snd_ts_ok to true
20971 	 * so that tcp_xmit_mp will
20972 	 * include the timestamp
20973 	 * option in the SYN segment.
20974 	 */
20975 	if (tcps->tcps_tstamp_always ||
20976 	    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
20977 		tcp->tcp_snd_ts_ok = B_TRUE;
20978 	}
20979 
20980 	/*
20981 	 * tcp_snd_sack_ok can be set in
20982 	 * tcp_set_destination() if the sack metric
20983 	 * is set.  So check it here also.
20984 	 */
20985 	if (tcps->tcps_sack_permitted == 2 ||
20986 	    tcp->tcp_snd_sack_ok) {
20987 		if (tcp->tcp_sack_info == NULL) {
20988 			tcp->tcp_sack_info = kmem_cache_alloc(
20989 			    tcp_sack_info_cache, KM_SLEEP);
20990 		}
20991 		tcp->tcp_snd_sack_ok = B_TRUE;
20992 	}
20993 
20994 	/*
20995 	 * Should we use ECN?  Note that the current
20996 	 * default value (SunOS 5.9) of tcp_ecn_permitted
20997 	 * is 1.  The reason for doing this is that there
20998 	 * are equipments out there that will drop ECN
20999 	 * enabled IP packets.  Setting it to 1 avoids
21000 	 * compatibility problems.
21001 	 */
21002 	if (tcps->tcps_ecn_permitted == 2)
21003 		tcp->tcp_ecn_ok = B_TRUE;
21004 
21005 	TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21006 	syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21007 	    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
21008 	if (syn_mp != NULL) {
21009 		/*
21010 		 * We must bump the generation before sending the syn
21011 		 * to ensure that we use the right generation in case
21012 		 * this thread issues a "connected" up call.
21013 		 */
21014 		SOCK_CONNID_BUMP(tcp->tcp_connid);
21015 		tcp_send_data(tcp, syn_mp);
21016 	}
21017 
21018 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21019 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21020 	return (0);
21021 
21022 connect_failed:
21023 	connp->conn_faddr_v6 = ipv6_all_zeros;
21024 	connp->conn_fport = 0;
21025 	tcp->tcp_state = oldstate;
21026 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21027 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21028 	return (error);
21029 }
21030 
21031 int
21032 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
21033     socklen_t len, sock_connid_t *id, cred_t *cr)
21034 {
21035 	conn_t		*connp = (conn_t *)proto_handle;
21036 	squeue_t	*sqp = connp->conn_sqp;
21037 	int		error;
21038 
21039 	ASSERT(connp->conn_upper_handle != NULL);
21040 
21041 	/* All Solaris components should pass a cred for this operation. */
21042 	ASSERT(cr != NULL);
21043 
21044 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
21045 	if (error != 0) {
21046 		return (error);
21047 	}
21048 
21049 	error = squeue_synch_enter(sqp, connp, NULL);
21050 	if (error != 0) {
21051 		/* failed to enter */
21052 		return (ENOSR);
21053 	}
21054 
21055 	/*
21056 	 * TCP supports quick connect, so no need to do an implicit bind
21057 	 */
21058 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
21059 	if (error == 0) {
21060 		*id = connp->conn_tcp->tcp_connid;
21061 	} else if (error < 0) {
21062 		if (error == -TOUTSTATE) {
21063 			switch (connp->conn_tcp->tcp_state) {
21064 			case TCPS_SYN_SENT:
21065 				error = EALREADY;
21066 				break;
21067 			case TCPS_ESTABLISHED:
21068 				error = EISCONN;
21069 				break;
21070 			case TCPS_LISTEN:
21071 				error = EOPNOTSUPP;
21072 				break;
21073 			default:
21074 				error = EINVAL;
21075 				break;
21076 			}
21077 		} else {
21078 			error = proto_tlitosyserr(-error);
21079 		}
21080 	}
21081 
21082 	if (connp->conn_tcp->tcp_loopback) {
21083 		struct sock_proto_props sopp;
21084 
21085 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
21086 		sopp.sopp_loopback = B_TRUE;
21087 
21088 		(*connp->conn_upcalls->su_set_proto_props)(
21089 		    connp->conn_upper_handle, &sopp);
21090 	}
21091 done:
21092 	squeue_synch_exit(sqp, connp);
21093 
21094 	return ((error == 0) ? EINPROGRESS : error);
21095 }
21096 
21097 /* ARGSUSED */
21098 sock_lower_handle_t
21099 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
21100     uint_t *smodep, int *errorp, int flags, cred_t *credp)
21101 {
21102 	conn_t		*connp;
21103 	boolean_t	isv6 = family == AF_INET6;
21104 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
21105 	    (proto != 0 && proto != IPPROTO_TCP)) {
21106 		*errorp = EPROTONOSUPPORT;
21107 		return (NULL);
21108 	}
21109 
21110 	connp = tcp_create_common(credp, isv6, B_TRUE, errorp);
21111 	if (connp == NULL) {
21112 		return (NULL);
21113 	}
21114 
21115 	/*
21116 	 * Put the ref for TCP. Ref for IP was already put
21117 	 * by ipcl_conn_create. Also Make the conn_t globally
21118 	 * visible to walkers
21119 	 */
21120 	mutex_enter(&connp->conn_lock);
21121 	CONN_INC_REF_LOCKED(connp);
21122 	ASSERT(connp->conn_ref == 2);
21123 	connp->conn_state_flags &= ~CONN_INCIPIENT;
21124 
21125 	connp->conn_flags |= IPCL_NONSTR;
21126 	mutex_exit(&connp->conn_lock);
21127 
21128 	ASSERT(errorp != NULL);
21129 	*errorp = 0;
21130 	*sock_downcalls = &sock_tcp_downcalls;
21131 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
21132 	    SM_SENDFILESUPP;
21133 
21134 	return ((sock_lower_handle_t)connp);
21135 }
21136 
21137 /* ARGSUSED */
21138 void
21139 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
21140     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
21141 {
21142 	conn_t *connp = (conn_t *)proto_handle;
21143 	struct sock_proto_props sopp;
21144 
21145 	ASSERT(connp->conn_upper_handle == NULL);
21146 
21147 	/* All Solaris components should pass a cred for this operation. */
21148 	ASSERT(cr != NULL);
21149 
21150 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
21151 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
21152 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
21153 
21154 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
21155 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
21156 	sopp.sopp_maxpsz = INFPSZ;
21157 	sopp.sopp_maxblk = INFPSZ;
21158 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
21159 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
21160 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
21161 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
21162 	    tcp_rinfo.mi_minpsz;
21163 
21164 	connp->conn_upcalls = sock_upcalls;
21165 	connp->conn_upper_handle = sock_handle;
21166 
21167 	ASSERT(connp->conn_rcvbuf != 0 &&
21168 	    connp->conn_rcvbuf == connp->conn_tcp->tcp_rwnd);
21169 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
21170 }
21171 
21172 /* ARGSUSED */
21173 int
21174 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
21175 {
21176 	conn_t *connp = (conn_t *)proto_handle;
21177 
21178 	ASSERT(connp->conn_upper_handle != NULL);
21179 
21180 	/* All Solaris components should pass a cred for this operation. */
21181 	ASSERT(cr != NULL);
21182 
21183 	tcp_close_common(connp, flags);
21184 
21185 	ip_free_helper_stream(connp);
21186 
21187 	/*
21188 	 * Drop IP's reference on the conn. This is the last reference
21189 	 * on the connp if the state was less than established. If the
21190 	 * connection has gone into timewait state, then we will have
21191 	 * one ref for the TCP and one more ref (total of two) for the
21192 	 * classifier connected hash list (a timewait connections stays
21193 	 * in connected hash till closed).
21194 	 *
21195 	 * We can't assert the references because there might be other
21196 	 * transient reference places because of some walkers or queued
21197 	 * packets in squeue for the timewait state.
21198 	 */
21199 	CONN_DEC_REF(connp);
21200 	return (0);
21201 }
21202 
21203 /* ARGSUSED */
21204 int
21205 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
21206     cred_t *cr)
21207 {
21208 	tcp_t		*tcp;
21209 	uint32_t	msize;
21210 	conn_t *connp = (conn_t *)proto_handle;
21211 	int32_t		tcpstate;
21212 
21213 	/* All Solaris components should pass a cred for this operation. */
21214 	ASSERT(cr != NULL);
21215 
21216 	ASSERT(connp->conn_ref >= 2);
21217 	ASSERT(connp->conn_upper_handle != NULL);
21218 
21219 	if (msg->msg_controllen != 0) {
21220 		freemsg(mp);
21221 		return (EOPNOTSUPP);
21222 	}
21223 
21224 	switch (DB_TYPE(mp)) {
21225 	case M_DATA:
21226 		tcp = connp->conn_tcp;
21227 		ASSERT(tcp != NULL);
21228 
21229 		tcpstate = tcp->tcp_state;
21230 		if (tcpstate < TCPS_ESTABLISHED) {
21231 			freemsg(mp);
21232 			/*
21233 			 * We return ENOTCONN if the endpoint is trying to
21234 			 * connect or has never been connected, and EPIPE if it
21235 			 * has been disconnected. The connection id helps us
21236 			 * distinguish between the last two cases.
21237 			 */
21238 			return ((tcpstate == TCPS_SYN_SENT) ? ENOTCONN :
21239 			    ((tcp->tcp_connid > 0) ? EPIPE : ENOTCONN));
21240 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
21241 			freemsg(mp);
21242 			return (EPIPE);
21243 		}
21244 
21245 		msize = msgdsize(mp);
21246 
21247 		mutex_enter(&tcp->tcp_non_sq_lock);
21248 		tcp->tcp_squeue_bytes += msize;
21249 		/*
21250 		 * Squeue Flow Control
21251 		 */
21252 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
21253 			tcp_setqfull(tcp);
21254 		}
21255 		mutex_exit(&tcp->tcp_non_sq_lock);
21256 
21257 		/*
21258 		 * The application may pass in an address in the msghdr, but
21259 		 * we ignore the address on connection-oriented sockets.
21260 		 * Just like BSD this code does not generate an error for
21261 		 * TCP (a CONNREQUIRED socket) when sending to an address
21262 		 * passed in with sendto/sendmsg. Instead the data is
21263 		 * delivered on the connection as if no address had been
21264 		 * supplied.
21265 		 */
21266 		CONN_INC_REF(connp);
21267 
21268 		if (msg->msg_flags & MSG_OOB) {
21269 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output_urgent,
21270 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21271 		} else {
21272 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
21273 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21274 		}
21275 
21276 		return (0);
21277 
21278 	default:
21279 		ASSERT(0);
21280 	}
21281 
21282 	freemsg(mp);
21283 	return (0);
21284 }
21285 
21286 /* ARGSUSED2 */
21287 void
21288 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21289 {
21290 	int len;
21291 	uint32_t msize;
21292 	conn_t *connp = (conn_t *)arg;
21293 	tcp_t *tcp = connp->conn_tcp;
21294 
21295 	msize = msgdsize(mp);
21296 
21297 	len = msize - 1;
21298 	if (len < 0) {
21299 		freemsg(mp);
21300 		return;
21301 	}
21302 
21303 	/*
21304 	 * Try to force urgent data out on the wire. Even if we have unsent
21305 	 * data this will at least send the urgent flag.
21306 	 * XXX does not handle more flag correctly.
21307 	 */
21308 	len += tcp->tcp_unsent;
21309 	len += tcp->tcp_snxt;
21310 	tcp->tcp_urg = len;
21311 	tcp->tcp_valid_bits |= TCP_URG_VALID;
21312 
21313 	/* Bypass tcp protocol for fused tcp loopback */
21314 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21315 		return;
21316 
21317 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
21318 	if (DB_TYPE(mp) != M_DATA) {
21319 		mblk_t *mp1 = mp;
21320 		ASSERT(!IPCL_IS_NONSTR(connp));
21321 		mp = mp->b_cont;
21322 		freeb(mp1);
21323 	}
21324 	tcp_wput_data(tcp, mp, B_TRUE);
21325 }
21326 
21327 /* ARGSUSED3 */
21328 int
21329 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21330     socklen_t *addrlenp, cred_t *cr)
21331 {
21332 	conn_t	*connp = (conn_t *)proto_handle;
21333 	tcp_t	*tcp = connp->conn_tcp;
21334 
21335 	ASSERT(connp->conn_upper_handle != NULL);
21336 	/* All Solaris components should pass a cred for this operation. */
21337 	ASSERT(cr != NULL);
21338 
21339 	ASSERT(tcp != NULL);
21340 	if (tcp->tcp_state < TCPS_SYN_RCVD)
21341 		return (ENOTCONN);
21342 
21343 	return (conn_getpeername(connp, addr, addrlenp));
21344 }
21345 
21346 /* ARGSUSED3 */
21347 int
21348 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21349     socklen_t *addrlenp, cred_t *cr)
21350 {
21351 	conn_t	*connp = (conn_t *)proto_handle;
21352 
21353 	/* All Solaris components should pass a cred for this operation. */
21354 	ASSERT(cr != NULL);
21355 
21356 	ASSERT(connp->conn_upper_handle != NULL);
21357 	return (conn_getsockname(connp, addr, addrlenp));
21358 }
21359 
21360 /*
21361  * tcp_fallback
21362  *
21363  * A direct socket is falling back to using STREAMS. The queue
21364  * that is being passed down was created using tcp_open() with
21365  * the SO_FALLBACK flag set. As a result, the queue is not
21366  * associated with a conn, and the q_ptrs instead contain the
21367  * dev and minor area that should be used.
21368  *
21369  * The 'issocket' flag indicates whether the FireEngine
21370  * optimizations should be used. The common case would be that
21371  * optimizations are enabled, and they might be subsequently
21372  * disabled using the _SIOCSOCKFALLBACK ioctl.
21373  */
21374 
21375 /*
21376  * An active connection is falling back to TPI. Gather all the information
21377  * required by the STREAM head and TPI sonode and send it up.
21378  */
21379 void
21380 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
21381     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
21382 {
21383 	conn_t			*connp = tcp->tcp_connp;
21384 	struct stroptions	*stropt;
21385 	struct T_capability_ack tca;
21386 	struct sockaddr_in6	laddr, faddr;
21387 	socklen_t 		laddrlen, faddrlen;
21388 	short			opts;
21389 	int			error;
21390 	mblk_t			*mp;
21391 
21392 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
21393 	connp->conn_minor_arena = WR(q)->q_ptr;
21394 
21395 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
21396 
21397 	connp->conn_rq = RD(q);
21398 	connp->conn_wq = WR(q);
21399 
21400 	WR(q)->q_qinfo = &tcp_sock_winit;
21401 
21402 	if (!issocket)
21403 		tcp_use_pure_tpi(tcp);
21404 
21405 	/*
21406 	 * free the helper stream
21407 	 */
21408 	ip_free_helper_stream(connp);
21409 
21410 	/*
21411 	 * Notify the STREAM head about options
21412 	 */
21413 	DB_TYPE(stropt_mp) = M_SETOPTS;
21414 	stropt = (struct stroptions *)stropt_mp->b_rptr;
21415 	stropt_mp->b_wptr += sizeof (struct stroptions);
21416 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
21417 
21418 	stropt->so_wroff = connp->conn_ht_iphc_len + (tcp->tcp_loopback ? 0 :
21419 	    tcp->tcp_tcps->tcps_wroff_xtra);
21420 	if (tcp->tcp_snd_sack_ok)
21421 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
21422 	stropt->so_hiwat = connp->conn_rcvbuf;
21423 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
21424 
21425 	putnext(RD(q), stropt_mp);
21426 
21427 	/*
21428 	 * Collect the information needed to sync with the sonode
21429 	 */
21430 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
21431 
21432 	laddrlen = faddrlen = sizeof (sin6_t);
21433 	(void) tcp_getsockname((sock_lower_handle_t)connp,
21434 	    (struct sockaddr *)&laddr, &laddrlen, CRED());
21435 	error = tcp_getpeername((sock_lower_handle_t)connp,
21436 	    (struct sockaddr *)&faddr, &faddrlen, CRED());
21437 	if (error != 0)
21438 		faddrlen = 0;
21439 
21440 	opts = 0;
21441 	if (connp->conn_oobinline)
21442 		opts |= SO_OOBINLINE;
21443 	if (connp->conn_ixa->ixa_flags & IXAF_DONTROUTE)
21444 		opts |= SO_DONTROUTE;
21445 
21446 	/*
21447 	 * Notify the socket that the protocol is now quiescent,
21448 	 * and it's therefore safe move data from the socket
21449 	 * to the stream head.
21450 	 */
21451 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
21452 	    (struct sockaddr *)&laddr, laddrlen,
21453 	    (struct sockaddr *)&faddr, faddrlen, opts);
21454 
21455 	while ((mp = tcp->tcp_rcv_list) != NULL) {
21456 		tcp->tcp_rcv_list = mp->b_next;
21457 		mp->b_next = NULL;
21458 		/* We never do fallback for kernel RPC */
21459 		putnext(q, mp);
21460 	}
21461 	tcp->tcp_rcv_last_head = NULL;
21462 	tcp->tcp_rcv_last_tail = NULL;
21463 	tcp->tcp_rcv_cnt = 0;
21464 }
21465 
21466 /*
21467  * An eager is falling back to TPI. All we have to do is send
21468  * up a T_CONN_IND.
21469  */
21470 void
21471 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
21472 {
21473 	tcp_t *listener = eager->tcp_listener;
21474 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
21475 
21476 	ASSERT(listener != NULL);
21477 	ASSERT(mp != NULL);
21478 
21479 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
21480 
21481 	/*
21482 	 * TLI/XTI applications will get confused by
21483 	 * sending eager as an option since it violates
21484 	 * the option semantics. So remove the eager as
21485 	 * option since TLI/XTI app doesn't need it anyway.
21486 	 */
21487 	if (!direct_sockfs) {
21488 		struct T_conn_ind *conn_ind;
21489 
21490 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
21491 		conn_ind->OPT_length = 0;
21492 		conn_ind->OPT_offset = 0;
21493 	}
21494 
21495 	/*
21496 	 * Sockfs guarantees that the listener will not be closed
21497 	 * during fallback. So we can safely use the listener's queue.
21498 	 */
21499 	putnext(listener->tcp_connp->conn_rq, mp);
21500 }
21501 
21502 int
21503 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
21504     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
21505 {
21506 	tcp_t			*tcp;
21507 	conn_t 			*connp = (conn_t *)proto_handle;
21508 	int			error;
21509 	mblk_t			*stropt_mp;
21510 	mblk_t			*ordrel_mp;
21511 
21512 	tcp = connp->conn_tcp;
21513 
21514 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
21515 	    NULL);
21516 
21517 	/* Pre-allocate the T_ordrel_ind mblk. */
21518 	ASSERT(tcp->tcp_ordrel_mp == NULL);
21519 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
21520 	    STR_NOSIG, NULL);
21521 	ordrel_mp->b_datap->db_type = M_PROTO;
21522 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
21523 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
21524 
21525 	/*
21526 	 * Enter the squeue so that no new packets can come in
21527 	 */
21528 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
21529 	if (error != 0) {
21530 		/* failed to enter, free all the pre-allocated messages. */
21531 		freeb(stropt_mp);
21532 		freeb(ordrel_mp);
21533 		/*
21534 		 * We cannot process the eager, so at least send out a
21535 		 * RST so the peer can reconnect.
21536 		 */
21537 		if (tcp->tcp_listener != NULL) {
21538 			(void) tcp_eager_blowoff(tcp->tcp_listener,
21539 			    tcp->tcp_conn_req_seqnum);
21540 		}
21541 		return (ENOMEM);
21542 	}
21543 
21544 	/*
21545 	 * Both endpoints must be of the same type (either STREAMS or
21546 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
21547 	 * we have to unfuse.
21548 	 */
21549 	if (tcp->tcp_fused)
21550 		tcp_unfuse(tcp);
21551 
21552 	/*
21553 	 * No longer a direct socket
21554 	 */
21555 	connp->conn_flags &= ~IPCL_NONSTR;
21556 	tcp->tcp_ordrel_mp = ordrel_mp;
21557 
21558 	if (tcp->tcp_listener != NULL) {
21559 		/* The eager will deal with opts when accept() is called */
21560 		freeb(stropt_mp);
21561 		tcp_fallback_eager(tcp, direct_sockfs);
21562 	} else {
21563 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
21564 		    quiesced_cb);
21565 	}
21566 
21567 	/*
21568 	 * There should be atleast two ref's (IP + TCP)
21569 	 */
21570 	ASSERT(connp->conn_ref >= 2);
21571 	squeue_synch_exit(connp->conn_sqp, connp);
21572 
21573 	return (0);
21574 }
21575 
21576 /* ARGSUSED */
21577 static void
21578 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21579 {
21580 	conn_t 	*connp = (conn_t *)arg;
21581 	tcp_t	*tcp = connp->conn_tcp;
21582 
21583 	freemsg(mp);
21584 
21585 	if (tcp->tcp_fused)
21586 		tcp_unfuse(tcp);
21587 
21588 	if (tcp_xmit_end(tcp) != 0) {
21589 		/*
21590 		 * We were crossing FINs and got a reset from
21591 		 * the other side. Just ignore it.
21592 		 */
21593 		if (connp->conn_debug) {
21594 			(void) strlog(TCP_MOD_ID, 0, 1,
21595 			    SL_ERROR|SL_TRACE,
21596 			    "tcp_shutdown_output() out of state %s",
21597 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
21598 		}
21599 	}
21600 }
21601 
21602 /* ARGSUSED */
21603 int
21604 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
21605 {
21606 	conn_t  *connp = (conn_t *)proto_handle;
21607 	tcp_t   *tcp = connp->conn_tcp;
21608 
21609 	ASSERT(connp->conn_upper_handle != NULL);
21610 
21611 	/* All Solaris components should pass a cred for this operation. */
21612 	ASSERT(cr != NULL);
21613 
21614 	/*
21615 	 * X/Open requires that we check the connected state.
21616 	 */
21617 	if (tcp->tcp_state < TCPS_SYN_SENT)
21618 		return (ENOTCONN);
21619 
21620 	/* shutdown the send side */
21621 	if (how != SHUT_RD) {
21622 		mblk_t *bp;
21623 
21624 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
21625 		CONN_INC_REF(connp);
21626 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
21627 		    connp, NULL, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
21628 
21629 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21630 		    SOCK_OPCTL_SHUT_SEND, 0);
21631 	}
21632 
21633 	/* shutdown the recv side */
21634 	if (how != SHUT_WR)
21635 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21636 		    SOCK_OPCTL_SHUT_RECV, 0);
21637 
21638 	return (0);
21639 }
21640 
21641 /*
21642  * SOP_LISTEN() calls into tcp_listen().
21643  */
21644 /* ARGSUSED */
21645 int
21646 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
21647 {
21648 	conn_t	*connp = (conn_t *)proto_handle;
21649 	int 	error;
21650 	squeue_t *sqp = connp->conn_sqp;
21651 
21652 	ASSERT(connp->conn_upper_handle != NULL);
21653 
21654 	/* All Solaris components should pass a cred for this operation. */
21655 	ASSERT(cr != NULL);
21656 
21657 	error = squeue_synch_enter(sqp, connp, NULL);
21658 	if (error != 0) {
21659 		/* failed to enter */
21660 		return (ENOBUFS);
21661 	}
21662 
21663 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
21664 	if (error == 0) {
21665 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21666 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
21667 	} else if (error < 0) {
21668 		if (error == -TOUTSTATE)
21669 			error = EINVAL;
21670 		else
21671 			error = proto_tlitosyserr(-error);
21672 	}
21673 	squeue_synch_exit(sqp, connp);
21674 	return (error);
21675 }
21676 
21677 static int
21678 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
21679     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
21680 {
21681 	tcp_t		*tcp = connp->conn_tcp;
21682 	int		error = 0;
21683 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21684 
21685 	/* All Solaris components should pass a cred for this operation. */
21686 	ASSERT(cr != NULL);
21687 
21688 	if (tcp->tcp_state >= TCPS_BOUND) {
21689 		if ((tcp->tcp_state == TCPS_BOUND ||
21690 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
21691 			/*
21692 			 * Handle listen() increasing backlog.
21693 			 * This is more "liberal" then what the TPI spec
21694 			 * requires but is needed to avoid a t_unbind
21695 			 * when handling listen() since the port number
21696 			 * might be "stolen" between the unbind and bind.
21697 			 */
21698 			goto do_listen;
21699 		}
21700 		if (connp->conn_debug) {
21701 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21702 			    "tcp_listen: bad state, %d", tcp->tcp_state);
21703 		}
21704 		return (-TOUTSTATE);
21705 	} else {
21706 		if (sa == NULL) {
21707 			sin6_t	addr;
21708 			sin_t *sin;
21709 			sin6_t *sin6;
21710 
21711 			ASSERT(IPCL_IS_NONSTR(connp));
21712 			/* Do an implicit bind: Request for a generic port. */
21713 			if (connp->conn_family == AF_INET) {
21714 				len = sizeof (sin_t);
21715 				sin = (sin_t *)&addr;
21716 				*sin = sin_null;
21717 				sin->sin_family = AF_INET;
21718 			} else {
21719 				ASSERT(connp->conn_family == AF_INET6);
21720 				len = sizeof (sin6_t);
21721 				sin6 = (sin6_t *)&addr;
21722 				*sin6 = sin6_null;
21723 				sin6->sin6_family = AF_INET6;
21724 			}
21725 			sa = (struct sockaddr *)&addr;
21726 		}
21727 
21728 		error = tcp_bind_check(connp, sa, len, cr,
21729 		    bind_to_req_port_only);
21730 		if (error)
21731 			return (error);
21732 		/* Fall through and do the fanout insertion */
21733 	}
21734 
21735 do_listen:
21736 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
21737 	tcp->tcp_conn_req_max = backlog;
21738 	if (tcp->tcp_conn_req_max) {
21739 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
21740 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
21741 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
21742 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
21743 		/*
21744 		 * If this is a listener, do not reset the eager list
21745 		 * and other stuffs.  Note that we don't check if the
21746 		 * existing eager list meets the new tcp_conn_req_max
21747 		 * requirement.
21748 		 */
21749 		if (tcp->tcp_state != TCPS_LISTEN) {
21750 			tcp->tcp_state = TCPS_LISTEN;
21751 			/* Initialize the chain. Don't need the eager_lock */
21752 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
21753 			tcp->tcp_eager_next_drop_q0 = tcp;
21754 			tcp->tcp_eager_prev_drop_q0 = tcp;
21755 			tcp->tcp_second_ctimer_threshold =
21756 			    tcps->tcps_ip_abort_linterval;
21757 		}
21758 	}
21759 
21760 	/*
21761 	 * We need to make sure that the conn_recv is set to a non-null
21762 	 * value before we insert the conn into the classifier table.
21763 	 * This is to avoid a race with an incoming packet which does an
21764 	 * ipcl_classify().
21765 	 * We initially set it to tcp_input_listener_unbound to try to
21766 	 * pick a good squeue for the listener when the first SYN arrives.
21767 	 * tcp_input_listener_unbound sets it to tcp_input_listener on that
21768 	 * first SYN.
21769 	 */
21770 	connp->conn_recv = tcp_input_listener_unbound;
21771 
21772 	/* Insert the listener in the classifier table */
21773 	error = ip_laddr_fanout_insert(connp);
21774 	if (error != 0) {
21775 		/* Undo the bind - release the port number */
21776 		tcp->tcp_state = TCPS_IDLE;
21777 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
21778 
21779 		connp->conn_laddr_v6 = ipv6_all_zeros;
21780 		connp->conn_saddr_v6 = ipv6_all_zeros;
21781 		connp->conn_ports = 0;
21782 
21783 		if (connp->conn_anon_port) {
21784 			zone_t		*zone;
21785 
21786 			zone = crgetzone(cr);
21787 			connp->conn_anon_port = B_FALSE;
21788 			(void) tsol_mlp_anon(zone, connp->conn_mlp_type,
21789 			    connp->conn_proto, connp->conn_lport, B_FALSE);
21790 		}
21791 		connp->conn_mlp_type = mlptSingle;
21792 
21793 		tcp_bind_hash_remove(tcp);
21794 		return (error);
21795 	} else {
21796 		/*
21797 		 * If there is a connection limit, allocate and initialize
21798 		 * the counter struct.  Note that since listen can be called
21799 		 * multiple times, the struct may have been allready allocated.
21800 		 */
21801 		if (!list_is_empty(&tcps->tcps_listener_conf) &&
21802 		    tcp->tcp_listen_cnt == NULL) {
21803 			tcp_listen_cnt_t *tlc;
21804 			uint32_t ratio;
21805 
21806 			ratio = tcp_find_listener_conf(tcps,
21807 			    ntohs(connp->conn_lport));
21808 			if (ratio != 0) {
21809 				uint32_t mem_ratio, tot_buf;
21810 
21811 				tlc = kmem_alloc(sizeof (tcp_listen_cnt_t),
21812 				    KM_SLEEP);
21813 				/*
21814 				 * Calculate the connection limit based on
21815 				 * the configured ratio and maxusers.  Maxusers
21816 				 * are calculated based on memory size,
21817 				 * ~ 1 user per MB.  Note that the conn_rcvbuf
21818 				 * and conn_sndbuf may change after a
21819 				 * connection is accepted.  So what we have
21820 				 * is only an approximation.
21821 				 */
21822 				if ((tot_buf = connp->conn_rcvbuf +
21823 				    connp->conn_sndbuf) < MB) {
21824 					mem_ratio = MB / tot_buf;
21825 					tlc->tlc_max = maxusers / ratio *
21826 					    mem_ratio;
21827 				} else {
21828 					mem_ratio = tot_buf / MB;
21829 					tlc->tlc_max = maxusers / ratio /
21830 					    mem_ratio;
21831 				}
21832 				/* At least we should allow two connections! */
21833 				if (tlc->tlc_max <= tcp_min_conn_listener)
21834 					tlc->tlc_max = tcp_min_conn_listener;
21835 				tlc->tlc_cnt = 1;
21836 				tlc->tlc_drop = 0;
21837 				tcp->tcp_listen_cnt = tlc;
21838 			}
21839 		}
21840 	}
21841 	return (error);
21842 }
21843 
21844 void
21845 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
21846 {
21847 	conn_t  *connp = (conn_t *)proto_handle;
21848 	tcp_t	*tcp = connp->conn_tcp;
21849 	mblk_t *mp;
21850 	int error;
21851 
21852 	ASSERT(connp->conn_upper_handle != NULL);
21853 
21854 	/*
21855 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
21856 	 * is currently running.
21857 	 */
21858 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21859 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
21860 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
21861 		return;
21862 	}
21863 	tcp->tcp_rsrv_mp = NULL;
21864 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21865 
21866 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
21867 	ASSERT(error == 0);
21868 
21869 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21870 	tcp->tcp_rsrv_mp = mp;
21871 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21872 
21873 	if (tcp->tcp_fused) {
21874 		tcp_fuse_backenable(tcp);
21875 	} else {
21876 		tcp->tcp_rwnd = connp->conn_rcvbuf;
21877 		/*
21878 		 * Send back a window update immediately if TCP is above
21879 		 * ESTABLISHED state and the increase of the rcv window
21880 		 * that the other side knows is at least 1 MSS after flow
21881 		 * control is lifted.
21882 		 */
21883 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
21884 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
21885 			tcp_xmit_ctl(NULL, tcp,
21886 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
21887 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21888 		}
21889 	}
21890 
21891 	squeue_synch_exit(connp->conn_sqp, connp);
21892 }
21893 
21894 /* ARGSUSED */
21895 int
21896 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
21897     int mode, int32_t *rvalp, cred_t *cr)
21898 {
21899 	conn_t  	*connp = (conn_t *)proto_handle;
21900 	int		error;
21901 
21902 	ASSERT(connp->conn_upper_handle != NULL);
21903 
21904 	/* All Solaris components should pass a cred for this operation. */
21905 	ASSERT(cr != NULL);
21906 
21907 	/*
21908 	 * If we don't have a helper stream then create one.
21909 	 * ip_create_helper_stream takes care of locking the conn_t,
21910 	 * so this check for NULL is just a performance optimization.
21911 	 */
21912 	if (connp->conn_helper_info == NULL) {
21913 		tcp_stack_t *tcps = connp->conn_tcp->tcp_tcps;
21914 
21915 		/*
21916 		 * Create a helper stream for non-STREAMS socket.
21917 		 */
21918 		error = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
21919 		if (error != 0) {
21920 			ip0dbg(("tcp_ioctl: create of IP helper stream "
21921 			    "failed %d\n", error));
21922 			return (error);
21923 		}
21924 	}
21925 
21926 	switch (cmd) {
21927 		case ND_SET:
21928 		case ND_GET:
21929 		case _SIOCSOCKFALLBACK:
21930 		case TCP_IOC_ABORT_CONN:
21931 		case TI_GETPEERNAME:
21932 		case TI_GETMYNAME:
21933 			ip1dbg(("tcp_ioctl: cmd 0x%x on non streams socket",
21934 			    cmd));
21935 			error = EINVAL;
21936 			break;
21937 		default:
21938 			/*
21939 			 * If the conn is not closing, pass on to IP using
21940 			 * helper stream. Bump the ioctlref to prevent tcp_close
21941 			 * from closing the rq/wq out from underneath the ioctl
21942 			 * if it ends up queued or aborted/interrupted.
21943 			 */
21944 			mutex_enter(&connp->conn_lock);
21945 			if (connp->conn_state_flags & (CONN_CLOSING)) {
21946 				mutex_exit(&connp->conn_lock);
21947 				error = EINVAL;
21948 				break;
21949 			}
21950 			CONN_INC_IOCTLREF_LOCKED(connp);
21951 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
21952 			    cmd, arg, mode, cr, rvalp);
21953 			CONN_DEC_IOCTLREF(connp);
21954 			break;
21955 	}
21956 	return (error);
21957 }
21958 
21959 sock_downcalls_t sock_tcp_downcalls = {
21960 	tcp_activate,
21961 	tcp_accept,
21962 	tcp_bind,
21963 	tcp_listen,
21964 	tcp_connect,
21965 	tcp_getpeername,
21966 	tcp_getsockname,
21967 	tcp_getsockopt,
21968 	tcp_setsockopt,
21969 	tcp_sendmsg,
21970 	NULL,
21971 	NULL,
21972 	NULL,
21973 	tcp_shutdown,
21974 	tcp_clr_flowctrl,
21975 	tcp_ioctl,
21976 	tcp_close,
21977 };
21978 
21979 /*
21980  * Timeout function to reset the TCP stack variable tcps_reclaim to false.
21981  */
21982 static void
21983 tcp_reclaim_timer(void *arg)
21984 {
21985 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
21986 
21987 	mutex_enter(&tcps->tcps_reclaim_lock);
21988 	tcps->tcps_reclaim = B_FALSE;
21989 	tcps->tcps_reclaim_tid = 0;
21990 	mutex_exit(&tcps->tcps_reclaim_lock);
21991 	/* Only need to print this once. */
21992 	if (tcps->tcps_netstack->netstack_stackid == GLOBAL_ZONEID)
21993 		cmn_err(CE_WARN, "TCP defensive mode off\n");
21994 }
21995 
21996 /*
21997  * Kmem reclaim call back function.  When the system is under memory
21998  * pressure, we set the TCP stack variable tcps_reclaim to true.  This
21999  * variable is reset to false after tcps_reclaim_period msecs.  During this
22000  * period, TCP will be more aggressive in aborting connections not making
22001  * progress, meaning retransmitting for some time (tcp_early_abort seconds).
22002  * TCP will also not accept new connection request for those listeners whose
22003  * q or q0 is not empty.
22004  */
22005 /* ARGSUSED */
22006 void
22007 tcp_conn_reclaim(void *arg)
22008 {
22009 	netstack_handle_t nh;
22010 	netstack_t *ns;
22011 	tcp_stack_t *tcps;
22012 	boolean_t new = B_FALSE;
22013 
22014 	netstack_next_init(&nh);
22015 	while ((ns = netstack_next(&nh)) != NULL) {
22016 		tcps = ns->netstack_tcp;
22017 		mutex_enter(&tcps->tcps_reclaim_lock);
22018 		if (!tcps->tcps_reclaim) {
22019 			tcps->tcps_reclaim = B_TRUE;
22020 			tcps->tcps_reclaim_tid = timeout(tcp_reclaim_timer,
22021 			    tcps, MSEC_TO_TICK(tcps->tcps_reclaim_period));
22022 			new = B_TRUE;
22023 		}
22024 		mutex_exit(&tcps->tcps_reclaim_lock);
22025 		netstack_rele(ns);
22026 	}
22027 	netstack_next_fini(&nh);
22028 	if (new)
22029 		cmn_err(CE_WARN, "Memory pressure: TCP defensive mode on\n");
22030 }
22031 
22032 /*
22033  * Given a tcp_stack_t and a port (in host byte order), find a listener
22034  * configuration for that port and return the ratio.
22035  */
22036 static uint32_t
22037 tcp_find_listener_conf(tcp_stack_t *tcps, in_port_t port)
22038 {
22039 	tcp_listener_t	*tl;
22040 	uint32_t ratio = 0;
22041 
22042 	mutex_enter(&tcps->tcps_listener_conf_lock);
22043 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22044 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22045 		if (tl->tl_port == port) {
22046 			ratio = tl->tl_ratio;
22047 			break;
22048 		}
22049 	}
22050 	mutex_exit(&tcps->tcps_listener_conf_lock);
22051 	return (ratio);
22052 }
22053 
22054 /*
22055  * Ndd param helper routine to return the current list of listener limit
22056  * configuration.
22057  */
22058 /* ARGSUSED */
22059 static int
22060 tcp_listener_conf_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22061 {
22062 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22063 	tcp_listener_t	*tl;
22064 
22065 	mutex_enter(&tcps->tcps_listener_conf_lock);
22066 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22067 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22068 		(void) mi_mpprintf(mp, "%d:%d ", tl->tl_port, tl->tl_ratio);
22069 	}
22070 	mutex_exit(&tcps->tcps_listener_conf_lock);
22071 	return (0);
22072 }
22073 
22074 /*
22075  * Ndd param helper routine to add a new listener limit configuration.
22076  */
22077 /* ARGSUSED */
22078 static int
22079 tcp_listener_conf_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22080     cred_t *cr)
22081 {
22082 	tcp_listener_t	*new_tl;
22083 	tcp_listener_t	*tl;
22084 	long		lport;
22085 	long		ratio;
22086 	char		*colon;
22087 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22088 
22089 	if (ddi_strtol(value, &colon, 10, &lport) != 0 || lport <= 0 ||
22090 	    lport > USHRT_MAX || *colon != ':') {
22091 		return (EINVAL);
22092 	}
22093 	if (ddi_strtol(colon + 1, NULL, 10, &ratio) != 0 || ratio <= 0)
22094 		return (EINVAL);
22095 
22096 	mutex_enter(&tcps->tcps_listener_conf_lock);
22097 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22098 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22099 		/* There is an existing entry, so update its ratio value. */
22100 		if (tl->tl_port == lport) {
22101 			tl->tl_ratio = ratio;
22102 			mutex_exit(&tcps->tcps_listener_conf_lock);
22103 			return (0);
22104 		}
22105 	}
22106 
22107 	if ((new_tl = kmem_alloc(sizeof (tcp_listener_t), KM_NOSLEEP)) ==
22108 	    NULL) {
22109 		mutex_exit(&tcps->tcps_listener_conf_lock);
22110 		return (ENOMEM);
22111 	}
22112 
22113 	new_tl->tl_port = lport;
22114 	new_tl->tl_ratio = ratio;
22115 	list_insert_tail(&tcps->tcps_listener_conf, new_tl);
22116 	mutex_exit(&tcps->tcps_listener_conf_lock);
22117 	return (0);
22118 }
22119 
22120 /*
22121  * Ndd param helper routine to remove a listener limit configuration.
22122  */
22123 /* ARGSUSED */
22124 static int
22125 tcp_listener_conf_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22126     cred_t *cr)
22127 {
22128 	tcp_listener_t	*tl;
22129 	long		lport;
22130 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22131 
22132 	if (ddi_strtol(value, NULL, 10, &lport) != 0 || lport <= 0 ||
22133 	    lport > USHRT_MAX) {
22134 		return (EINVAL);
22135 	}
22136 	mutex_enter(&tcps->tcps_listener_conf_lock);
22137 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22138 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22139 		if (tl->tl_port == lport) {
22140 			list_remove(&tcps->tcps_listener_conf, tl);
22141 			mutex_exit(&tcps->tcps_listener_conf_lock);
22142 			kmem_free(tl, sizeof (tcp_listener_t));
22143 			return (0);
22144 		}
22145 	}
22146 	mutex_exit(&tcps->tcps_listener_conf_lock);
22147 	return (ESRCH);
22148 }
22149 
22150 /*
22151  * To remove all listener limit configuration in a tcp_stack_t.
22152  */
22153 static void
22154 tcp_listener_conf_cleanup(tcp_stack_t *tcps)
22155 {
22156 	tcp_listener_t	*tl;
22157 
22158 	mutex_enter(&tcps->tcps_listener_conf_lock);
22159 	while ((tl = list_head(&tcps->tcps_listener_conf)) != NULL) {
22160 		list_remove(&tcps->tcps_listener_conf, tl);
22161 		kmem_free(tl, sizeof (tcp_listener_t));
22162 	}
22163 	mutex_destroy(&tcps->tcps_listener_conf_lock);
22164 	list_destroy(&tcps->tcps_listener_conf);
22165 }
22166