xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision d24234c24aeaca4ca56ee3ac2794507968f274c4)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* 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_urp = 0;
8804 		tcpha->tha_ack = 0;
8805 		tcpha->tha_offset_and_reserved = (5 << 4);
8806 		tcpha->tha_lport = connp->conn_lport;
8807 		tcpha->tha_fport = connp->conn_fport;
8808 	}
8809 
8810 	/*
8811 	 * IP wants our header length in the checksum field to
8812 	 * allow it to perform a single pseudo-header+checksum
8813 	 * calculation on behalf of TCP.
8814 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8815 	 */
8816 	cksum = sizeof (tcpha_t) + connp->conn_sum;
8817 	cksum = (cksum >> 16) + (cksum & 0xFFFF);
8818 	ASSERT(cksum < 0x10000);
8819 	tcpha->tha_sum = htons(cksum);
8820 
8821 	if (connp->conn_ipversion == IPV4_VERSION)
8822 		tcp->tcp_ipha = (ipha_t *)connp->conn_ht_iphc;
8823 	else
8824 		tcp->tcp_ip6h = (ip6_t *)connp->conn_ht_iphc;
8825 
8826 	if (connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra >
8827 	    connp->conn_wroff) {
8828 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8829 		    tcps->tcps_wroff_xtra;
8830 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8831 		    connp->conn_wroff);
8832 	}
8833 	return (0);
8834 }
8835 
8836 /* Get callback routine passed to nd_load by tcp_param_register */
8837 /* ARGSUSED */
8838 static int
8839 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
8840 {
8841 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8842 
8843 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
8844 	return (0);
8845 }
8846 
8847 /*
8848  * Walk through the param array specified registering each element with the
8849  * named dispatch handler.
8850  */
8851 static boolean_t
8852 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
8853 {
8854 	for (; cnt-- > 0; tcppa++) {
8855 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
8856 			if (!nd_load(ndp, tcppa->tcp_param_name,
8857 			    tcp_param_get, tcp_param_set,
8858 			    (caddr_t)tcppa)) {
8859 				nd_free(ndp);
8860 				return (B_FALSE);
8861 			}
8862 		}
8863 	}
8864 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
8865 	    KM_SLEEP);
8866 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
8867 	    sizeof (tcpparam_t));
8868 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
8869 	    tcp_param_get, tcp_param_set_aligned,
8870 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
8871 		nd_free(ndp);
8872 		return (B_FALSE);
8873 	}
8874 	if (!nd_load(ndp, "tcp_extra_priv_ports",
8875 	    tcp_extra_priv_ports_get, NULL, NULL)) {
8876 		nd_free(ndp);
8877 		return (B_FALSE);
8878 	}
8879 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
8880 	    NULL, tcp_extra_priv_ports_add, NULL)) {
8881 		nd_free(ndp);
8882 		return (B_FALSE);
8883 	}
8884 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
8885 	    NULL, tcp_extra_priv_ports_del, NULL)) {
8886 		nd_free(ndp);
8887 		return (B_FALSE);
8888 	}
8889 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
8890 	    tcp_1948_phrase_set, NULL)) {
8891 		nd_free(ndp);
8892 		return (B_FALSE);
8893 	}
8894 
8895 
8896 	if (!nd_load(ndp, "tcp_listener_limit_conf",
8897 	    tcp_listener_conf_get, NULL, NULL)) {
8898 		nd_free(ndp);
8899 		return (B_FALSE);
8900 	}
8901 	if (!nd_load(ndp, "tcp_listener_limit_conf_add",
8902 	    NULL, tcp_listener_conf_add, NULL)) {
8903 		nd_free(ndp);
8904 		return (B_FALSE);
8905 	}
8906 	if (!nd_load(ndp, "tcp_listener_limit_conf_del",
8907 	    NULL, tcp_listener_conf_del, NULL)) {
8908 		nd_free(ndp);
8909 		return (B_FALSE);
8910 	}
8911 
8912 	/*
8913 	 * Dummy ndd variables - only to convey obsolescence information
8914 	 * through printing of their name (no get or set routines)
8915 	 * XXX Remove in future releases ?
8916 	 */
8917 	if (!nd_load(ndp,
8918 	    "tcp_close_wait_interval(obsoleted - "
8919 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
8920 		nd_free(ndp);
8921 		return (B_FALSE);
8922 	}
8923 	return (B_TRUE);
8924 }
8925 
8926 /* ndd set routine for tcp_wroff_xtra. */
8927 /* ARGSUSED */
8928 static int
8929 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
8930     cred_t *cr)
8931 {
8932 	long new_value;
8933 	tcpparam_t *tcppa = (tcpparam_t *)cp;
8934 
8935 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8936 	    new_value < tcppa->tcp_param_min ||
8937 	    new_value > tcppa->tcp_param_max) {
8938 		return (EINVAL);
8939 	}
8940 	/*
8941 	 * Need to make sure new_value is a multiple of 4.  If it is not,
8942 	 * round it up.  For future 64 bit requirement, we actually make it
8943 	 * a multiple of 8.
8944 	 */
8945 	if (new_value & 0x7) {
8946 		new_value = (new_value & ~0x7) + 0x8;
8947 	}
8948 	tcppa->tcp_param_val = new_value;
8949 	return (0);
8950 }
8951 
8952 /* Set callback routine passed to nd_load by tcp_param_register */
8953 /* ARGSUSED */
8954 static int
8955 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
8956 {
8957 	long	new_value;
8958 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8959 
8960 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8961 	    new_value < tcppa->tcp_param_min ||
8962 	    new_value > tcppa->tcp_param_max) {
8963 		return (EINVAL);
8964 	}
8965 	tcppa->tcp_param_val = new_value;
8966 	return (0);
8967 }
8968 
8969 static void
8970 tcp_reass_timer(void *arg)
8971 {
8972 	conn_t *connp = (conn_t *)arg;
8973 	tcp_t *tcp = connp->conn_tcp;
8974 
8975 	tcp->tcp_reass_tid = 0;
8976 	if (tcp->tcp_reass_head == NULL)
8977 		return;
8978 	ASSERT(tcp->tcp_reass_tail != NULL);
8979 	tcp_sack_remove(tcp->tcp_sack_list, TCP_REASS_END(tcp->tcp_reass_tail),
8980 	    &tcp->tcp_num_sack_blk);
8981 	tcp_close_mpp(&tcp->tcp_reass_head);
8982 	tcp->tcp_reass_tail = NULL;
8983 }
8984 
8985 /*
8986  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
8987  * is filled, return as much as we can.  The message passed in may be
8988  * multi-part, chained using b_cont.  "start" is the starting sequence
8989  * number for this piece.
8990  */
8991 static mblk_t *
8992 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
8993 {
8994 	uint32_t	end;
8995 	mblk_t		*mp1;
8996 	mblk_t		*mp2;
8997 	mblk_t		*next_mp;
8998 	uint32_t	u1;
8999 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9000 
9001 
9002 	/* Walk through all the new pieces. */
9003 	do {
9004 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
9005 		    (uintptr_t)INT_MAX);
9006 		end = start + (int)(mp->b_wptr - mp->b_rptr);
9007 		next_mp = mp->b_cont;
9008 		if (start == end) {
9009 			/* Empty.  Blast it. */
9010 			freeb(mp);
9011 			continue;
9012 		}
9013 		mp->b_cont = NULL;
9014 		TCP_REASS_SET_SEQ(mp, start);
9015 		TCP_REASS_SET_END(mp, end);
9016 		mp1 = tcp->tcp_reass_tail;
9017 		if (!mp1) {
9018 			tcp->tcp_reass_tail = mp;
9019 			tcp->tcp_reass_head = mp;
9020 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9021 			UPDATE_MIB(&tcps->tcps_mib,
9022 			    tcpInDataUnorderBytes, end - start);
9023 			continue;
9024 		}
9025 		/* New stuff completely beyond tail? */
9026 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
9027 			/* Link it on end. */
9028 			mp1->b_cont = mp;
9029 			tcp->tcp_reass_tail = mp;
9030 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
9031 			UPDATE_MIB(&tcps->tcps_mib,
9032 			    tcpInDataUnorderBytes, end - start);
9033 			continue;
9034 		}
9035 		mp1 = tcp->tcp_reass_head;
9036 		u1 = TCP_REASS_SEQ(mp1);
9037 		/* New stuff at the front? */
9038 		if (SEQ_LT(start, u1)) {
9039 			/* Yes... Check for overlap. */
9040 			mp->b_cont = mp1;
9041 			tcp->tcp_reass_head = mp;
9042 			tcp_reass_elim_overlap(tcp, mp);
9043 			continue;
9044 		}
9045 		/*
9046 		 * The new piece fits somewhere between the head and tail.
9047 		 * We find our slot, where mp1 precedes us and mp2 trails.
9048 		 */
9049 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
9050 			u1 = TCP_REASS_SEQ(mp2);
9051 			if (SEQ_LEQ(start, u1))
9052 				break;
9053 		}
9054 		/* Link ourselves in */
9055 		mp->b_cont = mp2;
9056 		mp1->b_cont = mp;
9057 
9058 		/* Trim overlap with following mblk(s) first */
9059 		tcp_reass_elim_overlap(tcp, mp);
9060 
9061 		/* Trim overlap with preceding mblk */
9062 		tcp_reass_elim_overlap(tcp, mp1);
9063 
9064 	} while (start = end, mp = next_mp);
9065 	mp1 = tcp->tcp_reass_head;
9066 	/* Anything ready to go? */
9067 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
9068 		return (NULL);
9069 	/* Eat what we can off the queue */
9070 	for (;;) {
9071 		mp = mp1->b_cont;
9072 		end = TCP_REASS_END(mp1);
9073 		TCP_REASS_SET_SEQ(mp1, 0);
9074 		TCP_REASS_SET_END(mp1, 0);
9075 		if (!mp) {
9076 			tcp->tcp_reass_tail = NULL;
9077 			break;
9078 		}
9079 		if (end != TCP_REASS_SEQ(mp)) {
9080 			mp1->b_cont = NULL;
9081 			break;
9082 		}
9083 		mp1 = mp;
9084 	}
9085 	mp1 = tcp->tcp_reass_head;
9086 	tcp->tcp_reass_head = mp;
9087 	return (mp1);
9088 }
9089 
9090 /* Eliminate any overlap that mp may have over later mblks */
9091 static void
9092 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
9093 {
9094 	uint32_t	end;
9095 	mblk_t		*mp1;
9096 	uint32_t	u1;
9097 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9098 
9099 	end = TCP_REASS_END(mp);
9100 	while ((mp1 = mp->b_cont) != NULL) {
9101 		u1 = TCP_REASS_SEQ(mp1);
9102 		if (!SEQ_GT(end, u1))
9103 			break;
9104 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
9105 			mp->b_wptr -= end - u1;
9106 			TCP_REASS_SET_END(mp, u1);
9107 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
9108 			UPDATE_MIB(&tcps->tcps_mib,
9109 			    tcpInDataPartDupBytes, end - u1);
9110 			break;
9111 		}
9112 		mp->b_cont = mp1->b_cont;
9113 		TCP_REASS_SET_SEQ(mp1, 0);
9114 		TCP_REASS_SET_END(mp1, 0);
9115 		freeb(mp1);
9116 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
9117 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
9118 	}
9119 	if (!mp1)
9120 		tcp->tcp_reass_tail = mp;
9121 }
9122 
9123 static uint_t
9124 tcp_rwnd_reopen(tcp_t *tcp)
9125 {
9126 	uint_t ret = 0;
9127 	uint_t thwin;
9128 	conn_t *connp = tcp->tcp_connp;
9129 
9130 	/* Learn the latest rwnd information that we sent to the other side. */
9131 	thwin = ((uint_t)ntohs(tcp->tcp_tcpha->tha_win))
9132 	    << tcp->tcp_rcv_ws;
9133 	/* This is peer's calculated send window (our receive window). */
9134 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
9135 	/*
9136 	 * Increase the receive window to max.  But we need to do receiver
9137 	 * SWS avoidance.  This means that we need to check the increase of
9138 	 * of receive window is at least 1 MSS.
9139 	 */
9140 	if (connp->conn_rcvbuf - thwin >= tcp->tcp_mss) {
9141 		/*
9142 		 * If the window that the other side knows is less than max
9143 		 * deferred acks segments, send an update immediately.
9144 		 */
9145 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
9146 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
9147 			ret = TH_ACK_NEEDED;
9148 		}
9149 		tcp->tcp_rwnd = connp->conn_rcvbuf;
9150 	}
9151 	return (ret);
9152 }
9153 
9154 /*
9155  * Send up all messages queued on tcp_rcv_list.
9156  */
9157 static uint_t
9158 tcp_rcv_drain(tcp_t *tcp)
9159 {
9160 	mblk_t *mp;
9161 	uint_t ret = 0;
9162 #ifdef DEBUG
9163 	uint_t cnt = 0;
9164 #endif
9165 	queue_t	*q = tcp->tcp_connp->conn_rq;
9166 
9167 	/* Can't drain on an eager connection */
9168 	if (tcp->tcp_listener != NULL)
9169 		return (ret);
9170 
9171 	/* Can't be a non-STREAMS connection */
9172 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
9173 
9174 	/* No need for the push timer now. */
9175 	if (tcp->tcp_push_tid != 0) {
9176 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
9177 		tcp->tcp_push_tid = 0;
9178 	}
9179 
9180 	/*
9181 	 * Handle two cases here: we are currently fused or we were
9182 	 * previously fused and have some urgent data to be delivered
9183 	 * upstream.  The latter happens because we either ran out of
9184 	 * memory or were detached and therefore sending the SIGURG was
9185 	 * deferred until this point.  In either case we pass control
9186 	 * over to tcp_fuse_rcv_drain() since it may need to complete
9187 	 * some work.
9188 	 */
9189 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
9190 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
9191 		    tcp->tcp_fused_sigurg_mp != NULL);
9192 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
9193 		    &tcp->tcp_fused_sigurg_mp))
9194 			return (ret);
9195 	}
9196 
9197 	while ((mp = tcp->tcp_rcv_list) != NULL) {
9198 		tcp->tcp_rcv_list = mp->b_next;
9199 		mp->b_next = NULL;
9200 #ifdef DEBUG
9201 		cnt += msgdsize(mp);
9202 #endif
9203 		/* Does this need SSL processing first? */
9204 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
9205 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
9206 			    mblk_t *, mp);
9207 			tcp_kssl_input(tcp, mp, NULL);
9208 			continue;
9209 		}
9210 		putnext(q, mp);
9211 	}
9212 #ifdef DEBUG
9213 	ASSERT(cnt == tcp->tcp_rcv_cnt);
9214 #endif
9215 	tcp->tcp_rcv_last_head = NULL;
9216 	tcp->tcp_rcv_last_tail = NULL;
9217 	tcp->tcp_rcv_cnt = 0;
9218 
9219 	if (canputnext(q))
9220 		return (tcp_rwnd_reopen(tcp));
9221 
9222 	return (ret);
9223 }
9224 
9225 /*
9226  * Queue data on tcp_rcv_list which is a b_next chain.
9227  * tcp_rcv_last_head/tail is the last element of this chain.
9228  * Each element of the chain is a b_cont chain.
9229  *
9230  * M_DATA messages are added to the current element.
9231  * Other messages are added as new (b_next) elements.
9232  */
9233 void
9234 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len, cred_t *cr)
9235 {
9236 	ASSERT(seg_len == msgdsize(mp));
9237 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
9238 
9239 	if (is_system_labeled()) {
9240 		ASSERT(cr != NULL || msg_getcred(mp, NULL) != NULL);
9241 		/*
9242 		 * Provide for protocols above TCP such as RPC. NOPID leaves
9243 		 * db_cpid unchanged.
9244 		 * The cred could have already been set.
9245 		 */
9246 		if (cr != NULL)
9247 			mblk_setcred(mp, cr, NOPID);
9248 	}
9249 
9250 	if (tcp->tcp_rcv_list == NULL) {
9251 		ASSERT(tcp->tcp_rcv_last_head == NULL);
9252 		tcp->tcp_rcv_list = mp;
9253 		tcp->tcp_rcv_last_head = mp;
9254 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
9255 		tcp->tcp_rcv_last_tail->b_cont = mp;
9256 	} else {
9257 		tcp->tcp_rcv_last_head->b_next = mp;
9258 		tcp->tcp_rcv_last_head = mp;
9259 	}
9260 
9261 	while (mp->b_cont)
9262 		mp = mp->b_cont;
9263 
9264 	tcp->tcp_rcv_last_tail = mp;
9265 	tcp->tcp_rcv_cnt += seg_len;
9266 	tcp->tcp_rwnd -= seg_len;
9267 }
9268 
9269 /* The minimum of smoothed mean deviation in RTO calculation. */
9270 #define	TCP_SD_MIN	400
9271 
9272 /*
9273  * Set RTO for this connection.  The formula is from Jacobson and Karels'
9274  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
9275  * are the same as those in Appendix A.2 of that paper.
9276  *
9277  * m = new measurement
9278  * sa = smoothed RTT average (8 * average estimates).
9279  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
9280  */
9281 static void
9282 tcp_set_rto(tcp_t *tcp, clock_t rtt)
9283 {
9284 	long m = TICK_TO_MSEC(rtt);
9285 	clock_t sa = tcp->tcp_rtt_sa;
9286 	clock_t sv = tcp->tcp_rtt_sd;
9287 	clock_t rto;
9288 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9289 
9290 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
9291 	tcp->tcp_rtt_update++;
9292 
9293 	/* tcp_rtt_sa is not 0 means this is a new sample. */
9294 	if (sa != 0) {
9295 		/*
9296 		 * Update average estimator:
9297 		 *	new rtt = 7/8 old rtt + 1/8 Error
9298 		 */
9299 
9300 		/* m is now Error in estimate. */
9301 		m -= sa >> 3;
9302 		if ((sa += m) <= 0) {
9303 			/*
9304 			 * Don't allow the smoothed average to be negative.
9305 			 * We use 0 to denote reinitialization of the
9306 			 * variables.
9307 			 */
9308 			sa = 1;
9309 		}
9310 
9311 		/*
9312 		 * Update deviation estimator:
9313 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
9314 		 */
9315 		if (m < 0)
9316 			m = -m;
9317 		m -= sv >> 2;
9318 		sv += m;
9319 	} else {
9320 		/*
9321 		 * This follows BSD's implementation.  So the reinitialized
9322 		 * RTO is 3 * m.  We cannot go less than 2 because if the
9323 		 * link is bandwidth dominated, doubling the window size
9324 		 * during slow start means doubling the RTT.  We want to be
9325 		 * more conservative when we reinitialize our estimates.  3
9326 		 * is just a convenient number.
9327 		 */
9328 		sa = m << 3;
9329 		sv = m << 1;
9330 	}
9331 	if (sv < TCP_SD_MIN) {
9332 		/*
9333 		 * We do not know that if sa captures the delay ACK
9334 		 * effect as in a long train of segments, a receiver
9335 		 * does not delay its ACKs.  So set the minimum of sv
9336 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
9337 		 * of BSD DATO.  That means the minimum of mean
9338 		 * deviation is 100 ms.
9339 		 *
9340 		 */
9341 		sv = TCP_SD_MIN;
9342 	}
9343 	tcp->tcp_rtt_sa = sa;
9344 	tcp->tcp_rtt_sd = sv;
9345 	/*
9346 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
9347 	 *
9348 	 * Add tcp_rexmit_interval extra in case of extreme environment
9349 	 * where the algorithm fails to work.  The default value of
9350 	 * tcp_rexmit_interval_extra should be 0.
9351 	 *
9352 	 * As we use a finer grained clock than BSD and update
9353 	 * RTO for every ACKs, add in another .25 of RTT to the
9354 	 * deviation of RTO to accomodate burstiness of 1/4 of
9355 	 * window size.
9356 	 */
9357 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
9358 
9359 	if (rto > tcps->tcps_rexmit_interval_max) {
9360 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
9361 	} else if (rto < tcps->tcps_rexmit_interval_min) {
9362 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
9363 	} else {
9364 		tcp->tcp_rto = rto;
9365 	}
9366 
9367 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
9368 	tcp->tcp_timer_backoff = 0;
9369 }
9370 
9371 /*
9372  * tcp_get_seg_mp() is called to get the pointer to a segment in the
9373  * send queue which starts at the given sequence number. If the given
9374  * sequence number is equal to last valid sequence number (tcp_snxt), the
9375  * returned mblk is the last valid mblk, and off is set to the length of
9376  * that mblk.
9377  *
9378  * send queue which starts at the given seq. no.
9379  *
9380  * Parameters:
9381  *	tcp_t *tcp: the tcp instance pointer.
9382  *	uint32_t seq: the starting seq. no of the requested segment.
9383  *	int32_t *off: after the execution, *off will be the offset to
9384  *		the returned mblk which points to the requested seq no.
9385  *		It is the caller's responsibility to send in a non-null off.
9386  *
9387  * Return:
9388  *	A mblk_t pointer pointing to the requested segment in send queue.
9389  */
9390 static mblk_t *
9391 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
9392 {
9393 	int32_t	cnt;
9394 	mblk_t	*mp;
9395 
9396 	/* Defensive coding.  Make sure we don't send incorrect data. */
9397 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
9398 		return (NULL);
9399 
9400 	cnt = seq - tcp->tcp_suna;
9401 	mp = tcp->tcp_xmit_head;
9402 	while (cnt > 0 && mp != NULL) {
9403 		cnt -= mp->b_wptr - mp->b_rptr;
9404 		if (cnt <= 0) {
9405 			cnt += mp->b_wptr - mp->b_rptr;
9406 			break;
9407 		}
9408 		mp = mp->b_cont;
9409 	}
9410 	ASSERT(mp != NULL);
9411 	*off = cnt;
9412 	return (mp);
9413 }
9414 
9415 /*
9416  * This function handles all retransmissions if SACK is enabled for this
9417  * connection.  First it calculates how many segments can be retransmitted
9418  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
9419  * segments.  A segment is eligible if sack_cnt for that segment is greater
9420  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
9421  * all eligible segments, it checks to see if TCP can send some new segments
9422  * (fast recovery).  If it can, set the appropriate flag for tcp_input_data().
9423  *
9424  * Parameters:
9425  *	tcp_t *tcp: the tcp structure of the connection.
9426  *	uint_t *flags: in return, appropriate value will be set for
9427  *	tcp_input_data().
9428  */
9429 static void
9430 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
9431 {
9432 	notsack_blk_t	*notsack_blk;
9433 	int32_t		usable_swnd;
9434 	int32_t		mss;
9435 	uint32_t	seg_len;
9436 	mblk_t		*xmit_mp;
9437 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9438 
9439 	ASSERT(tcp->tcp_sack_info != NULL);
9440 	ASSERT(tcp->tcp_notsack_list != NULL);
9441 	ASSERT(tcp->tcp_rexmit == B_FALSE);
9442 
9443 	/* Defensive coding in case there is a bug... */
9444 	if (tcp->tcp_notsack_list == NULL) {
9445 		return;
9446 	}
9447 	notsack_blk = tcp->tcp_notsack_list;
9448 	mss = tcp->tcp_mss;
9449 
9450 	/*
9451 	 * Limit the num of outstanding data in the network to be
9452 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
9453 	 */
9454 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9455 
9456 	/* At least retransmit 1 MSS of data. */
9457 	if (usable_swnd <= 0) {
9458 		usable_swnd = mss;
9459 	}
9460 
9461 	/* Make sure no new RTT samples will be taken. */
9462 	tcp->tcp_csuna = tcp->tcp_snxt;
9463 
9464 	notsack_blk = tcp->tcp_notsack_list;
9465 	while (usable_swnd > 0) {
9466 		mblk_t		*snxt_mp, *tmp_mp;
9467 		tcp_seq		begin = tcp->tcp_sack_snxt;
9468 		tcp_seq		end;
9469 		int32_t		off;
9470 
9471 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
9472 			if (SEQ_GT(notsack_blk->end, begin) &&
9473 			    (notsack_blk->sack_cnt >=
9474 			    tcps->tcps_dupack_fast_retransmit)) {
9475 				end = notsack_blk->end;
9476 				if (SEQ_LT(begin, notsack_blk->begin)) {
9477 					begin = notsack_blk->begin;
9478 				}
9479 				break;
9480 			}
9481 		}
9482 		/*
9483 		 * All holes are filled.  Manipulate tcp_cwnd to send more
9484 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
9485 		 * set to tcp_cwnd_ssthresh.
9486 		 */
9487 		if (notsack_blk == NULL) {
9488 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9489 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
9490 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
9491 				ASSERT(tcp->tcp_cwnd > 0);
9492 				return;
9493 			} else {
9494 				usable_swnd = usable_swnd / mss;
9495 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
9496 				    MAX(usable_swnd * mss, mss);
9497 				*flags |= TH_XMIT_NEEDED;
9498 				return;
9499 			}
9500 		}
9501 
9502 		/*
9503 		 * Note that we may send more than usable_swnd allows here
9504 		 * because of round off, but no more than 1 MSS of data.
9505 		 */
9506 		seg_len = end - begin;
9507 		if (seg_len > mss)
9508 			seg_len = mss;
9509 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
9510 		ASSERT(snxt_mp != NULL);
9511 		/* This should not happen.  Defensive coding again... */
9512 		if (snxt_mp == NULL) {
9513 			return;
9514 		}
9515 
9516 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
9517 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
9518 		if (xmit_mp == NULL)
9519 			return;
9520 
9521 		usable_swnd -= seg_len;
9522 		tcp->tcp_pipe += seg_len;
9523 		tcp->tcp_sack_snxt = begin + seg_len;
9524 
9525 		tcp_send_data(tcp, xmit_mp);
9526 
9527 		/*
9528 		 * Update the send timestamp to avoid false retransmission.
9529 		 */
9530 		snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9531 
9532 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9533 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
9534 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
9535 		/*
9536 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
9537 		 * This happens when new data sent during fast recovery is
9538 		 * also lost.  If TCP retransmits those new data, it needs
9539 		 * to extend SACK recover phase to avoid starting another
9540 		 * fast retransmit/recovery unnecessarily.
9541 		 */
9542 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
9543 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
9544 		}
9545 	}
9546 }
9547 
9548 /*
9549  * tcp_ss_rexmit() is called to do slow start retransmission after a timeout
9550  * or ICMP errors.
9551  *
9552  * To limit the number of duplicate segments, we limit the number of segment
9553  * to be sent in one time to tcp_snd_burst, the burst variable.
9554  */
9555 static void
9556 tcp_ss_rexmit(tcp_t *tcp)
9557 {
9558 	uint32_t	snxt;
9559 	uint32_t	smax;
9560 	int32_t		win;
9561 	int32_t		mss;
9562 	int32_t		off;
9563 	int32_t		burst = tcp->tcp_snd_burst;
9564 	mblk_t		*snxt_mp;
9565 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9566 
9567 	/*
9568 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
9569 	 * all unack'ed segments.
9570 	 */
9571 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
9572 		smax = tcp->tcp_rexmit_max;
9573 		snxt = tcp->tcp_rexmit_nxt;
9574 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
9575 			snxt = tcp->tcp_suna;
9576 		}
9577 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
9578 		win -= snxt - tcp->tcp_suna;
9579 		mss = tcp->tcp_mss;
9580 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
9581 
9582 		while (SEQ_LT(snxt, smax) && (win > 0) &&
9583 		    (burst > 0) && (snxt_mp != NULL)) {
9584 			mblk_t	*xmit_mp;
9585 			mblk_t	*old_snxt_mp = snxt_mp;
9586 			uint32_t cnt = mss;
9587 
9588 			if (win < cnt) {
9589 				cnt = win;
9590 			}
9591 			if (SEQ_GT(snxt + cnt, smax)) {
9592 				cnt = smax - snxt;
9593 			}
9594 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
9595 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
9596 			if (xmit_mp == NULL)
9597 				return;
9598 
9599 			tcp_send_data(tcp, xmit_mp);
9600 
9601 			snxt += cnt;
9602 			win -= cnt;
9603 			/*
9604 			 * Update the send timestamp to avoid false
9605 			 * retransmission.
9606 			 */
9607 			old_snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9608 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9609 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
9610 
9611 			tcp->tcp_rexmit_nxt = snxt;
9612 			burst--;
9613 		}
9614 		/*
9615 		 * If we have transmitted all we have at the time
9616 		 * we started the retranmission, we can leave
9617 		 * the rest of the job to tcp_wput_data().  But we
9618 		 * need to check the send window first.  If the
9619 		 * win is not 0, go on with tcp_wput_data().
9620 		 */
9621 		if (SEQ_LT(snxt, smax) || win == 0) {
9622 			return;
9623 		}
9624 	}
9625 	/* Only call tcp_wput_data() if there is data to be sent. */
9626 	if (tcp->tcp_unsent) {
9627 		tcp_wput_data(tcp, NULL, B_FALSE);
9628 	}
9629 }
9630 
9631 /*
9632  * Process all TCP option in SYN segment.  Note that this function should
9633  * be called after tcp_set_destination() is called so that the necessary info
9634  * from IRE is already set in the tcp structure.
9635  *
9636  * This function sets up the correct tcp_mss value according to the
9637  * MSS option value and our header size.  It also sets up the window scale
9638  * and timestamp values, and initialize SACK info blocks.  But it does not
9639  * change receive window size after setting the tcp_mss value.  The caller
9640  * should do the appropriate change.
9641  */
9642 void
9643 tcp_process_options(tcp_t *tcp, tcpha_t *tcpha)
9644 {
9645 	int options;
9646 	tcp_opt_t tcpopt;
9647 	uint32_t mss_max;
9648 	char *tmp_tcph;
9649 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9650 	conn_t		*connp = tcp->tcp_connp;
9651 
9652 	tcpopt.tcp = NULL;
9653 	options = tcp_parse_options(tcpha, &tcpopt);
9654 
9655 	/*
9656 	 * Process MSS option.  Note that MSS option value does not account
9657 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
9658 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
9659 	 * IPv6.
9660 	 */
9661 	if (!(options & TCP_OPT_MSS_PRESENT)) {
9662 		if (connp->conn_ipversion == IPV4_VERSION)
9663 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
9664 		else
9665 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
9666 	} else {
9667 		if (connp->conn_ipversion == IPV4_VERSION)
9668 			mss_max = tcps->tcps_mss_max_ipv4;
9669 		else
9670 			mss_max = tcps->tcps_mss_max_ipv6;
9671 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
9672 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
9673 		else if (tcpopt.tcp_opt_mss > mss_max)
9674 			tcpopt.tcp_opt_mss = mss_max;
9675 	}
9676 
9677 	/* Process Window Scale option. */
9678 	if (options & TCP_OPT_WSCALE_PRESENT) {
9679 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
9680 		tcp->tcp_snd_ws_ok = B_TRUE;
9681 	} else {
9682 		tcp->tcp_snd_ws = B_FALSE;
9683 		tcp->tcp_snd_ws_ok = B_FALSE;
9684 		tcp->tcp_rcv_ws = B_FALSE;
9685 	}
9686 
9687 	/* Process Timestamp option. */
9688 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
9689 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
9690 		tmp_tcph = (char *)tcp->tcp_tcpha;
9691 
9692 		tcp->tcp_snd_ts_ok = B_TRUE;
9693 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
9694 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
9695 		ASSERT(OK_32PTR(tmp_tcph));
9696 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
9697 
9698 		/* Fill in our template header with basic timestamp option. */
9699 		tmp_tcph += connp->conn_ht_ulp_len;
9700 		tmp_tcph[0] = TCPOPT_NOP;
9701 		tmp_tcph[1] = TCPOPT_NOP;
9702 		tmp_tcph[2] = TCPOPT_TSTAMP;
9703 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
9704 		connp->conn_ht_iphc_len += TCPOPT_REAL_TS_LEN;
9705 		connp->conn_ht_ulp_len += TCPOPT_REAL_TS_LEN;
9706 		tcp->tcp_tcpha->tha_offset_and_reserved += (3 << 4);
9707 	} else {
9708 		tcp->tcp_snd_ts_ok = B_FALSE;
9709 	}
9710 
9711 	/*
9712 	 * Process SACK options.  If SACK is enabled for this connection,
9713 	 * then allocate the SACK info structure.  Note the following ways
9714 	 * when tcp_snd_sack_ok is set to true.
9715 	 *
9716 	 * For active connection: in tcp_set_destination() called in
9717 	 * tcp_connect().
9718 	 *
9719 	 * For passive connection: in tcp_set_destination() called in
9720 	 * tcp_input_listener().
9721 	 *
9722 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
9723 	 * That check makes sure that if we did not send a SACK OK option,
9724 	 * we will not enable SACK for this connection even though the other
9725 	 * side sends us SACK OK option.  For active connection, the SACK
9726 	 * info structure has already been allocated.  So we need to free
9727 	 * it if SACK is disabled.
9728 	 */
9729 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
9730 	    (tcp->tcp_snd_sack_ok ||
9731 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
9732 		/* This should be true only in the passive case. */
9733 		if (tcp->tcp_sack_info == NULL) {
9734 			ASSERT(TCP_IS_DETACHED(tcp));
9735 			tcp->tcp_sack_info =
9736 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
9737 		}
9738 		if (tcp->tcp_sack_info == NULL) {
9739 			tcp->tcp_snd_sack_ok = B_FALSE;
9740 		} else {
9741 			tcp->tcp_snd_sack_ok = B_TRUE;
9742 			if (tcp->tcp_snd_ts_ok) {
9743 				tcp->tcp_max_sack_blk = 3;
9744 			} else {
9745 				tcp->tcp_max_sack_blk = 4;
9746 			}
9747 		}
9748 	} else {
9749 		/*
9750 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
9751 		 * no SACK info will be used for this
9752 		 * connection.  This assumes that SACK usage
9753 		 * permission is negotiated.  This may need
9754 		 * to be changed once this is clarified.
9755 		 */
9756 		if (tcp->tcp_sack_info != NULL) {
9757 			ASSERT(tcp->tcp_notsack_list == NULL);
9758 			kmem_cache_free(tcp_sack_info_cache,
9759 			    tcp->tcp_sack_info);
9760 			tcp->tcp_sack_info = NULL;
9761 		}
9762 		tcp->tcp_snd_sack_ok = B_FALSE;
9763 	}
9764 
9765 	/*
9766 	 * Now we know the exact TCP/IP header length, subtract
9767 	 * that from tcp_mss to get our side's MSS.
9768 	 */
9769 	tcp->tcp_mss -= connp->conn_ht_iphc_len;
9770 
9771 	/*
9772 	 * Here we assume that the other side's header size will be equal to
9773 	 * our header size.  We calculate the real MSS accordingly.  Need to
9774 	 * take into additional stuffs IPsec puts in.
9775 	 *
9776 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
9777 	 */
9778 	tcpopt.tcp_opt_mss -= connp->conn_ht_iphc_len +
9779 	    tcp->tcp_ipsec_overhead -
9780 	    ((connp->conn_ipversion == IPV4_VERSION ?
9781 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
9782 
9783 	/*
9784 	 * Set MSS to the smaller one of both ends of the connection.
9785 	 * We should not have called tcp_mss_set() before, but our
9786 	 * side of the MSS should have been set to a proper value
9787 	 * by tcp_set_destination().  tcp_mss_set() will also set up the
9788 	 * STREAM head parameters properly.
9789 	 *
9790 	 * If we have a larger-than-16-bit window but the other side
9791 	 * didn't want to do window scale, tcp_rwnd_set() will take
9792 	 * care of that.
9793 	 */
9794 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
9795 
9796 	/*
9797 	 * Initialize tcp_cwnd value. After tcp_mss_set(), tcp_mss has been
9798 	 * updated properly.
9799 	 */
9800 	SET_TCP_INIT_CWND(tcp, tcp->tcp_mss, tcps->tcps_slow_start_initial);
9801 }
9802 
9803 /*
9804  * Sends the T_CONN_IND to the listener. The caller calls this
9805  * functions via squeue to get inside the listener's perimeter
9806  * once the 3 way hand shake is done a T_CONN_IND needs to be
9807  * sent. As an optimization, the caller can call this directly
9808  * if listener's perimeter is same as eager's.
9809  */
9810 /* ARGSUSED */
9811 void
9812 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
9813 {
9814 	conn_t			*lconnp = (conn_t *)arg;
9815 	tcp_t			*listener = lconnp->conn_tcp;
9816 	tcp_t			*tcp;
9817 	struct T_conn_ind	*conn_ind;
9818 	ipaddr_t 		*addr_cache;
9819 	boolean_t		need_send_conn_ind = B_FALSE;
9820 	tcp_stack_t		*tcps = listener->tcp_tcps;
9821 
9822 	/* retrieve the eager */
9823 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
9824 	ASSERT(conn_ind->OPT_offset != 0 &&
9825 	    conn_ind->OPT_length == sizeof (intptr_t));
9826 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
9827 	    conn_ind->OPT_length);
9828 
9829 	/*
9830 	 * TLI/XTI applications will get confused by
9831 	 * sending eager as an option since it violates
9832 	 * the option semantics. So remove the eager as
9833 	 * option since TLI/XTI app doesn't need it anyway.
9834 	 */
9835 	if (!TCP_IS_SOCKET(listener)) {
9836 		conn_ind->OPT_length = 0;
9837 		conn_ind->OPT_offset = 0;
9838 	}
9839 	if (listener->tcp_state != TCPS_LISTEN) {
9840 		/*
9841 		 * If listener has closed, it would have caused a
9842 		 * a cleanup/blowoff to happen for the eager. We
9843 		 * just need to return.
9844 		 */
9845 		freemsg(mp);
9846 		return;
9847 	}
9848 
9849 
9850 	/*
9851 	 * if the conn_req_q is full defer passing up the
9852 	 * T_CONN_IND until space is availabe after t_accept()
9853 	 * processing
9854 	 */
9855 	mutex_enter(&listener->tcp_eager_lock);
9856 
9857 	/*
9858 	 * Take the eager out, if it is in the list of droppable eagers
9859 	 * as we are here because the 3W handshake is over.
9860 	 */
9861 	MAKE_UNDROPPABLE(tcp);
9862 
9863 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
9864 		tcp_t *tail;
9865 
9866 		/*
9867 		 * The eager already has an extra ref put in tcp_input_data
9868 		 * so that it stays till accept comes back even though it
9869 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
9870 		 */
9871 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
9872 		listener->tcp_conn_req_cnt_q0--;
9873 		listener->tcp_conn_req_cnt_q++;
9874 
9875 		/* Move from SYN_RCVD to ESTABLISHED list  */
9876 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9877 		    tcp->tcp_eager_prev_q0;
9878 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9879 		    tcp->tcp_eager_next_q0;
9880 		tcp->tcp_eager_prev_q0 = NULL;
9881 		tcp->tcp_eager_next_q0 = NULL;
9882 
9883 		/*
9884 		 * Insert at end of the queue because sockfs
9885 		 * sends down T_CONN_RES in chronological
9886 		 * order. Leaving the older conn indications
9887 		 * at front of the queue helps reducing search
9888 		 * time.
9889 		 */
9890 		tail = listener->tcp_eager_last_q;
9891 		if (tail != NULL)
9892 			tail->tcp_eager_next_q = tcp;
9893 		else
9894 			listener->tcp_eager_next_q = tcp;
9895 		listener->tcp_eager_last_q = tcp;
9896 		tcp->tcp_eager_next_q = NULL;
9897 		/*
9898 		 * Delay sending up the T_conn_ind until we are
9899 		 * done with the eager. Once we have have sent up
9900 		 * the T_conn_ind, the accept can potentially complete
9901 		 * any time and release the refhold we have on the eager.
9902 		 */
9903 		need_send_conn_ind = B_TRUE;
9904 	} else {
9905 		/*
9906 		 * Defer connection on q0 and set deferred
9907 		 * connection bit true
9908 		 */
9909 		tcp->tcp_conn_def_q0 = B_TRUE;
9910 
9911 		/* take tcp out of q0 ... */
9912 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9913 		    tcp->tcp_eager_next_q0;
9914 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9915 		    tcp->tcp_eager_prev_q0;
9916 
9917 		/* ... and place it at the end of q0 */
9918 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
9919 		tcp->tcp_eager_next_q0 = listener;
9920 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
9921 		listener->tcp_eager_prev_q0 = tcp;
9922 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
9923 	}
9924 
9925 	/* we have timed out before */
9926 	if (tcp->tcp_syn_rcvd_timeout != 0) {
9927 		tcp->tcp_syn_rcvd_timeout = 0;
9928 		listener->tcp_syn_rcvd_timeout--;
9929 		if (listener->tcp_syn_defense &&
9930 		    listener->tcp_syn_rcvd_timeout <=
9931 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
9932 		    10*MINUTES < TICK_TO_MSEC(ddi_get_lbolt64() -
9933 		    listener->tcp_last_rcv_lbolt)) {
9934 			/*
9935 			 * Turn off the defense mode if we
9936 			 * believe the SYN attack is over.
9937 			 */
9938 			listener->tcp_syn_defense = B_FALSE;
9939 			if (listener->tcp_ip_addr_cache) {
9940 				kmem_free((void *)listener->tcp_ip_addr_cache,
9941 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
9942 				listener->tcp_ip_addr_cache = NULL;
9943 			}
9944 		}
9945 	}
9946 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
9947 	if (addr_cache != NULL) {
9948 		/*
9949 		 * We have finished a 3-way handshake with this
9950 		 * remote host. This proves the IP addr is good.
9951 		 * Cache it!
9952 		 */
9953 		addr_cache[IP_ADDR_CACHE_HASH(tcp->tcp_connp->conn_faddr_v4)] =
9954 		    tcp->tcp_connp->conn_faddr_v4;
9955 	}
9956 	mutex_exit(&listener->tcp_eager_lock);
9957 	if (need_send_conn_ind)
9958 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
9959 }
9960 
9961 /*
9962  * Send the newconn notification to ulp. The eager is blown off if the
9963  * notification fails.
9964  */
9965 static void
9966 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
9967 {
9968 	if (IPCL_IS_NONSTR(lconnp)) {
9969 		cred_t	*cr;
9970 		pid_t	cpid = NOPID;
9971 
9972 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
9973 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
9974 		    lconnp->conn_tcp);
9975 
9976 		cr = msg_getcred(mp, &cpid);
9977 
9978 		/* Keep the message around in case of a fallback to TPI */
9979 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
9980 		/*
9981 		 * Notify the ULP about the newconn. It is guaranteed that no
9982 		 * tcp_accept() call will be made for the eager if the
9983 		 * notification fails, so it's safe to blow it off in that
9984 		 * case.
9985 		 *
9986 		 * The upper handle will be assigned when tcp_accept() is
9987 		 * called.
9988 		 */
9989 		if ((*lconnp->conn_upcalls->su_newconn)
9990 		    (lconnp->conn_upper_handle,
9991 		    (sock_lower_handle_t)econnp,
9992 		    &sock_tcp_downcalls, cr, cpid,
9993 		    &econnp->conn_upcalls) == NULL) {
9994 			/* Failed to allocate a socket */
9995 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
9996 			    tcpEstabResets);
9997 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
9998 			    econnp->conn_tcp->tcp_conn_req_seqnum);
9999 		}
10000 	} else {
10001 		putnext(lconnp->conn_rq, mp);
10002 	}
10003 }
10004 
10005 /*
10006  * Handle a packet that has been reclassified by TCP.
10007  * This function drops the ref on connp that the caller had.
10008  */
10009 static void
10010 tcp_reinput(conn_t *connp, mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst)
10011 {
10012 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
10013 
10014 	if (connp->conn_incoming_ifindex != 0 &&
10015 	    connp->conn_incoming_ifindex != ira->ira_ruifindex) {
10016 		freemsg(mp);
10017 		CONN_DEC_REF(connp);
10018 		return;
10019 	}
10020 
10021 	if (CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss) ||
10022 	    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
10023 		ip6_t *ip6h;
10024 		ipha_t *ipha;
10025 
10026 		if (ira->ira_flags & IRAF_IS_IPV4) {
10027 			ipha = (ipha_t *)mp->b_rptr;
10028 			ip6h = NULL;
10029 		} else {
10030 			ipha = NULL;
10031 			ip6h = (ip6_t *)mp->b_rptr;
10032 		}
10033 		mp = ipsec_check_inbound_policy(mp, connp, ipha, ip6h, ira);
10034 		if (mp == NULL) {
10035 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
10036 			/* Note that mp is NULL */
10037 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
10038 			CONN_DEC_REF(connp);
10039 			return;
10040 		}
10041 	}
10042 
10043 	if (IPCL_IS_TCP(connp)) {
10044 		/*
10045 		 * do not drain, certain use cases can blow
10046 		 * the stack
10047 		 */
10048 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10049 		    connp->conn_recv, connp, ira,
10050 		    SQ_NODRAIN, SQTAG_IP_TCP_INPUT);
10051 	} else {
10052 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
10053 		(connp->conn_recv)(connp, mp, NULL,
10054 		    ira);
10055 		CONN_DEC_REF(connp);
10056 	}
10057 
10058 }
10059 
10060 boolean_t tcp_outbound_squeue_switch = B_FALSE;
10061 
10062 /*
10063  * Handle M_DATA messages from IP. Its called directly from IP via
10064  * squeue for received IP packets.
10065  *
10066  * The first argument is always the connp/tcp to which the mp belongs.
10067  * There are no exceptions to this rule. The caller has already put
10068  * a reference on this connp/tcp and once tcp_input_data() returns,
10069  * the squeue will do the refrele.
10070  *
10071  * The TH_SYN for the listener directly go to tcp_input_listener via
10072  * squeue. ICMP errors go directly to tcp_icmp_input().
10073  *
10074  * sqp: NULL = recursive, sqp != NULL means called from squeue
10075  */
10076 void
10077 tcp_input_data(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
10078 {
10079 	int32_t		bytes_acked;
10080 	int32_t		gap;
10081 	mblk_t		*mp1;
10082 	uint_t		flags;
10083 	uint32_t	new_swnd = 0;
10084 	uchar_t		*iphdr;
10085 	uchar_t		*rptr;
10086 	int32_t		rgap;
10087 	uint32_t	seg_ack;
10088 	int		seg_len;
10089 	uint_t		ip_hdr_len;
10090 	uint32_t	seg_seq;
10091 	tcpha_t		*tcpha;
10092 	int		urp;
10093 	tcp_opt_t	tcpopt;
10094 	ip_pkt_t	ipp;
10095 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
10096 	uint32_t	cwnd;
10097 	uint32_t	add;
10098 	int		npkt;
10099 	int		mss;
10100 	conn_t		*connp = (conn_t *)arg;
10101 	squeue_t	*sqp = (squeue_t *)arg2;
10102 	tcp_t		*tcp = connp->conn_tcp;
10103 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10104 
10105 	/*
10106 	 * RST from fused tcp loopback peer should trigger an unfuse.
10107 	 */
10108 	if (tcp->tcp_fused) {
10109 		TCP_STAT(tcps, tcp_fusion_aborted);
10110 		tcp_unfuse(tcp);
10111 	}
10112 
10113 	iphdr = mp->b_rptr;
10114 	rptr = mp->b_rptr;
10115 	ASSERT(OK_32PTR(rptr));
10116 
10117 	ip_hdr_len = ira->ira_ip_hdr_length;
10118 	if (connp->conn_recv_ancillary.crb_all != 0) {
10119 		/*
10120 		 * Record packet information in the ip_pkt_t
10121 		 */
10122 		ipp.ipp_fields = 0;
10123 		if (ira->ira_flags & IRAF_IS_IPV4) {
10124 			(void) ip_find_hdr_v4((ipha_t *)rptr, &ipp,
10125 			    B_FALSE);
10126 		} else {
10127 			uint8_t nexthdrp;
10128 
10129 			/*
10130 			 * IPv6 packets can only be received by applications
10131 			 * that are prepared to receive IPv6 addresses.
10132 			 * The IP fanout must ensure this.
10133 			 */
10134 			ASSERT(connp->conn_family == AF_INET6);
10135 
10136 			(void) ip_find_hdr_v6(mp, (ip6_t *)rptr, B_TRUE, &ipp,
10137 			    &nexthdrp);
10138 			ASSERT(nexthdrp == IPPROTO_TCP);
10139 
10140 			/* Could have caused a pullup? */
10141 			iphdr = mp->b_rptr;
10142 			rptr = mp->b_rptr;
10143 		}
10144 	}
10145 	ASSERT(DB_TYPE(mp) == M_DATA);
10146 	ASSERT(mp->b_next == NULL);
10147 
10148 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10149 	seg_seq = ntohl(tcpha->tha_seq);
10150 	seg_ack = ntohl(tcpha->tha_ack);
10151 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
10152 	seg_len = (int)(mp->b_wptr - rptr) -
10153 	    (ip_hdr_len + TCP_HDR_LENGTH(tcpha));
10154 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
10155 		do {
10156 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
10157 			    (uintptr_t)INT_MAX);
10158 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
10159 		} while ((mp1 = mp1->b_cont) != NULL &&
10160 		    mp1->b_datap->db_type == M_DATA);
10161 	}
10162 
10163 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
10164 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
10165 		    seg_len, tcpha, ira);
10166 		return;
10167 	}
10168 
10169 	if (sqp != NULL) {
10170 		/*
10171 		 * This is the correct place to update tcp_last_recv_time. Note
10172 		 * that it is also updated for tcp structure that belongs to
10173 		 * global and listener queues which do not really need updating.
10174 		 * But that should not cause any harm.  And it is updated for
10175 		 * all kinds of incoming segments, not only for data segments.
10176 		 */
10177 		tcp->tcp_last_recv_time = LBOLT_FASTPATH;
10178 	}
10179 
10180 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
10181 
10182 	BUMP_LOCAL(tcp->tcp_ibsegs);
10183 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10184 
10185 	if ((flags & TH_URG) && sqp != NULL) {
10186 		/*
10187 		 * TCP can't handle urgent pointers that arrive before
10188 		 * the connection has been accept()ed since it can't
10189 		 * buffer OOB data.  Discard segment if this happens.
10190 		 *
10191 		 * We can't just rely on a non-null tcp_listener to indicate
10192 		 * that the accept() has completed since unlinking of the
10193 		 * eager and completion of the accept are not atomic.
10194 		 * tcp_detached, when it is not set (B_FALSE) indicates
10195 		 * that the accept() has completed.
10196 		 *
10197 		 * Nor can it reassemble urgent pointers, so discard
10198 		 * if it's not the next segment expected.
10199 		 *
10200 		 * Otherwise, collapse chain into one mblk (discard if
10201 		 * that fails).  This makes sure the headers, retransmitted
10202 		 * data, and new data all are in the same mblk.
10203 		 */
10204 		ASSERT(mp != NULL);
10205 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
10206 			freemsg(mp);
10207 			return;
10208 		}
10209 		/* Update pointers into message */
10210 		iphdr = rptr = mp->b_rptr;
10211 		tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10212 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
10213 			/*
10214 			 * Since we can't handle any data with this urgent
10215 			 * pointer that is out of sequence, we expunge
10216 			 * the data.  This allows us to still register
10217 			 * the urgent mark and generate the M_PCSIG,
10218 			 * which we can do.
10219 			 */
10220 			mp->b_wptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10221 			seg_len = 0;
10222 		}
10223 	}
10224 
10225 	switch (tcp->tcp_state) {
10226 	case TCPS_SYN_SENT:
10227 		if (connp->conn_final_sqp == NULL &&
10228 		    tcp_outbound_squeue_switch && sqp != NULL) {
10229 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
10230 			connp->conn_final_sqp = sqp;
10231 			if (connp->conn_final_sqp != connp->conn_sqp) {
10232 				DTRACE_PROBE1(conn__final__sqp__switch,
10233 				    conn_t *, connp);
10234 				CONN_INC_REF(connp);
10235 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
10236 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10237 				    tcp_input_data, connp, ira, ip_squeue_flag,
10238 				    SQTAG_CONNECT_FINISH);
10239 				return;
10240 			}
10241 			DTRACE_PROBE1(conn__final__sqp__same, conn_t *, connp);
10242 		}
10243 		if (flags & TH_ACK) {
10244 			/*
10245 			 * Note that our stack cannot send data before a
10246 			 * connection is established, therefore the
10247 			 * following check is valid.  Otherwise, it has
10248 			 * to be changed.
10249 			 */
10250 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
10251 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10252 				freemsg(mp);
10253 				if (flags & TH_RST)
10254 					return;
10255 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
10256 				    tcp, seg_ack, 0, TH_RST);
10257 				return;
10258 			}
10259 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
10260 		}
10261 		if (flags & TH_RST) {
10262 			freemsg(mp);
10263 			if (flags & TH_ACK)
10264 				(void) tcp_clean_death(tcp,
10265 				    ECONNREFUSED, 13);
10266 			return;
10267 		}
10268 		if (!(flags & TH_SYN)) {
10269 			freemsg(mp);
10270 			return;
10271 		}
10272 
10273 		/* Process all TCP options. */
10274 		tcp_process_options(tcp, tcpha);
10275 		/*
10276 		 * The following changes our rwnd to be a multiple of the
10277 		 * MIN(peer MSS, our MSS) for performance reason.
10278 		 */
10279 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(connp->conn_rcvbuf,
10280 		    tcp->tcp_mss));
10281 
10282 		/* Is the other end ECN capable? */
10283 		if (tcp->tcp_ecn_ok) {
10284 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
10285 				tcp->tcp_ecn_ok = B_FALSE;
10286 			}
10287 		}
10288 		/*
10289 		 * Clear ECN flags because it may interfere with later
10290 		 * processing.
10291 		 */
10292 		flags &= ~(TH_ECE|TH_CWR);
10293 
10294 		tcp->tcp_irs = seg_seq;
10295 		tcp->tcp_rack = seg_seq;
10296 		tcp->tcp_rnxt = seg_seq + 1;
10297 		tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10298 		if (!TCP_IS_DETACHED(tcp)) {
10299 			/* Allocate room for SACK options if needed. */
10300 			connp->conn_wroff = connp->conn_ht_iphc_len;
10301 			if (tcp->tcp_snd_sack_ok)
10302 				connp->conn_wroff += TCPOPT_MAX_SACK_LEN;
10303 			if (!tcp->tcp_loopback)
10304 				connp->conn_wroff += tcps->tcps_wroff_xtra;
10305 
10306 			(void) proto_set_tx_wroff(connp->conn_rq, connp,
10307 			    connp->conn_wroff);
10308 		}
10309 		if (flags & TH_ACK) {
10310 			/*
10311 			 * If we can't get the confirmation upstream, pretend
10312 			 * we didn't even see this one.
10313 			 *
10314 			 * XXX: how can we pretend we didn't see it if we
10315 			 * have updated rnxt et. al.
10316 			 *
10317 			 * For loopback we defer sending up the T_CONN_CON
10318 			 * until after some checks below.
10319 			 */
10320 			mp1 = NULL;
10321 			/*
10322 			 * tcp_sendmsg() checks tcp_state without entering
10323 			 * the squeue so tcp_state should be updated before
10324 			 * sending up connection confirmation
10325 			 */
10326 			tcp->tcp_state = TCPS_ESTABLISHED;
10327 			if (!tcp_conn_con(tcp, iphdr, mp,
10328 			    tcp->tcp_loopback ? &mp1 : NULL, ira)) {
10329 				tcp->tcp_state = TCPS_SYN_SENT;
10330 				freemsg(mp);
10331 				return;
10332 			}
10333 			/* SYN was acked - making progress */
10334 			tcp->tcp_ip_forward_progress = B_TRUE;
10335 
10336 			/* One for the SYN */
10337 			tcp->tcp_suna = tcp->tcp_iss + 1;
10338 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
10339 
10340 			/*
10341 			 * If SYN was retransmitted, need to reset all
10342 			 * retransmission info.  This is because this
10343 			 * segment will be treated as a dup ACK.
10344 			 */
10345 			if (tcp->tcp_rexmit) {
10346 				tcp->tcp_rexmit = B_FALSE;
10347 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
10348 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
10349 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
10350 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
10351 				tcp->tcp_ms_we_have_waited = 0;
10352 
10353 				/*
10354 				 * Set tcp_cwnd back to 1 MSS, per
10355 				 * recommendation from
10356 				 * draft-floyd-incr-init-win-01.txt,
10357 				 * Increasing TCP's Initial Window.
10358 				 */
10359 				tcp->tcp_cwnd = tcp->tcp_mss;
10360 			}
10361 
10362 			tcp->tcp_swl1 = seg_seq;
10363 			tcp->tcp_swl2 = seg_ack;
10364 
10365 			new_swnd = ntohs(tcpha->tha_win);
10366 			tcp->tcp_swnd = new_swnd;
10367 			if (new_swnd > tcp->tcp_max_swnd)
10368 				tcp->tcp_max_swnd = new_swnd;
10369 
10370 			/*
10371 			 * Always send the three-way handshake ack immediately
10372 			 * in order to make the connection complete as soon as
10373 			 * possible on the accepting host.
10374 			 */
10375 			flags |= TH_ACK_NEEDED;
10376 
10377 			/*
10378 			 * Special case for loopback.  At this point we have
10379 			 * received SYN-ACK from the remote endpoint.  In
10380 			 * order to ensure that both endpoints reach the
10381 			 * fused state prior to any data exchange, the final
10382 			 * ACK needs to be sent before we indicate T_CONN_CON
10383 			 * to the module upstream.
10384 			 */
10385 			if (tcp->tcp_loopback) {
10386 				mblk_t *ack_mp;
10387 
10388 				ASSERT(!tcp->tcp_unfusable);
10389 				ASSERT(mp1 != NULL);
10390 				/*
10391 				 * For loopback, we always get a pure SYN-ACK
10392 				 * and only need to send back the final ACK
10393 				 * with no data (this is because the other
10394 				 * tcp is ours and we don't do T/TCP).  This
10395 				 * final ACK triggers the passive side to
10396 				 * perform fusion in ESTABLISHED state.
10397 				 */
10398 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
10399 					if (tcp->tcp_ack_tid != 0) {
10400 						(void) TCP_TIMER_CANCEL(tcp,
10401 						    tcp->tcp_ack_tid);
10402 						tcp->tcp_ack_tid = 0;
10403 					}
10404 					tcp_send_data(tcp, ack_mp);
10405 					BUMP_LOCAL(tcp->tcp_obsegs);
10406 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
10407 
10408 					if (!IPCL_IS_NONSTR(connp)) {
10409 						/* Send up T_CONN_CON */
10410 						if (ira->ira_cred != NULL) {
10411 							mblk_setcred(mp1,
10412 							    ira->ira_cred,
10413 							    ira->ira_cpid);
10414 						}
10415 						putnext(connp->conn_rq, mp1);
10416 					} else {
10417 						(*connp->conn_upcalls->
10418 						    su_connected)
10419 						    (connp->conn_upper_handle,
10420 						    tcp->tcp_connid,
10421 						    ira->ira_cred,
10422 						    ira->ira_cpid);
10423 						freemsg(mp1);
10424 					}
10425 
10426 					freemsg(mp);
10427 					return;
10428 				}
10429 				/*
10430 				 * Forget fusion; we need to handle more
10431 				 * complex cases below.  Send the deferred
10432 				 * T_CONN_CON message upstream and proceed
10433 				 * as usual.  Mark this tcp as not capable
10434 				 * of fusion.
10435 				 */
10436 				TCP_STAT(tcps, tcp_fusion_unfusable);
10437 				tcp->tcp_unfusable = B_TRUE;
10438 				if (!IPCL_IS_NONSTR(connp)) {
10439 					if (ira->ira_cred != NULL) {
10440 						mblk_setcred(mp1, ira->ira_cred,
10441 						    ira->ira_cpid);
10442 					}
10443 					putnext(connp->conn_rq, mp1);
10444 				} else {
10445 					(*connp->conn_upcalls->su_connected)
10446 					    (connp->conn_upper_handle,
10447 					    tcp->tcp_connid, ira->ira_cred,
10448 					    ira->ira_cpid);
10449 					freemsg(mp1);
10450 				}
10451 			}
10452 
10453 			/*
10454 			 * Check to see if there is data to be sent.  If
10455 			 * yes, set the transmit flag.  Then check to see
10456 			 * if received data processing needs to be done.
10457 			 * If not, go straight to xmit_check.  This short
10458 			 * cut is OK as we don't support T/TCP.
10459 			 */
10460 			if (tcp->tcp_unsent)
10461 				flags |= TH_XMIT_NEEDED;
10462 
10463 			if (seg_len == 0 && !(flags & TH_URG)) {
10464 				freemsg(mp);
10465 				goto xmit_check;
10466 			}
10467 
10468 			flags &= ~TH_SYN;
10469 			seg_seq++;
10470 			break;
10471 		}
10472 		tcp->tcp_state = TCPS_SYN_RCVD;
10473 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
10474 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
10475 		if (mp1 != NULL) {
10476 			tcp_send_data(tcp, mp1);
10477 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
10478 		}
10479 		freemsg(mp);
10480 		return;
10481 	case TCPS_SYN_RCVD:
10482 		if (flags & TH_ACK) {
10483 			/*
10484 			 * In this state, a SYN|ACK packet is either bogus
10485 			 * because the other side must be ACKing our SYN which
10486 			 * indicates it has seen the ACK for their SYN and
10487 			 * shouldn't retransmit it or we're crossing SYNs
10488 			 * on active open.
10489 			 */
10490 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
10491 				freemsg(mp);
10492 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
10493 				    tcp, seg_ack, 0, TH_RST);
10494 				return;
10495 			}
10496 			/*
10497 			 * NOTE: RFC 793 pg. 72 says this should be
10498 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
10499 			 * but that would mean we have an ack that ignored
10500 			 * our SYN.
10501 			 */
10502 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
10503 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10504 				freemsg(mp);
10505 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
10506 				    tcp, seg_ack, 0, TH_RST);
10507 				return;
10508 			}
10509 			/*
10510 			 * No sane TCP stack will send such a small window
10511 			 * without receiving any data.  Just drop this invalid
10512 			 * ACK.  We also shorten the abort timeout in case
10513 			 * this is an attack.
10514 			 */
10515 			if ((ntohs(tcpha->tha_win) << tcp->tcp_snd_ws) <
10516 			    (tcp->tcp_mss >> tcp_init_wnd_shft)) {
10517 				freemsg(mp);
10518 				TCP_STAT(tcps, tcp_zwin_ack_syn);
10519 				tcp->tcp_second_ctimer_threshold =
10520 				    tcp_early_abort * SECONDS;
10521 				return;
10522 			}
10523 		}
10524 		break;
10525 	case TCPS_LISTEN:
10526 		/*
10527 		 * Only a TLI listener can come through this path when a
10528 		 * acceptor is going back to be a listener and a packet
10529 		 * for the acceptor hits the classifier. For a socket
10530 		 * listener, this can never happen because a listener
10531 		 * can never accept connection on itself and hence a
10532 		 * socket acceptor can not go back to being a listener.
10533 		 */
10534 		ASSERT(!TCP_IS_SOCKET(tcp));
10535 		/*FALLTHRU*/
10536 	case TCPS_CLOSED:
10537 	case TCPS_BOUND: {
10538 		conn_t	*new_connp;
10539 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
10540 
10541 		/*
10542 		 * Don't accept any input on a closed tcp as this TCP logically
10543 		 * does not exist on the system. Don't proceed further with
10544 		 * this TCP. For instance, this packet could trigger another
10545 		 * close of this tcp which would be disastrous for tcp_refcnt.
10546 		 * tcp_close_detached / tcp_clean_death / tcp_closei_local must
10547 		 * be called at most once on a TCP. In this case we need to
10548 		 * refeed the packet into the classifier and figure out where
10549 		 * the packet should go.
10550 		 */
10551 		new_connp = ipcl_classify(mp, ira, ipst);
10552 		if (new_connp != NULL) {
10553 			/* Drops ref on new_connp */
10554 			tcp_reinput(new_connp, mp, ira, ipst);
10555 			return;
10556 		}
10557 		/* We failed to classify. For now just drop the packet */
10558 		freemsg(mp);
10559 		return;
10560 	}
10561 	case TCPS_IDLE:
10562 		/*
10563 		 * Handle the case where the tcp_clean_death() has happened
10564 		 * on a connection (application hasn't closed yet) but a packet
10565 		 * was already queued on squeue before tcp_clean_death()
10566 		 * was processed. Calling tcp_clean_death() twice on same
10567 		 * connection can result in weird behaviour.
10568 		 */
10569 		freemsg(mp);
10570 		return;
10571 	default:
10572 		break;
10573 	}
10574 
10575 	/*
10576 	 * Already on the correct queue/perimeter.
10577 	 * If this is a detached connection and not an eager
10578 	 * connection hanging off a listener then new data
10579 	 * (past the FIN) will cause a reset.
10580 	 * We do a special check here where it
10581 	 * is out of the main line, rather than check
10582 	 * if we are detached every time we see new
10583 	 * data down below.
10584 	 */
10585 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
10586 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
10587 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
10588 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10589 
10590 		freemsg(mp);
10591 		/*
10592 		 * This could be an SSL closure alert. We're detached so just
10593 		 * acknowledge it this last time.
10594 		 */
10595 		if (tcp->tcp_kssl_ctx != NULL) {
10596 			kssl_release_ctx(tcp->tcp_kssl_ctx);
10597 			tcp->tcp_kssl_ctx = NULL;
10598 
10599 			tcp->tcp_rnxt += seg_len;
10600 			tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10601 			flags |= TH_ACK_NEEDED;
10602 			goto ack_check;
10603 		}
10604 
10605 		tcp_xmit_ctl("new data when detached", tcp,
10606 		    tcp->tcp_snxt, 0, TH_RST);
10607 		(void) tcp_clean_death(tcp, EPROTO, 12);
10608 		return;
10609 	}
10610 
10611 	mp->b_rptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10612 	urp = ntohs(tcpha->tha_urp) - TCP_OLD_URP_INTERPRETATION;
10613 	new_swnd = ntohs(tcpha->tha_win) <<
10614 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
10615 
10616 	if (tcp->tcp_snd_ts_ok) {
10617 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
10618 			/*
10619 			 * This segment is not acceptable.
10620 			 * Drop it and send back an ACK.
10621 			 */
10622 			freemsg(mp);
10623 			flags |= TH_ACK_NEEDED;
10624 			goto ack_check;
10625 		}
10626 	} else if (tcp->tcp_snd_sack_ok) {
10627 		ASSERT(tcp->tcp_sack_info != NULL);
10628 		tcpopt.tcp = tcp;
10629 		/*
10630 		 * SACK info in already updated in tcp_parse_options.  Ignore
10631 		 * all other TCP options...
10632 		 */
10633 		(void) tcp_parse_options(tcpha, &tcpopt);
10634 	}
10635 try_again:;
10636 	mss = tcp->tcp_mss;
10637 	gap = seg_seq - tcp->tcp_rnxt;
10638 	rgap = tcp->tcp_rwnd - (gap + seg_len);
10639 	/*
10640 	 * gap is the amount of sequence space between what we expect to see
10641 	 * and what we got for seg_seq.  A positive value for gap means
10642 	 * something got lost.  A negative value means we got some old stuff.
10643 	 */
10644 	if (gap < 0) {
10645 		/* Old stuff present.  Is the SYN in there? */
10646 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
10647 		    (seg_len != 0)) {
10648 			flags &= ~TH_SYN;
10649 			seg_seq++;
10650 			urp--;
10651 			/* Recompute the gaps after noting the SYN. */
10652 			goto try_again;
10653 		}
10654 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
10655 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
10656 		    (seg_len > -gap ? -gap : seg_len));
10657 		/* Remove the old stuff from seg_len. */
10658 		seg_len += gap;
10659 		/*
10660 		 * Anything left?
10661 		 * Make sure to check for unack'd FIN when rest of data
10662 		 * has been previously ack'd.
10663 		 */
10664 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
10665 			/*
10666 			 * Resets are only valid if they lie within our offered
10667 			 * window.  If the RST bit is set, we just ignore this
10668 			 * segment.
10669 			 */
10670 			if (flags & TH_RST) {
10671 				freemsg(mp);
10672 				return;
10673 			}
10674 
10675 			/*
10676 			 * The arriving of dup data packets indicate that we
10677 			 * may have postponed an ack for too long, or the other
10678 			 * side's RTT estimate is out of shape. Start acking
10679 			 * more often.
10680 			 */
10681 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
10682 			    tcp->tcp_rack_cnt >= 1 &&
10683 			    tcp->tcp_rack_abs_max > 2) {
10684 				tcp->tcp_rack_abs_max--;
10685 			}
10686 			tcp->tcp_rack_cur_max = 1;
10687 
10688 			/*
10689 			 * This segment is "unacceptable".  None of its
10690 			 * sequence space lies within our advertized window.
10691 			 *
10692 			 * Adjust seg_len to the original value for tracing.
10693 			 */
10694 			seg_len -= gap;
10695 			if (connp->conn_debug) {
10696 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
10697 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
10698 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
10699 				    "seg_len %d, rnxt %u, snxt %u, %s",
10700 				    gap, rgap, flags, seg_seq, seg_ack,
10701 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
10702 				    tcp_display(tcp, NULL,
10703 				    DISP_ADDR_AND_PORT));
10704 			}
10705 
10706 			/*
10707 			 * Arrange to send an ACK in response to the
10708 			 * unacceptable segment per RFC 793 page 69. There
10709 			 * is only one small difference between ours and the
10710 			 * acceptability test in the RFC - we accept ACK-only
10711 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
10712 			 * will be generated.
10713 			 *
10714 			 * Note that we have to ACK an ACK-only packet at least
10715 			 * for stacks that send 0-length keep-alives with
10716 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
10717 			 * section 4.2.3.6. As long as we don't ever generate
10718 			 * an unacceptable packet in response to an incoming
10719 			 * packet that is unacceptable, it should not cause
10720 			 * "ACK wars".
10721 			 */
10722 			flags |=  TH_ACK_NEEDED;
10723 
10724 			/*
10725 			 * Continue processing this segment in order to use the
10726 			 * ACK information it contains, but skip all other
10727 			 * sequence-number processing.	Processing the ACK
10728 			 * information is necessary in order to
10729 			 * re-synchronize connections that may have lost
10730 			 * synchronization.
10731 			 *
10732 			 * We clear seg_len and flag fields related to
10733 			 * sequence number processing as they are not
10734 			 * to be trusted for an unacceptable segment.
10735 			 */
10736 			seg_len = 0;
10737 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
10738 			goto process_ack;
10739 		}
10740 
10741 		/* Fix seg_seq, and chew the gap off the front. */
10742 		seg_seq = tcp->tcp_rnxt;
10743 		urp += gap;
10744 		do {
10745 			mblk_t	*mp2;
10746 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10747 			    (uintptr_t)UINT_MAX);
10748 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
10749 			if (gap > 0) {
10750 				mp->b_rptr = mp->b_wptr - gap;
10751 				break;
10752 			}
10753 			mp2 = mp;
10754 			mp = mp->b_cont;
10755 			freeb(mp2);
10756 		} while (gap < 0);
10757 		/*
10758 		 * If the urgent data has already been acknowledged, we
10759 		 * should ignore TH_URG below
10760 		 */
10761 		if (urp < 0)
10762 			flags &= ~TH_URG;
10763 	}
10764 	/*
10765 	 * rgap is the amount of stuff received out of window.  A negative
10766 	 * value is the amount out of window.
10767 	 */
10768 	if (rgap < 0) {
10769 		mblk_t	*mp2;
10770 
10771 		if (tcp->tcp_rwnd == 0) {
10772 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
10773 		} else {
10774 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
10775 			UPDATE_MIB(&tcps->tcps_mib,
10776 			    tcpInDataPastWinBytes, -rgap);
10777 		}
10778 
10779 		/*
10780 		 * seg_len does not include the FIN, so if more than
10781 		 * just the FIN is out of window, we act like we don't
10782 		 * see it.  (If just the FIN is out of window, rgap
10783 		 * will be zero and we will go ahead and acknowledge
10784 		 * the FIN.)
10785 		 */
10786 		flags &= ~TH_FIN;
10787 
10788 		/* Fix seg_len and make sure there is something left. */
10789 		seg_len += rgap;
10790 		if (seg_len <= 0) {
10791 			/*
10792 			 * Resets are only valid if they lie within our offered
10793 			 * window.  If the RST bit is set, we just ignore this
10794 			 * segment.
10795 			 */
10796 			if (flags & TH_RST) {
10797 				freemsg(mp);
10798 				return;
10799 			}
10800 
10801 			/* Per RFC 793, we need to send back an ACK. */
10802 			flags |= TH_ACK_NEEDED;
10803 
10804 			/*
10805 			 * Send SIGURG as soon as possible i.e. even
10806 			 * if the TH_URG was delivered in a window probe
10807 			 * packet (which will be unacceptable).
10808 			 *
10809 			 * We generate a signal if none has been generated
10810 			 * for this connection or if this is a new urgent
10811 			 * byte. Also send a zero-length "unmarked" message
10812 			 * to inform SIOCATMARK that this is not the mark.
10813 			 *
10814 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
10815 			 * is sent up. This plus the check for old data
10816 			 * (gap >= 0) handles the wraparound of the sequence
10817 			 * number space without having to always track the
10818 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
10819 			 * this max in its rcv_up variable).
10820 			 *
10821 			 * This prevents duplicate SIGURGS due to a "late"
10822 			 * zero-window probe when the T_EXDATA_IND has already
10823 			 * been sent up.
10824 			 */
10825 			if ((flags & TH_URG) &&
10826 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
10827 			    tcp->tcp_urp_last))) {
10828 				if (IPCL_IS_NONSTR(connp)) {
10829 					if (!TCP_IS_DETACHED(tcp)) {
10830 						(*connp->conn_upcalls->
10831 						    su_signal_oob)
10832 						    (connp->conn_upper_handle,
10833 						    urp);
10834 					}
10835 				} else {
10836 					mp1 = allocb(0, BPRI_MED);
10837 					if (mp1 == NULL) {
10838 						freemsg(mp);
10839 						return;
10840 					}
10841 					if (!TCP_IS_DETACHED(tcp) &&
10842 					    !putnextctl1(connp->conn_rq,
10843 					    M_PCSIG, SIGURG)) {
10844 						/* Try again on the rexmit. */
10845 						freemsg(mp1);
10846 						freemsg(mp);
10847 						return;
10848 					}
10849 					/*
10850 					 * If the next byte would be the mark
10851 					 * then mark with MARKNEXT else mark
10852 					 * with NOTMARKNEXT.
10853 					 */
10854 					if (gap == 0 && urp == 0)
10855 						mp1->b_flag |= MSGMARKNEXT;
10856 					else
10857 						mp1->b_flag |= MSGNOTMARKNEXT;
10858 					freemsg(tcp->tcp_urp_mark_mp);
10859 					tcp->tcp_urp_mark_mp = mp1;
10860 					flags |= TH_SEND_URP_MARK;
10861 				}
10862 				tcp->tcp_urp_last_valid = B_TRUE;
10863 				tcp->tcp_urp_last = urp + seg_seq;
10864 			}
10865 			/*
10866 			 * If this is a zero window probe, continue to
10867 			 * process the ACK part.  But we need to set seg_len
10868 			 * to 0 to avoid data processing.  Otherwise just
10869 			 * drop the segment and send back an ACK.
10870 			 */
10871 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
10872 				flags &= ~(TH_SYN | TH_URG);
10873 				seg_len = 0;
10874 				goto process_ack;
10875 			} else {
10876 				freemsg(mp);
10877 				goto ack_check;
10878 			}
10879 		}
10880 		/* Pitch out of window stuff off the end. */
10881 		rgap = seg_len;
10882 		mp2 = mp;
10883 		do {
10884 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
10885 			    (uintptr_t)INT_MAX);
10886 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
10887 			if (rgap < 0) {
10888 				mp2->b_wptr += rgap;
10889 				if ((mp1 = mp2->b_cont) != NULL) {
10890 					mp2->b_cont = NULL;
10891 					freemsg(mp1);
10892 				}
10893 				break;
10894 			}
10895 		} while ((mp2 = mp2->b_cont) != NULL);
10896 	}
10897 ok:;
10898 	/*
10899 	 * TCP should check ECN info for segments inside the window only.
10900 	 * Therefore the check should be done here.
10901 	 */
10902 	if (tcp->tcp_ecn_ok) {
10903 		if (flags & TH_CWR) {
10904 			tcp->tcp_ecn_echo_on = B_FALSE;
10905 		}
10906 		/*
10907 		 * Note that both ECN_CE and CWR can be set in the
10908 		 * same segment.  In this case, we once again turn
10909 		 * on ECN_ECHO.
10910 		 */
10911 		if (connp->conn_ipversion == IPV4_VERSION) {
10912 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
10913 
10914 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
10915 				tcp->tcp_ecn_echo_on = B_TRUE;
10916 			}
10917 		} else {
10918 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
10919 
10920 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
10921 			    htonl(IPH_ECN_CE << 20)) {
10922 				tcp->tcp_ecn_echo_on = B_TRUE;
10923 			}
10924 		}
10925 	}
10926 
10927 	/*
10928 	 * Check whether we can update tcp_ts_recent.  This test is
10929 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
10930 	 * Extensions for High Performance: An Update", Internet Draft.
10931 	 */
10932 	if (tcp->tcp_snd_ts_ok &&
10933 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
10934 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
10935 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
10936 		tcp->tcp_last_rcv_lbolt = LBOLT_FASTPATH64;
10937 	}
10938 
10939 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
10940 		/*
10941 		 * FIN in an out of order segment.  We record this in
10942 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
10943 		 * Clear the FIN so that any check on FIN flag will fail.
10944 		 * Remember that FIN also counts in the sequence number
10945 		 * space.  So we need to ack out of order FIN only segments.
10946 		 */
10947 		if (flags & TH_FIN) {
10948 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
10949 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
10950 			flags &= ~TH_FIN;
10951 			flags |= TH_ACK_NEEDED;
10952 		}
10953 		if (seg_len > 0) {
10954 			/* Fill in the SACK blk list. */
10955 			if (tcp->tcp_snd_sack_ok) {
10956 				ASSERT(tcp->tcp_sack_info != NULL);
10957 				tcp_sack_insert(tcp->tcp_sack_list,
10958 				    seg_seq, seg_seq + seg_len,
10959 				    &(tcp->tcp_num_sack_blk));
10960 			}
10961 
10962 			/*
10963 			 * Attempt reassembly and see if we have something
10964 			 * ready to go.
10965 			 */
10966 			mp = tcp_reass(tcp, mp, seg_seq);
10967 			/* Always ack out of order packets */
10968 			flags |= TH_ACK_NEEDED | TH_PUSH;
10969 			if (mp) {
10970 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10971 				    (uintptr_t)INT_MAX);
10972 				seg_len = mp->b_cont ? msgdsize(mp) :
10973 				    (int)(mp->b_wptr - mp->b_rptr);
10974 				seg_seq = tcp->tcp_rnxt;
10975 				/*
10976 				 * A gap is filled and the seq num and len
10977 				 * of the gap match that of a previously
10978 				 * received FIN, put the FIN flag back in.
10979 				 */
10980 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
10981 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
10982 					flags |= TH_FIN;
10983 					tcp->tcp_valid_bits &=
10984 					    ~TCP_OFO_FIN_VALID;
10985 				}
10986 				if (tcp->tcp_reass_tid != 0) {
10987 					(void) TCP_TIMER_CANCEL(tcp,
10988 					    tcp->tcp_reass_tid);
10989 					/*
10990 					 * Restart the timer if there is still
10991 					 * data in the reassembly queue.
10992 					 */
10993 					if (tcp->tcp_reass_head != NULL) {
10994 						tcp->tcp_reass_tid = TCP_TIMER(
10995 						    tcp, tcp_reass_timer,
10996 						    MSEC_TO_TICK(
10997 						    tcps->tcps_reass_timeout));
10998 					} else {
10999 						tcp->tcp_reass_tid = 0;
11000 					}
11001 				}
11002 			} else {
11003 				/*
11004 				 * Keep going even with NULL mp.
11005 				 * There may be a useful ACK or something else
11006 				 * we don't want to miss.
11007 				 *
11008 				 * But TCP should not perform fast retransmit
11009 				 * because of the ack number.  TCP uses
11010 				 * seg_len == 0 to determine if it is a pure
11011 				 * ACK.  And this is not a pure ACK.
11012 				 */
11013 				seg_len = 0;
11014 				ofo_seg = B_TRUE;
11015 
11016 				if (tcps->tcps_reass_timeout != 0 &&
11017 				    tcp->tcp_reass_tid == 0) {
11018 					tcp->tcp_reass_tid = TCP_TIMER(tcp,
11019 					    tcp_reass_timer, MSEC_TO_TICK(
11020 					    tcps->tcps_reass_timeout));
11021 				}
11022 			}
11023 		}
11024 	} else if (seg_len > 0) {
11025 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
11026 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
11027 		/*
11028 		 * If an out of order FIN was received before, and the seq
11029 		 * num and len of the new segment match that of the FIN,
11030 		 * put the FIN flag back in.
11031 		 */
11032 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
11033 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
11034 			flags |= TH_FIN;
11035 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
11036 		}
11037 	}
11038 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
11039 	if (flags & TH_RST) {
11040 		freemsg(mp);
11041 		switch (tcp->tcp_state) {
11042 		case TCPS_SYN_RCVD:
11043 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
11044 			break;
11045 		case TCPS_ESTABLISHED:
11046 		case TCPS_FIN_WAIT_1:
11047 		case TCPS_FIN_WAIT_2:
11048 		case TCPS_CLOSE_WAIT:
11049 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
11050 			break;
11051 		case TCPS_CLOSING:
11052 		case TCPS_LAST_ACK:
11053 			(void) tcp_clean_death(tcp, 0, 16);
11054 			break;
11055 		default:
11056 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11057 			(void) tcp_clean_death(tcp, ENXIO, 17);
11058 			break;
11059 		}
11060 		return;
11061 	}
11062 	if (flags & TH_SYN) {
11063 		/*
11064 		 * See RFC 793, Page 71
11065 		 *
11066 		 * The seq number must be in the window as it should
11067 		 * be "fixed" above.  If it is outside window, it should
11068 		 * be already rejected.  Note that we allow seg_seq to be
11069 		 * rnxt + rwnd because we want to accept 0 window probe.
11070 		 */
11071 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
11072 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
11073 		freemsg(mp);
11074 		/*
11075 		 * If the ACK flag is not set, just use our snxt as the
11076 		 * seq number of the RST segment.
11077 		 */
11078 		if (!(flags & TH_ACK)) {
11079 			seg_ack = tcp->tcp_snxt;
11080 		}
11081 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
11082 		    TH_RST|TH_ACK);
11083 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11084 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
11085 		return;
11086 	}
11087 	/*
11088 	 * urp could be -1 when the urp field in the packet is 0
11089 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
11090 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
11091 	 */
11092 	if (flags & TH_URG && urp >= 0) {
11093 		if (!tcp->tcp_urp_last_valid ||
11094 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
11095 			/*
11096 			 * Non-STREAMS sockets handle the urgent data a litte
11097 			 * differently from STREAMS based sockets. There is no
11098 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
11099 			 * flags to keep SIOCATMARK happy. Instead a
11100 			 * su_signal_oob upcall is made to update the mark.
11101 			 * Neither is a T_EXDATA_IND mblk needed to be
11102 			 * prepended to the urgent data. The urgent data is
11103 			 * delivered using the su_recv upcall, where we set
11104 			 * the MSG_OOB flag to indicate that it is urg data.
11105 			 *
11106 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
11107 			 * are used by non-STREAMS sockets.
11108 			 */
11109 			if (IPCL_IS_NONSTR(connp)) {
11110 				if (!TCP_IS_DETACHED(tcp)) {
11111 					(*connp->conn_upcalls->su_signal_oob)
11112 					    (connp->conn_upper_handle, urp);
11113 				}
11114 			} else {
11115 				/*
11116 				 * If we haven't generated the signal yet for
11117 				 * this urgent pointer value, do it now.  Also,
11118 				 * send up a zero-length M_DATA indicating
11119 				 * whether or not this is the mark. The latter
11120 				 * is not needed when a T_EXDATA_IND is sent up.
11121 				 * However, if there are allocation failures
11122 				 * this code relies on the sender retransmitting
11123 				 * and the socket code for determining the mark
11124 				 * should not block waiting for the peer to
11125 				 * transmit. Thus, for simplicity we always
11126 				 * send up the mark indication.
11127 				 */
11128 				mp1 = allocb(0, BPRI_MED);
11129 				if (mp1 == NULL) {
11130 					freemsg(mp);
11131 					return;
11132 				}
11133 				if (!TCP_IS_DETACHED(tcp) &&
11134 				    !putnextctl1(connp->conn_rq, M_PCSIG,
11135 				    SIGURG)) {
11136 					/* Try again on the rexmit. */
11137 					freemsg(mp1);
11138 					freemsg(mp);
11139 					return;
11140 				}
11141 				/*
11142 				 * Mark with NOTMARKNEXT for now.
11143 				 * The code below will change this to MARKNEXT
11144 				 * if we are at the mark.
11145 				 *
11146 				 * If there are allocation failures (e.g. in
11147 				 * dupmsg below) the next time tcp_input_data
11148 				 * sees the urgent segment it will send up the
11149 				 * MSGMARKNEXT message.
11150 				 */
11151 				mp1->b_flag |= MSGNOTMARKNEXT;
11152 				freemsg(tcp->tcp_urp_mark_mp);
11153 				tcp->tcp_urp_mark_mp = mp1;
11154 				flags |= TH_SEND_URP_MARK;
11155 #ifdef DEBUG
11156 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11157 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
11158 				    "last %x, %s",
11159 				    seg_seq, urp, tcp->tcp_urp_last,
11160 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11161 #endif /* DEBUG */
11162 			}
11163 			tcp->tcp_urp_last_valid = B_TRUE;
11164 			tcp->tcp_urp_last = urp + seg_seq;
11165 		} else if (tcp->tcp_urp_mark_mp != NULL) {
11166 			/*
11167 			 * An allocation failure prevented the previous
11168 			 * tcp_input_data from sending up the allocated
11169 			 * MSG*MARKNEXT message - send it up this time
11170 			 * around.
11171 			 */
11172 			flags |= TH_SEND_URP_MARK;
11173 		}
11174 
11175 		/*
11176 		 * If the urgent byte is in this segment, make sure that it is
11177 		 * all by itself.  This makes it much easier to deal with the
11178 		 * possibility of an allocation failure on the T_exdata_ind.
11179 		 * Note that seg_len is the number of bytes in the segment, and
11180 		 * urp is the offset into the segment of the urgent byte.
11181 		 * urp < seg_len means that the urgent byte is in this segment.
11182 		 */
11183 		if (urp < seg_len) {
11184 			if (seg_len != 1) {
11185 				uint32_t  tmp_rnxt;
11186 				/*
11187 				 * Break it up and feed it back in.
11188 				 * Re-attach the IP header.
11189 				 */
11190 				mp->b_rptr = iphdr;
11191 				if (urp > 0) {
11192 					/*
11193 					 * There is stuff before the urgent
11194 					 * byte.
11195 					 */
11196 					mp1 = dupmsg(mp);
11197 					if (!mp1) {
11198 						/*
11199 						 * Trim from urgent byte on.
11200 						 * The rest will come back.
11201 						 */
11202 						(void) adjmsg(mp,
11203 						    urp - seg_len);
11204 						tcp_input_data(connp,
11205 						    mp, NULL, ira);
11206 						return;
11207 					}
11208 					(void) adjmsg(mp1, urp - seg_len);
11209 					/* Feed this piece back in. */
11210 					tmp_rnxt = tcp->tcp_rnxt;
11211 					tcp_input_data(connp, mp1, NULL, ira);
11212 					/*
11213 					 * If the data passed back in was not
11214 					 * processed (ie: bad ACK) sending
11215 					 * the remainder back in will cause a
11216 					 * loop. In this case, drop the
11217 					 * packet and let the sender try
11218 					 * sending a good packet.
11219 					 */
11220 					if (tmp_rnxt == tcp->tcp_rnxt) {
11221 						freemsg(mp);
11222 						return;
11223 					}
11224 				}
11225 				if (urp != seg_len - 1) {
11226 					uint32_t  tmp_rnxt;
11227 					/*
11228 					 * There is stuff after the urgent
11229 					 * byte.
11230 					 */
11231 					mp1 = dupmsg(mp);
11232 					if (!mp1) {
11233 						/*
11234 						 * Trim everything beyond the
11235 						 * urgent byte.  The rest will
11236 						 * come back.
11237 						 */
11238 						(void) adjmsg(mp,
11239 						    urp + 1 - seg_len);
11240 						tcp_input_data(connp,
11241 						    mp, NULL, ira);
11242 						return;
11243 					}
11244 					(void) adjmsg(mp1, urp + 1 - seg_len);
11245 					tmp_rnxt = tcp->tcp_rnxt;
11246 					tcp_input_data(connp, mp1, NULL, ira);
11247 					/*
11248 					 * If the data passed back in was not
11249 					 * processed (ie: bad ACK) sending
11250 					 * the remainder back in will cause a
11251 					 * loop. In this case, drop the
11252 					 * packet and let the sender try
11253 					 * sending a good packet.
11254 					 */
11255 					if (tmp_rnxt == tcp->tcp_rnxt) {
11256 						freemsg(mp);
11257 						return;
11258 					}
11259 				}
11260 				tcp_input_data(connp, mp, NULL, ira);
11261 				return;
11262 			}
11263 			/*
11264 			 * This segment contains only the urgent byte.  We
11265 			 * have to allocate the T_exdata_ind, if we can.
11266 			 */
11267 			if (IPCL_IS_NONSTR(connp)) {
11268 				int error;
11269 
11270 				(*connp->conn_upcalls->su_recv)
11271 				    (connp->conn_upper_handle, mp, seg_len,
11272 				    MSG_OOB, &error, NULL);
11273 				/*
11274 				 * We should never be in middle of a
11275 				 * fallback, the squeue guarantees that.
11276 				 */
11277 				ASSERT(error != EOPNOTSUPP);
11278 				mp = NULL;
11279 				goto update_ack;
11280 			} else if (!tcp->tcp_urp_mp) {
11281 				struct T_exdata_ind *tei;
11282 				mp1 = allocb(sizeof (struct T_exdata_ind),
11283 				    BPRI_MED);
11284 				if (!mp1) {
11285 					/*
11286 					 * Sigh... It'll be back.
11287 					 * Generate any MSG*MARK message now.
11288 					 */
11289 					freemsg(mp);
11290 					seg_len = 0;
11291 					if (flags & TH_SEND_URP_MARK) {
11292 
11293 
11294 						ASSERT(tcp->tcp_urp_mark_mp);
11295 						tcp->tcp_urp_mark_mp->b_flag &=
11296 						    ~MSGNOTMARKNEXT;
11297 						tcp->tcp_urp_mark_mp->b_flag |=
11298 						    MSGMARKNEXT;
11299 					}
11300 					goto ack_check;
11301 				}
11302 				mp1->b_datap->db_type = M_PROTO;
11303 				tei = (struct T_exdata_ind *)mp1->b_rptr;
11304 				tei->PRIM_type = T_EXDATA_IND;
11305 				tei->MORE_flag = 0;
11306 				mp1->b_wptr = (uchar_t *)&tei[1];
11307 				tcp->tcp_urp_mp = mp1;
11308 #ifdef DEBUG
11309 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11310 				    "tcp_rput: allocated exdata_ind %s",
11311 				    tcp_display(tcp, NULL,
11312 				    DISP_PORT_ONLY));
11313 #endif /* DEBUG */
11314 				/*
11315 				 * There is no need to send a separate MSG*MARK
11316 				 * message since the T_EXDATA_IND will be sent
11317 				 * now.
11318 				 */
11319 				flags &= ~TH_SEND_URP_MARK;
11320 				freemsg(tcp->tcp_urp_mark_mp);
11321 				tcp->tcp_urp_mark_mp = NULL;
11322 			}
11323 			/*
11324 			 * Now we are all set.  On the next putnext upstream,
11325 			 * tcp_urp_mp will be non-NULL and will get prepended
11326 			 * to what has to be this piece containing the urgent
11327 			 * byte.  If for any reason we abort this segment below,
11328 			 * if it comes back, we will have this ready, or it
11329 			 * will get blown off in close.
11330 			 */
11331 		} else if (urp == seg_len) {
11332 			/*
11333 			 * The urgent byte is the next byte after this sequence
11334 			 * number. If this endpoint is non-STREAMS, then there
11335 			 * is nothing to do here since the socket has already
11336 			 * been notified about the urg pointer by the
11337 			 * su_signal_oob call above.
11338 			 *
11339 			 * In case of STREAMS, some more work might be needed.
11340 			 * If there is data it is marked with MSGMARKNEXT and
11341 			 * and any tcp_urp_mark_mp is discarded since it is not
11342 			 * needed. Otherwise, if the code above just allocated
11343 			 * a zero-length tcp_urp_mark_mp message, that message
11344 			 * is tagged with MSGMARKNEXT. Sending up these
11345 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
11346 			 * even though the T_EXDATA_IND will not be sent up
11347 			 * until the urgent byte arrives.
11348 			 */
11349 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
11350 				if (seg_len != 0) {
11351 					flags |= TH_MARKNEXT_NEEDED;
11352 					freemsg(tcp->tcp_urp_mark_mp);
11353 					tcp->tcp_urp_mark_mp = NULL;
11354 					flags &= ~TH_SEND_URP_MARK;
11355 				} else if (tcp->tcp_urp_mark_mp != NULL) {
11356 					flags |= TH_SEND_URP_MARK;
11357 					tcp->tcp_urp_mark_mp->b_flag &=
11358 					    ~MSGNOTMARKNEXT;
11359 					tcp->tcp_urp_mark_mp->b_flag |=
11360 					    MSGMARKNEXT;
11361 				}
11362 			}
11363 #ifdef DEBUG
11364 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11365 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
11366 			    seg_len, flags,
11367 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11368 #endif /* DEBUG */
11369 		}
11370 #ifdef DEBUG
11371 		else {
11372 			/* Data left until we hit mark */
11373 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11374 			    "tcp_rput: URP %d bytes left, %s",
11375 			    urp - seg_len, tcp_display(tcp, NULL,
11376 			    DISP_PORT_ONLY));
11377 		}
11378 #endif /* DEBUG */
11379 	}
11380 
11381 process_ack:
11382 	if (!(flags & TH_ACK)) {
11383 		freemsg(mp);
11384 		goto xmit_check;
11385 	}
11386 	}
11387 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
11388 
11389 	if (bytes_acked > 0)
11390 		tcp->tcp_ip_forward_progress = B_TRUE;
11391 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
11392 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
11393 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
11394 			/* 3-way handshake complete - pass up the T_CONN_IND */
11395 			tcp_t	*listener = tcp->tcp_listener;
11396 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
11397 
11398 			tcp->tcp_tconnind_started = B_TRUE;
11399 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
11400 			/*
11401 			 * We are here means eager is fine but it can
11402 			 * get a TH_RST at any point between now and till
11403 			 * accept completes and disappear. We need to
11404 			 * ensure that reference to eager is valid after
11405 			 * we get out of eager's perimeter. So we do
11406 			 * an extra refhold.
11407 			 */
11408 			CONN_INC_REF(connp);
11409 
11410 			/*
11411 			 * The listener also exists because of the refhold
11412 			 * done in tcp_input_listener. Its possible that it
11413 			 * might have closed. We will check that once we
11414 			 * get inside listeners context.
11415 			 */
11416 			CONN_INC_REF(listener->tcp_connp);
11417 			if (listener->tcp_connp->conn_sqp ==
11418 			    connp->conn_sqp) {
11419 				/*
11420 				 * We optimize by not calling an SQUEUE_ENTER
11421 				 * on the listener since we know that the
11422 				 * listener and eager squeues are the same.
11423 				 * We are able to make this check safely only
11424 				 * because neither the eager nor the listener
11425 				 * can change its squeue. Only an active connect
11426 				 * can change its squeue
11427 				 */
11428 				tcp_send_conn_ind(listener->tcp_connp, mp,
11429 				    listener->tcp_connp->conn_sqp);
11430 				CONN_DEC_REF(listener->tcp_connp);
11431 			} else if (!tcp->tcp_loopback) {
11432 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11433 				    mp, tcp_send_conn_ind,
11434 				    listener->tcp_connp, NULL, SQ_FILL,
11435 				    SQTAG_TCP_CONN_IND);
11436 			} else {
11437 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11438 				    mp, tcp_send_conn_ind,
11439 				    listener->tcp_connp, NULL, SQ_PROCESS,
11440 				    SQTAG_TCP_CONN_IND);
11441 			}
11442 		}
11443 
11444 		/*
11445 		 * We are seeing the final ack in the three way
11446 		 * hand shake of a active open'ed connection
11447 		 * so we must send up a T_CONN_CON
11448 		 *
11449 		 * tcp_sendmsg() checks tcp_state without entering
11450 		 * the squeue so tcp_state should be updated before
11451 		 * sending up connection confirmation.
11452 		 */
11453 		tcp->tcp_state = TCPS_ESTABLISHED;
11454 		if (tcp->tcp_active_open) {
11455 			if (!tcp_conn_con(tcp, iphdr, mp, NULL, ira)) {
11456 				freemsg(mp);
11457 				tcp->tcp_state = TCPS_SYN_RCVD;
11458 				return;
11459 			}
11460 			/*
11461 			 * Don't fuse the loopback endpoints for
11462 			 * simultaneous active opens.
11463 			 */
11464 			if (tcp->tcp_loopback) {
11465 				TCP_STAT(tcps, tcp_fusion_unfusable);
11466 				tcp->tcp_unfusable = B_TRUE;
11467 			}
11468 		}
11469 
11470 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
11471 		bytes_acked--;
11472 		/* SYN was acked - making progress */
11473 		tcp->tcp_ip_forward_progress = B_TRUE;
11474 
11475 		/*
11476 		 * If SYN was retransmitted, need to reset all
11477 		 * retransmission info as this segment will be
11478 		 * treated as a dup ACK.
11479 		 */
11480 		if (tcp->tcp_rexmit) {
11481 			tcp->tcp_rexmit = B_FALSE;
11482 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11483 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
11484 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11485 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11486 			tcp->tcp_ms_we_have_waited = 0;
11487 			tcp->tcp_cwnd = mss;
11488 		}
11489 
11490 		/*
11491 		 * We set the send window to zero here.
11492 		 * This is needed if there is data to be
11493 		 * processed already on the queue.
11494 		 * Later (at swnd_update label), the
11495 		 * "new_swnd > tcp_swnd" condition is satisfied
11496 		 * the XMIT_NEEDED flag is set in the current
11497 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
11498 		 * called if there is already data on queue in
11499 		 * this state.
11500 		 */
11501 		tcp->tcp_swnd = 0;
11502 
11503 		if (new_swnd > tcp->tcp_max_swnd)
11504 			tcp->tcp_max_swnd = new_swnd;
11505 		tcp->tcp_swl1 = seg_seq;
11506 		tcp->tcp_swl2 = seg_ack;
11507 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
11508 
11509 		/* Fuse when both sides are in ESTABLISHED state */
11510 		if (tcp->tcp_loopback && do_tcp_fusion)
11511 			tcp_fuse(tcp, iphdr, tcpha);
11512 
11513 	}
11514 	/* This code follows 4.4BSD-Lite2 mostly. */
11515 	if (bytes_acked < 0)
11516 		goto est;
11517 
11518 	/*
11519 	 * If TCP is ECN capable and the congestion experience bit is
11520 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
11521 	 * done once per window (or more loosely, per RTT).
11522 	 */
11523 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
11524 		tcp->tcp_cwr = B_FALSE;
11525 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
11526 		if (!tcp->tcp_cwr) {
11527 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
11528 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
11529 			tcp->tcp_cwnd = npkt * mss;
11530 			/*
11531 			 * If the cwnd is 0, use the timer to clock out
11532 			 * new segments.  This is required by the ECN spec.
11533 			 */
11534 			if (npkt == 0) {
11535 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11536 				/*
11537 				 * This makes sure that when the ACK comes
11538 				 * back, we will increase tcp_cwnd by 1 MSS.
11539 				 */
11540 				tcp->tcp_cwnd_cnt = 0;
11541 			}
11542 			tcp->tcp_cwr = B_TRUE;
11543 			/*
11544 			 * This marks the end of the current window of in
11545 			 * flight data.  That is why we don't use
11546 			 * tcp_suna + tcp_swnd.  Only data in flight can
11547 			 * provide ECN info.
11548 			 */
11549 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11550 			tcp->tcp_ecn_cwr_sent = B_FALSE;
11551 		}
11552 	}
11553 
11554 	mp1 = tcp->tcp_xmit_head;
11555 	if (bytes_acked == 0) {
11556 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
11557 			int dupack_cnt;
11558 
11559 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
11560 			/*
11561 			 * Fast retransmit.  When we have seen exactly three
11562 			 * identical ACKs while we have unacked data
11563 			 * outstanding we take it as a hint that our peer
11564 			 * dropped something.
11565 			 *
11566 			 * If TCP is retransmitting, don't do fast retransmit.
11567 			 */
11568 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
11569 			    ! tcp->tcp_rexmit) {
11570 				/* Do Limited Transmit */
11571 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
11572 				    tcps->tcps_dupack_fast_retransmit) {
11573 					/*
11574 					 * RFC 3042
11575 					 *
11576 					 * What we need to do is temporarily
11577 					 * increase tcp_cwnd so that new
11578 					 * data can be sent if it is allowed
11579 					 * by the receive window (tcp_rwnd).
11580 					 * tcp_wput_data() will take care of
11581 					 * the rest.
11582 					 *
11583 					 * If the connection is SACK capable,
11584 					 * only do limited xmit when there
11585 					 * is SACK info.
11586 					 *
11587 					 * Note how tcp_cwnd is incremented.
11588 					 * The first dup ACK will increase
11589 					 * it by 1 MSS.  The second dup ACK
11590 					 * will increase it by 2 MSS.  This
11591 					 * means that only 1 new segment will
11592 					 * be sent for each dup ACK.
11593 					 */
11594 					if (tcp->tcp_unsent > 0 &&
11595 					    (!tcp->tcp_snd_sack_ok ||
11596 					    (tcp->tcp_snd_sack_ok &&
11597 					    tcp->tcp_notsack_list != NULL))) {
11598 						tcp->tcp_cwnd += mss <<
11599 						    (tcp->tcp_dupack_cnt - 1);
11600 						flags |= TH_LIMIT_XMIT;
11601 					}
11602 				} else if (dupack_cnt ==
11603 				    tcps->tcps_dupack_fast_retransmit) {
11604 
11605 				/*
11606 				 * If we have reduced tcp_ssthresh
11607 				 * because of ECN, do not reduce it again
11608 				 * unless it is already one window of data
11609 				 * away.  After one window of data, tcp_cwr
11610 				 * should then be cleared.  Note that
11611 				 * for non ECN capable connection, tcp_cwr
11612 				 * should always be false.
11613 				 *
11614 				 * Adjust cwnd since the duplicate
11615 				 * ack indicates that a packet was
11616 				 * dropped (due to congestion.)
11617 				 */
11618 				if (!tcp->tcp_cwr) {
11619 					npkt = ((tcp->tcp_snxt -
11620 					    tcp->tcp_suna) >> 1) / mss;
11621 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
11622 					    mss;
11623 					tcp->tcp_cwnd = (npkt +
11624 					    tcp->tcp_dupack_cnt) * mss;
11625 				}
11626 				if (tcp->tcp_ecn_ok) {
11627 					tcp->tcp_cwr = B_TRUE;
11628 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11629 					tcp->tcp_ecn_cwr_sent = B_FALSE;
11630 				}
11631 
11632 				/*
11633 				 * We do Hoe's algorithm.  Refer to her
11634 				 * paper "Improving the Start-up Behavior
11635 				 * of a Congestion Control Scheme for TCP,"
11636 				 * appeared in SIGCOMM'96.
11637 				 *
11638 				 * Save highest seq no we have sent so far.
11639 				 * Be careful about the invisible FIN byte.
11640 				 */
11641 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
11642 				    (tcp->tcp_unsent == 0)) {
11643 					tcp->tcp_rexmit_max = tcp->tcp_fss;
11644 				} else {
11645 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
11646 				}
11647 
11648 				/*
11649 				 * Do not allow bursty traffic during.
11650 				 * fast recovery.  Refer to Fall and Floyd's
11651 				 * paper "Simulation-based Comparisons of
11652 				 * Tahoe, Reno and SACK TCP" (in CCR?)
11653 				 * This is a best current practise.
11654 				 */
11655 				tcp->tcp_snd_burst = TCP_CWND_SS;
11656 
11657 				/*
11658 				 * For SACK:
11659 				 * Calculate tcp_pipe, which is the
11660 				 * estimated number of bytes in
11661 				 * network.
11662 				 *
11663 				 * tcp_fack is the highest sack'ed seq num
11664 				 * TCP has received.
11665 				 *
11666 				 * tcp_pipe is explained in the above quoted
11667 				 * Fall and Floyd's paper.  tcp_fack is
11668 				 * explained in Mathis and Mahdavi's
11669 				 * "Forward Acknowledgment: Refining TCP
11670 				 * Congestion Control" in SIGCOMM '96.
11671 				 */
11672 				if (tcp->tcp_snd_sack_ok) {
11673 					ASSERT(tcp->tcp_sack_info != NULL);
11674 					if (tcp->tcp_notsack_list != NULL) {
11675 						tcp->tcp_pipe = tcp->tcp_snxt -
11676 						    tcp->tcp_fack;
11677 						tcp->tcp_sack_snxt = seg_ack;
11678 						flags |= TH_NEED_SACK_REXMIT;
11679 					} else {
11680 						/*
11681 						 * Always initialize tcp_pipe
11682 						 * even though we don't have
11683 						 * any SACK info.  If later
11684 						 * we get SACK info and
11685 						 * tcp_pipe is not initialized,
11686 						 * funny things will happen.
11687 						 */
11688 						tcp->tcp_pipe =
11689 						    tcp->tcp_cwnd_ssthresh;
11690 					}
11691 				} else {
11692 					flags |= TH_REXMIT_NEEDED;
11693 				} /* tcp_snd_sack_ok */
11694 
11695 				} else {
11696 					/*
11697 					 * Here we perform congestion
11698 					 * avoidance, but NOT slow start.
11699 					 * This is known as the Fast
11700 					 * Recovery Algorithm.
11701 					 */
11702 					if (tcp->tcp_snd_sack_ok &&
11703 					    tcp->tcp_notsack_list != NULL) {
11704 						flags |= TH_NEED_SACK_REXMIT;
11705 						tcp->tcp_pipe -= mss;
11706 						if (tcp->tcp_pipe < 0)
11707 							tcp->tcp_pipe = 0;
11708 					} else {
11709 					/*
11710 					 * We know that one more packet has
11711 					 * left the pipe thus we can update
11712 					 * cwnd.
11713 					 */
11714 					cwnd = tcp->tcp_cwnd + mss;
11715 					if (cwnd > tcp->tcp_cwnd_max)
11716 						cwnd = tcp->tcp_cwnd_max;
11717 					tcp->tcp_cwnd = cwnd;
11718 					if (tcp->tcp_unsent > 0)
11719 						flags |= TH_XMIT_NEEDED;
11720 					}
11721 				}
11722 			}
11723 		} else if (tcp->tcp_zero_win_probe) {
11724 			/*
11725 			 * If the window has opened, need to arrange
11726 			 * to send additional data.
11727 			 */
11728 			if (new_swnd != 0) {
11729 				/* tcp_suna != tcp_snxt */
11730 				/* Packet contains a window update */
11731 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
11732 				tcp->tcp_zero_win_probe = 0;
11733 				tcp->tcp_timer_backoff = 0;
11734 				tcp->tcp_ms_we_have_waited = 0;
11735 
11736 				/*
11737 				 * Transmit starting with tcp_suna since
11738 				 * the one byte probe is not ack'ed.
11739 				 * If TCP has sent more than one identical
11740 				 * probe, tcp_rexmit will be set.  That means
11741 				 * tcp_ss_rexmit() will send out the one
11742 				 * byte along with new data.  Otherwise,
11743 				 * fake the retransmission.
11744 				 */
11745 				flags |= TH_XMIT_NEEDED;
11746 				if (!tcp->tcp_rexmit) {
11747 					tcp->tcp_rexmit = B_TRUE;
11748 					tcp->tcp_dupack_cnt = 0;
11749 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
11750 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
11751 				}
11752 			}
11753 		}
11754 		goto swnd_update;
11755 	}
11756 
11757 	/*
11758 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
11759 	 * If the ACK value acks something that we have not yet sent, it might
11760 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
11761 	 * other side.
11762 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
11763 	 * state is handled above, so we can always just drop the segment and
11764 	 * send an ACK here.
11765 	 *
11766 	 * In the case where the peer shrinks the window, we see the new window
11767 	 * update, but all the data sent previously is queued up by the peer.
11768 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
11769 	 * number, which was already sent, and within window, is recorded.
11770 	 * tcp_snxt is then updated.
11771 	 *
11772 	 * If the window has previously shrunk, and an ACK for data not yet
11773 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
11774 	 * the ACK is for data within the window at the time the window was
11775 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
11776 	 * the sequence number ACK'ed.
11777 	 *
11778 	 * If the ACK covers all the data sent at the time the window was
11779 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
11780 	 *
11781 	 * Should we send ACKs in response to ACK only segments?
11782 	 */
11783 
11784 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
11785 		if ((tcp->tcp_is_wnd_shrnk) &&
11786 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
11787 			uint32_t data_acked_ahead_snxt;
11788 
11789 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
11790 			tcp_update_xmit_tail(tcp, seg_ack);
11791 			tcp->tcp_unsent -= data_acked_ahead_snxt;
11792 		} else {
11793 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
11794 			/* drop the received segment */
11795 			freemsg(mp);
11796 
11797 			/*
11798 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
11799 			 * greater than 0, check if the number of such
11800 			 * bogus ACks is greater than that count.  If yes,
11801 			 * don't send back any ACK.  This prevents TCP from
11802 			 * getting into an ACK storm if somehow an attacker
11803 			 * successfully spoofs an acceptable segment to our
11804 			 * peer.  If this continues (count > 2 X threshold),
11805 			 * we should abort this connection.
11806 			 */
11807 			if (tcp_drop_ack_unsent_cnt > 0 &&
11808 			    ++tcp->tcp_in_ack_unsent >
11809 			    tcp_drop_ack_unsent_cnt) {
11810 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
11811 				if (tcp->tcp_in_ack_unsent > 2 *
11812 				    tcp_drop_ack_unsent_cnt) {
11813 					(void) tcp_clean_death(tcp, EPROTO, 20);
11814 				}
11815 				return;
11816 			}
11817 			mp = tcp_ack_mp(tcp);
11818 			if (mp != NULL) {
11819 				BUMP_LOCAL(tcp->tcp_obsegs);
11820 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
11821 				tcp_send_data(tcp, mp);
11822 			}
11823 			return;
11824 		}
11825 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
11826 	    tcp->tcp_snxt_shrunk)) {
11827 			tcp->tcp_is_wnd_shrnk = B_FALSE;
11828 	}
11829 
11830 	/*
11831 	 * TCP gets a new ACK, update the notsack'ed list to delete those
11832 	 * blocks that are covered by this ACK.
11833 	 */
11834 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
11835 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
11836 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
11837 	}
11838 
11839 	/*
11840 	 * If we got an ACK after fast retransmit, check to see
11841 	 * if it is a partial ACK.  If it is not and the congestion
11842 	 * window was inflated to account for the other side's
11843 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
11844 	 */
11845 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
11846 		ASSERT(tcp->tcp_rexmit == B_FALSE);
11847 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
11848 			tcp->tcp_dupack_cnt = 0;
11849 			/*
11850 			 * Restore the orig tcp_cwnd_ssthresh after
11851 			 * fast retransmit phase.
11852 			 */
11853 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
11854 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
11855 			}
11856 			tcp->tcp_rexmit_max = seg_ack;
11857 			tcp->tcp_cwnd_cnt = 0;
11858 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11859 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11860 
11861 			/*
11862 			 * Remove all notsack info to avoid confusion with
11863 			 * the next fast retrasnmit/recovery phase.
11864 			 */
11865 			if (tcp->tcp_snd_sack_ok &&
11866 			    tcp->tcp_notsack_list != NULL) {
11867 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
11868 				    tcp);
11869 			}
11870 		} else {
11871 			if (tcp->tcp_snd_sack_ok &&
11872 			    tcp->tcp_notsack_list != NULL) {
11873 				flags |= TH_NEED_SACK_REXMIT;
11874 				tcp->tcp_pipe -= mss;
11875 				if (tcp->tcp_pipe < 0)
11876 					tcp->tcp_pipe = 0;
11877 			} else {
11878 				/*
11879 				 * Hoe's algorithm:
11880 				 *
11881 				 * Retransmit the unack'ed segment and
11882 				 * restart fast recovery.  Note that we
11883 				 * need to scale back tcp_cwnd to the
11884 				 * original value when we started fast
11885 				 * recovery.  This is to prevent overly
11886 				 * aggressive behaviour in sending new
11887 				 * segments.
11888 				 */
11889 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
11890 				    tcps->tcps_dupack_fast_retransmit * mss;
11891 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
11892 				flags |= TH_REXMIT_NEEDED;
11893 			}
11894 		}
11895 	} else {
11896 		tcp->tcp_dupack_cnt = 0;
11897 		if (tcp->tcp_rexmit) {
11898 			/*
11899 			 * TCP is retranmitting.  If the ACK ack's all
11900 			 * outstanding data, update tcp_rexmit_max and
11901 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
11902 			 * to the correct value.
11903 			 *
11904 			 * Note that SEQ_LEQ() is used.  This is to avoid
11905 			 * unnecessary fast retransmit caused by dup ACKs
11906 			 * received when TCP does slow start retransmission
11907 			 * after a time out.  During this phase, TCP may
11908 			 * send out segments which are already received.
11909 			 * This causes dup ACKs to be sent back.
11910 			 */
11911 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
11912 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
11913 					tcp->tcp_rexmit_nxt = seg_ack;
11914 				}
11915 				if (seg_ack != tcp->tcp_rexmit_max) {
11916 					flags |= TH_XMIT_NEEDED;
11917 				}
11918 			} else {
11919 				tcp->tcp_rexmit = B_FALSE;
11920 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11921 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
11922 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11923 			}
11924 			tcp->tcp_ms_we_have_waited = 0;
11925 		}
11926 	}
11927 
11928 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
11929 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
11930 	tcp->tcp_suna = seg_ack;
11931 	if (tcp->tcp_zero_win_probe != 0) {
11932 		tcp->tcp_zero_win_probe = 0;
11933 		tcp->tcp_timer_backoff = 0;
11934 	}
11935 
11936 	/*
11937 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
11938 	 * Note that it cannot be the SYN being ack'ed.  The code flow
11939 	 * will not reach here.
11940 	 */
11941 	if (mp1 == NULL) {
11942 		goto fin_acked;
11943 	}
11944 
11945 	/*
11946 	 * Update the congestion window.
11947 	 *
11948 	 * If TCP is not ECN capable or TCP is ECN capable but the
11949 	 * congestion experience bit is not set, increase the tcp_cwnd as
11950 	 * usual.
11951 	 */
11952 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
11953 		cwnd = tcp->tcp_cwnd;
11954 		add = mss;
11955 
11956 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
11957 			/*
11958 			 * This is to prevent an increase of less than 1 MSS of
11959 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
11960 			 * may send out tinygrams in order to preserve mblk
11961 			 * boundaries.
11962 			 *
11963 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
11964 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
11965 			 * increased by 1 MSS for every RTTs.
11966 			 */
11967 			if (tcp->tcp_cwnd_cnt <= 0) {
11968 				tcp->tcp_cwnd_cnt = cwnd + add;
11969 			} else {
11970 				tcp->tcp_cwnd_cnt -= add;
11971 				add = 0;
11972 			}
11973 		}
11974 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
11975 	}
11976 
11977 	/* See if the latest urgent data has been acknowledged */
11978 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
11979 	    SEQ_GT(seg_ack, tcp->tcp_urg))
11980 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
11981 
11982 	/* Can we update the RTT estimates? */
11983 	if (tcp->tcp_snd_ts_ok) {
11984 		/* Ignore zero timestamp echo-reply. */
11985 		if (tcpopt.tcp_opt_ts_ecr != 0) {
11986 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
11987 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
11988 		}
11989 
11990 		/* If needed, restart the timer. */
11991 		if (tcp->tcp_set_timer == 1) {
11992 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11993 			tcp->tcp_set_timer = 0;
11994 		}
11995 		/*
11996 		 * Update tcp_csuna in case the other side stops sending
11997 		 * us timestamps.
11998 		 */
11999 		tcp->tcp_csuna = tcp->tcp_snxt;
12000 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
12001 		/*
12002 		 * An ACK sequence we haven't seen before, so get the RTT
12003 		 * and update the RTO. But first check if the timestamp is
12004 		 * valid to use.
12005 		 */
12006 		if ((mp1->b_next != NULL) &&
12007 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
12008 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
12009 			    (int32_t)(intptr_t)mp1->b_prev);
12010 		else
12011 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12012 
12013 		/* Remeber the last sequence to be ACKed */
12014 		tcp->tcp_csuna = seg_ack;
12015 		if (tcp->tcp_set_timer == 1) {
12016 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
12017 			tcp->tcp_set_timer = 0;
12018 		}
12019 	} else {
12020 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
12021 	}
12022 
12023 	/* Eat acknowledged bytes off the xmit queue. */
12024 	for (;;) {
12025 		mblk_t	*mp2;
12026 		uchar_t	*wptr;
12027 
12028 		wptr = mp1->b_wptr;
12029 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
12030 		bytes_acked -= (int)(wptr - mp1->b_rptr);
12031 		if (bytes_acked < 0) {
12032 			mp1->b_rptr = wptr + bytes_acked;
12033 			/*
12034 			 * Set a new timestamp if all the bytes timed by the
12035 			 * old timestamp have been ack'ed.
12036 			 */
12037 			if (SEQ_GT(seg_ack,
12038 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
12039 				mp1->b_prev =
12040 				    (mblk_t *)(uintptr_t)LBOLT_FASTPATH;
12041 				mp1->b_next = NULL;
12042 			}
12043 			break;
12044 		}
12045 		mp1->b_next = NULL;
12046 		mp1->b_prev = NULL;
12047 		mp2 = mp1;
12048 		mp1 = mp1->b_cont;
12049 
12050 		/*
12051 		 * This notification is required for some zero-copy
12052 		 * clients to maintain a copy semantic. After the data
12053 		 * is ack'ed, client is safe to modify or reuse the buffer.
12054 		 */
12055 		if (tcp->tcp_snd_zcopy_aware &&
12056 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
12057 			tcp_zcopy_notify(tcp);
12058 		freeb(mp2);
12059 		if (bytes_acked == 0) {
12060 			if (mp1 == NULL) {
12061 				/* Everything is ack'ed, clear the tail. */
12062 				tcp->tcp_xmit_tail = NULL;
12063 				/*
12064 				 * Cancel the timer unless we are still
12065 				 * waiting for an ACK for the FIN packet.
12066 				 */
12067 				if (tcp->tcp_timer_tid != 0 &&
12068 				    tcp->tcp_snxt == tcp->tcp_suna) {
12069 					(void) TCP_TIMER_CANCEL(tcp,
12070 					    tcp->tcp_timer_tid);
12071 					tcp->tcp_timer_tid = 0;
12072 				}
12073 				goto pre_swnd_update;
12074 			}
12075 			if (mp2 != tcp->tcp_xmit_tail)
12076 				break;
12077 			tcp->tcp_xmit_tail = mp1;
12078 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12079 			    (uintptr_t)INT_MAX);
12080 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
12081 			    mp1->b_rptr);
12082 			break;
12083 		}
12084 		if (mp1 == NULL) {
12085 			/*
12086 			 * More was acked but there is nothing more
12087 			 * outstanding.  This means that the FIN was
12088 			 * just acked or that we're talking to a clown.
12089 			 */
12090 fin_acked:
12091 			ASSERT(tcp->tcp_fin_sent);
12092 			tcp->tcp_xmit_tail = NULL;
12093 			if (tcp->tcp_fin_sent) {
12094 				/* FIN was acked - making progress */
12095 				if (!tcp->tcp_fin_acked)
12096 					tcp->tcp_ip_forward_progress = B_TRUE;
12097 				tcp->tcp_fin_acked = B_TRUE;
12098 				if (tcp->tcp_linger_tid != 0 &&
12099 				    TCP_TIMER_CANCEL(tcp,
12100 				    tcp->tcp_linger_tid) >= 0) {
12101 					tcp_stop_lingering(tcp);
12102 					freemsg(mp);
12103 					mp = NULL;
12104 				}
12105 			} else {
12106 				/*
12107 				 * We should never get here because
12108 				 * we have already checked that the
12109 				 * number of bytes ack'ed should be
12110 				 * smaller than or equal to what we
12111 				 * have sent so far (it is the
12112 				 * acceptability check of the ACK).
12113 				 * We can only get here if the send
12114 				 * queue is corrupted.
12115 				 *
12116 				 * Terminate the connection and
12117 				 * panic the system.  It is better
12118 				 * for us to panic instead of
12119 				 * continuing to avoid other disaster.
12120 				 */
12121 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
12122 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
12123 				panic("Memory corruption "
12124 				    "detected for connection %s.",
12125 				    tcp_display(tcp, NULL,
12126 				    DISP_ADDR_AND_PORT));
12127 				/*NOTREACHED*/
12128 			}
12129 			goto pre_swnd_update;
12130 		}
12131 		ASSERT(mp2 != tcp->tcp_xmit_tail);
12132 	}
12133 	if (tcp->tcp_unsent) {
12134 		flags |= TH_XMIT_NEEDED;
12135 	}
12136 pre_swnd_update:
12137 	tcp->tcp_xmit_head = mp1;
12138 swnd_update:
12139 	/*
12140 	 * The following check is different from most other implementations.
12141 	 * For bi-directional transfer, when segments are dropped, the
12142 	 * "normal" check will not accept a window update in those
12143 	 * retransmitted segemnts.  Failing to do that, TCP may send out
12144 	 * segments which are outside receiver's window.  As TCP accepts
12145 	 * the ack in those retransmitted segments, if the window update in
12146 	 * the same segment is not accepted, TCP will incorrectly calculates
12147 	 * that it can send more segments.  This can create a deadlock
12148 	 * with the receiver if its window becomes zero.
12149 	 */
12150 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
12151 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
12152 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
12153 		/*
12154 		 * The criteria for update is:
12155 		 *
12156 		 * 1. the segment acknowledges some data.  Or
12157 		 * 2. the segment is new, i.e. it has a higher seq num. Or
12158 		 * 3. the segment is not old and the advertised window is
12159 		 * larger than the previous advertised window.
12160 		 */
12161 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
12162 			flags |= TH_XMIT_NEEDED;
12163 		tcp->tcp_swnd = new_swnd;
12164 		if (new_swnd > tcp->tcp_max_swnd)
12165 			tcp->tcp_max_swnd = new_swnd;
12166 		tcp->tcp_swl1 = seg_seq;
12167 		tcp->tcp_swl2 = seg_ack;
12168 	}
12169 est:
12170 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
12171 
12172 		switch (tcp->tcp_state) {
12173 		case TCPS_FIN_WAIT_1:
12174 			if (tcp->tcp_fin_acked) {
12175 				tcp->tcp_state = TCPS_FIN_WAIT_2;
12176 				/*
12177 				 * We implement the non-standard BSD/SunOS
12178 				 * FIN_WAIT_2 flushing algorithm.
12179 				 * If there is no user attached to this
12180 				 * TCP endpoint, then this TCP struct
12181 				 * could hang around forever in FIN_WAIT_2
12182 				 * state if the peer forgets to send us
12183 				 * a FIN.  To prevent this, we wait only
12184 				 * 2*MSL (a convenient time value) for
12185 				 * the FIN to arrive.  If it doesn't show up,
12186 				 * we flush the TCP endpoint.  This algorithm,
12187 				 * though a violation of RFC-793, has worked
12188 				 * for over 10 years in BSD systems.
12189 				 * Note: SunOS 4.x waits 675 seconds before
12190 				 * flushing the FIN_WAIT_2 connection.
12191 				 */
12192 				TCP_TIMER_RESTART(tcp,
12193 				    tcps->tcps_fin_wait_2_flush_interval);
12194 			}
12195 			break;
12196 		case TCPS_FIN_WAIT_2:
12197 			break;	/* Shutdown hook? */
12198 		case TCPS_LAST_ACK:
12199 			freemsg(mp);
12200 			if (tcp->tcp_fin_acked) {
12201 				(void) tcp_clean_death(tcp, 0, 19);
12202 				return;
12203 			}
12204 			goto xmit_check;
12205 		case TCPS_CLOSING:
12206 			if (tcp->tcp_fin_acked)
12207 				SET_TIME_WAIT(tcps, tcp, connp);
12208 			/*FALLTHRU*/
12209 		case TCPS_CLOSE_WAIT:
12210 			freemsg(mp);
12211 			goto xmit_check;
12212 		default:
12213 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12214 			break;
12215 		}
12216 	}
12217 	if (flags & TH_FIN) {
12218 		/* Make sure we ack the fin */
12219 		flags |= TH_ACK_NEEDED;
12220 		if (!tcp->tcp_fin_rcvd) {
12221 			tcp->tcp_fin_rcvd = B_TRUE;
12222 			tcp->tcp_rnxt++;
12223 			tcpha = tcp->tcp_tcpha;
12224 			tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12225 
12226 			/*
12227 			 * Generate the ordrel_ind at the end unless we
12228 			 * are an eager guy.
12229 			 * In the eager case tcp_rsrv will do this when run
12230 			 * after tcp_accept is done.
12231 			 */
12232 			if (tcp->tcp_listener == NULL &&
12233 			    !TCP_IS_DETACHED(tcp) && !tcp->tcp_hard_binding)
12234 				flags |= TH_ORDREL_NEEDED;
12235 			switch (tcp->tcp_state) {
12236 			case TCPS_SYN_RCVD:
12237 			case TCPS_ESTABLISHED:
12238 				tcp->tcp_state = TCPS_CLOSE_WAIT;
12239 				/* Keepalive? */
12240 				break;
12241 			case TCPS_FIN_WAIT_1:
12242 				if (!tcp->tcp_fin_acked) {
12243 					tcp->tcp_state = TCPS_CLOSING;
12244 					break;
12245 				}
12246 				/* FALLTHRU */
12247 			case TCPS_FIN_WAIT_2:
12248 				SET_TIME_WAIT(tcps, tcp, connp);
12249 				if (seg_len) {
12250 					/*
12251 					 * implies data piggybacked on FIN.
12252 					 * break to handle data.
12253 					 */
12254 					break;
12255 				}
12256 				freemsg(mp);
12257 				goto ack_check;
12258 			}
12259 		}
12260 	}
12261 	if (mp == NULL)
12262 		goto xmit_check;
12263 	if (seg_len == 0) {
12264 		freemsg(mp);
12265 		goto xmit_check;
12266 	}
12267 	if (mp->b_rptr == mp->b_wptr) {
12268 		/*
12269 		 * The header has been consumed, so we remove the
12270 		 * zero-length mblk here.
12271 		 */
12272 		mp1 = mp;
12273 		mp = mp->b_cont;
12274 		freeb(mp1);
12275 	}
12276 update_ack:
12277 	tcpha = tcp->tcp_tcpha;
12278 	tcp->tcp_rack_cnt++;
12279 	{
12280 		uint32_t cur_max;
12281 
12282 		cur_max = tcp->tcp_rack_cur_max;
12283 		if (tcp->tcp_rack_cnt >= cur_max) {
12284 			/*
12285 			 * We have more unacked data than we should - send
12286 			 * an ACK now.
12287 			 */
12288 			flags |= TH_ACK_NEEDED;
12289 			cur_max++;
12290 			if (cur_max > tcp->tcp_rack_abs_max)
12291 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
12292 			else
12293 				tcp->tcp_rack_cur_max = cur_max;
12294 		} else if (TCP_IS_DETACHED(tcp)) {
12295 			/* We don't have an ACK timer for detached TCP. */
12296 			flags |= TH_ACK_NEEDED;
12297 		} else if (seg_len < mss) {
12298 			/*
12299 			 * If we get a segment that is less than an mss, and we
12300 			 * already have unacknowledged data, and the amount
12301 			 * unacknowledged is not a multiple of mss, then we
12302 			 * better generate an ACK now.  Otherwise, this may be
12303 			 * the tail piece of a transaction, and we would rather
12304 			 * wait for the response.
12305 			 */
12306 			uint32_t udif;
12307 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
12308 			    (uintptr_t)INT_MAX);
12309 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
12310 			if (udif && (udif % mss))
12311 				flags |= TH_ACK_NEEDED;
12312 			else
12313 				flags |= TH_ACK_TIMER_NEEDED;
12314 		} else {
12315 			/* Start delayed ack timer */
12316 			flags |= TH_ACK_TIMER_NEEDED;
12317 		}
12318 	}
12319 	tcp->tcp_rnxt += seg_len;
12320 	tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12321 
12322 	if (mp == NULL)
12323 		goto xmit_check;
12324 
12325 	/* Update SACK list */
12326 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
12327 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
12328 		    &(tcp->tcp_num_sack_blk));
12329 	}
12330 
12331 	if (tcp->tcp_urp_mp) {
12332 		tcp->tcp_urp_mp->b_cont = mp;
12333 		mp = tcp->tcp_urp_mp;
12334 		tcp->tcp_urp_mp = NULL;
12335 		/* Ready for a new signal. */
12336 		tcp->tcp_urp_last_valid = B_FALSE;
12337 #ifdef DEBUG
12338 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12339 		    "tcp_rput: sending exdata_ind %s",
12340 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12341 #endif /* DEBUG */
12342 	}
12343 
12344 	/*
12345 	 * Check for ancillary data changes compared to last segment.
12346 	 */
12347 	if (connp->conn_recv_ancillary.crb_all != 0) {
12348 		mp = tcp_input_add_ancillary(tcp, mp, &ipp, ira);
12349 		if (mp == NULL)
12350 			return;
12351 	}
12352 
12353 	if (tcp->tcp_listener != NULL || tcp->tcp_hard_binding) {
12354 		/*
12355 		 * Side queue inbound data until the accept happens.
12356 		 * tcp_accept/tcp_rput drains this when the accept happens.
12357 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
12358 		 * T_EXDATA_IND) it is queued on b_next.
12359 		 * XXX Make urgent data use this. Requires:
12360 		 *	Removing tcp_listener check for TH_URG
12361 		 *	Making M_PCPROTO and MARK messages skip the eager case
12362 		 */
12363 
12364 		if (tcp->tcp_kssl_pending) {
12365 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
12366 			    mblk_t *, mp);
12367 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12368 		} else {
12369 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12370 		}
12371 	} else if (IPCL_IS_NONSTR(connp)) {
12372 		/*
12373 		 * Non-STREAMS socket
12374 		 *
12375 		 * Note that no KSSL processing is done here, because
12376 		 * KSSL is not supported for non-STREAMS sockets.
12377 		 */
12378 		boolean_t push = flags & (TH_PUSH|TH_FIN);
12379 		int error;
12380 
12381 		if ((*connp->conn_upcalls->su_recv)(
12382 		    connp->conn_upper_handle,
12383 		    mp, seg_len, 0, &error, &push) <= 0) {
12384 			/*
12385 			 * We should never be in middle of a
12386 			 * fallback, the squeue guarantees that.
12387 			 */
12388 			ASSERT(error != EOPNOTSUPP);
12389 			if (error == ENOSPC)
12390 				tcp->tcp_rwnd -= seg_len;
12391 		} else if (push) {
12392 			/* PUSH bit set and sockfs is not flow controlled */
12393 			flags |= tcp_rwnd_reopen(tcp);
12394 		}
12395 	} else {
12396 		/* STREAMS socket */
12397 		if (mp->b_datap->db_type != M_DATA ||
12398 		    (flags & TH_MARKNEXT_NEEDED)) {
12399 			if (tcp->tcp_rcv_list != NULL) {
12400 				flags |= tcp_rcv_drain(tcp);
12401 			}
12402 			ASSERT(tcp->tcp_rcv_list == NULL ||
12403 			    tcp->tcp_fused_sigurg);
12404 
12405 			if (flags & TH_MARKNEXT_NEEDED) {
12406 #ifdef DEBUG
12407 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12408 				    "tcp_rput: sending MSGMARKNEXT %s",
12409 				    tcp_display(tcp, NULL,
12410 				    DISP_PORT_ONLY));
12411 #endif /* DEBUG */
12412 				mp->b_flag |= MSGMARKNEXT;
12413 				flags &= ~TH_MARKNEXT_NEEDED;
12414 			}
12415 
12416 			/* Does this need SSL processing first? */
12417 			if ((tcp->tcp_kssl_ctx != NULL) &&
12418 			    (DB_TYPE(mp) == M_DATA)) {
12419 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
12420 				    mblk_t *, mp);
12421 				tcp_kssl_input(tcp, mp, ira->ira_cred);
12422 			} else {
12423 				if (is_system_labeled())
12424 					tcp_setcred_data(mp, ira);
12425 
12426 				putnext(connp->conn_rq, mp);
12427 				if (!canputnext(connp->conn_rq))
12428 					tcp->tcp_rwnd -= seg_len;
12429 			}
12430 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
12431 		    (DB_TYPE(mp) == M_DATA)) {
12432 			/* Does this need SSL processing first? */
12433 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
12434 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12435 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
12436 		    tcp->tcp_rcv_cnt + seg_len >= connp->conn_rcvbuf >> 3) {
12437 			if (tcp->tcp_rcv_list != NULL) {
12438 				/*
12439 				 * Enqueue the new segment first and then
12440 				 * call tcp_rcv_drain() to send all data
12441 				 * up.  The other way to do this is to
12442 				 * send all queued data up and then call
12443 				 * putnext() to send the new segment up.
12444 				 * This way can remove the else part later
12445 				 * on.
12446 				 *
12447 				 * We don't do this to avoid one more call to
12448 				 * canputnext() as tcp_rcv_drain() needs to
12449 				 * call canputnext().
12450 				 */
12451 				tcp_rcv_enqueue(tcp, mp, seg_len,
12452 				    ira->ira_cred);
12453 				flags |= tcp_rcv_drain(tcp);
12454 			} else {
12455 				if (is_system_labeled())
12456 					tcp_setcred_data(mp, ira);
12457 
12458 				putnext(connp->conn_rq, mp);
12459 				if (!canputnext(connp->conn_rq))
12460 					tcp->tcp_rwnd -= seg_len;
12461 			}
12462 		} else {
12463 			/*
12464 			 * Enqueue all packets when processing an mblk
12465 			 * from the co queue and also enqueue normal packets.
12466 			 */
12467 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12468 		}
12469 		/*
12470 		 * Make sure the timer is running if we have data waiting
12471 		 * for a push bit. This provides resiliency against
12472 		 * implementations that do not correctly generate push bits.
12473 		 */
12474 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
12475 			/*
12476 			 * The connection may be closed at this point, so don't
12477 			 * do anything for a detached tcp.
12478 			 */
12479 			if (!TCP_IS_DETACHED(tcp))
12480 				tcp->tcp_push_tid = TCP_TIMER(tcp,
12481 				    tcp_push_timer,
12482 				    MSEC_TO_TICK(
12483 				    tcps->tcps_push_timer_interval));
12484 		}
12485 	}
12486 
12487 xmit_check:
12488 	/* Is there anything left to do? */
12489 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12490 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
12491 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
12492 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12493 		goto done;
12494 
12495 	/* Any transmit work to do and a non-zero window? */
12496 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
12497 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
12498 		if (flags & TH_REXMIT_NEEDED) {
12499 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
12500 
12501 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
12502 			if (snd_size > mss)
12503 				snd_size = mss;
12504 			if (snd_size > tcp->tcp_swnd)
12505 				snd_size = tcp->tcp_swnd;
12506 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
12507 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
12508 			    B_TRUE);
12509 
12510 			if (mp1 != NULL) {
12511 				tcp->tcp_xmit_head->b_prev =
12512 				    (mblk_t *)LBOLT_FASTPATH;
12513 				tcp->tcp_csuna = tcp->tcp_snxt;
12514 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12515 				UPDATE_MIB(&tcps->tcps_mib,
12516 				    tcpRetransBytes, snd_size);
12517 				tcp_send_data(tcp, mp1);
12518 			}
12519 		}
12520 		if (flags & TH_NEED_SACK_REXMIT) {
12521 			tcp_sack_rxmit(tcp, &flags);
12522 		}
12523 		/*
12524 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
12525 		 * out new segment.  Note that tcp_rexmit should not be
12526 		 * set, otherwise TH_LIMIT_XMIT should not be set.
12527 		 */
12528 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
12529 			if (!tcp->tcp_rexmit) {
12530 				tcp_wput_data(tcp, NULL, B_FALSE);
12531 			} else {
12532 				tcp_ss_rexmit(tcp);
12533 			}
12534 		}
12535 		/*
12536 		 * Adjust tcp_cwnd back to normal value after sending
12537 		 * new data segments.
12538 		 */
12539 		if (flags & TH_LIMIT_XMIT) {
12540 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
12541 			/*
12542 			 * This will restart the timer.  Restarting the
12543 			 * timer is used to avoid a timeout before the
12544 			 * limited transmitted segment's ACK gets back.
12545 			 */
12546 			if (tcp->tcp_xmit_head != NULL)
12547 				tcp->tcp_xmit_head->b_prev =
12548 				    (mblk_t *)LBOLT_FASTPATH;
12549 		}
12550 
12551 		/* Anything more to do? */
12552 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
12553 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12554 			goto done;
12555 	}
12556 ack_check:
12557 	if (flags & TH_SEND_URP_MARK) {
12558 		ASSERT(tcp->tcp_urp_mark_mp);
12559 		ASSERT(!IPCL_IS_NONSTR(connp));
12560 		/*
12561 		 * Send up any queued data and then send the mark message
12562 		 */
12563 		if (tcp->tcp_rcv_list != NULL) {
12564 			flags |= tcp_rcv_drain(tcp);
12565 
12566 		}
12567 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12568 		mp1 = tcp->tcp_urp_mark_mp;
12569 		tcp->tcp_urp_mark_mp = NULL;
12570 		if (is_system_labeled())
12571 			tcp_setcred_data(mp1, ira);
12572 
12573 		putnext(connp->conn_rq, mp1);
12574 #ifdef DEBUG
12575 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12576 		    "tcp_rput: sending zero-length %s %s",
12577 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
12578 		    "MSGNOTMARKNEXT"),
12579 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12580 #endif /* DEBUG */
12581 		flags &= ~TH_SEND_URP_MARK;
12582 	}
12583 	if (flags & TH_ACK_NEEDED) {
12584 		/*
12585 		 * Time to send an ack for some reason.
12586 		 */
12587 		mp1 = tcp_ack_mp(tcp);
12588 
12589 		if (mp1 != NULL) {
12590 			tcp_send_data(tcp, mp1);
12591 			BUMP_LOCAL(tcp->tcp_obsegs);
12592 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
12593 		}
12594 		if (tcp->tcp_ack_tid != 0) {
12595 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
12596 			tcp->tcp_ack_tid = 0;
12597 		}
12598 	}
12599 	if (flags & TH_ACK_TIMER_NEEDED) {
12600 		/*
12601 		 * Arrange for deferred ACK or push wait timeout.
12602 		 * Start timer if it is not already running.
12603 		 */
12604 		if (tcp->tcp_ack_tid == 0) {
12605 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
12606 			    MSEC_TO_TICK(tcp->tcp_localnet ?
12607 			    (clock_t)tcps->tcps_local_dack_interval :
12608 			    (clock_t)tcps->tcps_deferred_ack_interval));
12609 		}
12610 	}
12611 	if (flags & TH_ORDREL_NEEDED) {
12612 		/*
12613 		 * Send up the ordrel_ind unless we are an eager guy.
12614 		 * In the eager case tcp_rsrv will do this when run
12615 		 * after tcp_accept is done.
12616 		 */
12617 		ASSERT(tcp->tcp_listener == NULL);
12618 		ASSERT(!tcp->tcp_detached);
12619 
12620 		if (IPCL_IS_NONSTR(connp)) {
12621 			ASSERT(tcp->tcp_ordrel_mp == NULL);
12622 			tcp->tcp_ordrel_done = B_TRUE;
12623 			(*connp->conn_upcalls->su_opctl)
12624 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
12625 			goto done;
12626 		}
12627 
12628 		if (tcp->tcp_rcv_list != NULL) {
12629 			/*
12630 			 * Push any mblk(s) enqueued from co processing.
12631 			 */
12632 			flags |= tcp_rcv_drain(tcp);
12633 		}
12634 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12635 
12636 		mp1 = tcp->tcp_ordrel_mp;
12637 		tcp->tcp_ordrel_mp = NULL;
12638 		tcp->tcp_ordrel_done = B_TRUE;
12639 		putnext(connp->conn_rq, mp1);
12640 	}
12641 done:
12642 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12643 }
12644 
12645 /*
12646  * This routine adjusts next-to-send sequence number variables, in the
12647  * case where the reciever has shrunk it's window.
12648  */
12649 static void
12650 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
12651 {
12652 	mblk_t *xmit_tail;
12653 	int32_t offset;
12654 
12655 	tcp->tcp_snxt = snxt;
12656 
12657 	/* Get the mblk, and the offset in it, as per the shrunk window */
12658 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
12659 	ASSERT(xmit_tail != NULL);
12660 	tcp->tcp_xmit_tail = xmit_tail;
12661 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
12662 	    xmit_tail->b_rptr - offset;
12663 }
12664 
12665 /*
12666  * This function does PAWS protection check. Returns B_TRUE if the
12667  * segment passes the PAWS test, else returns B_FALSE.
12668  */
12669 boolean_t
12670 tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp)
12671 {
12672 	uint8_t	flags;
12673 	int	options;
12674 	uint8_t *up;
12675 	conn_t	*connp = tcp->tcp_connp;
12676 
12677 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
12678 	/*
12679 	 * If timestamp option is aligned nicely, get values inline,
12680 	 * otherwise call general routine to parse.  Only do that
12681 	 * if timestamp is the only option.
12682 	 */
12683 	if (TCP_HDR_LENGTH(tcpha) == (uint32_t)TCP_MIN_HEADER_LENGTH +
12684 	    TCPOPT_REAL_TS_LEN &&
12685 	    OK_32PTR((up = ((uint8_t *)tcpha) +
12686 	    TCP_MIN_HEADER_LENGTH)) &&
12687 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
12688 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
12689 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
12690 
12691 		options = TCP_OPT_TSTAMP_PRESENT;
12692 	} else {
12693 		if (tcp->tcp_snd_sack_ok) {
12694 			tcpoptp->tcp = tcp;
12695 		} else {
12696 			tcpoptp->tcp = NULL;
12697 		}
12698 		options = tcp_parse_options(tcpha, tcpoptp);
12699 	}
12700 
12701 	if (options & TCP_OPT_TSTAMP_PRESENT) {
12702 		/*
12703 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
12704 		 * regardless of the timestamp, page 18 RFC 1323.bis.
12705 		 */
12706 		if ((flags & TH_RST) == 0 &&
12707 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
12708 		    tcp->tcp_ts_recent)) {
12709 			if (TSTMP_LT(LBOLT_FASTPATH64,
12710 			    tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) {
12711 				/* This segment is not acceptable. */
12712 				return (B_FALSE);
12713 			} else {
12714 				/*
12715 				 * Connection has been idle for
12716 				 * too long.  Reset the timestamp
12717 				 * and assume the segment is valid.
12718 				 */
12719 				tcp->tcp_ts_recent =
12720 				    tcpoptp->tcp_opt_ts_val;
12721 			}
12722 		}
12723 	} else {
12724 		/*
12725 		 * If we don't get a timestamp on every packet, we
12726 		 * figure we can't really trust 'em, so we stop sending
12727 		 * and parsing them.
12728 		 */
12729 		tcp->tcp_snd_ts_ok = B_FALSE;
12730 
12731 		connp->conn_ht_iphc_len -= TCPOPT_REAL_TS_LEN;
12732 		connp->conn_ht_ulp_len -= TCPOPT_REAL_TS_LEN;
12733 		tcp->tcp_tcpha->tha_offset_and_reserved -= (3 << 4);
12734 		/*
12735 		 * Adjust the tcp_mss and tcp_cwnd accordingly. We avoid
12736 		 * doing a slow start here so as to not to lose on the
12737 		 * transfer rate built up so far.
12738 		 */
12739 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
12740 		if (tcp->tcp_snd_sack_ok) {
12741 			ASSERT(tcp->tcp_sack_info != NULL);
12742 			tcp->tcp_max_sack_blk = 4;
12743 		}
12744 	}
12745 	return (B_TRUE);
12746 }
12747 
12748 /*
12749  * Attach ancillary data to a received TCP segments for the
12750  * ancillary pieces requested by the application that are
12751  * different than they were in the previous data segment.
12752  *
12753  * Save the "current" values once memory allocation is ok so that
12754  * when memory allocation fails we can just wait for the next data segment.
12755  */
12756 static mblk_t *
12757 tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
12758     ip_recv_attr_t *ira)
12759 {
12760 	struct T_optdata_ind *todi;
12761 	int optlen;
12762 	uchar_t *optptr;
12763 	struct T_opthdr *toh;
12764 	crb_t addflag;	/* Which pieces to add */
12765 	mblk_t *mp1;
12766 	conn_t	*connp = tcp->tcp_connp;
12767 
12768 	optlen = 0;
12769 	addflag.crb_all = 0;
12770 	/* If app asked for pktinfo and the index has changed ... */
12771 	if (connp->conn_recv_ancillary.crb_ip_recvpktinfo &&
12772 	    ira->ira_ruifindex != tcp->tcp_recvifindex) {
12773 		optlen += sizeof (struct T_opthdr) +
12774 		    sizeof (struct in6_pktinfo);
12775 		addflag.crb_ip_recvpktinfo = 1;
12776 	}
12777 	/* If app asked for hoplimit and it has changed ... */
12778 	if (connp->conn_recv_ancillary.crb_ipv6_recvhoplimit &&
12779 	    ipp->ipp_hoplimit != tcp->tcp_recvhops) {
12780 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12781 		addflag.crb_ipv6_recvhoplimit = 1;
12782 	}
12783 	/* If app asked for tclass and it has changed ... */
12784 	if (connp->conn_recv_ancillary.crb_ipv6_recvtclass &&
12785 	    ipp->ipp_tclass != tcp->tcp_recvtclass) {
12786 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12787 		addflag.crb_ipv6_recvtclass = 1;
12788 	}
12789 	/*
12790 	 * If app asked for hopbyhop headers and it has changed ...
12791 	 * For security labels, note that (1) security labels can't change on
12792 	 * a connected socket at all, (2) we're connected to at most one peer,
12793 	 * (3) if anything changes, then it must be some other extra option.
12794 	 */
12795 	if (connp->conn_recv_ancillary.crb_ipv6_recvhopopts &&
12796 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
12797 	    (ipp->ipp_fields & IPPF_HOPOPTS),
12798 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
12799 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
12800 		addflag.crb_ipv6_recvhopopts = 1;
12801 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
12802 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
12803 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
12804 			return (mp);
12805 	}
12806 	/* If app asked for dst headers before routing headers ... */
12807 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdrdstopts &&
12808 	    ip_cmpbuf(tcp->tcp_rthdrdstopts, tcp->tcp_rthdrdstoptslen,
12809 	    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12810 	    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen)) {
12811 		optlen += sizeof (struct T_opthdr) +
12812 		    ipp->ipp_rthdrdstoptslen;
12813 		addflag.crb_ipv6_recvrthdrdstopts = 1;
12814 		if (!ip_allocbuf((void **)&tcp->tcp_rthdrdstopts,
12815 		    &tcp->tcp_rthdrdstoptslen,
12816 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12817 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen))
12818 			return (mp);
12819 	}
12820 	/* If app asked for routing headers and it has changed ... */
12821 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdr &&
12822 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
12823 	    (ipp->ipp_fields & IPPF_RTHDR),
12824 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
12825 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
12826 		addflag.crb_ipv6_recvrthdr = 1;
12827 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
12828 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
12829 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
12830 			return (mp);
12831 	}
12832 	/* If app asked for dest headers and it has changed ... */
12833 	if ((connp->conn_recv_ancillary.crb_ipv6_recvdstopts ||
12834 	    connp->conn_recv_ancillary.crb_old_ipv6_recvdstopts) &&
12835 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
12836 	    (ipp->ipp_fields & IPPF_DSTOPTS),
12837 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
12838 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
12839 		addflag.crb_ipv6_recvdstopts = 1;
12840 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
12841 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
12842 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
12843 			return (mp);
12844 	}
12845 
12846 	if (optlen == 0) {
12847 		/* Nothing to add */
12848 		return (mp);
12849 	}
12850 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
12851 	if (mp1 == NULL) {
12852 		/*
12853 		 * Defer sending ancillary data until the next TCP segment
12854 		 * arrives.
12855 		 */
12856 		return (mp);
12857 	}
12858 	mp1->b_cont = mp;
12859 	mp = mp1;
12860 	mp->b_wptr += sizeof (*todi) + optlen;
12861 	mp->b_datap->db_type = M_PROTO;
12862 	todi = (struct T_optdata_ind *)mp->b_rptr;
12863 	todi->PRIM_type = T_OPTDATA_IND;
12864 	todi->DATA_flag = 1;	/* MORE data */
12865 	todi->OPT_length = optlen;
12866 	todi->OPT_offset = sizeof (*todi);
12867 	optptr = (uchar_t *)&todi[1];
12868 	/*
12869 	 * If app asked for pktinfo and the index has changed ...
12870 	 * Note that the local address never changes for the connection.
12871 	 */
12872 	if (addflag.crb_ip_recvpktinfo) {
12873 		struct in6_pktinfo *pkti;
12874 		uint_t ifindex;
12875 
12876 		ifindex = ira->ira_ruifindex;
12877 		toh = (struct T_opthdr *)optptr;
12878 		toh->level = IPPROTO_IPV6;
12879 		toh->name = IPV6_PKTINFO;
12880 		toh->len = sizeof (*toh) + sizeof (*pkti);
12881 		toh->status = 0;
12882 		optptr += sizeof (*toh);
12883 		pkti = (struct in6_pktinfo *)optptr;
12884 		pkti->ipi6_addr = connp->conn_laddr_v6;
12885 		pkti->ipi6_ifindex = ifindex;
12886 		optptr += sizeof (*pkti);
12887 		ASSERT(OK_32PTR(optptr));
12888 		/* Save as "last" value */
12889 		tcp->tcp_recvifindex = ifindex;
12890 	}
12891 	/* If app asked for hoplimit and it has changed ... */
12892 	if (addflag.crb_ipv6_recvhoplimit) {
12893 		toh = (struct T_opthdr *)optptr;
12894 		toh->level = IPPROTO_IPV6;
12895 		toh->name = IPV6_HOPLIMIT;
12896 		toh->len = sizeof (*toh) + sizeof (uint_t);
12897 		toh->status = 0;
12898 		optptr += sizeof (*toh);
12899 		*(uint_t *)optptr = ipp->ipp_hoplimit;
12900 		optptr += sizeof (uint_t);
12901 		ASSERT(OK_32PTR(optptr));
12902 		/* Save as "last" value */
12903 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
12904 	}
12905 	/* If app asked for tclass and it has changed ... */
12906 	if (addflag.crb_ipv6_recvtclass) {
12907 		toh = (struct T_opthdr *)optptr;
12908 		toh->level = IPPROTO_IPV6;
12909 		toh->name = IPV6_TCLASS;
12910 		toh->len = sizeof (*toh) + sizeof (uint_t);
12911 		toh->status = 0;
12912 		optptr += sizeof (*toh);
12913 		*(uint_t *)optptr = ipp->ipp_tclass;
12914 		optptr += sizeof (uint_t);
12915 		ASSERT(OK_32PTR(optptr));
12916 		/* Save as "last" value */
12917 		tcp->tcp_recvtclass = ipp->ipp_tclass;
12918 	}
12919 	if (addflag.crb_ipv6_recvhopopts) {
12920 		toh = (struct T_opthdr *)optptr;
12921 		toh->level = IPPROTO_IPV6;
12922 		toh->name = IPV6_HOPOPTS;
12923 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
12924 		toh->status = 0;
12925 		optptr += sizeof (*toh);
12926 		bcopy((uchar_t *)ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
12927 		optptr += ipp->ipp_hopoptslen;
12928 		ASSERT(OK_32PTR(optptr));
12929 		/* Save as last value */
12930 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
12931 		    (ipp->ipp_fields & IPPF_HOPOPTS),
12932 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
12933 	}
12934 	if (addflag.crb_ipv6_recvrthdrdstopts) {
12935 		toh = (struct T_opthdr *)optptr;
12936 		toh->level = IPPROTO_IPV6;
12937 		toh->name = IPV6_RTHDRDSTOPTS;
12938 		toh->len = sizeof (*toh) + ipp->ipp_rthdrdstoptslen;
12939 		toh->status = 0;
12940 		optptr += sizeof (*toh);
12941 		bcopy(ipp->ipp_rthdrdstopts, optptr, ipp->ipp_rthdrdstoptslen);
12942 		optptr += ipp->ipp_rthdrdstoptslen;
12943 		ASSERT(OK_32PTR(optptr));
12944 		/* Save as last value */
12945 		ip_savebuf((void **)&tcp->tcp_rthdrdstopts,
12946 		    &tcp->tcp_rthdrdstoptslen,
12947 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12948 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
12949 	}
12950 	if (addflag.crb_ipv6_recvrthdr) {
12951 		toh = (struct T_opthdr *)optptr;
12952 		toh->level = IPPROTO_IPV6;
12953 		toh->name = IPV6_RTHDR;
12954 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
12955 		toh->status = 0;
12956 		optptr += sizeof (*toh);
12957 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
12958 		optptr += ipp->ipp_rthdrlen;
12959 		ASSERT(OK_32PTR(optptr));
12960 		/* Save as last value */
12961 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
12962 		    (ipp->ipp_fields & IPPF_RTHDR),
12963 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
12964 	}
12965 	if (addflag.crb_ipv6_recvdstopts) {
12966 		toh = (struct T_opthdr *)optptr;
12967 		toh->level = IPPROTO_IPV6;
12968 		toh->name = IPV6_DSTOPTS;
12969 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
12970 		toh->status = 0;
12971 		optptr += sizeof (*toh);
12972 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
12973 		optptr += ipp->ipp_dstoptslen;
12974 		ASSERT(OK_32PTR(optptr));
12975 		/* Save as last value */
12976 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
12977 		    (ipp->ipp_fields & IPPF_DSTOPTS),
12978 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
12979 	}
12980 	ASSERT(optptr == mp->b_wptr);
12981 	return (mp);
12982 }
12983 
12984 /* ARGSUSED */
12985 static void
12986 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
12987 {
12988 	conn_t	*connp = (conn_t *)arg;
12989 	tcp_t	*tcp = connp->conn_tcp;
12990 	queue_t	*q = connp->conn_rq;
12991 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12992 
12993 	ASSERT(!IPCL_IS_NONSTR(connp));
12994 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
12995 	tcp->tcp_rsrv_mp = mp;
12996 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
12997 
12998 	TCP_STAT(tcps, tcp_rsrv_calls);
12999 
13000 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
13001 		return;
13002 	}
13003 
13004 	if (tcp->tcp_fused) {
13005 		tcp_fuse_backenable(tcp);
13006 		return;
13007 	}
13008 
13009 	if (canputnext(q)) {
13010 		/* Not flow-controlled, open rwnd */
13011 		tcp->tcp_rwnd = connp->conn_rcvbuf;
13012 
13013 		/*
13014 		 * Send back a window update immediately if TCP is above
13015 		 * ESTABLISHED state and the increase of the rcv window
13016 		 * that the other side knows is at least 1 MSS after flow
13017 		 * control is lifted.
13018 		 */
13019 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
13020 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
13021 			tcp_xmit_ctl(NULL, tcp,
13022 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
13023 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
13024 		}
13025 	}
13026 }
13027 
13028 /*
13029  * The read side service routine is called mostly when we get back-enabled as a
13030  * result of flow control relief.  Since we don't actually queue anything in
13031  * TCP, we have no data to send out of here.  What we do is clear the receive
13032  * window, and send out a window update.
13033  */
13034 static void
13035 tcp_rsrv(queue_t *q)
13036 {
13037 	conn_t		*connp = Q_TO_CONN(q);
13038 	tcp_t		*tcp = connp->conn_tcp;
13039 	mblk_t		*mp;
13040 
13041 	/* No code does a putq on the read side */
13042 	ASSERT(q->q_first == NULL);
13043 
13044 	/*
13045 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
13046 	 * been run.  So just return.
13047 	 */
13048 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
13049 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
13050 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
13051 		return;
13052 	}
13053 	tcp->tcp_rsrv_mp = NULL;
13054 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
13055 
13056 	CONN_INC_REF(connp);
13057 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
13058 	    NULL, SQ_PROCESS, SQTAG_TCP_RSRV);
13059 }
13060 
13061 /*
13062  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
13063  * We do not allow the receive window to shrink.  After setting rwnd,
13064  * set the flow control hiwat of the stream.
13065  *
13066  * This function is called in 2 cases:
13067  *
13068  * 1) Before data transfer begins, in tcp_input_listener() for accepting a
13069  *    connection (passive open) and in tcp_input_data() for active connect.
13070  *    This is called after tcp_mss_set() when the desired MSS value is known.
13071  *    This makes sure that our window size is a mutiple of the other side's
13072  *    MSS.
13073  * 2) Handling SO_RCVBUF option.
13074  *
13075  * It is ASSUMED that the requested size is a multiple of the current MSS.
13076  *
13077  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
13078  * user requests so.
13079  */
13080 int
13081 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
13082 {
13083 	uint32_t	mss = tcp->tcp_mss;
13084 	uint32_t	old_max_rwnd;
13085 	uint32_t	max_transmittable_rwnd;
13086 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
13087 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13088 	conn_t		*connp = tcp->tcp_connp;
13089 
13090 	/*
13091 	 * Insist on a receive window that is at least
13092 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
13093 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
13094 	 * and delayed acknowledgement.
13095 	 */
13096 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
13097 
13098 	if (tcp->tcp_fused) {
13099 		size_t sth_hiwat;
13100 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
13101 
13102 		ASSERT(peer_tcp != NULL);
13103 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
13104 		if (!tcp_detached) {
13105 			(void) proto_set_rx_hiwat(connp->conn_rq, connp,
13106 			    sth_hiwat);
13107 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
13108 		}
13109 
13110 		/* Caller could have changed tcp_rwnd; update tha_win */
13111 		if (tcp->tcp_tcpha != NULL) {
13112 			tcp->tcp_tcpha->tha_win =
13113 			    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13114 		}
13115 		if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13116 			tcp->tcp_cwnd_max = rwnd;
13117 
13118 		/*
13119 		 * In the fusion case, the maxpsz stream head value of
13120 		 * our peer is set according to its send buffer size
13121 		 * and our receive buffer size; since the latter may
13122 		 * have changed we need to update the peer's maxpsz.
13123 		 */
13124 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
13125 		return (sth_hiwat);
13126 	}
13127 
13128 	if (tcp_detached)
13129 		old_max_rwnd = tcp->tcp_rwnd;
13130 	else
13131 		old_max_rwnd = connp->conn_rcvbuf;
13132 
13133 
13134 	/*
13135 	 * If window size info has already been exchanged, TCP should not
13136 	 * shrink the window.  Shrinking window is doable if done carefully.
13137 	 * We may add that support later.  But so far there is not a real
13138 	 * need to do that.
13139 	 */
13140 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
13141 		/* MSS may have changed, do a round up again. */
13142 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
13143 	}
13144 
13145 	/*
13146 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
13147 	 * can be applied even before the window scale option is decided.
13148 	 */
13149 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
13150 	if (rwnd > max_transmittable_rwnd) {
13151 		rwnd = max_transmittable_rwnd -
13152 		    (max_transmittable_rwnd % mss);
13153 		if (rwnd < mss)
13154 			rwnd = max_transmittable_rwnd;
13155 		/*
13156 		 * If we're over the limit we may have to back down tcp_rwnd.
13157 		 * The increment below won't work for us. So we set all three
13158 		 * here and the increment below will have no effect.
13159 		 */
13160 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
13161 	}
13162 	if (tcp->tcp_localnet) {
13163 		tcp->tcp_rack_abs_max =
13164 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
13165 	} else {
13166 		/*
13167 		 * For a remote host on a different subnet (through a router),
13168 		 * we ack every other packet to be conforming to RFC1122.
13169 		 * tcp_deferred_acks_max is default to 2.
13170 		 */
13171 		tcp->tcp_rack_abs_max =
13172 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
13173 	}
13174 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
13175 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
13176 	else
13177 		tcp->tcp_rack_cur_max = 0;
13178 	/*
13179 	 * Increment the current rwnd by the amount the maximum grew (we
13180 	 * can not overwrite it since we might be in the middle of a
13181 	 * connection.)
13182 	 */
13183 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
13184 	connp->conn_rcvbuf = rwnd;
13185 
13186 	/* Are we already connected? */
13187 	if (tcp->tcp_tcpha != NULL) {
13188 		tcp->tcp_tcpha->tha_win =
13189 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13190 	}
13191 
13192 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13193 		tcp->tcp_cwnd_max = rwnd;
13194 
13195 	if (tcp_detached)
13196 		return (rwnd);
13197 
13198 	tcp_set_recv_threshold(tcp, rwnd >> 3);
13199 
13200 	(void) proto_set_rx_hiwat(connp->conn_rq, connp, rwnd);
13201 	return (rwnd);
13202 }
13203 
13204 /*
13205  * Return SNMP stuff in buffer in mpdata.
13206  */
13207 mblk_t *
13208 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
13209 {
13210 	mblk_t			*mpdata;
13211 	mblk_t			*mp_conn_ctl = NULL;
13212 	mblk_t			*mp_conn_tail;
13213 	mblk_t			*mp_attr_ctl = NULL;
13214 	mblk_t			*mp_attr_tail;
13215 	mblk_t			*mp6_conn_ctl = NULL;
13216 	mblk_t			*mp6_conn_tail;
13217 	mblk_t			*mp6_attr_ctl = NULL;
13218 	mblk_t			*mp6_attr_tail;
13219 	struct opthdr		*optp;
13220 	mib2_tcpConnEntry_t	tce;
13221 	mib2_tcp6ConnEntry_t	tce6;
13222 	mib2_transportMLPEntry_t mlp;
13223 	connf_t			*connfp;
13224 	int			i;
13225 	boolean_t 		ispriv;
13226 	zoneid_t 		zoneid;
13227 	int			v4_conn_idx;
13228 	int			v6_conn_idx;
13229 	conn_t			*connp = Q_TO_CONN(q);
13230 	tcp_stack_t		*tcps;
13231 	ip_stack_t		*ipst;
13232 	mblk_t			*mp2ctl;
13233 
13234 	/*
13235 	 * make a copy of the original message
13236 	 */
13237 	mp2ctl = copymsg(mpctl);
13238 
13239 	if (mpctl == NULL ||
13240 	    (mpdata = mpctl->b_cont) == NULL ||
13241 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
13242 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
13243 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
13244 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
13245 		freemsg(mp_conn_ctl);
13246 		freemsg(mp_attr_ctl);
13247 		freemsg(mp6_conn_ctl);
13248 		freemsg(mp6_attr_ctl);
13249 		freemsg(mpctl);
13250 		freemsg(mp2ctl);
13251 		return (NULL);
13252 	}
13253 
13254 	ipst = connp->conn_netstack->netstack_ip;
13255 	tcps = connp->conn_netstack->netstack_tcp;
13256 
13257 	/* build table of connections -- need count in fixed part */
13258 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
13259 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
13260 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
13261 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
13262 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
13263 
13264 	ispriv =
13265 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
13266 	zoneid = Q_TO_CONN(q)->conn_zoneid;
13267 
13268 	v4_conn_idx = v6_conn_idx = 0;
13269 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
13270 
13271 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
13272 		ipst = tcps->tcps_netstack->netstack_ip;
13273 
13274 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
13275 
13276 		connp = NULL;
13277 
13278 		while ((connp =
13279 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
13280 			tcp_t *tcp;
13281 			boolean_t needattr;
13282 
13283 			if (connp->conn_zoneid != zoneid)
13284 				continue;	/* not in this zone */
13285 
13286 			tcp = connp->conn_tcp;
13287 			UPDATE_MIB(&tcps->tcps_mib,
13288 			    tcpHCInSegs, tcp->tcp_ibsegs);
13289 			tcp->tcp_ibsegs = 0;
13290 			UPDATE_MIB(&tcps->tcps_mib,
13291 			    tcpHCOutSegs, tcp->tcp_obsegs);
13292 			tcp->tcp_obsegs = 0;
13293 
13294 			tce6.tcp6ConnState = tce.tcpConnState =
13295 			    tcp_snmp_state(tcp);
13296 			if (tce.tcpConnState == MIB2_TCP_established ||
13297 			    tce.tcpConnState == MIB2_TCP_closeWait)
13298 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
13299 
13300 			needattr = B_FALSE;
13301 			bzero(&mlp, sizeof (mlp));
13302 			if (connp->conn_mlp_type != mlptSingle) {
13303 				if (connp->conn_mlp_type == mlptShared ||
13304 				    connp->conn_mlp_type == mlptBoth)
13305 					mlp.tme_flags |= MIB2_TMEF_SHARED;
13306 				if (connp->conn_mlp_type == mlptPrivate ||
13307 				    connp->conn_mlp_type == mlptBoth)
13308 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
13309 				needattr = B_TRUE;
13310 			}
13311 			if (connp->conn_anon_mlp) {
13312 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
13313 				needattr = B_TRUE;
13314 			}
13315 			switch (connp->conn_mac_mode) {
13316 			case CONN_MAC_DEFAULT:
13317 				break;
13318 			case CONN_MAC_AWARE:
13319 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
13320 				needattr = B_TRUE;
13321 				break;
13322 			case CONN_MAC_IMPLICIT:
13323 				mlp.tme_flags |= MIB2_TMEF_MACIMPLICIT;
13324 				needattr = B_TRUE;
13325 				break;
13326 			}
13327 			if (connp->conn_ixa->ixa_tsl != NULL) {
13328 				ts_label_t *tsl;
13329 
13330 				tsl = connp->conn_ixa->ixa_tsl;
13331 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
13332 				mlp.tme_doi = label2doi(tsl);
13333 				mlp.tme_label = *label2bslabel(tsl);
13334 				needattr = B_TRUE;
13335 			}
13336 
13337 			/* Create a message to report on IPv6 entries */
13338 			if (connp->conn_ipversion == IPV6_VERSION) {
13339 			tce6.tcp6ConnLocalAddress = connp->conn_laddr_v6;
13340 			tce6.tcp6ConnRemAddress = connp->conn_faddr_v6;
13341 			tce6.tcp6ConnLocalPort = ntohs(connp->conn_lport);
13342 			tce6.tcp6ConnRemPort = ntohs(connp->conn_fport);
13343 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET) {
13344 				tce6.tcp6ConnIfIndex =
13345 				    connp->conn_ixa->ixa_scopeid;
13346 			} else {
13347 				tce6.tcp6ConnIfIndex = connp->conn_bound_if;
13348 			}
13349 			/* Don't want just anybody seeing these... */
13350 			if (ispriv) {
13351 				tce6.tcp6ConnEntryInfo.ce_snxt =
13352 				    tcp->tcp_snxt;
13353 				tce6.tcp6ConnEntryInfo.ce_suna =
13354 				    tcp->tcp_suna;
13355 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13356 				    tcp->tcp_rnxt;
13357 				tce6.tcp6ConnEntryInfo.ce_rack =
13358 				    tcp->tcp_rack;
13359 			} else {
13360 				/*
13361 				 * Netstat, unfortunately, uses this to
13362 				 * get send/receive queue sizes.  How to fix?
13363 				 * Why not compute the difference only?
13364 				 */
13365 				tce6.tcp6ConnEntryInfo.ce_snxt =
13366 				    tcp->tcp_snxt - tcp->tcp_suna;
13367 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
13368 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13369 				    tcp->tcp_rnxt - tcp->tcp_rack;
13370 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
13371 			}
13372 
13373 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13374 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13375 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
13376 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
13377 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
13378 
13379 			tce6.tcp6ConnCreationProcess =
13380 			    (connp->conn_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
13381 			    connp->conn_cpid;
13382 			tce6.tcp6ConnCreationTime = connp->conn_open_time;
13383 
13384 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
13385 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
13386 
13387 			mlp.tme_connidx = v6_conn_idx++;
13388 			if (needattr)
13389 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
13390 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
13391 			}
13392 			/*
13393 			 * Create an IPv4 table entry for IPv4 entries and also
13394 			 * for IPv6 entries which are bound to in6addr_any
13395 			 * but don't have IPV6_V6ONLY set.
13396 			 * (i.e. anything an IPv4 peer could connect to)
13397 			 */
13398 			if (connp->conn_ipversion == IPV4_VERSION ||
13399 			    (tcp->tcp_state <= TCPS_LISTEN &&
13400 			    !connp->conn_ipv6_v6only &&
13401 			    IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6))) {
13402 				if (connp->conn_ipversion == IPV6_VERSION) {
13403 					tce.tcpConnRemAddress = INADDR_ANY;
13404 					tce.tcpConnLocalAddress = INADDR_ANY;
13405 				} else {
13406 					tce.tcpConnRemAddress =
13407 					    connp->conn_faddr_v4;
13408 					tce.tcpConnLocalAddress =
13409 					    connp->conn_laddr_v4;
13410 				}
13411 				tce.tcpConnLocalPort = ntohs(connp->conn_lport);
13412 				tce.tcpConnRemPort = ntohs(connp->conn_fport);
13413 				/* Don't want just anybody seeing these... */
13414 				if (ispriv) {
13415 					tce.tcpConnEntryInfo.ce_snxt =
13416 					    tcp->tcp_snxt;
13417 					tce.tcpConnEntryInfo.ce_suna =
13418 					    tcp->tcp_suna;
13419 					tce.tcpConnEntryInfo.ce_rnxt =
13420 					    tcp->tcp_rnxt;
13421 					tce.tcpConnEntryInfo.ce_rack =
13422 					    tcp->tcp_rack;
13423 				} else {
13424 					/*
13425 					 * Netstat, unfortunately, uses this to
13426 					 * get send/receive queue sizes.  How
13427 					 * to fix?
13428 					 * Why not compute the difference only?
13429 					 */
13430 					tce.tcpConnEntryInfo.ce_snxt =
13431 					    tcp->tcp_snxt - tcp->tcp_suna;
13432 					tce.tcpConnEntryInfo.ce_suna = 0;
13433 					tce.tcpConnEntryInfo.ce_rnxt =
13434 					    tcp->tcp_rnxt - tcp->tcp_rack;
13435 					tce.tcpConnEntryInfo.ce_rack = 0;
13436 				}
13437 
13438 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13439 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13440 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
13441 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
13442 				tce.tcpConnEntryInfo.ce_state =
13443 				    tcp->tcp_state;
13444 
13445 				tce.tcpConnCreationProcess =
13446 				    (connp->conn_cpid < 0) ?
13447 				    MIB2_UNKNOWN_PROCESS :
13448 				    connp->conn_cpid;
13449 				tce.tcpConnCreationTime = connp->conn_open_time;
13450 
13451 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
13452 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
13453 
13454 				mlp.tme_connidx = v4_conn_idx++;
13455 				if (needattr)
13456 					(void) snmp_append_data2(
13457 					    mp_attr_ctl->b_cont,
13458 					    &mp_attr_tail, (char *)&mlp,
13459 					    sizeof (mlp));
13460 			}
13461 		}
13462 	}
13463 
13464 	/* fixed length structure for IPv4 and IPv6 counters */
13465 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
13466 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
13467 	    sizeof (mib2_tcp6ConnEntry_t));
13468 	/* synchronize 32- and 64-bit counters */
13469 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
13470 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
13471 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
13472 	optp->level = MIB2_TCP;
13473 	optp->name = 0;
13474 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
13475 	    sizeof (tcps->tcps_mib));
13476 	optp->len = msgdsize(mpdata);
13477 	qreply(q, mpctl);
13478 
13479 	/* table of connections... */
13480 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
13481 	    sizeof (struct T_optmgmt_ack)];
13482 	optp->level = MIB2_TCP;
13483 	optp->name = MIB2_TCP_CONN;
13484 	optp->len = msgdsize(mp_conn_ctl->b_cont);
13485 	qreply(q, mp_conn_ctl);
13486 
13487 	/* table of MLP attributes... */
13488 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
13489 	    sizeof (struct T_optmgmt_ack)];
13490 	optp->level = MIB2_TCP;
13491 	optp->name = EXPER_XPORT_MLP;
13492 	optp->len = msgdsize(mp_attr_ctl->b_cont);
13493 	if (optp->len == 0)
13494 		freemsg(mp_attr_ctl);
13495 	else
13496 		qreply(q, mp_attr_ctl);
13497 
13498 	/* table of IPv6 connections... */
13499 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
13500 	    sizeof (struct T_optmgmt_ack)];
13501 	optp->level = MIB2_TCP6;
13502 	optp->name = MIB2_TCP6_CONN;
13503 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
13504 	qreply(q, mp6_conn_ctl);
13505 
13506 	/* table of IPv6 MLP attributes... */
13507 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
13508 	    sizeof (struct T_optmgmt_ack)];
13509 	optp->level = MIB2_TCP6;
13510 	optp->name = EXPER_XPORT_MLP;
13511 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
13512 	if (optp->len == 0)
13513 		freemsg(mp6_attr_ctl);
13514 	else
13515 		qreply(q, mp6_attr_ctl);
13516 	return (mp2ctl);
13517 }
13518 
13519 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
13520 /* ARGSUSED */
13521 int
13522 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
13523 {
13524 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
13525 
13526 	switch (level) {
13527 	case MIB2_TCP:
13528 		switch (name) {
13529 		case 13:
13530 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
13531 				return (0);
13532 			/* TODO: delete entry defined by tce */
13533 			return (1);
13534 		default:
13535 			return (0);
13536 		}
13537 	default:
13538 		return (1);
13539 	}
13540 }
13541 
13542 /* Translate TCP state to MIB2 TCP state. */
13543 static int
13544 tcp_snmp_state(tcp_t *tcp)
13545 {
13546 	if (tcp == NULL)
13547 		return (0);
13548 
13549 	switch (tcp->tcp_state) {
13550 	case TCPS_CLOSED:
13551 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
13552 	case TCPS_BOUND:
13553 		return (MIB2_TCP_closed);
13554 	case TCPS_LISTEN:
13555 		return (MIB2_TCP_listen);
13556 	case TCPS_SYN_SENT:
13557 		return (MIB2_TCP_synSent);
13558 	case TCPS_SYN_RCVD:
13559 		return (MIB2_TCP_synReceived);
13560 	case TCPS_ESTABLISHED:
13561 		return (MIB2_TCP_established);
13562 	case TCPS_CLOSE_WAIT:
13563 		return (MIB2_TCP_closeWait);
13564 	case TCPS_FIN_WAIT_1:
13565 		return (MIB2_TCP_finWait1);
13566 	case TCPS_CLOSING:
13567 		return (MIB2_TCP_closing);
13568 	case TCPS_LAST_ACK:
13569 		return (MIB2_TCP_lastAck);
13570 	case TCPS_FIN_WAIT_2:
13571 		return (MIB2_TCP_finWait2);
13572 	case TCPS_TIME_WAIT:
13573 		return (MIB2_TCP_timeWait);
13574 	default:
13575 		return (0);
13576 	}
13577 }
13578 
13579 /*
13580  * tcp_timer is the timer service routine.  It handles the retransmission,
13581  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
13582  * from the state of the tcp instance what kind of action needs to be done
13583  * at the time it is called.
13584  */
13585 static void
13586 tcp_timer(void *arg)
13587 {
13588 	mblk_t		*mp;
13589 	clock_t		first_threshold;
13590 	clock_t		second_threshold;
13591 	clock_t		ms;
13592 	uint32_t	mss;
13593 	conn_t		*connp = (conn_t *)arg;
13594 	tcp_t		*tcp = connp->conn_tcp;
13595 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13596 
13597 	tcp->tcp_timer_tid = 0;
13598 
13599 	if (tcp->tcp_fused)
13600 		return;
13601 
13602 	first_threshold =  tcp->tcp_first_timer_threshold;
13603 	second_threshold = tcp->tcp_second_timer_threshold;
13604 	switch (tcp->tcp_state) {
13605 	case TCPS_IDLE:
13606 	case TCPS_BOUND:
13607 	case TCPS_LISTEN:
13608 		return;
13609 	case TCPS_SYN_RCVD: {
13610 		tcp_t	*listener = tcp->tcp_listener;
13611 
13612 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
13613 			/* it's our first timeout */
13614 			tcp->tcp_syn_rcvd_timeout = 1;
13615 			mutex_enter(&listener->tcp_eager_lock);
13616 			listener->tcp_syn_rcvd_timeout++;
13617 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
13618 				/*
13619 				 * Make this eager available for drop if we
13620 				 * need to drop one to accomodate a new
13621 				 * incoming SYN request.
13622 				 */
13623 				MAKE_DROPPABLE(listener, tcp);
13624 			}
13625 			if (!listener->tcp_syn_defense &&
13626 			    (listener->tcp_syn_rcvd_timeout >
13627 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
13628 			    (tcps->tcps_conn_req_max_q0 > 200)) {
13629 				/* We may be under attack. Put on a defense. */
13630 				listener->tcp_syn_defense = B_TRUE;
13631 				cmn_err(CE_WARN, "High TCP connect timeout "
13632 				    "rate! System (port %d) may be under a "
13633 				    "SYN flood attack!",
13634 				    ntohs(listener->tcp_connp->conn_lport));
13635 
13636 				listener->tcp_ip_addr_cache = kmem_zalloc(
13637 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
13638 				    KM_NOSLEEP);
13639 			}
13640 			mutex_exit(&listener->tcp_eager_lock);
13641 		} else if (listener != NULL) {
13642 			mutex_enter(&listener->tcp_eager_lock);
13643 			tcp->tcp_syn_rcvd_timeout++;
13644 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
13645 			    !tcp->tcp_closemp_used) {
13646 				/*
13647 				 * This is our second timeout. Put the tcp in
13648 				 * the list of droppable eagers to allow it to
13649 				 * be dropped, if needed. We don't check
13650 				 * whether tcp_dontdrop is set or not to
13651 				 * protect ourselve from a SYN attack where a
13652 				 * remote host can spoof itself as one of the
13653 				 * good IP source and continue to hold
13654 				 * resources too long.
13655 				 */
13656 				MAKE_DROPPABLE(listener, tcp);
13657 			}
13658 			mutex_exit(&listener->tcp_eager_lock);
13659 		}
13660 	}
13661 		/* FALLTHRU */
13662 	case TCPS_SYN_SENT:
13663 		first_threshold =  tcp->tcp_first_ctimer_threshold;
13664 		second_threshold = tcp->tcp_second_ctimer_threshold;
13665 		break;
13666 	case TCPS_ESTABLISHED:
13667 	case TCPS_FIN_WAIT_1:
13668 	case TCPS_CLOSING:
13669 	case TCPS_CLOSE_WAIT:
13670 	case TCPS_LAST_ACK:
13671 		/* If we have data to rexmit */
13672 		if (tcp->tcp_suna != tcp->tcp_snxt) {
13673 			clock_t	time_to_wait;
13674 
13675 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
13676 			if (!tcp->tcp_xmit_head)
13677 				break;
13678 			time_to_wait = ddi_get_lbolt() -
13679 			    (clock_t)tcp->tcp_xmit_head->b_prev;
13680 			time_to_wait = tcp->tcp_rto -
13681 			    TICK_TO_MSEC(time_to_wait);
13682 			/*
13683 			 * If the timer fires too early, 1 clock tick earlier,
13684 			 * restart the timer.
13685 			 */
13686 			if (time_to_wait > msec_per_tick) {
13687 				TCP_STAT(tcps, tcp_timer_fire_early);
13688 				TCP_TIMER_RESTART(tcp, time_to_wait);
13689 				return;
13690 			}
13691 			/*
13692 			 * When we probe zero windows, we force the swnd open.
13693 			 * If our peer acks with a closed window swnd will be
13694 			 * set to zero by tcp_rput(). As long as we are
13695 			 * receiving acks tcp_rput will
13696 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
13697 			 * first and second interval actions.  NOTE: the timer
13698 			 * interval is allowed to continue its exponential
13699 			 * backoff.
13700 			 */
13701 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
13702 				if (connp->conn_debug) {
13703 					(void) strlog(TCP_MOD_ID, 0, 1,
13704 					    SL_TRACE, "tcp_timer: zero win");
13705 				}
13706 			} else {
13707 				/*
13708 				 * After retransmission, we need to do
13709 				 * slow start.  Set the ssthresh to one
13710 				 * half of current effective window and
13711 				 * cwnd to one MSS.  Also reset
13712 				 * tcp_cwnd_cnt.
13713 				 *
13714 				 * Note that if tcp_ssthresh is reduced because
13715 				 * of ECN, do not reduce it again unless it is
13716 				 * already one window of data away (tcp_cwr
13717 				 * should then be cleared) or this is a
13718 				 * timeout for a retransmitted segment.
13719 				 */
13720 				uint32_t npkt;
13721 
13722 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
13723 					npkt = ((tcp->tcp_timer_backoff ?
13724 					    tcp->tcp_cwnd_ssthresh :
13725 					    tcp->tcp_snxt -
13726 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
13727 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13728 					    tcp->tcp_mss;
13729 				}
13730 				tcp->tcp_cwnd = tcp->tcp_mss;
13731 				tcp->tcp_cwnd_cnt = 0;
13732 				if (tcp->tcp_ecn_ok) {
13733 					tcp->tcp_cwr = B_TRUE;
13734 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13735 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13736 				}
13737 			}
13738 			break;
13739 		}
13740 		/*
13741 		 * We have something to send yet we cannot send.  The
13742 		 * reason can be:
13743 		 *
13744 		 * 1. Zero send window: we need to do zero window probe.
13745 		 * 2. Zero cwnd: because of ECN, we need to "clock out
13746 		 * segments.
13747 		 * 3. SWS avoidance: receiver may have shrunk window,
13748 		 * reset our knowledge.
13749 		 *
13750 		 * Note that condition 2 can happen with either 1 or
13751 		 * 3.  But 1 and 3 are exclusive.
13752 		 */
13753 		if (tcp->tcp_unsent != 0) {
13754 			/*
13755 			 * Should not hold the zero-copy messages for too long.
13756 			 */
13757 			if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13758 				tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13759 				    tcp->tcp_xmit_head, B_TRUE);
13760 
13761 			if (tcp->tcp_cwnd == 0) {
13762 				/*
13763 				 * Set tcp_cwnd to 1 MSS so that a
13764 				 * new segment can be sent out.  We
13765 				 * are "clocking out" new data when
13766 				 * the network is really congested.
13767 				 */
13768 				ASSERT(tcp->tcp_ecn_ok);
13769 				tcp->tcp_cwnd = tcp->tcp_mss;
13770 			}
13771 			if (tcp->tcp_swnd == 0) {
13772 				/* Extend window for zero window probe */
13773 				tcp->tcp_swnd++;
13774 				tcp->tcp_zero_win_probe = B_TRUE;
13775 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
13776 			} else {
13777 				/*
13778 				 * Handle timeout from sender SWS avoidance.
13779 				 * Reset our knowledge of the max send window
13780 				 * since the receiver might have reduced its
13781 				 * receive buffer.  Avoid setting tcp_max_swnd
13782 				 * to one since that will essentially disable
13783 				 * the SWS checks.
13784 				 *
13785 				 * Note that since we don't have a SWS
13786 				 * state variable, if the timeout is set
13787 				 * for ECN but not for SWS, this
13788 				 * code will also be executed.  This is
13789 				 * fine as tcp_max_swnd is updated
13790 				 * constantly and it will not affect
13791 				 * anything.
13792 				 */
13793 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
13794 			}
13795 			tcp_wput_data(tcp, NULL, B_FALSE);
13796 			return;
13797 		}
13798 		/* Is there a FIN that needs to be to re retransmitted? */
13799 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13800 		    !tcp->tcp_fin_acked)
13801 			break;
13802 		/* Nothing to do, return without restarting timer. */
13803 		TCP_STAT(tcps, tcp_timer_fire_miss);
13804 		return;
13805 	case TCPS_FIN_WAIT_2:
13806 		/*
13807 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
13808 		 * We waited some time for for peer's FIN, but it hasn't
13809 		 * arrived.  We flush the connection now to avoid
13810 		 * case where the peer has rebooted.
13811 		 */
13812 		if (TCP_IS_DETACHED(tcp)) {
13813 			(void) tcp_clean_death(tcp, 0, 23);
13814 		} else {
13815 			TCP_TIMER_RESTART(tcp,
13816 			    tcps->tcps_fin_wait_2_flush_interval);
13817 		}
13818 		return;
13819 	case TCPS_TIME_WAIT:
13820 		(void) tcp_clean_death(tcp, 0, 24);
13821 		return;
13822 	default:
13823 		if (connp->conn_debug) {
13824 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
13825 			    "tcp_timer: strange state (%d) %s",
13826 			    tcp->tcp_state, tcp_display(tcp, NULL,
13827 			    DISP_PORT_ONLY));
13828 		}
13829 		return;
13830 	}
13831 
13832 	/*
13833 	 * If the system is under memory pressure or the max number of
13834 	 * connections have been established for the listener, be more
13835 	 * aggressive in aborting connections.
13836 	 */
13837 	if (tcps->tcps_reclaim || (tcp->tcp_listen_cnt != NULL &&
13838 	    tcp->tcp_listen_cnt->tlc_cnt > tcp->tcp_listen_cnt->tlc_max)) {
13839 		second_threshold = tcp_early_abort * SECONDS;
13840 	}
13841 
13842 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
13843 		/*
13844 		 * Should not hold the zero-copy messages for too long.
13845 		 */
13846 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13847 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13848 			    tcp->tcp_xmit_head, B_TRUE);
13849 
13850 		/*
13851 		 * For zero window probe, we need to send indefinitely,
13852 		 * unless we have not heard from the other side for some
13853 		 * time...
13854 		 */
13855 		if ((tcp->tcp_zero_win_probe == 0) ||
13856 		    (TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time) >
13857 		    second_threshold)) {
13858 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
13859 			/*
13860 			 * If TCP is in SYN_RCVD state, send back a
13861 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
13862 			 * should be zero in TCPS_SYN_RCVD state.
13863 			 */
13864 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
13865 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
13866 				    "in SYN_RCVD",
13867 				    tcp, tcp->tcp_snxt,
13868 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
13869 			}
13870 			(void) tcp_clean_death(tcp,
13871 			    tcp->tcp_client_errno ?
13872 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
13873 			return;
13874 		} else {
13875 			/*
13876 			 * If the system is under memory pressure, we also
13877 			 * abort connection in zero window probing.
13878 			 */
13879 			if (tcps->tcps_reclaim) {
13880 				(void) tcp_clean_death(tcp,
13881 				    tcp->tcp_client_errno ?
13882 				    tcp->tcp_client_errno : ETIMEDOUT, 25);
13883 				return;
13884 			}
13885 			/*
13886 			 * Set tcp_ms_we_have_waited to second_threshold
13887 			 * so that in next timeout, we will do the above
13888 			 * check (ddi_get_lbolt() - tcp_last_recv_time).
13889 			 * This is also to avoid overflow.
13890 			 *
13891 			 * We don't need to decrement tcp_timer_backoff
13892 			 * to avoid overflow because it will be decremented
13893 			 * later if new timeout value is greater than
13894 			 * tcp_rexmit_interval_max.  In the case when
13895 			 * tcp_rexmit_interval_max is greater than
13896 			 * second_threshold, it means that we will wait
13897 			 * longer than second_threshold to send the next
13898 			 * window probe.
13899 			 */
13900 			tcp->tcp_ms_we_have_waited = second_threshold;
13901 		}
13902 	} else if (ms > first_threshold) {
13903 		/*
13904 		 * Should not hold the zero-copy messages for too long.
13905 		 */
13906 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13907 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13908 			    tcp->tcp_xmit_head, B_TRUE);
13909 
13910 		/*
13911 		 * We have been retransmitting for too long...  The RTT
13912 		 * we calculated is probably incorrect.  Reinitialize it.
13913 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
13914 		 * tcp_rtt_update so that we won't accidentally cache a
13915 		 * bad value.  But only do this if this is not a zero
13916 		 * window probe.
13917 		 */
13918 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
13919 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
13920 			    (tcp->tcp_rtt_sa >> 5);
13921 			tcp->tcp_rtt_sa = 0;
13922 			tcp_ip_notify(tcp);
13923 			tcp->tcp_rtt_update = 0;
13924 		}
13925 	}
13926 	tcp->tcp_timer_backoff++;
13927 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
13928 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
13929 	    tcps->tcps_rexmit_interval_min) {
13930 		/*
13931 		 * This means the original RTO is tcp_rexmit_interval_min.
13932 		 * So we will use tcp_rexmit_interval_min as the RTO value
13933 		 * and do the backoff.
13934 		 */
13935 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
13936 	} else {
13937 		ms <<= tcp->tcp_timer_backoff;
13938 	}
13939 	if (ms > tcps->tcps_rexmit_interval_max) {
13940 		ms = tcps->tcps_rexmit_interval_max;
13941 		/*
13942 		 * ms is at max, decrement tcp_timer_backoff to avoid
13943 		 * overflow.
13944 		 */
13945 		tcp->tcp_timer_backoff--;
13946 	}
13947 	tcp->tcp_ms_we_have_waited += ms;
13948 	if (tcp->tcp_zero_win_probe == 0) {
13949 		tcp->tcp_rto = ms;
13950 	}
13951 	TCP_TIMER_RESTART(tcp, ms);
13952 	/*
13953 	 * This is after a timeout and tcp_rto is backed off.  Set
13954 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
13955 	 * restart the timer with a correct value.
13956 	 */
13957 	tcp->tcp_set_timer = 1;
13958 	mss = tcp->tcp_snxt - tcp->tcp_suna;
13959 	if (mss > tcp->tcp_mss)
13960 		mss = tcp->tcp_mss;
13961 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
13962 		mss = tcp->tcp_swnd;
13963 
13964 	if ((mp = tcp->tcp_xmit_head) != NULL)
13965 		mp->b_prev = (mblk_t *)ddi_get_lbolt();
13966 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
13967 	    B_TRUE);
13968 
13969 	/*
13970 	 * When slow start after retransmission begins, start with
13971 	 * this seq no.  tcp_rexmit_max marks the end of special slow
13972 	 * start phase.  tcp_snd_burst controls how many segments
13973 	 * can be sent because of an ack.
13974 	 */
13975 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13976 	tcp->tcp_snd_burst = TCP_CWND_SS;
13977 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13978 	    (tcp->tcp_unsent == 0)) {
13979 		tcp->tcp_rexmit_max = tcp->tcp_fss;
13980 	} else {
13981 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
13982 	}
13983 	tcp->tcp_rexmit = B_TRUE;
13984 	tcp->tcp_dupack_cnt = 0;
13985 
13986 	/*
13987 	 * Remove all rexmit SACK blk to start from fresh.
13988 	 */
13989 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
13990 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
13991 	if (mp == NULL) {
13992 		return;
13993 	}
13994 
13995 	tcp->tcp_csuna = tcp->tcp_snxt;
13996 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
13997 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
13998 	tcp_send_data(tcp, mp);
13999 
14000 }
14001 
14002 static int
14003 tcp_do_unbind(conn_t *connp)
14004 {
14005 	tcp_t *tcp = connp->conn_tcp;
14006 
14007 	switch (tcp->tcp_state) {
14008 	case TCPS_BOUND:
14009 	case TCPS_LISTEN:
14010 		break;
14011 	default:
14012 		return (-TOUTSTATE);
14013 	}
14014 
14015 	/*
14016 	 * Need to clean up all the eagers since after the unbind, segments
14017 	 * will no longer be delivered to this listener stream.
14018 	 */
14019 	mutex_enter(&tcp->tcp_eager_lock);
14020 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
14021 		tcp_eager_cleanup(tcp, 0);
14022 	}
14023 	mutex_exit(&tcp->tcp_eager_lock);
14024 
14025 	/* Clean up the listener connection counter if necessary. */
14026 	if (tcp->tcp_listen_cnt != NULL)
14027 		TCP_DECR_LISTEN_CNT(tcp);
14028 	connp->conn_laddr_v6 = ipv6_all_zeros;
14029 	connp->conn_saddr_v6 = ipv6_all_zeros;
14030 	tcp_bind_hash_remove(tcp);
14031 	tcp->tcp_state = TCPS_IDLE;
14032 
14033 	ip_unbind(connp);
14034 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
14035 
14036 	return (0);
14037 }
14038 
14039 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
14040 static void
14041 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
14042 {
14043 	conn_t *connp = tcp->tcp_connp;
14044 	int error;
14045 
14046 	error = tcp_do_unbind(connp);
14047 	if (error > 0) {
14048 		tcp_err_ack(tcp, mp, TSYSERR, error);
14049 	} else if (error < 0) {
14050 		tcp_err_ack(tcp, mp, -error, 0);
14051 	} else {
14052 		/* Send M_FLUSH according to TPI */
14053 		(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
14054 
14055 		mp = mi_tpi_ok_ack_alloc(mp);
14056 		if (mp != NULL)
14057 			putnext(connp->conn_rq, mp);
14058 	}
14059 }
14060 
14061 /*
14062  * Don't let port fall into the privileged range.
14063  * Since the extra privileged ports can be arbitrary we also
14064  * ensure that we exclude those from consideration.
14065  * tcp_g_epriv_ports is not sorted thus we loop over it until
14066  * there are no changes.
14067  *
14068  * Note: No locks are held when inspecting tcp_g_*epriv_ports
14069  * but instead the code relies on:
14070  * - the fact that the address of the array and its size never changes
14071  * - the atomic assignment of the elements of the array
14072  *
14073  * Returns 0 if there are no more ports available.
14074  *
14075  * TS note: skip multilevel ports.
14076  */
14077 static in_port_t
14078 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
14079 {
14080 	int i;
14081 	boolean_t restart = B_FALSE;
14082 	tcp_stack_t *tcps = tcp->tcp_tcps;
14083 
14084 	if (random && tcp_random_anon_port != 0) {
14085 		(void) random_get_pseudo_bytes((uint8_t *)&port,
14086 		    sizeof (in_port_t));
14087 		/*
14088 		 * Unless changed by a sys admin, the smallest anon port
14089 		 * is 32768 and the largest anon port is 65535.  It is
14090 		 * very likely (50%) for the random port to be smaller
14091 		 * than the smallest anon port.  When that happens,
14092 		 * add port % (anon port range) to the smallest anon
14093 		 * port to get the random port.  It should fall into the
14094 		 * valid anon port range.
14095 		 */
14096 		if (port < tcps->tcps_smallest_anon_port) {
14097 			port = tcps->tcps_smallest_anon_port +
14098 			    port % (tcps->tcps_largest_anon_port -
14099 			    tcps->tcps_smallest_anon_port);
14100 		}
14101 	}
14102 
14103 retry:
14104 	if (port < tcps->tcps_smallest_anon_port)
14105 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14106 
14107 	if (port > tcps->tcps_largest_anon_port) {
14108 		if (restart)
14109 			return (0);
14110 		restart = B_TRUE;
14111 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14112 	}
14113 
14114 	if (port < tcps->tcps_smallest_nonpriv_port)
14115 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
14116 
14117 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
14118 		if (port == tcps->tcps_g_epriv_ports[i]) {
14119 			port++;
14120 			/*
14121 			 * Make sure whether the port is in the
14122 			 * valid range.
14123 			 */
14124 			goto retry;
14125 		}
14126 	}
14127 	if (is_system_labeled() &&
14128 	    (i = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred), port,
14129 	    IPPROTO_TCP, B_TRUE)) != 0) {
14130 		port = i;
14131 		goto retry;
14132 	}
14133 	return (port);
14134 }
14135 
14136 /*
14137  * Return the next anonymous port in the privileged port range for
14138  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
14139  * downwards.  This is the same behavior as documented in the userland
14140  * library call rresvport(3N).
14141  *
14142  * TS note: skip multilevel ports.
14143  */
14144 static in_port_t
14145 tcp_get_next_priv_port(const tcp_t *tcp)
14146 {
14147 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
14148 	in_port_t nextport;
14149 	boolean_t restart = B_FALSE;
14150 	tcp_stack_t *tcps = tcp->tcp_tcps;
14151 retry:
14152 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
14153 	    next_priv_port >= IPPORT_RESERVED) {
14154 		next_priv_port = IPPORT_RESERVED - 1;
14155 		if (restart)
14156 			return (0);
14157 		restart = B_TRUE;
14158 	}
14159 	if (is_system_labeled() &&
14160 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred),
14161 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
14162 		next_priv_port = nextport;
14163 		goto retry;
14164 	}
14165 	return (next_priv_port--);
14166 }
14167 
14168 /* The write side r/w procedure. */
14169 
14170 #if CCS_STATS
14171 struct {
14172 	struct {
14173 		int64_t count, bytes;
14174 	} tot, hit;
14175 } wrw_stats;
14176 #endif
14177 
14178 /*
14179  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
14180  * messages.
14181  */
14182 /* ARGSUSED */
14183 static void
14184 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14185 {
14186 	conn_t	*connp = (conn_t *)arg;
14187 	tcp_t	*tcp = connp->conn_tcp;
14188 
14189 	ASSERT(DB_TYPE(mp) != M_IOCTL);
14190 	/*
14191 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
14192 	 * Once the close starts, streamhead and sockfs will not let any data
14193 	 * packets come down (close ensures that there are no threads using the
14194 	 * queue and no new threads will come down) but since qprocsoff()
14195 	 * hasn't happened yet, a M_FLUSH or some non data message might
14196 	 * get reflected back (in response to our own FLUSHRW) and get
14197 	 * processed after tcp_close() is done. The conn would still be valid
14198 	 * because a ref would have added but we need to check the state
14199 	 * before actually processing the packet.
14200 	 */
14201 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
14202 		freemsg(mp);
14203 		return;
14204 	}
14205 
14206 	switch (DB_TYPE(mp)) {
14207 	case M_IOCDATA:
14208 		tcp_wput_iocdata(tcp, mp);
14209 		break;
14210 	case M_FLUSH:
14211 		tcp_wput_flush(tcp, mp);
14212 		break;
14213 	default:
14214 		ip_wput_nondata(connp->conn_wq, mp);
14215 		break;
14216 	}
14217 }
14218 
14219 /*
14220  * The TCP fast path write put procedure.
14221  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
14222  */
14223 /* ARGSUSED */
14224 void
14225 tcp_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14226 {
14227 	int		len;
14228 	int		hdrlen;
14229 	int		plen;
14230 	mblk_t		*mp1;
14231 	uchar_t		*rptr;
14232 	uint32_t	snxt;
14233 	tcpha_t		*tcpha;
14234 	struct datab	*db;
14235 	uint32_t	suna;
14236 	uint32_t	mss;
14237 	ipaddr_t	*dst;
14238 	ipaddr_t	*src;
14239 	uint32_t	sum;
14240 	int		usable;
14241 	conn_t		*connp = (conn_t *)arg;
14242 	tcp_t		*tcp = connp->conn_tcp;
14243 	uint32_t	msize;
14244 	tcp_stack_t	*tcps = tcp->tcp_tcps;
14245 	ip_xmit_attr_t	*ixa;
14246 	clock_t		now;
14247 
14248 	/*
14249 	 * Try and ASSERT the minimum possible references on the
14250 	 * conn early enough. Since we are executing on write side,
14251 	 * the connection is obviously not detached and that means
14252 	 * there is a ref each for TCP and IP. Since we are behind
14253 	 * the squeue, the minimum references needed are 3. If the
14254 	 * conn is in classifier hash list, there should be an
14255 	 * extra ref for that (we check both the possibilities).
14256 	 */
14257 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14258 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14259 
14260 	ASSERT(DB_TYPE(mp) == M_DATA);
14261 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
14262 
14263 	mutex_enter(&tcp->tcp_non_sq_lock);
14264 	tcp->tcp_squeue_bytes -= msize;
14265 	mutex_exit(&tcp->tcp_non_sq_lock);
14266 
14267 	/* Bypass tcp protocol for fused tcp loopback */
14268 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
14269 		return;
14270 
14271 	mss = tcp->tcp_mss;
14272 	/*
14273 	 * If ZEROCOPY has turned off, try not to send any zero-copy message
14274 	 * down. Do backoff, now.
14275 	 */
14276 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on)
14277 		mp = tcp_zcopy_backoff(tcp, mp, B_FALSE);
14278 
14279 
14280 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
14281 	len = (int)(mp->b_wptr - mp->b_rptr);
14282 
14283 	/*
14284 	 * Criteria for fast path:
14285 	 *
14286 	 *   1. no unsent data
14287 	 *   2. single mblk in request
14288 	 *   3. connection established
14289 	 *   4. data in mblk
14290 	 *   5. len <= mss
14291 	 *   6. no tcp_valid bits
14292 	 */
14293 	if ((tcp->tcp_unsent != 0) ||
14294 	    (tcp->tcp_cork) ||
14295 	    (mp->b_cont != NULL) ||
14296 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
14297 	    (len == 0) ||
14298 	    (len > mss) ||
14299 	    (tcp->tcp_valid_bits != 0)) {
14300 		tcp_wput_data(tcp, mp, B_FALSE);
14301 		return;
14302 	}
14303 
14304 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
14305 	ASSERT(tcp->tcp_fin_sent == 0);
14306 
14307 	/* queue new packet onto retransmission queue */
14308 	if (tcp->tcp_xmit_head == NULL) {
14309 		tcp->tcp_xmit_head = mp;
14310 	} else {
14311 		tcp->tcp_xmit_last->b_cont = mp;
14312 	}
14313 	tcp->tcp_xmit_last = mp;
14314 	tcp->tcp_xmit_tail = mp;
14315 
14316 	/* find out how much we can send */
14317 	/* BEGIN CSTYLED */
14318 	/*
14319 	 *    un-acked	   usable
14320 	 *  |--------------|-----------------|
14321 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
14322 	 */
14323 	/* END CSTYLED */
14324 
14325 	/* start sending from tcp_snxt */
14326 	snxt = tcp->tcp_snxt;
14327 
14328 	/*
14329 	 * Check to see if this connection has been idled for some
14330 	 * time and no ACK is expected.  If it is, we need to slow
14331 	 * start again to get back the connection's "self-clock" as
14332 	 * described in VJ's paper.
14333 	 *
14334 	 * Reinitialize tcp_cwnd after idle.
14335 	 */
14336 	now = LBOLT_FASTPATH;
14337 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
14338 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
14339 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
14340 	}
14341 
14342 	usable = tcp->tcp_swnd;		/* tcp window size */
14343 	if (usable > tcp->tcp_cwnd)
14344 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
14345 	usable -= snxt;		/* subtract stuff already sent */
14346 	suna = tcp->tcp_suna;
14347 	usable += suna;
14348 	/* usable can be < 0 if the congestion window is smaller */
14349 	if (len > usable) {
14350 		/* Can't send complete M_DATA in one shot */
14351 		goto slow;
14352 	}
14353 
14354 	mutex_enter(&tcp->tcp_non_sq_lock);
14355 	if (tcp->tcp_flow_stopped &&
14356 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
14357 		tcp_clrqfull(tcp);
14358 	}
14359 	mutex_exit(&tcp->tcp_non_sq_lock);
14360 
14361 	/*
14362 	 * determine if anything to send (Nagle).
14363 	 *
14364 	 *   1. len < tcp_mss (i.e. small)
14365 	 *   2. unacknowledged data present
14366 	 *   3. len < nagle limit
14367 	 *   4. last packet sent < nagle limit (previous packet sent)
14368 	 */
14369 	if ((len < mss) && (snxt != suna) &&
14370 	    (len < (int)tcp->tcp_naglim) &&
14371 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
14372 		/*
14373 		 * This was the first unsent packet and normally
14374 		 * mss < xmit_hiwater so there is no need to worry
14375 		 * about flow control. The next packet will go
14376 		 * through the flow control check in tcp_wput_data().
14377 		 */
14378 		/* leftover work from above */
14379 		tcp->tcp_unsent = len;
14380 		tcp->tcp_xmit_tail_unsent = len;
14381 
14382 		return;
14383 	}
14384 
14385 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
14386 
14387 	if (snxt == suna) {
14388 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14389 	}
14390 
14391 	/* we have always sent something */
14392 	tcp->tcp_rack_cnt = 0;
14393 
14394 	tcp->tcp_snxt = snxt + len;
14395 	tcp->tcp_rack = tcp->tcp_rnxt;
14396 
14397 	if ((mp1 = dupb(mp)) == 0)
14398 		goto no_memory;
14399 	mp->b_prev = (mblk_t *)(uintptr_t)now;
14400 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
14401 
14402 	/* adjust tcp header information */
14403 	tcpha = tcp->tcp_tcpha;
14404 	tcpha->tha_flags = (TH_ACK|TH_PUSH);
14405 
14406 	sum = len + connp->conn_ht_ulp_len + connp->conn_sum;
14407 	sum = (sum >> 16) + (sum & 0xFFFF);
14408 	tcpha->tha_sum = htons(sum);
14409 
14410 	tcpha->tha_seq = htonl(snxt);
14411 
14412 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
14413 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
14414 	BUMP_LOCAL(tcp->tcp_obsegs);
14415 
14416 	/* Update the latest receive window size in TCP header. */
14417 	tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
14418 
14419 	tcp->tcp_last_sent_len = (ushort_t)len;
14420 
14421 	plen = len + connp->conn_ht_iphc_len;
14422 
14423 	ixa = connp->conn_ixa;
14424 	ixa->ixa_pktlen = plen;
14425 
14426 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
14427 		tcp->tcp_ipha->ipha_length = htons(plen);
14428 	} else {
14429 		tcp->tcp_ip6h->ip6_plen = htons(plen - IPV6_HDR_LEN);
14430 	}
14431 
14432 	/* see if we need to allocate a mblk for the headers */
14433 	hdrlen = connp->conn_ht_iphc_len;
14434 	rptr = mp1->b_rptr - hdrlen;
14435 	db = mp1->b_datap;
14436 	if ((db->db_ref != 2) || rptr < db->db_base ||
14437 	    (!OK_32PTR(rptr))) {
14438 		/* NOTE: we assume allocb returns an OK_32PTR */
14439 		mp = allocb(hdrlen + tcps->tcps_wroff_xtra, BPRI_MED);
14440 		if (!mp) {
14441 			freemsg(mp1);
14442 			goto no_memory;
14443 		}
14444 		mp->b_cont = mp1;
14445 		mp1 = mp;
14446 		/* Leave room for Link Level header */
14447 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
14448 		mp1->b_wptr = &rptr[hdrlen];
14449 	}
14450 	mp1->b_rptr = rptr;
14451 
14452 	/* Fill in the timestamp option. */
14453 	if (tcp->tcp_snd_ts_ok) {
14454 		uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
14455 
14456 		U32_TO_BE32(llbolt,
14457 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
14458 		U32_TO_BE32(tcp->tcp_ts_recent,
14459 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
14460 	} else {
14461 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
14462 	}
14463 
14464 	/* copy header into outgoing packet */
14465 	dst = (ipaddr_t *)rptr;
14466 	src = (ipaddr_t *)connp->conn_ht_iphc;
14467 	dst[0] = src[0];
14468 	dst[1] = src[1];
14469 	dst[2] = src[2];
14470 	dst[3] = src[3];
14471 	dst[4] = src[4];
14472 	dst[5] = src[5];
14473 	dst[6] = src[6];
14474 	dst[7] = src[7];
14475 	dst[8] = src[8];
14476 	dst[9] = src[9];
14477 	if (hdrlen -= 40) {
14478 		hdrlen >>= 2;
14479 		dst += 10;
14480 		src += 10;
14481 		do {
14482 			*dst++ = *src++;
14483 		} while (--hdrlen);
14484 	}
14485 
14486 	/*
14487 	 * Set the ECN info in the TCP header.  Note that this
14488 	 * is not the template header.
14489 	 */
14490 	if (tcp->tcp_ecn_ok) {
14491 		SET_ECT(tcp, rptr);
14492 
14493 		tcpha = (tcpha_t *)(rptr + ixa->ixa_ip_hdr_length);
14494 		if (tcp->tcp_ecn_echo_on)
14495 			tcpha->tha_flags |= TH_ECE;
14496 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
14497 			tcpha->tha_flags |= TH_CWR;
14498 			tcp->tcp_ecn_cwr_sent = B_TRUE;
14499 		}
14500 	}
14501 
14502 	if (tcp->tcp_ip_forward_progress) {
14503 		tcp->tcp_ip_forward_progress = B_FALSE;
14504 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
14505 	} else {
14506 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
14507 	}
14508 	tcp_send_data(tcp, mp1);
14509 	return;
14510 
14511 	/*
14512 	 * If we ran out of memory, we pretend to have sent the packet
14513 	 * and that it was lost on the wire.
14514 	 */
14515 no_memory:
14516 	return;
14517 
14518 slow:
14519 	/* leftover work from above */
14520 	tcp->tcp_unsent = len;
14521 	tcp->tcp_xmit_tail_unsent = len;
14522 	tcp_wput_data(tcp, NULL, B_FALSE);
14523 }
14524 
14525 /*
14526  * This runs at the tail end of accept processing on the squeue of the
14527  * new connection.
14528  */
14529 /* ARGSUSED */
14530 void
14531 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14532 {
14533 	conn_t			*connp = (conn_t *)arg;
14534 	tcp_t			*tcp = connp->conn_tcp;
14535 	queue_t			*q = connp->conn_rq;
14536 	tcp_stack_t		*tcps = tcp->tcp_tcps;
14537 	/* socket options */
14538 	struct sock_proto_props	sopp;
14539 
14540 	/* We should just receive a single mblk that fits a T_discon_ind */
14541 	ASSERT(mp->b_cont == NULL);
14542 
14543 	/*
14544 	 * Drop the eager's ref on the listener, that was placed when
14545 	 * this eager began life in tcp_input_listener.
14546 	 */
14547 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
14548 	if (IPCL_IS_NONSTR(connp)) {
14549 		/* Safe to free conn_ind message */
14550 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
14551 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14552 	}
14553 
14554 	tcp->tcp_detached = B_FALSE;
14555 
14556 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
14557 		/*
14558 		 * Someone blewoff the eager before we could finish
14559 		 * the accept.
14560 		 *
14561 		 * The only reason eager exists it because we put in
14562 		 * a ref on it when conn ind went up. We need to send
14563 		 * a disconnect indication up while the last reference
14564 		 * on the eager will be dropped by the squeue when we
14565 		 * return.
14566 		 */
14567 		ASSERT(tcp->tcp_listener == NULL);
14568 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
14569 			if (IPCL_IS_NONSTR(connp)) {
14570 				ASSERT(tcp->tcp_issocket);
14571 				(*connp->conn_upcalls->su_disconnected)(
14572 				    connp->conn_upper_handle, tcp->tcp_connid,
14573 				    ECONNREFUSED);
14574 				freemsg(mp);
14575 			} else {
14576 				struct	T_discon_ind	*tdi;
14577 
14578 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
14579 				/*
14580 				 * Let us reuse the incoming mblk to avoid
14581 				 * memory allocation failure problems. We know
14582 				 * that the size of the incoming mblk i.e.
14583 				 * stroptions is greater than sizeof
14584 				 * T_discon_ind.
14585 				 */
14586 				ASSERT(DB_REF(mp) == 1);
14587 				ASSERT(MBLKSIZE(mp) >=
14588 				    sizeof (struct T_discon_ind));
14589 
14590 				DB_TYPE(mp) = M_PROTO;
14591 				((union T_primitives *)mp->b_rptr)->type =
14592 				    T_DISCON_IND;
14593 				tdi = (struct T_discon_ind *)mp->b_rptr;
14594 				if (tcp->tcp_issocket) {
14595 					tdi->DISCON_reason = ECONNREFUSED;
14596 					tdi->SEQ_number = 0;
14597 				} else {
14598 					tdi->DISCON_reason = ENOPROTOOPT;
14599 					tdi->SEQ_number =
14600 					    tcp->tcp_conn_req_seqnum;
14601 				}
14602 				mp->b_wptr = mp->b_rptr +
14603 				    sizeof (struct T_discon_ind);
14604 				putnext(q, mp);
14605 			}
14606 		}
14607 		tcp->tcp_hard_binding = B_FALSE;
14608 		return;
14609 	}
14610 
14611 	/*
14612 	 * This is the first time we run on the correct
14613 	 * queue after tcp_accept. So fix all the q parameters
14614 	 * here.
14615 	 */
14616 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
14617 	sopp.sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
14618 
14619 	sopp.sopp_rxhiwat = tcp->tcp_fused ?
14620 	    tcp_fuse_set_rcv_hiwat(tcp, connp->conn_rcvbuf) :
14621 	    connp->conn_rcvbuf;
14622 
14623 	/*
14624 	 * Determine what write offset value to use depending on SACK and
14625 	 * whether the endpoint is fused or not.
14626 	 */
14627 	if (tcp->tcp_fused) {
14628 		ASSERT(tcp->tcp_loopback);
14629 		ASSERT(tcp->tcp_loopback_peer != NULL);
14630 		/*
14631 		 * For fused tcp loopback, set the stream head's write
14632 		 * offset value to zero since we won't be needing any room
14633 		 * for TCP/IP headers.  This would also improve performance
14634 		 * since it would reduce the amount of work done by kmem.
14635 		 * Non-fused tcp loopback case is handled separately below.
14636 		 */
14637 		sopp.sopp_wroff = 0;
14638 		/*
14639 		 * Update the peer's transmit parameters according to
14640 		 * our recently calculated high water mark value.
14641 		 */
14642 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
14643 	} else if (tcp->tcp_snd_sack_ok) {
14644 		sopp.sopp_wroff = connp->conn_ht_iphc_allocated +
14645 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14646 	} else {
14647 		sopp.sopp_wroff = connp->conn_ht_iphc_len +
14648 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14649 	}
14650 
14651 	/*
14652 	 * If this is endpoint is handling SSL, then reserve extra
14653 	 * offset and space at the end.
14654 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
14655 	 * overriding the previous setting. The extra cost of signing and
14656 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
14657 	 * instead of a single contiguous one by the stream head
14658 	 * largely outweighs the statistical reduction of ACKs, when
14659 	 * applicable. The peer will also save on decryption and verification
14660 	 * costs.
14661 	 */
14662 	if (tcp->tcp_kssl_ctx != NULL) {
14663 		sopp.sopp_wroff += SSL3_WROFFSET;
14664 
14665 		sopp.sopp_flags |= SOCKOPT_TAIL;
14666 		sopp.sopp_tail = SSL3_MAX_TAIL_LEN;
14667 
14668 		sopp.sopp_flags |= SOCKOPT_ZCOPY;
14669 		sopp.sopp_zcopyflag = ZCVMUNSAFE;
14670 
14671 		sopp.sopp_maxblk = SSL3_MAX_RECORD_LEN;
14672 	}
14673 
14674 	/* Send the options up */
14675 	if (IPCL_IS_NONSTR(connp)) {
14676 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14677 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14678 			ASSERT(sopp.sopp_flags & SOCKOPT_ZCOPY);
14679 		}
14680 		if (tcp->tcp_loopback) {
14681 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
14682 			sopp.sopp_loopback = B_TRUE;
14683 		}
14684 		(*connp->conn_upcalls->su_set_proto_props)
14685 		    (connp->conn_upper_handle, &sopp);
14686 		freemsg(mp);
14687 	} else {
14688 		/*
14689 		 * Let us reuse the incoming mblk to avoid
14690 		 * memory allocation failure problems. We know
14691 		 * that the size of the incoming mblk is at least
14692 		 * stroptions
14693 		 */
14694 		struct stroptions *stropt;
14695 
14696 		ASSERT(DB_REF(mp) == 1);
14697 		ASSERT(MBLKSIZE(mp) >= sizeof (struct stroptions));
14698 
14699 		DB_TYPE(mp) = M_SETOPTS;
14700 		stropt = (struct stroptions *)mp->b_rptr;
14701 		mp->b_wptr = mp->b_rptr + sizeof (struct stroptions);
14702 		stropt = (struct stroptions *)mp->b_rptr;
14703 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
14704 		stropt->so_hiwat = sopp.sopp_rxhiwat;
14705 		stropt->so_wroff = sopp.sopp_wroff;
14706 		stropt->so_maxblk = sopp.sopp_maxblk;
14707 
14708 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14709 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14710 
14711 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
14712 			stropt->so_tail = sopp.sopp_tail;
14713 			stropt->so_copyopt = sopp.sopp_zcopyflag;
14714 		}
14715 
14716 		/* Send the options up */
14717 		putnext(q, mp);
14718 	}
14719 
14720 	/*
14721 	 * Pass up any data and/or a fin that has been received.
14722 	 *
14723 	 * Adjust receive window in case it had decreased
14724 	 * (because there is data <=> tcp_rcv_list != NULL)
14725 	 * while the connection was detached. Note that
14726 	 * in case the eager was flow-controlled, w/o this
14727 	 * code, the rwnd may never open up again!
14728 	 */
14729 	if (tcp->tcp_rcv_list != NULL) {
14730 		if (IPCL_IS_NONSTR(connp)) {
14731 			mblk_t *mp;
14732 			int space_left;
14733 			int error;
14734 			boolean_t push = B_TRUE;
14735 
14736 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
14737 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
14738 			    &push) >= 0) {
14739 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14740 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14741 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14742 					tcp_xmit_ctl(NULL,
14743 					    tcp, (tcp->tcp_swnd == 0) ?
14744 					    tcp->tcp_suna : tcp->tcp_snxt,
14745 					    tcp->tcp_rnxt, TH_ACK);
14746 				}
14747 			}
14748 			while ((mp = tcp->tcp_rcv_list) != NULL) {
14749 				push = B_TRUE;
14750 				tcp->tcp_rcv_list = mp->b_next;
14751 				mp->b_next = NULL;
14752 				space_left = (*connp->conn_upcalls->su_recv)
14753 				    (connp->conn_upper_handle, mp, msgdsize(mp),
14754 				    0, &error, &push);
14755 				if (space_left < 0) {
14756 					/*
14757 					 * We should never be in middle of a
14758 					 * fallback, the squeue guarantees that.
14759 					 */
14760 					ASSERT(error != EOPNOTSUPP);
14761 				}
14762 			}
14763 			tcp->tcp_rcv_last_head = NULL;
14764 			tcp->tcp_rcv_last_tail = NULL;
14765 			tcp->tcp_rcv_cnt = 0;
14766 		} else {
14767 			/* We drain directly in case of fused tcp loopback */
14768 
14769 			if (!tcp->tcp_fused && canputnext(q)) {
14770 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14771 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14772 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14773 					tcp_xmit_ctl(NULL,
14774 					    tcp, (tcp->tcp_swnd == 0) ?
14775 					    tcp->tcp_suna : tcp->tcp_snxt,
14776 					    tcp->tcp_rnxt, TH_ACK);
14777 				}
14778 			}
14779 
14780 			(void) tcp_rcv_drain(tcp);
14781 		}
14782 
14783 		/*
14784 		 * For fused tcp loopback, back-enable peer endpoint
14785 		 * if it's currently flow-controlled.
14786 		 */
14787 		if (tcp->tcp_fused) {
14788 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
14789 
14790 			ASSERT(peer_tcp != NULL);
14791 			ASSERT(peer_tcp->tcp_fused);
14792 
14793 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
14794 			if (peer_tcp->tcp_flow_stopped) {
14795 				tcp_clrqfull(peer_tcp);
14796 				TCP_STAT(tcps, tcp_fusion_backenabled);
14797 			}
14798 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
14799 		}
14800 	}
14801 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14802 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
14803 		tcp->tcp_ordrel_done = B_TRUE;
14804 		if (IPCL_IS_NONSTR(connp)) {
14805 			ASSERT(tcp->tcp_ordrel_mp == NULL);
14806 			(*connp->conn_upcalls->su_opctl)(
14807 			    connp->conn_upper_handle,
14808 			    SOCK_OPCTL_SHUT_RECV, 0);
14809 		} else {
14810 			mp = tcp->tcp_ordrel_mp;
14811 			tcp->tcp_ordrel_mp = NULL;
14812 			putnext(q, mp);
14813 		}
14814 	}
14815 	tcp->tcp_hard_binding = B_FALSE;
14816 
14817 	if (connp->conn_keepalive) {
14818 		tcp->tcp_ka_last_intrvl = 0;
14819 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
14820 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
14821 	}
14822 
14823 	/*
14824 	 * At this point, eager is fully established and will
14825 	 * have the following references -
14826 	 *
14827 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
14828 	 * 1 reference for the squeue which will be dropped by the squeue as
14829 	 *	soon as this function returns.
14830 	 * There will be 1 additonal reference for being in classifier
14831 	 *	hash list provided something bad hasn't happened.
14832 	 */
14833 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14834 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14835 }
14836 
14837 /*
14838  * The function called through squeue to get behind listener's perimeter to
14839  * send a deferred conn_ind.
14840  */
14841 /* ARGSUSED */
14842 void
14843 tcp_send_pending(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14844 {
14845 	conn_t	*lconnp = (conn_t *)arg;
14846 	tcp_t *listener = lconnp->conn_tcp;
14847 	struct T_conn_ind *conn_ind;
14848 	tcp_t *tcp;
14849 
14850 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
14851 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
14852 	    conn_ind->OPT_length);
14853 
14854 	if (listener->tcp_state != TCPS_LISTEN) {
14855 		/*
14856 		 * If listener has closed, it would have caused a
14857 		 * a cleanup/blowoff to happen for the eager, so
14858 		 * we don't need to do anything more.
14859 		 */
14860 		freemsg(mp);
14861 		return;
14862 	}
14863 
14864 	tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
14865 }
14866 
14867 /*
14868  * Common to TPI and sockfs accept code.
14869  */
14870 /* ARGSUSED2 */
14871 static int
14872 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
14873 {
14874 	tcp_t *listener, *eager;
14875 	mblk_t *discon_mp;
14876 
14877 	listener = lconnp->conn_tcp;
14878 	ASSERT(listener->tcp_state == TCPS_LISTEN);
14879 	eager = econnp->conn_tcp;
14880 	ASSERT(eager->tcp_listener != NULL);
14881 
14882 	/*
14883 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
14884 	 * use it if something failed.
14885 	 */
14886 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
14887 	    sizeof (struct stroptions)), BPRI_HI);
14888 
14889 	if (discon_mp == NULL) {
14890 		return (-TPROTO);
14891 	}
14892 	eager->tcp_issocket = B_TRUE;
14893 
14894 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
14895 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
14896 	ASSERT(econnp->conn_netstack ==
14897 	    listener->tcp_connp->conn_netstack);
14898 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
14899 
14900 	/* Put the ref for IP */
14901 	CONN_INC_REF(econnp);
14902 
14903 	/*
14904 	 * We should have minimum of 3 references on the conn
14905 	 * at this point. One each for TCP and IP and one for
14906 	 * the T_conn_ind that was sent up when the 3-way handshake
14907 	 * completed. In the normal case we would also have another
14908 	 * reference (making a total of 4) for the conn being in the
14909 	 * classifier hash list. However the eager could have received
14910 	 * an RST subsequently and tcp_closei_local could have removed
14911 	 * the eager from the classifier hash list, hence we can't
14912 	 * assert that reference.
14913 	 */
14914 	ASSERT(econnp->conn_ref >= 3);
14915 
14916 	mutex_enter(&listener->tcp_eager_lock);
14917 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
14918 
14919 		tcp_t *tail;
14920 		tcp_t *tcp;
14921 		mblk_t *mp1;
14922 
14923 		tcp = listener->tcp_eager_prev_q0;
14924 		/*
14925 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
14926 		 * deferred T_conn_ind queue. We need to get to the head
14927 		 * of the queue in order to send up T_conn_ind the same
14928 		 * order as how the 3WHS is completed.
14929 		 */
14930 		while (tcp != listener) {
14931 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
14932 			    !tcp->tcp_kssl_pending)
14933 				break;
14934 			else
14935 				tcp = tcp->tcp_eager_prev_q0;
14936 		}
14937 		/* None of the pending eagers can be sent up now */
14938 		if (tcp == listener)
14939 			goto no_more_eagers;
14940 
14941 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
14942 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14943 		/* Move from q0 to q */
14944 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
14945 		listener->tcp_conn_req_cnt_q0--;
14946 		listener->tcp_conn_req_cnt_q++;
14947 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
14948 		    tcp->tcp_eager_prev_q0;
14949 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
14950 		    tcp->tcp_eager_next_q0;
14951 		tcp->tcp_eager_prev_q0 = NULL;
14952 		tcp->tcp_eager_next_q0 = NULL;
14953 		tcp->tcp_conn_def_q0 = B_FALSE;
14954 
14955 		/* Make sure the tcp isn't in the list of droppables */
14956 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
14957 		    tcp->tcp_eager_prev_drop_q0 == NULL);
14958 
14959 		/*
14960 		 * Insert at end of the queue because sockfs sends
14961 		 * down T_CONN_RES in chronological order. Leaving
14962 		 * the older conn indications at front of the queue
14963 		 * helps reducing search time.
14964 		 */
14965 		tail = listener->tcp_eager_last_q;
14966 		if (tail != NULL) {
14967 			tail->tcp_eager_next_q = tcp;
14968 		} else {
14969 			listener->tcp_eager_next_q = tcp;
14970 		}
14971 		listener->tcp_eager_last_q = tcp;
14972 		tcp->tcp_eager_next_q = NULL;
14973 
14974 		/* Need to get inside the listener perimeter */
14975 		CONN_INC_REF(listener->tcp_connp);
14976 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
14977 		    tcp_send_pending, listener->tcp_connp, NULL, SQ_FILL,
14978 		    SQTAG_TCP_SEND_PENDING);
14979 	}
14980 no_more_eagers:
14981 	tcp_eager_unlink(eager);
14982 	mutex_exit(&listener->tcp_eager_lock);
14983 
14984 	/*
14985 	 * At this point, the eager is detached from the listener
14986 	 * but we still have an extra refs on eager (apart from the
14987 	 * usual tcp references). The ref was placed in tcp_input_data
14988 	 * before sending the conn_ind in tcp_send_conn_ind.
14989 	 * The ref will be dropped in tcp_accept_finish().
14990 	 */
14991 	SQUEUE_ENTER_ONE(econnp->conn_sqp, discon_mp, tcp_accept_finish,
14992 	    econnp, NULL, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
14993 	return (0);
14994 }
14995 
14996 int
14997 tcp_accept(sock_lower_handle_t lproto_handle,
14998     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
14999     cred_t *cr)
15000 {
15001 	conn_t *lconnp, *econnp;
15002 	tcp_t *listener, *eager;
15003 
15004 	lconnp = (conn_t *)lproto_handle;
15005 	listener = lconnp->conn_tcp;
15006 	ASSERT(listener->tcp_state == TCPS_LISTEN);
15007 	econnp = (conn_t *)eproto_handle;
15008 	eager = econnp->conn_tcp;
15009 	ASSERT(eager->tcp_listener != NULL);
15010 
15011 	/*
15012 	 * It is OK to manipulate these fields outside the eager's squeue
15013 	 * because they will not start being used until tcp_accept_finish
15014 	 * has been called.
15015 	 */
15016 	ASSERT(lconnp->conn_upper_handle != NULL);
15017 	ASSERT(econnp->conn_upper_handle == NULL);
15018 	econnp->conn_upper_handle = sock_handle;
15019 	econnp->conn_upcalls = lconnp->conn_upcalls;
15020 	ASSERT(IPCL_IS_NONSTR(econnp));
15021 	return (tcp_accept_common(lconnp, econnp, cr));
15022 }
15023 
15024 
15025 /*
15026  * This is the STREAMS entry point for T_CONN_RES coming down on
15027  * Acceptor STREAM when  sockfs listener does accept processing.
15028  * Read the block comment on top of tcp_input_listener().
15029  */
15030 void
15031 tcp_tpi_accept(queue_t *q, mblk_t *mp)
15032 {
15033 	queue_t *rq = RD(q);
15034 	struct T_conn_res *conn_res;
15035 	tcp_t *eager;
15036 	tcp_t *listener;
15037 	struct T_ok_ack *ok;
15038 	t_scalar_t PRIM_type;
15039 	conn_t *econnp;
15040 	cred_t *cr;
15041 
15042 	ASSERT(DB_TYPE(mp) == M_PROTO);
15043 
15044 	/*
15045 	 * All Solaris components should pass a db_credp
15046 	 * for this TPI message, hence we ASSERT.
15047 	 * But in case there is some other M_PROTO that looks
15048 	 * like a TPI message sent by some other kernel
15049 	 * component, we check and return an error.
15050 	 */
15051 	cr = msg_getcred(mp, NULL);
15052 	ASSERT(cr != NULL);
15053 	if (cr == NULL) {
15054 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
15055 		if (mp != NULL)
15056 			putnext(rq, mp);
15057 		return;
15058 	}
15059 	conn_res = (struct T_conn_res *)mp->b_rptr;
15060 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
15061 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
15062 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15063 		if (mp != NULL)
15064 			putnext(rq, mp);
15065 		return;
15066 	}
15067 	switch (conn_res->PRIM_type) {
15068 	case O_T_CONN_RES:
15069 	case T_CONN_RES:
15070 		/*
15071 		 * We pass up an err ack if allocb fails. This will
15072 		 * cause sockfs to issue a T_DISCON_REQ which will cause
15073 		 * tcp_eager_blowoff to be called. sockfs will then call
15074 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
15075 		 * we need to do the allocb up here because we have to
15076 		 * make sure rq->q_qinfo->qi_qclose still points to the
15077 		 * correct function (tcp_tpi_close_accept) in case allocb
15078 		 * fails.
15079 		 */
15080 		bcopy(mp->b_rptr + conn_res->OPT_offset,
15081 		    &eager, conn_res->OPT_length);
15082 		PRIM_type = conn_res->PRIM_type;
15083 		mp->b_datap->db_type = M_PCPROTO;
15084 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
15085 		ok = (struct T_ok_ack *)mp->b_rptr;
15086 		ok->PRIM_type = T_OK_ACK;
15087 		ok->CORRECT_prim = PRIM_type;
15088 		econnp = eager->tcp_connp;
15089 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
15090 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
15091 		econnp->conn_rq = rq;
15092 		econnp->conn_wq = q;
15093 		rq->q_ptr = econnp;
15094 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
15095 		q->q_ptr = econnp;
15096 		q->q_qinfo = &tcp_winit;
15097 		listener = eager->tcp_listener;
15098 
15099 		if (tcp_accept_common(listener->tcp_connp,
15100 		    econnp, cr) < 0) {
15101 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15102 			if (mp != NULL)
15103 				putnext(rq, mp);
15104 			return;
15105 		}
15106 
15107 		/*
15108 		 * Send the new local address also up to sockfs. There
15109 		 * should already be enough space in the mp that came
15110 		 * down from soaccept().
15111 		 */
15112 		if (econnp->conn_family == AF_INET) {
15113 			sin_t *sin;
15114 
15115 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15116 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
15117 			sin = (sin_t *)mp->b_wptr;
15118 			mp->b_wptr += sizeof (sin_t);
15119 			sin->sin_family = AF_INET;
15120 			sin->sin_port = econnp->conn_lport;
15121 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
15122 		} else {
15123 			sin6_t *sin6;
15124 
15125 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15126 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
15127 			sin6 = (sin6_t *)mp->b_wptr;
15128 			mp->b_wptr += sizeof (sin6_t);
15129 			sin6->sin6_family = AF_INET6;
15130 			sin6->sin6_port = econnp->conn_lport;
15131 			sin6->sin6_addr = econnp->conn_laddr_v6;
15132 			if (econnp->conn_ipversion == IPV4_VERSION)
15133 				sin6->sin6_flowinfo = 0;
15134 			else
15135 				sin6->sin6_flowinfo = econnp->conn_flowinfo;
15136 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
15137 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
15138 				sin6->sin6_scope_id =
15139 				    econnp->conn_ixa->ixa_scopeid;
15140 			} else {
15141 				sin6->sin6_scope_id = 0;
15142 			}
15143 			sin6->__sin6_src_id = 0;
15144 		}
15145 
15146 		putnext(rq, mp);
15147 		return;
15148 	default:
15149 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
15150 		if (mp != NULL)
15151 			putnext(rq, mp);
15152 		return;
15153 	}
15154 }
15155 
15156 /*
15157  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
15158  */
15159 static void
15160 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
15161 {
15162 	void	*data;
15163 	mblk_t	*datamp = mp->b_cont;
15164 	conn_t	*connp = Q_TO_CONN(q);
15165 	tcp_t	*tcp = connp->conn_tcp;
15166 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
15167 
15168 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
15169 		cmdp->cb_error = EPROTO;
15170 		qreply(q, mp);
15171 		return;
15172 	}
15173 
15174 	data = datamp->b_rptr;
15175 
15176 	switch (cmdp->cb_cmd) {
15177 	case TI_GETPEERNAME:
15178 		if (tcp->tcp_state < TCPS_SYN_RCVD)
15179 			cmdp->cb_error = ENOTCONN;
15180 		else
15181 			cmdp->cb_error = conn_getpeername(connp, data,
15182 			    &cmdp->cb_len);
15183 		break;
15184 	case TI_GETMYNAME:
15185 		cmdp->cb_error = conn_getsockname(connp, data, &cmdp->cb_len);
15186 		break;
15187 	default:
15188 		cmdp->cb_error = EINVAL;
15189 		break;
15190 	}
15191 
15192 	qreply(q, mp);
15193 }
15194 
15195 void
15196 tcp_wput(queue_t *q, mblk_t *mp)
15197 {
15198 	conn_t	*connp = Q_TO_CONN(q);
15199 	tcp_t	*tcp;
15200 	void (*output_proc)();
15201 	t_scalar_t type;
15202 	uchar_t *rptr;
15203 	struct iocblk	*iocp;
15204 	size_t size;
15205 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
15206 
15207 	ASSERT(connp->conn_ref >= 2);
15208 
15209 	switch (DB_TYPE(mp)) {
15210 	case M_DATA:
15211 		tcp = connp->conn_tcp;
15212 		ASSERT(tcp != NULL);
15213 
15214 		size = msgdsize(mp);
15215 
15216 		mutex_enter(&tcp->tcp_non_sq_lock);
15217 		tcp->tcp_squeue_bytes += size;
15218 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
15219 			tcp_setqfull(tcp);
15220 		}
15221 		mutex_exit(&tcp->tcp_non_sq_lock);
15222 
15223 		CONN_INC_REF(connp);
15224 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
15225 		    NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
15226 		return;
15227 
15228 	case M_CMD:
15229 		tcp_wput_cmdblk(q, mp);
15230 		return;
15231 
15232 	case M_PROTO:
15233 	case M_PCPROTO:
15234 		/*
15235 		 * if it is a snmp message, don't get behind the squeue
15236 		 */
15237 		tcp = connp->conn_tcp;
15238 		rptr = mp->b_rptr;
15239 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
15240 			type = ((union T_primitives *)rptr)->type;
15241 		} else {
15242 			if (connp->conn_debug) {
15243 				(void) strlog(TCP_MOD_ID, 0, 1,
15244 				    SL_ERROR|SL_TRACE,
15245 				    "tcp_wput_proto, dropping one...");
15246 			}
15247 			freemsg(mp);
15248 			return;
15249 		}
15250 		if (type == T_SVR4_OPTMGMT_REQ) {
15251 			/*
15252 			 * All Solaris components should pass a db_credp
15253 			 * for this TPI message, hence we ASSERT.
15254 			 * But in case there is some other M_PROTO that looks
15255 			 * like a TPI message sent by some other kernel
15256 			 * component, we check and return an error.
15257 			 */
15258 			cred_t	*cr = msg_getcred(mp, NULL);
15259 
15260 			ASSERT(cr != NULL);
15261 			if (cr == NULL) {
15262 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
15263 				return;
15264 			}
15265 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
15266 			    cr)) {
15267 				/*
15268 				 * This was a SNMP request
15269 				 */
15270 				return;
15271 			} else {
15272 				output_proc = tcp_wput_proto;
15273 			}
15274 		} else {
15275 			output_proc = tcp_wput_proto;
15276 		}
15277 		break;
15278 	case M_IOCTL:
15279 		/*
15280 		 * Most ioctls can be processed right away without going via
15281 		 * squeues - process them right here. Those that do require
15282 		 * squeue (currently _SIOCSOCKFALLBACK)
15283 		 * are processed by tcp_wput_ioctl().
15284 		 */
15285 		iocp = (struct iocblk *)mp->b_rptr;
15286 		tcp = connp->conn_tcp;
15287 
15288 		switch (iocp->ioc_cmd) {
15289 		case TCP_IOC_ABORT_CONN:
15290 			tcp_ioctl_abort_conn(q, mp);
15291 			return;
15292 		case TI_GETPEERNAME:
15293 		case TI_GETMYNAME:
15294 			mi_copyin(q, mp, NULL,
15295 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
15296 			return;
15297 		case ND_SET:
15298 			/* nd_getset does the necessary checks */
15299 		case ND_GET:
15300 			if (nd_getset(q, tcps->tcps_g_nd, mp)) {
15301 				qreply(q, mp);
15302 				return;
15303 			}
15304 			CONN_INC_IOCTLREF(connp);
15305 			ip_wput_nondata(q, mp);
15306 			CONN_DEC_IOCTLREF(connp);
15307 			return;
15308 
15309 		default:
15310 			output_proc = tcp_wput_ioctl;
15311 			break;
15312 		}
15313 		break;
15314 	default:
15315 		output_proc = tcp_wput_nondata;
15316 		break;
15317 	}
15318 
15319 	CONN_INC_REF(connp);
15320 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
15321 	    NULL, tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
15322 }
15323 
15324 /*
15325  * Initial STREAMS write side put() procedure for sockets. It tries to
15326  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
15327  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
15328  * are handled by tcp_wput() as usual.
15329  *
15330  * All further messages will also be handled by tcp_wput() because we cannot
15331  * be sure that the above short cut is safe later.
15332  */
15333 static void
15334 tcp_wput_sock(queue_t *wq, mblk_t *mp)
15335 {
15336 	conn_t			*connp = Q_TO_CONN(wq);
15337 	tcp_t			*tcp = connp->conn_tcp;
15338 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
15339 
15340 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
15341 	wq->q_qinfo = &tcp_winit;
15342 
15343 	ASSERT(IPCL_IS_TCP(connp));
15344 	ASSERT(TCP_IS_SOCKET(tcp));
15345 
15346 	if (DB_TYPE(mp) == M_PCPROTO &&
15347 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
15348 	    car->PRIM_type == T_CAPABILITY_REQ) {
15349 		tcp_capability_req(tcp, mp);
15350 		return;
15351 	}
15352 
15353 	tcp_wput(wq, mp);
15354 }
15355 
15356 /* ARGSUSED */
15357 static void
15358 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
15359 {
15360 #ifdef DEBUG
15361 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
15362 #endif
15363 	freemsg(mp);
15364 }
15365 
15366 /*
15367  * Check the usability of ZEROCOPY. It's instead checking the flag set by IP.
15368  */
15369 static boolean_t
15370 tcp_zcopy_check(tcp_t *tcp)
15371 {
15372 	conn_t		*connp = tcp->tcp_connp;
15373 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
15374 	boolean_t	zc_enabled = B_FALSE;
15375 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15376 
15377 	if (do_tcpzcopy == 2)
15378 		zc_enabled = B_TRUE;
15379 	else if ((do_tcpzcopy == 1) && (ixa->ixa_flags & IXAF_ZCOPY_CAPAB))
15380 		zc_enabled = B_TRUE;
15381 
15382 	tcp->tcp_snd_zcopy_on = zc_enabled;
15383 	if (!TCP_IS_DETACHED(tcp)) {
15384 		if (zc_enabled) {
15385 			ixa->ixa_flags |= IXAF_VERIFY_ZCOPY;
15386 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15387 			    ZCVMSAFE);
15388 			TCP_STAT(tcps, tcp_zcopy_on);
15389 		} else {
15390 			ixa->ixa_flags &= ~IXAF_VERIFY_ZCOPY;
15391 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15392 			    ZCVMUNSAFE);
15393 			TCP_STAT(tcps, tcp_zcopy_off);
15394 		}
15395 	}
15396 	return (zc_enabled);
15397 }
15398 
15399 /*
15400  * Backoff from a zero-copy message by copying data to a new allocated
15401  * message and freeing the original desballoca'ed segmapped message.
15402  *
15403  * This function is called by following two callers:
15404  * 1. tcp_timer: fix_xmitlist is set to B_TRUE, because it's safe to free
15405  *    the origial desballoca'ed message and notify sockfs. This is in re-
15406  *    transmit state.
15407  * 2. tcp_output: fix_xmitlist is set to B_FALSE. Flag STRUIO_ZCNOTIFY need
15408  *    to be copied to new message.
15409  */
15410 static mblk_t *
15411 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, boolean_t fix_xmitlist)
15412 {
15413 	mblk_t		*nbp;
15414 	mblk_t		*head = NULL;
15415 	mblk_t		*tail = NULL;
15416 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15417 
15418 	ASSERT(bp != NULL);
15419 	while (bp != NULL) {
15420 		if (IS_VMLOANED_MBLK(bp)) {
15421 			TCP_STAT(tcps, tcp_zcopy_backoff);
15422 			if ((nbp = copyb(bp)) == NULL) {
15423 				tcp->tcp_xmit_zc_clean = B_FALSE;
15424 				if (tail != NULL)
15425 					tail->b_cont = bp;
15426 				return ((head == NULL) ? bp : head);
15427 			}
15428 
15429 			if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
15430 				if (fix_xmitlist)
15431 					tcp_zcopy_notify(tcp);
15432 				else
15433 					nbp->b_datap->db_struioflag |=
15434 					    STRUIO_ZCNOTIFY;
15435 			}
15436 			nbp->b_cont = bp->b_cont;
15437 
15438 			/*
15439 			 * Copy saved information and adjust tcp_xmit_tail
15440 			 * if needed.
15441 			 */
15442 			if (fix_xmitlist) {
15443 				nbp->b_prev = bp->b_prev;
15444 				nbp->b_next = bp->b_next;
15445 
15446 				if (tcp->tcp_xmit_tail == bp)
15447 					tcp->tcp_xmit_tail = nbp;
15448 			}
15449 
15450 			/* Free the original message. */
15451 			bp->b_prev = NULL;
15452 			bp->b_next = NULL;
15453 			freeb(bp);
15454 
15455 			bp = nbp;
15456 		}
15457 
15458 		if (head == NULL) {
15459 			head = bp;
15460 		}
15461 		if (tail == NULL) {
15462 			tail = bp;
15463 		} else {
15464 			tail->b_cont = bp;
15465 			tail = bp;
15466 		}
15467 
15468 		/* Move forward. */
15469 		bp = bp->b_cont;
15470 	}
15471 
15472 	if (fix_xmitlist) {
15473 		tcp->tcp_xmit_last = tail;
15474 		tcp->tcp_xmit_zc_clean = B_TRUE;
15475 	}
15476 
15477 	return (head);
15478 }
15479 
15480 static void
15481 tcp_zcopy_notify(tcp_t *tcp)
15482 {
15483 	struct stdata	*stp;
15484 	conn_t		*connp;
15485 
15486 	if (tcp->tcp_detached)
15487 		return;
15488 	connp = tcp->tcp_connp;
15489 	if (IPCL_IS_NONSTR(connp)) {
15490 		(*connp->conn_upcalls->su_zcopy_notify)
15491 		    (connp->conn_upper_handle);
15492 		return;
15493 	}
15494 	stp = STREAM(connp->conn_rq);
15495 	mutex_enter(&stp->sd_lock);
15496 	stp->sd_flag |= STZCNOTIFY;
15497 	cv_broadcast(&stp->sd_zcopy_wait);
15498 	mutex_exit(&stp->sd_lock);
15499 }
15500 
15501 /*
15502  * Update the TCP connection according to change of LSO capability.
15503  */
15504 static void
15505 tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa)
15506 {
15507 	/*
15508 	 * We check against IPv4 header length to preserve the old behavior
15509 	 * of only enabling LSO when there are no IP options.
15510 	 * But this restriction might not be necessary at all. Before removing
15511 	 * it, need to verify how LSO is handled for source routing case, with
15512 	 * which IP does software checksum.
15513 	 *
15514 	 * For IPv6, whenever any extension header is needed, LSO is supressed.
15515 	 */
15516 	if (ixa->ixa_ip_hdr_length != ((ixa->ixa_flags & IXAF_IS_IPV4) ?
15517 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN))
15518 		return;
15519 
15520 	/*
15521 	 * Either the LSO capability newly became usable, or it has changed.
15522 	 */
15523 	if (ixa->ixa_flags & IXAF_LSO_CAPAB) {
15524 		ill_lso_capab_t	*lsoc = &ixa->ixa_lso_capab;
15525 
15526 		ASSERT(lsoc->ill_lso_max > 0);
15527 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH, lsoc->ill_lso_max);
15528 
15529 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15530 		    boolean_t, B_TRUE, uint32_t, tcp->tcp_lso_max);
15531 
15532 		/*
15533 		 * If LSO to be enabled, notify the STREAM header with larger
15534 		 * data block.
15535 		 */
15536 		if (!tcp->tcp_lso)
15537 			tcp->tcp_maxpsz_multiplier = 0;
15538 
15539 		tcp->tcp_lso = B_TRUE;
15540 		TCP_STAT(tcp->tcp_tcps, tcp_lso_enabled);
15541 	} else { /* LSO capability is not usable any more. */
15542 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15543 		    boolean_t, B_FALSE, uint32_t, tcp->tcp_lso_max);
15544 
15545 		/*
15546 		 * If LSO to be disabled, notify the STREAM header with smaller
15547 		 * data block. And need to restore fragsize to PMTU.
15548 		 */
15549 		if (tcp->tcp_lso) {
15550 			tcp->tcp_maxpsz_multiplier =
15551 			    tcp->tcp_tcps->tcps_maxpsz_multiplier;
15552 			ixa->ixa_fragsize = ixa->ixa_pmtu;
15553 			tcp->tcp_lso = B_FALSE;
15554 			TCP_STAT(tcp->tcp_tcps, tcp_lso_disabled);
15555 		}
15556 	}
15557 
15558 	(void) tcp_maxpsz_set(tcp, B_TRUE);
15559 }
15560 
15561 /*
15562  * Update the TCP connection according to change of ZEROCOPY capability.
15563  */
15564 static void
15565 tcp_update_zcopy(tcp_t *tcp)
15566 {
15567 	conn_t		*connp = tcp->tcp_connp;
15568 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15569 
15570 	if (tcp->tcp_snd_zcopy_on) {
15571 		tcp->tcp_snd_zcopy_on = B_FALSE;
15572 		if (!TCP_IS_DETACHED(tcp)) {
15573 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15574 			    ZCVMUNSAFE);
15575 			TCP_STAT(tcps, tcp_zcopy_off);
15576 		}
15577 	} else {
15578 		tcp->tcp_snd_zcopy_on = B_TRUE;
15579 		if (!TCP_IS_DETACHED(tcp)) {
15580 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15581 			    ZCVMSAFE);
15582 			TCP_STAT(tcps, tcp_zcopy_on);
15583 		}
15584 	}
15585 }
15586 
15587 /*
15588  * Notify function registered with ip_xmit_attr_t. It's called in the squeue
15589  * so it's safe to update the TCP connection.
15590  */
15591 /* ARGSUSED1 */
15592 static void
15593 tcp_notify(void *arg, ip_xmit_attr_t *ixa, ixa_notify_type_t ntype,
15594     ixa_notify_arg_t narg)
15595 {
15596 	tcp_t		*tcp = (tcp_t *)arg;
15597 	conn_t		*connp = tcp->tcp_connp;
15598 
15599 	switch (ntype) {
15600 	case IXAN_LSO:
15601 		tcp_update_lso(tcp, connp->conn_ixa);
15602 		break;
15603 	case IXAN_PMTU:
15604 		tcp_update_pmtu(tcp, B_FALSE);
15605 		break;
15606 	case IXAN_ZCOPY:
15607 		tcp_update_zcopy(tcp);
15608 		break;
15609 	default:
15610 		break;
15611 	}
15612 }
15613 
15614 static void
15615 tcp_send_data(tcp_t *tcp, mblk_t *mp)
15616 {
15617 	conn_t		*connp = tcp->tcp_connp;
15618 
15619 	/*
15620 	 * Check here to avoid sending zero-copy message down to IP when
15621 	 * ZEROCOPY capability has turned off. We only need to deal with
15622 	 * the race condition between sockfs and the notification here.
15623 	 * Since we have tried to backoff the tcp_xmit_head when turning
15624 	 * zero-copy off and new messages in tcp_output(), we simply drop
15625 	 * the dup'ed packet here and let tcp retransmit, if tcp_xmit_zc_clean
15626 	 * is not true.
15627 	 */
15628 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on &&
15629 	    !tcp->tcp_xmit_zc_clean) {
15630 		ip_drop_output("TCP ZC was disabled but not clean", mp, NULL);
15631 		freemsg(mp);
15632 		return;
15633 	}
15634 
15635 	ASSERT(connp->conn_ixa->ixa_notify_cookie == connp->conn_tcp);
15636 	(void) conn_ip_output(mp, connp->conn_ixa);
15637 }
15638 
15639 /*
15640  * This handles the case when the receiver has shrunk its win. Per RFC 1122
15641  * if the receiver shrinks the window, i.e. moves the right window to the
15642  * left, the we should not send new data, but should retransmit normally the
15643  * old unacked data between suna and suna + swnd. We might has sent data
15644  * that is now outside the new window, pretend that we didn't send  it.
15645  */
15646 static void
15647 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
15648 {
15649 	uint32_t	snxt = tcp->tcp_snxt;
15650 
15651 	ASSERT(shrunk_count > 0);
15652 
15653 	if (!tcp->tcp_is_wnd_shrnk) {
15654 		tcp->tcp_snxt_shrunk = snxt;
15655 		tcp->tcp_is_wnd_shrnk = B_TRUE;
15656 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
15657 		tcp->tcp_snxt_shrunk = snxt;
15658 	}
15659 
15660 	/* Pretend we didn't send the data outside the window */
15661 	snxt -= shrunk_count;
15662 
15663 	/* Reset all the values per the now shrunk window */
15664 	tcp_update_xmit_tail(tcp, snxt);
15665 	tcp->tcp_unsent += shrunk_count;
15666 
15667 	/*
15668 	 * If the SACK option is set, delete the entire list of
15669 	 * notsack'ed blocks.
15670 	 */
15671 	if (tcp->tcp_sack_info != NULL) {
15672 		if (tcp->tcp_notsack_list != NULL)
15673 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
15674 	}
15675 
15676 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
15677 		/*
15678 		 * Make sure the timer is running so that we will probe a zero
15679 		 * window.
15680 		 */
15681 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15682 }
15683 
15684 
15685 /*
15686  * The TCP normal data output path.
15687  * NOTE: the logic of the fast path is duplicated from this function.
15688  */
15689 static void
15690 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
15691 {
15692 	int		len;
15693 	mblk_t		*local_time;
15694 	mblk_t		*mp1;
15695 	uint32_t	snxt;
15696 	int		tail_unsent;
15697 	int		tcpstate;
15698 	int		usable = 0;
15699 	mblk_t		*xmit_tail;
15700 	int32_t		mss;
15701 	int32_t		num_sack_blk = 0;
15702 	int32_t		total_hdr_len;
15703 	int32_t		tcp_hdr_len;
15704 	int		rc;
15705 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15706 	conn_t		*connp = tcp->tcp_connp;
15707 	clock_t		now = LBOLT_FASTPATH;
15708 
15709 	tcpstate = tcp->tcp_state;
15710 	if (mp == NULL) {
15711 		/*
15712 		 * tcp_wput_data() with NULL mp should only be called when
15713 		 * there is unsent data.
15714 		 */
15715 		ASSERT(tcp->tcp_unsent > 0);
15716 		/* Really tacky... but we need this for detached closes. */
15717 		len = tcp->tcp_unsent;
15718 		goto data_null;
15719 	}
15720 
15721 #if CCS_STATS
15722 	wrw_stats.tot.count++;
15723 	wrw_stats.tot.bytes += msgdsize(mp);
15724 #endif
15725 	ASSERT(mp->b_datap->db_type == M_DATA);
15726 	/*
15727 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
15728 	 * or before a connection attempt has begun.
15729 	 */
15730 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
15731 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15732 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15733 #ifdef DEBUG
15734 			cmn_err(CE_WARN,
15735 			    "tcp_wput_data: data after ordrel, %s",
15736 			    tcp_display(tcp, NULL,
15737 			    DISP_ADDR_AND_PORT));
15738 #else
15739 			if (connp->conn_debug) {
15740 				(void) strlog(TCP_MOD_ID, 0, 1,
15741 				    SL_TRACE|SL_ERROR,
15742 				    "tcp_wput_data: data after ordrel, %s\n",
15743 				    tcp_display(tcp, NULL,
15744 				    DISP_ADDR_AND_PORT));
15745 			}
15746 #endif /* DEBUG */
15747 		}
15748 		if (tcp->tcp_snd_zcopy_aware &&
15749 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15750 			tcp_zcopy_notify(tcp);
15751 		freemsg(mp);
15752 		mutex_enter(&tcp->tcp_non_sq_lock);
15753 		if (tcp->tcp_flow_stopped &&
15754 		    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
15755 			tcp_clrqfull(tcp);
15756 		}
15757 		mutex_exit(&tcp->tcp_non_sq_lock);
15758 		return;
15759 	}
15760 
15761 	/* Strip empties */
15762 	for (;;) {
15763 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
15764 		    (uintptr_t)INT_MAX);
15765 		len = (int)(mp->b_wptr - mp->b_rptr);
15766 		if (len > 0)
15767 			break;
15768 		mp1 = mp;
15769 		mp = mp->b_cont;
15770 		freeb(mp1);
15771 		if (!mp) {
15772 			return;
15773 		}
15774 	}
15775 
15776 	/* If we are the first on the list ... */
15777 	if (tcp->tcp_xmit_head == NULL) {
15778 		tcp->tcp_xmit_head = mp;
15779 		tcp->tcp_xmit_tail = mp;
15780 		tcp->tcp_xmit_tail_unsent = len;
15781 	} else {
15782 		/* If tiny tx and room in txq tail, pullup to save mblks. */
15783 		struct datab *dp;
15784 
15785 		mp1 = tcp->tcp_xmit_last;
15786 		if (len < tcp_tx_pull_len &&
15787 		    (dp = mp1->b_datap)->db_ref == 1 &&
15788 		    dp->db_lim - mp1->b_wptr >= len) {
15789 			ASSERT(len > 0);
15790 			ASSERT(!mp1->b_cont);
15791 			if (len == 1) {
15792 				*mp1->b_wptr++ = *mp->b_rptr;
15793 			} else {
15794 				bcopy(mp->b_rptr, mp1->b_wptr, len);
15795 				mp1->b_wptr += len;
15796 			}
15797 			if (mp1 == tcp->tcp_xmit_tail)
15798 				tcp->tcp_xmit_tail_unsent += len;
15799 			mp1->b_cont = mp->b_cont;
15800 			if (tcp->tcp_snd_zcopy_aware &&
15801 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15802 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
15803 			freeb(mp);
15804 			mp = mp1;
15805 		} else {
15806 			tcp->tcp_xmit_last->b_cont = mp;
15807 		}
15808 		len += tcp->tcp_unsent;
15809 	}
15810 
15811 	/* Tack on however many more positive length mblks we have */
15812 	if ((mp1 = mp->b_cont) != NULL) {
15813 		do {
15814 			int tlen;
15815 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
15816 			    (uintptr_t)INT_MAX);
15817 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
15818 			if (tlen <= 0) {
15819 				mp->b_cont = mp1->b_cont;
15820 				freeb(mp1);
15821 			} else {
15822 				len += tlen;
15823 				mp = mp1;
15824 			}
15825 		} while ((mp1 = mp->b_cont) != NULL);
15826 	}
15827 	tcp->tcp_xmit_last = mp;
15828 	tcp->tcp_unsent = len;
15829 
15830 	if (urgent)
15831 		usable = 1;
15832 
15833 data_null:
15834 	snxt = tcp->tcp_snxt;
15835 	xmit_tail = tcp->tcp_xmit_tail;
15836 	tail_unsent = tcp->tcp_xmit_tail_unsent;
15837 
15838 	/*
15839 	 * Note that tcp_mss has been adjusted to take into account the
15840 	 * timestamp option if applicable.  Because SACK options do not
15841 	 * appear in every TCP segments and they are of variable lengths,
15842 	 * they cannot be included in tcp_mss.  Thus we need to calculate
15843 	 * the actual segment length when we need to send a segment which
15844 	 * includes SACK options.
15845 	 */
15846 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15847 		int32_t	opt_len;
15848 
15849 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
15850 		    tcp->tcp_num_sack_blk);
15851 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
15852 		    2 + TCPOPT_HEADER_LEN;
15853 		mss = tcp->tcp_mss - opt_len;
15854 		total_hdr_len = connp->conn_ht_iphc_len + opt_len;
15855 		tcp_hdr_len = connp->conn_ht_ulp_len + opt_len;
15856 	} else {
15857 		mss = tcp->tcp_mss;
15858 		total_hdr_len = connp->conn_ht_iphc_len;
15859 		tcp_hdr_len = connp->conn_ht_ulp_len;
15860 	}
15861 
15862 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
15863 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
15864 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
15865 	}
15866 	if (tcpstate == TCPS_SYN_RCVD) {
15867 		/*
15868 		 * The three-way connection establishment handshake is not
15869 		 * complete yet. We want to queue the data for transmission
15870 		 * after entering ESTABLISHED state (RFC793). A jump to
15871 		 * "done" label effectively leaves data on the queue.
15872 		 */
15873 		goto done;
15874 	} else {
15875 		int usable_r;
15876 
15877 		/*
15878 		 * In the special case when cwnd is zero, which can only
15879 		 * happen if the connection is ECN capable, return now.
15880 		 * New segments is sent using tcp_timer().  The timer
15881 		 * is set in tcp_input_data().
15882 		 */
15883 		if (tcp->tcp_cwnd == 0) {
15884 			/*
15885 			 * Note that tcp_cwnd is 0 before 3-way handshake is
15886 			 * finished.
15887 			 */
15888 			ASSERT(tcp->tcp_ecn_ok ||
15889 			    tcp->tcp_state < TCPS_ESTABLISHED);
15890 			return;
15891 		}
15892 
15893 		/* NOTE: trouble if xmitting while SYN not acked? */
15894 		usable_r = snxt - tcp->tcp_suna;
15895 		usable_r = tcp->tcp_swnd - usable_r;
15896 
15897 		/*
15898 		 * Check if the receiver has shrunk the window.  If
15899 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
15900 		 * cannot be set as there is unsent data, so FIN cannot
15901 		 * be sent out.  Otherwise, we need to take into account
15902 		 * of FIN as it consumes an "invisible" sequence number.
15903 		 */
15904 		ASSERT(tcp->tcp_fin_sent == 0);
15905 		if (usable_r < 0) {
15906 			/*
15907 			 * The receiver has shrunk the window and we have sent
15908 			 * -usable_r date beyond the window, re-adjust.
15909 			 *
15910 			 * If TCP window scaling is enabled, there can be
15911 			 * round down error as the advertised receive window
15912 			 * is actually right shifted n bits.  This means that
15913 			 * the lower n bits info is wiped out.  It will look
15914 			 * like the window is shrunk.  Do a check here to
15915 			 * see if the shrunk amount is actually within the
15916 			 * error in window calculation.  If it is, just
15917 			 * return.  Note that this check is inside the
15918 			 * shrunk window check.  This makes sure that even
15919 			 * though tcp_process_shrunk_swnd() is not called,
15920 			 * we will stop further processing.
15921 			 */
15922 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
15923 				tcp_process_shrunk_swnd(tcp, -usable_r);
15924 			}
15925 			return;
15926 		}
15927 
15928 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
15929 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
15930 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
15931 
15932 		/* usable = MIN(usable, unsent) */
15933 		if (usable_r > len)
15934 			usable_r = len;
15935 
15936 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
15937 		if (usable_r > 0) {
15938 			usable = usable_r;
15939 		} else {
15940 			/* Bypass all other unnecessary processing. */
15941 			goto done;
15942 		}
15943 	}
15944 
15945 	local_time = (mblk_t *)now;
15946 
15947 	/*
15948 	 * "Our" Nagle Algorithm.  This is not the same as in the old
15949 	 * BSD.  This is more in line with the true intent of Nagle.
15950 	 *
15951 	 * The conditions are:
15952 	 * 1. The amount of unsent data (or amount of data which can be
15953 	 *    sent, whichever is smaller) is less than Nagle limit.
15954 	 * 2. The last sent size is also less than Nagle limit.
15955 	 * 3. There is unack'ed data.
15956 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
15957 	 *    Nagle algorithm.  This reduces the probability that urgent
15958 	 *    bytes get "merged" together.
15959 	 * 5. The app has not closed the connection.  This eliminates the
15960 	 *    wait time of the receiving side waiting for the last piece of
15961 	 *    (small) data.
15962 	 *
15963 	 * If all are satisified, exit without sending anything.  Note
15964 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
15965 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
15966 	 * 4095).
15967 	 */
15968 	if (usable < (int)tcp->tcp_naglim &&
15969 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
15970 	    snxt != tcp->tcp_suna &&
15971 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
15972 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
15973 		goto done;
15974 	}
15975 
15976 	/*
15977 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
15978 	 * is set, then we have to force TCP not to send partial segment
15979 	 * (smaller than MSS bytes). We are calculating the usable now
15980 	 * based on full mss and will save the rest of remaining data for
15981 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
15982 	 * something to do zero window probe.
15983 	 */
15984 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
15985 		if (usable < mss)
15986 			goto done;
15987 		usable = (usable / mss) * mss;
15988 	}
15989 
15990 	/* Update the latest receive window size in TCP header. */
15991 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
15992 
15993 	/* Send the packet. */
15994 	rc = tcp_send(tcp, mss, total_hdr_len, tcp_hdr_len,
15995 	    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
15996 	    local_time);
15997 
15998 	/* Pretend that all we were trying to send really got sent */
15999 	if (rc < 0 && tail_unsent < 0) {
16000 		do {
16001 			xmit_tail = xmit_tail->b_cont;
16002 			xmit_tail->b_prev = local_time;
16003 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
16004 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
16005 			tail_unsent += (int)(xmit_tail->b_wptr -
16006 			    xmit_tail->b_rptr);
16007 		} while (tail_unsent < 0);
16008 	}
16009 done:;
16010 	tcp->tcp_xmit_tail = xmit_tail;
16011 	tcp->tcp_xmit_tail_unsent = tail_unsent;
16012 	len = tcp->tcp_snxt - snxt;
16013 	if (len) {
16014 		/*
16015 		 * If new data was sent, need to update the notsack
16016 		 * list, which is, afterall, data blocks that have
16017 		 * not been sack'ed by the receiver.  New data is
16018 		 * not sack'ed.
16019 		 */
16020 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
16021 			/* len is a negative value. */
16022 			tcp->tcp_pipe -= len;
16023 			tcp_notsack_update(&(tcp->tcp_notsack_list),
16024 			    tcp->tcp_snxt, snxt,
16025 			    &(tcp->tcp_num_notsack_blk),
16026 			    &(tcp->tcp_cnt_notsack_list));
16027 		}
16028 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
16029 		tcp->tcp_rack = tcp->tcp_rnxt;
16030 		tcp->tcp_rack_cnt = 0;
16031 		if ((snxt + len) == tcp->tcp_suna) {
16032 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16033 		}
16034 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
16035 		/*
16036 		 * Didn't send anything. Make sure the timer is running
16037 		 * so that we will probe a zero window.
16038 		 */
16039 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16040 	}
16041 	/* Note that len is the amount we just sent but with a negative sign */
16042 	tcp->tcp_unsent += len;
16043 	mutex_enter(&tcp->tcp_non_sq_lock);
16044 	if (tcp->tcp_flow_stopped) {
16045 		if (TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
16046 			tcp_clrqfull(tcp);
16047 		}
16048 	} else if (TCP_UNSENT_BYTES(tcp) >= connp->conn_sndbuf) {
16049 		if (!(tcp->tcp_detached))
16050 			tcp_setqfull(tcp);
16051 	}
16052 	mutex_exit(&tcp->tcp_non_sq_lock);
16053 }
16054 
16055 /*
16056  * tcp_fill_header is called by tcp_send() to fill the outgoing TCP header
16057  * with the template header, as well as other options such as time-stamp,
16058  * ECN and/or SACK.
16059  */
16060 static void
16061 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
16062 {
16063 	tcpha_t *tcp_tmpl, *tcpha;
16064 	uint32_t *dst, *src;
16065 	int hdrlen;
16066 	conn_t *connp = tcp->tcp_connp;
16067 
16068 	ASSERT(OK_32PTR(rptr));
16069 
16070 	/* Template header */
16071 	tcp_tmpl = tcp->tcp_tcpha;
16072 
16073 	/* Header of outgoing packet */
16074 	tcpha = (tcpha_t *)(rptr + connp->conn_ixa->ixa_ip_hdr_length);
16075 
16076 	/* dst and src are opaque 32-bit fields, used for copying */
16077 	dst = (uint32_t *)rptr;
16078 	src = (uint32_t *)connp->conn_ht_iphc;
16079 	hdrlen = connp->conn_ht_iphc_len;
16080 
16081 	/* Fill time-stamp option if needed */
16082 	if (tcp->tcp_snd_ts_ok) {
16083 		U32_TO_BE32((uint32_t)now,
16084 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
16085 		U32_TO_BE32(tcp->tcp_ts_recent,
16086 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
16087 	} else {
16088 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
16089 	}
16090 
16091 	/*
16092 	 * Copy the template header; is this really more efficient than
16093 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
16094 	 * but perhaps not for other scenarios.
16095 	 */
16096 	dst[0] = src[0];
16097 	dst[1] = src[1];
16098 	dst[2] = src[2];
16099 	dst[3] = src[3];
16100 	dst[4] = src[4];
16101 	dst[5] = src[5];
16102 	dst[6] = src[6];
16103 	dst[7] = src[7];
16104 	dst[8] = src[8];
16105 	dst[9] = src[9];
16106 	if (hdrlen -= 40) {
16107 		hdrlen >>= 2;
16108 		dst += 10;
16109 		src += 10;
16110 		do {
16111 			*dst++ = *src++;
16112 		} while (--hdrlen);
16113 	}
16114 
16115 	/*
16116 	 * Set the ECN info in the TCP header if it is not a zero
16117 	 * window probe.  Zero window probe is only sent in
16118 	 * tcp_wput_data() and tcp_timer().
16119 	 */
16120 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
16121 		SET_ECT(tcp, rptr);
16122 
16123 		if (tcp->tcp_ecn_echo_on)
16124 			tcpha->tha_flags |= TH_ECE;
16125 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16126 			tcpha->tha_flags |= TH_CWR;
16127 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16128 		}
16129 	}
16130 
16131 	/* Fill in SACK options */
16132 	if (num_sack_blk > 0) {
16133 		uchar_t *wptr = rptr + connp->conn_ht_iphc_len;
16134 		sack_blk_t *tmp;
16135 		int32_t	i;
16136 
16137 		wptr[0] = TCPOPT_NOP;
16138 		wptr[1] = TCPOPT_NOP;
16139 		wptr[2] = TCPOPT_SACK;
16140 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
16141 		    sizeof (sack_blk_t);
16142 		wptr += TCPOPT_REAL_SACK_LEN;
16143 
16144 		tmp = tcp->tcp_sack_list;
16145 		for (i = 0; i < num_sack_blk; i++) {
16146 			U32_TO_BE32(tmp[i].begin, wptr);
16147 			wptr += sizeof (tcp_seq);
16148 			U32_TO_BE32(tmp[i].end, wptr);
16149 			wptr += sizeof (tcp_seq);
16150 		}
16151 		tcpha->tha_offset_and_reserved +=
16152 		    ((num_sack_blk * 2 + 1) << 4);
16153 	}
16154 }
16155 
16156 /*
16157  * tcp_send() is called by tcp_wput_data() and returns one of the following:
16158  *
16159  * -1 = failed allocation.
16160  *  0 = success; burst count reached, or usable send window is too small,
16161  *      and that we'd rather wait until later before sending again.
16162  */
16163 static int
16164 tcp_send(tcp_t *tcp, const int mss, const int total_hdr_len,
16165     const int tcp_hdr_len, const int num_sack_blk, int *usable,
16166     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time)
16167 {
16168 	int		num_burst_seg = tcp->tcp_snd_burst;
16169 	int		num_lso_seg = 1;
16170 	uint_t		lso_usable;
16171 	boolean_t	do_lso_send = B_FALSE;
16172 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16173 	conn_t		*connp = tcp->tcp_connp;
16174 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
16175 
16176 	/*
16177 	 * Check LSO possibility. The value of tcp->tcp_lso indicates whether
16178 	 * the underlying connection is LSO capable. Will check whether having
16179 	 * enough available data to initiate LSO transmission in the for(){}
16180 	 * loops.
16181 	 */
16182 	if (tcp->tcp_lso && (tcp->tcp_valid_bits & ~TCP_FSS_VALID) == 0)
16183 		do_lso_send = B_TRUE;
16184 
16185 	for (;;) {
16186 		struct datab	*db;
16187 		tcpha_t		*tcpha;
16188 		uint32_t	sum;
16189 		mblk_t		*mp, *mp1;
16190 		uchar_t		*rptr;
16191 		int		len;
16192 
16193 		/*
16194 		 * Burst count reached, return successfully.
16195 		 */
16196 		if (num_burst_seg == 0)
16197 			break;
16198 
16199 		/*
16200 		 * Calculate the maximum payload length we can send at one
16201 		 * time.
16202 		 */
16203 		if (do_lso_send) {
16204 			/*
16205 			 * Check whether be able to to do LSO for the current
16206 			 * available data.
16207 			 */
16208 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
16209 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
16210 				lso_usable = MIN(lso_usable,
16211 				    num_burst_seg * mss);
16212 
16213 				num_lso_seg = lso_usable / mss;
16214 				if (lso_usable % mss) {
16215 					num_lso_seg++;
16216 					tcp->tcp_last_sent_len = (ushort_t)
16217 					    (lso_usable % mss);
16218 				} else {
16219 					tcp->tcp_last_sent_len = (ushort_t)mss;
16220 				}
16221 			} else {
16222 				do_lso_send = B_FALSE;
16223 				num_lso_seg = 1;
16224 				lso_usable = mss;
16225 			}
16226 		}
16227 
16228 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
16229 #ifdef DEBUG
16230 		DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg, boolean_t,
16231 		    do_lso_send);
16232 #endif
16233 		/*
16234 		 * Adjust num_burst_seg here.
16235 		 */
16236 		num_burst_seg -= num_lso_seg;
16237 
16238 		len = mss;
16239 		if (len > *usable) {
16240 			ASSERT(do_lso_send == B_FALSE);
16241 
16242 			len = *usable;
16243 			if (len <= 0) {
16244 				/* Terminate the loop */
16245 				break;	/* success; too small */
16246 			}
16247 			/*
16248 			 * Sender silly-window avoidance.
16249 			 * Ignore this if we are going to send a
16250 			 * zero window probe out.
16251 			 *
16252 			 * TODO: force data into microscopic window?
16253 			 *	==> (!pushed || (unsent > usable))
16254 			 */
16255 			if (len < (tcp->tcp_max_swnd >> 1) &&
16256 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
16257 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
16258 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
16259 				/*
16260 				 * If the retransmit timer is not running
16261 				 * we start it so that we will retransmit
16262 				 * in the case when the receiver has
16263 				 * decremented the window.
16264 				 */
16265 				if (*snxt == tcp->tcp_snxt &&
16266 				    *snxt == tcp->tcp_suna) {
16267 					/*
16268 					 * We are not supposed to send
16269 					 * anything.  So let's wait a little
16270 					 * bit longer before breaking SWS
16271 					 * avoidance.
16272 					 *
16273 					 * What should the value be?
16274 					 * Suggestion: MAX(init rexmit time,
16275 					 * tcp->tcp_rto)
16276 					 */
16277 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16278 				}
16279 				break;	/* success; too small */
16280 			}
16281 		}
16282 
16283 		tcpha = tcp->tcp_tcpha;
16284 
16285 		/*
16286 		 * The reason to adjust len here is that we need to set flags
16287 		 * and calculate checksum.
16288 		 */
16289 		if (do_lso_send)
16290 			len = lso_usable;
16291 
16292 		*usable -= len; /* Approximate - can be adjusted later */
16293 		if (*usable > 0)
16294 			tcpha->tha_flags = TH_ACK;
16295 		else
16296 			tcpha->tha_flags = (TH_ACK | TH_PUSH);
16297 
16298 		/*
16299 		 * Prime pump for IP's checksumming on our behalf.
16300 		 * Include the adjustment for a source route if any.
16301 		 * In case of LSO, the partial pseudo-header checksum should
16302 		 * exclusive TCP length, so zero tha_sum before IP calculate
16303 		 * pseudo-header checksum for partial checksum offload.
16304 		 */
16305 		if (do_lso_send) {
16306 			sum = 0;
16307 		} else {
16308 			sum = len + tcp_hdr_len + connp->conn_sum;
16309 			sum = (sum >> 16) + (sum & 0xFFFF);
16310 		}
16311 		tcpha->tha_sum = htons(sum);
16312 		tcpha->tha_seq = htonl(*snxt);
16313 
16314 		/*
16315 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
16316 		 * set.  For the case when TCP_FSS_VALID is the only valid
16317 		 * bit (normal active close), branch off only when we think
16318 		 * that the FIN flag needs to be set.  Note for this case,
16319 		 * that (snxt + len) may not reflect the actual seg_len,
16320 		 * as len may be further reduced in tcp_xmit_mp().  If len
16321 		 * gets modified, we will end up here again.
16322 		 */
16323 		if (tcp->tcp_valid_bits != 0 &&
16324 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
16325 		    ((*snxt + len) == tcp->tcp_fss))) {
16326 			uchar_t		*prev_rptr;
16327 			uint32_t	prev_snxt = tcp->tcp_snxt;
16328 
16329 			if (*tail_unsent == 0) {
16330 				ASSERT((*xmit_tail)->b_cont != NULL);
16331 				*xmit_tail = (*xmit_tail)->b_cont;
16332 				prev_rptr = (*xmit_tail)->b_rptr;
16333 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
16334 				    (*xmit_tail)->b_rptr);
16335 			} else {
16336 				prev_rptr = (*xmit_tail)->b_rptr;
16337 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
16338 				    *tail_unsent;
16339 			}
16340 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
16341 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
16342 			/* Restore tcp_snxt so we get amount sent right. */
16343 			tcp->tcp_snxt = prev_snxt;
16344 			if (prev_rptr == (*xmit_tail)->b_rptr) {
16345 				/*
16346 				 * If the previous timestamp is still in use,
16347 				 * don't stomp on it.
16348 				 */
16349 				if ((*xmit_tail)->b_next == NULL) {
16350 					(*xmit_tail)->b_prev = local_time;
16351 					(*xmit_tail)->b_next =
16352 					    (mblk_t *)(uintptr_t)(*snxt);
16353 				}
16354 			} else
16355 				(*xmit_tail)->b_rptr = prev_rptr;
16356 
16357 			if (mp == NULL) {
16358 				return (-1);
16359 			}
16360 			mp1 = mp->b_cont;
16361 
16362 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
16363 				tcp->tcp_last_sent_len = (ushort_t)len;
16364 			while (mp1->b_cont) {
16365 				*xmit_tail = (*xmit_tail)->b_cont;
16366 				(*xmit_tail)->b_prev = local_time;
16367 				(*xmit_tail)->b_next =
16368 				    (mblk_t *)(uintptr_t)(*snxt);
16369 				mp1 = mp1->b_cont;
16370 			}
16371 			*snxt += len;
16372 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
16373 			BUMP_LOCAL(tcp->tcp_obsegs);
16374 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16375 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16376 			tcp_send_data(tcp, mp);
16377 			continue;
16378 		}
16379 
16380 		*snxt += len;	/* Adjust later if we don't send all of len */
16381 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16382 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16383 
16384 		if (*tail_unsent) {
16385 			/* Are the bytes above us in flight? */
16386 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
16387 			if (rptr != (*xmit_tail)->b_rptr) {
16388 				*tail_unsent -= len;
16389 				if (len <= mss) /* LSO is unusable */
16390 					tcp->tcp_last_sent_len = (ushort_t)len;
16391 				len += total_hdr_len;
16392 				ixa->ixa_pktlen = len;
16393 
16394 				if (ixa->ixa_flags & IXAF_IS_IPV4) {
16395 					tcp->tcp_ipha->ipha_length = htons(len);
16396 				} else {
16397 					tcp->tcp_ip6h->ip6_plen =
16398 					    htons(len - IPV6_HDR_LEN);
16399 				}
16400 
16401 				mp = dupb(*xmit_tail);
16402 				if (mp == NULL) {
16403 					return (-1);	/* out_of_mem */
16404 				}
16405 				mp->b_rptr = rptr;
16406 				/*
16407 				 * If the old timestamp is no longer in use,
16408 				 * sample a new timestamp now.
16409 				 */
16410 				if ((*xmit_tail)->b_next == NULL) {
16411 					(*xmit_tail)->b_prev = local_time;
16412 					(*xmit_tail)->b_next =
16413 					    (mblk_t *)(uintptr_t)(*snxt-len);
16414 				}
16415 				goto must_alloc;
16416 			}
16417 		} else {
16418 			*xmit_tail = (*xmit_tail)->b_cont;
16419 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
16420 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
16421 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
16422 			    (*xmit_tail)->b_rptr);
16423 		}
16424 
16425 		(*xmit_tail)->b_prev = local_time;
16426 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
16427 
16428 		*tail_unsent -= len;
16429 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
16430 			tcp->tcp_last_sent_len = (ushort_t)len;
16431 
16432 		len += total_hdr_len;
16433 		ixa->ixa_pktlen = len;
16434 
16435 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
16436 			tcp->tcp_ipha->ipha_length = htons(len);
16437 		} else {
16438 			tcp->tcp_ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
16439 		}
16440 
16441 		mp = dupb(*xmit_tail);
16442 		if (mp == NULL) {
16443 			return (-1);	/* out_of_mem */
16444 		}
16445 
16446 		len = total_hdr_len;
16447 		/*
16448 		 * There are four reasons to allocate a new hdr mblk:
16449 		 *  1) The bytes above us are in use by another packet
16450 		 *  2) We don't have good alignment
16451 		 *  3) The mblk is being shared
16452 		 *  4) We don't have enough room for a header
16453 		 */
16454 		rptr = mp->b_rptr - len;
16455 		if (!OK_32PTR(rptr) ||
16456 		    ((db = mp->b_datap), db->db_ref != 2) ||
16457 		    rptr < db->db_base) {
16458 			/* NOTE: we assume allocb returns an OK_32PTR */
16459 
16460 		must_alloc:;
16461 			mp1 = allocb(connp->conn_ht_iphc_allocated +
16462 			    tcps->tcps_wroff_xtra, BPRI_MED);
16463 			if (mp1 == NULL) {
16464 				freemsg(mp);
16465 				return (-1);	/* out_of_mem */
16466 			}
16467 			mp1->b_cont = mp;
16468 			mp = mp1;
16469 			/* Leave room for Link Level header */
16470 			len = total_hdr_len;
16471 			rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
16472 			mp->b_wptr = &rptr[len];
16473 		}
16474 
16475 		/*
16476 		 * Fill in the header using the template header, and add
16477 		 * options such as time-stamp, ECN and/or SACK, as needed.
16478 		 */
16479 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
16480 
16481 		mp->b_rptr = rptr;
16482 
16483 		if (*tail_unsent) {
16484 			int spill = *tail_unsent;
16485 
16486 			mp1 = mp->b_cont;
16487 			if (mp1 == NULL)
16488 				mp1 = mp;
16489 
16490 			/*
16491 			 * If we're a little short, tack on more mblks until
16492 			 * there is no more spillover.
16493 			 */
16494 			while (spill < 0) {
16495 				mblk_t *nmp;
16496 				int nmpsz;
16497 
16498 				nmp = (*xmit_tail)->b_cont;
16499 				nmpsz = MBLKL(nmp);
16500 
16501 				/*
16502 				 * Excess data in mblk; can we split it?
16503 				 * If LSO is enabled for the connection,
16504 				 * keep on splitting as this is a transient
16505 				 * send path.
16506 				 */
16507 				if (!do_lso_send && (spill + nmpsz > 0)) {
16508 					/*
16509 					 * Don't split if stream head was
16510 					 * told to break up larger writes
16511 					 * into smaller ones.
16512 					 */
16513 					if (tcp->tcp_maxpsz_multiplier > 0)
16514 						break;
16515 
16516 					/*
16517 					 * Next mblk is less than SMSS/2
16518 					 * rounded up to nearest 64-byte;
16519 					 * let it get sent as part of the
16520 					 * next segment.
16521 					 */
16522 					if (tcp->tcp_localnet &&
16523 					    !tcp->tcp_cork &&
16524 					    (nmpsz < roundup((mss >> 1), 64)))
16525 						break;
16526 				}
16527 
16528 				*xmit_tail = nmp;
16529 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
16530 				/* Stash for rtt use later */
16531 				(*xmit_tail)->b_prev = local_time;
16532 				(*xmit_tail)->b_next =
16533 				    (mblk_t *)(uintptr_t)(*snxt - len);
16534 				mp1->b_cont = dupb(*xmit_tail);
16535 				mp1 = mp1->b_cont;
16536 
16537 				spill += nmpsz;
16538 				if (mp1 == NULL) {
16539 					*tail_unsent = spill;
16540 					freemsg(mp);
16541 					return (-1);	/* out_of_mem */
16542 				}
16543 			}
16544 
16545 			/* Trim back any surplus on the last mblk */
16546 			if (spill >= 0) {
16547 				mp1->b_wptr -= spill;
16548 				*tail_unsent = spill;
16549 			} else {
16550 				/*
16551 				 * We did not send everything we could in
16552 				 * order to remain within the b_cont limit.
16553 				 */
16554 				*usable -= spill;
16555 				*snxt += spill;
16556 				tcp->tcp_last_sent_len += spill;
16557 				UPDATE_MIB(&tcps->tcps_mib,
16558 				    tcpOutDataBytes, spill);
16559 				/*
16560 				 * Adjust the checksum
16561 				 */
16562 				tcpha = (tcpha_t *)(rptr +
16563 				    ixa->ixa_ip_hdr_length);
16564 				sum += spill;
16565 				sum = (sum >> 16) + (sum & 0xFFFF);
16566 				tcpha->tha_sum = htons(sum);
16567 				if (connp->conn_ipversion == IPV4_VERSION) {
16568 					sum = ntohs(
16569 					    ((ipha_t *)rptr)->ipha_length) +
16570 					    spill;
16571 					((ipha_t *)rptr)->ipha_length =
16572 					    htons(sum);
16573 				} else {
16574 					sum = ntohs(
16575 					    ((ip6_t *)rptr)->ip6_plen) +
16576 					    spill;
16577 					((ip6_t *)rptr)->ip6_plen =
16578 					    htons(sum);
16579 				}
16580 				ixa->ixa_pktlen += spill;
16581 				*tail_unsent = 0;
16582 			}
16583 		}
16584 		if (tcp->tcp_ip_forward_progress) {
16585 			tcp->tcp_ip_forward_progress = B_FALSE;
16586 			ixa->ixa_flags |= IXAF_REACH_CONF;
16587 		} else {
16588 			ixa->ixa_flags &= ~IXAF_REACH_CONF;
16589 		}
16590 
16591 		if (do_lso_send) {
16592 			/* Append LSO information to the mp. */
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 			/*
16612 			 * Make sure to clean up LSO information. Wherever a
16613 			 * new mp uses the prepended header room after dupb(),
16614 			 * lso_info_cleanup() should be called.
16615 			 */
16616 			lso_info_cleanup(mp);
16617 			tcp_send_data(tcp, mp);
16618 			BUMP_LOCAL(tcp->tcp_obsegs);
16619 		}
16620 	}
16621 
16622 	return (0);
16623 }
16624 
16625 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
16626 static void
16627 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
16628 {
16629 	uchar_t	fval = *mp->b_rptr;
16630 	mblk_t	*tail;
16631 	conn_t	*connp = tcp->tcp_connp;
16632 	queue_t	*q = connp->conn_wq;
16633 
16634 	/* TODO: How should flush interact with urgent data? */
16635 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
16636 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
16637 		/*
16638 		 * Flush only data that has not yet been put on the wire.  If
16639 		 * we flush data that we have already transmitted, life, as we
16640 		 * know it, may come to an end.
16641 		 */
16642 		tail = tcp->tcp_xmit_tail;
16643 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
16644 		tcp->tcp_xmit_tail_unsent = 0;
16645 		tcp->tcp_unsent = 0;
16646 		if (tail->b_wptr != tail->b_rptr)
16647 			tail = tail->b_cont;
16648 		if (tail) {
16649 			mblk_t **excess = &tcp->tcp_xmit_head;
16650 			for (;;) {
16651 				mblk_t *mp1 = *excess;
16652 				if (mp1 == tail)
16653 					break;
16654 				tcp->tcp_xmit_tail = mp1;
16655 				tcp->tcp_xmit_last = mp1;
16656 				excess = &mp1->b_cont;
16657 			}
16658 			*excess = NULL;
16659 			tcp_close_mpp(&tail);
16660 			if (tcp->tcp_snd_zcopy_aware)
16661 				tcp_zcopy_notify(tcp);
16662 		}
16663 		/*
16664 		 * We have no unsent data, so unsent must be less than
16665 		 * conn_sndlowat, so re-enable flow.
16666 		 */
16667 		mutex_enter(&tcp->tcp_non_sq_lock);
16668 		if (tcp->tcp_flow_stopped) {
16669 			tcp_clrqfull(tcp);
16670 		}
16671 		mutex_exit(&tcp->tcp_non_sq_lock);
16672 	}
16673 	/*
16674 	 * TODO: you can't just flush these, you have to increase rwnd for one
16675 	 * thing.  For another, how should urgent data interact?
16676 	 */
16677 	if (fval & FLUSHR) {
16678 		*mp->b_rptr = fval & ~FLUSHW;
16679 		/* XXX */
16680 		qreply(q, mp);
16681 		return;
16682 	}
16683 	freemsg(mp);
16684 }
16685 
16686 /*
16687  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
16688  * messages.
16689  */
16690 static void
16691 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
16692 {
16693 	mblk_t		*mp1;
16694 	struct iocblk	*iocp = (struct iocblk *)mp->b_rptr;
16695 	STRUCT_HANDLE(strbuf, sb);
16696 	uint_t		addrlen;
16697 	conn_t		*connp = tcp->tcp_connp;
16698 	queue_t 	*q = connp->conn_wq;
16699 
16700 	/* Make sure it is one of ours. */
16701 	switch (iocp->ioc_cmd) {
16702 	case TI_GETMYNAME:
16703 	case TI_GETPEERNAME:
16704 		break;
16705 	default:
16706 		/*
16707 		 * If the conn is closing, then error the ioctl here. Otherwise
16708 		 * use the CONN_IOCTLREF_* macros to hold off tcp_close until
16709 		 * we're done here. We also need to decrement the ioctlref which
16710 		 * was bumped in either tcp_ioctl or tcp_wput_ioctl.
16711 		 */
16712 		mutex_enter(&connp->conn_lock);
16713 		if (connp->conn_state_flags & CONN_CLOSING) {
16714 			mutex_exit(&connp->conn_lock);
16715 			iocp = (struct iocblk *)mp->b_rptr;
16716 			iocp->ioc_error = EINVAL;
16717 			mp->b_datap->db_type = M_IOCNAK;
16718 			iocp->ioc_count = 0;
16719 			qreply(q, mp);
16720 			return;
16721 		}
16722 
16723 		CONN_INC_IOCTLREF_LOCKED(connp);
16724 		ip_wput_nondata(q, mp);
16725 		CONN_DEC_IOCTLREF(connp);
16726 		return;
16727 	}
16728 	switch (mi_copy_state(q, mp, &mp1)) {
16729 	case -1:
16730 		return;
16731 	case MI_COPY_CASE(MI_COPY_IN, 1):
16732 		break;
16733 	case MI_COPY_CASE(MI_COPY_OUT, 1):
16734 		/* Copy out the strbuf. */
16735 		mi_copyout(q, mp);
16736 		return;
16737 	case MI_COPY_CASE(MI_COPY_OUT, 2):
16738 		/* All done. */
16739 		mi_copy_done(q, mp, 0);
16740 		return;
16741 	default:
16742 		mi_copy_done(q, mp, EPROTO);
16743 		return;
16744 	}
16745 	/* Check alignment of the strbuf */
16746 	if (!OK_32PTR(mp1->b_rptr)) {
16747 		mi_copy_done(q, mp, EINVAL);
16748 		return;
16749 	}
16750 
16751 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
16752 
16753 	if (connp->conn_family == AF_INET)
16754 		addrlen = sizeof (sin_t);
16755 	else
16756 		addrlen = sizeof (sin6_t);
16757 
16758 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
16759 		mi_copy_done(q, mp, EINVAL);
16760 		return;
16761 	}
16762 
16763 	switch (iocp->ioc_cmd) {
16764 	case TI_GETMYNAME:
16765 		break;
16766 	case TI_GETPEERNAME:
16767 		if (tcp->tcp_state < TCPS_SYN_RCVD) {
16768 			mi_copy_done(q, mp, ENOTCONN);
16769 			return;
16770 		}
16771 		break;
16772 	}
16773 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
16774 	if (!mp1)
16775 		return;
16776 
16777 	STRUCT_FSET(sb, len, addrlen);
16778 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
16779 	case TI_GETMYNAME:
16780 		(void) conn_getsockname(connp, (struct sockaddr *)mp1->b_wptr,
16781 		    &addrlen);
16782 		break;
16783 	case TI_GETPEERNAME:
16784 		(void) conn_getpeername(connp, (struct sockaddr *)mp1->b_wptr,
16785 		    &addrlen);
16786 		break;
16787 	}
16788 	mp1->b_wptr += addrlen;
16789 	/* Copy out the address */
16790 	mi_copyout(q, mp);
16791 }
16792 
16793 static void
16794 tcp_use_pure_tpi(tcp_t *tcp)
16795 {
16796 	conn_t		*connp = tcp->tcp_connp;
16797 
16798 #ifdef	_ILP32
16799 	tcp->tcp_acceptor_id = (t_uscalar_t)connp->conn_rq;
16800 #else
16801 	tcp->tcp_acceptor_id = connp->conn_dev;
16802 #endif
16803 	/*
16804 	 * Insert this socket into the acceptor hash.
16805 	 * We might need it for T_CONN_RES message
16806 	 */
16807 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
16808 
16809 	tcp->tcp_issocket = B_FALSE;
16810 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
16811 }
16812 
16813 /*
16814  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
16815  * messages.
16816  */
16817 /* ARGSUSED */
16818 static void
16819 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16820 {
16821 	conn_t 		*connp = (conn_t *)arg;
16822 	tcp_t		*tcp = connp->conn_tcp;
16823 	queue_t		*q = connp->conn_wq;
16824 	struct iocblk	*iocp;
16825 
16826 	ASSERT(DB_TYPE(mp) == M_IOCTL);
16827 	/*
16828 	 * Try and ASSERT the minimum possible references on the
16829 	 * conn early enough. Since we are executing on write side,
16830 	 * the connection is obviously not detached and that means
16831 	 * there is a ref each for TCP and IP. Since we are behind
16832 	 * the squeue, the minimum references needed are 3. If the
16833 	 * conn is in classifier hash list, there should be an
16834 	 * extra ref for that (we check both the possibilities).
16835 	 */
16836 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16837 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16838 
16839 	iocp = (struct iocblk *)mp->b_rptr;
16840 	switch (iocp->ioc_cmd) {
16841 	case _SIOCSOCKFALLBACK:
16842 		/*
16843 		 * Either sockmod is about to be popped and the socket
16844 		 * would now be treated as a plain stream, or a module
16845 		 * is about to be pushed so we could no longer use read-
16846 		 * side synchronous streams for fused loopback tcp.
16847 		 * Drain any queued data and disable direct sockfs
16848 		 * interface from now on.
16849 		 */
16850 		if (!tcp->tcp_issocket) {
16851 			DB_TYPE(mp) = M_IOCNAK;
16852 			iocp->ioc_error = EINVAL;
16853 		} else {
16854 			tcp_use_pure_tpi(tcp);
16855 			DB_TYPE(mp) = M_IOCACK;
16856 			iocp->ioc_error = 0;
16857 		}
16858 		iocp->ioc_count = 0;
16859 		iocp->ioc_rval = 0;
16860 		qreply(q, mp);
16861 		return;
16862 	}
16863 
16864 	/*
16865 	 * If the conn is closing, then error the ioctl here. Otherwise bump the
16866 	 * conn_ioctlref to hold off tcp_close until we're done here.
16867 	 */
16868 	mutex_enter(&(connp)->conn_lock);
16869 	if ((connp)->conn_state_flags & CONN_CLOSING) {
16870 		mutex_exit(&(connp)->conn_lock);
16871 		iocp->ioc_error = EINVAL;
16872 		mp->b_datap->db_type = M_IOCNAK;
16873 		iocp->ioc_count = 0;
16874 		qreply(q, mp);
16875 		return;
16876 	}
16877 
16878 	CONN_INC_IOCTLREF_LOCKED(connp);
16879 	ip_wput_nondata(q, mp);
16880 	CONN_DEC_IOCTLREF(connp);
16881 }
16882 
16883 /*
16884  * This routine is called by tcp_wput() to handle all TPI requests.
16885  */
16886 /* ARGSUSED */
16887 static void
16888 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16889 {
16890 	conn_t		*connp = (conn_t *)arg;
16891 	tcp_t		*tcp = connp->conn_tcp;
16892 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
16893 	uchar_t		*rptr;
16894 	t_scalar_t	type;
16895 	cred_t		*cr;
16896 
16897 	/*
16898 	 * Try and ASSERT the minimum possible references on the
16899 	 * conn early enough. Since we are executing on write side,
16900 	 * the connection is obviously not detached and that means
16901 	 * there is a ref each for TCP and IP. Since we are behind
16902 	 * the squeue, the minimum references needed are 3. If the
16903 	 * conn is in classifier hash list, there should be an
16904 	 * extra ref for that (we check both the possibilities).
16905 	 */
16906 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16907 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16908 
16909 	rptr = mp->b_rptr;
16910 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
16911 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
16912 		type = ((union T_primitives *)rptr)->type;
16913 		if (type == T_EXDATA_REQ) {
16914 			tcp_output_urgent(connp, mp, arg2, NULL);
16915 		} else if (type != T_DATA_REQ) {
16916 			goto non_urgent_data;
16917 		} else {
16918 			/* TODO: options, flags, ... from user */
16919 			/* Set length to zero for reclamation below */
16920 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
16921 			freeb(mp);
16922 		}
16923 		return;
16924 	} else {
16925 		if (connp->conn_debug) {
16926 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
16927 			    "tcp_wput_proto, dropping one...");
16928 		}
16929 		freemsg(mp);
16930 		return;
16931 	}
16932 
16933 non_urgent_data:
16934 
16935 	switch ((int)tprim->type) {
16936 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
16937 		/*
16938 		 * save the kssl_ent_t from the next block, and convert this
16939 		 * back to a normal bind_req.
16940 		 */
16941 		if (mp->b_cont != NULL) {
16942 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
16943 
16944 			if (tcp->tcp_kssl_ent != NULL) {
16945 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
16946 				    KSSL_NO_PROXY);
16947 				tcp->tcp_kssl_ent = NULL;
16948 			}
16949 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
16950 			    sizeof (kssl_ent_t));
16951 			kssl_hold_ent(tcp->tcp_kssl_ent);
16952 			freemsg(mp->b_cont);
16953 			mp->b_cont = NULL;
16954 		}
16955 		tprim->type = T_BIND_REQ;
16956 
16957 	/* FALLTHROUGH */
16958 	case O_T_BIND_REQ:	/* bind request */
16959 	case T_BIND_REQ:	/* new semantics bind request */
16960 		tcp_tpi_bind(tcp, mp);
16961 		break;
16962 	case T_UNBIND_REQ:	/* unbind request */
16963 		tcp_tpi_unbind(tcp, mp);
16964 		break;
16965 	case O_T_CONN_RES:	/* old connection response XXX */
16966 	case T_CONN_RES:	/* connection response */
16967 		tcp_tli_accept(tcp, mp);
16968 		break;
16969 	case T_CONN_REQ:	/* connection request */
16970 		tcp_tpi_connect(tcp, mp);
16971 		break;
16972 	case T_DISCON_REQ:	/* disconnect request */
16973 		tcp_disconnect(tcp, mp);
16974 		break;
16975 	case T_CAPABILITY_REQ:
16976 		tcp_capability_req(tcp, mp);	/* capability request */
16977 		break;
16978 	case T_INFO_REQ:	/* information request */
16979 		tcp_info_req(tcp, mp);
16980 		break;
16981 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
16982 	case T_OPTMGMT_REQ:
16983 		/*
16984 		 * Note:  no support for snmpcom_req() through new
16985 		 * T_OPTMGMT_REQ. See comments in ip.c
16986 		 */
16987 
16988 		/*
16989 		 * All Solaris components should pass a db_credp
16990 		 * for this TPI message, hence we ASSERT.
16991 		 * But in case there is some other M_PROTO that looks
16992 		 * like a TPI message sent by some other kernel
16993 		 * component, we check and return an error.
16994 		 */
16995 		cr = msg_getcred(mp, NULL);
16996 		ASSERT(cr != NULL);
16997 		if (cr == NULL) {
16998 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
16999 			return;
17000 		}
17001 		/*
17002 		 * If EINPROGRESS is returned, the request has been queued
17003 		 * for subsequent processing by ip_restart_optmgmt(), which
17004 		 * will do the CONN_DEC_REF().
17005 		 */
17006 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
17007 			svr4_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17008 		} else {
17009 			tpi_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
17010 		}
17011 		break;
17012 
17013 	case T_UNITDATA_REQ:	/* unitdata request */
17014 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17015 		break;
17016 	case T_ORDREL_REQ:	/* orderly release req */
17017 		freemsg(mp);
17018 
17019 		if (tcp->tcp_fused)
17020 			tcp_unfuse(tcp);
17021 
17022 		if (tcp_xmit_end(tcp) != 0) {
17023 			/*
17024 			 * We were crossing FINs and got a reset from
17025 			 * the other side. Just ignore it.
17026 			 */
17027 			if (connp->conn_debug) {
17028 				(void) strlog(TCP_MOD_ID, 0, 1,
17029 				    SL_ERROR|SL_TRACE,
17030 				    "tcp_wput_proto, T_ORDREL_REQ out of "
17031 				    "state %s",
17032 				    tcp_display(tcp, NULL,
17033 				    DISP_ADDR_AND_PORT));
17034 			}
17035 		}
17036 		break;
17037 	case T_ADDR_REQ:
17038 		tcp_addr_req(tcp, mp);
17039 		break;
17040 	default:
17041 		if (connp->conn_debug) {
17042 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
17043 			    "tcp_wput_proto, bogus TPI msg, type %d",
17044 			    tprim->type);
17045 		}
17046 		/*
17047 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
17048 		 * to recover.
17049 		 */
17050 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
17051 		break;
17052 	}
17053 }
17054 
17055 /*
17056  * The TCP write service routine should never be called...
17057  */
17058 /* ARGSUSED */
17059 static void
17060 tcp_wsrv(queue_t *q)
17061 {
17062 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17063 
17064 	TCP_STAT(tcps, tcp_wsrv_called);
17065 }
17066 
17067 /*
17068  * Send out a control packet on the tcp connection specified.  This routine
17069  * is typically called where we need a simple ACK or RST generated.
17070  */
17071 static void
17072 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
17073 {
17074 	uchar_t		*rptr;
17075 	tcpha_t		*tcpha;
17076 	ipha_t		*ipha = NULL;
17077 	ip6_t		*ip6h = NULL;
17078 	uint32_t	sum;
17079 	int		total_hdr_len;
17080 	int		ip_hdr_len;
17081 	mblk_t		*mp;
17082 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17083 	conn_t		*connp = tcp->tcp_connp;
17084 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17085 
17086 	/*
17087 	 * Save sum for use in source route later.
17088 	 */
17089 	sum = connp->conn_ht_ulp_len + connp->conn_sum;
17090 	total_hdr_len = connp->conn_ht_iphc_len;
17091 	ip_hdr_len = ixa->ixa_ip_hdr_length;
17092 
17093 	/* If a text string is passed in with the request, pass it to strlog. */
17094 	if (str != NULL && connp->conn_debug) {
17095 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17096 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
17097 		    str, seq, ack, ctl);
17098 	}
17099 	mp = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17100 	    BPRI_MED);
17101 	if (mp == NULL) {
17102 		return;
17103 	}
17104 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
17105 	mp->b_rptr = rptr;
17106 	mp->b_wptr = &rptr[total_hdr_len];
17107 	bcopy(connp->conn_ht_iphc, rptr, total_hdr_len);
17108 
17109 	ixa->ixa_pktlen = total_hdr_len;
17110 
17111 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
17112 		ipha = (ipha_t *)rptr;
17113 		ipha->ipha_length = htons(total_hdr_len);
17114 	} else {
17115 		ip6h = (ip6_t *)rptr;
17116 		ip6h->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
17117 	}
17118 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17119 	tcpha->tha_flags = (uint8_t)ctl;
17120 	if (ctl & TH_RST) {
17121 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17122 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17123 		/*
17124 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
17125 		 */
17126 		if (tcp->tcp_snd_ts_ok &&
17127 		    tcp->tcp_state > TCPS_SYN_SENT) {
17128 			mp->b_wptr = &rptr[total_hdr_len - TCPOPT_REAL_TS_LEN];
17129 			*(mp->b_wptr) = TCPOPT_EOL;
17130 
17131 			ixa->ixa_pktlen = total_hdr_len - TCPOPT_REAL_TS_LEN;
17132 
17133 			if (connp->conn_ipversion == IPV4_VERSION) {
17134 				ipha->ipha_length = htons(total_hdr_len -
17135 				    TCPOPT_REAL_TS_LEN);
17136 			} else {
17137 				ip6h->ip6_plen = htons(total_hdr_len -
17138 				    IPV6_HDR_LEN - TCPOPT_REAL_TS_LEN);
17139 			}
17140 			tcpha->tha_offset_and_reserved -= (3 << 4);
17141 			sum -= TCPOPT_REAL_TS_LEN;
17142 		}
17143 	}
17144 	if (ctl & TH_ACK) {
17145 		if (tcp->tcp_snd_ts_ok) {
17146 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17147 
17148 			U32_TO_BE32(llbolt,
17149 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17150 			U32_TO_BE32(tcp->tcp_ts_recent,
17151 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17152 		}
17153 
17154 		/* Update the latest receive window size in TCP header. */
17155 		tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17156 		/* Track what we sent to the peer */
17157 		tcp->tcp_tcpha->tha_win = tcpha->tha_win;
17158 		tcp->tcp_rack = ack;
17159 		tcp->tcp_rack_cnt = 0;
17160 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
17161 	}
17162 	BUMP_LOCAL(tcp->tcp_obsegs);
17163 	tcpha->tha_seq = htonl(seq);
17164 	tcpha->tha_ack = htonl(ack);
17165 	/*
17166 	 * Include the adjustment for a source route if any.
17167 	 */
17168 	sum = (sum >> 16) + (sum & 0xFFFF);
17169 	tcpha->tha_sum = htons(sum);
17170 	tcp_send_data(tcp, mp);
17171 }
17172 
17173 /*
17174  * If this routine returns B_TRUE, TCP can generate a RST in response
17175  * to a segment.  If it returns B_FALSE, TCP should not respond.
17176  */
17177 static boolean_t
17178 tcp_send_rst_chk(tcp_stack_t *tcps)
17179 {
17180 	int64_t	now;
17181 
17182 	/*
17183 	 * TCP needs to protect itself from generating too many RSTs.
17184 	 * This can be a DoS attack by sending us random segments
17185 	 * soliciting RSTs.
17186 	 *
17187 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
17188 	 * in each 1 second interval.  In this way, TCP still generate
17189 	 * RSTs in normal cases but when under attack, the impact is
17190 	 * limited.
17191 	 */
17192 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
17193 		now = ddi_get_lbolt64();
17194 		if (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
17195 		    1*SECONDS) {
17196 			tcps->tcps_last_rst_intrvl = now;
17197 			tcps->tcps_rst_cnt = 1;
17198 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
17199 			return (B_FALSE);
17200 		}
17201 	}
17202 	return (B_TRUE);
17203 }
17204 
17205 /*
17206  * Generate a reset based on an inbound packet, connp is set by caller
17207  * when RST is in response to an unexpected inbound packet for which
17208  * there is active tcp state in the system.
17209  *
17210  * IPSEC NOTE : Try to send the reply with the same protection as it came
17211  * in.  We have the ip_recv_attr_t which is reversed to form the ip_xmit_attr_t.
17212  * That way the packet will go out at the same level of protection as it
17213  * came in with.
17214  */
17215 static void
17216 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl,
17217     ip_recv_attr_t *ira, ip_stack_t *ipst, conn_t *connp)
17218 {
17219 	ipha_t		*ipha = NULL;
17220 	ip6_t		*ip6h = NULL;
17221 	ushort_t	len;
17222 	tcpha_t		*tcpha;
17223 	int		i;
17224 	ipaddr_t	v4addr;
17225 	in6_addr_t	v6addr;
17226 	netstack_t	*ns = ipst->ips_netstack;
17227 	tcp_stack_t	*tcps = ns->netstack_tcp;
17228 	ip_xmit_attr_t	ixas, *ixa;
17229 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17230 	boolean_t	need_refrele = B_FALSE;		/* ixa_refrele(ixa) */
17231 	ushort_t	port;
17232 
17233 	if (!tcp_send_rst_chk(tcps)) {
17234 		TCP_STAT(tcps, tcp_rst_unsent);
17235 		freemsg(mp);
17236 		return;
17237 	}
17238 
17239 	/*
17240 	 * If connp != NULL we use conn_ixa to keep IP_NEXTHOP and other
17241 	 * options from the listener. In that case the caller must ensure that
17242 	 * we are running on the listener = connp squeue.
17243 	 *
17244 	 * We get a safe copy of conn_ixa so we don't need to restore anything
17245 	 * we or ip_output_simple might change in the ixa.
17246 	 */
17247 	if (connp != NULL) {
17248 		ASSERT(connp->conn_on_sqp);
17249 
17250 		ixa = conn_get_ixa_exclusive(connp);
17251 		if (ixa == NULL) {
17252 			TCP_STAT(tcps, tcp_rst_unsent);
17253 			freemsg(mp);
17254 			return;
17255 		}
17256 		need_refrele = B_TRUE;
17257 	} else {
17258 		bzero(&ixas, sizeof (ixas));
17259 		ixa = &ixas;
17260 		/*
17261 		 * IXAF_VERIFY_SOURCE is overkill since we know the
17262 		 * packet was for us.
17263 		 */
17264 		ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE;
17265 		ixa->ixa_protocol = IPPROTO_TCP;
17266 		ixa->ixa_zoneid = ira->ira_zoneid;
17267 		ixa->ixa_ifindex = 0;
17268 		ixa->ixa_ipst = ipst;
17269 		ixa->ixa_cred = kcred;
17270 		ixa->ixa_cpid = NOPID;
17271 	}
17272 
17273 	if (str && tcps->tcps_dbg) {
17274 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17275 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
17276 		    "flags 0x%x",
17277 		    str, seq, ack, ctl);
17278 	}
17279 	if (mp->b_datap->db_ref != 1) {
17280 		mblk_t *mp1 = copyb(mp);
17281 		freemsg(mp);
17282 		mp = mp1;
17283 		if (mp == NULL)
17284 			goto done;
17285 	} else if (mp->b_cont) {
17286 		freemsg(mp->b_cont);
17287 		mp->b_cont = NULL;
17288 		DB_CKSUMFLAGS(mp) = 0;
17289 	}
17290 	/*
17291 	 * We skip reversing source route here.
17292 	 * (for now we replace all IP options with EOL)
17293 	 */
17294 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17295 		ipha = (ipha_t *)mp->b_rptr;
17296 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
17297 			mp->b_rptr[i] = IPOPT_EOL;
17298 		/*
17299 		 * Make sure that src address isn't flagrantly invalid.
17300 		 * Not all broadcast address checking for the src address
17301 		 * is possible, since we don't know the netmask of the src
17302 		 * addr.  No check for destination address is done, since
17303 		 * IP will not pass up a packet with a broadcast dest
17304 		 * address to TCP.  Similar checks are done below for IPv6.
17305 		 */
17306 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
17307 		    CLASSD(ipha->ipha_src)) {
17308 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
17309 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17310 			freemsg(mp);
17311 			goto done;
17312 		}
17313 	} else {
17314 		ip6h = (ip6_t *)mp->b_rptr;
17315 
17316 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
17317 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
17318 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
17319 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17320 			freemsg(mp);
17321 			goto done;
17322 		}
17323 
17324 		/* Remove any extension headers assuming partial overlay */
17325 		if (ip_hdr_len > IPV6_HDR_LEN) {
17326 			uint8_t *to;
17327 
17328 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
17329 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
17330 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
17331 			ip_hdr_len = IPV6_HDR_LEN;
17332 			ip6h = (ip6_t *)mp->b_rptr;
17333 			ip6h->ip6_nxt = IPPROTO_TCP;
17334 		}
17335 	}
17336 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
17337 	if (tcpha->tha_flags & TH_RST) {
17338 		freemsg(mp);
17339 		goto done;
17340 	}
17341 	tcpha->tha_offset_and_reserved = (5 << 4);
17342 	len = ip_hdr_len + sizeof (tcpha_t);
17343 	mp->b_wptr = &mp->b_rptr[len];
17344 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17345 		ipha->ipha_length = htons(len);
17346 		/* Swap addresses */
17347 		v4addr = ipha->ipha_src;
17348 		ipha->ipha_src = ipha->ipha_dst;
17349 		ipha->ipha_dst = v4addr;
17350 		ipha->ipha_ident = 0;
17351 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
17352 		ixa->ixa_flags |= IXAF_IS_IPV4;
17353 		ixa->ixa_ip_hdr_length = ip_hdr_len;
17354 	} else {
17355 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
17356 		/* Swap addresses */
17357 		v6addr = ip6h->ip6_src;
17358 		ip6h->ip6_src = ip6h->ip6_dst;
17359 		ip6h->ip6_dst = v6addr;
17360 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
17361 		ixa->ixa_flags &= ~IXAF_IS_IPV4;
17362 
17363 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_dst)) {
17364 			ixa->ixa_flags |= IXAF_SCOPEID_SET;
17365 			ixa->ixa_scopeid = ira->ira_ruifindex;
17366 		}
17367 		ixa->ixa_ip_hdr_length = IPV6_HDR_LEN;
17368 	}
17369 	ixa->ixa_pktlen = len;
17370 
17371 	/* Swap the ports */
17372 	port = tcpha->tha_fport;
17373 	tcpha->tha_fport = tcpha->tha_lport;
17374 	tcpha->tha_lport = port;
17375 
17376 	tcpha->tha_ack = htonl(ack);
17377 	tcpha->tha_seq = htonl(seq);
17378 	tcpha->tha_win = 0;
17379 	tcpha->tha_sum = htons(sizeof (tcpha_t));
17380 	tcpha->tha_flags = (uint8_t)ctl;
17381 	if (ctl & TH_RST) {
17382 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17383 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17384 	}
17385 
17386 	/* Discard any old label */
17387 	if (ixa->ixa_free_flags & IXA_FREE_TSL) {
17388 		ASSERT(ixa->ixa_tsl != NULL);
17389 		label_rele(ixa->ixa_tsl);
17390 		ixa->ixa_free_flags &= ~IXA_FREE_TSL;
17391 	}
17392 	ixa->ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
17393 
17394 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
17395 		/*
17396 		 * Apply IPsec based on how IPsec was applied to
17397 		 * the packet that caused the RST.
17398 		 */
17399 		if (!ipsec_in_to_out(ira, ixa, mp, ipha, ip6h)) {
17400 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
17401 			/* Note: mp already consumed and ip_drop_packet done */
17402 			goto done;
17403 		}
17404 	} else {
17405 		/*
17406 		 * This is in clear. The RST message we are building
17407 		 * here should go out in clear, independent of our policy.
17408 		 */
17409 		ixa->ixa_flags |= IXAF_NO_IPSEC;
17410 	}
17411 
17412 	/*
17413 	 * NOTE:  one might consider tracing a TCP packet here, but
17414 	 * this function has no active TCP state and no tcp structure
17415 	 * that has a trace buffer.  If we traced here, we would have
17416 	 * to keep a local trace buffer in tcp_record_trace().
17417 	 */
17418 
17419 	(void) ip_output_simple(mp, ixa);
17420 done:
17421 	ixa_cleanup(ixa);
17422 	if (need_refrele) {
17423 		ASSERT(ixa != &ixas);
17424 		ixa_refrele(ixa);
17425 	}
17426 }
17427 
17428 /*
17429  * Initiate closedown sequence on an active connection.  (May be called as
17430  * writer.)  Return value zero for OK return, non-zero for error return.
17431  */
17432 static int
17433 tcp_xmit_end(tcp_t *tcp)
17434 {
17435 	mblk_t		*mp;
17436 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17437 	iulp_t		uinfo;
17438 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17439 	conn_t		*connp = tcp->tcp_connp;
17440 
17441 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
17442 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
17443 		/*
17444 		 * Invalid state, only states TCPS_SYN_RCVD,
17445 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
17446 		 */
17447 		return (-1);
17448 	}
17449 
17450 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
17451 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
17452 	/*
17453 	 * If there is nothing more unsent, send the FIN now.
17454 	 * Otherwise, it will go out with the last segment.
17455 	 */
17456 	if (tcp->tcp_unsent == 0) {
17457 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
17458 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
17459 
17460 		if (mp) {
17461 			tcp_send_data(tcp, mp);
17462 		} else {
17463 			/*
17464 			 * Couldn't allocate msg.  Pretend we got it out.
17465 			 * Wait for rexmit timeout.
17466 			 */
17467 			tcp->tcp_snxt = tcp->tcp_fss + 1;
17468 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17469 		}
17470 
17471 		/*
17472 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
17473 		 * changed.
17474 		 */
17475 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
17476 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
17477 		}
17478 	} else {
17479 		/*
17480 		 * If tcp->tcp_cork is set, then the data will not get sent,
17481 		 * so we have to check that and unset it first.
17482 		 */
17483 		if (tcp->tcp_cork)
17484 			tcp->tcp_cork = B_FALSE;
17485 		tcp_wput_data(tcp, NULL, B_FALSE);
17486 	}
17487 
17488 	/*
17489 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
17490 	 * is 0, don't update the cache.
17491 	 */
17492 	if (tcps->tcps_rtt_updates == 0 ||
17493 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
17494 		return (0);
17495 
17496 	/*
17497 	 * We do not have a good algorithm to update ssthresh at this time.
17498 	 * So don't do any update.
17499 	 */
17500 	bzero(&uinfo, sizeof (uinfo));
17501 	uinfo.iulp_rtt = tcp->tcp_rtt_sa;
17502 	uinfo.iulp_rtt_sd = tcp->tcp_rtt_sd;
17503 
17504 	/*
17505 	 * Note that uinfo is kept for conn_faddr in the DCE. Could update even
17506 	 * if source routed but we don't.
17507 	 */
17508 	if (connp->conn_ipversion == IPV4_VERSION) {
17509 		if (connp->conn_faddr_v4 !=  tcp->tcp_ipha->ipha_dst) {
17510 			return (0);
17511 		}
17512 		(void) dce_update_uinfo_v4(connp->conn_faddr_v4, &uinfo, ipst);
17513 	} else {
17514 		uint_t ifindex;
17515 
17516 		if (!(IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
17517 		    &tcp->tcp_ip6h->ip6_dst))) {
17518 			return (0);
17519 		}
17520 		ifindex = 0;
17521 		if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_faddr_v6)) {
17522 			ip_xmit_attr_t *ixa = connp->conn_ixa;
17523 
17524 			/*
17525 			 * If we are going to create a DCE we'd better have
17526 			 * an ifindex
17527 			 */
17528 			if (ixa->ixa_nce != NULL) {
17529 				ifindex = ixa->ixa_nce->nce_common->ncec_ill->
17530 				    ill_phyint->phyint_ifindex;
17531 			} else {
17532 				return (0);
17533 			}
17534 		}
17535 
17536 		(void) dce_update_uinfo(&connp->conn_faddr_v6, ifindex, &uinfo,
17537 		    ipst);
17538 	}
17539 	return (0);
17540 }
17541 
17542 /*
17543  * Generate a "no listener here" RST in response to an "unknown" segment.
17544  * connp is set by caller when RST is in response to an unexpected
17545  * inbound packet for which there is active tcp state in the system.
17546  * Note that we are reusing the incoming mp to construct the outgoing RST.
17547  */
17548 void
17549 tcp_xmit_listeners_reset(mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst,
17550     conn_t *connp)
17551 {
17552 	uchar_t		*rptr;
17553 	uint32_t	seg_len;
17554 	tcpha_t		*tcpha;
17555 	uint32_t	seg_seq;
17556 	uint32_t	seg_ack;
17557 	uint_t		flags;
17558 	ipha_t 		*ipha;
17559 	ip6_t 		*ip6h;
17560 	boolean_t	policy_present;
17561 	netstack_t	*ns = ipst->ips_netstack;
17562 	tcp_stack_t	*tcps = ns->netstack_tcp;
17563 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
17564 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17565 
17566 	TCP_STAT(tcps, tcp_no_listener);
17567 
17568 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17569 		policy_present = ipss->ipsec_inbound_v4_policy_present;
17570 		ipha = (ipha_t *)mp->b_rptr;
17571 		ip6h = NULL;
17572 	} else {
17573 		policy_present = ipss->ipsec_inbound_v6_policy_present;
17574 		ipha = NULL;
17575 		ip6h = (ip6_t *)mp->b_rptr;
17576 	}
17577 
17578 	if (policy_present) {
17579 		/*
17580 		 * The conn_t parameter is NULL because we already know
17581 		 * nobody's home.
17582 		 */
17583 		mp = ipsec_check_global_policy(mp, (conn_t *)NULL, ipha, ip6h,
17584 		    ira, ns);
17585 		if (mp == NULL)
17586 			return;
17587 	}
17588 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
17589 		DTRACE_PROBE2(
17590 		    tx__ip__log__error__nolistener__tcp,
17591 		    char *, "Could not reply with RST to mp(1)",
17592 		    mblk_t *, mp);
17593 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
17594 		freemsg(mp);
17595 		return;
17596 	}
17597 
17598 	rptr = mp->b_rptr;
17599 
17600 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17601 	seg_seq = ntohl(tcpha->tha_seq);
17602 	seg_ack = ntohl(tcpha->tha_ack);
17603 	flags = tcpha->tha_flags;
17604 
17605 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcpha) + ip_hdr_len);
17606 	if (flags & TH_RST) {
17607 		freemsg(mp);
17608 	} else if (flags & TH_ACK) {
17609 		tcp_xmit_early_reset("no tcp, reset", mp, seg_ack, 0, TH_RST,
17610 		    ira, ipst, connp);
17611 	} else {
17612 		if (flags & TH_SYN) {
17613 			seg_len++;
17614 		} else {
17615 			/*
17616 			 * Here we violate the RFC.  Note that a normal
17617 			 * TCP will never send a segment without the ACK
17618 			 * flag, except for RST or SYN segment.  This
17619 			 * segment is neither.  Just drop it on the
17620 			 * floor.
17621 			 */
17622 			freemsg(mp);
17623 			TCP_STAT(tcps, tcp_rst_unsent);
17624 			return;
17625 		}
17626 
17627 		tcp_xmit_early_reset("no tcp, reset/ack", mp, 0,
17628 		    seg_seq + seg_len, TH_RST | TH_ACK, ira, ipst, connp);
17629 	}
17630 }
17631 
17632 /*
17633  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
17634  * ip and tcp header ready to pass down to IP.  If the mp passed in is
17635  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
17636  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
17637  * otherwise it will dup partial mblks.)
17638  * Otherwise, an appropriate ACK packet will be generated.  This
17639  * routine is not usually called to send new data for the first time.  It
17640  * is mostly called out of the timer for retransmits, and to generate ACKs.
17641  *
17642  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
17643  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
17644  * of the original mblk chain will be returned in *offset and *end_mp.
17645  */
17646 mblk_t *
17647 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
17648     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
17649     boolean_t rexmit)
17650 {
17651 	int	data_length;
17652 	int32_t	off = 0;
17653 	uint_t	flags;
17654 	mblk_t	*mp1;
17655 	mblk_t	*mp2;
17656 	uchar_t	*rptr;
17657 	tcpha_t	*tcpha;
17658 	int32_t	num_sack_blk = 0;
17659 	int32_t	sack_opt_len = 0;
17660 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17661 	conn_t		*connp = tcp->tcp_connp;
17662 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17663 
17664 	/* Allocate for our maximum TCP header + link-level */
17665 	mp1 = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17666 	    BPRI_MED);
17667 	if (!mp1)
17668 		return (NULL);
17669 	data_length = 0;
17670 
17671 	/*
17672 	 * Note that tcp_mss has been adjusted to take into account the
17673 	 * timestamp option if applicable.  Because SACK options do not
17674 	 * appear in every TCP segments and they are of variable lengths,
17675 	 * they cannot be included in tcp_mss.  Thus we need to calculate
17676 	 * the actual segment length when we need to send a segment which
17677 	 * includes SACK options.
17678 	 */
17679 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
17680 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
17681 		    tcp->tcp_num_sack_blk);
17682 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
17683 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
17684 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
17685 			max_to_send -= sack_opt_len;
17686 	}
17687 
17688 	if (offset != NULL) {
17689 		off = *offset;
17690 		/* We use offset as an indicator that end_mp is not NULL. */
17691 		*end_mp = NULL;
17692 	}
17693 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
17694 		/* This could be faster with cooperation from downstream */
17695 		if (mp2 != mp1 && !sendall &&
17696 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
17697 		    max_to_send)
17698 			/*
17699 			 * Don't send the next mblk since the whole mblk
17700 			 * does not fit.
17701 			 */
17702 			break;
17703 		mp2->b_cont = dupb(mp);
17704 		mp2 = mp2->b_cont;
17705 		if (!mp2) {
17706 			freemsg(mp1);
17707 			return (NULL);
17708 		}
17709 		mp2->b_rptr += off;
17710 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
17711 		    (uintptr_t)INT_MAX);
17712 
17713 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
17714 		if (data_length > max_to_send) {
17715 			mp2->b_wptr -= data_length - max_to_send;
17716 			data_length = max_to_send;
17717 			off = mp2->b_wptr - mp->b_rptr;
17718 			break;
17719 		} else {
17720 			off = 0;
17721 		}
17722 	}
17723 	if (offset != NULL) {
17724 		*offset = off;
17725 		*end_mp = mp;
17726 	}
17727 	if (seg_len != NULL) {
17728 		*seg_len = data_length;
17729 	}
17730 
17731 	/* Update the latest receive window size in TCP header. */
17732 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17733 
17734 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
17735 	mp1->b_rptr = rptr;
17736 	mp1->b_wptr = rptr + connp->conn_ht_iphc_len + sack_opt_len;
17737 	bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
17738 	tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
17739 	tcpha->tha_seq = htonl(seq);
17740 
17741 	/*
17742 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
17743 	 * that this function was called from tcp_wput_data. Thus, when called
17744 	 * to retransmit data the setting of the PUSH bit may appear some
17745 	 * what random in that it might get set when it should not. This
17746 	 * should not pose any performance issues.
17747 	 */
17748 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
17749 	    tcp->tcp_unsent == data_length)) {
17750 		flags = TH_ACK | TH_PUSH;
17751 	} else {
17752 		flags = TH_ACK;
17753 	}
17754 
17755 	if (tcp->tcp_ecn_ok) {
17756 		if (tcp->tcp_ecn_echo_on)
17757 			flags |= TH_ECE;
17758 
17759 		/*
17760 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
17761 		 * There is no TCP flow control for non-data segments, and
17762 		 * only data segment is transmitted reliably.
17763 		 */
17764 		if (data_length > 0 && !rexmit) {
17765 			SET_ECT(tcp, rptr);
17766 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17767 				flags |= TH_CWR;
17768 				tcp->tcp_ecn_cwr_sent = B_TRUE;
17769 			}
17770 		}
17771 	}
17772 
17773 	if (tcp->tcp_valid_bits) {
17774 		uint32_t u1;
17775 
17776 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
17777 		    seq == tcp->tcp_iss) {
17778 			uchar_t	*wptr;
17779 
17780 			/*
17781 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
17782 			 * TCP can only be in SYN-SENT, SYN-RCVD or
17783 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
17784 			 * our SYN is not ack'ed but the app closes this
17785 			 * TCP connection.
17786 			 */
17787 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
17788 			    tcp->tcp_state == TCPS_SYN_RCVD ||
17789 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
17790 
17791 			/*
17792 			 * Tack on the MSS option.  It is always needed
17793 			 * for both active and passive open.
17794 			 *
17795 			 * MSS option value should be interface MTU - MIN
17796 			 * TCP/IP header according to RFC 793 as it means
17797 			 * the maximum segment size TCP can receive.  But
17798 			 * to get around some broken middle boxes/end hosts
17799 			 * out there, we allow the option value to be the
17800 			 * same as the MSS option size on the peer side.
17801 			 * In this way, the other side will not send
17802 			 * anything larger than they can receive.
17803 			 *
17804 			 * Note that for SYN_SENT state, the ndd param
17805 			 * tcp_use_smss_as_mss_opt has no effect as we
17806 			 * don't know the peer's MSS option value. So
17807 			 * the only case we need to take care of is in
17808 			 * SYN_RCVD state, which is done later.
17809 			 */
17810 			wptr = mp1->b_wptr;
17811 			wptr[0] = TCPOPT_MAXSEG;
17812 			wptr[1] = TCPOPT_MAXSEG_LEN;
17813 			wptr += 2;
17814 			u1 = tcp->tcp_initial_pmtu -
17815 			    (connp->conn_ipversion == IPV4_VERSION ?
17816 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
17817 			    TCP_MIN_HEADER_LENGTH;
17818 			U16_TO_BE16(u1, wptr);
17819 			mp1->b_wptr = wptr + 2;
17820 			/* Update the offset to cover the additional word */
17821 			tcpha->tha_offset_and_reserved += (1 << 4);
17822 
17823 			/*
17824 			 * Note that the following way of filling in
17825 			 * TCP options are not optimal.  Some NOPs can
17826 			 * be saved.  But there is no need at this time
17827 			 * to optimize it.  When it is needed, we will
17828 			 * do it.
17829 			 */
17830 			switch (tcp->tcp_state) {
17831 			case TCPS_SYN_SENT:
17832 				flags = TH_SYN;
17833 
17834 				if (tcp->tcp_snd_ts_ok) {
17835 					uint32_t llbolt =
17836 					    (uint32_t)LBOLT_FASTPATH;
17837 
17838 					wptr = mp1->b_wptr;
17839 					wptr[0] = TCPOPT_NOP;
17840 					wptr[1] = TCPOPT_NOP;
17841 					wptr[2] = TCPOPT_TSTAMP;
17842 					wptr[3] = TCPOPT_TSTAMP_LEN;
17843 					wptr += 4;
17844 					U32_TO_BE32(llbolt, wptr);
17845 					wptr += 4;
17846 					ASSERT(tcp->tcp_ts_recent == 0);
17847 					U32_TO_BE32(0L, wptr);
17848 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
17849 					tcpha->tha_offset_and_reserved +=
17850 					    (3 << 4);
17851 				}
17852 
17853 				/*
17854 				 * Set up all the bits to tell other side
17855 				 * we are ECN capable.
17856 				 */
17857 				if (tcp->tcp_ecn_ok) {
17858 					flags |= (TH_ECE | TH_CWR);
17859 				}
17860 				break;
17861 			case TCPS_SYN_RCVD:
17862 				flags |= TH_SYN;
17863 
17864 				/*
17865 				 * Reset the MSS option value to be SMSS
17866 				 * We should probably add back the bytes
17867 				 * for timestamp option and IPsec.  We
17868 				 * don't do that as this is a workaround
17869 				 * for broken middle boxes/end hosts, it
17870 				 * is better for us to be more cautious.
17871 				 * They may not take these things into
17872 				 * account in their SMSS calculation.  Thus
17873 				 * the peer's calculated SMSS may be smaller
17874 				 * than what it can be.  This should be OK.
17875 				 */
17876 				if (tcps->tcps_use_smss_as_mss_opt) {
17877 					u1 = tcp->tcp_mss;
17878 					U16_TO_BE16(u1, wptr);
17879 				}
17880 
17881 				/*
17882 				 * If the other side is ECN capable, reply
17883 				 * that we are also ECN capable.
17884 				 */
17885 				if (tcp->tcp_ecn_ok)
17886 					flags |= TH_ECE;
17887 				break;
17888 			default:
17889 				/*
17890 				 * The above ASSERT() makes sure that this
17891 				 * must be FIN-WAIT-1 state.  Our SYN has
17892 				 * not been ack'ed so retransmit it.
17893 				 */
17894 				flags |= TH_SYN;
17895 				break;
17896 			}
17897 
17898 			if (tcp->tcp_snd_ws_ok) {
17899 				wptr = mp1->b_wptr;
17900 				wptr[0] =  TCPOPT_NOP;
17901 				wptr[1] =  TCPOPT_WSCALE;
17902 				wptr[2] =  TCPOPT_WS_LEN;
17903 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
17904 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
17905 				tcpha->tha_offset_and_reserved += (1 << 4);
17906 			}
17907 
17908 			if (tcp->tcp_snd_sack_ok) {
17909 				wptr = mp1->b_wptr;
17910 				wptr[0] = TCPOPT_NOP;
17911 				wptr[1] = TCPOPT_NOP;
17912 				wptr[2] = TCPOPT_SACK_PERMITTED;
17913 				wptr[3] = TCPOPT_SACK_OK_LEN;
17914 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
17915 				tcpha->tha_offset_and_reserved += (1 << 4);
17916 			}
17917 
17918 			/* allocb() of adequate mblk assures space */
17919 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
17920 			    (uintptr_t)INT_MAX);
17921 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
17922 			/*
17923 			 * Get IP set to checksum on our behalf
17924 			 * Include the adjustment for a source route if any.
17925 			 */
17926 			u1 += connp->conn_sum;
17927 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
17928 			tcpha->tha_sum = htons(u1);
17929 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17930 		}
17931 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17932 		    (seq + data_length) == tcp->tcp_fss) {
17933 			if (!tcp->tcp_fin_acked) {
17934 				flags |= TH_FIN;
17935 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17936 			}
17937 			if (!tcp->tcp_fin_sent) {
17938 				tcp->tcp_fin_sent = B_TRUE;
17939 				switch (tcp->tcp_state) {
17940 				case TCPS_SYN_RCVD:
17941 				case TCPS_ESTABLISHED:
17942 					tcp->tcp_state = TCPS_FIN_WAIT_1;
17943 					break;
17944 				case TCPS_CLOSE_WAIT:
17945 					tcp->tcp_state = TCPS_LAST_ACK;
17946 					break;
17947 				}
17948 				if (tcp->tcp_suna == tcp->tcp_snxt)
17949 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17950 				tcp->tcp_snxt = tcp->tcp_fss + 1;
17951 			}
17952 		}
17953 		/*
17954 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
17955 		 * is smaller than seq, u1 will become a very huge value.
17956 		 * So the comparison will fail.  Also note that tcp_urp
17957 		 * should be positive, see RFC 793 page 17.
17958 		 */
17959 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
17960 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
17961 		    u1 < (uint32_t)(64 * 1024)) {
17962 			flags |= TH_URG;
17963 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
17964 			tcpha->tha_urp = htons(u1);
17965 		}
17966 	}
17967 	tcpha->tha_flags = (uchar_t)flags;
17968 	tcp->tcp_rack = tcp->tcp_rnxt;
17969 	tcp->tcp_rack_cnt = 0;
17970 
17971 	if (tcp->tcp_snd_ts_ok) {
17972 		if (tcp->tcp_state != TCPS_SYN_SENT) {
17973 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17974 
17975 			U32_TO_BE32(llbolt,
17976 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17977 			U32_TO_BE32(tcp->tcp_ts_recent,
17978 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17979 		}
17980 	}
17981 
17982 	if (num_sack_blk > 0) {
17983 		uchar_t *wptr = (uchar_t *)tcpha + connp->conn_ht_ulp_len;
17984 		sack_blk_t *tmp;
17985 		int32_t	i;
17986 
17987 		wptr[0] = TCPOPT_NOP;
17988 		wptr[1] = TCPOPT_NOP;
17989 		wptr[2] = TCPOPT_SACK;
17990 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
17991 		    sizeof (sack_blk_t);
17992 		wptr += TCPOPT_REAL_SACK_LEN;
17993 
17994 		tmp = tcp->tcp_sack_list;
17995 		for (i = 0; i < num_sack_blk; i++) {
17996 			U32_TO_BE32(tmp[i].begin, wptr);
17997 			wptr += sizeof (tcp_seq);
17998 			U32_TO_BE32(tmp[i].end, wptr);
17999 			wptr += sizeof (tcp_seq);
18000 		}
18001 		tcpha->tha_offset_and_reserved += ((num_sack_blk * 2 + 1) << 4);
18002 	}
18003 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
18004 	data_length += (int)(mp1->b_wptr - rptr);
18005 
18006 	ixa->ixa_pktlen = data_length;
18007 
18008 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
18009 		((ipha_t *)rptr)->ipha_length = htons(data_length);
18010 	} else {
18011 		ip6_t *ip6 = (ip6_t *)rptr;
18012 
18013 		ip6->ip6_plen = htons(data_length - IPV6_HDR_LEN);
18014 	}
18015 
18016 	/*
18017 	 * Prime pump for IP
18018 	 * Include the adjustment for a source route if any.
18019 	 */
18020 	data_length -= ixa->ixa_ip_hdr_length;
18021 	data_length += connp->conn_sum;
18022 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
18023 	tcpha->tha_sum = htons(data_length);
18024 	if (tcp->tcp_ip_forward_progress) {
18025 		tcp->tcp_ip_forward_progress = B_FALSE;
18026 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18027 	} else {
18028 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18029 	}
18030 	return (mp1);
18031 }
18032 
18033 /* This function handles the push timeout. */
18034 void
18035 tcp_push_timer(void *arg)
18036 {
18037 	conn_t	*connp = (conn_t *)arg;
18038 	tcp_t *tcp = connp->conn_tcp;
18039 
18040 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
18041 
18042 	ASSERT(tcp->tcp_listener == NULL);
18043 
18044 	ASSERT(!IPCL_IS_NONSTR(connp));
18045 
18046 	tcp->tcp_push_tid = 0;
18047 
18048 	if (tcp->tcp_rcv_list != NULL &&
18049 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
18050 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
18051 }
18052 
18053 /*
18054  * This function handles delayed ACK timeout.
18055  */
18056 static void
18057 tcp_ack_timer(void *arg)
18058 {
18059 	conn_t	*connp = (conn_t *)arg;
18060 	tcp_t *tcp = connp->conn_tcp;
18061 	mblk_t *mp;
18062 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18063 
18064 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
18065 
18066 	tcp->tcp_ack_tid = 0;
18067 
18068 	if (tcp->tcp_fused)
18069 		return;
18070 
18071 	/*
18072 	 * Do not send ACK if there is no outstanding unack'ed data.
18073 	 */
18074 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
18075 		return;
18076 	}
18077 
18078 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
18079 		/*
18080 		 * Make sure we don't allow deferred ACKs to result in
18081 		 * timer-based ACKing.  If we have held off an ACK
18082 		 * when there was more than an mss here, and the timer
18083 		 * goes off, we have to worry about the possibility
18084 		 * that the sender isn't doing slow-start, or is out
18085 		 * of step with us for some other reason.  We fall
18086 		 * permanently back in the direction of
18087 		 * ACK-every-other-packet as suggested in RFC 1122.
18088 		 */
18089 		if (tcp->tcp_rack_abs_max > 2)
18090 			tcp->tcp_rack_abs_max--;
18091 		tcp->tcp_rack_cur_max = 2;
18092 	}
18093 	mp = tcp_ack_mp(tcp);
18094 
18095 	if (mp != NULL) {
18096 		BUMP_LOCAL(tcp->tcp_obsegs);
18097 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
18098 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
18099 		tcp_send_data(tcp, mp);
18100 	}
18101 }
18102 
18103 
18104 /* Generate an ACK-only (no data) segment for a TCP endpoint */
18105 static mblk_t *
18106 tcp_ack_mp(tcp_t *tcp)
18107 {
18108 	uint32_t	seq_no;
18109 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18110 	conn_t		*connp = tcp->tcp_connp;
18111 
18112 	/*
18113 	 * There are a few cases to be considered while setting the sequence no.
18114 	 * Essentially, we can come here while processing an unacceptable pkt
18115 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
18116 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
18117 	 * If we are here for a zero window probe, stick with suna. In all
18118 	 * other cases, we check if suna + swnd encompasses snxt and set
18119 	 * the sequence number to snxt, if so. If snxt falls outside the
18120 	 * window (the receiver probably shrunk its window), we will go with
18121 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
18122 	 * receiver.
18123 	 */
18124 	if (tcp->tcp_zero_win_probe) {
18125 		seq_no = tcp->tcp_suna;
18126 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
18127 		ASSERT(tcp->tcp_swnd == 0);
18128 		seq_no = tcp->tcp_snxt;
18129 	} else {
18130 		seq_no = SEQ_GT(tcp->tcp_snxt,
18131 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
18132 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
18133 	}
18134 
18135 	if (tcp->tcp_valid_bits) {
18136 		/*
18137 		 * For the complex case where we have to send some
18138 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
18139 		 */
18140 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
18141 		    NULL, B_FALSE));
18142 	} else {
18143 		/* Generate a simple ACK */
18144 		int	data_length;
18145 		uchar_t	*rptr;
18146 		tcpha_t	*tcpha;
18147 		mblk_t	*mp1;
18148 		int32_t	total_hdr_len;
18149 		int32_t	tcp_hdr_len;
18150 		int32_t	num_sack_blk = 0;
18151 		int32_t sack_opt_len;
18152 		ip_xmit_attr_t *ixa = connp->conn_ixa;
18153 
18154 		/*
18155 		 * Allocate space for TCP + IP headers
18156 		 * and link-level header
18157 		 */
18158 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18159 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18160 			    tcp->tcp_num_sack_blk);
18161 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
18162 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
18163 			total_hdr_len = connp->conn_ht_iphc_len + sack_opt_len;
18164 			tcp_hdr_len = connp->conn_ht_ulp_len + sack_opt_len;
18165 		} else {
18166 			total_hdr_len = connp->conn_ht_iphc_len;
18167 			tcp_hdr_len = connp->conn_ht_ulp_len;
18168 		}
18169 		mp1 = allocb(total_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
18170 		if (!mp1)
18171 			return (NULL);
18172 
18173 		/* Update the latest receive window size in TCP header. */
18174 		tcp->tcp_tcpha->tha_win =
18175 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
18176 		/* copy in prototype TCP + IP header */
18177 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
18178 		mp1->b_rptr = rptr;
18179 		mp1->b_wptr = rptr + total_hdr_len;
18180 		bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
18181 
18182 		tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
18183 
18184 		/* Set the TCP sequence number. */
18185 		tcpha->tha_seq = htonl(seq_no);
18186 
18187 		/* Set up the TCP flag field. */
18188 		tcpha->tha_flags = (uchar_t)TH_ACK;
18189 		if (tcp->tcp_ecn_echo_on)
18190 			tcpha->tha_flags |= TH_ECE;
18191 
18192 		tcp->tcp_rack = tcp->tcp_rnxt;
18193 		tcp->tcp_rack_cnt = 0;
18194 
18195 		/* fill in timestamp option if in use */
18196 		if (tcp->tcp_snd_ts_ok) {
18197 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
18198 
18199 			U32_TO_BE32(llbolt,
18200 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
18201 			U32_TO_BE32(tcp->tcp_ts_recent,
18202 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
18203 		}
18204 
18205 		/* Fill in SACK options */
18206 		if (num_sack_blk > 0) {
18207 			uchar_t *wptr = (uchar_t *)tcpha +
18208 			    connp->conn_ht_ulp_len;
18209 			sack_blk_t *tmp;
18210 			int32_t	i;
18211 
18212 			wptr[0] = TCPOPT_NOP;
18213 			wptr[1] = TCPOPT_NOP;
18214 			wptr[2] = TCPOPT_SACK;
18215 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18216 			    sizeof (sack_blk_t);
18217 			wptr += TCPOPT_REAL_SACK_LEN;
18218 
18219 			tmp = tcp->tcp_sack_list;
18220 			for (i = 0; i < num_sack_blk; i++) {
18221 				U32_TO_BE32(tmp[i].begin, wptr);
18222 				wptr += sizeof (tcp_seq);
18223 				U32_TO_BE32(tmp[i].end, wptr);
18224 				wptr += sizeof (tcp_seq);
18225 			}
18226 			tcpha->tha_offset_and_reserved +=
18227 			    ((num_sack_blk * 2 + 1) << 4);
18228 		}
18229 
18230 		ixa->ixa_pktlen = total_hdr_len;
18231 
18232 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
18233 			((ipha_t *)rptr)->ipha_length = htons(total_hdr_len);
18234 		} else {
18235 			ip6_t *ip6 = (ip6_t *)rptr;
18236 
18237 			ip6->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
18238 		}
18239 
18240 		/*
18241 		 * Prime pump for checksum calculation in IP.  Include the
18242 		 * adjustment for a source route if any.
18243 		 */
18244 		data_length = tcp_hdr_len + connp->conn_sum;
18245 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
18246 		tcpha->tha_sum = htons(data_length);
18247 
18248 		if (tcp->tcp_ip_forward_progress) {
18249 			tcp->tcp_ip_forward_progress = B_FALSE;
18250 			connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18251 		} else {
18252 			connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18253 		}
18254 		return (mp1);
18255 	}
18256 }
18257 
18258 /*
18259  * Hash list insertion routine for tcp_t structures. Each hash bucket
18260  * contains a list of tcp_t entries, and each entry is bound to a unique
18261  * port. If there are multiple tcp_t's that are bound to the same port, then
18262  * one of them will be linked into the hash bucket list, and the rest will
18263  * hang off of that one entry. For each port, entries bound to a specific IP
18264  * address will be inserted before those those bound to INADDR_ANY.
18265  */
18266 static void
18267 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
18268 {
18269 	tcp_t	**tcpp;
18270 	tcp_t	*tcpnext;
18271 	tcp_t	*tcphash;
18272 	conn_t	*connp = tcp->tcp_connp;
18273 	conn_t	*connext;
18274 
18275 	if (tcp->tcp_ptpbhn != NULL) {
18276 		ASSERT(!caller_holds_lock);
18277 		tcp_bind_hash_remove(tcp);
18278 	}
18279 	tcpp = &tbf->tf_tcp;
18280 	if (!caller_holds_lock) {
18281 		mutex_enter(&tbf->tf_lock);
18282 	} else {
18283 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
18284 	}
18285 	tcphash = tcpp[0];
18286 	tcpnext = NULL;
18287 	if (tcphash != NULL) {
18288 		/* Look for an entry using the same port */
18289 		while ((tcphash = tcpp[0]) != NULL &&
18290 		    connp->conn_lport != tcphash->tcp_connp->conn_lport)
18291 			tcpp = &(tcphash->tcp_bind_hash);
18292 
18293 		/* The port was not found, just add to the end */
18294 		if (tcphash == NULL)
18295 			goto insert;
18296 
18297 		/*
18298 		 * OK, there already exists an entry bound to the
18299 		 * same port.
18300 		 *
18301 		 * If the new tcp bound to the INADDR_ANY address
18302 		 * and the first one in the list is not bound to
18303 		 * INADDR_ANY we skip all entries until we find the
18304 		 * first one bound to INADDR_ANY.
18305 		 * This makes sure that applications binding to a
18306 		 * specific address get preference over those binding to
18307 		 * INADDR_ANY.
18308 		 */
18309 		tcpnext = tcphash;
18310 		connext = tcpnext->tcp_connp;
18311 		tcphash = NULL;
18312 		if (V6_OR_V4_INADDR_ANY(connp->conn_bound_addr_v6) &&
18313 		    !V6_OR_V4_INADDR_ANY(connext->conn_bound_addr_v6)) {
18314 			while ((tcpnext = tcpp[0]) != NULL) {
18315 				connext = tcpnext->tcp_connp;
18316 				if (!V6_OR_V4_INADDR_ANY(
18317 				    connext->conn_bound_addr_v6))
18318 					tcpp = &(tcpnext->tcp_bind_hash_port);
18319 				else
18320 					break;
18321 			}
18322 			if (tcpnext != NULL) {
18323 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18324 				tcphash = tcpnext->tcp_bind_hash;
18325 				if (tcphash != NULL) {
18326 					tcphash->tcp_ptpbhn =
18327 					    &(tcp->tcp_bind_hash);
18328 					tcpnext->tcp_bind_hash = NULL;
18329 				}
18330 			}
18331 		} else {
18332 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18333 			tcphash = tcpnext->tcp_bind_hash;
18334 			if (tcphash != NULL) {
18335 				tcphash->tcp_ptpbhn =
18336 				    &(tcp->tcp_bind_hash);
18337 				tcpnext->tcp_bind_hash = NULL;
18338 			}
18339 		}
18340 	}
18341 insert:
18342 	tcp->tcp_bind_hash_port = tcpnext;
18343 	tcp->tcp_bind_hash = tcphash;
18344 	tcp->tcp_ptpbhn = tcpp;
18345 	tcpp[0] = tcp;
18346 	if (!caller_holds_lock)
18347 		mutex_exit(&tbf->tf_lock);
18348 }
18349 
18350 /*
18351  * Hash list removal routine for tcp_t structures.
18352  */
18353 static void
18354 tcp_bind_hash_remove(tcp_t *tcp)
18355 {
18356 	tcp_t	*tcpnext;
18357 	kmutex_t *lockp;
18358 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18359 	conn_t		*connp = tcp->tcp_connp;
18360 
18361 	if (tcp->tcp_ptpbhn == NULL)
18362 		return;
18363 
18364 	/*
18365 	 * Extract the lock pointer in case there are concurrent
18366 	 * hash_remove's for this instance.
18367 	 */
18368 	ASSERT(connp->conn_lport != 0);
18369 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(
18370 	    connp->conn_lport)].tf_lock;
18371 
18372 	ASSERT(lockp != NULL);
18373 	mutex_enter(lockp);
18374 	if (tcp->tcp_ptpbhn) {
18375 		tcpnext = tcp->tcp_bind_hash_port;
18376 		if (tcpnext != NULL) {
18377 			tcp->tcp_bind_hash_port = NULL;
18378 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18379 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
18380 			if (tcpnext->tcp_bind_hash != NULL) {
18381 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
18382 				    &(tcpnext->tcp_bind_hash);
18383 				tcp->tcp_bind_hash = NULL;
18384 			}
18385 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
18386 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18387 			tcp->tcp_bind_hash = NULL;
18388 		}
18389 		*tcp->tcp_ptpbhn = tcpnext;
18390 		tcp->tcp_ptpbhn = NULL;
18391 	}
18392 	mutex_exit(lockp);
18393 }
18394 
18395 
18396 /*
18397  * Hash list lookup routine for tcp_t structures.
18398  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
18399  */
18400 static tcp_t *
18401 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
18402 {
18403 	tf_t	*tf;
18404 	tcp_t	*tcp;
18405 
18406 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18407 	mutex_enter(&tf->tf_lock);
18408 	for (tcp = tf->tf_tcp; tcp != NULL;
18409 	    tcp = tcp->tcp_acceptor_hash) {
18410 		if (tcp->tcp_acceptor_id == id) {
18411 			CONN_INC_REF(tcp->tcp_connp);
18412 			mutex_exit(&tf->tf_lock);
18413 			return (tcp);
18414 		}
18415 	}
18416 	mutex_exit(&tf->tf_lock);
18417 	return (NULL);
18418 }
18419 
18420 
18421 /*
18422  * Hash list insertion routine for tcp_t structures.
18423  */
18424 void
18425 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
18426 {
18427 	tf_t	*tf;
18428 	tcp_t	**tcpp;
18429 	tcp_t	*tcpnext;
18430 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18431 
18432 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18433 
18434 	if (tcp->tcp_ptpahn != NULL)
18435 		tcp_acceptor_hash_remove(tcp);
18436 	tcpp = &tf->tf_tcp;
18437 	mutex_enter(&tf->tf_lock);
18438 	tcpnext = tcpp[0];
18439 	if (tcpnext)
18440 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
18441 	tcp->tcp_acceptor_hash = tcpnext;
18442 	tcp->tcp_ptpahn = tcpp;
18443 	tcpp[0] = tcp;
18444 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
18445 	mutex_exit(&tf->tf_lock);
18446 }
18447 
18448 /*
18449  * Hash list removal routine for tcp_t structures.
18450  */
18451 static void
18452 tcp_acceptor_hash_remove(tcp_t *tcp)
18453 {
18454 	tcp_t	*tcpnext;
18455 	kmutex_t *lockp;
18456 
18457 	/*
18458 	 * Extract the lock pointer in case there are concurrent
18459 	 * hash_remove's for this instance.
18460 	 */
18461 	lockp = tcp->tcp_acceptor_lockp;
18462 
18463 	if (tcp->tcp_ptpahn == NULL)
18464 		return;
18465 
18466 	ASSERT(lockp != NULL);
18467 	mutex_enter(lockp);
18468 	if (tcp->tcp_ptpahn) {
18469 		tcpnext = tcp->tcp_acceptor_hash;
18470 		if (tcpnext) {
18471 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
18472 			tcp->tcp_acceptor_hash = NULL;
18473 		}
18474 		*tcp->tcp_ptpahn = tcpnext;
18475 		tcp->tcp_ptpahn = NULL;
18476 	}
18477 	mutex_exit(lockp);
18478 	tcp->tcp_acceptor_lockp = NULL;
18479 }
18480 
18481 /*
18482  * Type three generator adapted from the random() function in 4.4 BSD:
18483  */
18484 
18485 /*
18486  * Copyright (c) 1983, 1993
18487  *	The Regents of the University of California.  All rights reserved.
18488  *
18489  * Redistribution and use in source and binary forms, with or without
18490  * modification, are permitted provided that the following conditions
18491  * are met:
18492  * 1. Redistributions of source code must retain the above copyright
18493  *    notice, this list of conditions and the following disclaimer.
18494  * 2. Redistributions in binary form must reproduce the above copyright
18495  *    notice, this list of conditions and the following disclaimer in the
18496  *    documentation and/or other materials provided with the distribution.
18497  * 3. All advertising materials mentioning features or use of this software
18498  *    must display the following acknowledgement:
18499  *	This product includes software developed by the University of
18500  *	California, Berkeley and its contributors.
18501  * 4. Neither the name of the University nor the names of its contributors
18502  *    may be used to endorse or promote products derived from this software
18503  *    without specific prior written permission.
18504  *
18505  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18506  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18507  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18508  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18509  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18510  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
18511  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
18512  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18513  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18514  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
18515  * SUCH DAMAGE.
18516  */
18517 
18518 /* Type 3 -- x**31 + x**3 + 1 */
18519 #define	DEG_3		31
18520 #define	SEP_3		3
18521 
18522 
18523 /* Protected by tcp_random_lock */
18524 static int tcp_randtbl[DEG_3 + 1];
18525 
18526 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
18527 static int *tcp_random_rptr = &tcp_randtbl[1];
18528 
18529 static int *tcp_random_state = &tcp_randtbl[1];
18530 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
18531 
18532 kmutex_t tcp_random_lock;
18533 
18534 void
18535 tcp_random_init(void)
18536 {
18537 	int i;
18538 	hrtime_t hrt;
18539 	time_t wallclock;
18540 	uint64_t result;
18541 
18542 	/*
18543 	 * Use high-res timer and current time for seed.  Gethrtime() returns
18544 	 * a longlong, which may contain resolution down to nanoseconds.
18545 	 * The current time will either be a 32-bit or a 64-bit quantity.
18546 	 * XOR the two together in a 64-bit result variable.
18547 	 * Convert the result to a 32-bit value by multiplying the high-order
18548 	 * 32-bits by the low-order 32-bits.
18549 	 */
18550 
18551 	hrt = gethrtime();
18552 	(void) drv_getparm(TIME, &wallclock);
18553 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
18554 	mutex_enter(&tcp_random_lock);
18555 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
18556 	    (result & 0xffffffff);
18557 
18558 	for (i = 1; i < DEG_3; i++)
18559 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
18560 		    + 12345;
18561 	tcp_random_fptr = &tcp_random_state[SEP_3];
18562 	tcp_random_rptr = &tcp_random_state[0];
18563 	mutex_exit(&tcp_random_lock);
18564 	for (i = 0; i < 10 * DEG_3; i++)
18565 		(void) tcp_random();
18566 }
18567 
18568 /*
18569  * tcp_random: Return a random number in the range [1 - (128K + 1)].
18570  * This range is selected to be approximately centered on TCP_ISS / 2,
18571  * and easy to compute. We get this value by generating a 32-bit random
18572  * number, selecting out the high-order 17 bits, and then adding one so
18573  * that we never return zero.
18574  */
18575 int
18576 tcp_random(void)
18577 {
18578 	int i;
18579 
18580 	mutex_enter(&tcp_random_lock);
18581 	*tcp_random_fptr += *tcp_random_rptr;
18582 
18583 	/*
18584 	 * The high-order bits are more random than the low-order bits,
18585 	 * so we select out the high-order 17 bits and add one so that
18586 	 * we never return zero.
18587 	 */
18588 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
18589 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
18590 		tcp_random_fptr = tcp_random_state;
18591 		++tcp_random_rptr;
18592 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
18593 		tcp_random_rptr = tcp_random_state;
18594 
18595 	mutex_exit(&tcp_random_lock);
18596 	return (i);
18597 }
18598 
18599 static int
18600 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
18601     int *t_errorp, int *sys_errorp)
18602 {
18603 	int error;
18604 	int is_absreq_failure;
18605 	t_scalar_t *opt_lenp;
18606 	t_scalar_t opt_offset;
18607 	int prim_type;
18608 	struct T_conn_req *tcreqp;
18609 	struct T_conn_res *tcresp;
18610 	cred_t *cr;
18611 
18612 	/*
18613 	 * All Solaris components should pass a db_credp
18614 	 * for this TPI message, hence we ASSERT.
18615 	 * But in case there is some other M_PROTO that looks
18616 	 * like a TPI message sent by some other kernel
18617 	 * component, we check and return an error.
18618 	 */
18619 	cr = msg_getcred(mp, NULL);
18620 	ASSERT(cr != NULL);
18621 	if (cr == NULL)
18622 		return (-1);
18623 
18624 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
18625 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
18626 	    prim_type == T_CONN_RES);
18627 
18628 	switch (prim_type) {
18629 	case T_CONN_REQ:
18630 		tcreqp = (struct T_conn_req *)mp->b_rptr;
18631 		opt_offset = tcreqp->OPT_offset;
18632 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
18633 		break;
18634 	case O_T_CONN_RES:
18635 	case T_CONN_RES:
18636 		tcresp = (struct T_conn_res *)mp->b_rptr;
18637 		opt_offset = tcresp->OPT_offset;
18638 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
18639 		break;
18640 	}
18641 
18642 	*t_errorp = 0;
18643 	*sys_errorp = 0;
18644 	*do_disconnectp = 0;
18645 
18646 	error = tpi_optcom_buf(tcp->tcp_connp->conn_wq, mp, opt_lenp,
18647 	    opt_offset, cr, &tcp_opt_obj,
18648 	    NULL, &is_absreq_failure);
18649 
18650 	switch (error) {
18651 	case  0:		/* no error */
18652 		ASSERT(is_absreq_failure == 0);
18653 		return (0);
18654 	case ENOPROTOOPT:
18655 		*t_errorp = TBADOPT;
18656 		break;
18657 	case EACCES:
18658 		*t_errorp = TACCES;
18659 		break;
18660 	default:
18661 		*t_errorp = TSYSERR; *sys_errorp = error;
18662 		break;
18663 	}
18664 	if (is_absreq_failure != 0) {
18665 		/*
18666 		 * The connection request should get the local ack
18667 		 * T_OK_ACK and then a T_DISCON_IND.
18668 		 */
18669 		*do_disconnectp = 1;
18670 	}
18671 	return (-1);
18672 }
18673 
18674 /*
18675  * Split this function out so that if the secret changes, I'm okay.
18676  *
18677  * Initialize the tcp_iss_cookie and tcp_iss_key.
18678  */
18679 
18680 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
18681 
18682 static void
18683 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
18684 {
18685 	struct {
18686 		int32_t current_time;
18687 		uint32_t randnum;
18688 		uint16_t pad;
18689 		uint8_t ether[6];
18690 		uint8_t passwd[PASSWD_SIZE];
18691 	} tcp_iss_cookie;
18692 	time_t t;
18693 
18694 	/*
18695 	 * Start with the current absolute time.
18696 	 */
18697 	(void) drv_getparm(TIME, &t);
18698 	tcp_iss_cookie.current_time = t;
18699 
18700 	/*
18701 	 * XXX - Need a more random number per RFC 1750, not this crap.
18702 	 * OTOH, if what follows is pretty random, then I'm in better shape.
18703 	 */
18704 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
18705 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
18706 
18707 	/*
18708 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
18709 	 * as a good template.
18710 	 */
18711 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
18712 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
18713 
18714 	/*
18715 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
18716 	 */
18717 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
18718 
18719 	/*
18720 	 * See 4010593 if this section becomes a problem again,
18721 	 * but the local ethernet address is useful here.
18722 	 */
18723 	(void) localetheraddr(NULL,
18724 	    (struct ether_addr *)&tcp_iss_cookie.ether);
18725 
18726 	/*
18727 	 * Hash 'em all together.  The MD5Final is called per-connection.
18728 	 */
18729 	mutex_enter(&tcps->tcps_iss_key_lock);
18730 	MD5Init(&tcps->tcps_iss_key);
18731 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
18732 	    sizeof (tcp_iss_cookie));
18733 	mutex_exit(&tcps->tcps_iss_key_lock);
18734 }
18735 
18736 /*
18737  * Set the RFC 1948 pass phrase
18738  */
18739 /* ARGSUSED */
18740 static int
18741 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
18742     cred_t *cr)
18743 {
18744 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18745 
18746 	/*
18747 	 * Basically, value contains a new pass phrase.  Pass it along!
18748 	 */
18749 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
18750 	return (0);
18751 }
18752 
18753 /* ARGSUSED */
18754 static int
18755 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
18756 {
18757 	bzero(buf, sizeof (tcp_sack_info_t));
18758 	return (0);
18759 }
18760 
18761 /*
18762  * Called by IP when IP is loaded into the kernel
18763  */
18764 void
18765 tcp_ddi_g_init(void)
18766 {
18767 	tcp_timercache = kmem_cache_create("tcp_timercache",
18768 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
18769 	    NULL, NULL, NULL, NULL, NULL, 0);
18770 
18771 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
18772 	    sizeof (tcp_sack_info_t), 0,
18773 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
18774 
18775 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
18776 
18777 	/* Initialize the random number generator */
18778 	tcp_random_init();
18779 
18780 	/* A single callback independently of how many netstacks we have */
18781 	ip_squeue_init(tcp_squeue_add);
18782 
18783 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
18784 
18785 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
18786 
18787 	/*
18788 	 * We want to be informed each time a stack is created or
18789 	 * destroyed in the kernel, so we can maintain the
18790 	 * set of tcp_stack_t's.
18791 	 */
18792 	netstack_register(NS_TCP, tcp_stack_init, NULL, tcp_stack_fini);
18793 }
18794 
18795 
18796 #define	INET_NAME	"ip"
18797 
18798 /*
18799  * Initialize the TCP stack instance.
18800  */
18801 static void *
18802 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
18803 {
18804 	tcp_stack_t	*tcps;
18805 	tcpparam_t	*pa;
18806 	int		i;
18807 	int		error = 0;
18808 	major_t		major;
18809 
18810 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
18811 	tcps->tcps_netstack = ns;
18812 
18813 	/* Initialize locks */
18814 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
18815 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
18816 
18817 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
18818 	tcps->tcps_g_epriv_ports[0] = 2049;
18819 	tcps->tcps_g_epriv_ports[1] = 4045;
18820 	tcps->tcps_min_anonpriv_port = 512;
18821 
18822 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
18823 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
18824 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
18825 	    TCP_ACCEPTOR_FANOUT_SIZE, KM_SLEEP);
18826 
18827 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18828 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
18829 		    MUTEX_DEFAULT, NULL);
18830 	}
18831 
18832 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18833 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
18834 		    MUTEX_DEFAULT, NULL);
18835 	}
18836 
18837 	/* TCP's IPsec code calls the packet dropper. */
18838 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
18839 
18840 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
18841 	tcps->tcps_params = pa;
18842 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18843 
18844 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
18845 	    A_CNT(lcl_tcp_param_arr), tcps);
18846 
18847 	/*
18848 	 * Note: To really walk the device tree you need the devinfo
18849 	 * pointer to your device which is only available after probe/attach.
18850 	 * The following is safe only because it uses ddi_root_node()
18851 	 */
18852 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
18853 	    tcp_opt_obj.odb_opt_arr_cnt);
18854 
18855 	/*
18856 	 * Initialize RFC 1948 secret values.  This will probably be reset once
18857 	 * by the boot scripts.
18858 	 *
18859 	 * Use NULL name, as the name is caught by the new lockstats.
18860 	 *
18861 	 * Initialize with some random, non-guessable string, like the global
18862 	 * T_INFO_ACK.
18863 	 */
18864 
18865 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
18866 	    sizeof (tcp_g_t_info_ack), tcps);
18867 
18868 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
18869 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
18870 
18871 	major = mod_name_to_major(INET_NAME);
18872 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
18873 	ASSERT(error == 0);
18874 	tcps->tcps_ixa_cleanup_mp = allocb_wait(0, BPRI_MED, STR_NOSIG, NULL);
18875 	ASSERT(tcps->tcps_ixa_cleanup_mp != NULL);
18876 	cv_init(&tcps->tcps_ixa_cleanup_cv, NULL, CV_DEFAULT, NULL);
18877 	mutex_init(&tcps->tcps_ixa_cleanup_lock, NULL, MUTEX_DEFAULT, NULL);
18878 
18879 	mutex_init(&tcps->tcps_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
18880 	tcps->tcps_reclaim = B_FALSE;
18881 	tcps->tcps_reclaim_tid = 0;
18882 	tcps->tcps_reclaim_period = tcps->tcps_rexmit_interval_max * 3;
18883 
18884 	mutex_init(&tcps->tcps_listener_conf_lock, NULL, MUTEX_DEFAULT, NULL);
18885 	list_create(&tcps->tcps_listener_conf, sizeof (tcp_listener_t),
18886 	    offsetof(tcp_listener_t, tl_link));
18887 
18888 	return (tcps);
18889 }
18890 
18891 /*
18892  * Called when the IP module is about to be unloaded.
18893  */
18894 void
18895 tcp_ddi_g_destroy(void)
18896 {
18897 	tcp_g_kstat_fini(tcp_g_kstat);
18898 	tcp_g_kstat = NULL;
18899 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
18900 
18901 	mutex_destroy(&tcp_random_lock);
18902 
18903 	kmem_cache_destroy(tcp_timercache);
18904 	kmem_cache_destroy(tcp_sack_info_cache);
18905 
18906 	netstack_unregister(NS_TCP);
18907 }
18908 
18909 /*
18910  * Free the TCP stack instance.
18911  */
18912 static void
18913 tcp_stack_fini(netstackid_t stackid, void *arg)
18914 {
18915 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
18916 	int i;
18917 
18918 	freeb(tcps->tcps_ixa_cleanup_mp);
18919 	tcps->tcps_ixa_cleanup_mp = NULL;
18920 	cv_destroy(&tcps->tcps_ixa_cleanup_cv);
18921 	mutex_destroy(&tcps->tcps_ixa_cleanup_lock);
18922 
18923 	if (tcps->tcps_reclaim_tid != 0)
18924 		(void) untimeout(tcps->tcps_reclaim_tid);
18925 	mutex_destroy(&tcps->tcps_reclaim_lock);
18926 
18927 	tcp_listener_conf_cleanup(tcps);
18928 
18929 	nd_free(&tcps->tcps_g_nd);
18930 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18931 	tcps->tcps_params = NULL;
18932 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
18933 	tcps->tcps_wroff_xtra_param = NULL;
18934 
18935 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18936 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
18937 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
18938 	}
18939 
18940 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18941 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
18942 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
18943 	}
18944 
18945 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
18946 	tcps->tcps_bind_fanout = NULL;
18947 
18948 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) *
18949 	    TCP_ACCEPTOR_FANOUT_SIZE);
18950 	tcps->tcps_acceptor_fanout = NULL;
18951 
18952 	mutex_destroy(&tcps->tcps_iss_key_lock);
18953 	mutex_destroy(&tcps->tcps_epriv_port_lock);
18954 
18955 	ip_drop_unregister(&tcps->tcps_dropper);
18956 
18957 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
18958 	tcps->tcps_kstat = NULL;
18959 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
18960 
18961 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
18962 	tcps->tcps_mibkp = NULL;
18963 
18964 	ldi_ident_release(tcps->tcps_ldi_ident);
18965 	kmem_free(tcps, sizeof (*tcps));
18966 }
18967 
18968 /*
18969  * Generate ISS, taking into account NDD changes may happen halfway through.
18970  * (If the iss is not zero, set it.)
18971  */
18972 
18973 static void
18974 tcp_iss_init(tcp_t *tcp)
18975 {
18976 	MD5_CTX context;
18977 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
18978 	uint32_t answer[4];
18979 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18980 	conn_t		*connp = tcp->tcp_connp;
18981 
18982 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
18983 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
18984 	switch (tcps->tcps_strong_iss) {
18985 	case 2:
18986 		mutex_enter(&tcps->tcps_iss_key_lock);
18987 		context = tcps->tcps_iss_key;
18988 		mutex_exit(&tcps->tcps_iss_key_lock);
18989 		arg.ports = connp->conn_ports;
18990 		arg.src = connp->conn_laddr_v6;
18991 		arg.dst = connp->conn_faddr_v6;
18992 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
18993 		MD5Final((uchar_t *)answer, &context);
18994 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
18995 		/*
18996 		 * Now that we've hashed into a unique per-connection sequence
18997 		 * space, add a random increment per strong_iss == 1.  So I
18998 		 * guess we'll have to...
18999 		 */
19000 		/* FALLTHRU */
19001 	case 1:
19002 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
19003 		break;
19004 	default:
19005 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19006 		break;
19007 	}
19008 	tcp->tcp_valid_bits = TCP_ISS_VALID;
19009 	tcp->tcp_fss = tcp->tcp_iss - 1;
19010 	tcp->tcp_suna = tcp->tcp_iss;
19011 	tcp->tcp_snxt = tcp->tcp_iss + 1;
19012 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
19013 	tcp->tcp_csuna = tcp->tcp_snxt;
19014 }
19015 
19016 /*
19017  * Exported routine for extracting active tcp connection status.
19018  *
19019  * This is used by the Solaris Cluster Networking software to
19020  * gather a list of connections that need to be forwarded to
19021  * specific nodes in the cluster when configuration changes occur.
19022  *
19023  * The callback is invoked for each tcp_t structure from all netstacks,
19024  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
19025  * from the netstack with the specified stack_id. Returning
19026  * non-zero from the callback routine terminates the search.
19027  */
19028 int
19029 cl_tcp_walk_list(netstackid_t stack_id,
19030     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
19031 {
19032 	netstack_handle_t nh;
19033 	netstack_t *ns;
19034 	int ret = 0;
19035 
19036 	if (stack_id >= 0) {
19037 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
19038 			return (EINVAL);
19039 
19040 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19041 		    ns->netstack_tcp);
19042 		netstack_rele(ns);
19043 		return (ret);
19044 	}
19045 
19046 	netstack_next_init(&nh);
19047 	while ((ns = netstack_next(&nh)) != NULL) {
19048 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
19049 		    ns->netstack_tcp);
19050 		netstack_rele(ns);
19051 	}
19052 	netstack_next_fini(&nh);
19053 	return (ret);
19054 }
19055 
19056 static int
19057 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
19058     tcp_stack_t *tcps)
19059 {
19060 	tcp_t *tcp;
19061 	cl_tcp_info_t	cl_tcpi;
19062 	connf_t	*connfp;
19063 	conn_t	*connp;
19064 	int	i;
19065 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19066 
19067 	ASSERT(callback != NULL);
19068 
19069 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
19070 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
19071 		connp = NULL;
19072 
19073 		while ((connp =
19074 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
19075 
19076 			tcp = connp->conn_tcp;
19077 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
19078 			cl_tcpi.cl_tcpi_ipversion = connp->conn_ipversion;
19079 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
19080 			cl_tcpi.cl_tcpi_lport = connp->conn_lport;
19081 			cl_tcpi.cl_tcpi_fport = connp->conn_fport;
19082 			cl_tcpi.cl_tcpi_laddr_v6 = connp->conn_laddr_v6;
19083 			cl_tcpi.cl_tcpi_faddr_v6 = connp->conn_faddr_v6;
19084 
19085 			/*
19086 			 * If the callback returns non-zero
19087 			 * we terminate the traversal.
19088 			 */
19089 			if ((*callback)(&cl_tcpi, arg) != 0) {
19090 				CONN_DEC_REF(tcp->tcp_connp);
19091 				return (1);
19092 			}
19093 		}
19094 	}
19095 
19096 	return (0);
19097 }
19098 
19099 /*
19100  * Macros used for accessing the different types of sockaddr
19101  * structures inside a tcp_ioc_abort_conn_t.
19102  */
19103 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
19104 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
19105 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
19106 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
19107 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
19108 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
19109 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
19110 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
19111 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
19112 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
19113 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
19114 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
19115 
19116 /*
19117  * Return the correct error code to mimic the behavior
19118  * of a connection reset.
19119  */
19120 #define	TCP_AC_GET_ERRCODE(state, err) {	\
19121 		switch ((state)) {		\
19122 		case TCPS_SYN_SENT:		\
19123 		case TCPS_SYN_RCVD:		\
19124 			(err) = ECONNREFUSED;	\
19125 			break;			\
19126 		case TCPS_ESTABLISHED:		\
19127 		case TCPS_FIN_WAIT_1:		\
19128 		case TCPS_FIN_WAIT_2:		\
19129 		case TCPS_CLOSE_WAIT:		\
19130 			(err) = ECONNRESET;	\
19131 			break;			\
19132 		case TCPS_CLOSING:		\
19133 		case TCPS_LAST_ACK:		\
19134 		case TCPS_TIME_WAIT:		\
19135 			(err) = 0;		\
19136 			break;			\
19137 		default:			\
19138 			(err) = ENXIO;		\
19139 		}				\
19140 	}
19141 
19142 /*
19143  * Check if a tcp structure matches the info in acp.
19144  */
19145 #define	TCP_AC_ADDR_MATCH(acp, connp, tcp)			\
19146 	(((acp)->ac_local.ss_family == AF_INET) ?		\
19147 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
19148 	TCP_AC_V4LOCAL((acp)) == (connp)->conn_laddr_v4) &&	\
19149 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
19150 	TCP_AC_V4REMOTE((acp)) == (connp)->conn_faddr_v4) &&	\
19151 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
19152 	TCP_AC_V4LPORT((acp)) == (connp)->conn_lport) &&	\
19153 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
19154 	TCP_AC_V4RPORT((acp)) == (connp)->conn_fport) &&	\
19155 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19156 	(acp)->ac_end >= (tcp)->tcp_state) :			\
19157 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
19158 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
19159 	&(connp)->conn_laddr_v6)) &&				\
19160 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
19161 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
19162 	&(connp)->conn_faddr_v6)) &&				\
19163 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
19164 	TCP_AC_V6LPORT((acp)) == (connp)->conn_lport) &&	\
19165 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
19166 	TCP_AC_V6RPORT((acp)) == (connp)->conn_fport) &&	\
19167 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19168 	(acp)->ac_end >= (tcp)->tcp_state))
19169 
19170 #define	TCP_AC_MATCH(acp, connp, tcp)				\
19171 	(((acp)->ac_zoneid == ALL_ZONES ||			\
19172 	(acp)->ac_zoneid == (connp)->conn_zoneid) ?		\
19173 	TCP_AC_ADDR_MATCH(acp, connp, tcp) : 0)
19174 
19175 /*
19176  * Build a message containing a tcp_ioc_abort_conn_t structure
19177  * which is filled in with information from acp and tp.
19178  */
19179 static mblk_t *
19180 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
19181 {
19182 	mblk_t *mp;
19183 	tcp_ioc_abort_conn_t *tacp;
19184 
19185 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
19186 	if (mp == NULL)
19187 		return (NULL);
19188 
19189 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
19190 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
19191 	    sizeof (uint32_t));
19192 
19193 	tacp->ac_start = acp->ac_start;
19194 	tacp->ac_end = acp->ac_end;
19195 	tacp->ac_zoneid = acp->ac_zoneid;
19196 
19197 	if (acp->ac_local.ss_family == AF_INET) {
19198 		tacp->ac_local.ss_family = AF_INET;
19199 		tacp->ac_remote.ss_family = AF_INET;
19200 		TCP_AC_V4LOCAL(tacp) = tp->tcp_connp->conn_laddr_v4;
19201 		TCP_AC_V4REMOTE(tacp) = tp->tcp_connp->conn_faddr_v4;
19202 		TCP_AC_V4LPORT(tacp) = tp->tcp_connp->conn_lport;
19203 		TCP_AC_V4RPORT(tacp) = tp->tcp_connp->conn_fport;
19204 	} else {
19205 		tacp->ac_local.ss_family = AF_INET6;
19206 		tacp->ac_remote.ss_family = AF_INET6;
19207 		TCP_AC_V6LOCAL(tacp) = tp->tcp_connp->conn_laddr_v6;
19208 		TCP_AC_V6REMOTE(tacp) = tp->tcp_connp->conn_faddr_v6;
19209 		TCP_AC_V6LPORT(tacp) = tp->tcp_connp->conn_lport;
19210 		TCP_AC_V6RPORT(tacp) = tp->tcp_connp->conn_fport;
19211 	}
19212 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
19213 	return (mp);
19214 }
19215 
19216 /*
19217  * Print a tcp_ioc_abort_conn_t structure.
19218  */
19219 static void
19220 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
19221 {
19222 	char lbuf[128];
19223 	char rbuf[128];
19224 	sa_family_t af;
19225 	in_port_t lport, rport;
19226 	ushort_t logflags;
19227 
19228 	af = acp->ac_local.ss_family;
19229 
19230 	if (af == AF_INET) {
19231 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
19232 		    lbuf, 128);
19233 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
19234 		    rbuf, 128);
19235 		lport = ntohs(TCP_AC_V4LPORT(acp));
19236 		rport = ntohs(TCP_AC_V4RPORT(acp));
19237 	} else {
19238 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
19239 		    lbuf, 128);
19240 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
19241 		    rbuf, 128);
19242 		lport = ntohs(TCP_AC_V6LPORT(acp));
19243 		rport = ntohs(TCP_AC_V6RPORT(acp));
19244 	}
19245 
19246 	logflags = SL_TRACE | SL_NOTE;
19247 	/*
19248 	 * Don't print this message to the console if the operation was done
19249 	 * to a non-global zone.
19250 	 */
19251 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19252 		logflags |= SL_CONSOLE;
19253 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
19254 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
19255 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
19256 	    acp->ac_start, acp->ac_end);
19257 }
19258 
19259 /*
19260  * Called using SQ_FILL when a message built using
19261  * tcp_ioctl_abort_build_msg is put into a queue.
19262  * Note that when we get here there is no wildcard in acp any more.
19263  */
19264 /* ARGSUSED2 */
19265 static void
19266 tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
19267     ip_recv_attr_t *dummy)
19268 {
19269 	conn_t			*connp = (conn_t *)arg;
19270 	tcp_t			*tcp = connp->conn_tcp;
19271 	tcp_ioc_abort_conn_t	*acp;
19272 
19273 	/*
19274 	 * Don't accept any input on a closed tcp as this TCP logically does
19275 	 * not exist on the system. Don't proceed further with this TCP.
19276 	 * For eg. this packet could trigger another close of this tcp
19277 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
19278 	 * tcp_clean_death / tcp_closei_local must be called at most once
19279 	 * on a TCP.
19280 	 */
19281 	if (tcp->tcp_state == TCPS_CLOSED ||
19282 	    tcp->tcp_state == TCPS_BOUND) {
19283 		freemsg(mp);
19284 		return;
19285 	}
19286 
19287 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
19288 	if (tcp->tcp_state <= acp->ac_end) {
19289 		/*
19290 		 * If we get here, we are already on the correct
19291 		 * squeue. This ioctl follows the following path
19292 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
19293 		 * ->tcp_ioctl_abort->squeue_enter (if on a
19294 		 * different squeue)
19295 		 */
19296 		int errcode;
19297 
19298 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
19299 		(void) tcp_clean_death(tcp, errcode, 26);
19300 	}
19301 	freemsg(mp);
19302 }
19303 
19304 /*
19305  * Abort all matching connections on a hash chain.
19306  */
19307 static int
19308 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
19309     boolean_t exact, tcp_stack_t *tcps)
19310 {
19311 	int nmatch, err = 0;
19312 	tcp_t *tcp;
19313 	MBLKP mp, last, listhead = NULL;
19314 	conn_t	*tconnp;
19315 	connf_t	*connfp;
19316 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19317 
19318 	connfp = &ipst->ips_ipcl_conn_fanout[index];
19319 
19320 startover:
19321 	nmatch = 0;
19322 
19323 	mutex_enter(&connfp->connf_lock);
19324 	for (tconnp = connfp->connf_head; tconnp != NULL;
19325 	    tconnp = tconnp->conn_next) {
19326 		tcp = tconnp->conn_tcp;
19327 		/*
19328 		 * We are missing a check on sin6_scope_id for linklocals here,
19329 		 * but current usage is just for aborting based on zoneid
19330 		 * for shared-IP zones.
19331 		 */
19332 		if (TCP_AC_MATCH(acp, tconnp, tcp)) {
19333 			CONN_INC_REF(tconnp);
19334 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
19335 			if (mp == NULL) {
19336 				err = ENOMEM;
19337 				CONN_DEC_REF(tconnp);
19338 				break;
19339 			}
19340 			mp->b_prev = (mblk_t *)tcp;
19341 
19342 			if (listhead == NULL) {
19343 				listhead = mp;
19344 				last = mp;
19345 			} else {
19346 				last->b_next = mp;
19347 				last = mp;
19348 			}
19349 			nmatch++;
19350 			if (exact)
19351 				break;
19352 		}
19353 
19354 		/* Avoid holding lock for too long. */
19355 		if (nmatch >= 500)
19356 			break;
19357 	}
19358 	mutex_exit(&connfp->connf_lock);
19359 
19360 	/* Pass mp into the correct tcp */
19361 	while ((mp = listhead) != NULL) {
19362 		listhead = listhead->b_next;
19363 		tcp = (tcp_t *)mp->b_prev;
19364 		mp->b_next = mp->b_prev = NULL;
19365 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp,
19366 		    tcp_ioctl_abort_handler, tcp->tcp_connp, NULL,
19367 		    SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
19368 	}
19369 
19370 	*count += nmatch;
19371 	if (nmatch >= 500 && err == 0)
19372 		goto startover;
19373 	return (err);
19374 }
19375 
19376 /*
19377  * Abort all connections that matches the attributes specified in acp.
19378  */
19379 static int
19380 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
19381 {
19382 	sa_family_t af;
19383 	uint32_t  ports;
19384 	uint16_t *pports;
19385 	int err = 0, count = 0;
19386 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
19387 	int index = -1;
19388 	ushort_t logflags;
19389 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19390 
19391 	af = acp->ac_local.ss_family;
19392 
19393 	if (af == AF_INET) {
19394 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
19395 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
19396 			pports = (uint16_t *)&ports;
19397 			pports[1] = TCP_AC_V4LPORT(acp);
19398 			pports[0] = TCP_AC_V4RPORT(acp);
19399 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
19400 		}
19401 	} else {
19402 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
19403 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
19404 			pports = (uint16_t *)&ports;
19405 			pports[1] = TCP_AC_V6LPORT(acp);
19406 			pports[0] = TCP_AC_V6RPORT(acp);
19407 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
19408 		}
19409 	}
19410 
19411 	/*
19412 	 * For cases where remote addr, local port, and remote port are non-
19413 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
19414 	 */
19415 	if (index != -1) {
19416 		err = tcp_ioctl_abort_bucket(acp, index,
19417 		    &count, exact, tcps);
19418 	} else {
19419 		/*
19420 		 * loop through all entries for wildcard case
19421 		 */
19422 		for (index = 0;
19423 		    index < ipst->ips_ipcl_conn_fanout_size;
19424 		    index++) {
19425 			err = tcp_ioctl_abort_bucket(acp, index,
19426 			    &count, exact, tcps);
19427 			if (err != 0)
19428 				break;
19429 		}
19430 	}
19431 
19432 	logflags = SL_TRACE | SL_NOTE;
19433 	/*
19434 	 * Don't print this message to the console if the operation was done
19435 	 * to a non-global zone.
19436 	 */
19437 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19438 		logflags |= SL_CONSOLE;
19439 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
19440 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
19441 	if (err == 0 && count == 0)
19442 		err = ENOENT;
19443 	return (err);
19444 }
19445 
19446 /*
19447  * Process the TCP_IOC_ABORT_CONN ioctl request.
19448  */
19449 static void
19450 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
19451 {
19452 	int	err;
19453 	IOCP    iocp;
19454 	MBLKP   mp1;
19455 	sa_family_t laf, raf;
19456 	tcp_ioc_abort_conn_t *acp;
19457 	zone_t		*zptr;
19458 	conn_t		*connp = Q_TO_CONN(q);
19459 	zoneid_t	zoneid = connp->conn_zoneid;
19460 	tcp_t		*tcp = connp->conn_tcp;
19461 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19462 
19463 	iocp = (IOCP)mp->b_rptr;
19464 
19465 	if ((mp1 = mp->b_cont) == NULL ||
19466 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
19467 		err = EINVAL;
19468 		goto out;
19469 	}
19470 
19471 	/* check permissions */
19472 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19473 		err = EPERM;
19474 		goto out;
19475 	}
19476 
19477 	if (mp1->b_cont != NULL) {
19478 		freemsg(mp1->b_cont);
19479 		mp1->b_cont = NULL;
19480 	}
19481 
19482 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
19483 	laf = acp->ac_local.ss_family;
19484 	raf = acp->ac_remote.ss_family;
19485 
19486 	/* check that a zone with the supplied zoneid exists */
19487 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
19488 		zptr = zone_find_by_id(zoneid);
19489 		if (zptr != NULL) {
19490 			zone_rele(zptr);
19491 		} else {
19492 			err = EINVAL;
19493 			goto out;
19494 		}
19495 	}
19496 
19497 	/*
19498 	 * For exclusive stacks we set the zoneid to zero
19499 	 * to make TCP operate as if in the global zone.
19500 	 */
19501 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
19502 		acp->ac_zoneid = GLOBAL_ZONEID;
19503 
19504 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
19505 	    acp->ac_start > acp->ac_end || laf != raf ||
19506 	    (laf != AF_INET && laf != AF_INET6)) {
19507 		err = EINVAL;
19508 		goto out;
19509 	}
19510 
19511 	tcp_ioctl_abort_dump(acp);
19512 	err = tcp_ioctl_abort(acp, tcps);
19513 
19514 out:
19515 	if (mp1 != NULL) {
19516 		freemsg(mp1);
19517 		mp->b_cont = NULL;
19518 	}
19519 
19520 	if (err != 0)
19521 		miocnak(q, mp, 0, err);
19522 	else
19523 		miocack(q, mp, 0, 0);
19524 }
19525 
19526 /*
19527  * tcp_time_wait_processing() handles processing of incoming packets when
19528  * the tcp is in the TIME_WAIT state.
19529  * A TIME_WAIT tcp that has an associated open TCP stream is never put
19530  * on the time wait list.
19531  */
19532 void
19533 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
19534     uint32_t seg_ack, int seg_len, tcpha_t *tcpha, ip_recv_attr_t *ira)
19535 {
19536 	int32_t		bytes_acked;
19537 	int32_t		gap;
19538 	int32_t		rgap;
19539 	tcp_opt_t	tcpopt;
19540 	uint_t		flags;
19541 	uint32_t	new_swnd = 0;
19542 	conn_t		*nconnp;
19543 	conn_t		*connp = tcp->tcp_connp;
19544 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19545 
19546 	BUMP_LOCAL(tcp->tcp_ibsegs);
19547 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
19548 
19549 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
19550 	new_swnd = ntohs(tcpha->tha_win) <<
19551 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
19552 	if (tcp->tcp_snd_ts_ok) {
19553 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
19554 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19555 			    tcp->tcp_rnxt, TH_ACK);
19556 			goto done;
19557 		}
19558 	}
19559 	gap = seg_seq - tcp->tcp_rnxt;
19560 	rgap = tcp->tcp_rwnd - (gap + seg_len);
19561 	if (gap < 0) {
19562 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
19563 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
19564 		    (seg_len > -gap ? -gap : seg_len));
19565 		seg_len += gap;
19566 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
19567 			if (flags & TH_RST) {
19568 				goto done;
19569 			}
19570 			if ((flags & TH_FIN) && seg_len == -1) {
19571 				/*
19572 				 * When TCP receives a duplicate FIN in
19573 				 * TIME_WAIT state, restart the 2 MSL timer.
19574 				 * See page 73 in RFC 793. Make sure this TCP
19575 				 * is already on the TIME_WAIT list. If not,
19576 				 * just restart the timer.
19577 				 */
19578 				if (TCP_IS_DETACHED(tcp)) {
19579 					if (tcp_time_wait_remove(tcp, NULL) ==
19580 					    B_TRUE) {
19581 						tcp_time_wait_append(tcp);
19582 						TCP_DBGSTAT(tcps,
19583 						    tcp_rput_time_wait);
19584 					}
19585 				} else {
19586 					ASSERT(tcp != NULL);
19587 					TCP_TIMER_RESTART(tcp,
19588 					    tcps->tcps_time_wait_interval);
19589 				}
19590 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19591 				    tcp->tcp_rnxt, TH_ACK);
19592 				goto done;
19593 			}
19594 			flags |=  TH_ACK_NEEDED;
19595 			seg_len = 0;
19596 			goto process_ack;
19597 		}
19598 
19599 		/* Fix seg_seq, and chew the gap off the front. */
19600 		seg_seq = tcp->tcp_rnxt;
19601 	}
19602 
19603 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
19604 		/*
19605 		 * Make sure that when we accept the connection, pick
19606 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
19607 		 * old connection.
19608 		 *
19609 		 * The next ISS generated is equal to tcp_iss_incr_extra
19610 		 * + ISS_INCR/2 + other components depending on the
19611 		 * value of tcp_strong_iss.  We pre-calculate the new
19612 		 * ISS here and compare with tcp_snxt to determine if
19613 		 * we need to make adjustment to tcp_iss_incr_extra.
19614 		 *
19615 		 * The above calculation is ugly and is a
19616 		 * waste of CPU cycles...
19617 		 */
19618 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
19619 		int32_t adj;
19620 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19621 
19622 		switch (tcps->tcps_strong_iss) {
19623 		case 2: {
19624 			/* Add time and MD5 components. */
19625 			uint32_t answer[4];
19626 			struct {
19627 				uint32_t ports;
19628 				in6_addr_t src;
19629 				in6_addr_t dst;
19630 			} arg;
19631 			MD5_CTX context;
19632 
19633 			mutex_enter(&tcps->tcps_iss_key_lock);
19634 			context = tcps->tcps_iss_key;
19635 			mutex_exit(&tcps->tcps_iss_key_lock);
19636 			arg.ports = connp->conn_ports;
19637 			/* We use MAPPED addresses in tcp_iss_init */
19638 			arg.src = connp->conn_laddr_v6;
19639 			arg.dst = connp->conn_faddr_v6;
19640 			MD5Update(&context, (uchar_t *)&arg,
19641 			    sizeof (arg));
19642 			MD5Final((uchar_t *)answer, &context);
19643 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
19644 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
19645 			break;
19646 		}
19647 		case 1:
19648 			/* Add time component and min random (i.e. 1). */
19649 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
19650 			break;
19651 		default:
19652 			/* Add only time component. */
19653 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19654 			break;
19655 		}
19656 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
19657 			/*
19658 			 * New ISS not guaranteed to be ISS_INCR/2
19659 			 * ahead of the current tcp_snxt, so add the
19660 			 * difference to tcp_iss_incr_extra.
19661 			 */
19662 			tcps->tcps_iss_incr_extra += adj;
19663 		}
19664 		/*
19665 		 * If tcp_clean_death() can not perform the task now,
19666 		 * drop the SYN packet and let the other side re-xmit.
19667 		 * Otherwise pass the SYN packet back in, since the
19668 		 * old tcp state has been cleaned up or freed.
19669 		 */
19670 		if (tcp_clean_death(tcp, 0, 27) == -1)
19671 			goto done;
19672 		nconnp = ipcl_classify(mp, ira, ipst);
19673 		if (nconnp != NULL) {
19674 			TCP_STAT(tcps, tcp_time_wait_syn_success);
19675 			/* Drops ref on nconnp */
19676 			tcp_reinput(nconnp, mp, ira, ipst);
19677 			return;
19678 		}
19679 		goto done;
19680 	}
19681 
19682 	/*
19683 	 * rgap is the amount of stuff received out of window.  A negative
19684 	 * value is the amount out of window.
19685 	 */
19686 	if (rgap < 0) {
19687 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
19688 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
19689 		/* Fix seg_len and make sure there is something left. */
19690 		seg_len += rgap;
19691 		if (seg_len <= 0) {
19692 			if (flags & TH_RST) {
19693 				goto done;
19694 			}
19695 			flags |=  TH_ACK_NEEDED;
19696 			seg_len = 0;
19697 			goto process_ack;
19698 		}
19699 	}
19700 	/*
19701 	 * Check whether we can update tcp_ts_recent.  This test is
19702 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
19703 	 * Extensions for High Performance: An Update", Internet Draft.
19704 	 */
19705 	if (tcp->tcp_snd_ts_ok &&
19706 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
19707 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
19708 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
19709 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
19710 	}
19711 
19712 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
19713 		/* Always ack out of order packets */
19714 		flags |= TH_ACK_NEEDED;
19715 		seg_len = 0;
19716 	} else if (seg_len > 0) {
19717 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
19718 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
19719 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
19720 	}
19721 	if (flags & TH_RST) {
19722 		(void) tcp_clean_death(tcp, 0, 28);
19723 		goto done;
19724 	}
19725 	if (flags & TH_SYN) {
19726 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
19727 		    TH_RST|TH_ACK);
19728 		/*
19729 		 * Do not delete the TCP structure if it is in
19730 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
19731 		 */
19732 		goto done;
19733 	}
19734 process_ack:
19735 	if (flags & TH_ACK) {
19736 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
19737 		if (bytes_acked <= 0) {
19738 			if (bytes_acked == 0 && seg_len == 0 &&
19739 			    new_swnd == tcp->tcp_swnd)
19740 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
19741 		} else {
19742 			/* Acks something not sent */
19743 			flags |= TH_ACK_NEEDED;
19744 		}
19745 	}
19746 	if (flags & TH_ACK_NEEDED) {
19747 		/*
19748 		 * Time to send an ack for some reason.
19749 		 */
19750 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19751 		    tcp->tcp_rnxt, TH_ACK);
19752 	}
19753 done:
19754 	freemsg(mp);
19755 }
19756 
19757 /*
19758  * TCP Timers Implementation.
19759  */
19760 timeout_id_t
19761 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
19762 {
19763 	mblk_t *mp;
19764 	tcp_timer_t *tcpt;
19765 	tcp_t *tcp = connp->conn_tcp;
19766 
19767 	ASSERT(connp->conn_sqp != NULL);
19768 
19769 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
19770 
19771 	if (tcp->tcp_timercache == NULL) {
19772 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
19773 	} else {
19774 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
19775 		mp = tcp->tcp_timercache;
19776 		tcp->tcp_timercache = mp->b_next;
19777 		mp->b_next = NULL;
19778 		ASSERT(mp->b_wptr == NULL);
19779 	}
19780 
19781 	CONN_INC_REF(connp);
19782 	tcpt = (tcp_timer_t *)mp->b_rptr;
19783 	tcpt->connp = connp;
19784 	tcpt->tcpt_proc = f;
19785 	/*
19786 	 * TCP timers are normal timeouts. Plus, they do not require more than
19787 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
19788 	 * rounding up the expiration to the next resolution boundary, we can
19789 	 * batch timers in the callout subsystem to make TCP timers more
19790 	 * efficient. The roundup also protects short timers from expiring too
19791 	 * early before they have a chance to be cancelled.
19792 	 */
19793 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
19794 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
19795 
19796 	return ((timeout_id_t)mp);
19797 }
19798 
19799 static void
19800 tcp_timer_callback(void *arg)
19801 {
19802 	mblk_t *mp = (mblk_t *)arg;
19803 	tcp_timer_t *tcpt;
19804 	conn_t	*connp;
19805 
19806 	tcpt = (tcp_timer_t *)mp->b_rptr;
19807 	connp = tcpt->connp;
19808 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
19809 	    NULL, SQ_FILL, SQTAG_TCP_TIMER);
19810 }
19811 
19812 /* ARGSUSED */
19813 static void
19814 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
19815 {
19816 	tcp_timer_t *tcpt;
19817 	conn_t *connp = (conn_t *)arg;
19818 	tcp_t *tcp = connp->conn_tcp;
19819 
19820 	tcpt = (tcp_timer_t *)mp->b_rptr;
19821 	ASSERT(connp == tcpt->connp);
19822 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
19823 
19824 	/*
19825 	 * If the TCP has reached the closed state, don't proceed any
19826 	 * further. This TCP logically does not exist on the system.
19827 	 * tcpt_proc could for example access queues, that have already
19828 	 * been qprocoff'ed off.
19829 	 */
19830 	if (tcp->tcp_state != TCPS_CLOSED) {
19831 		(*tcpt->tcpt_proc)(connp);
19832 	} else {
19833 		tcp->tcp_timer_tid = 0;
19834 	}
19835 	tcp_timer_free(connp->conn_tcp, mp);
19836 }
19837 
19838 /*
19839  * There is potential race with untimeout and the handler firing at the same
19840  * time. The mblock may be freed by the handler while we are trying to use
19841  * it. But since both should execute on the same squeue, this race should not
19842  * occur.
19843  */
19844 clock_t
19845 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
19846 {
19847 	mblk_t	*mp = (mblk_t *)id;
19848 	tcp_timer_t *tcpt;
19849 	clock_t delta;
19850 
19851 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
19852 
19853 	if (mp == NULL)
19854 		return (-1);
19855 
19856 	tcpt = (tcp_timer_t *)mp->b_rptr;
19857 	ASSERT(tcpt->connp == connp);
19858 
19859 	delta = untimeout_default(tcpt->tcpt_tid, 0);
19860 
19861 	if (delta >= 0) {
19862 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
19863 		tcp_timer_free(connp->conn_tcp, mp);
19864 		CONN_DEC_REF(connp);
19865 	}
19866 
19867 	return (delta);
19868 }
19869 
19870 /*
19871  * Allocate space for the timer event. The allocation looks like mblk, but it is
19872  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
19873  *
19874  * Dealing with failures: If we can't allocate from the timer cache we try
19875  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
19876  * points to b_rptr.
19877  * If we can't allocate anything using allocb_tryhard(), we perform a last
19878  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
19879  * save the actual allocation size in b_datap.
19880  */
19881 mblk_t *
19882 tcp_timermp_alloc(int kmflags)
19883 {
19884 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
19885 	    kmflags & ~KM_PANIC);
19886 
19887 	if (mp != NULL) {
19888 		mp->b_next = mp->b_prev = NULL;
19889 		mp->b_rptr = (uchar_t *)(&mp[1]);
19890 		mp->b_wptr = NULL;
19891 		mp->b_datap = NULL;
19892 		mp->b_queue = NULL;
19893 		mp->b_cont = NULL;
19894 	} else if (kmflags & KM_PANIC) {
19895 		/*
19896 		 * Failed to allocate memory for the timer. Try allocating from
19897 		 * dblock caches.
19898 		 */
19899 		/* ipclassifier calls this from a constructor - hence no tcps */
19900 		TCP_G_STAT(tcp_timermp_allocfail);
19901 		mp = allocb_tryhard(sizeof (tcp_timer_t));
19902 		if (mp == NULL) {
19903 			size_t size = 0;
19904 			/*
19905 			 * Memory is really low. Try tryhard allocation.
19906 			 *
19907 			 * ipclassifier calls this from a constructor -
19908 			 * hence no tcps
19909 			 */
19910 			TCP_G_STAT(tcp_timermp_allocdblfail);
19911 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
19912 			    sizeof (tcp_timer_t), &size, kmflags);
19913 			mp->b_rptr = (uchar_t *)(&mp[1]);
19914 			mp->b_next = mp->b_prev = NULL;
19915 			mp->b_wptr = (uchar_t *)-1;
19916 			mp->b_datap = (dblk_t *)size;
19917 			mp->b_queue = NULL;
19918 			mp->b_cont = NULL;
19919 		}
19920 		ASSERT(mp->b_wptr != NULL);
19921 	}
19922 	/* ipclassifier calls this from a constructor - hence no tcps */
19923 	TCP_G_DBGSTAT(tcp_timermp_alloced);
19924 
19925 	return (mp);
19926 }
19927 
19928 /*
19929  * Free per-tcp timer cache.
19930  * It can only contain entries from tcp_timercache.
19931  */
19932 void
19933 tcp_timermp_free(tcp_t *tcp)
19934 {
19935 	mblk_t *mp;
19936 
19937 	while ((mp = tcp->tcp_timercache) != NULL) {
19938 		ASSERT(mp->b_wptr == NULL);
19939 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
19940 		kmem_cache_free(tcp_timercache, mp);
19941 	}
19942 }
19943 
19944 /*
19945  * Free timer event. Put it on the per-tcp timer cache if there is not too many
19946  * events there already (currently at most two events are cached).
19947  * If the event is not allocated from the timer cache, free it right away.
19948  */
19949 static void
19950 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
19951 {
19952 	mblk_t *mp1 = tcp->tcp_timercache;
19953 
19954 	if (mp->b_wptr != NULL) {
19955 		/*
19956 		 * This allocation is not from a timer cache, free it right
19957 		 * away.
19958 		 */
19959 		if (mp->b_wptr != (uchar_t *)-1)
19960 			freeb(mp);
19961 		else
19962 			kmem_free(mp, (size_t)mp->b_datap);
19963 	} else if (mp1 == NULL || mp1->b_next == NULL) {
19964 		/* Cache this timer block for future allocations */
19965 		mp->b_rptr = (uchar_t *)(&mp[1]);
19966 		mp->b_next = mp1;
19967 		tcp->tcp_timercache = mp;
19968 	} else {
19969 		kmem_cache_free(tcp_timercache, mp);
19970 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
19971 	}
19972 }
19973 
19974 /*
19975  * End of TCP Timers implementation.
19976  */
19977 
19978 /*
19979  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
19980  * on the specified backing STREAMS q. Note, the caller may make the
19981  * decision to call based on the tcp_t.tcp_flow_stopped value which
19982  * when check outside the q's lock is only an advisory check ...
19983  */
19984 void
19985 tcp_setqfull(tcp_t *tcp)
19986 {
19987 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19988 	conn_t	*connp = tcp->tcp_connp;
19989 
19990 	if (tcp->tcp_closed)
19991 		return;
19992 
19993 	conn_setqfull(connp, &tcp->tcp_flow_stopped);
19994 	if (tcp->tcp_flow_stopped)
19995 		TCP_STAT(tcps, tcp_flwctl_on);
19996 }
19997 
19998 void
19999 tcp_clrqfull(tcp_t *tcp)
20000 {
20001 	conn_t  *connp = tcp->tcp_connp;
20002 
20003 	if (tcp->tcp_closed)
20004 		return;
20005 	conn_clrqfull(connp, &tcp->tcp_flow_stopped);
20006 }
20007 
20008 /*
20009  * kstats related to squeues i.e. not per IP instance
20010  */
20011 static void *
20012 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
20013 {
20014 	kstat_t *ksp;
20015 
20016 	tcp_g_stat_t template = {
20017 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
20018 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
20019 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
20020 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
20021 	};
20022 
20023 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
20024 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20025 	    KSTAT_FLAG_VIRTUAL);
20026 
20027 	if (ksp == NULL)
20028 		return (NULL);
20029 
20030 	bcopy(&template, tcp_g_statp, sizeof (template));
20031 	ksp->ks_data = (void *)tcp_g_statp;
20032 
20033 	kstat_install(ksp);
20034 	return (ksp);
20035 }
20036 
20037 static void
20038 tcp_g_kstat_fini(kstat_t *ksp)
20039 {
20040 	if (ksp != NULL) {
20041 		kstat_delete(ksp);
20042 	}
20043 }
20044 
20045 
20046 static void *
20047 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
20048 {
20049 	kstat_t *ksp;
20050 
20051 	tcp_stat_t template = {
20052 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
20053 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
20054 		{ "tcp_time_wait_syn_success",	KSTAT_DATA_UINT64 },
20055 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
20056 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
20057 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
20058 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
20059 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
20060 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
20061 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
20062 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
20063 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
20064 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
20065 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
20066 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
20067 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
20068 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
20069 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
20070 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
20071 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
20072 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
20073 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
20074 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
20075 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
20076 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
20077 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
20078 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
20079 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
20080 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
20081 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
20082 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
20083 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
20084 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
20085 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
20086 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
20087 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
20088 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
20089 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
20090 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
20091 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
20092 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
20093 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
20094 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
20095 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
20096 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
20097 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
20098 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
20099 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
20100 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
20101 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
20102 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
20103 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
20104 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
20105 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
20106 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
20107 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
20108 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
20109 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
20110 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
20111 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
20112 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
20113 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
20114 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
20115 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
20116 		{ "tcp_listen_cnt_drop",	KSTAT_DATA_UINT64 },
20117 		{ "tcp_listen_mem_drop",	KSTAT_DATA_UINT64 },
20118 		{ "tcp_zwin_ack_syn",		KSTAT_DATA_UINT64 },
20119 		{ "tcp_rst_unsent",		KSTAT_DATA_UINT64 }
20120 	};
20121 
20122 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
20123 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20124 	    KSTAT_FLAG_VIRTUAL, stackid);
20125 
20126 	if (ksp == NULL)
20127 		return (NULL);
20128 
20129 	bcopy(&template, tcps_statisticsp, sizeof (template));
20130 	ksp->ks_data = (void *)tcps_statisticsp;
20131 	ksp->ks_private = (void *)(uintptr_t)stackid;
20132 
20133 	kstat_install(ksp);
20134 	return (ksp);
20135 }
20136 
20137 static void
20138 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
20139 {
20140 	if (ksp != NULL) {
20141 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20142 		kstat_delete_netstack(ksp, stackid);
20143 	}
20144 }
20145 
20146 /*
20147  * TCP Kstats implementation
20148  */
20149 static void *
20150 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
20151 {
20152 	kstat_t	*ksp;
20153 
20154 	tcp_named_kstat_t template = {
20155 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
20156 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
20157 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
20158 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
20159 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
20160 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
20161 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
20162 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
20163 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
20164 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
20165 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
20166 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
20167 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
20168 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
20169 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
20170 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
20171 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
20172 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
20173 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
20174 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
20175 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
20176 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
20177 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
20178 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
20179 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
20180 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
20181 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
20182 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
20183 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
20184 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
20185 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
20186 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
20187 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
20188 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
20189 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
20190 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
20191 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
20192 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
20193 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
20194 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
20195 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
20196 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
20197 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
20198 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
20199 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
20200 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
20201 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
20202 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
20203 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
20204 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
20205 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
20206 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
20207 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
20208 	};
20209 
20210 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
20211 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
20212 
20213 	if (ksp == NULL)
20214 		return (NULL);
20215 
20216 	template.rtoAlgorithm.value.ui32 = 4;
20217 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
20218 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
20219 	template.maxConn.value.i32 = -1;
20220 
20221 	bcopy(&template, ksp->ks_data, sizeof (template));
20222 	ksp->ks_update = tcp_kstat_update;
20223 	ksp->ks_private = (void *)(uintptr_t)stackid;
20224 
20225 	kstat_install(ksp);
20226 	return (ksp);
20227 }
20228 
20229 static void
20230 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
20231 {
20232 	if (ksp != NULL) {
20233 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20234 		kstat_delete_netstack(ksp, stackid);
20235 	}
20236 }
20237 
20238 static int
20239 tcp_kstat_update(kstat_t *kp, int rw)
20240 {
20241 	tcp_named_kstat_t *tcpkp;
20242 	tcp_t		*tcp;
20243 	connf_t		*connfp;
20244 	conn_t		*connp;
20245 	int 		i;
20246 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
20247 	netstack_t	*ns;
20248 	tcp_stack_t	*tcps;
20249 	ip_stack_t	*ipst;
20250 
20251 	if ((kp == NULL) || (kp->ks_data == NULL))
20252 		return (EIO);
20253 
20254 	if (rw == KSTAT_WRITE)
20255 		return (EACCES);
20256 
20257 	ns = netstack_find_by_stackid(stackid);
20258 	if (ns == NULL)
20259 		return (-1);
20260 	tcps = ns->netstack_tcp;
20261 	if (tcps == NULL) {
20262 		netstack_rele(ns);
20263 		return (-1);
20264 	}
20265 
20266 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
20267 
20268 	tcpkp->currEstab.value.ui32 = 0;
20269 
20270 	ipst = ns->netstack_ip;
20271 
20272 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
20273 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
20274 		connp = NULL;
20275 		while ((connp =
20276 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
20277 			tcp = connp->conn_tcp;
20278 			switch (tcp_snmp_state(tcp)) {
20279 			case MIB2_TCP_established:
20280 			case MIB2_TCP_closeWait:
20281 				tcpkp->currEstab.value.ui32++;
20282 				break;
20283 			}
20284 		}
20285 	}
20286 
20287 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
20288 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
20289 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
20290 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
20291 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
20292 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
20293 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
20294 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
20295 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
20296 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
20297 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
20298 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
20299 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
20300 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
20301 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
20302 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
20303 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
20304 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
20305 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
20306 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
20307 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
20308 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
20309 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
20310 	tcpkp->inDataInorderSegs.value.ui32 =
20311 	    tcps->tcps_mib.tcpInDataInorderSegs;
20312 	tcpkp->inDataInorderBytes.value.ui32 =
20313 	    tcps->tcps_mib.tcpInDataInorderBytes;
20314 	tcpkp->inDataUnorderSegs.value.ui32 =
20315 	    tcps->tcps_mib.tcpInDataUnorderSegs;
20316 	tcpkp->inDataUnorderBytes.value.ui32 =
20317 	    tcps->tcps_mib.tcpInDataUnorderBytes;
20318 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
20319 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
20320 	tcpkp->inDataPartDupSegs.value.ui32 =
20321 	    tcps->tcps_mib.tcpInDataPartDupSegs;
20322 	tcpkp->inDataPartDupBytes.value.ui32 =
20323 	    tcps->tcps_mib.tcpInDataPartDupBytes;
20324 	tcpkp->inDataPastWinSegs.value.ui32 =
20325 	    tcps->tcps_mib.tcpInDataPastWinSegs;
20326 	tcpkp->inDataPastWinBytes.value.ui32 =
20327 	    tcps->tcps_mib.tcpInDataPastWinBytes;
20328 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
20329 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
20330 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
20331 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
20332 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
20333 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
20334 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
20335 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
20336 	tcpkp->timKeepaliveProbe.value.ui32 =
20337 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
20338 	tcpkp->timKeepaliveDrop.value.ui32 =
20339 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
20340 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
20341 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
20342 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
20343 	tcpkp->outSackRetransSegs.value.ui32 =
20344 	    tcps->tcps_mib.tcpOutSackRetransSegs;
20345 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
20346 
20347 	netstack_rele(ns);
20348 	return (0);
20349 }
20350 
20351 static int
20352 tcp_squeue_switch(int val)
20353 {
20354 	int rval = SQ_FILL;
20355 
20356 	switch (val) {
20357 	case 1:
20358 		rval = SQ_NODRAIN;
20359 		break;
20360 	case 2:
20361 		rval = SQ_PROCESS;
20362 		break;
20363 	default:
20364 		break;
20365 	}
20366 	return (rval);
20367 }
20368 
20369 /*
20370  * This is called once for each squeue - globally for all stack
20371  * instances.
20372  */
20373 static void
20374 tcp_squeue_add(squeue_t *sqp)
20375 {
20376 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
20377 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
20378 
20379 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
20380 	tcp_time_wait->tcp_time_wait_tid =
20381 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
20382 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
20383 	    CALLOUT_FLAG_ROUNDUP);
20384 	if (tcp_free_list_max_cnt == 0) {
20385 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
20386 		    max_ncpus : boot_max_ncpus);
20387 
20388 		/*
20389 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
20390 		 */
20391 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
20392 		    (tcp_ncpus * sizeof (tcp_t) * 100);
20393 	}
20394 	tcp_time_wait->tcp_free_list_cnt = 0;
20395 }
20396 
20397 /*
20398  * On a labeled system we have some protocols above TCP, such as RPC, which
20399  * appear to assume that every mblk in a chain has a db_credp.
20400  */
20401 static void
20402 tcp_setcred_data(mblk_t *mp, ip_recv_attr_t *ira)
20403 {
20404 	ASSERT(is_system_labeled());
20405 	ASSERT(ira->ira_cred != NULL);
20406 
20407 	while (mp != NULL) {
20408 		mblk_setcred(mp, ira->ira_cred, NOPID);
20409 		mp = mp->b_cont;
20410 	}
20411 }
20412 
20413 static int
20414 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
20415     boolean_t bind_to_req_port_only, cred_t *cr)
20416 {
20417 	in_port_t	mlp_port;
20418 	mlp_type_t 	addrtype, mlptype;
20419 	boolean_t	user_specified;
20420 	in_port_t	allocated_port;
20421 	in_port_t	requested_port = *requested_port_ptr;
20422 	conn_t		*connp = tcp->tcp_connp;
20423 	zone_t		*zone;
20424 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20425 	in6_addr_t	v6addr = connp->conn_laddr_v6;
20426 
20427 	/*
20428 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
20429 	 */
20430 	ASSERT(cr != NULL);
20431 
20432 	/*
20433 	 * Get a valid port (within the anonymous range and should not
20434 	 * be a privileged one) to use if the user has not given a port.
20435 	 * If multiple threads are here, they may all start with
20436 	 * with the same initial port. But, it should be fine as long as
20437 	 * tcp_bindi will ensure that no two threads will be assigned
20438 	 * the same port.
20439 	 *
20440 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
20441 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
20442 	 * unless TCP_ANONPRIVBIND option is set.
20443 	 */
20444 	mlptype = mlptSingle;
20445 	mlp_port = requested_port;
20446 	if (requested_port == 0) {
20447 		requested_port = connp->conn_anon_priv_bind ?
20448 		    tcp_get_next_priv_port(tcp) :
20449 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
20450 		    tcp, B_TRUE);
20451 		if (requested_port == 0) {
20452 			return (-TNOADDR);
20453 		}
20454 		user_specified = B_FALSE;
20455 
20456 		/*
20457 		 * If the user went through one of the RPC interfaces to create
20458 		 * this socket and RPC is MLP in this zone, then give him an
20459 		 * anonymous MLP.
20460 		 */
20461 		if (connp->conn_anon_mlp && is_system_labeled()) {
20462 			zone = crgetzone(cr);
20463 			addrtype = tsol_mlp_addr_type(
20464 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20465 			    IPV6_VERSION, &v6addr,
20466 			    tcps->tcps_netstack->netstack_ip);
20467 			if (addrtype == mlptSingle) {
20468 				return (-TNOADDR);
20469 			}
20470 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20471 			    PMAPPORT, addrtype);
20472 			mlp_port = PMAPPORT;
20473 		}
20474 	} else {
20475 		int i;
20476 		boolean_t priv = B_FALSE;
20477 
20478 		/*
20479 		 * If the requested_port is in the well-known privileged range,
20480 		 * verify that the stream was opened by a privileged user.
20481 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
20482 		 * but instead the code relies on:
20483 		 * - the fact that the address of the array and its size never
20484 		 *   changes
20485 		 * - the atomic assignment of the elements of the array
20486 		 */
20487 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
20488 			priv = B_TRUE;
20489 		} else {
20490 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
20491 				if (requested_port ==
20492 				    tcps->tcps_g_epriv_ports[i]) {
20493 					priv = B_TRUE;
20494 					break;
20495 				}
20496 			}
20497 		}
20498 		if (priv) {
20499 			if (secpolicy_net_privaddr(cr, requested_port,
20500 			    IPPROTO_TCP) != 0) {
20501 				if (connp->conn_debug) {
20502 					(void) strlog(TCP_MOD_ID, 0, 1,
20503 					    SL_ERROR|SL_TRACE,
20504 					    "tcp_bind: no priv for port %d",
20505 					    requested_port);
20506 				}
20507 				return (-TACCES);
20508 			}
20509 		}
20510 		user_specified = B_TRUE;
20511 
20512 		connp = tcp->tcp_connp;
20513 		if (is_system_labeled()) {
20514 			zone = crgetzone(cr);
20515 			addrtype = tsol_mlp_addr_type(
20516 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20517 			    IPV6_VERSION, &v6addr,
20518 			    tcps->tcps_netstack->netstack_ip);
20519 			if (addrtype == mlptSingle) {
20520 				return (-TNOADDR);
20521 			}
20522 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20523 			    requested_port, addrtype);
20524 		}
20525 	}
20526 
20527 	if (mlptype != mlptSingle) {
20528 		if (secpolicy_net_bindmlp(cr) != 0) {
20529 			if (connp->conn_debug) {
20530 				(void) strlog(TCP_MOD_ID, 0, 1,
20531 				    SL_ERROR|SL_TRACE,
20532 				    "tcp_bind: no priv for multilevel port %d",
20533 				    requested_port);
20534 			}
20535 			return (-TACCES);
20536 		}
20537 
20538 		/*
20539 		 * If we're specifically binding a shared IP address and the
20540 		 * port is MLP on shared addresses, then check to see if this
20541 		 * zone actually owns the MLP.  Reject if not.
20542 		 */
20543 		if (mlptype == mlptShared && addrtype == mlptShared) {
20544 			/*
20545 			 * No need to handle exclusive-stack zones since
20546 			 * ALL_ZONES only applies to the shared stack.
20547 			 */
20548 			zoneid_t mlpzone;
20549 
20550 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
20551 			    htons(mlp_port));
20552 			if (connp->conn_zoneid != mlpzone) {
20553 				if (connp->conn_debug) {
20554 					(void) strlog(TCP_MOD_ID, 0, 1,
20555 					    SL_ERROR|SL_TRACE,
20556 					    "tcp_bind: attempt to bind port "
20557 					    "%d on shared addr in zone %d "
20558 					    "(should be %d)",
20559 					    mlp_port, connp->conn_zoneid,
20560 					    mlpzone);
20561 				}
20562 				return (-TACCES);
20563 			}
20564 		}
20565 
20566 		if (!user_specified) {
20567 			int err;
20568 			err = tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20569 			    requested_port, B_TRUE);
20570 			if (err != 0) {
20571 				if (connp->conn_debug) {
20572 					(void) strlog(TCP_MOD_ID, 0, 1,
20573 					    SL_ERROR|SL_TRACE,
20574 					    "tcp_bind: cannot establish anon "
20575 					    "MLP for port %d",
20576 					    requested_port);
20577 				}
20578 				return (err);
20579 			}
20580 			connp->conn_anon_port = B_TRUE;
20581 		}
20582 		connp->conn_mlp_type = mlptype;
20583 	}
20584 
20585 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
20586 	    connp->conn_reuseaddr, B_FALSE, bind_to_req_port_only,
20587 	    user_specified);
20588 
20589 	if (allocated_port == 0) {
20590 		connp->conn_mlp_type = mlptSingle;
20591 		if (connp->conn_anon_port) {
20592 			connp->conn_anon_port = B_FALSE;
20593 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20594 			    requested_port, B_FALSE);
20595 		}
20596 		if (bind_to_req_port_only) {
20597 			if (connp->conn_debug) {
20598 				(void) strlog(TCP_MOD_ID, 0, 1,
20599 				    SL_ERROR|SL_TRACE,
20600 				    "tcp_bind: requested addr busy");
20601 			}
20602 			return (-TADDRBUSY);
20603 		} else {
20604 			/* If we are out of ports, fail the bind. */
20605 			if (connp->conn_debug) {
20606 				(void) strlog(TCP_MOD_ID, 0, 1,
20607 				    SL_ERROR|SL_TRACE,
20608 				    "tcp_bind: out of ports?");
20609 			}
20610 			return (-TNOADDR);
20611 		}
20612 	}
20613 
20614 	/* Pass the allocated port back */
20615 	*requested_port_ptr = allocated_port;
20616 	return (0);
20617 }
20618 
20619 /*
20620  * Check the address and check/pick a local port number.
20621  */
20622 static int
20623 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20624     boolean_t bind_to_req_port_only)
20625 {
20626 	tcp_t	*tcp = connp->conn_tcp;
20627 	sin_t	*sin;
20628 	sin6_t  *sin6;
20629 	in_port_t	requested_port;
20630 	ipaddr_t	v4addr;
20631 	in6_addr_t	v6addr;
20632 	ip_laddr_t	laddr_type = IPVL_UNICAST_UP;	/* INADDR_ANY */
20633 	zoneid_t	zoneid = IPCL_ZONEID(connp);
20634 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
20635 	uint_t		scopeid = 0;
20636 	int		error = 0;
20637 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20638 
20639 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
20640 
20641 	if (tcp->tcp_state == TCPS_BOUND) {
20642 		return (0);
20643 	} else if (tcp->tcp_state > TCPS_BOUND) {
20644 		if (connp->conn_debug) {
20645 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20646 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20647 		}
20648 		return (-TOUTSTATE);
20649 	}
20650 
20651 	ASSERT(sa != NULL && len != 0);
20652 
20653 	if (!OK_32PTR((char *)sa)) {
20654 		if (connp->conn_debug) {
20655 			(void) strlog(TCP_MOD_ID, 0, 1,
20656 			    SL_ERROR|SL_TRACE,
20657 			    "tcp_bind: bad address parameter, "
20658 			    "address %p, len %d",
20659 			    (void *)sa, len);
20660 		}
20661 		return (-TPROTO);
20662 	}
20663 
20664 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
20665 	if (error != 0) {
20666 		return (error);
20667 	}
20668 
20669 	switch (len) {
20670 	case sizeof (sin_t):	/* Complete IPv4 address */
20671 		sin = (sin_t *)sa;
20672 		requested_port = ntohs(sin->sin_port);
20673 		v4addr = sin->sin_addr.s_addr;
20674 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
20675 		if (v4addr != INADDR_ANY) {
20676 			laddr_type = ip_laddr_verify_v4(v4addr, zoneid, ipst,
20677 			    B_FALSE);
20678 		}
20679 		break;
20680 
20681 	case sizeof (sin6_t): /* Complete IPv6 address */
20682 		sin6 = (sin6_t *)sa;
20683 		v6addr = sin6->sin6_addr;
20684 		requested_port = ntohs(sin6->sin6_port);
20685 		if (IN6_IS_ADDR_V4MAPPED(&v6addr)) {
20686 			if (connp->conn_ipv6_v6only)
20687 				return (EADDRNOTAVAIL);
20688 
20689 			IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
20690 			if (v4addr != INADDR_ANY) {
20691 				laddr_type = ip_laddr_verify_v4(v4addr,
20692 				    zoneid, ipst, B_FALSE);
20693 			}
20694 		} else {
20695 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6addr)) {
20696 				if (IN6_IS_ADDR_LINKSCOPE(&v6addr))
20697 					scopeid = sin6->sin6_scope_id;
20698 				laddr_type = ip_laddr_verify_v6(&v6addr,
20699 				    zoneid, ipst, B_FALSE, scopeid);
20700 			}
20701 		}
20702 		break;
20703 
20704 	default:
20705 		if (connp->conn_debug) {
20706 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20707 			    "tcp_bind: bad address length, %d", len);
20708 		}
20709 		return (EAFNOSUPPORT);
20710 		/* return (-TBADADDR); */
20711 	}
20712 
20713 	/* Is the local address a valid unicast address? */
20714 	if (laddr_type == IPVL_BAD)
20715 		return (EADDRNOTAVAIL);
20716 
20717 	connp->conn_bound_addr_v6 = v6addr;
20718 	if (scopeid != 0) {
20719 		ixa->ixa_flags |= IXAF_SCOPEID_SET;
20720 		ixa->ixa_scopeid = scopeid;
20721 		connp->conn_incoming_ifindex = scopeid;
20722 	} else {
20723 		ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
20724 		connp->conn_incoming_ifindex = connp->conn_bound_if;
20725 	}
20726 
20727 	connp->conn_laddr_v6 = v6addr;
20728 	connp->conn_saddr_v6 = v6addr;
20729 
20730 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
20731 
20732 	error = tcp_bind_select_lport(tcp, &requested_port,
20733 	    bind_to_req_port_only, cr);
20734 	if (error != 0) {
20735 		connp->conn_laddr_v6 = ipv6_all_zeros;
20736 		connp->conn_saddr_v6 = ipv6_all_zeros;
20737 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
20738 	}
20739 	return (error);
20740 }
20741 
20742 /*
20743  * Return unix error is tli error is TSYSERR, otherwise return a negative
20744  * tli error.
20745  */
20746 int
20747 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20748     boolean_t bind_to_req_port_only)
20749 {
20750 	int error;
20751 	tcp_t *tcp = connp->conn_tcp;
20752 
20753 	if (tcp->tcp_state >= TCPS_BOUND) {
20754 		if (connp->conn_debug) {
20755 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20756 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20757 		}
20758 		return (-TOUTSTATE);
20759 	}
20760 
20761 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
20762 	if (error != 0)
20763 		return (error);
20764 
20765 	ASSERT(tcp->tcp_state == TCPS_BOUND);
20766 	tcp->tcp_conn_req_max = 0;
20767 	return (0);
20768 }
20769 
20770 int
20771 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
20772     socklen_t len, cred_t *cr)
20773 {
20774 	int 		error;
20775 	conn_t		*connp = (conn_t *)proto_handle;
20776 	squeue_t	*sqp = connp->conn_sqp;
20777 
20778 	/* All Solaris components should pass a cred for this operation. */
20779 	ASSERT(cr != NULL);
20780 
20781 	ASSERT(sqp != NULL);
20782 	ASSERT(connp->conn_upper_handle != NULL);
20783 
20784 	error = squeue_synch_enter(sqp, connp, NULL);
20785 	if (error != 0) {
20786 		/* failed to enter */
20787 		return (ENOSR);
20788 	}
20789 
20790 	/* binding to a NULL address really means unbind */
20791 	if (sa == NULL) {
20792 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
20793 			error = tcp_do_unbind(connp);
20794 		else
20795 			error = EINVAL;
20796 	} else {
20797 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
20798 	}
20799 
20800 	squeue_synch_exit(sqp, connp);
20801 
20802 	if (error < 0) {
20803 		if (error == -TOUTSTATE)
20804 			error = EINVAL;
20805 		else
20806 			error = proto_tlitosyserr(-error);
20807 	}
20808 
20809 	return (error);
20810 }
20811 
20812 /*
20813  * If the return value from this function is positive, it's a UNIX error.
20814  * Otherwise, if it's negative, then the absolute value is a TLI error.
20815  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
20816  */
20817 int
20818 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
20819     cred_t *cr, pid_t pid)
20820 {
20821 	tcp_t		*tcp = connp->conn_tcp;
20822 	sin_t		*sin = (sin_t *)sa;
20823 	sin6_t		*sin6 = (sin6_t *)sa;
20824 	ipaddr_t	*dstaddrp;
20825 	in_port_t	dstport;
20826 	uint_t		srcid;
20827 	int		error;
20828 	uint32_t	mss;
20829 	mblk_t		*syn_mp;
20830 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20831 	int32_t		oldstate;
20832 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20833 
20834 	oldstate = tcp->tcp_state;
20835 
20836 	switch (len) {
20837 	default:
20838 		/*
20839 		 * Should never happen
20840 		 */
20841 		return (EINVAL);
20842 
20843 	case sizeof (sin_t):
20844 		sin = (sin_t *)sa;
20845 		if (sin->sin_port == 0) {
20846 			return (-TBADADDR);
20847 		}
20848 		if (connp->conn_ipv6_v6only) {
20849 			return (EAFNOSUPPORT);
20850 		}
20851 		break;
20852 
20853 	case sizeof (sin6_t):
20854 		sin6 = (sin6_t *)sa;
20855 		if (sin6->sin6_port == 0) {
20856 			return (-TBADADDR);
20857 		}
20858 		break;
20859 	}
20860 	/*
20861 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
20862 	 * make sure that the conn_ipversion is IPV4_VERSION.  We
20863 	 * need to this before we call tcp_bindi() so that the port lookup
20864 	 * code will look for ports in the correct port space (IPv4 and
20865 	 * IPv6 have separate port spaces).
20866 	 */
20867 	if (connp->conn_family == AF_INET6 &&
20868 	    connp->conn_ipversion == IPV6_VERSION &&
20869 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20870 		if (connp->conn_ipv6_v6only)
20871 			return (EADDRNOTAVAIL);
20872 
20873 		connp->conn_ipversion = IPV4_VERSION;
20874 	}
20875 
20876 	switch (tcp->tcp_state) {
20877 	case TCPS_LISTEN:
20878 		/*
20879 		 * Listening sockets are not allowed to issue connect().
20880 		 */
20881 		if (IPCL_IS_NONSTR(connp))
20882 			return (EOPNOTSUPP);
20883 		/* FALLTHRU */
20884 	case TCPS_IDLE:
20885 		/*
20886 		 * We support quick connect, refer to comments in
20887 		 * tcp_connect_*()
20888 		 */
20889 		/* FALLTHRU */
20890 	case TCPS_BOUND:
20891 		break;
20892 	default:
20893 		return (-TOUTSTATE);
20894 	}
20895 
20896 	/*
20897 	 * We update our cred/cpid based on the caller of connect
20898 	 */
20899 	if (connp->conn_cred != cr) {
20900 		crhold(cr);
20901 		crfree(connp->conn_cred);
20902 		connp->conn_cred = cr;
20903 	}
20904 	connp->conn_cpid = pid;
20905 
20906 	/* Cache things in the ixa without any refhold */
20907 	ixa->ixa_cred = cr;
20908 	ixa->ixa_cpid = pid;
20909 	if (is_system_labeled()) {
20910 		/* We need to restart with a label based on the cred */
20911 		ip_xmit_attr_restore_tsl(ixa, ixa->ixa_cred);
20912 	}
20913 
20914 	if (connp->conn_family == AF_INET6) {
20915 		if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20916 			error = tcp_connect_ipv6(tcp, &sin6->sin6_addr,
20917 			    sin6->sin6_port, sin6->sin6_flowinfo,
20918 			    sin6->__sin6_src_id, sin6->sin6_scope_id);
20919 		} else {
20920 			/*
20921 			 * Destination adress is mapped IPv6 address.
20922 			 * Source bound address should be unspecified or
20923 			 * IPv6 mapped address as well.
20924 			 */
20925 			if (!IN6_IS_ADDR_UNSPECIFIED(
20926 			    &connp->conn_bound_addr_v6) &&
20927 			    !IN6_IS_ADDR_V4MAPPED(&connp->conn_bound_addr_v6)) {
20928 				return (EADDRNOTAVAIL);
20929 			}
20930 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
20931 			dstport = sin6->sin6_port;
20932 			srcid = sin6->__sin6_src_id;
20933 			error = tcp_connect_ipv4(tcp, dstaddrp, dstport,
20934 			    srcid);
20935 		}
20936 	} else {
20937 		dstaddrp = &sin->sin_addr.s_addr;
20938 		dstport = sin->sin_port;
20939 		srcid = 0;
20940 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid);
20941 	}
20942 
20943 	if (error != 0)
20944 		goto connect_failed;
20945 
20946 	CL_INET_CONNECT(connp, B_TRUE, error);
20947 	if (error != 0)
20948 		goto connect_failed;
20949 
20950 	/* connect succeeded */
20951 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
20952 	tcp->tcp_active_open = 1;
20953 
20954 	/*
20955 	 * tcp_set_destination() does not adjust for TCP/IP header length.
20956 	 */
20957 	mss = tcp->tcp_mss - connp->conn_ht_iphc_len;
20958 
20959 	/*
20960 	 * Just make sure our rwnd is at least rcvbuf * MSS large, and round up
20961 	 * to the nearest MSS.
20962 	 *
20963 	 * We do the round up here because we need to get the interface MTU
20964 	 * first before we can do the round up.
20965 	 */
20966 	tcp->tcp_rwnd = connp->conn_rcvbuf;
20967 	tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
20968 	    tcps->tcps_recv_hiwat_minmss * mss);
20969 	connp->conn_rcvbuf = tcp->tcp_rwnd;
20970 	tcp_set_ws_value(tcp);
20971 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
20972 	if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
20973 		tcp->tcp_snd_ws_ok = B_TRUE;
20974 
20975 	/*
20976 	 * Set tcp_snd_ts_ok to true
20977 	 * so that tcp_xmit_mp will
20978 	 * include the timestamp
20979 	 * option in the SYN segment.
20980 	 */
20981 	if (tcps->tcps_tstamp_always ||
20982 	    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
20983 		tcp->tcp_snd_ts_ok = B_TRUE;
20984 	}
20985 
20986 	/*
20987 	 * tcp_snd_sack_ok can be set in
20988 	 * tcp_set_destination() if the sack metric
20989 	 * is set.  So check it here also.
20990 	 */
20991 	if (tcps->tcps_sack_permitted == 2 ||
20992 	    tcp->tcp_snd_sack_ok) {
20993 		if (tcp->tcp_sack_info == NULL) {
20994 			tcp->tcp_sack_info = kmem_cache_alloc(
20995 			    tcp_sack_info_cache, KM_SLEEP);
20996 		}
20997 		tcp->tcp_snd_sack_ok = B_TRUE;
20998 	}
20999 
21000 	/*
21001 	 * Should we use ECN?  Note that the current
21002 	 * default value (SunOS 5.9) of tcp_ecn_permitted
21003 	 * is 1.  The reason for doing this is that there
21004 	 * are equipments out there that will drop ECN
21005 	 * enabled IP packets.  Setting it to 1 avoids
21006 	 * compatibility problems.
21007 	 */
21008 	if (tcps->tcps_ecn_permitted == 2)
21009 		tcp->tcp_ecn_ok = B_TRUE;
21010 
21011 	TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21012 	syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
21013 	    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
21014 	if (syn_mp != NULL) {
21015 		/*
21016 		 * We must bump the generation before sending the syn
21017 		 * to ensure that we use the right generation in case
21018 		 * this thread issues a "connected" up call.
21019 		 */
21020 		SOCK_CONNID_BUMP(tcp->tcp_connid);
21021 		tcp_send_data(tcp, syn_mp);
21022 	}
21023 
21024 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21025 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21026 	return (0);
21027 
21028 connect_failed:
21029 	connp->conn_faddr_v6 = ipv6_all_zeros;
21030 	connp->conn_fport = 0;
21031 	tcp->tcp_state = oldstate;
21032 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
21033 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
21034 	return (error);
21035 }
21036 
21037 int
21038 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
21039     socklen_t len, sock_connid_t *id, cred_t *cr)
21040 {
21041 	conn_t		*connp = (conn_t *)proto_handle;
21042 	squeue_t	*sqp = connp->conn_sqp;
21043 	int		error;
21044 
21045 	ASSERT(connp->conn_upper_handle != NULL);
21046 
21047 	/* All Solaris components should pass a cred for this operation. */
21048 	ASSERT(cr != NULL);
21049 
21050 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
21051 	if (error != 0) {
21052 		return (error);
21053 	}
21054 
21055 	error = squeue_synch_enter(sqp, connp, NULL);
21056 	if (error != 0) {
21057 		/* failed to enter */
21058 		return (ENOSR);
21059 	}
21060 
21061 	/*
21062 	 * TCP supports quick connect, so no need to do an implicit bind
21063 	 */
21064 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
21065 	if (error == 0) {
21066 		*id = connp->conn_tcp->tcp_connid;
21067 	} else if (error < 0) {
21068 		if (error == -TOUTSTATE) {
21069 			switch (connp->conn_tcp->tcp_state) {
21070 			case TCPS_SYN_SENT:
21071 				error = EALREADY;
21072 				break;
21073 			case TCPS_ESTABLISHED:
21074 				error = EISCONN;
21075 				break;
21076 			case TCPS_LISTEN:
21077 				error = EOPNOTSUPP;
21078 				break;
21079 			default:
21080 				error = EINVAL;
21081 				break;
21082 			}
21083 		} else {
21084 			error = proto_tlitosyserr(-error);
21085 		}
21086 	}
21087 
21088 	if (connp->conn_tcp->tcp_loopback) {
21089 		struct sock_proto_props sopp;
21090 
21091 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
21092 		sopp.sopp_loopback = B_TRUE;
21093 
21094 		(*connp->conn_upcalls->su_set_proto_props)(
21095 		    connp->conn_upper_handle, &sopp);
21096 	}
21097 done:
21098 	squeue_synch_exit(sqp, connp);
21099 
21100 	return ((error == 0) ? EINPROGRESS : error);
21101 }
21102 
21103 /* ARGSUSED */
21104 sock_lower_handle_t
21105 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
21106     uint_t *smodep, int *errorp, int flags, cred_t *credp)
21107 {
21108 	conn_t		*connp;
21109 	boolean_t	isv6 = family == AF_INET6;
21110 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
21111 	    (proto != 0 && proto != IPPROTO_TCP)) {
21112 		*errorp = EPROTONOSUPPORT;
21113 		return (NULL);
21114 	}
21115 
21116 	connp = tcp_create_common(credp, isv6, B_TRUE, errorp);
21117 	if (connp == NULL) {
21118 		return (NULL);
21119 	}
21120 
21121 	/*
21122 	 * Put the ref for TCP. Ref for IP was already put
21123 	 * by ipcl_conn_create. Also Make the conn_t globally
21124 	 * visible to walkers
21125 	 */
21126 	mutex_enter(&connp->conn_lock);
21127 	CONN_INC_REF_LOCKED(connp);
21128 	ASSERT(connp->conn_ref == 2);
21129 	connp->conn_state_flags &= ~CONN_INCIPIENT;
21130 
21131 	connp->conn_flags |= IPCL_NONSTR;
21132 	mutex_exit(&connp->conn_lock);
21133 
21134 	ASSERT(errorp != NULL);
21135 	*errorp = 0;
21136 	*sock_downcalls = &sock_tcp_downcalls;
21137 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
21138 	    SM_SENDFILESUPP;
21139 
21140 	return ((sock_lower_handle_t)connp);
21141 }
21142 
21143 /* ARGSUSED */
21144 void
21145 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
21146     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
21147 {
21148 	conn_t *connp = (conn_t *)proto_handle;
21149 	struct sock_proto_props sopp;
21150 
21151 	ASSERT(connp->conn_upper_handle == NULL);
21152 
21153 	/* All Solaris components should pass a cred for this operation. */
21154 	ASSERT(cr != NULL);
21155 
21156 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
21157 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
21158 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
21159 
21160 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
21161 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
21162 	sopp.sopp_maxpsz = INFPSZ;
21163 	sopp.sopp_maxblk = INFPSZ;
21164 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
21165 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
21166 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
21167 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
21168 	    tcp_rinfo.mi_minpsz;
21169 
21170 	connp->conn_upcalls = sock_upcalls;
21171 	connp->conn_upper_handle = sock_handle;
21172 
21173 	ASSERT(connp->conn_rcvbuf != 0 &&
21174 	    connp->conn_rcvbuf == connp->conn_tcp->tcp_rwnd);
21175 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
21176 }
21177 
21178 /* ARGSUSED */
21179 int
21180 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
21181 {
21182 	conn_t *connp = (conn_t *)proto_handle;
21183 
21184 	ASSERT(connp->conn_upper_handle != NULL);
21185 
21186 	/* All Solaris components should pass a cred for this operation. */
21187 	ASSERT(cr != NULL);
21188 
21189 	tcp_close_common(connp, flags);
21190 
21191 	ip_free_helper_stream(connp);
21192 
21193 	/*
21194 	 * Drop IP's reference on the conn. This is the last reference
21195 	 * on the connp if the state was less than established. If the
21196 	 * connection has gone into timewait state, then we will have
21197 	 * one ref for the TCP and one more ref (total of two) for the
21198 	 * classifier connected hash list (a timewait connections stays
21199 	 * in connected hash till closed).
21200 	 *
21201 	 * We can't assert the references because there might be other
21202 	 * transient reference places because of some walkers or queued
21203 	 * packets in squeue for the timewait state.
21204 	 */
21205 	CONN_DEC_REF(connp);
21206 	return (0);
21207 }
21208 
21209 /* ARGSUSED */
21210 int
21211 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
21212     cred_t *cr)
21213 {
21214 	tcp_t		*tcp;
21215 	uint32_t	msize;
21216 	conn_t *connp = (conn_t *)proto_handle;
21217 	int32_t		tcpstate;
21218 
21219 	/* All Solaris components should pass a cred for this operation. */
21220 	ASSERT(cr != NULL);
21221 
21222 	ASSERT(connp->conn_ref >= 2);
21223 	ASSERT(connp->conn_upper_handle != NULL);
21224 
21225 	if (msg->msg_controllen != 0) {
21226 		freemsg(mp);
21227 		return (EOPNOTSUPP);
21228 	}
21229 
21230 	switch (DB_TYPE(mp)) {
21231 	case M_DATA:
21232 		tcp = connp->conn_tcp;
21233 		ASSERT(tcp != NULL);
21234 
21235 		tcpstate = tcp->tcp_state;
21236 		if (tcpstate < TCPS_ESTABLISHED) {
21237 			freemsg(mp);
21238 			/*
21239 			 * We return ENOTCONN if the endpoint is trying to
21240 			 * connect or has never been connected, and EPIPE if it
21241 			 * has been disconnected. The connection id helps us
21242 			 * distinguish between the last two cases.
21243 			 */
21244 			return ((tcpstate == TCPS_SYN_SENT) ? ENOTCONN :
21245 			    ((tcp->tcp_connid > 0) ? EPIPE : ENOTCONN));
21246 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
21247 			freemsg(mp);
21248 			return (EPIPE);
21249 		}
21250 
21251 		msize = msgdsize(mp);
21252 
21253 		mutex_enter(&tcp->tcp_non_sq_lock);
21254 		tcp->tcp_squeue_bytes += msize;
21255 		/*
21256 		 * Squeue Flow Control
21257 		 */
21258 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
21259 			tcp_setqfull(tcp);
21260 		}
21261 		mutex_exit(&tcp->tcp_non_sq_lock);
21262 
21263 		/*
21264 		 * The application may pass in an address in the msghdr, but
21265 		 * we ignore the address on connection-oriented sockets.
21266 		 * Just like BSD this code does not generate an error for
21267 		 * TCP (a CONNREQUIRED socket) when sending to an address
21268 		 * passed in with sendto/sendmsg. Instead the data is
21269 		 * delivered on the connection as if no address had been
21270 		 * supplied.
21271 		 */
21272 		CONN_INC_REF(connp);
21273 
21274 		if (msg->msg_flags & MSG_OOB) {
21275 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output_urgent,
21276 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21277 		} else {
21278 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
21279 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21280 		}
21281 
21282 		return (0);
21283 
21284 	default:
21285 		ASSERT(0);
21286 	}
21287 
21288 	freemsg(mp);
21289 	return (0);
21290 }
21291 
21292 /* ARGSUSED2 */
21293 void
21294 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21295 {
21296 	int len;
21297 	uint32_t msize;
21298 	conn_t *connp = (conn_t *)arg;
21299 	tcp_t *tcp = connp->conn_tcp;
21300 
21301 	msize = msgdsize(mp);
21302 
21303 	len = msize - 1;
21304 	if (len < 0) {
21305 		freemsg(mp);
21306 		return;
21307 	}
21308 
21309 	/*
21310 	 * Try to force urgent data out on the wire. Even if we have unsent
21311 	 * data this will at least send the urgent flag.
21312 	 * XXX does not handle more flag correctly.
21313 	 */
21314 	len += tcp->tcp_unsent;
21315 	len += tcp->tcp_snxt;
21316 	tcp->tcp_urg = len;
21317 	tcp->tcp_valid_bits |= TCP_URG_VALID;
21318 
21319 	/* Bypass tcp protocol for fused tcp loopback */
21320 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21321 		return;
21322 
21323 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
21324 	if (DB_TYPE(mp) != M_DATA) {
21325 		mblk_t *mp1 = mp;
21326 		ASSERT(!IPCL_IS_NONSTR(connp));
21327 		mp = mp->b_cont;
21328 		freeb(mp1);
21329 	}
21330 	tcp_wput_data(tcp, mp, B_TRUE);
21331 }
21332 
21333 /* ARGSUSED3 */
21334 int
21335 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21336     socklen_t *addrlenp, cred_t *cr)
21337 {
21338 	conn_t	*connp = (conn_t *)proto_handle;
21339 	tcp_t	*tcp = connp->conn_tcp;
21340 
21341 	ASSERT(connp->conn_upper_handle != NULL);
21342 	/* All Solaris components should pass a cred for this operation. */
21343 	ASSERT(cr != NULL);
21344 
21345 	ASSERT(tcp != NULL);
21346 	if (tcp->tcp_state < TCPS_SYN_RCVD)
21347 		return (ENOTCONN);
21348 
21349 	return (conn_getpeername(connp, addr, addrlenp));
21350 }
21351 
21352 /* ARGSUSED3 */
21353 int
21354 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21355     socklen_t *addrlenp, cred_t *cr)
21356 {
21357 	conn_t	*connp = (conn_t *)proto_handle;
21358 
21359 	/* All Solaris components should pass a cred for this operation. */
21360 	ASSERT(cr != NULL);
21361 
21362 	ASSERT(connp->conn_upper_handle != NULL);
21363 	return (conn_getsockname(connp, addr, addrlenp));
21364 }
21365 
21366 /*
21367  * tcp_fallback
21368  *
21369  * A direct socket is falling back to using STREAMS. The queue
21370  * that is being passed down was created using tcp_open() with
21371  * the SO_FALLBACK flag set. As a result, the queue is not
21372  * associated with a conn, and the q_ptrs instead contain the
21373  * dev and minor area that should be used.
21374  *
21375  * The 'issocket' flag indicates whether the FireEngine
21376  * optimizations should be used. The common case would be that
21377  * optimizations are enabled, and they might be subsequently
21378  * disabled using the _SIOCSOCKFALLBACK ioctl.
21379  */
21380 
21381 /*
21382  * An active connection is falling back to TPI. Gather all the information
21383  * required by the STREAM head and TPI sonode and send it up.
21384  */
21385 void
21386 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
21387     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
21388 {
21389 	conn_t			*connp = tcp->tcp_connp;
21390 	struct stroptions	*stropt;
21391 	struct T_capability_ack tca;
21392 	struct sockaddr_in6	laddr, faddr;
21393 	socklen_t 		laddrlen, faddrlen;
21394 	short			opts;
21395 	int			error;
21396 	mblk_t			*mp;
21397 
21398 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
21399 	connp->conn_minor_arena = WR(q)->q_ptr;
21400 
21401 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
21402 
21403 	connp->conn_rq = RD(q);
21404 	connp->conn_wq = WR(q);
21405 
21406 	WR(q)->q_qinfo = &tcp_sock_winit;
21407 
21408 	if (!issocket)
21409 		tcp_use_pure_tpi(tcp);
21410 
21411 	/*
21412 	 * free the helper stream
21413 	 */
21414 	ip_free_helper_stream(connp);
21415 
21416 	/*
21417 	 * Notify the STREAM head about options
21418 	 */
21419 	DB_TYPE(stropt_mp) = M_SETOPTS;
21420 	stropt = (struct stroptions *)stropt_mp->b_rptr;
21421 	stropt_mp->b_wptr += sizeof (struct stroptions);
21422 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
21423 
21424 	stropt->so_wroff = connp->conn_ht_iphc_len + (tcp->tcp_loopback ? 0 :
21425 	    tcp->tcp_tcps->tcps_wroff_xtra);
21426 	if (tcp->tcp_snd_sack_ok)
21427 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
21428 	stropt->so_hiwat = connp->conn_rcvbuf;
21429 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
21430 
21431 	putnext(RD(q), stropt_mp);
21432 
21433 	/*
21434 	 * Collect the information needed to sync with the sonode
21435 	 */
21436 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
21437 
21438 	laddrlen = faddrlen = sizeof (sin6_t);
21439 	(void) tcp_getsockname((sock_lower_handle_t)connp,
21440 	    (struct sockaddr *)&laddr, &laddrlen, CRED());
21441 	error = tcp_getpeername((sock_lower_handle_t)connp,
21442 	    (struct sockaddr *)&faddr, &faddrlen, CRED());
21443 	if (error != 0)
21444 		faddrlen = 0;
21445 
21446 	opts = 0;
21447 	if (connp->conn_oobinline)
21448 		opts |= SO_OOBINLINE;
21449 	if (connp->conn_ixa->ixa_flags & IXAF_DONTROUTE)
21450 		opts |= SO_DONTROUTE;
21451 
21452 	/*
21453 	 * Notify the socket that the protocol is now quiescent,
21454 	 * and it's therefore safe move data from the socket
21455 	 * to the stream head.
21456 	 */
21457 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
21458 	    (struct sockaddr *)&laddr, laddrlen,
21459 	    (struct sockaddr *)&faddr, faddrlen, opts);
21460 
21461 	while ((mp = tcp->tcp_rcv_list) != NULL) {
21462 		tcp->tcp_rcv_list = mp->b_next;
21463 		mp->b_next = NULL;
21464 		/* We never do fallback for kernel RPC */
21465 		putnext(q, mp);
21466 	}
21467 	tcp->tcp_rcv_last_head = NULL;
21468 	tcp->tcp_rcv_last_tail = NULL;
21469 	tcp->tcp_rcv_cnt = 0;
21470 }
21471 
21472 /*
21473  * An eager is falling back to TPI. All we have to do is send
21474  * up a T_CONN_IND.
21475  */
21476 void
21477 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
21478 {
21479 	tcp_t *listener = eager->tcp_listener;
21480 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
21481 
21482 	ASSERT(listener != NULL);
21483 	ASSERT(mp != NULL);
21484 
21485 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
21486 
21487 	/*
21488 	 * TLI/XTI applications will get confused by
21489 	 * sending eager as an option since it violates
21490 	 * the option semantics. So remove the eager as
21491 	 * option since TLI/XTI app doesn't need it anyway.
21492 	 */
21493 	if (!direct_sockfs) {
21494 		struct T_conn_ind *conn_ind;
21495 
21496 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
21497 		conn_ind->OPT_length = 0;
21498 		conn_ind->OPT_offset = 0;
21499 	}
21500 
21501 	/*
21502 	 * Sockfs guarantees that the listener will not be closed
21503 	 * during fallback. So we can safely use the listener's queue.
21504 	 */
21505 	putnext(listener->tcp_connp->conn_rq, mp);
21506 }
21507 
21508 int
21509 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
21510     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
21511 {
21512 	tcp_t			*tcp;
21513 	conn_t 			*connp = (conn_t *)proto_handle;
21514 	int			error;
21515 	mblk_t			*stropt_mp;
21516 	mblk_t			*ordrel_mp;
21517 
21518 	tcp = connp->conn_tcp;
21519 
21520 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
21521 	    NULL);
21522 
21523 	/* Pre-allocate the T_ordrel_ind mblk. */
21524 	ASSERT(tcp->tcp_ordrel_mp == NULL);
21525 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
21526 	    STR_NOSIG, NULL);
21527 	ordrel_mp->b_datap->db_type = M_PROTO;
21528 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
21529 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
21530 
21531 	/*
21532 	 * Enter the squeue so that no new packets can come in
21533 	 */
21534 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
21535 	if (error != 0) {
21536 		/* failed to enter, free all the pre-allocated messages. */
21537 		freeb(stropt_mp);
21538 		freeb(ordrel_mp);
21539 		/*
21540 		 * We cannot process the eager, so at least send out a
21541 		 * RST so the peer can reconnect.
21542 		 */
21543 		if (tcp->tcp_listener != NULL) {
21544 			(void) tcp_eager_blowoff(tcp->tcp_listener,
21545 			    tcp->tcp_conn_req_seqnum);
21546 		}
21547 		return (ENOMEM);
21548 	}
21549 
21550 	/*
21551 	 * Both endpoints must be of the same type (either STREAMS or
21552 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
21553 	 * we have to unfuse.
21554 	 */
21555 	if (tcp->tcp_fused)
21556 		tcp_unfuse(tcp);
21557 
21558 	/*
21559 	 * No longer a direct socket
21560 	 */
21561 	connp->conn_flags &= ~IPCL_NONSTR;
21562 	tcp->tcp_ordrel_mp = ordrel_mp;
21563 
21564 	if (tcp->tcp_listener != NULL) {
21565 		/* The eager will deal with opts when accept() is called */
21566 		freeb(stropt_mp);
21567 		tcp_fallback_eager(tcp, direct_sockfs);
21568 	} else {
21569 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
21570 		    quiesced_cb);
21571 	}
21572 
21573 	/*
21574 	 * There should be atleast two ref's (IP + TCP)
21575 	 */
21576 	ASSERT(connp->conn_ref >= 2);
21577 	squeue_synch_exit(connp->conn_sqp, connp);
21578 
21579 	return (0);
21580 }
21581 
21582 /* ARGSUSED */
21583 static void
21584 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21585 {
21586 	conn_t 	*connp = (conn_t *)arg;
21587 	tcp_t	*tcp = connp->conn_tcp;
21588 
21589 	freemsg(mp);
21590 
21591 	if (tcp->tcp_fused)
21592 		tcp_unfuse(tcp);
21593 
21594 	if (tcp_xmit_end(tcp) != 0) {
21595 		/*
21596 		 * We were crossing FINs and got a reset from
21597 		 * the other side. Just ignore it.
21598 		 */
21599 		if (connp->conn_debug) {
21600 			(void) strlog(TCP_MOD_ID, 0, 1,
21601 			    SL_ERROR|SL_TRACE,
21602 			    "tcp_shutdown_output() out of state %s",
21603 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
21604 		}
21605 	}
21606 }
21607 
21608 /* ARGSUSED */
21609 int
21610 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
21611 {
21612 	conn_t  *connp = (conn_t *)proto_handle;
21613 	tcp_t   *tcp = connp->conn_tcp;
21614 
21615 	ASSERT(connp->conn_upper_handle != NULL);
21616 
21617 	/* All Solaris components should pass a cred for this operation. */
21618 	ASSERT(cr != NULL);
21619 
21620 	/*
21621 	 * X/Open requires that we check the connected state.
21622 	 */
21623 	if (tcp->tcp_state < TCPS_SYN_SENT)
21624 		return (ENOTCONN);
21625 
21626 	/* shutdown the send side */
21627 	if (how != SHUT_RD) {
21628 		mblk_t *bp;
21629 
21630 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
21631 		CONN_INC_REF(connp);
21632 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
21633 		    connp, NULL, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
21634 
21635 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21636 		    SOCK_OPCTL_SHUT_SEND, 0);
21637 	}
21638 
21639 	/* shutdown the recv side */
21640 	if (how != SHUT_WR)
21641 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21642 		    SOCK_OPCTL_SHUT_RECV, 0);
21643 
21644 	return (0);
21645 }
21646 
21647 /*
21648  * SOP_LISTEN() calls into tcp_listen().
21649  */
21650 /* ARGSUSED */
21651 int
21652 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
21653 {
21654 	conn_t	*connp = (conn_t *)proto_handle;
21655 	int 	error;
21656 	squeue_t *sqp = connp->conn_sqp;
21657 
21658 	ASSERT(connp->conn_upper_handle != NULL);
21659 
21660 	/* All Solaris components should pass a cred for this operation. */
21661 	ASSERT(cr != NULL);
21662 
21663 	error = squeue_synch_enter(sqp, connp, NULL);
21664 	if (error != 0) {
21665 		/* failed to enter */
21666 		return (ENOBUFS);
21667 	}
21668 
21669 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
21670 	if (error == 0) {
21671 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21672 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
21673 	} else if (error < 0) {
21674 		if (error == -TOUTSTATE)
21675 			error = EINVAL;
21676 		else
21677 			error = proto_tlitosyserr(-error);
21678 	}
21679 	squeue_synch_exit(sqp, connp);
21680 	return (error);
21681 }
21682 
21683 static int
21684 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
21685     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
21686 {
21687 	tcp_t		*tcp = connp->conn_tcp;
21688 	int		error = 0;
21689 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21690 
21691 	/* All Solaris components should pass a cred for this operation. */
21692 	ASSERT(cr != NULL);
21693 
21694 	if (tcp->tcp_state >= TCPS_BOUND) {
21695 		if ((tcp->tcp_state == TCPS_BOUND ||
21696 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
21697 			/*
21698 			 * Handle listen() increasing backlog.
21699 			 * This is more "liberal" then what the TPI spec
21700 			 * requires but is needed to avoid a t_unbind
21701 			 * when handling listen() since the port number
21702 			 * might be "stolen" between the unbind and bind.
21703 			 */
21704 			goto do_listen;
21705 		}
21706 		if (connp->conn_debug) {
21707 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21708 			    "tcp_listen: bad state, %d", tcp->tcp_state);
21709 		}
21710 		return (-TOUTSTATE);
21711 	} else {
21712 		if (sa == NULL) {
21713 			sin6_t	addr;
21714 			sin_t *sin;
21715 			sin6_t *sin6;
21716 
21717 			ASSERT(IPCL_IS_NONSTR(connp));
21718 			/* Do an implicit bind: Request for a generic port. */
21719 			if (connp->conn_family == AF_INET) {
21720 				len = sizeof (sin_t);
21721 				sin = (sin_t *)&addr;
21722 				*sin = sin_null;
21723 				sin->sin_family = AF_INET;
21724 			} else {
21725 				ASSERT(connp->conn_family == AF_INET6);
21726 				len = sizeof (sin6_t);
21727 				sin6 = (sin6_t *)&addr;
21728 				*sin6 = sin6_null;
21729 				sin6->sin6_family = AF_INET6;
21730 			}
21731 			sa = (struct sockaddr *)&addr;
21732 		}
21733 
21734 		error = tcp_bind_check(connp, sa, len, cr,
21735 		    bind_to_req_port_only);
21736 		if (error)
21737 			return (error);
21738 		/* Fall through and do the fanout insertion */
21739 	}
21740 
21741 do_listen:
21742 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
21743 	tcp->tcp_conn_req_max = backlog;
21744 	if (tcp->tcp_conn_req_max) {
21745 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
21746 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
21747 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
21748 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
21749 		/*
21750 		 * If this is a listener, do not reset the eager list
21751 		 * and other stuffs.  Note that we don't check if the
21752 		 * existing eager list meets the new tcp_conn_req_max
21753 		 * requirement.
21754 		 */
21755 		if (tcp->tcp_state != TCPS_LISTEN) {
21756 			tcp->tcp_state = TCPS_LISTEN;
21757 			/* Initialize the chain. Don't need the eager_lock */
21758 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
21759 			tcp->tcp_eager_next_drop_q0 = tcp;
21760 			tcp->tcp_eager_prev_drop_q0 = tcp;
21761 			tcp->tcp_second_ctimer_threshold =
21762 			    tcps->tcps_ip_abort_linterval;
21763 		}
21764 	}
21765 
21766 	/*
21767 	 * We need to make sure that the conn_recv is set to a non-null
21768 	 * value before we insert the conn into the classifier table.
21769 	 * This is to avoid a race with an incoming packet which does an
21770 	 * ipcl_classify().
21771 	 * We initially set it to tcp_input_listener_unbound to try to
21772 	 * pick a good squeue for the listener when the first SYN arrives.
21773 	 * tcp_input_listener_unbound sets it to tcp_input_listener on that
21774 	 * first SYN.
21775 	 */
21776 	connp->conn_recv = tcp_input_listener_unbound;
21777 
21778 	/* Insert the listener in the classifier table */
21779 	error = ip_laddr_fanout_insert(connp);
21780 	if (error != 0) {
21781 		/* Undo the bind - release the port number */
21782 		tcp->tcp_state = TCPS_IDLE;
21783 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
21784 
21785 		connp->conn_laddr_v6 = ipv6_all_zeros;
21786 		connp->conn_saddr_v6 = ipv6_all_zeros;
21787 		connp->conn_ports = 0;
21788 
21789 		if (connp->conn_anon_port) {
21790 			zone_t		*zone;
21791 
21792 			zone = crgetzone(cr);
21793 			connp->conn_anon_port = B_FALSE;
21794 			(void) tsol_mlp_anon(zone, connp->conn_mlp_type,
21795 			    connp->conn_proto, connp->conn_lport, B_FALSE);
21796 		}
21797 		connp->conn_mlp_type = mlptSingle;
21798 
21799 		tcp_bind_hash_remove(tcp);
21800 		return (error);
21801 	} else {
21802 		/*
21803 		 * If there is a connection limit, allocate and initialize
21804 		 * the counter struct.  Note that since listen can be called
21805 		 * multiple times, the struct may have been allready allocated.
21806 		 */
21807 		if (!list_is_empty(&tcps->tcps_listener_conf) &&
21808 		    tcp->tcp_listen_cnt == NULL) {
21809 			tcp_listen_cnt_t *tlc;
21810 			uint32_t ratio;
21811 
21812 			ratio = tcp_find_listener_conf(tcps,
21813 			    ntohs(connp->conn_lport));
21814 			if (ratio != 0) {
21815 				uint32_t mem_ratio, tot_buf;
21816 
21817 				tlc = kmem_alloc(sizeof (tcp_listen_cnt_t),
21818 				    KM_SLEEP);
21819 				/*
21820 				 * Calculate the connection limit based on
21821 				 * the configured ratio and maxusers.  Maxusers
21822 				 * are calculated based on memory size,
21823 				 * ~ 1 user per MB.  Note that the conn_rcvbuf
21824 				 * and conn_sndbuf may change after a
21825 				 * connection is accepted.  So what we have
21826 				 * is only an approximation.
21827 				 */
21828 				if ((tot_buf = connp->conn_rcvbuf +
21829 				    connp->conn_sndbuf) < MB) {
21830 					mem_ratio = MB / tot_buf;
21831 					tlc->tlc_max = maxusers / ratio *
21832 					    mem_ratio;
21833 				} else {
21834 					mem_ratio = tot_buf / MB;
21835 					tlc->tlc_max = maxusers / ratio /
21836 					    mem_ratio;
21837 				}
21838 				/* At least we should allow two connections! */
21839 				if (tlc->tlc_max <= tcp_min_conn_listener)
21840 					tlc->tlc_max = tcp_min_conn_listener;
21841 				tlc->tlc_cnt = 1;
21842 				tlc->tlc_drop = 0;
21843 				tcp->tcp_listen_cnt = tlc;
21844 			}
21845 		}
21846 	}
21847 	return (error);
21848 }
21849 
21850 void
21851 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
21852 {
21853 	conn_t  *connp = (conn_t *)proto_handle;
21854 	tcp_t	*tcp = connp->conn_tcp;
21855 	mblk_t *mp;
21856 	int error;
21857 
21858 	ASSERT(connp->conn_upper_handle != NULL);
21859 
21860 	/*
21861 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
21862 	 * is currently running.
21863 	 */
21864 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21865 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
21866 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
21867 		return;
21868 	}
21869 	tcp->tcp_rsrv_mp = NULL;
21870 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21871 
21872 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
21873 	ASSERT(error == 0);
21874 
21875 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21876 	tcp->tcp_rsrv_mp = mp;
21877 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21878 
21879 	if (tcp->tcp_fused) {
21880 		tcp_fuse_backenable(tcp);
21881 	} else {
21882 		tcp->tcp_rwnd = connp->conn_rcvbuf;
21883 		/*
21884 		 * Send back a window update immediately if TCP is above
21885 		 * ESTABLISHED state and the increase of the rcv window
21886 		 * that the other side knows is at least 1 MSS after flow
21887 		 * control is lifted.
21888 		 */
21889 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
21890 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
21891 			tcp_xmit_ctl(NULL, tcp,
21892 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
21893 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21894 		}
21895 	}
21896 
21897 	squeue_synch_exit(connp->conn_sqp, connp);
21898 }
21899 
21900 /* ARGSUSED */
21901 int
21902 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
21903     int mode, int32_t *rvalp, cred_t *cr)
21904 {
21905 	conn_t  	*connp = (conn_t *)proto_handle;
21906 	int		error;
21907 
21908 	ASSERT(connp->conn_upper_handle != NULL);
21909 
21910 	/* All Solaris components should pass a cred for this operation. */
21911 	ASSERT(cr != NULL);
21912 
21913 	/*
21914 	 * If we don't have a helper stream then create one.
21915 	 * ip_create_helper_stream takes care of locking the conn_t,
21916 	 * so this check for NULL is just a performance optimization.
21917 	 */
21918 	if (connp->conn_helper_info == NULL) {
21919 		tcp_stack_t *tcps = connp->conn_tcp->tcp_tcps;
21920 
21921 		/*
21922 		 * Create a helper stream for non-STREAMS socket.
21923 		 */
21924 		error = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
21925 		if (error != 0) {
21926 			ip0dbg(("tcp_ioctl: create of IP helper stream "
21927 			    "failed %d\n", error));
21928 			return (error);
21929 		}
21930 	}
21931 
21932 	switch (cmd) {
21933 		case ND_SET:
21934 		case ND_GET:
21935 		case _SIOCSOCKFALLBACK:
21936 		case TCP_IOC_ABORT_CONN:
21937 		case TI_GETPEERNAME:
21938 		case TI_GETMYNAME:
21939 			ip1dbg(("tcp_ioctl: cmd 0x%x on non streams socket",
21940 			    cmd));
21941 			error = EINVAL;
21942 			break;
21943 		default:
21944 			/*
21945 			 * If the conn is not closing, pass on to IP using
21946 			 * helper stream. Bump the ioctlref to prevent tcp_close
21947 			 * from closing the rq/wq out from underneath the ioctl
21948 			 * if it ends up queued or aborted/interrupted.
21949 			 */
21950 			mutex_enter(&connp->conn_lock);
21951 			if (connp->conn_state_flags & (CONN_CLOSING)) {
21952 				mutex_exit(&connp->conn_lock);
21953 				error = EINVAL;
21954 				break;
21955 			}
21956 			CONN_INC_IOCTLREF_LOCKED(connp);
21957 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
21958 			    cmd, arg, mode, cr, rvalp);
21959 			CONN_DEC_IOCTLREF(connp);
21960 			break;
21961 	}
21962 	return (error);
21963 }
21964 
21965 sock_downcalls_t sock_tcp_downcalls = {
21966 	tcp_activate,
21967 	tcp_accept,
21968 	tcp_bind,
21969 	tcp_listen,
21970 	tcp_connect,
21971 	tcp_getpeername,
21972 	tcp_getsockname,
21973 	tcp_getsockopt,
21974 	tcp_setsockopt,
21975 	tcp_sendmsg,
21976 	NULL,
21977 	NULL,
21978 	NULL,
21979 	tcp_shutdown,
21980 	tcp_clr_flowctrl,
21981 	tcp_ioctl,
21982 	tcp_close,
21983 };
21984 
21985 /*
21986  * Timeout function to reset the TCP stack variable tcps_reclaim to false.
21987  */
21988 static void
21989 tcp_reclaim_timer(void *arg)
21990 {
21991 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
21992 
21993 	mutex_enter(&tcps->tcps_reclaim_lock);
21994 	tcps->tcps_reclaim = B_FALSE;
21995 	tcps->tcps_reclaim_tid = 0;
21996 	mutex_exit(&tcps->tcps_reclaim_lock);
21997 	/* Only need to print this once. */
21998 	if (tcps->tcps_netstack->netstack_stackid == GLOBAL_ZONEID)
21999 		cmn_err(CE_WARN, "TCP defensive mode off\n");
22000 }
22001 
22002 /*
22003  * Kmem reclaim call back function.  When the system is under memory
22004  * pressure, we set the TCP stack variable tcps_reclaim to true.  This
22005  * variable is reset to false after tcps_reclaim_period msecs.  During this
22006  * period, TCP will be more aggressive in aborting connections not making
22007  * progress, meaning retransmitting for some time (tcp_early_abort seconds).
22008  * TCP will also not accept new connection request for those listeners whose
22009  * q or q0 is not empty.
22010  */
22011 /* ARGSUSED */
22012 void
22013 tcp_conn_reclaim(void *arg)
22014 {
22015 	netstack_handle_t nh;
22016 	netstack_t *ns;
22017 	tcp_stack_t *tcps;
22018 	boolean_t new = B_FALSE;
22019 
22020 	netstack_next_init(&nh);
22021 	while ((ns = netstack_next(&nh)) != NULL) {
22022 		tcps = ns->netstack_tcp;
22023 		mutex_enter(&tcps->tcps_reclaim_lock);
22024 		if (!tcps->tcps_reclaim) {
22025 			tcps->tcps_reclaim = B_TRUE;
22026 			tcps->tcps_reclaim_tid = timeout(tcp_reclaim_timer,
22027 			    tcps, MSEC_TO_TICK(tcps->tcps_reclaim_period));
22028 			new = B_TRUE;
22029 		}
22030 		mutex_exit(&tcps->tcps_reclaim_lock);
22031 		netstack_rele(ns);
22032 	}
22033 	netstack_next_fini(&nh);
22034 	if (new)
22035 		cmn_err(CE_WARN, "Memory pressure: TCP defensive mode on\n");
22036 }
22037 
22038 /*
22039  * Given a tcp_stack_t and a port (in host byte order), find a listener
22040  * configuration for that port and return the ratio.
22041  */
22042 static uint32_t
22043 tcp_find_listener_conf(tcp_stack_t *tcps, in_port_t port)
22044 {
22045 	tcp_listener_t	*tl;
22046 	uint32_t ratio = 0;
22047 
22048 	mutex_enter(&tcps->tcps_listener_conf_lock);
22049 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22050 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22051 		if (tl->tl_port == port) {
22052 			ratio = tl->tl_ratio;
22053 			break;
22054 		}
22055 	}
22056 	mutex_exit(&tcps->tcps_listener_conf_lock);
22057 	return (ratio);
22058 }
22059 
22060 /*
22061  * Ndd param helper routine to return the current list of listener limit
22062  * configuration.
22063  */
22064 /* ARGSUSED */
22065 static int
22066 tcp_listener_conf_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
22067 {
22068 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22069 	tcp_listener_t	*tl;
22070 
22071 	mutex_enter(&tcps->tcps_listener_conf_lock);
22072 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22073 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22074 		(void) mi_mpprintf(mp, "%d:%d ", tl->tl_port, tl->tl_ratio);
22075 	}
22076 	mutex_exit(&tcps->tcps_listener_conf_lock);
22077 	return (0);
22078 }
22079 
22080 /*
22081  * Ndd param helper routine to add a new listener limit configuration.
22082  */
22083 /* ARGSUSED */
22084 static int
22085 tcp_listener_conf_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22086     cred_t *cr)
22087 {
22088 	tcp_listener_t	*new_tl;
22089 	tcp_listener_t	*tl;
22090 	long		lport;
22091 	long		ratio;
22092 	char		*colon;
22093 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22094 
22095 	if (ddi_strtol(value, &colon, 10, &lport) != 0 || lport <= 0 ||
22096 	    lport > USHRT_MAX || *colon != ':') {
22097 		return (EINVAL);
22098 	}
22099 	if (ddi_strtol(colon + 1, NULL, 10, &ratio) != 0 || ratio <= 0)
22100 		return (EINVAL);
22101 
22102 	mutex_enter(&tcps->tcps_listener_conf_lock);
22103 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22104 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22105 		/* There is an existing entry, so update its ratio value. */
22106 		if (tl->tl_port == lport) {
22107 			tl->tl_ratio = ratio;
22108 			mutex_exit(&tcps->tcps_listener_conf_lock);
22109 			return (0);
22110 		}
22111 	}
22112 
22113 	if ((new_tl = kmem_alloc(sizeof (tcp_listener_t), KM_NOSLEEP)) ==
22114 	    NULL) {
22115 		mutex_exit(&tcps->tcps_listener_conf_lock);
22116 		return (ENOMEM);
22117 	}
22118 
22119 	new_tl->tl_port = lport;
22120 	new_tl->tl_ratio = ratio;
22121 	list_insert_tail(&tcps->tcps_listener_conf, new_tl);
22122 	mutex_exit(&tcps->tcps_listener_conf_lock);
22123 	return (0);
22124 }
22125 
22126 /*
22127  * Ndd param helper routine to remove a listener limit configuration.
22128  */
22129 /* ARGSUSED */
22130 static int
22131 tcp_listener_conf_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22132     cred_t *cr)
22133 {
22134 	tcp_listener_t	*tl;
22135 	long		lport;
22136 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22137 
22138 	if (ddi_strtol(value, NULL, 10, &lport) != 0 || lport <= 0 ||
22139 	    lport > USHRT_MAX) {
22140 		return (EINVAL);
22141 	}
22142 	mutex_enter(&tcps->tcps_listener_conf_lock);
22143 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22144 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22145 		if (tl->tl_port == lport) {
22146 			list_remove(&tcps->tcps_listener_conf, tl);
22147 			mutex_exit(&tcps->tcps_listener_conf_lock);
22148 			kmem_free(tl, sizeof (tcp_listener_t));
22149 			return (0);
22150 		}
22151 	}
22152 	mutex_exit(&tcps->tcps_listener_conf_lock);
22153 	return (ESRCH);
22154 }
22155 
22156 /*
22157  * To remove all listener limit configuration in a tcp_stack_t.
22158  */
22159 static void
22160 tcp_listener_conf_cleanup(tcp_stack_t *tcps)
22161 {
22162 	tcp_listener_t	*tl;
22163 
22164 	mutex_enter(&tcps->tcps_listener_conf_lock);
22165 	while ((tl = list_head(&tcps->tcps_listener_conf)) != NULL) {
22166 		list_remove(&tcps->tcps_listener_conf, tl);
22167 		kmem_free(tl, sizeof (tcp_listener_t));
22168 	}
22169 	mutex_destroy(&tcps->tcps_listener_conf_lock);
22170 	list_destroy(&tcps->tcps_listener_conf);
22171 }
22172