xref: /titanic_51/usr/src/uts/common/inet/tcp/tcp.c (revision e2e5537f18c3760ce88f9038f7fe8b59cdf3b1d5)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #define	_SUN_TPI_VERSION 2
35 #include <sys/tihdr.h>
36 #include <sys/timod.h>
37 #include <sys/ddi.h>
38 #include <sys/sunddi.h>
39 #include <sys/suntpi.h>
40 #include <sys/xti_inet.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/sdt.h>
44 #include <sys/vtrace.h>
45 #include <sys/kmem.h>
46 #include <sys/ethernet.h>
47 #include <sys/cpuvar.h>
48 #include <sys/dlpi.h>
49 #include <sys/pattr.h>
50 #include <sys/policy.h>
51 #include <sys/priv.h>
52 #include <sys/zone.h>
53 #include <sys/sunldi.h>
54 
55 #include <sys/errno.h>
56 #include <sys/signal.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/sockio.h>
60 #include <sys/isa_defs.h>
61 #include <sys/md5.h>
62 #include <sys/random.h>
63 #include <sys/uio.h>
64 #include <sys/systm.h>
65 #include <netinet/in.h>
66 #include <netinet/tcp.h>
67 #include <netinet/ip6.h>
68 #include <netinet/icmp6.h>
69 #include <net/if.h>
70 #include <net/route.h>
71 #include <inet/ipsec_impl.h>
72 
73 #include <inet/common.h>
74 #include <inet/ip.h>
75 #include <inet/ip_impl.h>
76 #include <inet/ip6.h>
77 #include <inet/ip_ndp.h>
78 #include <inet/proto_set.h>
79 #include <inet/mib2.h>
80 #include <inet/nd.h>
81 #include <inet/optcom.h>
82 #include <inet/snmpcom.h>
83 #include <inet/kstatcom.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/udp_impl.h>
87 #include <net/pfkeyv2.h>
88 #include <inet/ipdrop.h>
89 
90 #include <inet/ipclassifier.h>
91 #include <inet/ip_ire.h>
92 #include <inet/ip_ftable.h>
93 #include <inet/ip_if.h>
94 #include <inet/ipp_common.h>
95 #include <inet/ip_rts.h>
96 #include <inet/ip_netinfo.h>
97 #include <sys/squeue_impl.h>
98 #include <sys/squeue.h>
99 #include <inet/kssl/ksslapi.h>
100 #include <sys/tsol/label.h>
101 #include <sys/tsol/tnet.h>
102 #include <rpc/pmap_prot.h>
103 #include <sys/callo.h>
104 
105 #include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */
106 
107 /*
108  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
109  *
110  * (Read the detailed design doc in PSARC case directory)
111  *
112  * The entire tcp state is contained in tcp_t and conn_t structure
113  * which are allocated in tandem using ipcl_conn_create() and passing
114  * IPCL_TCPCONN as a flag. We use 'conn_ref' and 'conn_lock' to protect
115  * the references on the tcp_t. The tcp_t structure is never compressed
116  * and packets always land on the correct TCP perimeter from the time
117  * eager is created till the time tcp_t dies (as such the old mentat
118  * TCP global queue is not used for detached state and no IPSEC checking
119  * is required). The global queue is still allocated to send out resets
120  * for connection which have no listeners and IP directly calls
121  * tcp_xmit_listeners_reset() which does any policy check.
122  *
123  * Protection and Synchronisation mechanism:
124  *
125  * The tcp data structure does not use any kind of lock for protecting
126  * its state but instead uses 'squeues' for mutual exclusion from various
127  * read and write side threads. To access a tcp member, the thread should
128  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
129  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
130  * can pass any tcp function having prototype of edesc_t as argument
131  * (different from traditional STREAMs model where packets come in only
132  * designated entry points). The list of functions that can be directly
133  * called via squeue are listed before the usual function prototype.
134  *
135  * Referencing:
136  *
137  * TCP is MT-Hot and we use a reference based scheme to make sure that the
138  * tcp structure doesn't disappear when its needed. When the application
139  * creates an outgoing connection or accepts an incoming connection, we
140  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
141  * The IP reference is just a symbolic reference since ip_tcpclose()
142  * looks at tcp structure after tcp_close_output() returns which could
143  * have dropped the last TCP reference. So as long as the connection is
144  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
145  * conn_t. The classifier puts its own reference when the connection is
146  * inserted in listen or connected hash. Anytime a thread needs to enter
147  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
148  * on write side or by doing a classify on read side and then puts a
149  * reference on the conn before doing squeue_enter/tryenter/fill. For
150  * read side, the classifier itself puts the reference under fanout lock
151  * to make sure that tcp can't disappear before it gets processed. The
152  * squeue will drop this reference automatically so the called function
153  * doesn't have to do a DEC_REF.
154  *
155  * Opening a new connection:
156  *
157  * The outgoing connection open is pretty simple. tcp_open() does the
158  * work in creating the conn/tcp structure and initializing it. The
159  * squeue assignment is done based on the CPU the application
160  * is running on. So for outbound connections, processing is always done
161  * on application CPU which might be different from the incoming CPU
162  * being interrupted by the NIC. An optimal way would be to figure out
163  * the NIC <-> CPU binding at listen time, and assign the outgoing
164  * connection to the squeue attached to the CPU that will be interrupted
165  * for incoming packets (we know the NIC based on the bind IP address).
166  * This might seem like a problem if more data is going out but the
167  * fact is that in most cases the transmit is ACK driven transmit where
168  * the outgoing data normally sits on TCP's xmit queue waiting to be
169  * transmitted.
170  *
171  * Accepting a connection:
172  *
173  * This is a more interesting case because of various races involved in
174  * establishing a eager in its own perimeter. Read the meta comment on
175  * top of tcp_input_listener(). But briefly, the squeue is picked by
176  * ip_fanout based on the ring or the sender (if loopback).
177  *
178  * Closing a connection:
179  *
180  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
181  * via squeue to do the close and mark the tcp as detached if the connection
182  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
183  * reference but tcp_close() drop IP's reference always. So if tcp was
184  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
185  * and 1 because it is in classifier's connected hash. This is the condition
186  * we use to determine that its OK to clean up the tcp outside of squeue
187  * when time wait expires (check the ref under fanout and conn_lock and
188  * if it is 2, remove it from fanout hash and kill it).
189  *
190  * Although close just drops the necessary references and marks the
191  * tcp_detached state, tcp_close needs to know the tcp_detached has been
192  * set (under squeue) before letting the STREAM go away (because a
193  * inbound packet might attempt to go up the STREAM while the close
194  * has happened and tcp_detached is not set). So a special lock and
195  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
196  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
197  * tcp_detached.
198  *
199  * Special provisions and fast paths:
200  *
201  * We make special provisions for sockfs by marking tcp_issocket
202  * whenever we have only sockfs on top of TCP. This allows us to skip
203  * putting the tcp in acceptor hash since a sockfs listener can never
204  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
205  * since eager has already been allocated and the accept now happens
206  * on acceptor STREAM. There is a big blob of comment on top of
207  * tcp_input_listener explaining the new accept. When socket is POP'd,
208  * sockfs sends us an ioctl to mark the fact and we go back to old
209  * behaviour. Once tcp_issocket is unset, its never set for the
210  * life of that connection.
211  *
212  * IPsec notes :
213  *
214  * Since a packet is always executed on the correct TCP perimeter
215  * all IPsec processing is defered to IP including checking new
216  * connections and setting IPSEC policies for new connection. The
217  * only exception is tcp_xmit_listeners_reset() which is called
218  * directly from IP and needs to policy check to see if TH_RST
219  * can be sent out.
220  */
221 
222 /*
223  * Values for squeue switch:
224  * 1: SQ_NODRAIN
225  * 2: SQ_PROCESS
226  * 3: SQ_FILL
227  */
228 int tcp_squeue_wput = 2;	/* /etc/systems */
229 int tcp_squeue_flag;
230 
231 /*
232  * This controls how tiny a write must be before we try to copy it
233  * into the mblk on the tail of the transmit queue.  Not much
234  * speedup is observed for values larger than sixteen.  Zero will
235  * disable the optimisation.
236  */
237 int tcp_tx_pull_len = 16;
238 
239 /*
240  * TCP Statistics.
241  *
242  * How TCP statistics work.
243  *
244  * There are two types of statistics invoked by two macros.
245  *
246  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
247  * supposed to be used in non MT-hot paths of the code.
248  *
249  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
250  * supposed to be used for DEBUG purposes and may be used on a hot path.
251  *
252  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
253  * (use "kstat tcp" to get them).
254  *
255  * There is also additional debugging facility that marks tcp_clean_death()
256  * instances and saves them in tcp_t structure. It is triggered by
257  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
258  * tcp_clean_death() calls that counts the number of times each tag was hit. It
259  * is triggered by TCP_CLD_COUNTERS define.
260  *
261  * How to add new counters.
262  *
263  * 1) Add a field in the tcp_stat structure describing your counter.
264  * 2) Add a line in the template in tcp_kstat2_init() with the name
265  *    of the counter.
266  *
267  *    IMPORTANT!! - make sure that both are in sync !!
268  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
269  *
270  * Please avoid using private counters which are not kstat-exported.
271  *
272  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
273  * in tcp_t structure.
274  *
275  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
276  */
277 
278 #ifndef TCP_DEBUG_COUNTER
279 #ifdef DEBUG
280 #define	TCP_DEBUG_COUNTER 1
281 #else
282 #define	TCP_DEBUG_COUNTER 0
283 #endif
284 #endif
285 
286 #define	TCP_CLD_COUNTERS 0
287 
288 #define	TCP_TAG_CLEAN_DEATH 1
289 #define	TCP_MAX_CLEAN_DEATH_TAG 32
290 
291 #ifdef lint
292 static int _lint_dummy_;
293 #endif
294 
295 #if TCP_CLD_COUNTERS
296 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
297 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
298 #elif defined(lint)
299 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
300 #else
301 #define	TCP_CLD_STAT(x)
302 #endif
303 
304 #if TCP_DEBUG_COUNTER
305 #define	TCP_DBGSTAT(tcps, x)	\
306 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
307 #define	TCP_G_DBGSTAT(x)	\
308 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
309 #elif defined(lint)
310 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
311 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
312 #else
313 #define	TCP_DBGSTAT(tcps, x)
314 #define	TCP_G_DBGSTAT(x)
315 #endif
316 
317 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
318 
319 tcp_g_stat_t	tcp_g_statistics;
320 kstat_t		*tcp_g_kstat;
321 
322 /* Macros for timestamp comparisons */
323 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
324 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
325 
326 /*
327  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
328  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
329  * by adding three components: a time component which grows by 1 every 4096
330  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
331  * a per-connection component which grows by 125000 for every new connection;
332  * and an "extra" component that grows by a random amount centered
333  * approximately on 64000.  This causes the ISS generator to cycle every
334  * 4.89 hours if no TCP connections are made, and faster if connections are
335  * made.
336  *
337  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
338  * components: a time component which grows by 250000 every second; and
339  * a per-connection component which grows by 125000 for every new connections.
340  *
341  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
342  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
343  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
344  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
345  * password.
346  */
347 #define	ISS_INCR	250000
348 #define	ISS_NSEC_SHT	12
349 
350 static sin_t	sin_null;	/* Zero address for quick clears */
351 static sin6_t	sin6_null;	/* Zero address for quick clears */
352 
353 /*
354  * This implementation follows the 4.3BSD interpretation of the urgent
355  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
356  * incompatible changes in protocols like telnet and rlogin.
357  */
358 #define	TCP_OLD_URP_INTERPRETATION	1
359 
360 /*
361  * Since tcp_listener is not cleared atomically with tcp_detached
362  * being cleared we need this extra bit to tell a detached connection
363  * apart from one that is in the process of being accepted.
364  */
365 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
366 	(TCP_IS_DETACHED(tcp) &&	\
367 	    (!(tcp)->tcp_hard_binding))
368 
369 /*
370  * TCP reassembly macros.  We hide starting and ending sequence numbers in
371  * b_next and b_prev of messages on the reassembly queue.  The messages are
372  * chained using b_cont.  These macros are used in tcp_reass() so we don't
373  * have to see the ugly casts and assignments.
374  */
375 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
376 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
377 					(mblk_t *)(uintptr_t)(u))
378 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
379 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
380 					(mblk_t *)(uintptr_t)(u))
381 
382 /*
383  * Implementation of TCP Timers.
384  * =============================
385  *
386  * INTERFACE:
387  *
388  * There are two basic functions dealing with tcp timers:
389  *
390  *	timeout_id_t	tcp_timeout(connp, func, time)
391  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
392  *	TCP_TIMER_RESTART(tcp, intvl)
393  *
394  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
395  * after 'time' ticks passed. The function called by timeout() must adhere to
396  * the same restrictions as a driver soft interrupt handler - it must not sleep
397  * or call other functions that might sleep. The value returned is the opaque
398  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
399  * cancel the request. The call to tcp_timeout() may fail in which case it
400  * returns zero. This is different from the timeout(9F) function which never
401  * fails.
402  *
403  * The call-back function 'func' always receives 'connp' as its single
404  * argument. It is always executed in the squeue corresponding to the tcp
405  * structure. The tcp structure is guaranteed to be present at the time the
406  * call-back is called.
407  *
408  * NOTE: The call-back function 'func' is never called if tcp is in
409  * 	the TCPS_CLOSED state.
410  *
411  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
412  * request. locks acquired by the call-back routine should not be held across
413  * the call to tcp_timeout_cancel() or a deadlock may result.
414  *
415  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
416  * Otherwise, it returns an integer value greater than or equal to 0. In
417  * particular, if the call-back function is already placed on the squeue, it can
418  * not be canceled.
419  *
420  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
421  * 	within squeue context corresponding to the tcp instance. Since the
422  *	call-back is also called via the same squeue, there are no race
423  *	conditions described in untimeout(9F) manual page since all calls are
424  *	strictly serialized.
425  *
426  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
427  *	stored in tcp_timer_tid and starts a new one using
428  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
429  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
430  *	field.
431  *
432  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
433  *	call-back may still be called, so it is possible tcp_timer() will be
434  *	called several times. This should not be a problem since tcp_timer()
435  *	should always check the tcp instance state.
436  *
437  *
438  * IMPLEMENTATION:
439  *
440  * TCP timers are implemented using three-stage process. The call to
441  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
442  * when the timer expires. The tcp_timer_callback() arranges the call of the
443  * tcp_timer_handler() function via squeue corresponding to the tcp
444  * instance. The tcp_timer_handler() calls actual requested timeout call-back
445  * and passes tcp instance as an argument to it. Information is passed between
446  * stages using the tcp_timer_t structure which contains the connp pointer, the
447  * tcp call-back to call and the timeout id returned by the timeout(9F).
448  *
449  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
450  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
451  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
452  * returns the pointer to this mblk.
453  *
454  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
455  * looks like a normal mblk without actual dblk attached to it.
456  *
457  * To optimize performance each tcp instance holds a small cache of timer
458  * mblocks. In the current implementation it caches up to two timer mblocks per
459  * tcp instance. The cache is preserved over tcp frees and is only freed when
460  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
461  * timer processing happens on a corresponding squeue, the cache manipulation
462  * does not require any locks. Experiments show that majority of timer mblocks
463  * allocations are satisfied from the tcp cache and do not involve kmem calls.
464  *
465  * The tcp_timeout() places a refhold on the connp instance which guarantees
466  * that it will be present at the time the call-back function fires. The
467  * tcp_timer_handler() drops the reference after calling the call-back, so the
468  * call-back function does not need to manipulate the references explicitly.
469  */
470 
471 typedef struct tcp_timer_s {
472 	conn_t	*connp;
473 	void 	(*tcpt_proc)(void *);
474 	callout_id_t   tcpt_tid;
475 } tcp_timer_t;
476 
477 static kmem_cache_t *tcp_timercache;
478 kmem_cache_t	*tcp_sack_info_cache;
479 
480 /*
481  * For scalability, we must not run a timer for every TCP connection
482  * in TIME_WAIT state.  To see why, consider (for time wait interval of
483  * 4 minutes):
484  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
485  *
486  * This list is ordered by time, so you need only delete from the head
487  * until you get to entries which aren't old enough to delete yet.
488  * The list consists of only the detached TIME_WAIT connections.
489  *
490  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
491  * becomes detached TIME_WAIT (either by changing the state and already
492  * being detached or the other way around). This means that the TIME_WAIT
493  * state can be extended (up to doubled) if the connection doesn't become
494  * detached for a long time.
495  *
496  * The list manipulations (including tcp_time_wait_next/prev)
497  * are protected by the tcp_time_wait_lock. The content of the
498  * detached TIME_WAIT connections is protected by the normal perimeters.
499  *
500  * This list is per squeue and squeues are shared across the tcp_stack_t's.
501  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
502  * and conn_netstack.
503  * The tcp_t's that are added to tcp_free_list are disassociated and
504  * have NULL tcp_tcps and conn_netstack pointers.
505  */
506 typedef struct tcp_squeue_priv_s {
507 	kmutex_t	tcp_time_wait_lock;
508 	callout_id_t	tcp_time_wait_tid;
509 	tcp_t		*tcp_time_wait_head;
510 	tcp_t		*tcp_time_wait_tail;
511 	tcp_t		*tcp_free_list;
512 	uint_t		tcp_free_list_cnt;
513 } tcp_squeue_priv_t;
514 
515 /*
516  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
517  * Running it every 5 seconds seems to give the best results.
518  */
519 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
520 
521 /*
522  * To prevent memory hog, limit the number of entries in tcp_free_list
523  * to 1% of available memory / number of cpus
524  */
525 uint_t tcp_free_list_max_cnt = 0;
526 
527 #define	TCP_XMIT_LOWATER	4096
528 #define	TCP_XMIT_HIWATER	49152
529 #define	TCP_RECV_LOWATER	2048
530 #define	TCP_RECV_HIWATER	128000
531 
532 /*
533  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
534  */
535 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
536 
537 #define	TIDUSZ	4096	/* transport interface data unit size */
538 
539 /*
540  * Bind hash list size and has function.  It has to be a power of 2 for
541  * hashing.
542  */
543 #define	TCP_BIND_FANOUT_SIZE	512
544 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
545 
546 /*
547  * Size of acceptor hash list.  It has to be a power of 2 for hashing.
548  */
549 #define	TCP_ACCEPTOR_FANOUT_SIZE		256
550 
551 #ifdef	_ILP32
552 #define	TCP_ACCEPTOR_HASH(accid)					\
553 		(((uint_t)(accid) >> 8) & (TCP_ACCEPTOR_FANOUT_SIZE - 1))
554 #else
555 #define	TCP_ACCEPTOR_HASH(accid)					\
556 		((uint_t)(accid) & (TCP_ACCEPTOR_FANOUT_SIZE - 1))
557 #endif	/* _ILP32 */
558 
559 #define	IP_ADDR_CACHE_SIZE	2048
560 #define	IP_ADDR_CACHE_HASH(faddr)					\
561 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
562 
563 /*
564  * If there is a limit set on the number of connections allowed per each
565  * listener, the following struct is used to store that counter.  This needs
566  * to be separated from the listener since the listener can go away before
567  * all the connections are gone.  When the struct is allocated, tlc_cnt is set
568  * to 1.  When the listener goes away, tlc_cnt is decremented  by one.  And
569  * the last connection (or the listener) which decrements tlc_cnt to zero
570  * frees the struct.
571  *
572  * tlc_max is the threshold value tcps_conn_listen_port.  It is set when the
573  * tcp_listen_cnt_t is allocated.
574  *
575  * tlc_report_time stores the time when cmn_err() is called to report that the
576  * max has been exceeeded.  Report is done at most once every
577  * TCP_TLC_REPORT_INTERVAL mins for a listener.
578  *
579  * tlc_drop stores the number of connection attempt dropped because the
580  * limit has reached.
581  */
582 typedef struct tcp_listen_cnt_s {
583 	uint32_t	tlc_max;
584 	uint32_t	tlc_cnt;
585 	int64_t		tlc_report_time;
586 	uint32_t	tlc_drop;
587 } tcp_listen_cnt_t;
588 
589 #define	TCP_TLC_REPORT_INTERVAL	(1 * MINUTES)
590 
591 #define	TCP_DECR_LISTEN_CNT(tcp)					\
592 {									\
593 	ASSERT((tcp)->tcp_listen_cnt->tlc_cnt > 0);			\
594 	if (atomic_add_32_nv(&(tcp)->tcp_listen_cnt->tlc_cnt, -1) == 0) \
595 		kmem_free((tcp)->tcp_listen_cnt, sizeof (tcp_listen_cnt_t)); \
596 	(tcp)->tcp_listen_cnt = NULL;					\
597 }
598 
599 /* Minimum number of connections per listener. */
600 uint32_t tcp_min_conn_listener = 2;
601 
602 /*
603  * Linked list struct to store listener connection limit configuration per
604  * IP stack.
605  */
606 typedef struct tcp_listener_s {
607 	in_port_t	tl_port;
608 	uint32_t	tl_ratio;
609 	list_node_t	tl_link;
610 } tcp_listener_t;
611 
612 /*
613  * The shift factor applied to tcp_mss to decide if the peer sends us a
614  * valid initial receive window.  By default, if the peer receive window
615  * is smaller than 1 MSS (shift factor is 0), it is considered as invalid.
616  */
617 uint32_t tcp_init_wnd_shft = 0;
618 
619 /*
620  * When the system is under memory pressure, stack variable tcps_reclaim is
621  * true, we shorten the connection timeout abort interval to tcp_early_abort
622  * seconds.
623  */
624 uint32_t tcp_early_abort = 30;
625 
626 /*
627  * TCP options struct returned from tcp_parse_options.
628  */
629 typedef struct tcp_opt_s {
630 	uint32_t	tcp_opt_mss;
631 	uint32_t	tcp_opt_wscale;
632 	uint32_t	tcp_opt_ts_val;
633 	uint32_t	tcp_opt_ts_ecr;
634 	tcp_t		*tcp;
635 } tcp_opt_t;
636 
637 /*
638  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
639  */
640 
641 #ifdef _BIG_ENDIAN
642 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
643 	(TCPOPT_TSTAMP << 8) | 10)
644 #else
645 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
646 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
647 #endif
648 
649 /*
650  * Flags returned from tcp_parse_options.
651  */
652 #define	TCP_OPT_MSS_PRESENT	1
653 #define	TCP_OPT_WSCALE_PRESENT	2
654 #define	TCP_OPT_TSTAMP_PRESENT	4
655 #define	TCP_OPT_SACK_OK_PRESENT	8
656 #define	TCP_OPT_SACK_PRESENT	16
657 
658 /* TCP option length */
659 #define	TCPOPT_NOP_LEN		1
660 #define	TCPOPT_MAXSEG_LEN	4
661 #define	TCPOPT_WS_LEN		3
662 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
663 #define	TCPOPT_TSTAMP_LEN	10
664 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
665 #define	TCPOPT_SACK_OK_LEN	2
666 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
667 #define	TCPOPT_REAL_SACK_LEN	4
668 #define	TCPOPT_MAX_SACK_LEN	36
669 #define	TCPOPT_HEADER_LEN	2
670 
671 /* TCP cwnd burst factor. */
672 #define	TCP_CWND_INFINITE	65535
673 #define	TCP_CWND_SS		3
674 #define	TCP_CWND_NORMAL		5
675 
676 /* Maximum TCP initial cwin (start/restart). */
677 #define	TCP_MAX_INIT_CWND	8
678 
679 /*
680  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
681  * either tcp_slow_start_initial or tcp_slow_start_after idle
682  * depending on the caller.  If the upper layer has not used the
683  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
684  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
685  * If the upper layer has changed set the tcp_init_cwnd, just use
686  * it to calculate the tcp_cwnd.
687  */
688 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
689 {									\
690 	if ((tcp)->tcp_init_cwnd == 0) {				\
691 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
692 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
693 	} else {							\
694 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
695 	}								\
696 	tcp->tcp_cwnd_cnt = 0;						\
697 }
698 
699 /* TCP Timer control structure */
700 typedef struct tcpt_s {
701 	pfv_t	tcpt_pfv;	/* The routine we are to call */
702 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
703 } tcpt_t;
704 
705 /*
706  * Functions called directly via squeue having a prototype of edesc_t.
707  */
708 void		tcp_input_listener(void *arg, mblk_t *mp, void *arg2,
709     ip_recv_attr_t *ira);
710 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2,
711     ip_recv_attr_t *dummy);
712 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2,
713     ip_recv_attr_t *dummy);
714 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2,
715     ip_recv_attr_t *dummy);
716 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2,
717     ip_recv_attr_t *dummy);
718 void		tcp_input_data(void *arg, mblk_t *mp, void *arg2,
719     ip_recv_attr_t *ira);
720 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2,
721     ip_recv_attr_t *dummy);
722 void		tcp_output(void *arg, mblk_t *mp, void *arg2,
723     ip_recv_attr_t *dummy);
724 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2,
725     ip_recv_attr_t *dummy);
726 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2,
727     ip_recv_attr_t *dummy);
728 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2,
729     ip_recv_attr_t *dummy);
730 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2,
731     ip_recv_attr_t *dummy);
732 
733 
734 /* Prototype for TCP functions */
735 static void	tcp_random_init(void);
736 int		tcp_random(void);
737 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
738 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
739 		    tcp_t *eager);
740 static int	tcp_set_destination(tcp_t *tcp);
741 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
742     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
743     boolean_t user_specified);
744 static void	tcp_closei_local(tcp_t *tcp);
745 static void	tcp_close_detached(tcp_t *tcp);
746 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr,
747 		    mblk_t *idmp, mblk_t **defermp, ip_recv_attr_t *ira);
748 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
749 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
750 		    in_port_t dstport, uint_t srcid);
751 static int	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
752 		    in_port_t dstport, uint32_t flowinfo,
753 		    uint_t srcid, uint32_t scope_id);
754 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
755 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
756 static char	*tcp_display(tcp_t *tcp, char *, char);
757 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
758 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
759 static void	tcp_eager_unlink(tcp_t *tcp);
760 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
761 		    int unixerr);
762 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
763 		    int tlierr, int unixerr);
764 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
765 		    cred_t *cr);
766 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
767 		    char *value, caddr_t cp, cred_t *cr);
768 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
769 		    char *value, caddr_t cp, cred_t *cr);
770 static int	tcp_tpistate(tcp_t *tcp);
771 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
772     int caller_holds_lock);
773 static void	tcp_bind_hash_remove(tcp_t *tcp);
774 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
775 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
776 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
777 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
778 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
779 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
780 static void	tcp_init_values(tcp_t *tcp);
781 static void	tcp_ip_notify(tcp_t *tcp);
782 static void	tcp_iss_init(tcp_t *tcp);
783 static void	tcp_keepalive_killer(void *arg);
784 static int	tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt);
785 static void	tcp_mss_set(tcp_t *tcp, uint32_t size);
786 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
787 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
788 static boolean_t tcp_allow_connopt_set(int level, int name);
789 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
790 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
791 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
792     tcp_stack_t *);
793 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
794 		    caddr_t cp, cred_t *cr);
795 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
796 		    caddr_t cp, cred_t *cr);
797 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
798 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
799 		    caddr_t cp, cred_t *cr);
800 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
801 static void	tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt);
802 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
803 static void	tcp_reass_timer(void *arg);
804 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
805 static void	tcp_reinit(tcp_t *tcp);
806 static void	tcp_reinit_values(tcp_t *tcp);
807 
808 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
809 static uint_t	tcp_rcv_drain(tcp_t *tcp);
810 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
811 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
812 static void	tcp_ss_rexmit(tcp_t *tcp);
813 static mblk_t	*tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
814     ip_recv_attr_t *);
815 static void	tcp_process_options(tcp_t *, tcpha_t *);
816 static void	tcp_rsrv(queue_t *q);
817 static int	tcp_snmp_state(tcp_t *tcp);
818 static void	tcp_timer(void *arg);
819 static void	tcp_timer_callback(void *);
820 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
821     boolean_t random);
822 static in_port_t tcp_get_next_priv_port(const tcp_t *);
823 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
824 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
825 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
826 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
827 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
828 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
829 static int	tcp_send(tcp_t *tcp, const int mss,
830 		    const int total_hdr_len, const int tcp_hdr_len,
831 		    const int num_sack_blk, int *usable, uint_t *snxt,
832 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time);
833 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
834 		    int num_sack_blk);
835 static void	tcp_wsrv(queue_t *q);
836 static int	tcp_xmit_end(tcp_t *tcp);
837 static void	tcp_ack_timer(void *arg);
838 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
839 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
840 		    uint32_t seq, uint32_t ack, int ctl, ip_recv_attr_t *,
841 		    ip_stack_t *, conn_t *);
842 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
843 		    uint32_t ack, int ctl);
844 static void	tcp_set_rto(tcp_t *, time_t);
845 static void	tcp_icmp_input(void *, mblk_t *, void *, ip_recv_attr_t *);
846 static void	tcp_icmp_error_ipv6(tcp_t *, mblk_t *, ip_recv_attr_t *);
847 static boolean_t tcp_verifyicmp(conn_t *, void *, icmph_t *, icmp6_t *,
848     ip_recv_attr_t *);
849 static int	tcp_build_hdrs(tcp_t *);
850 static void	tcp_time_wait_append(tcp_t *tcp);
851 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
852     uint32_t seg_seq, uint32_t seg_ack, int seg_len, tcpha_t *tcpha,
853     ip_recv_attr_t *ira);
854 boolean_t	tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp);
855 static boolean_t tcp_zcopy_check(tcp_t *);
856 static void	tcp_zcopy_notify(tcp_t *);
857 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, boolean_t);
858 static void	tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa);
859 static void	tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only);
860 static void	tcp_update_zcopy(tcp_t *tcp);
861 static void	tcp_notify(void *, ip_xmit_attr_t *, ixa_notify_type_t,
862     ixa_notify_arg_t);
863 static void	tcp_rexmit_after_error(tcp_t *tcp);
864 static void	tcp_send_data(tcp_t *, mblk_t *);
865 extern mblk_t	*tcp_timermp_alloc(int);
866 extern void	tcp_timermp_free(tcp_t *);
867 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
868 static void	tcp_stop_lingering(tcp_t *tcp);
869 static void	tcp_close_linger_timeout(void *arg);
870 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
871 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
872 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
873 static void	tcp_g_kstat_fini(kstat_t *);
874 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
875 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
876 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
877 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
878 static int	tcp_kstat_update(kstat_t *kp, int rw);
879 static mblk_t	*tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
880     ip_recv_attr_t *ira);
881 static mblk_t	*tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
882     ip_recv_attr_t *ira);
883 static int	tcp_squeue_switch(int);
884 
885 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
886 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
887 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
888 static int	tcp_tpi_close(queue_t *, int);
889 static int	tcp_tpi_close_accept(queue_t *);
890 
891 static void	tcp_squeue_add(squeue_t *);
892 static void	tcp_setcred_data(mblk_t *, ip_recv_attr_t *);
893 
894 extern void	tcp_kssl_input(tcp_t *, mblk_t *, cred_t *);
895 
896 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy);
897 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
898     ip_recv_attr_t *dummy);
899 
900 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
901 	    sock_upper_handle_t, cred_t *);
902 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
903 static int tcp_do_listen(conn_t *, struct sockaddr *, socklen_t, int, cred_t *,
904     boolean_t);
905 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
906     cred_t *, pid_t);
907 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
908     boolean_t);
909 static int tcp_do_unbind(conn_t *);
910 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
911     boolean_t);
912 
913 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_t *);
914 
915 static uint32_t tcp_find_listener_conf(tcp_stack_t *, in_port_t);
916 static int tcp_listener_conf_get(queue_t *, mblk_t *, caddr_t, cred_t *);
917 static int tcp_listener_conf_add(queue_t *, mblk_t *, char *, caddr_t,
918     cred_t *);
919 static int tcp_listener_conf_del(queue_t *, mblk_t *, char *, caddr_t,
920     cred_t *);
921 static void tcp_listener_conf_cleanup(tcp_stack_t *);
922 
923 /*
924  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
925  *
926  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
927  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
928  * (defined in tcp.h) needs to be filled in and passed into the kernel
929  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
930  * structure contains the four-tuple of a TCP connection and a range of TCP
931  * states (specified by ac_start and ac_end). The use of wildcard addresses
932  * and ports is allowed. Connections with a matching four tuple and a state
933  * within the specified range will be aborted. The valid states for the
934  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
935  * inclusive.
936  *
937  * An application which has its connection aborted by this ioctl will receive
938  * an error that is dependent on the connection state at the time of the abort.
939  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
940  * though a RST packet has been received.  If the connection state is equal to
941  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
942  * and all resources associated with the connection will be freed.
943  */
944 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
945 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
946 static void	tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
947     ip_recv_attr_t *dummy);
948 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
949 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
950 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
951     boolean_t, tcp_stack_t *);
952 
953 static struct module_info tcp_rinfo =  {
954 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
955 };
956 
957 static struct module_info tcp_winfo =  {
958 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
959 };
960 
961 /*
962  * Entry points for TCP as a device. The normal case which supports
963  * the TCP functionality.
964  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
965  */
966 struct qinit tcp_rinitv4 = {
967 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
968 };
969 
970 struct qinit tcp_rinitv6 = {
971 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
972 };
973 
974 struct qinit tcp_winit = {
975 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
976 };
977 
978 /* Initial entry point for TCP in socket mode. */
979 struct qinit tcp_sock_winit = {
980 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
981 };
982 
983 /* TCP entry point during fallback */
984 struct qinit tcp_fallback_sock_winit = {
985 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
986 };
987 
988 /*
989  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
990  * an accept. Avoid allocating data structures since eager has already
991  * been created.
992  */
993 struct qinit tcp_acceptor_rinit = {
994 	NULL, (pfi_t)tcp_rsrv, NULL, tcp_tpi_close_accept, NULL, &tcp_winfo
995 };
996 
997 struct qinit tcp_acceptor_winit = {
998 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
999 };
1000 
1001 /* For AF_INET aka /dev/tcp */
1002 struct streamtab tcpinfov4 = {
1003 	&tcp_rinitv4, &tcp_winit
1004 };
1005 
1006 /* For AF_INET6 aka /dev/tcp6 */
1007 struct streamtab tcpinfov6 = {
1008 	&tcp_rinitv6, &tcp_winit
1009 };
1010 
1011 sock_downcalls_t sock_tcp_downcalls;
1012 
1013 /* Setable only in /etc/system. Move to ndd? */
1014 boolean_t tcp_icmp_source_quench = B_FALSE;
1015 
1016 /*
1017  * Following assumes TPI alignment requirements stay along 32 bit
1018  * boundaries
1019  */
1020 #define	ROUNDUP32(x) \
1021 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1022 
1023 /* Template for response to info request. */
1024 static struct T_info_ack tcp_g_t_info_ack = {
1025 	T_INFO_ACK,		/* PRIM_type */
1026 	0,			/* TSDU_size */
1027 	T_INFINITE,		/* ETSDU_size */
1028 	T_INVALID,		/* CDATA_size */
1029 	T_INVALID,		/* DDATA_size */
1030 	sizeof (sin_t),		/* ADDR_size */
1031 	0,			/* OPT_size - not initialized here */
1032 	TIDUSZ,			/* TIDU_size */
1033 	T_COTS_ORD,		/* SERV_type */
1034 	TCPS_IDLE,		/* CURRENT_state */
1035 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1036 };
1037 
1038 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1039 	T_INFO_ACK,		/* PRIM_type */
1040 	0,			/* TSDU_size */
1041 	T_INFINITE,		/* ETSDU_size */
1042 	T_INVALID,		/* CDATA_size */
1043 	T_INVALID,		/* DDATA_size */
1044 	sizeof (sin6_t),	/* ADDR_size */
1045 	0,			/* OPT_size - not initialized here */
1046 	TIDUSZ,		/* TIDU_size */
1047 	T_COTS_ORD,		/* SERV_type */
1048 	TCPS_IDLE,		/* CURRENT_state */
1049 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1050 };
1051 
1052 #define	MS	1L
1053 #define	SECONDS	(1000 * MS)
1054 #define	MINUTES	(60 * SECONDS)
1055 #define	HOURS	(60 * MINUTES)
1056 #define	DAYS	(24 * HOURS)
1057 
1058 #define	PARAM_MAX (~(uint32_t)0)
1059 
1060 /* Max size IP datagram is 64k - 1 */
1061 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcpha_t)))
1062 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcpha_t)))
1063 /* Max of the above */
1064 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1065 
1066 /* Largest TCP port number */
1067 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1068 
1069 /*
1070  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1071  * layer header.  It has to be a multiple of 4.
1072  */
1073 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1074 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1075 
1076 #define	MB	(1024 * 1024)
1077 
1078 /*
1079  * All of these are alterable, within the min/max values given, at run time.
1080  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1081  * per the TCP spec.
1082  */
1083 /* BEGIN CSTYLED */
1084 static tcpparam_t	lcl_tcp_param_arr[] = {
1085  /*min		max		value		name */
1086  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1087  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1088  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1089  { 1,		1024,		1,		"tcp_conn_req_min" },
1090  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1091  { 128,		(1<<30),	1*MB,		"tcp_cwnd_max" },
1092  { 0,		10,		0,		"tcp_debug" },
1093  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1094  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1095  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1096  { 500*MS,	PARAM_MAX,	5*MINUTES,	"tcp_ip_abort_interval"},
1097  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1098  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1099  { 1,		255,		64,		"tcp_ipv4_ttl"},
1100  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1101  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1102  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1103  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1104  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1105  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1106  { 1*MS,	20*SECONDS,	1*SECONDS,	"tcp_rexmit_interval_initial"},
1107  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1108  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1109  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1110  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1111  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1112  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1113  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1114  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1115  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1116  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1117  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1118  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1119  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1120  { 8192,	(1<<30),	1*MB,		"tcp_max_buf"},
1121 /*
1122  * Question:  What default value should I set for tcp_strong_iss?
1123  */
1124  { 0,		2,		1,		"tcp_strong_iss"},
1125  { 0,		65536,		20,		"tcp_rtt_updates"},
1126  { 0,		1,		1,		"tcp_wscale_always"},
1127  { 0,		1,		0,		"tcp_tstamp_always"},
1128  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1129  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1130  { 0,		16,		2,		"tcp_deferred_acks_max"},
1131  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1132  { 1,		4,		4,		"tcp_slow_start_initial"},
1133  { 0,		2,		2,		"tcp_sack_permitted"},
1134  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1135  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1136  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1137  { 0,		1,		0,		"tcp_rev_src_routes"},
1138  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1139  { 0,		16,		8,		"tcp_local_dacks_max"},
1140  { 0,		2,		1,		"tcp_ecn_permitted"},
1141  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1142  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1143  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1144  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1145  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1146  { 0,		1,		0,		"tcp_dev_flow_ctl"},
1147  { 0,		PARAM_MAX,	100*SECONDS,	"tcp_reass_timeout"}
1148 };
1149 /* END CSTYLED */
1150 
1151 /* Round up the value to the nearest mss. */
1152 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1153 
1154 /*
1155  * Set ECN capable transport (ECT) code point in IP header.
1156  *
1157  * Note that there are 2 ECT code points '01' and '10', which are called
1158  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1159  * point ECT(0) for TCP as described in RFC 2481.
1160  */
1161 #define	SET_ECT(tcp, iph) \
1162 	if ((tcp)->tcp_connp->conn_ipversion == IPV4_VERSION) { \
1163 		/* We need to clear the code point first. */ \
1164 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1165 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1166 	} else { \
1167 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1168 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1169 	}
1170 
1171 /*
1172  * The format argument to pass to tcp_display().
1173  * DISP_PORT_ONLY means that the returned string has only port info.
1174  * DISP_ADDR_AND_PORT means that the returned string also contains the
1175  * remote and local IP address.
1176  */
1177 #define	DISP_PORT_ONLY		1
1178 #define	DISP_ADDR_AND_PORT	2
1179 
1180 #define	IS_VMLOANED_MBLK(mp) \
1181 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1182 
1183 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1184 
1185 /*
1186  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1187  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1188  * determined dynamically during tcp_set_destination(), which is the default.
1189  */
1190 boolean_t tcp_static_maxpsz = B_FALSE;
1191 
1192 /* Setable in /etc/system */
1193 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1194 uint32_t tcp_random_anon_port = 1;
1195 
1196 /*
1197  * To reach to an eager in Q0 which can be dropped due to an incoming
1198  * new SYN request when Q0 is full, a new doubly linked list is
1199  * introduced. This list allows to select an eager from Q0 in O(1) time.
1200  * This is needed to avoid spending too much time walking through the
1201  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1202  * this new list has to be a member of Q0.
1203  * This list is headed by listener's tcp_t. When the list is empty,
1204  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1205  * of listener's tcp_t point to listener's tcp_t itself.
1206  *
1207  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1208  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1209  * These macros do not affect the eager's membership to Q0.
1210  */
1211 
1212 
1213 #define	MAKE_DROPPABLE(listener, eager)					\
1214 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1215 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1216 		    = (eager);						\
1217 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1218 		(eager)->tcp_eager_next_drop_q0 =			\
1219 		    (listener)->tcp_eager_next_drop_q0;			\
1220 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1221 	}
1222 
1223 #define	MAKE_UNDROPPABLE(eager)						\
1224 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1225 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1226 		    = (eager)->tcp_eager_prev_drop_q0;			\
1227 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1228 		    = (eager)->tcp_eager_next_drop_q0;			\
1229 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1230 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1231 	}
1232 
1233 /*
1234  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1235  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1236  * data, TCP will not respond with an ACK.  RFC 793 requires that
1237  * TCP responds with an ACK for such a bogus ACK.  By not following
1238  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1239  * an attacker successfully spoofs an acceptable segment to our
1240  * peer; or when our peer is "confused."
1241  */
1242 uint32_t tcp_drop_ack_unsent_cnt = 10;
1243 
1244 /*
1245  * Hook functions to enable cluster networking
1246  * On non-clustered systems these vectors must always be NULL.
1247  */
1248 
1249 void (*cl_inet_listen)(netstackid_t stack_id, uint8_t protocol,
1250 			    sa_family_t addr_family, uint8_t *laddrp,
1251 			    in_port_t lport, void *args) = NULL;
1252 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1253 			    sa_family_t addr_family, uint8_t *laddrp,
1254 			    in_port_t lport, void *args) = NULL;
1255 
1256 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1257 			    boolean_t is_outgoing,
1258 			    sa_family_t addr_family,
1259 			    uint8_t *laddrp, in_port_t lport,
1260 			    uint8_t *faddrp, in_port_t fport,
1261 			    void *args) = NULL;
1262 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1263 			    sa_family_t addr_family, uint8_t *laddrp,
1264 			    in_port_t lport, uint8_t *faddrp,
1265 			    in_port_t fport, void *args) = NULL;
1266 
1267 
1268 /*
1269  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1270  */
1271 #define	CL_INET_CONNECT(connp, is_outgoing, err) {		\
1272 	(err) = 0;						\
1273 	if (cl_inet_connect2 != NULL) {				\
1274 		/*						\
1275 		 * Running in cluster mode - register active connection	\
1276 		 * information						\
1277 		 */							\
1278 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1279 			if ((connp)->conn_laddr_v4 != 0) {		\
1280 				(err) = (*cl_inet_connect2)(		\
1281 				    (connp)->conn_netstack->netstack_stackid,\
1282 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1283 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1284 				    (in_port_t)(connp)->conn_lport,	\
1285 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1286 				    (in_port_t)(connp)->conn_fport, NULL); \
1287 			}						\
1288 		} else {						\
1289 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1290 			    &(connp)->conn_laddr_v6)) {			\
1291 				(err) = (*cl_inet_connect2)(		\
1292 				    (connp)->conn_netstack->netstack_stackid,\
1293 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1294 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1295 				    (in_port_t)(connp)->conn_lport,	\
1296 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1297 				    (in_port_t)(connp)->conn_fport, NULL); \
1298 			}						\
1299 		}							\
1300 	}								\
1301 }
1302 
1303 #define	CL_INET_DISCONNECT(connp)	{				\
1304 	if (cl_inet_disconnect != NULL) {				\
1305 		/*							\
1306 		 * Running in cluster mode - deregister active		\
1307 		 * connection information				\
1308 		 */							\
1309 		if ((connp)->conn_ipversion == IPV4_VERSION) {		\
1310 			if ((connp)->conn_laddr_v4 != 0) {		\
1311 				(*cl_inet_disconnect)(			\
1312 				    (connp)->conn_netstack->netstack_stackid,\
1313 				    IPPROTO_TCP, AF_INET,		\
1314 				    (uint8_t *)(&((connp)->conn_laddr_v4)),\
1315 				    (in_port_t)(connp)->conn_lport,	\
1316 				    (uint8_t *)(&((connp)->conn_faddr_v4)),\
1317 				    (in_port_t)(connp)->conn_fport, NULL); \
1318 			}						\
1319 		} else {						\
1320 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1321 			    &(connp)->conn_laddr_v6)) {			\
1322 				(*cl_inet_disconnect)(			\
1323 				    (connp)->conn_netstack->netstack_stackid,\
1324 				    IPPROTO_TCP, AF_INET6,		\
1325 				    (uint8_t *)(&((connp)->conn_laddr_v6)),\
1326 				    (in_port_t)(connp)->conn_lport,	\
1327 				    (uint8_t *)(&((connp)->conn_faddr_v6)), \
1328 				    (in_port_t)(connp)->conn_fport, NULL); \
1329 			}						\
1330 		}							\
1331 	}								\
1332 }
1333 
1334 /*
1335  * Steps to do when a tcp_t moves to TIME-WAIT state.
1336  *
1337  * This connection is done, we don't need to account for it.  Decrement
1338  * the listener connection counter if needed.
1339  *
1340  * Unconditionally clear the exclusive binding bit so this TIME-WAIT
1341  * connection won't interfere with new ones.
1342  *
1343  * Start the TIME-WAIT timer.  If upper layer has not closed the connection,
1344  * the timer is handled within the context of this tcp_t.  When the timer
1345  * fires, tcp_clean_death() is called.  If upper layer closes the connection
1346  * during this period, tcp_time_wait_append() will be called to add this
1347  * tcp_t to the global TIME-WAIT list.  Note that this means that the
1348  * actual wait time in TIME-WAIT state will be longer than the
1349  * tcps_time_wait_interval since the period before upper layer closes the
1350  * connection is not accounted for when tcp_time_wait_append() is called.
1351  *
1352  * If uppser layer has closed the connection, call tcp_time_wait_append()
1353  * directly.
1354  */
1355 #define	SET_TIME_WAIT(tcps, tcp, connp)				\
1356 {								\
1357 	(tcp)->tcp_state = TCPS_TIME_WAIT;			\
1358 	if ((tcp)->tcp_listen_cnt != NULL)			\
1359 		TCP_DECR_LISTEN_CNT(tcp);			\
1360 	(connp)->conn_exclbind = 0;				\
1361 	if (!TCP_IS_DETACHED(tcp)) {				\
1362 		TCP_TIMER_RESTART(tcp, (tcps)->tcps_time_wait_interval); \
1363 	} else {						\
1364 		tcp_time_wait_append(tcp);			\
1365 		TCP_DBGSTAT(tcps, tcp_rput_time_wait);		\
1366 	}							\
1367 }
1368 
1369 /*
1370  * Cluster networking hook for traversing current connection list.
1371  * This routine is used to extract the current list of live connections
1372  * which must continue to to be dispatched to this node.
1373  */
1374 int cl_tcp_walk_list(netstackid_t stack_id,
1375     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1376 
1377 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1378     void *arg, tcp_stack_t *tcps);
1379 
1380 static void
1381 tcp_set_recv_threshold(tcp_t *tcp, uint32_t new_rcvthresh)
1382 {
1383 	uint32_t default_threshold = SOCKET_RECVHIWATER >> 3;
1384 
1385 	if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
1386 		conn_t *connp = tcp->tcp_connp;
1387 		struct sock_proto_props sopp;
1388 
1389 		/*
1390 		 * only increase rcvthresh upto default_threshold
1391 		 */
1392 		if (new_rcvthresh > default_threshold)
1393 			new_rcvthresh = default_threshold;
1394 
1395 		sopp.sopp_flags = SOCKOPT_RCVTHRESH;
1396 		sopp.sopp_rcvthresh = new_rcvthresh;
1397 
1398 		(*connp->conn_upcalls->su_set_proto_props)
1399 		    (connp->conn_upper_handle, &sopp);
1400 	}
1401 }
1402 /*
1403  * Figure out the value of window scale opton.  Note that the rwnd is
1404  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1405  * We cannot find the scale value and then do a round up of tcp_rwnd
1406  * because the scale value may not be correct after that.
1407  *
1408  * Set the compiler flag to make this function inline.
1409  */
1410 static void
1411 tcp_set_ws_value(tcp_t *tcp)
1412 {
1413 	int i;
1414 	uint32_t rwnd = tcp->tcp_rwnd;
1415 
1416 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1417 	    i++, rwnd >>= 1)
1418 		;
1419 	tcp->tcp_rcv_ws = i;
1420 }
1421 
1422 /*
1423  * Remove a connection from the list of detached TIME_WAIT connections.
1424  * It returns B_FALSE if it can't remove the connection from the list
1425  * as the connection has already been removed from the list due to an
1426  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1427  */
1428 static boolean_t
1429 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1430 {
1431 	boolean_t	locked = B_FALSE;
1432 
1433 	if (tcp_time_wait == NULL) {
1434 		tcp_time_wait = *((tcp_squeue_priv_t **)
1435 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1436 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1437 		locked = B_TRUE;
1438 	} else {
1439 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1440 	}
1441 
1442 	if (tcp->tcp_time_wait_expire == 0) {
1443 		ASSERT(tcp->tcp_time_wait_next == NULL);
1444 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1445 		if (locked)
1446 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1447 		return (B_FALSE);
1448 	}
1449 	ASSERT(TCP_IS_DETACHED(tcp));
1450 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1451 
1452 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1453 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1454 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1455 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1456 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1457 			    NULL;
1458 		} else {
1459 			tcp_time_wait->tcp_time_wait_tail = NULL;
1460 		}
1461 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1462 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1463 		ASSERT(tcp->tcp_time_wait_next == NULL);
1464 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1465 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1466 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1467 	} else {
1468 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1469 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1470 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1471 		    tcp->tcp_time_wait_next;
1472 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1473 		    tcp->tcp_time_wait_prev;
1474 	}
1475 	tcp->tcp_time_wait_next = NULL;
1476 	tcp->tcp_time_wait_prev = NULL;
1477 	tcp->tcp_time_wait_expire = 0;
1478 
1479 	if (locked)
1480 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1481 	return (B_TRUE);
1482 }
1483 
1484 /*
1485  * Add a connection to the list of detached TIME_WAIT connections
1486  * and set its time to expire.
1487  */
1488 static void
1489 tcp_time_wait_append(tcp_t *tcp)
1490 {
1491 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1492 	tcp_squeue_priv_t *tcp_time_wait =
1493 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1494 	    SQPRIVATE_TCP));
1495 
1496 	tcp_timers_stop(tcp);
1497 
1498 	/* Freed above */
1499 	ASSERT(tcp->tcp_timer_tid == 0);
1500 	ASSERT(tcp->tcp_ack_tid == 0);
1501 
1502 	/* must have happened at the time of detaching the tcp */
1503 	ASSERT(tcp->tcp_ptpahn == NULL);
1504 	ASSERT(tcp->tcp_flow_stopped == 0);
1505 	ASSERT(tcp->tcp_time_wait_next == NULL);
1506 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1507 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1508 	ASSERT(tcp->tcp_listener == NULL);
1509 
1510 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1511 	/*
1512 	 * The value computed below in tcp->tcp_time_wait_expire may
1513 	 * appear negative or wrap around. That is ok since our
1514 	 * interest is only in the difference between the current lbolt
1515 	 * value and tcp->tcp_time_wait_expire. But the value should not
1516 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1517 	 * The corresponding comparison in tcp_time_wait_collector() uses
1518 	 * modular arithmetic.
1519 	 */
1520 	tcp->tcp_time_wait_expire +=
1521 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1522 	if (tcp->tcp_time_wait_expire == 0)
1523 		tcp->tcp_time_wait_expire = 1;
1524 
1525 	ASSERT(TCP_IS_DETACHED(tcp));
1526 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1527 	ASSERT(tcp->tcp_time_wait_next == NULL);
1528 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1529 	TCP_DBGSTAT(tcps, tcp_time_wait);
1530 
1531 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1532 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1533 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1534 		tcp_time_wait->tcp_time_wait_head = tcp;
1535 	} else {
1536 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1537 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1538 		    TCPS_TIME_WAIT);
1539 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1540 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1541 	}
1542 	tcp_time_wait->tcp_time_wait_tail = tcp;
1543 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1544 }
1545 
1546 /* ARGSUSED */
1547 void
1548 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
1549 {
1550 	conn_t	*connp = (conn_t *)arg;
1551 	tcp_t	*tcp = connp->conn_tcp;
1552 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1553 
1554 	ASSERT(tcp != NULL);
1555 	if (tcp->tcp_state == TCPS_CLOSED) {
1556 		return;
1557 	}
1558 
1559 	ASSERT((connp->conn_family == AF_INET &&
1560 	    connp->conn_ipversion == IPV4_VERSION) ||
1561 	    (connp->conn_family == AF_INET6 &&
1562 	    (connp->conn_ipversion == IPV4_VERSION ||
1563 	    connp->conn_ipversion == IPV6_VERSION)));
1564 	ASSERT(!tcp->tcp_listener);
1565 
1566 	TCP_STAT(tcps, tcp_time_wait_reap);
1567 	ASSERT(TCP_IS_DETACHED(tcp));
1568 
1569 	/*
1570 	 * Because they have no upstream client to rebind or tcp_close()
1571 	 * them later, we axe the connection here and now.
1572 	 */
1573 	tcp_close_detached(tcp);
1574 }
1575 
1576 /*
1577  * Remove cached/latched IPsec references.
1578  */
1579 void
1580 tcp_ipsec_cleanup(tcp_t *tcp)
1581 {
1582 	conn_t		*connp = tcp->tcp_connp;
1583 
1584 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1585 
1586 	if (connp->conn_latch != NULL) {
1587 		IPLATCH_REFRELE(connp->conn_latch);
1588 		connp->conn_latch = NULL;
1589 	}
1590 	if (connp->conn_latch_in_policy != NULL) {
1591 		IPPOL_REFRELE(connp->conn_latch_in_policy);
1592 		connp->conn_latch_in_policy = NULL;
1593 	}
1594 	if (connp->conn_latch_in_action != NULL) {
1595 		IPACT_REFRELE(connp->conn_latch_in_action);
1596 		connp->conn_latch_in_action = NULL;
1597 	}
1598 	if (connp->conn_policy != NULL) {
1599 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1600 		connp->conn_policy = NULL;
1601 	}
1602 }
1603 
1604 /*
1605  * Cleaup before placing on free list.
1606  * Disassociate from the netstack/tcp_stack_t since the freelist
1607  * is per squeue and not per netstack.
1608  */
1609 void
1610 tcp_cleanup(tcp_t *tcp)
1611 {
1612 	mblk_t		*mp;
1613 	tcp_sack_info_t	*tcp_sack_info;
1614 	conn_t		*connp = tcp->tcp_connp;
1615 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1616 	netstack_t	*ns = tcps->tcps_netstack;
1617 	mblk_t		*tcp_rsrv_mp;
1618 
1619 	tcp_bind_hash_remove(tcp);
1620 
1621 	/* Cleanup that which needs the netstack first */
1622 	tcp_ipsec_cleanup(tcp);
1623 	ixa_cleanup(connp->conn_ixa);
1624 
1625 	if (connp->conn_ht_iphc != NULL) {
1626 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
1627 		connp->conn_ht_iphc = NULL;
1628 		connp->conn_ht_iphc_allocated = 0;
1629 		connp->conn_ht_iphc_len = 0;
1630 		connp->conn_ht_ulp = NULL;
1631 		connp->conn_ht_ulp_len = 0;
1632 		tcp->tcp_ipha = NULL;
1633 		tcp->tcp_ip6h = NULL;
1634 		tcp->tcp_tcpha = NULL;
1635 	}
1636 
1637 	/* We clear any IP_OPTIONS and extension headers */
1638 	ip_pkt_free(&connp->conn_xmit_ipp);
1639 
1640 	tcp_free(tcp);
1641 
1642 	/* Release any SSL context */
1643 	if (tcp->tcp_kssl_ent != NULL) {
1644 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1645 		tcp->tcp_kssl_ent = NULL;
1646 	}
1647 
1648 	if (tcp->tcp_kssl_ctx != NULL) {
1649 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1650 		tcp->tcp_kssl_ctx = NULL;
1651 	}
1652 	tcp->tcp_kssl_pending = B_FALSE;
1653 
1654 	/*
1655 	 * Since we will bzero the entire structure, we need to
1656 	 * remove it and reinsert it in global hash list. We
1657 	 * know the walkers can't get to this conn because we
1658 	 * had set CONDEMNED flag earlier and checked reference
1659 	 * under conn_lock so walker won't pick it and when we
1660 	 * go the ipcl_globalhash_remove() below, no walker
1661 	 * can get to it.
1662 	 */
1663 	ipcl_globalhash_remove(connp);
1664 
1665 	/* Save some state */
1666 	mp = tcp->tcp_timercache;
1667 
1668 	tcp_sack_info = tcp->tcp_sack_info;
1669 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1670 
1671 	if (connp->conn_cred != NULL) {
1672 		crfree(connp->conn_cred);
1673 		connp->conn_cred = NULL;
1674 	}
1675 	ipcl_conn_cleanup(connp);
1676 	connp->conn_flags = IPCL_TCPCONN;
1677 
1678 	/*
1679 	 * Now it is safe to decrement the reference counts.
1680 	 * This might be the last reference on the netstack
1681 	 * in which case it will cause the freeing of the IP Instance.
1682 	 */
1683 	connp->conn_netstack = NULL;
1684 	connp->conn_ixa->ixa_ipst = NULL;
1685 	netstack_rele(ns);
1686 	ASSERT(tcps != NULL);
1687 	tcp->tcp_tcps = NULL;
1688 
1689 	bzero(tcp, sizeof (tcp_t));
1690 
1691 	/* restore the state */
1692 	tcp->tcp_timercache = mp;
1693 
1694 	tcp->tcp_sack_info = tcp_sack_info;
1695 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1696 
1697 	tcp->tcp_connp = connp;
1698 
1699 	ASSERT(connp->conn_tcp == tcp);
1700 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1701 	connp->conn_state_flags = CONN_INCIPIENT;
1702 	ASSERT(connp->conn_proto == IPPROTO_TCP);
1703 	ASSERT(connp->conn_ref == 1);
1704 }
1705 
1706 /*
1707  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1708  * is done forwards from the head.
1709  * This walks all stack instances since
1710  * tcp_time_wait remains global across all stacks.
1711  */
1712 /* ARGSUSED */
1713 void
1714 tcp_time_wait_collector(void *arg)
1715 {
1716 	tcp_t *tcp;
1717 	clock_t now;
1718 	mblk_t *mp;
1719 	conn_t *connp;
1720 	kmutex_t *lock;
1721 	boolean_t removed;
1722 
1723 	squeue_t *sqp = (squeue_t *)arg;
1724 	tcp_squeue_priv_t *tcp_time_wait =
1725 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1726 
1727 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1728 	tcp_time_wait->tcp_time_wait_tid = 0;
1729 
1730 	if (tcp_time_wait->tcp_free_list != NULL &&
1731 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1732 		TCP_G_STAT(tcp_freelist_cleanup);
1733 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1734 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1735 			tcp->tcp_time_wait_next = NULL;
1736 			tcp_time_wait->tcp_free_list_cnt--;
1737 			ASSERT(tcp->tcp_tcps == NULL);
1738 			CONN_DEC_REF(tcp->tcp_connp);
1739 		}
1740 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1741 	}
1742 
1743 	/*
1744 	 * In order to reap time waits reliably, we should use a
1745 	 * source of time that is not adjustable by the user -- hence
1746 	 * the call to ddi_get_lbolt().
1747 	 */
1748 	now = ddi_get_lbolt();
1749 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1750 		/*
1751 		 * Compare times using modular arithmetic, since
1752 		 * lbolt can wrapover.
1753 		 */
1754 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1755 			break;
1756 		}
1757 
1758 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1759 		ASSERT(removed);
1760 
1761 		connp = tcp->tcp_connp;
1762 		ASSERT(connp->conn_fanout != NULL);
1763 		lock = &connp->conn_fanout->connf_lock;
1764 		/*
1765 		 * This is essentially a TW reclaim fast path optimization for
1766 		 * performance where the timewait collector checks under the
1767 		 * fanout lock (so that no one else can get access to the
1768 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1769 		 * the classifier hash list. If ref count is indeed 2, we can
1770 		 * just remove the conn under the fanout lock and avoid
1771 		 * cleaning up the conn under the squeue, provided that
1772 		 * clustering callbacks are not enabled. If clustering is
1773 		 * enabled, we need to make the clustering callback before
1774 		 * setting the CONDEMNED flag and after dropping all locks and
1775 		 * so we forego this optimization and fall back to the slow
1776 		 * path. Also please see the comments in tcp_closei_local
1777 		 * regarding the refcnt logic.
1778 		 *
1779 		 * Since we are holding the tcp_time_wait_lock, its better
1780 		 * not to block on the fanout_lock because other connections
1781 		 * can't add themselves to time_wait list. So we do a
1782 		 * tryenter instead of mutex_enter.
1783 		 */
1784 		if (mutex_tryenter(lock)) {
1785 			mutex_enter(&connp->conn_lock);
1786 			if ((connp->conn_ref == 2) &&
1787 			    (cl_inet_disconnect == NULL)) {
1788 				ipcl_hash_remove_locked(connp,
1789 				    connp->conn_fanout);
1790 				/*
1791 				 * Set the CONDEMNED flag now itself so that
1792 				 * the refcnt cannot increase due to any
1793 				 * walker.
1794 				 */
1795 				connp->conn_state_flags |= CONN_CONDEMNED;
1796 				mutex_exit(lock);
1797 				mutex_exit(&connp->conn_lock);
1798 				if (tcp_time_wait->tcp_free_list_cnt <
1799 				    tcp_free_list_max_cnt) {
1800 					/* Add to head of tcp_free_list */
1801 					mutex_exit(
1802 					    &tcp_time_wait->tcp_time_wait_lock);
1803 					tcp_cleanup(tcp);
1804 					ASSERT(connp->conn_latch == NULL);
1805 					ASSERT(connp->conn_policy == NULL);
1806 					ASSERT(tcp->tcp_tcps == NULL);
1807 					ASSERT(connp->conn_netstack == NULL);
1808 
1809 					mutex_enter(
1810 					    &tcp_time_wait->tcp_time_wait_lock);
1811 					tcp->tcp_time_wait_next =
1812 					    tcp_time_wait->tcp_free_list;
1813 					tcp_time_wait->tcp_free_list = tcp;
1814 					tcp_time_wait->tcp_free_list_cnt++;
1815 					continue;
1816 				} else {
1817 					/* Do not add to tcp_free_list */
1818 					mutex_exit(
1819 					    &tcp_time_wait->tcp_time_wait_lock);
1820 					tcp_bind_hash_remove(tcp);
1821 					ixa_cleanup(tcp->tcp_connp->conn_ixa);
1822 					tcp_ipsec_cleanup(tcp);
1823 					CONN_DEC_REF(tcp->tcp_connp);
1824 				}
1825 			} else {
1826 				CONN_INC_REF_LOCKED(connp);
1827 				mutex_exit(lock);
1828 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1829 				mutex_exit(&connp->conn_lock);
1830 				/*
1831 				 * We can reuse the closemp here since conn has
1832 				 * detached (otherwise we wouldn't even be in
1833 				 * time_wait list). tcp_closemp_used can safely
1834 				 * be changed without taking a lock as no other
1835 				 * thread can concurrently access it at this
1836 				 * point in the connection lifecycle.
1837 				 */
1838 
1839 				if (tcp->tcp_closemp.b_prev == NULL)
1840 					tcp->tcp_closemp_used = B_TRUE;
1841 				else
1842 					cmn_err(CE_PANIC,
1843 					    "tcp_timewait_collector: "
1844 					    "concurrent use of tcp_closemp: "
1845 					    "connp %p tcp %p\n", (void *)connp,
1846 					    (void *)tcp);
1847 
1848 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1849 				mp = &tcp->tcp_closemp;
1850 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1851 				    tcp_timewait_output, connp, NULL,
1852 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1853 			}
1854 		} else {
1855 			mutex_enter(&connp->conn_lock);
1856 			CONN_INC_REF_LOCKED(connp);
1857 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1858 			mutex_exit(&connp->conn_lock);
1859 			/*
1860 			 * We can reuse the closemp here since conn has
1861 			 * detached (otherwise we wouldn't even be in
1862 			 * time_wait list). tcp_closemp_used can safely
1863 			 * be changed without taking a lock as no other
1864 			 * thread can concurrently access it at this
1865 			 * point in the connection lifecycle.
1866 			 */
1867 
1868 			if (tcp->tcp_closemp.b_prev == NULL)
1869 				tcp->tcp_closemp_used = B_TRUE;
1870 			else
1871 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1872 				    "concurrent use of tcp_closemp: "
1873 				    "connp %p tcp %p\n", (void *)connp,
1874 				    (void *)tcp);
1875 
1876 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1877 			mp = &tcp->tcp_closemp;
1878 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1879 			    tcp_timewait_output, connp, NULL,
1880 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1881 		}
1882 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1883 	}
1884 
1885 	if (tcp_time_wait->tcp_free_list != NULL)
1886 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1887 
1888 	tcp_time_wait->tcp_time_wait_tid =
1889 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1890 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1891 	    CALLOUT_FLAG_ROUNDUP);
1892 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1893 }
1894 
1895 /*
1896  * Reply to a clients T_CONN_RES TPI message. This function
1897  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1898  * on the acceptor STREAM and processed in tcp_accept_common().
1899  * Read the block comment on top of tcp_input_listener().
1900  */
1901 static void
1902 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1903 {
1904 	tcp_t		*acceptor;
1905 	tcp_t		*eager;
1906 	tcp_t   	*tcp;
1907 	struct T_conn_res	*tcr;
1908 	t_uscalar_t	acceptor_id;
1909 	t_scalar_t	seqnum;
1910 	mblk_t		*discon_mp = NULL;
1911 	mblk_t		*ok_mp;
1912 	mblk_t		*mp1;
1913 	tcp_stack_t	*tcps = listener->tcp_tcps;
1914 	conn_t		*econnp;
1915 
1916 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1917 		tcp_err_ack(listener, mp, TPROTO, 0);
1918 		return;
1919 	}
1920 	tcr = (struct T_conn_res *)mp->b_rptr;
1921 
1922 	/*
1923 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1924 	 * read side queue of the streams device underneath us i.e. the
1925 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1926 	 * look it up in the queue_hash.  Under LP64 it sends down the
1927 	 * minor_t of the accepting endpoint.
1928 	 *
1929 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1930 	 * fanout hash lock is held.
1931 	 * This prevents any thread from entering the acceptor queue from
1932 	 * below (since it has not been hard bound yet i.e. any inbound
1933 	 * packets will arrive on the listener conn_t and
1934 	 * go through the classifier).
1935 	 * The CONN_INC_REF will prevent the acceptor from closing.
1936 	 *
1937 	 * XXX It is still possible for a tli application to send down data
1938 	 * on the accepting stream while another thread calls t_accept.
1939 	 * This should not be a problem for well-behaved applications since
1940 	 * the T_OK_ACK is sent after the queue swapping is completed.
1941 	 *
1942 	 * If the accepting fd is the same as the listening fd, avoid
1943 	 * queue hash lookup since that will return an eager listener in a
1944 	 * already established state.
1945 	 */
1946 	acceptor_id = tcr->ACCEPTOR_id;
1947 	mutex_enter(&listener->tcp_eager_lock);
1948 	if (listener->tcp_acceptor_id == acceptor_id) {
1949 		eager = listener->tcp_eager_next_q;
1950 		/* only count how many T_CONN_INDs so don't count q0 */
1951 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1952 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1953 			mutex_exit(&listener->tcp_eager_lock);
1954 			tcp_err_ack(listener, mp, TBADF, 0);
1955 			return;
1956 		}
1957 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1958 			/* Throw away all the eagers on q0. */
1959 			tcp_eager_cleanup(listener, 1);
1960 		}
1961 		if (listener->tcp_syn_defense) {
1962 			listener->tcp_syn_defense = B_FALSE;
1963 			if (listener->tcp_ip_addr_cache != NULL) {
1964 				kmem_free(listener->tcp_ip_addr_cache,
1965 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1966 				listener->tcp_ip_addr_cache = NULL;
1967 			}
1968 		}
1969 		/*
1970 		 * Transfer tcp_conn_req_max to the eager so that when
1971 		 * a disconnect occurs we can revert the endpoint to the
1972 		 * listen state.
1973 		 */
1974 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1975 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1976 		/*
1977 		 * Get a reference on the acceptor just like the
1978 		 * tcp_acceptor_hash_lookup below.
1979 		 */
1980 		acceptor = listener;
1981 		CONN_INC_REF(acceptor->tcp_connp);
1982 	} else {
1983 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1984 		if (acceptor == NULL) {
1985 			if (listener->tcp_connp->conn_debug) {
1986 				(void) strlog(TCP_MOD_ID, 0, 1,
1987 				    SL_ERROR|SL_TRACE,
1988 				    "tcp_accept: did not find acceptor 0x%x\n",
1989 				    acceptor_id);
1990 			}
1991 			mutex_exit(&listener->tcp_eager_lock);
1992 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
1993 			return;
1994 		}
1995 		/*
1996 		 * Verify acceptor state. The acceptable states for an acceptor
1997 		 * include TCPS_IDLE and TCPS_BOUND.
1998 		 */
1999 		switch (acceptor->tcp_state) {
2000 		case TCPS_IDLE:
2001 			/* FALLTHRU */
2002 		case TCPS_BOUND:
2003 			break;
2004 		default:
2005 			CONN_DEC_REF(acceptor->tcp_connp);
2006 			mutex_exit(&listener->tcp_eager_lock);
2007 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2008 			return;
2009 		}
2010 	}
2011 
2012 	/* The listener must be in TCPS_LISTEN */
2013 	if (listener->tcp_state != TCPS_LISTEN) {
2014 		CONN_DEC_REF(acceptor->tcp_connp);
2015 		mutex_exit(&listener->tcp_eager_lock);
2016 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2017 		return;
2018 	}
2019 
2020 	/*
2021 	 * Rendezvous with an eager connection request packet hanging off
2022 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2023 	 * tcp structure when the connection packet arrived in
2024 	 * tcp_input_listener().
2025 	 */
2026 	seqnum = tcr->SEQ_number;
2027 	eager = listener;
2028 	do {
2029 		eager = eager->tcp_eager_next_q;
2030 		if (eager == NULL) {
2031 			CONN_DEC_REF(acceptor->tcp_connp);
2032 			mutex_exit(&listener->tcp_eager_lock);
2033 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2034 			return;
2035 		}
2036 	} while (eager->tcp_conn_req_seqnum != seqnum);
2037 	mutex_exit(&listener->tcp_eager_lock);
2038 
2039 	/*
2040 	 * At this point, both acceptor and listener have 2 ref
2041 	 * that they begin with. Acceptor has one additional ref
2042 	 * we placed in lookup while listener has 3 additional
2043 	 * ref for being behind the squeue (tcp_accept() is
2044 	 * done on listener's squeue); being in classifier hash;
2045 	 * and eager's ref on listener.
2046 	 */
2047 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2048 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2049 
2050 	/*
2051 	 * The eager at this point is set in its own squeue and
2052 	 * could easily have been killed (tcp_accept_finish will
2053 	 * deal with that) because of a TH_RST so we can only
2054 	 * ASSERT for a single ref.
2055 	 */
2056 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2057 
2058 	/*
2059 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
2060 	 * use it if something failed.
2061 	 */
2062 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
2063 	    sizeof (struct stroptions)), BPRI_HI);
2064 	if (discon_mp == NULL) {
2065 		CONN_DEC_REF(acceptor->tcp_connp);
2066 		CONN_DEC_REF(eager->tcp_connp);
2067 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2068 		return;
2069 	}
2070 
2071 	econnp = eager->tcp_connp;
2072 
2073 	/* Hold a copy of mp, in case reallocb fails */
2074 	if ((mp1 = copymsg(mp)) == NULL) {
2075 		CONN_DEC_REF(acceptor->tcp_connp);
2076 		CONN_DEC_REF(eager->tcp_connp);
2077 		freemsg(discon_mp);
2078 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2079 		return;
2080 	}
2081 
2082 	tcr = (struct T_conn_res *)mp1->b_rptr;
2083 
2084 	/*
2085 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2086 	 * which allocates a larger mblk and appends the new
2087 	 * local address to the ok_ack.  The address is copied by
2088 	 * soaccept() for getsockname().
2089 	 */
2090 	{
2091 		int extra;
2092 
2093 		extra = (econnp->conn_family == AF_INET) ?
2094 		    sizeof (sin_t) : sizeof (sin6_t);
2095 
2096 		/*
2097 		 * Try to re-use mp, if possible.  Otherwise, allocate
2098 		 * an mblk and return it as ok_mp.  In any case, mp
2099 		 * is no longer usable upon return.
2100 		 */
2101 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2102 			CONN_DEC_REF(acceptor->tcp_connp);
2103 			CONN_DEC_REF(eager->tcp_connp);
2104 			freemsg(discon_mp);
2105 			/* Original mp has been freed by now, so use mp1 */
2106 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2107 			return;
2108 		}
2109 
2110 		mp = NULL;	/* We should never use mp after this point */
2111 
2112 		switch (extra) {
2113 		case sizeof (sin_t): {
2114 			sin_t *sin = (sin_t *)ok_mp->b_wptr;
2115 
2116 			ok_mp->b_wptr += extra;
2117 			sin->sin_family = AF_INET;
2118 			sin->sin_port = econnp->conn_lport;
2119 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
2120 			break;
2121 		}
2122 		case sizeof (sin6_t): {
2123 			sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2124 
2125 			ok_mp->b_wptr += extra;
2126 			sin6->sin6_family = AF_INET6;
2127 			sin6->sin6_port = econnp->conn_lport;
2128 			sin6->sin6_addr = econnp->conn_laddr_v6;
2129 			sin6->sin6_flowinfo = econnp->conn_flowinfo;
2130 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
2131 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
2132 				sin6->sin6_scope_id =
2133 				    econnp->conn_ixa->ixa_scopeid;
2134 			} else {
2135 				sin6->sin6_scope_id = 0;
2136 			}
2137 			sin6->__sin6_src_id = 0;
2138 			break;
2139 		}
2140 		default:
2141 			break;
2142 		}
2143 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2144 	}
2145 
2146 	/*
2147 	 * If there are no options we know that the T_CONN_RES will
2148 	 * succeed. However, we can't send the T_OK_ACK upstream until
2149 	 * the tcp_accept_swap is done since it would be dangerous to
2150 	 * let the application start using the new fd prior to the swap.
2151 	 */
2152 	tcp_accept_swap(listener, acceptor, eager);
2153 
2154 	/*
2155 	 * tcp_accept_swap unlinks eager from listener but does not drop
2156 	 * the eager's reference on the listener.
2157 	 */
2158 	ASSERT(eager->tcp_listener == NULL);
2159 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2160 
2161 	/*
2162 	 * The eager is now associated with its own queue. Insert in
2163 	 * the hash so that the connection can be reused for a future
2164 	 * T_CONN_RES.
2165 	 */
2166 	tcp_acceptor_hash_insert(acceptor_id, eager);
2167 
2168 	/*
2169 	 * We now do the processing of options with T_CONN_RES.
2170 	 * We delay till now since we wanted to have queue to pass to
2171 	 * option processing routines that points back to the right
2172 	 * instance structure which does not happen until after
2173 	 * tcp_accept_swap().
2174 	 *
2175 	 * Note:
2176 	 * The sanity of the logic here assumes that whatever options
2177 	 * are appropriate to inherit from listner=>eager are done
2178 	 * before this point, and whatever were to be overridden (or not)
2179 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2180 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2181 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2182 	 * This may not be true at this point in time but can be fixed
2183 	 * independently. This option processing code starts with
2184 	 * the instantiated acceptor instance and the final queue at
2185 	 * this point.
2186 	 */
2187 
2188 	if (tcr->OPT_length != 0) {
2189 		/* Options to process */
2190 		int t_error = 0;
2191 		int sys_error = 0;
2192 		int do_disconnect = 0;
2193 
2194 		if (tcp_conprim_opt_process(eager, mp1,
2195 		    &do_disconnect, &t_error, &sys_error) < 0) {
2196 			eager->tcp_accept_error = 1;
2197 			if (do_disconnect) {
2198 				/*
2199 				 * An option failed which does not allow
2200 				 * connection to be accepted.
2201 				 *
2202 				 * We allow T_CONN_RES to succeed and
2203 				 * put a T_DISCON_IND on the eager queue.
2204 				 */
2205 				ASSERT(t_error == 0 && sys_error == 0);
2206 				eager->tcp_send_discon_ind = 1;
2207 			} else {
2208 				ASSERT(t_error != 0);
2209 				freemsg(ok_mp);
2210 				/*
2211 				 * Original mp was either freed or set
2212 				 * to ok_mp above, so use mp1 instead.
2213 				 */
2214 				tcp_err_ack(listener, mp1, t_error, sys_error);
2215 				goto finish;
2216 			}
2217 		}
2218 		/*
2219 		 * Most likely success in setting options (except if
2220 		 * eager->tcp_send_discon_ind set).
2221 		 * mp1 option buffer represented by OPT_length/offset
2222 		 * potentially modified and contains results of setting
2223 		 * options at this point
2224 		 */
2225 	}
2226 
2227 	/* We no longer need mp1, since all options processing has passed */
2228 	freemsg(mp1);
2229 
2230 	putnext(listener->tcp_connp->conn_rq, ok_mp);
2231 
2232 	mutex_enter(&listener->tcp_eager_lock);
2233 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2234 		tcp_t	*tail;
2235 		mblk_t	*conn_ind;
2236 
2237 		/*
2238 		 * This path should not be executed if listener and
2239 		 * acceptor streams are the same.
2240 		 */
2241 		ASSERT(listener != acceptor);
2242 
2243 		tcp = listener->tcp_eager_prev_q0;
2244 		/*
2245 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2246 		 * deferred T_conn_ind queue. We need to get to the head of
2247 		 * the queue in order to send up T_conn_ind the same order as
2248 		 * how the 3WHS is completed.
2249 		 */
2250 		while (tcp != listener) {
2251 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2252 				break;
2253 			else
2254 				tcp = tcp->tcp_eager_prev_q0;
2255 		}
2256 		ASSERT(tcp != listener);
2257 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2258 		ASSERT(conn_ind != NULL);
2259 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2260 
2261 		/* Move from q0 to q */
2262 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2263 		listener->tcp_conn_req_cnt_q0--;
2264 		listener->tcp_conn_req_cnt_q++;
2265 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2266 		    tcp->tcp_eager_prev_q0;
2267 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2268 		    tcp->tcp_eager_next_q0;
2269 		tcp->tcp_eager_prev_q0 = NULL;
2270 		tcp->tcp_eager_next_q0 = NULL;
2271 		tcp->tcp_conn_def_q0 = B_FALSE;
2272 
2273 		/* Make sure the tcp isn't in the list of droppables */
2274 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2275 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2276 
2277 		/*
2278 		 * Insert at end of the queue because sockfs sends
2279 		 * down T_CONN_RES in chronological order. Leaving
2280 		 * the older conn indications at front of the queue
2281 		 * helps reducing search time.
2282 		 */
2283 		tail = listener->tcp_eager_last_q;
2284 		if (tail != NULL)
2285 			tail->tcp_eager_next_q = tcp;
2286 		else
2287 			listener->tcp_eager_next_q = tcp;
2288 		listener->tcp_eager_last_q = tcp;
2289 		tcp->tcp_eager_next_q = NULL;
2290 		mutex_exit(&listener->tcp_eager_lock);
2291 		putnext(tcp->tcp_connp->conn_rq, conn_ind);
2292 	} else {
2293 		mutex_exit(&listener->tcp_eager_lock);
2294 	}
2295 
2296 	/*
2297 	 * Done with the acceptor - free it
2298 	 *
2299 	 * Note: from this point on, no access to listener should be made
2300 	 * as listener can be equal to acceptor.
2301 	 */
2302 finish:
2303 	ASSERT(acceptor->tcp_detached);
2304 	acceptor->tcp_connp->conn_rq = NULL;
2305 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2306 	acceptor->tcp_connp->conn_wq = NULL;
2307 	(void) tcp_clean_death(acceptor, 0, 2);
2308 	CONN_DEC_REF(acceptor->tcp_connp);
2309 
2310 	/*
2311 	 * We pass discon_mp to tcp_accept_finish to get on the right squeue.
2312 	 *
2313 	 * It will update the setting for sockfs/stream head and also take
2314 	 * care of any data that arrived before accept() wad called.
2315 	 * In case we already received a FIN then tcp_accept_finish will send up
2316 	 * the ordrel. It will also send up a window update if the window
2317 	 * has opened up.
2318 	 */
2319 
2320 	/*
2321 	 * XXX: we currently have a problem if XTI application closes the
2322 	 * acceptor stream in between. This problem exists in on10-gate also
2323 	 * and is well know but nothing can be done short of major rewrite
2324 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2325 	 * eager same squeue as listener (we can distinguish non socket
2326 	 * listeners at the time of handling a SYN in tcp_input_listener)
2327 	 * and do most of the work that tcp_accept_finish does here itself
2328 	 * and then get behind the acceptor squeue to access the acceptor
2329 	 * queue.
2330 	 */
2331 	/*
2332 	 * We already have a ref on tcp so no need to do one before squeue_enter
2333 	 */
2334 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, discon_mp,
2335 	    tcp_accept_finish, eager->tcp_connp, NULL, SQ_FILL,
2336 	    SQTAG_TCP_ACCEPT_FINISH);
2337 }
2338 
2339 /*
2340  * Swap information between the eager and acceptor for a TLI/XTI client.
2341  * The sockfs accept is done on the acceptor stream and control goes
2342  * through tcp_tli_accept() and tcp_accept()/tcp_accept_swap() is not
2343  * called. In either case, both the eager and listener are in their own
2344  * perimeter (squeue) and the code has to deal with potential race.
2345  *
2346  * See the block comment on top of tcp_accept() and tcp_tli_accept().
2347  */
2348 static void
2349 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2350 {
2351 	conn_t	*econnp, *aconnp;
2352 
2353 	ASSERT(eager->tcp_connp->conn_rq == listener->tcp_connp->conn_rq);
2354 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2355 	ASSERT(!TCP_IS_SOCKET(acceptor));
2356 	ASSERT(!TCP_IS_SOCKET(eager));
2357 	ASSERT(!TCP_IS_SOCKET(listener));
2358 
2359 	/*
2360 	 * Trusted Extensions may need to use a security label that is
2361 	 * different from the acceptor's label on MLP and MAC-Exempt
2362 	 * sockets. If this is the case, the required security label
2363 	 * already exists in econnp->conn_ixa->ixa_tsl. Since we make the
2364 	 * acceptor stream refer to econnp we atomatically get that label.
2365 	 */
2366 
2367 	acceptor->tcp_detached = B_TRUE;
2368 	/*
2369 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2370 	 * the acceptor id.
2371 	 */
2372 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2373 
2374 	/* remove eager from listen list... */
2375 	mutex_enter(&listener->tcp_eager_lock);
2376 	tcp_eager_unlink(eager);
2377 	ASSERT(eager->tcp_eager_next_q == NULL &&
2378 	    eager->tcp_eager_last_q == NULL);
2379 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2380 	    eager->tcp_eager_prev_q0 == NULL);
2381 	mutex_exit(&listener->tcp_eager_lock);
2382 
2383 	econnp = eager->tcp_connp;
2384 	aconnp = acceptor->tcp_connp;
2385 	econnp->conn_rq = aconnp->conn_rq;
2386 	econnp->conn_wq = aconnp->conn_wq;
2387 	econnp->conn_rq->q_ptr = econnp;
2388 	econnp->conn_wq->q_ptr = econnp;
2389 
2390 	/*
2391 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2392 	 * which might be a different squeue from our peer TCP instance.
2393 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2394 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2395 	 * membar_producer() to ensure that the assignments of conn_rq/conn_wq
2396 	 * above reach global visibility prior to the clearing of tcp_detached.
2397 	 */
2398 	membar_producer();
2399 	eager->tcp_detached = B_FALSE;
2400 
2401 	ASSERT(eager->tcp_ack_tid == 0);
2402 
2403 	econnp->conn_dev = aconnp->conn_dev;
2404 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2405 
2406 	ASSERT(econnp->conn_minor_arena != NULL);
2407 	if (econnp->conn_cred != NULL)
2408 		crfree(econnp->conn_cred);
2409 	econnp->conn_cred = aconnp->conn_cred;
2410 	aconnp->conn_cred = NULL;
2411 	econnp->conn_cpid = aconnp->conn_cpid;
2412 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2413 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2414 
2415 	econnp->conn_zoneid = aconnp->conn_zoneid;
2416 	econnp->conn_allzones = aconnp->conn_allzones;
2417 	econnp->conn_ixa->ixa_zoneid = aconnp->conn_ixa->ixa_zoneid;
2418 
2419 	econnp->conn_mac_mode = aconnp->conn_mac_mode;
2420 	econnp->conn_zone_is_global = aconnp->conn_zone_is_global;
2421 	aconnp->conn_mac_mode = CONN_MAC_DEFAULT;
2422 
2423 	/* Do the IPC initialization */
2424 	CONN_INC_REF(econnp);
2425 
2426 	/* Done with old IPC. Drop its ref on its connp */
2427 	CONN_DEC_REF(aconnp);
2428 }
2429 
2430 
2431 /*
2432  * Adapt to the information, such as rtt and rtt_sd, provided from the
2433  * DCE and IRE maintained by IP.
2434  *
2435  * Checks for multicast and broadcast destination address.
2436  * Returns zero if ok; an errno on failure.
2437  *
2438  * Note that the MSS calculation here is based on the info given in
2439  * the DCE and IRE.  We do not do any calculation based on TCP options.  They
2440  * will be handled in tcp_input_data() when TCP knows which options to use.
2441  *
2442  * Note on how TCP gets its parameters for a connection.
2443  *
2444  * When a tcp_t structure is allocated, it gets all the default parameters.
2445  * In tcp_set_destination(), it gets those metric parameters, like rtt, rtt_sd,
2446  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2447  * default.
2448  *
2449  * An incoming SYN with a multicast or broadcast destination address is dropped
2450  * in ip_fanout_v4/v6.
2451  *
2452  * An incoming SYN with a multicast or broadcast source address is always
2453  * dropped in tcp_set_destination, since IPDF_ALLOW_MCBC is not set in
2454  * conn_connect.
2455  * The same logic in tcp_set_destination also serves to
2456  * reject an attempt to connect to a broadcast or multicast (destination)
2457  * address.
2458  */
2459 static int
2460 tcp_set_destination(tcp_t *tcp)
2461 {
2462 	uint32_t	mss_max;
2463 	uint32_t	mss;
2464 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2465 	conn_t		*connp = tcp->tcp_connp;
2466 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2467 	iulp_t		uinfo;
2468 	int		error;
2469 	uint32_t	flags;
2470 
2471 	flags = IPDF_LSO | IPDF_ZCOPY;
2472 	/*
2473 	 * Make sure we have a dce for the destination to avoid dce_ident
2474 	 * contention for connected sockets.
2475 	 */
2476 	flags |= IPDF_UNIQUE_DCE;
2477 
2478 	if (!tcps->tcps_ignore_path_mtu)
2479 		connp->conn_ixa->ixa_flags |= IXAF_PMTU_DISCOVERY;
2480 
2481 	/* Use conn_lock to satify ASSERT; tcp is already serialized */
2482 	mutex_enter(&connp->conn_lock);
2483 	error = conn_connect(connp, &uinfo, flags);
2484 	mutex_exit(&connp->conn_lock);
2485 	if (error != 0)
2486 		return (error);
2487 
2488 	error = tcp_build_hdrs(tcp);
2489 	if (error != 0)
2490 		return (error);
2491 
2492 	tcp->tcp_localnet = uinfo.iulp_localnet;
2493 
2494 	if (uinfo.iulp_rtt != 0) {
2495 		clock_t	rto;
2496 
2497 		tcp->tcp_rtt_sa = uinfo.iulp_rtt;
2498 		tcp->tcp_rtt_sd = uinfo.iulp_rtt_sd;
2499 		rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2500 		    tcps->tcps_rexmit_interval_extra +
2501 		    (tcp->tcp_rtt_sa >> 5);
2502 
2503 		if (rto > tcps->tcps_rexmit_interval_max) {
2504 			tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2505 		} else if (rto < tcps->tcps_rexmit_interval_min) {
2506 			tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2507 		} else {
2508 			tcp->tcp_rto = rto;
2509 		}
2510 	}
2511 	if (uinfo.iulp_ssthresh != 0)
2512 		tcp->tcp_cwnd_ssthresh = uinfo.iulp_ssthresh;
2513 	else
2514 		tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2515 	if (uinfo.iulp_spipe > 0) {
2516 		connp->conn_sndbuf = MIN(uinfo.iulp_spipe,
2517 		    tcps->tcps_max_buf);
2518 		if (tcps->tcps_snd_lowat_fraction != 0) {
2519 			connp->conn_sndlowat = connp->conn_sndbuf /
2520 			    tcps->tcps_snd_lowat_fraction;
2521 		}
2522 		(void) tcp_maxpsz_set(tcp, B_TRUE);
2523 	}
2524 	/*
2525 	 * Note that up till now, acceptor always inherits receive
2526 	 * window from the listener.  But if there is a metrics
2527 	 * associated with a host, we should use that instead of
2528 	 * inheriting it from listener. Thus we need to pass this
2529 	 * info back to the caller.
2530 	 */
2531 	if (uinfo.iulp_rpipe > 0) {
2532 		tcp->tcp_rwnd = MIN(uinfo.iulp_rpipe,
2533 		    tcps->tcps_max_buf);
2534 	}
2535 
2536 	if (uinfo.iulp_rtomax > 0) {
2537 		tcp->tcp_second_timer_threshold =
2538 		    uinfo.iulp_rtomax;
2539 	}
2540 
2541 	/*
2542 	 * Use the metric option settings, iulp_tstamp_ok and
2543 	 * iulp_wscale_ok, only for active open. What this means
2544 	 * is that if the other side uses timestamp or window
2545 	 * scale option, TCP will also use those options. That
2546 	 * is for passive open.  If the application sets a
2547 	 * large window, window scale is enabled regardless of
2548 	 * the value in iulp_wscale_ok.  This is the behavior
2549 	 * since 2.6.  So we keep it.
2550 	 * The only case left in passive open processing is the
2551 	 * check for SACK.
2552 	 * For ECN, it should probably be like SACK.  But the
2553 	 * current value is binary, so we treat it like the other
2554 	 * cases.  The metric only controls active open.For passive
2555 	 * open, the ndd param, tcp_ecn_permitted, controls the
2556 	 * behavior.
2557 	 */
2558 	if (!tcp_detached) {
2559 		/*
2560 		 * The if check means that the following can only
2561 		 * be turned on by the metrics only IRE, but not off.
2562 		 */
2563 		if (uinfo.iulp_tstamp_ok)
2564 			tcp->tcp_snd_ts_ok = B_TRUE;
2565 		if (uinfo.iulp_wscale_ok)
2566 			tcp->tcp_snd_ws_ok = B_TRUE;
2567 		if (uinfo.iulp_sack == 2)
2568 			tcp->tcp_snd_sack_ok = B_TRUE;
2569 		if (uinfo.iulp_ecn_ok)
2570 			tcp->tcp_ecn_ok = B_TRUE;
2571 	} else {
2572 		/*
2573 		 * Passive open.
2574 		 *
2575 		 * As above, the if check means that SACK can only be
2576 		 * turned on by the metric only IRE.
2577 		 */
2578 		if (uinfo.iulp_sack > 0) {
2579 			tcp->tcp_snd_sack_ok = B_TRUE;
2580 		}
2581 	}
2582 
2583 	/*
2584 	 * XXX Note that currently, iulp_mtu can be as small as 68
2585 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2586 	 * length of all those options exceeds 28 bytes.  But because
2587 	 * of the tcp_mss_min check below, we may not have a problem if
2588 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2589 	 * the negative problem still exists.  And the check defeats PMTUd.
2590 	 * In fact, if PMTUd finds that the MSS should be smaller than
2591 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2592 	 * value.
2593 	 *
2594 	 * We do not deal with that now.  All those problems related to
2595 	 * PMTUd will be fixed later.
2596 	 */
2597 	ASSERT(uinfo.iulp_mtu != 0);
2598 	mss = tcp->tcp_initial_pmtu = uinfo.iulp_mtu;
2599 
2600 	/* Sanity check for MSS value. */
2601 	if (connp->conn_ipversion == IPV4_VERSION)
2602 		mss_max = tcps->tcps_mss_max_ipv4;
2603 	else
2604 		mss_max = tcps->tcps_mss_max_ipv6;
2605 
2606 	if (tcp->tcp_ipsec_overhead == 0)
2607 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2608 
2609 	mss -= tcp->tcp_ipsec_overhead;
2610 
2611 	if (mss < tcps->tcps_mss_min)
2612 		mss = tcps->tcps_mss_min;
2613 	if (mss > mss_max)
2614 		mss = mss_max;
2615 
2616 	/* Note that this is the maximum MSS, excluding all options. */
2617 	tcp->tcp_mss = mss;
2618 
2619 	/*
2620 	 * Update the tcp connection with LSO capability.
2621 	 */
2622 	tcp_update_lso(tcp, connp->conn_ixa);
2623 
2624 	/*
2625 	 * Initialize the ISS here now that we have the full connection ID.
2626 	 * The RFC 1948 method of initial sequence number generation requires
2627 	 * knowledge of the full connection ID before setting the ISS.
2628 	 */
2629 	tcp_iss_init(tcp);
2630 
2631 	tcp->tcp_loopback = (uinfo.iulp_loopback | uinfo.iulp_local);
2632 
2633 	/*
2634 	 * Make sure that conn is not marked incipient
2635 	 * for incoming connections. A blind
2636 	 * removal of incipient flag is cheaper than
2637 	 * check and removal.
2638 	 */
2639 	mutex_enter(&connp->conn_lock);
2640 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2641 	mutex_exit(&connp->conn_lock);
2642 	return (0);
2643 }
2644 
2645 static void
2646 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
2647 {
2648 	int	error;
2649 	conn_t	*connp = tcp->tcp_connp;
2650 	struct sockaddr	*sa;
2651 	mblk_t  *mp1;
2652 	struct T_bind_req *tbr;
2653 	int	backlog;
2654 	socklen_t	len;
2655 	sin_t	*sin;
2656 	sin6_t	*sin6;
2657 	cred_t		*cr;
2658 
2659 	/*
2660 	 * All Solaris components should pass a db_credp
2661 	 * for this TPI message, hence we ASSERT.
2662 	 * But in case there is some other M_PROTO that looks
2663 	 * like a TPI message sent by some other kernel
2664 	 * component, we check and return an error.
2665 	 */
2666 	cr = msg_getcred(mp, NULL);
2667 	ASSERT(cr != NULL);
2668 	if (cr == NULL) {
2669 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
2670 		return;
2671 	}
2672 
2673 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
2674 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
2675 		if (connp->conn_debug) {
2676 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2677 			    "tcp_tpi_bind: bad req, len %u",
2678 			    (uint_t)(mp->b_wptr - mp->b_rptr));
2679 		}
2680 		tcp_err_ack(tcp, mp, TPROTO, 0);
2681 		return;
2682 	}
2683 	/* Make sure the largest address fits */
2684 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t), 1);
2685 	if (mp1 == NULL) {
2686 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
2687 		return;
2688 	}
2689 	mp = mp1;
2690 	tbr = (struct T_bind_req *)mp->b_rptr;
2691 
2692 	backlog = tbr->CONIND_number;
2693 	len = tbr->ADDR_length;
2694 
2695 	switch (len) {
2696 	case 0:		/* request for a generic port */
2697 		tbr->ADDR_offset = sizeof (struct T_bind_req);
2698 		if (connp->conn_family == AF_INET) {
2699 			tbr->ADDR_length = sizeof (sin_t);
2700 			sin = (sin_t *)&tbr[1];
2701 			*sin = sin_null;
2702 			sin->sin_family = AF_INET;
2703 			sa = (struct sockaddr *)sin;
2704 			len = sizeof (sin_t);
2705 			mp->b_wptr = (uchar_t *)&sin[1];
2706 		} else {
2707 			ASSERT(connp->conn_family == AF_INET6);
2708 			tbr->ADDR_length = sizeof (sin6_t);
2709 			sin6 = (sin6_t *)&tbr[1];
2710 			*sin6 = sin6_null;
2711 			sin6->sin6_family = AF_INET6;
2712 			sa = (struct sockaddr *)sin6;
2713 			len = sizeof (sin6_t);
2714 			mp->b_wptr = (uchar_t *)&sin6[1];
2715 		}
2716 		break;
2717 
2718 	case sizeof (sin_t):    /* Complete IPv4 address */
2719 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
2720 		    sizeof (sin_t));
2721 		break;
2722 
2723 	case sizeof (sin6_t): /* Complete IPv6 address */
2724 		sa = (struct sockaddr *)mi_offset_param(mp,
2725 		    tbr->ADDR_offset, sizeof (sin6_t));
2726 		break;
2727 
2728 	default:
2729 		if (connp->conn_debug) {
2730 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
2731 			    "tcp_tpi_bind: bad address length, %d",
2732 			    tbr->ADDR_length);
2733 		}
2734 		tcp_err_ack(tcp, mp, TBADADDR, 0);
2735 		return;
2736 	}
2737 
2738 	if (backlog > 0) {
2739 		error = tcp_do_listen(connp, sa, len, backlog, DB_CRED(mp),
2740 		    tbr->PRIM_type != O_T_BIND_REQ);
2741 	} else {
2742 		error = tcp_do_bind(connp, sa, len, DB_CRED(mp),
2743 		    tbr->PRIM_type != O_T_BIND_REQ);
2744 	}
2745 done:
2746 	if (error > 0) {
2747 		tcp_err_ack(tcp, mp, TSYSERR, error);
2748 	} else if (error < 0) {
2749 		tcp_err_ack(tcp, mp, -error, 0);
2750 	} else {
2751 		/*
2752 		 * Update port information as sockfs/tpi needs it for checking
2753 		 */
2754 		if (connp->conn_family == AF_INET) {
2755 			sin = (sin_t *)sa;
2756 			sin->sin_port = connp->conn_lport;
2757 		} else {
2758 			sin6 = (sin6_t *)sa;
2759 			sin6->sin6_port = connp->conn_lport;
2760 		}
2761 		mp->b_datap->db_type = M_PCPROTO;
2762 		tbr->PRIM_type = T_BIND_ACK;
2763 		putnext(connp->conn_rq, mp);
2764 	}
2765 }
2766 
2767 /*
2768  * If the "bind_to_req_port_only" parameter is set, if the requested port
2769  * number is available, return it, If not return 0
2770  *
2771  * If "bind_to_req_port_only" parameter is not set and
2772  * If the requested port number is available, return it.  If not, return
2773  * the first anonymous port we happen across.  If no anonymous ports are
2774  * available, return 0. addr is the requested local address, if any.
2775  *
2776  * In either case, when succeeding update the tcp_t to record the port number
2777  * and insert it in the bind hash table.
2778  *
2779  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
2780  * without setting SO_REUSEADDR. This is needed so that they
2781  * can be viewed as two independent transport protocols.
2782  */
2783 static in_port_t
2784 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
2785     int reuseaddr, boolean_t quick_connect,
2786     boolean_t bind_to_req_port_only, boolean_t user_specified)
2787 {
2788 	/* number of times we have run around the loop */
2789 	int count = 0;
2790 	/* maximum number of times to run around the loop */
2791 	int loopmax;
2792 	conn_t *connp = tcp->tcp_connp;
2793 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2794 
2795 	/*
2796 	 * Lookup for free addresses is done in a loop and "loopmax"
2797 	 * influences how long we spin in the loop
2798 	 */
2799 	if (bind_to_req_port_only) {
2800 		/*
2801 		 * If the requested port is busy, don't bother to look
2802 		 * for a new one. Setting loop maximum count to 1 has
2803 		 * that effect.
2804 		 */
2805 		loopmax = 1;
2806 	} else {
2807 		/*
2808 		 * If the requested port is busy, look for a free one
2809 		 * in the anonymous port range.
2810 		 * Set loopmax appropriately so that one does not look
2811 		 * forever in the case all of the anonymous ports are in use.
2812 		 */
2813 		if (connp->conn_anon_priv_bind) {
2814 			/*
2815 			 * loopmax =
2816 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
2817 			 */
2818 			loopmax = IPPORT_RESERVED -
2819 			    tcps->tcps_min_anonpriv_port;
2820 		} else {
2821 			loopmax = (tcps->tcps_largest_anon_port -
2822 			    tcps->tcps_smallest_anon_port + 1);
2823 		}
2824 	}
2825 	do {
2826 		uint16_t	lport;
2827 		tf_t		*tbf;
2828 		tcp_t		*ltcp;
2829 		conn_t		*lconnp;
2830 
2831 		lport = htons(port);
2832 
2833 		/*
2834 		 * Ensure that the tcp_t is not currently in the bind hash.
2835 		 * Hold the lock on the hash bucket to ensure that
2836 		 * the duplicate check plus the insertion is an atomic
2837 		 * operation.
2838 		 *
2839 		 * This function does an inline lookup on the bind hash list
2840 		 * Make sure that we access only members of tcp_t
2841 		 * and that we don't look at tcp_tcp, since we are not
2842 		 * doing a CONN_INC_REF.
2843 		 */
2844 		tcp_bind_hash_remove(tcp);
2845 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
2846 		mutex_enter(&tbf->tf_lock);
2847 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
2848 		    ltcp = ltcp->tcp_bind_hash) {
2849 			if (lport == ltcp->tcp_connp->conn_lport)
2850 				break;
2851 		}
2852 
2853 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
2854 			boolean_t not_socket;
2855 			boolean_t exclbind;
2856 
2857 			lconnp = ltcp->tcp_connp;
2858 
2859 			/*
2860 			 * On a labeled system, we must treat bindings to ports
2861 			 * on shared IP addresses by sockets with MAC exemption
2862 			 * privilege as being in all zones, as there's
2863 			 * otherwise no way to identify the right receiver.
2864 			 */
2865 			if (!IPCL_BIND_ZONE_MATCH(lconnp, connp))
2866 				continue;
2867 
2868 			/*
2869 			 * If TCP_EXCLBIND is set for either the bound or
2870 			 * binding endpoint, the semantics of bind
2871 			 * is changed according to the following.
2872 			 *
2873 			 * spec = specified address (v4 or v6)
2874 			 * unspec = unspecified address (v4 or v6)
2875 			 * A = specified addresses are different for endpoints
2876 			 *
2877 			 * bound	bind to		allowed
2878 			 * -------------------------------------
2879 			 * unspec	unspec		no
2880 			 * unspec	spec		no
2881 			 * spec		unspec		no
2882 			 * spec		spec		yes if A
2883 			 *
2884 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
2885 			 * as TCP_EXCLBIND, except that zoneid is ignored.
2886 			 *
2887 			 * Note:
2888 			 *
2889 			 * 1. Because of TLI semantics, an endpoint can go
2890 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
2891 			 * TCPS_BOUND, depending on whether it is originally
2892 			 * a listener or not.  That is why we need to check
2893 			 * for states greater than or equal to TCPS_BOUND
2894 			 * here.
2895 			 *
2896 			 * 2. Ideally, we should only check for state equals
2897 			 * to TCPS_LISTEN. And the following check should be
2898 			 * added.
2899 			 *
2900 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
2901 			 *	!reuseaddr || !lconnp->conn_reuseaddr) {
2902 			 *		...
2903 			 * }
2904 			 *
2905 			 * The semantics will be changed to this.  If the
2906 			 * endpoint on the list is in state not equal to
2907 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
2908 			 * set, let the bind succeed.
2909 			 *
2910 			 * Because of (1), we cannot do that for TLI
2911 			 * endpoints.  But we can do that for socket endpoints.
2912 			 * If in future, we can change this going back
2913 			 * semantics, we can use the above check for TLI also.
2914 			 */
2915 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
2916 			    TCP_IS_SOCKET(tcp));
2917 			exclbind = lconnp->conn_exclbind ||
2918 			    connp->conn_exclbind;
2919 
2920 			if ((lconnp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2921 			    (connp->conn_mac_mode != CONN_MAC_DEFAULT) ||
2922 			    (exclbind && (not_socket ||
2923 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
2924 				if (V6_OR_V4_INADDR_ANY(
2925 				    lconnp->conn_bound_addr_v6) ||
2926 				    V6_OR_V4_INADDR_ANY(*laddr) ||
2927 				    IN6_ARE_ADDR_EQUAL(laddr,
2928 				    &lconnp->conn_bound_addr_v6)) {
2929 					break;
2930 				}
2931 				continue;
2932 			}
2933 
2934 			/*
2935 			 * Check ipversion to allow IPv4 and IPv6 sockets to
2936 			 * have disjoint port number spaces, if *_EXCLBIND
2937 			 * is not set and only if the application binds to a
2938 			 * specific port. We use the same autoassigned port
2939 			 * number space for IPv4 and IPv6 sockets.
2940 			 */
2941 			if (connp->conn_ipversion != lconnp->conn_ipversion &&
2942 			    bind_to_req_port_only)
2943 				continue;
2944 
2945 			/*
2946 			 * Ideally, we should make sure that the source
2947 			 * address, remote address, and remote port in the
2948 			 * four tuple for this tcp-connection is unique.
2949 			 * However, trying to find out the local source
2950 			 * address would require too much code duplication
2951 			 * with IP, since IP needs needs to have that code
2952 			 * to support userland TCP implementations.
2953 			 */
2954 			if (quick_connect &&
2955 			    (ltcp->tcp_state > TCPS_LISTEN) &&
2956 			    ((connp->conn_fport != lconnp->conn_fport) ||
2957 			    !IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
2958 			    &lconnp->conn_faddr_v6)))
2959 				continue;
2960 
2961 			if (!reuseaddr) {
2962 				/*
2963 				 * No socket option SO_REUSEADDR.
2964 				 * If existing port is bound to
2965 				 * a non-wildcard IP address
2966 				 * and the requesting stream is
2967 				 * bound to a distinct
2968 				 * different IP addresses
2969 				 * (non-wildcard, also), keep
2970 				 * going.
2971 				 */
2972 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
2973 				    !V6_OR_V4_INADDR_ANY(
2974 				    lconnp->conn_bound_addr_v6) &&
2975 				    !IN6_ARE_ADDR_EQUAL(laddr,
2976 				    &lconnp->conn_bound_addr_v6))
2977 					continue;
2978 				if (ltcp->tcp_state >= TCPS_BOUND) {
2979 					/*
2980 					 * This port is being used and
2981 					 * its state is >= TCPS_BOUND,
2982 					 * so we can't bind to it.
2983 					 */
2984 					break;
2985 				}
2986 			} else {
2987 				/*
2988 				 * socket option SO_REUSEADDR is set on the
2989 				 * binding tcp_t.
2990 				 *
2991 				 * If two streams are bound to
2992 				 * same IP address or both addr
2993 				 * and bound source are wildcards
2994 				 * (INADDR_ANY), we want to stop
2995 				 * searching.
2996 				 * We have found a match of IP source
2997 				 * address and source port, which is
2998 				 * refused regardless of the
2999 				 * SO_REUSEADDR setting, so we break.
3000 				 */
3001 				if (IN6_ARE_ADDR_EQUAL(laddr,
3002 				    &lconnp->conn_bound_addr_v6) &&
3003 				    (ltcp->tcp_state == TCPS_LISTEN ||
3004 				    ltcp->tcp_state == TCPS_BOUND))
3005 					break;
3006 			}
3007 		}
3008 		if (ltcp != NULL) {
3009 			/* The port number is busy */
3010 			mutex_exit(&tbf->tf_lock);
3011 		} else {
3012 			/*
3013 			 * This port is ours. Insert in fanout and mark as
3014 			 * bound to prevent others from getting the port
3015 			 * number.
3016 			 */
3017 			tcp->tcp_state = TCPS_BOUND;
3018 			connp->conn_lport = htons(port);
3019 
3020 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3021 			    connp->conn_lport)] == tbf);
3022 			tcp_bind_hash_insert(tbf, tcp, 1);
3023 
3024 			mutex_exit(&tbf->tf_lock);
3025 
3026 			/*
3027 			 * We don't want tcp_next_port_to_try to "inherit"
3028 			 * a port number supplied by the user in a bind.
3029 			 */
3030 			if (user_specified)
3031 				return (port);
3032 
3033 			/*
3034 			 * This is the only place where tcp_next_port_to_try
3035 			 * is updated. After the update, it may or may not
3036 			 * be in the valid range.
3037 			 */
3038 			if (!connp->conn_anon_priv_bind)
3039 				tcps->tcps_next_port_to_try = port + 1;
3040 			return (port);
3041 		}
3042 
3043 		if (connp->conn_anon_priv_bind) {
3044 			port = tcp_get_next_priv_port(tcp);
3045 		} else {
3046 			if (count == 0 && user_specified) {
3047 				/*
3048 				 * We may have to return an anonymous port. So
3049 				 * get one to start with.
3050 				 */
3051 				port =
3052 				    tcp_update_next_port(
3053 				    tcps->tcps_next_port_to_try,
3054 				    tcp, B_TRUE);
3055 				user_specified = B_FALSE;
3056 			} else {
3057 				port = tcp_update_next_port(port + 1, tcp,
3058 				    B_FALSE);
3059 			}
3060 		}
3061 		if (port == 0)
3062 			break;
3063 
3064 		/*
3065 		 * Don't let this loop run forever in the case where
3066 		 * all of the anonymous ports are in use.
3067 		 */
3068 	} while (++count < loopmax);
3069 	return (0);
3070 }
3071 
3072 /*
3073  * tcp_clean_death / tcp_close_detached must not be called more than once
3074  * on a tcp. Thus every function that potentially calls tcp_clean_death
3075  * must check for the tcp state before calling tcp_clean_death.
3076  * Eg. tcp_input_data, tcp_eager_kill, tcp_clean_death_wrapper,
3077  * tcp_timer_handler, all check for the tcp state.
3078  */
3079 /* ARGSUSED */
3080 void
3081 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2,
3082     ip_recv_attr_t *dummy)
3083 {
3084 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3085 
3086 	freemsg(mp);
3087 	if (tcp->tcp_state > TCPS_BOUND)
3088 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3089 		    ETIMEDOUT, 5);
3090 }
3091 
3092 /*
3093  * We are dying for some reason.  Try to do it gracefully.  (May be called
3094  * as writer.)
3095  *
3096  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3097  * done by a service procedure).
3098  * TBD - Should the return value distinguish between the tcp_t being
3099  * freed and it being reinitialized?
3100  */
3101 static int
3102 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3103 {
3104 	mblk_t	*mp;
3105 	queue_t	*q;
3106 	conn_t	*connp = tcp->tcp_connp;
3107 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3108 
3109 	TCP_CLD_STAT(tag);
3110 
3111 #if TCP_TAG_CLEAN_DEATH
3112 	tcp->tcp_cleandeathtag = tag;
3113 #endif
3114 
3115 	if (tcp->tcp_fused)
3116 		tcp_unfuse(tcp);
3117 
3118 	if (tcp->tcp_linger_tid != 0 &&
3119 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3120 		tcp_stop_lingering(tcp);
3121 	}
3122 
3123 	ASSERT(tcp != NULL);
3124 	ASSERT((connp->conn_family == AF_INET &&
3125 	    connp->conn_ipversion == IPV4_VERSION) ||
3126 	    (connp->conn_family == AF_INET6 &&
3127 	    (connp->conn_ipversion == IPV4_VERSION ||
3128 	    connp->conn_ipversion == IPV6_VERSION)));
3129 
3130 	if (TCP_IS_DETACHED(tcp)) {
3131 		if (tcp->tcp_hard_binding) {
3132 			/*
3133 			 * Its an eager that we are dealing with. We close the
3134 			 * eager but in case a conn_ind has already gone to the
3135 			 * listener, let tcp_accept_finish() send a discon_ind
3136 			 * to the listener and drop the last reference. If the
3137 			 * listener doesn't even know about the eager i.e. the
3138 			 * conn_ind hasn't gone up, blow away the eager and drop
3139 			 * the last reference as well. If the conn_ind has gone
3140 			 * up, state should be BOUND. tcp_accept_finish
3141 			 * will figure out that the connection has received a
3142 			 * RST and will send a DISCON_IND to the application.
3143 			 */
3144 			tcp_closei_local(tcp);
3145 			if (!tcp->tcp_tconnind_started) {
3146 				CONN_DEC_REF(connp);
3147 			} else {
3148 				tcp->tcp_state = TCPS_BOUND;
3149 			}
3150 		} else {
3151 			tcp_close_detached(tcp);
3152 		}
3153 		return (0);
3154 	}
3155 
3156 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3157 
3158 	/*
3159 	 * The connection is dead.  Decrement listener connection counter if
3160 	 * necessary.
3161 	 */
3162 	if (tcp->tcp_listen_cnt != NULL)
3163 		TCP_DECR_LISTEN_CNT(tcp);
3164 
3165 	q = connp->conn_rq;
3166 
3167 	/* Trash all inbound data */
3168 	if (!IPCL_IS_NONSTR(connp)) {
3169 		ASSERT(q != NULL);
3170 		flushq(q, FLUSHALL);
3171 	}
3172 
3173 	/*
3174 	 * If we are at least part way open and there is error
3175 	 * (err==0 implies no error)
3176 	 * notify our client by a T_DISCON_IND.
3177 	 */
3178 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3179 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3180 		    !TCP_IS_SOCKET(tcp)) {
3181 			/*
3182 			 * Send M_FLUSH according to TPI. Because sockets will
3183 			 * (and must) ignore FLUSHR we do that only for TPI
3184 			 * endpoints and sockets in STREAMS mode.
3185 			 */
3186 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3187 		}
3188 		if (connp->conn_debug) {
3189 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3190 			    "tcp_clean_death: discon err %d", err);
3191 		}
3192 		if (IPCL_IS_NONSTR(connp)) {
3193 			/* Direct socket, use upcall */
3194 			(*connp->conn_upcalls->su_disconnected)(
3195 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3196 		} else {
3197 			mp = mi_tpi_discon_ind(NULL, err, 0);
3198 			if (mp != NULL) {
3199 				putnext(q, mp);
3200 			} else {
3201 				if (connp->conn_debug) {
3202 					(void) strlog(TCP_MOD_ID, 0, 1,
3203 					    SL_ERROR|SL_TRACE,
3204 					    "tcp_clean_death, sending M_ERROR");
3205 				}
3206 				(void) putnextctl1(q, M_ERROR, EPROTO);
3207 			}
3208 		}
3209 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3210 			/* SYN_SENT or SYN_RCVD */
3211 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3212 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3213 			/* ESTABLISHED or CLOSE_WAIT */
3214 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3215 		}
3216 	}
3217 
3218 	tcp_reinit(tcp);
3219 	if (IPCL_IS_NONSTR(connp))
3220 		(void) tcp_do_unbind(connp);
3221 
3222 	return (-1);
3223 }
3224 
3225 /*
3226  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3227  * to expire, stop the wait and finish the close.
3228  */
3229 static void
3230 tcp_stop_lingering(tcp_t *tcp)
3231 {
3232 	clock_t	delta = 0;
3233 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3234 	conn_t		*connp = tcp->tcp_connp;
3235 
3236 	tcp->tcp_linger_tid = 0;
3237 	if (tcp->tcp_state > TCPS_LISTEN) {
3238 		tcp_acceptor_hash_remove(tcp);
3239 		mutex_enter(&tcp->tcp_non_sq_lock);
3240 		if (tcp->tcp_flow_stopped) {
3241 			tcp_clrqfull(tcp);
3242 		}
3243 		mutex_exit(&tcp->tcp_non_sq_lock);
3244 
3245 		if (tcp->tcp_timer_tid != 0) {
3246 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3247 			tcp->tcp_timer_tid = 0;
3248 		}
3249 		/*
3250 		 * Need to cancel those timers which will not be used when
3251 		 * TCP is detached.  This has to be done before the conn_wq
3252 		 * is cleared.
3253 		 */
3254 		tcp_timers_stop(tcp);
3255 
3256 		tcp->tcp_detached = B_TRUE;
3257 		connp->conn_rq = NULL;
3258 		connp->conn_wq = NULL;
3259 
3260 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3261 			tcp_time_wait_append(tcp);
3262 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3263 			goto finish;
3264 		}
3265 
3266 		/*
3267 		 * If delta is zero the timer event wasn't executed and was
3268 		 * successfully canceled. In this case we need to restart it
3269 		 * with the minimal delta possible.
3270 		 */
3271 		if (delta >= 0) {
3272 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3273 			    delta ? delta : 1);
3274 		}
3275 	} else {
3276 		tcp_closei_local(tcp);
3277 		CONN_DEC_REF(connp);
3278 	}
3279 finish:
3280 	/* Signal closing thread that it can complete close */
3281 	mutex_enter(&tcp->tcp_closelock);
3282 	tcp->tcp_detached = B_TRUE;
3283 	connp->conn_rq = NULL;
3284 	connp->conn_wq = NULL;
3285 
3286 	tcp->tcp_closed = 1;
3287 	cv_signal(&tcp->tcp_closecv);
3288 	mutex_exit(&tcp->tcp_closelock);
3289 }
3290 
3291 /*
3292  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3293  * expires.
3294  */
3295 static void
3296 tcp_close_linger_timeout(void *arg)
3297 {
3298 	conn_t	*connp = (conn_t *)arg;
3299 	tcp_t 	*tcp = connp->conn_tcp;
3300 
3301 	tcp->tcp_client_errno = ETIMEDOUT;
3302 	tcp_stop_lingering(tcp);
3303 }
3304 
3305 static void
3306 tcp_close_common(conn_t *connp, int flags)
3307 {
3308 	tcp_t		*tcp = connp->conn_tcp;
3309 	mblk_t 		*mp = &tcp->tcp_closemp;
3310 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3311 	mblk_t		*bp;
3312 
3313 	ASSERT(connp->conn_ref >= 2);
3314 
3315 	/*
3316 	 * Mark the conn as closing. ipsq_pending_mp_add will not
3317 	 * add any mp to the pending mp list, after this conn has
3318 	 * started closing.
3319 	 */
3320 	mutex_enter(&connp->conn_lock);
3321 	connp->conn_state_flags |= CONN_CLOSING;
3322 	if (connp->conn_oper_pending_ill != NULL)
3323 		conn_ioctl_cleanup_reqd = B_TRUE;
3324 	CONN_INC_REF_LOCKED(connp);
3325 	mutex_exit(&connp->conn_lock);
3326 	tcp->tcp_closeflags = (uint8_t)flags;
3327 	ASSERT(connp->conn_ref >= 3);
3328 
3329 	/*
3330 	 * tcp_closemp_used is used below without any protection of a lock
3331 	 * as we don't expect any one else to use it concurrently at this
3332 	 * point otherwise it would be a major defect.
3333 	 */
3334 
3335 	if (mp->b_prev == NULL)
3336 		tcp->tcp_closemp_used = B_TRUE;
3337 	else
3338 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3339 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3340 
3341 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3342 
3343 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3344 	    NULL, tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3345 
3346 	mutex_enter(&tcp->tcp_closelock);
3347 	while (!tcp->tcp_closed) {
3348 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3349 			/*
3350 			 * The cv_wait_sig() was interrupted. We now do the
3351 			 * following:
3352 			 *
3353 			 * 1) If the endpoint was lingering, we allow this
3354 			 * to be interrupted by cancelling the linger timeout
3355 			 * and closing normally.
3356 			 *
3357 			 * 2) Revert to calling cv_wait()
3358 			 *
3359 			 * We revert to using cv_wait() to avoid an
3360 			 * infinite loop which can occur if the calling
3361 			 * thread is higher priority than the squeue worker
3362 			 * thread and is bound to the same cpu.
3363 			 */
3364 			if (connp->conn_linger && connp->conn_lingertime > 0) {
3365 				mutex_exit(&tcp->tcp_closelock);
3366 				/* Entering squeue, bump ref count. */
3367 				CONN_INC_REF(connp);
3368 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3369 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3370 				    tcp_linger_interrupted, connp, NULL,
3371 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3372 				mutex_enter(&tcp->tcp_closelock);
3373 			}
3374 			break;
3375 		}
3376 	}
3377 	while (!tcp->tcp_closed)
3378 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3379 	mutex_exit(&tcp->tcp_closelock);
3380 
3381 	/*
3382 	 * In the case of listener streams that have eagers in the q or q0
3383 	 * we wait for the eagers to drop their reference to us. conn_rq and
3384 	 * conn_wq of the eagers point to our queues. By waiting for the
3385 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3386 	 * up their queue pointers and also dropped their references to us.
3387 	 */
3388 	if (tcp->tcp_wait_for_eagers) {
3389 		mutex_enter(&connp->conn_lock);
3390 		while (connp->conn_ref != 1) {
3391 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3392 		}
3393 		mutex_exit(&connp->conn_lock);
3394 	}
3395 	/*
3396 	 * ioctl cleanup. The mp is queued in the ipx_pending_mp.
3397 	 */
3398 	if (conn_ioctl_cleanup_reqd)
3399 		conn_ioctl_cleanup(connp);
3400 
3401 	connp->conn_cpid = NOPID;
3402 }
3403 
3404 static int
3405 tcp_tpi_close(queue_t *q, int flags)
3406 {
3407 	conn_t		*connp;
3408 
3409 	ASSERT(WR(q)->q_next == NULL);
3410 
3411 	if (flags & SO_FALLBACK) {
3412 		/*
3413 		 * stream is being closed while in fallback
3414 		 * simply free the resources that were allocated
3415 		 */
3416 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3417 		qprocsoff(q);
3418 		goto done;
3419 	}
3420 
3421 	connp = Q_TO_CONN(q);
3422 	/*
3423 	 * We are being closed as /dev/tcp or /dev/tcp6.
3424 	 */
3425 	tcp_close_common(connp, flags);
3426 
3427 	qprocsoff(q);
3428 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3429 
3430 	/*
3431 	 * Drop IP's reference on the conn. This is the last reference
3432 	 * on the connp if the state was less than established. If the
3433 	 * connection has gone into timewait state, then we will have
3434 	 * one ref for the TCP and one more ref (total of two) for the
3435 	 * classifier connected hash list (a timewait connections stays
3436 	 * in connected hash till closed).
3437 	 *
3438 	 * We can't assert the references because there might be other
3439 	 * transient reference places because of some walkers or queued
3440 	 * packets in squeue for the timewait state.
3441 	 */
3442 	CONN_DEC_REF(connp);
3443 done:
3444 	q->q_ptr = WR(q)->q_ptr = NULL;
3445 	return (0);
3446 }
3447 
3448 static int
3449 tcp_tpi_close_accept(queue_t *q)
3450 {
3451 	vmem_t	*minor_arena;
3452 	dev_t	conn_dev;
3453 
3454 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3455 
3456 	/*
3457 	 * We had opened an acceptor STREAM for sockfs which is
3458 	 * now being closed due to some error.
3459 	 */
3460 	qprocsoff(q);
3461 
3462 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3463 	conn_dev = (dev_t)RD(q)->q_ptr;
3464 	ASSERT(minor_arena != NULL);
3465 	ASSERT(conn_dev != 0);
3466 	inet_minor_free(minor_arena, conn_dev);
3467 	q->q_ptr = WR(q)->q_ptr = NULL;
3468 	return (0);
3469 }
3470 
3471 /*
3472  * Called by tcp_close() routine via squeue when lingering is
3473  * interrupted by a signal.
3474  */
3475 
3476 /* ARGSUSED */
3477 static void
3478 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3479 {
3480 	conn_t	*connp = (conn_t *)arg;
3481 	tcp_t	*tcp = connp->conn_tcp;
3482 
3483 	freeb(mp);
3484 	if (tcp->tcp_linger_tid != 0 &&
3485 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3486 		tcp_stop_lingering(tcp);
3487 		tcp->tcp_client_errno = EINTR;
3488 	}
3489 }
3490 
3491 /*
3492  * Called by streams close routine via squeues when our client blows off her
3493  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3494  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3495  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3496  * acked.
3497  *
3498  * NOTE: tcp_close potentially returns error when lingering.
3499  * However, the stream head currently does not pass these errors
3500  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3501  * errors to the application (from tsleep()) and not errors
3502  * like ECONNRESET caused by receiving a reset packet.
3503  */
3504 
3505 /* ARGSUSED */
3506 static void
3507 tcp_close_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
3508 {
3509 	char	*msg;
3510 	conn_t	*connp = (conn_t *)arg;
3511 	tcp_t	*tcp = connp->conn_tcp;
3512 	clock_t	delta = 0;
3513 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3514 
3515 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3516 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3517 
3518 	mutex_enter(&tcp->tcp_eager_lock);
3519 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3520 		/* Cleanup for listener */
3521 		tcp_eager_cleanup(tcp, 0);
3522 		tcp->tcp_wait_for_eagers = 1;
3523 	}
3524 	mutex_exit(&tcp->tcp_eager_lock);
3525 
3526 	tcp->tcp_lso = B_FALSE;
3527 
3528 	msg = NULL;
3529 	switch (tcp->tcp_state) {
3530 	case TCPS_CLOSED:
3531 	case TCPS_IDLE:
3532 	case TCPS_BOUND:
3533 	case TCPS_LISTEN:
3534 		break;
3535 	case TCPS_SYN_SENT:
3536 		msg = "tcp_close, during connect";
3537 		break;
3538 	case TCPS_SYN_RCVD:
3539 		/*
3540 		 * Close during the connect 3-way handshake
3541 		 * but here there may or may not be pending data
3542 		 * already on queue. Process almost same as in
3543 		 * the ESTABLISHED state.
3544 		 */
3545 		/* FALLTHRU */
3546 	default:
3547 		if (tcp->tcp_fused)
3548 			tcp_unfuse(tcp);
3549 
3550 		/*
3551 		 * If SO_LINGER has set a zero linger time, abort the
3552 		 * connection with a reset.
3553 		 */
3554 		if (connp->conn_linger && connp->conn_lingertime == 0) {
3555 			msg = "tcp_close, zero lingertime";
3556 			break;
3557 		}
3558 
3559 		/*
3560 		 * Abort connection if there is unread data queued.
3561 		 */
3562 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3563 			msg = "tcp_close, unread data";
3564 			break;
3565 		}
3566 		/*
3567 		 * We have done a qwait() above which could have possibly
3568 		 * drained more messages in turn causing transition to a
3569 		 * different state. Check whether we have to do the rest
3570 		 * of the processing or not.
3571 		 */
3572 		if (tcp->tcp_state <= TCPS_LISTEN)
3573 			break;
3574 
3575 		/*
3576 		 * Transmit the FIN before detaching the tcp_t.
3577 		 * After tcp_detach returns this queue/perimeter
3578 		 * no longer owns the tcp_t thus others can modify it.
3579 		 */
3580 		(void) tcp_xmit_end(tcp);
3581 
3582 		/*
3583 		 * If lingering on close then wait until the fin is acked,
3584 		 * the SO_LINGER time passes, or a reset is sent/received.
3585 		 */
3586 		if (connp->conn_linger && connp->conn_lingertime > 0 &&
3587 		    !(tcp->tcp_fin_acked) &&
3588 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3589 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3590 				tcp->tcp_client_errno = EWOULDBLOCK;
3591 			} else if (tcp->tcp_client_errno == 0) {
3592 
3593 				ASSERT(tcp->tcp_linger_tid == 0);
3594 
3595 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3596 				    tcp_close_linger_timeout,
3597 				    connp->conn_lingertime * hz);
3598 
3599 				/* tcp_close_linger_timeout will finish close */
3600 				if (tcp->tcp_linger_tid == 0)
3601 					tcp->tcp_client_errno = ENOSR;
3602 				else
3603 					return;
3604 			}
3605 
3606 			/*
3607 			 * Check if we need to detach or just close
3608 			 * the instance.
3609 			 */
3610 			if (tcp->tcp_state <= TCPS_LISTEN)
3611 				break;
3612 		}
3613 
3614 		/*
3615 		 * Make sure that no other thread will access the conn_rq of
3616 		 * this instance (through lookups etc.) as conn_rq will go
3617 		 * away shortly.
3618 		 */
3619 		tcp_acceptor_hash_remove(tcp);
3620 
3621 		mutex_enter(&tcp->tcp_non_sq_lock);
3622 		if (tcp->tcp_flow_stopped) {
3623 			tcp_clrqfull(tcp);
3624 		}
3625 		mutex_exit(&tcp->tcp_non_sq_lock);
3626 
3627 		if (tcp->tcp_timer_tid != 0) {
3628 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3629 			tcp->tcp_timer_tid = 0;
3630 		}
3631 		/*
3632 		 * Need to cancel those timers which will not be used when
3633 		 * TCP is detached.  This has to be done before the conn_wq
3634 		 * is set to NULL.
3635 		 */
3636 		tcp_timers_stop(tcp);
3637 
3638 		tcp->tcp_detached = B_TRUE;
3639 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3640 			tcp_time_wait_append(tcp);
3641 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3642 			ASSERT(connp->conn_ref >= 3);
3643 			goto finish;
3644 		}
3645 
3646 		/*
3647 		 * If delta is zero the timer event wasn't executed and was
3648 		 * successfully canceled. In this case we need to restart it
3649 		 * with the minimal delta possible.
3650 		 */
3651 		if (delta >= 0)
3652 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3653 			    delta ? delta : 1);
3654 
3655 		ASSERT(connp->conn_ref >= 3);
3656 		goto finish;
3657 	}
3658 
3659 	/* Detach did not complete. Still need to remove q from stream. */
3660 	if (msg) {
3661 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
3662 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
3663 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3664 		if (tcp->tcp_state == TCPS_SYN_SENT ||
3665 		    tcp->tcp_state == TCPS_SYN_RCVD)
3666 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3667 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
3668 	}
3669 
3670 	tcp_closei_local(tcp);
3671 	CONN_DEC_REF(connp);
3672 	ASSERT(connp->conn_ref >= 2);
3673 
3674 finish:
3675 	mutex_enter(&tcp->tcp_closelock);
3676 	/*
3677 	 * Don't change the queues in the case of a listener that has
3678 	 * eagers in its q or q0. It could surprise the eagers.
3679 	 * Instead wait for the eagers outside the squeue.
3680 	 */
3681 	if (!tcp->tcp_wait_for_eagers) {
3682 		tcp->tcp_detached = B_TRUE;
3683 		connp->conn_rq = NULL;
3684 		connp->conn_wq = NULL;
3685 	}
3686 
3687 	/* Signal tcp_close() to finish closing. */
3688 	tcp->tcp_closed = 1;
3689 	cv_signal(&tcp->tcp_closecv);
3690 	mutex_exit(&tcp->tcp_closelock);
3691 }
3692 
3693 /*
3694  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
3695  * Some stream heads get upset if they see these later on as anything but NULL.
3696  */
3697 static void
3698 tcp_close_mpp(mblk_t **mpp)
3699 {
3700 	mblk_t	*mp;
3701 
3702 	if ((mp = *mpp) != NULL) {
3703 		do {
3704 			mp->b_next = NULL;
3705 			mp->b_prev = NULL;
3706 		} while ((mp = mp->b_cont) != NULL);
3707 
3708 		mp = *mpp;
3709 		*mpp = NULL;
3710 		freemsg(mp);
3711 	}
3712 }
3713 
3714 /* Do detached close. */
3715 static void
3716 tcp_close_detached(tcp_t *tcp)
3717 {
3718 	if (tcp->tcp_fused)
3719 		tcp_unfuse(tcp);
3720 
3721 	/*
3722 	 * Clustering code serializes TCP disconnect callbacks and
3723 	 * cluster tcp list walks by blocking a TCP disconnect callback
3724 	 * if a cluster tcp list walk is in progress. This ensures
3725 	 * accurate accounting of TCPs in the cluster code even though
3726 	 * the TCP list walk itself is not atomic.
3727 	 */
3728 	tcp_closei_local(tcp);
3729 	CONN_DEC_REF(tcp->tcp_connp);
3730 }
3731 
3732 /*
3733  * Stop all TCP timers, and free the timer mblks if requested.
3734  */
3735 void
3736 tcp_timers_stop(tcp_t *tcp)
3737 {
3738 	if (tcp->tcp_timer_tid != 0) {
3739 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3740 		tcp->tcp_timer_tid = 0;
3741 	}
3742 	if (tcp->tcp_ka_tid != 0) {
3743 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
3744 		tcp->tcp_ka_tid = 0;
3745 	}
3746 	if (tcp->tcp_ack_tid != 0) {
3747 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
3748 		tcp->tcp_ack_tid = 0;
3749 	}
3750 	if (tcp->tcp_push_tid != 0) {
3751 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
3752 		tcp->tcp_push_tid = 0;
3753 	}
3754 	if (tcp->tcp_reass_tid != 0) {
3755 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_reass_tid);
3756 		tcp->tcp_reass_tid = 0;
3757 	}
3758 }
3759 
3760 /*
3761  * The tcp_t is going away. Remove it from all lists and set it
3762  * to TCPS_CLOSED. The freeing up of memory is deferred until
3763  * tcp_inactive. This is needed since a thread in tcp_rput might have
3764  * done a CONN_INC_REF on this structure before it was removed from the
3765  * hashes.
3766  */
3767 static void
3768 tcp_closei_local(tcp_t *tcp)
3769 {
3770 	conn_t		*connp = tcp->tcp_connp;
3771 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3772 
3773 	if (!TCP_IS_SOCKET(tcp))
3774 		tcp_acceptor_hash_remove(tcp);
3775 
3776 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
3777 	tcp->tcp_ibsegs = 0;
3778 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
3779 	tcp->tcp_obsegs = 0;
3780 
3781 	/*
3782 	 * If we are an eager connection hanging off a listener that
3783 	 * hasn't formally accepted the connection yet, get off his
3784 	 * list and blow off any data that we have accumulated.
3785 	 */
3786 	if (tcp->tcp_listener != NULL) {
3787 		tcp_t	*listener = tcp->tcp_listener;
3788 		mutex_enter(&listener->tcp_eager_lock);
3789 		/*
3790 		 * tcp_tconnind_started == B_TRUE means that the
3791 		 * conn_ind has already gone to listener. At
3792 		 * this point, eager will be closed but we
3793 		 * leave it in listeners eager list so that
3794 		 * if listener decides to close without doing
3795 		 * accept, we can clean this up. In tcp_tli_accept
3796 		 * we take care of the case of accept on closed
3797 		 * eager.
3798 		 */
3799 		if (!tcp->tcp_tconnind_started) {
3800 			tcp_eager_unlink(tcp);
3801 			mutex_exit(&listener->tcp_eager_lock);
3802 			/*
3803 			 * We don't want to have any pointers to the
3804 			 * listener queue, after we have released our
3805 			 * reference on the listener
3806 			 */
3807 			ASSERT(tcp->tcp_detached);
3808 			connp->conn_rq = NULL;
3809 			connp->conn_wq = NULL;
3810 			CONN_DEC_REF(listener->tcp_connp);
3811 		} else {
3812 			mutex_exit(&listener->tcp_eager_lock);
3813 		}
3814 	}
3815 
3816 	/* Stop all the timers */
3817 	tcp_timers_stop(tcp);
3818 
3819 	if (tcp->tcp_state == TCPS_LISTEN) {
3820 		if (tcp->tcp_ip_addr_cache) {
3821 			kmem_free((void *)tcp->tcp_ip_addr_cache,
3822 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
3823 			tcp->tcp_ip_addr_cache = NULL;
3824 		}
3825 	}
3826 
3827 	/* Decrement listerner connection counter if necessary. */
3828 	if (tcp->tcp_listen_cnt != NULL)
3829 		TCP_DECR_LISTEN_CNT(tcp);
3830 
3831 	mutex_enter(&tcp->tcp_non_sq_lock);
3832 	if (tcp->tcp_flow_stopped)
3833 		tcp_clrqfull(tcp);
3834 	mutex_exit(&tcp->tcp_non_sq_lock);
3835 
3836 	tcp_bind_hash_remove(tcp);
3837 	/*
3838 	 * If the tcp_time_wait_collector (which runs outside the squeue)
3839 	 * is trying to remove this tcp from the time wait list, we will
3840 	 * block in tcp_time_wait_remove while trying to acquire the
3841 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
3842 	 * requires the ipcl_hash_remove to be ordered after the
3843 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
3844 	 */
3845 	if (tcp->tcp_state == TCPS_TIME_WAIT)
3846 		(void) tcp_time_wait_remove(tcp, NULL);
3847 	CL_INET_DISCONNECT(connp);
3848 	ipcl_hash_remove(connp);
3849 	ixa_cleanup(connp->conn_ixa);
3850 
3851 	/*
3852 	 * Mark the conn as CONDEMNED
3853 	 */
3854 	mutex_enter(&connp->conn_lock);
3855 	connp->conn_state_flags |= CONN_CONDEMNED;
3856 	mutex_exit(&connp->conn_lock);
3857 
3858 	/* Need to cleanup any pending ioctls */
3859 	ASSERT(tcp->tcp_time_wait_next == NULL);
3860 	ASSERT(tcp->tcp_time_wait_prev == NULL);
3861 	ASSERT(tcp->tcp_time_wait_expire == 0);
3862 	tcp->tcp_state = TCPS_CLOSED;
3863 
3864 	/* Release any SSL context */
3865 	if (tcp->tcp_kssl_ent != NULL) {
3866 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
3867 		tcp->tcp_kssl_ent = NULL;
3868 	}
3869 	if (tcp->tcp_kssl_ctx != NULL) {
3870 		kssl_release_ctx(tcp->tcp_kssl_ctx);
3871 		tcp->tcp_kssl_ctx = NULL;
3872 	}
3873 	tcp->tcp_kssl_pending = B_FALSE;
3874 
3875 	tcp_ipsec_cleanup(tcp);
3876 }
3877 
3878 /*
3879  * tcp is dying (called from ipcl_conn_destroy and error cases).
3880  * Free the tcp_t in either case.
3881  */
3882 void
3883 tcp_free(tcp_t *tcp)
3884 {
3885 	mblk_t		*mp;
3886 	conn_t		*connp = tcp->tcp_connp;
3887 
3888 	ASSERT(tcp != NULL);
3889 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
3890 
3891 	connp->conn_rq = NULL;
3892 	connp->conn_wq = NULL;
3893 
3894 	tcp_close_mpp(&tcp->tcp_xmit_head);
3895 	tcp_close_mpp(&tcp->tcp_reass_head);
3896 	if (tcp->tcp_rcv_list != NULL) {
3897 		/* Free b_next chain */
3898 		tcp_close_mpp(&tcp->tcp_rcv_list);
3899 	}
3900 	if ((mp = tcp->tcp_urp_mp) != NULL) {
3901 		freemsg(mp);
3902 	}
3903 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
3904 		freemsg(mp);
3905 	}
3906 
3907 	if (tcp->tcp_fused_sigurg_mp != NULL) {
3908 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3909 		freeb(tcp->tcp_fused_sigurg_mp);
3910 		tcp->tcp_fused_sigurg_mp = NULL;
3911 	}
3912 
3913 	if (tcp->tcp_ordrel_mp != NULL) {
3914 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
3915 		freeb(tcp->tcp_ordrel_mp);
3916 		tcp->tcp_ordrel_mp = NULL;
3917 	}
3918 
3919 	if (tcp->tcp_sack_info != NULL) {
3920 		if (tcp->tcp_notsack_list != NULL) {
3921 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
3922 			    tcp);
3923 		}
3924 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
3925 	}
3926 
3927 	if (tcp->tcp_hopopts != NULL) {
3928 		mi_free(tcp->tcp_hopopts);
3929 		tcp->tcp_hopopts = NULL;
3930 		tcp->tcp_hopoptslen = 0;
3931 	}
3932 	ASSERT(tcp->tcp_hopoptslen == 0);
3933 	if (tcp->tcp_dstopts != NULL) {
3934 		mi_free(tcp->tcp_dstopts);
3935 		tcp->tcp_dstopts = NULL;
3936 		tcp->tcp_dstoptslen = 0;
3937 	}
3938 	ASSERT(tcp->tcp_dstoptslen == 0);
3939 	if (tcp->tcp_rthdrdstopts != NULL) {
3940 		mi_free(tcp->tcp_rthdrdstopts);
3941 		tcp->tcp_rthdrdstopts = NULL;
3942 		tcp->tcp_rthdrdstoptslen = 0;
3943 	}
3944 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
3945 	if (tcp->tcp_rthdr != NULL) {
3946 		mi_free(tcp->tcp_rthdr);
3947 		tcp->tcp_rthdr = NULL;
3948 		tcp->tcp_rthdrlen = 0;
3949 	}
3950 	ASSERT(tcp->tcp_rthdrlen == 0);
3951 
3952 	/*
3953 	 * Following is really a blowing away a union.
3954 	 * It happens to have exactly two members of identical size
3955 	 * the following code is enough.
3956 	 */
3957 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
3958 }
3959 
3960 
3961 /*
3962  * Put a connection confirmation message upstream built from the
3963  * address/flowid information with the conn and iph. Report our success or
3964  * failure.
3965  */
3966 static boolean_t
3967 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, mblk_t *idmp,
3968     mblk_t **defermp, ip_recv_attr_t *ira)
3969 {
3970 	sin_t	sin;
3971 	sin6_t	sin6;
3972 	mblk_t	*mp;
3973 	char	*optp = NULL;
3974 	int	optlen = 0;
3975 	conn_t	*connp = tcp->tcp_connp;
3976 
3977 	if (defermp != NULL)
3978 		*defermp = NULL;
3979 
3980 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
3981 		/*
3982 		 * Return in T_CONN_CON results of option negotiation through
3983 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
3984 		 * negotiation, then what is received from remote end needs
3985 		 * to be taken into account but there is no such thing (yet?)
3986 		 * in our TCP/IP.
3987 		 * Note: We do not use mi_offset_param() here as
3988 		 * tcp_opts_conn_req contents do not directly come from
3989 		 * an application and are either generated in kernel or
3990 		 * from user input that was already verified.
3991 		 */
3992 		mp = tcp->tcp_conn.tcp_opts_conn_req;
3993 		optp = (char *)(mp->b_rptr +
3994 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
3995 		optlen = (int)
3996 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
3997 	}
3998 
3999 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4000 
4001 		/* packet is IPv4 */
4002 		if (connp->conn_family == AF_INET) {
4003 			sin = sin_null;
4004 			sin.sin_addr.s_addr = connp->conn_faddr_v4;
4005 			sin.sin_port = connp->conn_fport;
4006 			sin.sin_family = AF_INET;
4007 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4008 			    (int)sizeof (sin_t), optp, optlen);
4009 		} else {
4010 			sin6 = sin6_null;
4011 			sin6.sin6_addr = connp->conn_faddr_v6;
4012 			sin6.sin6_port = connp->conn_fport;
4013 			sin6.sin6_family = AF_INET6;
4014 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4015 			    (int)sizeof (sin6_t), optp, optlen);
4016 
4017 		}
4018 	} else {
4019 		ip6_t	*ip6h = (ip6_t *)iphdr;
4020 
4021 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4022 		ASSERT(connp->conn_family == AF_INET6);
4023 		sin6 = sin6_null;
4024 		sin6.sin6_addr = connp->conn_faddr_v6;
4025 		sin6.sin6_port = connp->conn_fport;
4026 		sin6.sin6_family = AF_INET6;
4027 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4028 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4029 		    (int)sizeof (sin6_t), optp, optlen);
4030 	}
4031 
4032 	if (!mp)
4033 		return (B_FALSE);
4034 
4035 	mblk_copycred(mp, idmp);
4036 
4037 	if (defermp == NULL) {
4038 		conn_t *connp = tcp->tcp_connp;
4039 		if (IPCL_IS_NONSTR(connp)) {
4040 			(*connp->conn_upcalls->su_connected)
4041 			    (connp->conn_upper_handle, tcp->tcp_connid,
4042 			    ira->ira_cred, ira->ira_cpid);
4043 			freemsg(mp);
4044 		} else {
4045 			if (ira->ira_cred != NULL) {
4046 				/* So that getpeerucred works for TPI sockfs */
4047 				mblk_setcred(mp, ira->ira_cred, ira->ira_cpid);
4048 			}
4049 			putnext(connp->conn_rq, mp);
4050 		}
4051 	} else {
4052 		*defermp = mp;
4053 	}
4054 
4055 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4056 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4057 	return (B_TRUE);
4058 }
4059 
4060 /*
4061  * Defense for the SYN attack -
4062  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4063  *    one from the list of droppable eagers. This list is a subset of q0.
4064  *    see comments before the definition of MAKE_DROPPABLE().
4065  * 2. Don't drop a SYN request before its first timeout. This gives every
4066  *    request at least til the first timeout to complete its 3-way handshake.
4067  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4068  *    requests currently on the queue that has timed out. This will be used
4069  *    as an indicator of whether an attack is under way, so that appropriate
4070  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4071  *    either when eager goes into ESTABLISHED, or gets freed up.)
4072  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4073  *    # of timeout drops back to <= q0len/32 => SYN alert off
4074  */
4075 static boolean_t
4076 tcp_drop_q0(tcp_t *tcp)
4077 {
4078 	tcp_t	*eager;
4079 	mblk_t	*mp;
4080 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4081 
4082 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4083 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4084 
4085 	/* Pick oldest eager from the list of droppable eagers */
4086 	eager = tcp->tcp_eager_prev_drop_q0;
4087 
4088 	/* If list is empty. return B_FALSE */
4089 	if (eager == tcp) {
4090 		return (B_FALSE);
4091 	}
4092 
4093 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4094 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4095 		return (B_FALSE);
4096 
4097 	/*
4098 	 * Take this eager out from the list of droppable eagers since we are
4099 	 * going to drop it.
4100 	 */
4101 	MAKE_UNDROPPABLE(eager);
4102 
4103 	if (tcp->tcp_connp->conn_debug) {
4104 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4105 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4106 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4107 		    tcp->tcp_conn_req_cnt_q0,
4108 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4109 	}
4110 
4111 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4112 
4113 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4114 	CONN_INC_REF(eager->tcp_connp);
4115 
4116 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4117 	    tcp_clean_death_wrapper, eager->tcp_connp, NULL,
4118 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4119 
4120 	return (B_TRUE);
4121 }
4122 
4123 /*
4124  * Handle a SYN on an AF_INET6 socket; can be either IPv4 or IPv6
4125  */
4126 static mblk_t *
4127 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4128     ip_recv_attr_t *ira)
4129 {
4130 	tcp_t 		*ltcp = lconnp->conn_tcp;
4131 	tcp_t		*tcp = connp->conn_tcp;
4132 	mblk_t		*tpi_mp;
4133 	ipha_t		*ipha;
4134 	ip6_t		*ip6h;
4135 	sin6_t 		sin6;
4136 	uint_t		ifindex = ira->ira_ruifindex;
4137 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4138 
4139 	if (ira->ira_flags & IRAF_IS_IPV4) {
4140 		ipha = (ipha_t *)mp->b_rptr;
4141 
4142 		connp->conn_ipversion = IPV4_VERSION;
4143 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4144 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4145 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4146 
4147 		sin6 = sin6_null;
4148 		sin6.sin6_addr = connp->conn_faddr_v6;
4149 		sin6.sin6_port = connp->conn_fport;
4150 		sin6.sin6_family = AF_INET6;
4151 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4152 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4153 
4154 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4155 			sin6_t	sin6d;
4156 
4157 			sin6d = sin6_null;
4158 			sin6d.sin6_addr = connp->conn_laddr_v6;
4159 			sin6d.sin6_port = connp->conn_lport;
4160 			sin6d.sin6_family = AF_INET;
4161 			tpi_mp = mi_tpi_extconn_ind(NULL,
4162 			    (char *)&sin6d, sizeof (sin6_t),
4163 			    (char *)&tcp,
4164 			    (t_scalar_t)sizeof (intptr_t),
4165 			    (char *)&sin6d, sizeof (sin6_t),
4166 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4167 		} else {
4168 			tpi_mp = mi_tpi_conn_ind(NULL,
4169 			    (char *)&sin6, sizeof (sin6_t),
4170 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4171 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4172 		}
4173 	} else {
4174 		ip6h = (ip6_t *)mp->b_rptr;
4175 
4176 		connp->conn_ipversion = IPV6_VERSION;
4177 		connp->conn_laddr_v6 = ip6h->ip6_dst;
4178 		connp->conn_faddr_v6 = ip6h->ip6_src;
4179 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
4180 
4181 		sin6 = sin6_null;
4182 		sin6.sin6_addr = connp->conn_faddr_v6;
4183 		sin6.sin6_port = connp->conn_fport;
4184 		sin6.sin6_family = AF_INET6;
4185 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4186 		sin6.__sin6_src_id = ip_srcid_find_addr(&connp->conn_laddr_v6,
4187 		    IPCL_ZONEID(lconnp), tcps->tcps_netstack);
4188 
4189 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4190 			/* Pass up the scope_id of remote addr */
4191 			sin6.sin6_scope_id = ifindex;
4192 		} else {
4193 			sin6.sin6_scope_id = 0;
4194 		}
4195 		if (connp->conn_recv_ancillary.crb_recvdstaddr) {
4196 			sin6_t	sin6d;
4197 
4198 			sin6d = sin6_null;
4199 			sin6.sin6_addr = connp->conn_laddr_v6;
4200 			sin6d.sin6_port = connp->conn_lport;
4201 			sin6d.sin6_family = AF_INET6;
4202 			if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_laddr_v6))
4203 				sin6d.sin6_scope_id = ifindex;
4204 
4205 			tpi_mp = mi_tpi_extconn_ind(NULL,
4206 			    (char *)&sin6d, sizeof (sin6_t),
4207 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4208 			    (char *)&sin6d, sizeof (sin6_t),
4209 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4210 		} else {
4211 			tpi_mp = mi_tpi_conn_ind(NULL,
4212 			    (char *)&sin6, sizeof (sin6_t),
4213 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4214 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4215 		}
4216 	}
4217 
4218 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4219 	return (tpi_mp);
4220 }
4221 
4222 /* Handle a SYN on an AF_INET socket */
4223 mblk_t *
4224 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4225     ip_recv_attr_t *ira)
4226 {
4227 	tcp_t 		*ltcp = lconnp->conn_tcp;
4228 	tcp_t		*tcp = connp->conn_tcp;
4229 	sin_t		sin;
4230 	mblk_t		*tpi_mp = NULL;
4231 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4232 	ipha_t		*ipha;
4233 
4234 	ASSERT(ira->ira_flags & IRAF_IS_IPV4);
4235 	ipha = (ipha_t *)mp->b_rptr;
4236 
4237 	connp->conn_ipversion = IPV4_VERSION;
4238 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_laddr_v6);
4239 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_faddr_v6);
4240 	connp->conn_saddr_v6 = connp->conn_laddr_v6;
4241 
4242 	sin = sin_null;
4243 	sin.sin_addr.s_addr = connp->conn_faddr_v4;
4244 	sin.sin_port = connp->conn_fport;
4245 	sin.sin_family = AF_INET;
4246 	if (lconnp->conn_recv_ancillary.crb_recvdstaddr) {
4247 		sin_t	sind;
4248 
4249 		sind = sin_null;
4250 		sind.sin_addr.s_addr = connp->conn_laddr_v4;
4251 		sind.sin_port = connp->conn_lport;
4252 		sind.sin_family = AF_INET;
4253 		tpi_mp = mi_tpi_extconn_ind(NULL,
4254 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4255 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4256 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4257 	} else {
4258 		tpi_mp = mi_tpi_conn_ind(NULL,
4259 		    (char *)&sin, sizeof (sin_t),
4260 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4261 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4262 	}
4263 
4264 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4265 	return (tpi_mp);
4266 }
4267 
4268 /*
4269  * tcp_get_conn/tcp_free_conn
4270  *
4271  * tcp_get_conn is used to get a clean tcp connection structure.
4272  * It tries to reuse the connections put on the freelist by the
4273  * time_wait_collector failing which it goes to kmem_cache. This
4274  * way has two benefits compared to just allocating from and
4275  * freeing to kmem_cache.
4276  * 1) The time_wait_collector can free (which includes the cleanup)
4277  * outside the squeue. So when the interrupt comes, we have a clean
4278  * connection sitting in the freelist. Obviously, this buys us
4279  * performance.
4280  *
4281  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_input_listener
4282  * has multiple disadvantages - tying up the squeue during alloc.
4283  * But allocating the conn/tcp in IP land is also not the best since
4284  * we can't check the 'q' and 'q0' which are protected by squeue and
4285  * blindly allocate memory which might have to be freed here if we are
4286  * not allowed to accept the connection. By using the freelist and
4287  * putting the conn/tcp back in freelist, we don't pay a penalty for
4288  * allocating memory without checking 'q/q0' and freeing it if we can't
4289  * accept the connection.
4290  *
4291  * Care should be taken to put the conn back in the same squeue's freelist
4292  * from which it was allocated. Best results are obtained if conn is
4293  * allocated from listener's squeue and freed to the same. Time wait
4294  * collector will free up the freelist is the connection ends up sitting
4295  * there for too long.
4296  */
4297 void *
4298 tcp_get_conn(void *arg, tcp_stack_t *tcps)
4299 {
4300 	tcp_t			*tcp = NULL;
4301 	conn_t			*connp = NULL;
4302 	squeue_t		*sqp = (squeue_t *)arg;
4303 	tcp_squeue_priv_t 	*tcp_time_wait;
4304 	netstack_t		*ns;
4305 	mblk_t			*tcp_rsrv_mp = NULL;
4306 
4307 	tcp_time_wait =
4308 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
4309 
4310 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
4311 	tcp = tcp_time_wait->tcp_free_list;
4312 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
4313 	if (tcp != NULL) {
4314 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
4315 		tcp_time_wait->tcp_free_list_cnt--;
4316 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4317 		tcp->tcp_time_wait_next = NULL;
4318 		connp = tcp->tcp_connp;
4319 		connp->conn_flags |= IPCL_REUSED;
4320 
4321 		ASSERT(tcp->tcp_tcps == NULL);
4322 		ASSERT(connp->conn_netstack == NULL);
4323 		ASSERT(tcp->tcp_rsrv_mp != NULL);
4324 		ns = tcps->tcps_netstack;
4325 		netstack_hold(ns);
4326 		connp->conn_netstack = ns;
4327 		connp->conn_ixa->ixa_ipst = ns->netstack_ip;
4328 		tcp->tcp_tcps = tcps;
4329 		ipcl_globalhash_insert(connp);
4330 
4331 		connp->conn_ixa->ixa_notify_cookie = tcp;
4332 		ASSERT(connp->conn_ixa->ixa_notify == tcp_notify);
4333 		connp->conn_recv = tcp_input_data;
4334 		ASSERT(connp->conn_recvicmp == tcp_icmp_input);
4335 		ASSERT(connp->conn_verifyicmp == tcp_verifyicmp);
4336 		return ((void *)connp);
4337 	}
4338 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
4339 	/*
4340 	 * Pre-allocate the tcp_rsrv_mp. This mblk will not be freed until
4341 	 * this conn_t/tcp_t is freed at ipcl_conn_destroy().
4342 	 */
4343 	tcp_rsrv_mp = allocb(0, BPRI_HI);
4344 	if (tcp_rsrv_mp == NULL)
4345 		return (NULL);
4346 
4347 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
4348 	    tcps->tcps_netstack)) == NULL) {
4349 		freeb(tcp_rsrv_mp);
4350 		return (NULL);
4351 	}
4352 
4353 	tcp = connp->conn_tcp;
4354 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
4355 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
4356 
4357 	tcp->tcp_tcps = tcps;
4358 
4359 	connp->conn_recv = tcp_input_data;
4360 	connp->conn_recvicmp = tcp_icmp_input;
4361 	connp->conn_verifyicmp = tcp_verifyicmp;
4362 
4363 	/*
4364 	 * Register tcp_notify to listen to capability changes detected by IP.
4365 	 * This upcall is made in the context of the call to conn_ip_output
4366 	 * thus it is inside the squeue.
4367 	 */
4368 	connp->conn_ixa->ixa_notify = tcp_notify;
4369 	connp->conn_ixa->ixa_notify_cookie = tcp;
4370 
4371 	return ((void *)connp);
4372 }
4373 
4374 /* BEGIN CSTYLED */
4375 /*
4376  *
4377  * The sockfs ACCEPT path:
4378  * =======================
4379  *
4380  * The eager is now established in its own perimeter as soon as SYN is
4381  * received in tcp_input_listener(). When sockfs receives conn_ind, it
4382  * completes the accept processing on the acceptor STREAM. The sending
4383  * of conn_ind part is common for both sockfs listener and a TLI/XTI
4384  * listener but a TLI/XTI listener completes the accept processing
4385  * on the listener perimeter.
4386  *
4387  * Common control flow for 3 way handshake:
4388  * ----------------------------------------
4389  *
4390  * incoming SYN (listener perimeter)	-> tcp_input_listener()
4391  *
4392  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_input_data()
4393  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
4394  *
4395  * Sockfs ACCEPT Path:
4396  * -------------------
4397  *
4398  * open acceptor stream (tcp_open allocates tcp_tli_accept()
4399  * as STREAM entry point)
4400  *
4401  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_tli_accept()
4402  *
4403  * tcp_tli_accept() extracts the eager and makes the q->q_ptr <-> eager
4404  * association (we are not behind eager's squeue but sockfs is protecting us
4405  * and no one knows about this stream yet. The STREAMS entry point q->q_info
4406  * is changed to point at tcp_wput().
4407  *
4408  * tcp_accept_common() sends any deferred eagers via tcp_send_pending() to
4409  * listener (done on listener's perimeter).
4410  *
4411  * tcp_tli_accept() calls tcp_accept_finish() on eagers perimeter to finish
4412  * accept.
4413  *
4414  * TLI/XTI client ACCEPT path:
4415  * ---------------------------
4416  *
4417  * soaccept() sends T_CONN_RES on the listener STREAM.
4418  *
4419  * tcp_tli_accept() -> tcp_accept_swap() complete the processing and send
4420  * a M_SETOPS mblk to eager perimeter to finish accept (tcp_accept_finish()).
4421  *
4422  * Locks:
4423  * ======
4424  *
4425  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
4426  * and listeners->tcp_eager_next_q.
4427  *
4428  * Referencing:
4429  * ============
4430  *
4431  * 1) We start out in tcp_input_listener by eager placing a ref on
4432  * listener and listener adding eager to listeners->tcp_eager_next_q0.
4433  *
4434  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
4435  * doing so we place a ref on the eager. This ref is finally dropped at the
4436  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
4437  * reference is dropped by the squeue framework.
4438  *
4439  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
4440  *
4441  * The reference must be released by the same entity that added the reference
4442  * In the above scheme, the eager is the entity that adds and releases the
4443  * references. Note that tcp_accept_finish executes in the squeue of the eager
4444  * (albeit after it is attached to the acceptor stream). Though 1. executes
4445  * in the listener's squeue, the eager is nascent at this point and the
4446  * reference can be considered to have been added on behalf of the eager.
4447  *
4448  * Eager getting a Reset or listener closing:
4449  * ==========================================
4450  *
4451  * Once the listener and eager are linked, the listener never does the unlink.
4452  * If the listener needs to close, tcp_eager_cleanup() is called which queues
4453  * a message on all eager perimeter. The eager then does the unlink, clears
4454  * any pointers to the listener's queue and drops the reference to the
4455  * listener. The listener waits in tcp_close outside the squeue until its
4456  * refcount has dropped to 1. This ensures that the listener has waited for
4457  * all eagers to clear their association with the listener.
4458  *
4459  * Similarly, if eager decides to go away, it can unlink itself and close.
4460  * When the T_CONN_RES comes down, we check if eager has closed. Note that
4461  * the reference to eager is still valid because of the extra ref we put
4462  * in tcp_send_conn_ind.
4463  *
4464  * Listener can always locate the eager under the protection
4465  * of the listener->tcp_eager_lock, and then do a refhold
4466  * on the eager during the accept processing.
4467  *
4468  * The acceptor stream accesses the eager in the accept processing
4469  * based on the ref placed on eager before sending T_conn_ind.
4470  * The only entity that can negate this refhold is a listener close
4471  * which is mutually exclusive with an active acceptor stream.
4472  *
4473  * Eager's reference on the listener
4474  * ===================================
4475  *
4476  * If the accept happens (even on a closed eager) the eager drops its
4477  * reference on the listener at the start of tcp_accept_finish. If the
4478  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
4479  * the reference is dropped in tcp_closei_local. If the listener closes,
4480  * the reference is dropped in tcp_eager_kill. In all cases the reference
4481  * is dropped while executing in the eager's context (squeue).
4482  */
4483 /* END CSTYLED */
4484 
4485 /* Process the SYN packet, mp, directed at the listener 'tcp' */
4486 
4487 /*
4488  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
4489  * tcp_input_data will not see any packets for listeners since the listener
4490  * has conn_recv set to tcp_input_listener.
4491  */
4492 /* ARGSUSED */
4493 void
4494 tcp_input_listener(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
4495 {
4496 	tcpha_t		*tcpha;
4497 	uint32_t	seg_seq;
4498 	tcp_t		*eager;
4499 	int		err;
4500 	conn_t		*econnp = NULL;
4501 	squeue_t	*new_sqp;
4502 	mblk_t		*mp1;
4503 	uint_t 		ip_hdr_len;
4504 	conn_t		*lconnp = (conn_t *)arg;
4505 	tcp_t		*listener = lconnp->conn_tcp;
4506 	tcp_stack_t	*tcps = listener->tcp_tcps;
4507 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
4508 	uint_t		flags;
4509 	mblk_t		*tpi_mp;
4510 	uint_t		ifindex = ira->ira_ruifindex;
4511 	boolean_t	tlc_set = B_FALSE;
4512 
4513 	ip_hdr_len = ira->ira_ip_hdr_length;
4514 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
4515 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
4516 
4517 	if (!(flags & TH_SYN)) {
4518 		if ((flags & TH_RST) || (flags & TH_URG)) {
4519 			freemsg(mp);
4520 			return;
4521 		}
4522 		if (flags & TH_ACK) {
4523 			/* Note this executes in listener's squeue */
4524 			tcp_xmit_listeners_reset(mp, ira, ipst, lconnp);
4525 			return;
4526 		}
4527 
4528 		freemsg(mp);
4529 		return;
4530 	}
4531 
4532 	if (listener->tcp_state != TCPS_LISTEN)
4533 		goto error2;
4534 
4535 	ASSERT(IPCL_IS_BOUND(lconnp));
4536 
4537 	mutex_enter(&listener->tcp_eager_lock);
4538 
4539 	/*
4540 	 * The system is under memory pressure, so we need to do our part
4541 	 * to relieve the pressure.  So we only accept new request if there
4542 	 * is nothing waiting to be accepted or waiting to complete the 3-way
4543 	 * handshake.  This means that busy listener will not get too many
4544 	 * new requests which they cannot handle in time while non-busy
4545 	 * listener is still functioning properly.
4546 	 */
4547 	if (tcps->tcps_reclaim && (listener->tcp_conn_req_cnt_q > 0 ||
4548 	    listener->tcp_conn_req_cnt_q0 > 0)) {
4549 		mutex_exit(&listener->tcp_eager_lock);
4550 		TCP_STAT(tcps, tcp_listen_mem_drop);
4551 		goto error2;
4552 	}
4553 
4554 	if (listener->tcp_conn_req_cnt_q >= listener->tcp_conn_req_max) {
4555 		mutex_exit(&listener->tcp_eager_lock);
4556 		TCP_STAT(tcps, tcp_listendrop);
4557 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
4558 		if (lconnp->conn_debug) {
4559 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
4560 			    "tcp_input_listener: listen backlog (max=%d) "
4561 			    "overflow (%d pending) on %s",
4562 			    listener->tcp_conn_req_max,
4563 			    listener->tcp_conn_req_cnt_q,
4564 			    tcp_display(listener, NULL, DISP_PORT_ONLY));
4565 		}
4566 		goto error2;
4567 	}
4568 
4569 	if (listener->tcp_conn_req_cnt_q0 >=
4570 	    listener->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
4571 		/*
4572 		 * Q0 is full. Drop a pending half-open req from the queue
4573 		 * to make room for the new SYN req. Also mark the time we
4574 		 * drop a SYN.
4575 		 *
4576 		 * A more aggressive defense against SYN attack will
4577 		 * be to set the "tcp_syn_defense" flag now.
4578 		 */
4579 		TCP_STAT(tcps, tcp_listendropq0);
4580 		listener->tcp_last_rcv_lbolt = ddi_get_lbolt64();
4581 		if (!tcp_drop_q0(listener)) {
4582 			mutex_exit(&listener->tcp_eager_lock);
4583 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
4584 			if (lconnp->conn_debug) {
4585 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4586 				    "tcp_input_listener: listen half-open "
4587 				    "queue (max=%d) full (%d pending) on %s",
4588 				    tcps->tcps_conn_req_max_q0,
4589 				    listener->tcp_conn_req_cnt_q0,
4590 				    tcp_display(listener, NULL,
4591 				    DISP_PORT_ONLY));
4592 			}
4593 			goto error2;
4594 		}
4595 	}
4596 
4597 	/*
4598 	 * Enforce the limit set on the number of connections per listener.
4599 	 * Note that tlc_cnt starts with 1.  So need to add 1 to tlc_max
4600 	 * for comparison.
4601 	 */
4602 	if (listener->tcp_listen_cnt != NULL) {
4603 		tcp_listen_cnt_t *tlc = listener->tcp_listen_cnt;
4604 		int64_t now;
4605 
4606 		if (atomic_add_32_nv(&tlc->tlc_cnt, 1) > tlc->tlc_max + 1) {
4607 			mutex_exit(&listener->tcp_eager_lock);
4608 			now = ddi_get_lbolt64();
4609 			atomic_add_32(&tlc->tlc_cnt, -1);
4610 			TCP_STAT(tcps, tcp_listen_cnt_drop);
4611 			tlc->tlc_drop++;
4612 			if (now - tlc->tlc_report_time >
4613 			    MSEC_TO_TICK(TCP_TLC_REPORT_INTERVAL)) {
4614 				zcmn_err(lconnp->conn_zoneid, CE_WARN,
4615 				    "Listener (port %d) connection max (%u) "
4616 				    "reached: %u attempts dropped total\n",
4617 				    ntohs(listener->tcp_connp->conn_lport),
4618 				    tlc->tlc_max, tlc->tlc_drop);
4619 				tlc->tlc_report_time = now;
4620 			}
4621 			goto error2;
4622 		}
4623 		tlc_set = B_TRUE;
4624 	}
4625 
4626 	mutex_exit(&listener->tcp_eager_lock);
4627 
4628 	/*
4629 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
4630 	 * or based on the ring (for packets from GLD). Otherwise it is
4631 	 * set based on lbolt i.e., a somewhat random number.
4632 	 */
4633 	ASSERT(ira->ira_sqp != NULL);
4634 	new_sqp = ira->ira_sqp;
4635 
4636 	econnp = (conn_t *)tcp_get_conn(arg2, tcps);
4637 	if (econnp == NULL)
4638 		goto error2;
4639 
4640 	ASSERT(econnp->conn_netstack == lconnp->conn_netstack);
4641 	econnp->conn_sqp = new_sqp;
4642 	econnp->conn_initial_sqp = new_sqp;
4643 	econnp->conn_ixa->ixa_sqp = new_sqp;
4644 
4645 	econnp->conn_fport = tcpha->tha_lport;
4646 	econnp->conn_lport = tcpha->tha_fport;
4647 
4648 	err = conn_inherit_parent(lconnp, econnp);
4649 	if (err != 0)
4650 		goto error3;
4651 
4652 	ASSERT(OK_32PTR(mp->b_rptr));
4653 	ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION ||
4654 	    IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
4655 
4656 	if (lconnp->conn_family == AF_INET) {
4657 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
4658 		tpi_mp = tcp_conn_create_v4(lconnp, econnp, mp, ira);
4659 	} else {
4660 		tpi_mp = tcp_conn_create_v6(lconnp, econnp, mp, ira);
4661 	}
4662 
4663 	if (tpi_mp == NULL)
4664 		goto error3;
4665 
4666 	eager = econnp->conn_tcp;
4667 	eager->tcp_detached = B_TRUE;
4668 	SOCK_CONNID_INIT(eager->tcp_connid);
4669 
4670 	tcp_init_values(eager);
4671 
4672 	ASSERT((econnp->conn_ixa->ixa_flags &
4673 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4674 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO)) ==
4675 	    (IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
4676 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO));
4677 
4678 	if (!tcps->tcps_dev_flow_ctl)
4679 		econnp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
4680 
4681 	/* Prepare for diffing against previous packets */
4682 	eager->tcp_recvifindex = 0;
4683 	eager->tcp_recvhops = 0xffffffffU;
4684 
4685 	if (!(ira->ira_flags & IRAF_IS_IPV4) && econnp->conn_bound_if == 0) {
4686 		if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_faddr_v6) ||
4687 		    IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6)) {
4688 			econnp->conn_incoming_ifindex = ifindex;
4689 			econnp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
4690 			econnp->conn_ixa->ixa_scopeid = ifindex;
4691 		}
4692 	}
4693 
4694 	if ((ira->ira_flags & (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS)) ==
4695 	    (IRAF_IS_IPV4|IRAF_IPV4_OPTIONS) &&
4696 	    tcps->tcps_rev_src_routes) {
4697 		ipha_t *ipha = (ipha_t *)mp->b_rptr;
4698 		ip_pkt_t *ipp = &econnp->conn_xmit_ipp;
4699 
4700 		/* Source routing option copyover (reverse it) */
4701 		err = ip_find_hdr_v4(ipha, ipp, B_TRUE);
4702 		if (err != 0) {
4703 			freemsg(tpi_mp);
4704 			goto error3;
4705 		}
4706 		ip_pkt_source_route_reverse_v4(ipp);
4707 	}
4708 
4709 	ASSERT(eager->tcp_conn.tcp_eager_conn_ind == NULL);
4710 	ASSERT(!eager->tcp_tconnind_started);
4711 	/*
4712 	 * If the SYN came with a credential, it's a loopback packet or a
4713 	 * labeled packet; attach the credential to the TPI message.
4714 	 */
4715 	if (ira->ira_cred != NULL)
4716 		mblk_setcred(tpi_mp, ira->ira_cred, ira->ira_cpid);
4717 
4718 	eager->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4719 
4720 	/* Inherit the listener's SSL protection state */
4721 	if ((eager->tcp_kssl_ent = listener->tcp_kssl_ent) != NULL) {
4722 		kssl_hold_ent(eager->tcp_kssl_ent);
4723 		eager->tcp_kssl_pending = B_TRUE;
4724 	}
4725 
4726 	/* Inherit the listener's non-STREAMS flag */
4727 	if (IPCL_IS_NONSTR(lconnp)) {
4728 		econnp->conn_flags |= IPCL_NONSTR;
4729 	}
4730 
4731 	ASSERT(eager->tcp_ordrel_mp == NULL);
4732 
4733 	if (!IPCL_IS_NONSTR(econnp)) {
4734 		/*
4735 		 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that
4736 		 * at close time, we will always have that to send up.
4737 		 * Otherwise, we need to do special handling in case the
4738 		 * allocation fails at that time.
4739 		 */
4740 		if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
4741 			goto error3;
4742 	}
4743 	/*
4744 	 * Now that the IP addresses and ports are setup in econnp we
4745 	 * can do the IPsec policy work.
4746 	 */
4747 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
4748 		if (lconnp->conn_policy != NULL) {
4749 			/*
4750 			 * Inherit the policy from the listener; use
4751 			 * actions from ira
4752 			 */
4753 			if (!ip_ipsec_policy_inherit(econnp, lconnp, ira)) {
4754 				CONN_DEC_REF(econnp);
4755 				freemsg(mp);
4756 				goto error3;
4757 			}
4758 		}
4759 	}
4760 
4761 	/* Inherit various TCP parameters from the listener */
4762 	eager->tcp_naglim = listener->tcp_naglim;
4763 	eager->tcp_first_timer_threshold = listener->tcp_first_timer_threshold;
4764 	eager->tcp_second_timer_threshold =
4765 	    listener->tcp_second_timer_threshold;
4766 	eager->tcp_first_ctimer_threshold =
4767 	    listener->tcp_first_ctimer_threshold;
4768 	eager->tcp_second_ctimer_threshold =
4769 	    listener->tcp_second_ctimer_threshold;
4770 
4771 	/*
4772 	 * tcp_set_destination() may set tcp_rwnd according to the route
4773 	 * metrics. If it does not, the eager's receive window will be set
4774 	 * to the listener's receive window later in this function.
4775 	 */
4776 	eager->tcp_rwnd = 0;
4777 
4778 	/*
4779 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
4780 	 * calling tcp_process_options() which set the initial cwnd.
4781 	 */
4782 	eager->tcp_init_cwnd = listener->tcp_init_cwnd;
4783 
4784 	if (is_system_labeled()) {
4785 		ip_xmit_attr_t *ixa = econnp->conn_ixa;
4786 
4787 		ASSERT(ira->ira_tsl != NULL);
4788 		/* Discard any old label */
4789 		if (ixa->ixa_free_flags & IXA_FREE_TSL) {
4790 			ASSERT(ixa->ixa_tsl != NULL);
4791 			label_rele(ixa->ixa_tsl);
4792 			ixa->ixa_free_flags &= ~IXA_FREE_TSL;
4793 			ixa->ixa_tsl = NULL;
4794 		}
4795 		if ((lconnp->conn_mlp_type != mlptSingle ||
4796 		    lconnp->conn_mac_mode != CONN_MAC_DEFAULT) &&
4797 		    ira->ira_tsl != NULL) {
4798 			/*
4799 			 * If this is an MLP connection or a MAC-Exempt
4800 			 * connection with an unlabeled node, packets are to be
4801 			 * exchanged using the security label of the received
4802 			 * SYN packet instead of the server application's label.
4803 			 * tsol_check_dest called from ip_set_destination
4804 			 * might later update TSF_UNLABELED by replacing
4805 			 * ixa_tsl with a new label.
4806 			 */
4807 			label_hold(ira->ira_tsl);
4808 			ip_xmit_attr_replace_tsl(ixa, ira->ira_tsl);
4809 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
4810 			    econnp, ts_label_t *, ixa->ixa_tsl)
4811 		} else {
4812 			ixa->ixa_tsl = crgetlabel(econnp->conn_cred);
4813 			DTRACE_PROBE2(syn_accept, conn_t *,
4814 			    econnp, ts_label_t *, ixa->ixa_tsl)
4815 		}
4816 		/*
4817 		 * conn_connect() called from tcp_set_destination will verify
4818 		 * the destination is allowed to receive packets at the
4819 		 * security label of the SYN-ACK we are generating. As part of
4820 		 * that, tsol_check_dest() may create a new effective label for
4821 		 * this connection.
4822 		 * Finally conn_connect() will call conn_update_label.
4823 		 * All that remains for TCP to do is to call
4824 		 * conn_build_hdr_template which is done as part of
4825 		 * tcp_set_destination.
4826 		 */
4827 	}
4828 
4829 	/*
4830 	 * Since we will clear tcp_listener before we clear tcp_detached
4831 	 * in the accept code we need tcp_hard_binding aka tcp_accept_inprogress
4832 	 * so we can tell a TCP_DETACHED_NONEAGER apart.
4833 	 */
4834 	eager->tcp_hard_binding = B_TRUE;
4835 
4836 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
4837 	    TCP_BIND_HASH(econnp->conn_lport)], eager, 0);
4838 
4839 	CL_INET_CONNECT(econnp, B_FALSE, err);
4840 	if (err != 0) {
4841 		tcp_bind_hash_remove(eager);
4842 		goto error3;
4843 	}
4844 
4845 	/*
4846 	 * No need to check for multicast destination since ip will only pass
4847 	 * up multicasts to those that have expressed interest
4848 	 * TODO: what about rejecting broadcasts?
4849 	 * Also check that source is not a multicast or broadcast address.
4850 	 */
4851 	eager->tcp_state = TCPS_SYN_RCVD;
4852 	SOCK_CONNID_BUMP(eager->tcp_connid);
4853 
4854 	/*
4855 	 * Adapt our mss, ttl, ... based on the remote address.
4856 	 */
4857 
4858 	if (tcp_set_destination(eager) != 0) {
4859 		BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4860 		/* Undo the bind_hash_insert */
4861 		tcp_bind_hash_remove(eager);
4862 		goto error3;
4863 	}
4864 
4865 	/* Process all TCP options. */
4866 	tcp_process_options(eager, tcpha);
4867 
4868 	/* Is the other end ECN capable? */
4869 	if (tcps->tcps_ecn_permitted >= 1 &&
4870 	    (tcpha->tha_flags & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
4871 		eager->tcp_ecn_ok = B_TRUE;
4872 	}
4873 
4874 	/*
4875 	 * The listener's conn_rcvbuf should be the default window size or a
4876 	 * window size changed via SO_RCVBUF option. First round up the
4877 	 * eager's tcp_rwnd to the nearest MSS. Then find out the window
4878 	 * scale option value if needed. Call tcp_rwnd_set() to finish the
4879 	 * setting.
4880 	 *
4881 	 * Note if there is a rpipe metric associated with the remote host,
4882 	 * we should not inherit receive window size from listener.
4883 	 */
4884 	eager->tcp_rwnd = MSS_ROUNDUP(
4885 	    (eager->tcp_rwnd == 0 ? econnp->conn_rcvbuf :
4886 	    eager->tcp_rwnd), eager->tcp_mss);
4887 	if (eager->tcp_snd_ws_ok)
4888 		tcp_set_ws_value(eager);
4889 	/*
4890 	 * Note that this is the only place tcp_rwnd_set() is called for
4891 	 * accepting a connection.  We need to call it here instead of
4892 	 * after the 3-way handshake because we need to tell the other
4893 	 * side our rwnd in the SYN-ACK segment.
4894 	 */
4895 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
4896 
4897 	ASSERT(eager->tcp_connp->conn_rcvbuf != 0 &&
4898 	    eager->tcp_connp->conn_rcvbuf == eager->tcp_rwnd);
4899 
4900 	ASSERT(econnp->conn_rcvbuf != 0 &&
4901 	    econnp->conn_rcvbuf == eager->tcp_rwnd);
4902 
4903 	/* Put a ref on the listener for the eager. */
4904 	CONN_INC_REF(lconnp);
4905 	mutex_enter(&listener->tcp_eager_lock);
4906 	listener->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
4907 	eager->tcp_eager_next_q0 = listener->tcp_eager_next_q0;
4908 	listener->tcp_eager_next_q0 = eager;
4909 	eager->tcp_eager_prev_q0 = listener;
4910 
4911 	/* Set tcp_listener before adding it to tcp_conn_fanout */
4912 	eager->tcp_listener = listener;
4913 	eager->tcp_saved_listener = listener;
4914 
4915 	/*
4916 	 * Set tcp_listen_cnt so that when the connection is done, the counter
4917 	 * is decremented.
4918 	 */
4919 	eager->tcp_listen_cnt = listener->tcp_listen_cnt;
4920 
4921 	/*
4922 	 * Tag this detached tcp vector for later retrieval
4923 	 * by our listener client in tcp_accept().
4924 	 */
4925 	eager->tcp_conn_req_seqnum = listener->tcp_conn_req_seqnum;
4926 	listener->tcp_conn_req_cnt_q0++;
4927 	if (++listener->tcp_conn_req_seqnum == -1) {
4928 		/*
4929 		 * -1 is "special" and defined in TPI as something
4930 		 * that should never be used in T_CONN_IND
4931 		 */
4932 		++listener->tcp_conn_req_seqnum;
4933 	}
4934 	mutex_exit(&listener->tcp_eager_lock);
4935 
4936 	if (listener->tcp_syn_defense) {
4937 		/* Don't drop the SYN that comes from a good IP source */
4938 		ipaddr_t *addr_cache;
4939 
4940 		addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
4941 		if (addr_cache != NULL && econnp->conn_faddr_v4 ==
4942 		    addr_cache[IP_ADDR_CACHE_HASH(econnp->conn_faddr_v4)]) {
4943 			eager->tcp_dontdrop = B_TRUE;
4944 		}
4945 	}
4946 
4947 	/*
4948 	 * We need to insert the eager in its own perimeter but as soon
4949 	 * as we do that, we expose the eager to the classifier and
4950 	 * should not touch any field outside the eager's perimeter.
4951 	 * So do all the work necessary before inserting the eager
4952 	 * in its own perimeter. Be optimistic that conn_connect()
4953 	 * will succeed but undo everything if it fails.
4954 	 */
4955 	seg_seq = ntohl(tcpha->tha_seq);
4956 	eager->tcp_irs = seg_seq;
4957 	eager->tcp_rack = seg_seq;
4958 	eager->tcp_rnxt = seg_seq + 1;
4959 	eager->tcp_tcpha->tha_ack = htonl(eager->tcp_rnxt);
4960 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
4961 	eager->tcp_state = TCPS_SYN_RCVD;
4962 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
4963 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
4964 	if (mp1 == NULL) {
4965 		/*
4966 		 * Increment the ref count as we are going to
4967 		 * enqueueing an mp in squeue
4968 		 */
4969 		CONN_INC_REF(econnp);
4970 		goto error;
4971 	}
4972 
4973 	/*
4974 	 * We need to start the rto timer. In normal case, we start
4975 	 * the timer after sending the packet on the wire (or at
4976 	 * least believing that packet was sent by waiting for
4977 	 * conn_ip_output() to return). Since this is the first packet
4978 	 * being sent on the wire for the eager, our initial tcp_rto
4979 	 * is at least tcp_rexmit_interval_min which is a fairly
4980 	 * large value to allow the algorithm to adjust slowly to large
4981 	 * fluctuations of RTT during first few transmissions.
4982 	 *
4983 	 * Starting the timer first and then sending the packet in this
4984 	 * case shouldn't make much difference since tcp_rexmit_interval_min
4985 	 * is of the order of several 100ms and starting the timer
4986 	 * first and then sending the packet will result in difference
4987 	 * of few micro seconds.
4988 	 *
4989 	 * Without this optimization, we are forced to hold the fanout
4990 	 * lock across the ipcl_bind_insert() and sending the packet
4991 	 * so that we don't race against an incoming packet (maybe RST)
4992 	 * for this eager.
4993 	 *
4994 	 * It is necessary to acquire an extra reference on the eager
4995 	 * at this point and hold it until after tcp_send_data() to
4996 	 * ensure against an eager close race.
4997 	 */
4998 
4999 	CONN_INC_REF(econnp);
5000 
5001 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5002 
5003 	/*
5004 	 * Insert the eager in its own perimeter now. We are ready to deal
5005 	 * with any packets on eager.
5006 	 */
5007 	if (ipcl_conn_insert(econnp) != 0)
5008 		goto error;
5009 
5010 	/*
5011 	 * Send the SYN-ACK. Can't use tcp_send_data since we can't update
5012 	 * pmtu etc; we are not on the eager's squeue
5013 	 */
5014 	ASSERT(econnp->conn_ixa->ixa_notify_cookie == econnp->conn_tcp);
5015 	(void) conn_ip_output(mp1, econnp->conn_ixa);
5016 	CONN_DEC_REF(econnp);
5017 	freemsg(mp);
5018 
5019 	return;
5020 error:
5021 	freemsg(mp1);
5022 	eager->tcp_closemp_used = B_TRUE;
5023 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5024 	mp1 = &eager->tcp_closemp;
5025 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5026 	    econnp, NULL, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5027 
5028 	/*
5029 	 * If a connection already exists, send the mp to that connections so
5030 	 * that it can be appropriately dealt with.
5031 	 */
5032 	ipst = tcps->tcps_netstack->netstack_ip;
5033 
5034 	if ((econnp = ipcl_classify(mp, ira, ipst)) != NULL) {
5035 		if (!IPCL_IS_CONNECTED(econnp)) {
5036 			/*
5037 			 * Something bad happened. ipcl_conn_insert()
5038 			 * failed because a connection already existed
5039 			 * in connected hash but we can't find it
5040 			 * anymore (someone blew it away). Just
5041 			 * free this message and hopefully remote
5042 			 * will retransmit at which time the SYN can be
5043 			 * treated as a new connection or dealth with
5044 			 * a TH_RST if a connection already exists.
5045 			 */
5046 			CONN_DEC_REF(econnp);
5047 			freemsg(mp);
5048 		} else {
5049 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp, tcp_input_data,
5050 			    econnp, ira, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5051 		}
5052 	} else {
5053 		/* Nobody wants this packet */
5054 		freemsg(mp);
5055 	}
5056 	return;
5057 error3:
5058 	CONN_DEC_REF(econnp);
5059 error2:
5060 	freemsg(mp);
5061 	if (tlc_set)
5062 		atomic_add_32(&listener->tcp_listen_cnt->tlc_cnt, -1);
5063 }
5064 
5065 /*
5066  * In an ideal case of vertical partition in NUMA architecture, its
5067  * beneficial to have the listener and all the incoming connections
5068  * tied to the same squeue. The other constraint is that incoming
5069  * connections should be tied to the squeue attached to interrupted
5070  * CPU for obvious locality reason so this leaves the listener to
5071  * be tied to the same squeue. Our only problem is that when listener
5072  * is binding, the CPU that will get interrupted by the NIC whose
5073  * IP address the listener is binding to is not even known. So
5074  * the code below allows us to change that binding at the time the
5075  * CPU is interrupted by virtue of incoming connection's squeue.
5076  *
5077  * This is usefull only in case of a listener bound to a specific IP
5078  * address. For other kind of listeners, they get bound the
5079  * very first time and there is no attempt to rebind them.
5080  */
5081 void
5082 tcp_input_listener_unbound(void *arg, mblk_t *mp, void *arg2,
5083     ip_recv_attr_t *ira)
5084 {
5085 	conn_t		*connp = (conn_t *)arg;
5086 	squeue_t	*sqp = (squeue_t *)arg2;
5087 	squeue_t	*new_sqp;
5088 	uint32_t	conn_flags;
5089 
5090 	/*
5091 	 * IP sets ira_sqp to either the senders conn_sqp (for loopback)
5092 	 * or based on the ring (for packets from GLD). Otherwise it is
5093 	 * set based on lbolt i.e., a somewhat random number.
5094 	 */
5095 	ASSERT(ira->ira_sqp != NULL);
5096 	new_sqp = ira->ira_sqp;
5097 
5098 	if (connp->conn_fanout == NULL)
5099 		goto done;
5100 
5101 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5102 		mutex_enter(&connp->conn_fanout->connf_lock);
5103 		mutex_enter(&connp->conn_lock);
5104 		/*
5105 		 * No one from read or write side can access us now
5106 		 * except for already queued packets on this squeue.
5107 		 * But since we haven't changed the squeue yet, they
5108 		 * can't execute. If they are processed after we have
5109 		 * changed the squeue, they are sent back to the
5110 		 * correct squeue down below.
5111 		 * But a listner close can race with processing of
5112 		 * incoming SYN. If incoming SYN processing changes
5113 		 * the squeue then the listener close which is waiting
5114 		 * to enter the squeue would operate on the wrong
5115 		 * squeue. Hence we don't change the squeue here unless
5116 		 * the refcount is exactly the minimum refcount. The
5117 		 * minimum refcount of 4 is counted as - 1 each for
5118 		 * TCP and IP, 1 for being in the classifier hash, and
5119 		 * 1 for the mblk being processed.
5120 		 */
5121 
5122 		if (connp->conn_ref != 4 ||
5123 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5124 			mutex_exit(&connp->conn_lock);
5125 			mutex_exit(&connp->conn_fanout->connf_lock);
5126 			goto done;
5127 		}
5128 		if (connp->conn_sqp != new_sqp) {
5129 			while (connp->conn_sqp != new_sqp)
5130 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5131 			/* No special MT issues for outbound ixa_sqp hint */
5132 			connp->conn_ixa->ixa_sqp = new_sqp;
5133 		}
5134 
5135 		do {
5136 			conn_flags = connp->conn_flags;
5137 			conn_flags |= IPCL_FULLY_BOUND;
5138 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5139 			    conn_flags);
5140 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5141 
5142 		mutex_exit(&connp->conn_fanout->connf_lock);
5143 		mutex_exit(&connp->conn_lock);
5144 
5145 		/*
5146 		 * Assume we have picked a good squeue for the listener. Make
5147 		 * subsequent SYNs not try to change the squeue.
5148 		 */
5149 		connp->conn_recv = tcp_input_listener;
5150 	}
5151 
5152 done:
5153 	if (connp->conn_sqp != sqp) {
5154 		CONN_INC_REF(connp);
5155 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5156 		    ira, SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5157 	} else {
5158 		tcp_input_listener(connp, mp, sqp, ira);
5159 	}
5160 }
5161 
5162 /*
5163  * Successful connect request processing begins when our client passes
5164  * a T_CONN_REQ message into tcp_wput(), which performs function calls into
5165  * IP and the passes a T_OK_ACK (or T_ERROR_ACK upstream).
5166  *
5167  * After various error checks are completed, tcp_tpi_connect() lays
5168  * the target address and port into the composite header template.
5169  * Then we ask IP for information, including a source address if we didn't
5170  * already have one. Finally we prepare to send the SYN packet, and then
5171  * send up the T_OK_ACK reply message.
5172  */
5173 static void
5174 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5175 {
5176 	sin_t		*sin;
5177 	struct T_conn_req	*tcr;
5178 	struct sockaddr	*sa;
5179 	socklen_t	len;
5180 	int		error;
5181 	cred_t		*cr;
5182 	pid_t		cpid;
5183 	conn_t		*connp = tcp->tcp_connp;
5184 	queue_t		*q = connp->conn_wq;
5185 
5186 	/*
5187 	 * All Solaris components should pass a db_credp
5188 	 * for this TPI message, hence we ASSERT.
5189 	 * But in case there is some other M_PROTO that looks
5190 	 * like a TPI message sent by some other kernel
5191 	 * component, we check and return an error.
5192 	 */
5193 	cr = msg_getcred(mp, &cpid);
5194 	ASSERT(cr != NULL);
5195 	if (cr == NULL) {
5196 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5197 		return;
5198 	}
5199 
5200 	tcr = (struct T_conn_req *)mp->b_rptr;
5201 
5202 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5203 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5204 		tcp_err_ack(tcp, mp, TPROTO, 0);
5205 		return;
5206 	}
5207 
5208 	/*
5209 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5210 	 * will always have that to send up.  Otherwise, we need to do
5211 	 * special handling in case the allocation fails at that time.
5212 	 * If the end point is TPI, the tcp_t can be reused and the
5213 	 * tcp_ordrel_mp may be allocated already.
5214 	 */
5215 	if (tcp->tcp_ordrel_mp == NULL) {
5216 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5217 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5218 			return;
5219 		}
5220 	}
5221 
5222 	/*
5223 	 * Determine packet type based on type of address passed in
5224 	 * the request should contain an IPv4 or IPv6 address.
5225 	 * Make sure that address family matches the type of
5226 	 * family of the address passed down.
5227 	 */
5228 	switch (tcr->DEST_length) {
5229 	default:
5230 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5231 		return;
5232 
5233 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5234 		/*
5235 		 * XXX: The check for valid DEST_length was not there
5236 		 * in earlier releases and some buggy
5237 		 * TLI apps (e.g Sybase) got away with not feeding
5238 		 * in sin_zero part of address.
5239 		 * We allow that bug to keep those buggy apps humming.
5240 		 * Test suites require the check on DEST_length.
5241 		 * We construct a new mblk with valid DEST_length
5242 		 * free the original so the rest of the code does
5243 		 * not have to keep track of this special shorter
5244 		 * length address case.
5245 		 */
5246 		mblk_t *nmp;
5247 		struct T_conn_req *ntcr;
5248 		sin_t *nsin;
5249 
5250 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5251 		    tcr->OPT_length, BPRI_HI);
5252 		if (nmp == NULL) {
5253 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5254 			return;
5255 		}
5256 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5257 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5258 		ntcr->PRIM_type = T_CONN_REQ;
5259 		ntcr->DEST_length = sizeof (sin_t);
5260 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5261 
5262 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5263 		*nsin = sin_null;
5264 		/* Get pointer to shorter address to copy from original mp */
5265 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5266 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5267 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5268 			freemsg(nmp);
5269 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5270 			return;
5271 		}
5272 		nsin->sin_family = sin->sin_family;
5273 		nsin->sin_port = sin->sin_port;
5274 		nsin->sin_addr = sin->sin_addr;
5275 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5276 		nmp->b_wptr = (uchar_t *)&nsin[1];
5277 		if (tcr->OPT_length != 0) {
5278 			ntcr->OPT_length = tcr->OPT_length;
5279 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5280 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5281 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5282 			    tcr->OPT_length);
5283 			nmp->b_wptr += tcr->OPT_length;
5284 		}
5285 		freemsg(mp);	/* original mp freed */
5286 		mp = nmp;	/* re-initialize original variables */
5287 		tcr = ntcr;
5288 	}
5289 	/* FALLTHRU */
5290 
5291 	case sizeof (sin_t):
5292 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5293 		    sizeof (sin_t));
5294 		len = sizeof (sin_t);
5295 		break;
5296 
5297 	case sizeof (sin6_t):
5298 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
5299 		    sizeof (sin6_t));
5300 		len = sizeof (sin6_t);
5301 		break;
5302 	}
5303 
5304 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
5305 	if (error != 0) {
5306 		tcp_err_ack(tcp, mp, TSYSERR, error);
5307 		return;
5308 	}
5309 
5310 	/*
5311 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
5312 	 * should key on their sequence number and cut them loose.
5313 	 */
5314 
5315 	/*
5316 	 * If options passed in, feed it for verification and handling
5317 	 */
5318 	if (tcr->OPT_length != 0) {
5319 		mblk_t	*ok_mp;
5320 		mblk_t	*discon_mp;
5321 		mblk_t  *conn_opts_mp;
5322 		int t_error, sys_error, do_disconnect;
5323 
5324 		conn_opts_mp = NULL;
5325 
5326 		if (tcp_conprim_opt_process(tcp, mp,
5327 		    &do_disconnect, &t_error, &sys_error) < 0) {
5328 			if (do_disconnect) {
5329 				ASSERT(t_error == 0 && sys_error == 0);
5330 				discon_mp = mi_tpi_discon_ind(NULL,
5331 				    ECONNREFUSED, 0);
5332 				if (!discon_mp) {
5333 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5334 					    TSYSERR, ENOMEM);
5335 					return;
5336 				}
5337 				ok_mp = mi_tpi_ok_ack_alloc(mp);
5338 				if (!ok_mp) {
5339 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5340 					    TSYSERR, ENOMEM);
5341 					return;
5342 				}
5343 				qreply(q, ok_mp);
5344 				qreply(q, discon_mp); /* no flush! */
5345 			} else {
5346 				ASSERT(t_error != 0);
5347 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
5348 				    sys_error);
5349 			}
5350 			return;
5351 		}
5352 		/*
5353 		 * Success in setting options, the mp option buffer represented
5354 		 * by OPT_length/offset has been potentially modified and
5355 		 * contains results of option processing. We copy it in
5356 		 * another mp to save it for potentially influencing returning
5357 		 * it in T_CONN_CONN.
5358 		 */
5359 		if (tcr->OPT_length != 0) { /* there are resulting options */
5360 			conn_opts_mp = copyb(mp);
5361 			if (!conn_opts_mp) {
5362 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
5363 				    TSYSERR, ENOMEM);
5364 				return;
5365 			}
5366 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
5367 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
5368 			/*
5369 			 * Note:
5370 			 * These resulting option negotiation can include any
5371 			 * end-to-end negotiation options but there no such
5372 			 * thing (yet?) in our TCP/IP.
5373 			 */
5374 		}
5375 	}
5376 
5377 	/* call the non-TPI version */
5378 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
5379 	if (error < 0) {
5380 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
5381 	} else if (error > 0) {
5382 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
5383 	} else {
5384 		mp = mi_tpi_ok_ack_alloc(mp);
5385 	}
5386 
5387 	/*
5388 	 * Note: Code below is the "failure" case
5389 	 */
5390 	/* return error ack and blow away saved option results if any */
5391 connect_failed:
5392 	if (mp != NULL)
5393 		putnext(connp->conn_rq, mp);
5394 	else {
5395 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
5396 		    TSYSERR, ENOMEM);
5397 	}
5398 }
5399 
5400 /*
5401  * Handle connect to IPv4 destinations, including connections for AF_INET6
5402  * sockets connecting to IPv4 mapped IPv6 destinations.
5403  * Returns zero if OK, a positive errno, or a negative TLI error.
5404  */
5405 static int
5406 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
5407     uint_t srcid)
5408 {
5409 	ipaddr_t 	dstaddr = *dstaddrp;
5410 	uint16_t 	lport;
5411 	conn_t		*connp = tcp->tcp_connp;
5412 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5413 	int		error;
5414 
5415 	ASSERT(connp->conn_ipversion == IPV4_VERSION);
5416 
5417 	/* Check for attempt to connect to INADDR_ANY */
5418 	if (dstaddr == INADDR_ANY)  {
5419 		/*
5420 		 * SunOS 4.x and 4.3 BSD allow an application
5421 		 * to connect a TCP socket to INADDR_ANY.
5422 		 * When they do this, the kernel picks the
5423 		 * address of one interface and uses it
5424 		 * instead.  The kernel usually ends up
5425 		 * picking the address of the loopback
5426 		 * interface.  This is an undocumented feature.
5427 		 * However, we provide the same thing here
5428 		 * in order to have source and binary
5429 		 * compatibility with SunOS 4.x.
5430 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
5431 		 * generate the T_CONN_CON.
5432 		 */
5433 		dstaddr = htonl(INADDR_LOOPBACK);
5434 		*dstaddrp = dstaddr;
5435 	}
5436 
5437 	/* Handle __sin6_src_id if socket not bound to an IP address */
5438 	if (srcid != 0 && connp->conn_laddr_v4 == INADDR_ANY) {
5439 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5440 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5441 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5442 	}
5443 
5444 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &connp->conn_faddr_v6);
5445 	connp->conn_fport = dstport;
5446 
5447 	/*
5448 	 * At this point the remote destination address and remote port fields
5449 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5450 	 * have to see which state tcp was in so we can take appropriate action.
5451 	 */
5452 	if (tcp->tcp_state == TCPS_IDLE) {
5453 		/*
5454 		 * We support a quick connect capability here, allowing
5455 		 * clients to transition directly from IDLE to SYN_SENT
5456 		 * tcp_bindi will pick an unused port, insert the connection
5457 		 * in the bind hash and transition to BOUND state.
5458 		 */
5459 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5460 		    tcp, B_TRUE);
5461 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5462 		    B_FALSE, B_FALSE);
5463 		if (lport == 0)
5464 			return (-TNOADDR);
5465 	}
5466 
5467 	/*
5468 	 * Lookup the route to determine a source address and the uinfo.
5469 	 * Setup TCP parameters based on the metrics/DCE.
5470 	 */
5471 	error = tcp_set_destination(tcp);
5472 	if (error != 0)
5473 		return (error);
5474 
5475 	/*
5476 	 * Don't let an endpoint connect to itself.
5477 	 */
5478 	if (connp->conn_faddr_v4 == connp->conn_laddr_v4 &&
5479 	    connp->conn_fport == connp->conn_lport)
5480 		return (-TBADADDR);
5481 
5482 	tcp->tcp_state = TCPS_SYN_SENT;
5483 
5484 	return (ipcl_conn_insert_v4(connp));
5485 }
5486 
5487 /*
5488  * Handle connect to IPv6 destinations.
5489  * Returns zero if OK, a positive errno, or a negative TLI error.
5490  */
5491 static int
5492 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
5493     uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
5494 {
5495 	uint16_t 	lport;
5496 	conn_t		*connp = tcp->tcp_connp;
5497 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5498 	int		error;
5499 
5500 	ASSERT(connp->conn_family == AF_INET6);
5501 
5502 	/*
5503 	 * If we're here, it means that the destination address is a native
5504 	 * IPv6 address.  Return an error if conn_ipversion is not IPv6.  A
5505 	 * reason why it might not be IPv6 is if the socket was bound to an
5506 	 * IPv4-mapped IPv6 address.
5507 	 */
5508 	if (connp->conn_ipversion != IPV6_VERSION)
5509 		return (-TBADADDR);
5510 
5511 	/*
5512 	 * Interpret a zero destination to mean loopback.
5513 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
5514 	 * generate the T_CONN_CON.
5515 	 */
5516 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp))
5517 		*dstaddrp = ipv6_loopback;
5518 
5519 	/* Handle __sin6_src_id if socket not bound to an IP address */
5520 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6)) {
5521 		ip_srcid_find_id(srcid, &connp->conn_laddr_v6,
5522 		    IPCL_ZONEID(connp), tcps->tcps_netstack);
5523 		connp->conn_saddr_v6 = connp->conn_laddr_v6;
5524 	}
5525 
5526 	/*
5527 	 * Take care of the scope_id now.
5528 	 */
5529 	if (scope_id != 0 && IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
5530 		connp->conn_ixa->ixa_flags |= IXAF_SCOPEID_SET;
5531 		connp->conn_ixa->ixa_scopeid = scope_id;
5532 	} else {
5533 		connp->conn_ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
5534 	}
5535 
5536 	connp->conn_flowinfo = flowinfo;
5537 	connp->conn_faddr_v6 = *dstaddrp;
5538 	connp->conn_fport = dstport;
5539 
5540 	/*
5541 	 * At this point the remote destination address and remote port fields
5542 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
5543 	 * have to see which state tcp was in so we can take appropriate action.
5544 	 */
5545 	if (tcp->tcp_state == TCPS_IDLE) {
5546 		/*
5547 		 * We support a quick connect capability here, allowing
5548 		 * clients to transition directly from IDLE to SYN_SENT
5549 		 * tcp_bindi will pick an unused port, insert the connection
5550 		 * in the bind hash and transition to BOUND state.
5551 		 */
5552 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
5553 		    tcp, B_TRUE);
5554 		lport = tcp_bindi(tcp, lport, &connp->conn_laddr_v6, 0, B_TRUE,
5555 		    B_FALSE, B_FALSE);
5556 		if (lport == 0)
5557 			return (-TNOADDR);
5558 	}
5559 
5560 	/*
5561 	 * Lookup the route to determine a source address and the uinfo.
5562 	 * Setup TCP parameters based on the metrics/DCE.
5563 	 */
5564 	error = tcp_set_destination(tcp);
5565 	if (error != 0)
5566 		return (error);
5567 
5568 	/*
5569 	 * Don't let an endpoint connect to itself.
5570 	 */
5571 	if (IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6, &connp->conn_laddr_v6) &&
5572 	    connp->conn_fport == connp->conn_lport)
5573 		return (-TBADADDR);
5574 
5575 	tcp->tcp_state = TCPS_SYN_SENT;
5576 
5577 	return (ipcl_conn_insert_v6(connp));
5578 }
5579 
5580 /*
5581  * Disconnect
5582  * Note that unlike other functions this returns a positive tli error
5583  * when it fails; it never returns an errno.
5584  */
5585 static int
5586 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
5587 {
5588 	conn_t		*lconnp;
5589 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5590 	conn_t		*connp = tcp->tcp_connp;
5591 
5592 	/*
5593 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
5594 	 * when the stream is in BOUND state. Do not send a reset,
5595 	 * since the destination IP address is not valid, and it can
5596 	 * be the initialized value of all zeros (broadcast address).
5597 	 */
5598 	if (tcp->tcp_state <= TCPS_BOUND) {
5599 		if (connp->conn_debug) {
5600 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
5601 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
5602 		}
5603 		return (TOUTSTATE);
5604 	}
5605 
5606 
5607 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
5608 
5609 		/*
5610 		 * According to TPI, for non-listeners, ignore seqnum
5611 		 * and disconnect.
5612 		 * Following interpretation of -1 seqnum is historical
5613 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
5614 		 * a valid seqnum should not be -1).
5615 		 *
5616 		 *	-1 means disconnect everything
5617 		 *	regardless even on a listener.
5618 		 */
5619 
5620 		int old_state = tcp->tcp_state;
5621 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
5622 
5623 		/*
5624 		 * The connection can't be on the tcp_time_wait_head list
5625 		 * since it is not detached.
5626 		 */
5627 		ASSERT(tcp->tcp_time_wait_next == NULL);
5628 		ASSERT(tcp->tcp_time_wait_prev == NULL);
5629 		ASSERT(tcp->tcp_time_wait_expire == 0);
5630 		/*
5631 		 * If it used to be a listener, check to make sure no one else
5632 		 * has taken the port before switching back to LISTEN state.
5633 		 */
5634 		if (connp->conn_ipversion == IPV4_VERSION) {
5635 			lconnp = ipcl_lookup_listener_v4(connp->conn_lport,
5636 			    connp->conn_laddr_v4, IPCL_ZONEID(connp), ipst);
5637 		} else {
5638 			uint_t ifindex = 0;
5639 
5640 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)
5641 				ifindex = connp->conn_ixa->ixa_scopeid;
5642 
5643 			/* Allow conn_bound_if listeners? */
5644 			lconnp = ipcl_lookup_listener_v6(connp->conn_lport,
5645 			    &connp->conn_laddr_v6, ifindex, IPCL_ZONEID(connp),
5646 			    ipst);
5647 		}
5648 		if (tcp->tcp_conn_req_max && lconnp == NULL) {
5649 			tcp->tcp_state = TCPS_LISTEN;
5650 		} else if (old_state > TCPS_BOUND) {
5651 			tcp->tcp_conn_req_max = 0;
5652 			tcp->tcp_state = TCPS_BOUND;
5653 
5654 			/*
5655 			 * If this end point is not going to become a listener,
5656 			 * decrement the listener connection count if
5657 			 * necessary.  Note that we do not do this if it is
5658 			 * going to be a listner (the above if case) since
5659 			 * then it may remove the counter struct.
5660 			 */
5661 			if (tcp->tcp_listen_cnt != NULL)
5662 				TCP_DECR_LISTEN_CNT(tcp);
5663 		}
5664 		if (lconnp != NULL)
5665 			CONN_DEC_REF(lconnp);
5666 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
5667 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
5668 		} else if (old_state == TCPS_ESTABLISHED ||
5669 		    old_state == TCPS_CLOSE_WAIT) {
5670 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
5671 		}
5672 
5673 		if (tcp->tcp_fused)
5674 			tcp_unfuse(tcp);
5675 
5676 		mutex_enter(&tcp->tcp_eager_lock);
5677 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
5678 		    (tcp->tcp_conn_req_cnt_q != 0)) {
5679 			tcp_eager_cleanup(tcp, 0);
5680 		}
5681 		mutex_exit(&tcp->tcp_eager_lock);
5682 
5683 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
5684 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
5685 
5686 		tcp_reinit(tcp);
5687 
5688 		return (0);
5689 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
5690 		return (TBADSEQ);
5691 	}
5692 	return (0);
5693 }
5694 
5695 /*
5696  * Our client hereby directs us to reject the connection request
5697  * that tcp_input_listener() marked with 'seqnum'.  Rejection consists
5698  * of sending the appropriate RST, not an ICMP error.
5699  */
5700 static void
5701 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
5702 {
5703 	t_scalar_t seqnum;
5704 	int	error;
5705 	conn_t	*connp = tcp->tcp_connp;
5706 
5707 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5708 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
5709 		tcp_err_ack(tcp, mp, TPROTO, 0);
5710 		return;
5711 	}
5712 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
5713 	error = tcp_disconnect_common(tcp, seqnum);
5714 	if (error != 0)
5715 		tcp_err_ack(tcp, mp, error, 0);
5716 	else {
5717 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
5718 			/* Send M_FLUSH according to TPI */
5719 			(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
5720 		}
5721 		mp = mi_tpi_ok_ack_alloc(mp);
5722 		if (mp != NULL)
5723 			putnext(connp->conn_rq, mp);
5724 	}
5725 }
5726 
5727 /*
5728  * Diagnostic routine used to return a string associated with the tcp state.
5729  * Note that if the caller does not supply a buffer, it will use an internal
5730  * static string.  This means that if multiple threads call this function at
5731  * the same time, output can be corrupted...  Note also that this function
5732  * does not check the size of the supplied buffer.  The caller has to make
5733  * sure that it is big enough.
5734  */
5735 static char *
5736 tcp_display(tcp_t *tcp, char *sup_buf, char format)
5737 {
5738 	char		buf1[30];
5739 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
5740 	char		*buf;
5741 	char		*cp;
5742 	in6_addr_t	local, remote;
5743 	char		local_addrbuf[INET6_ADDRSTRLEN];
5744 	char		remote_addrbuf[INET6_ADDRSTRLEN];
5745 	conn_t		*connp;
5746 
5747 	if (sup_buf != NULL)
5748 		buf = sup_buf;
5749 	else
5750 		buf = priv_buf;
5751 
5752 	if (tcp == NULL)
5753 		return ("NULL_TCP");
5754 
5755 	connp = tcp->tcp_connp;
5756 	switch (tcp->tcp_state) {
5757 	case TCPS_CLOSED:
5758 		cp = "TCP_CLOSED";
5759 		break;
5760 	case TCPS_IDLE:
5761 		cp = "TCP_IDLE";
5762 		break;
5763 	case TCPS_BOUND:
5764 		cp = "TCP_BOUND";
5765 		break;
5766 	case TCPS_LISTEN:
5767 		cp = "TCP_LISTEN";
5768 		break;
5769 	case TCPS_SYN_SENT:
5770 		cp = "TCP_SYN_SENT";
5771 		break;
5772 	case TCPS_SYN_RCVD:
5773 		cp = "TCP_SYN_RCVD";
5774 		break;
5775 	case TCPS_ESTABLISHED:
5776 		cp = "TCP_ESTABLISHED";
5777 		break;
5778 	case TCPS_CLOSE_WAIT:
5779 		cp = "TCP_CLOSE_WAIT";
5780 		break;
5781 	case TCPS_FIN_WAIT_1:
5782 		cp = "TCP_FIN_WAIT_1";
5783 		break;
5784 	case TCPS_CLOSING:
5785 		cp = "TCP_CLOSING";
5786 		break;
5787 	case TCPS_LAST_ACK:
5788 		cp = "TCP_LAST_ACK";
5789 		break;
5790 	case TCPS_FIN_WAIT_2:
5791 		cp = "TCP_FIN_WAIT_2";
5792 		break;
5793 	case TCPS_TIME_WAIT:
5794 		cp = "TCP_TIME_WAIT";
5795 		break;
5796 	default:
5797 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
5798 		cp = buf1;
5799 		break;
5800 	}
5801 	switch (format) {
5802 	case DISP_ADDR_AND_PORT:
5803 		if (connp->conn_ipversion == IPV4_VERSION) {
5804 			/*
5805 			 * Note that we use the remote address in the tcp_b
5806 			 * structure.  This means that it will print out
5807 			 * the real destination address, not the next hop's
5808 			 * address if source routing is used.
5809 			 */
5810 			IN6_IPADDR_TO_V4MAPPED(connp->conn_laddr_v4, &local);
5811 			IN6_IPADDR_TO_V4MAPPED(connp->conn_faddr_v4, &remote);
5812 
5813 		} else {
5814 			local = connp->conn_laddr_v6;
5815 			remote = connp->conn_faddr_v6;
5816 		}
5817 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
5818 		    sizeof (local_addrbuf));
5819 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
5820 		    sizeof (remote_addrbuf));
5821 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
5822 		    local_addrbuf, ntohs(connp->conn_lport), remote_addrbuf,
5823 		    ntohs(connp->conn_fport), cp);
5824 		break;
5825 	case DISP_PORT_ONLY:
5826 	default:
5827 		(void) mi_sprintf(buf, "[%u, %u] %s",
5828 		    ntohs(connp->conn_lport), ntohs(connp->conn_fport), cp);
5829 		break;
5830 	}
5831 
5832 	return (buf);
5833 }
5834 
5835 /*
5836  * Called via squeue to get on to eager's perimeter. It sends a
5837  * TH_RST if eager is in the fanout table. The listener wants the
5838  * eager to disappear either by means of tcp_eager_blowoff() or
5839  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
5840  * called (via squeue) if the eager cannot be inserted in the
5841  * fanout table in tcp_input_listener().
5842  */
5843 /* ARGSUSED */
5844 void
5845 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
5846 {
5847 	conn_t	*econnp = (conn_t *)arg;
5848 	tcp_t	*eager = econnp->conn_tcp;
5849 	tcp_t	*listener = eager->tcp_listener;
5850 
5851 	/*
5852 	 * We could be called because listener is closing. Since
5853 	 * the eager was using listener's queue's, we avoid
5854 	 * using the listeners queues from now on.
5855 	 */
5856 	ASSERT(eager->tcp_detached);
5857 	econnp->conn_rq = NULL;
5858 	econnp->conn_wq = NULL;
5859 
5860 	/*
5861 	 * An eager's conn_fanout will be NULL if it's a duplicate
5862 	 * for an existing 4-tuples in the conn fanout table.
5863 	 * We don't want to send an RST out in such case.
5864 	 */
5865 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
5866 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
5867 		    eager, eager->tcp_snxt, 0, TH_RST);
5868 	}
5869 
5870 	/* We are here because listener wants this eager gone */
5871 	if (listener != NULL) {
5872 		mutex_enter(&listener->tcp_eager_lock);
5873 		tcp_eager_unlink(eager);
5874 		if (eager->tcp_tconnind_started) {
5875 			/*
5876 			 * The eager has sent a conn_ind up to the
5877 			 * listener but listener decides to close
5878 			 * instead. We need to drop the extra ref
5879 			 * placed on eager in tcp_input_data() before
5880 			 * sending the conn_ind to listener.
5881 			 */
5882 			CONN_DEC_REF(econnp);
5883 		}
5884 		mutex_exit(&listener->tcp_eager_lock);
5885 		CONN_DEC_REF(listener->tcp_connp);
5886 	}
5887 
5888 	if (eager->tcp_state != TCPS_CLOSED)
5889 		tcp_close_detached(eager);
5890 }
5891 
5892 /*
5893  * Reset any eager connection hanging off this listener marked
5894  * with 'seqnum' and then reclaim it's resources.
5895  */
5896 static boolean_t
5897 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
5898 {
5899 	tcp_t	*eager;
5900 	mblk_t 	*mp;
5901 	tcp_stack_t	*tcps = listener->tcp_tcps;
5902 
5903 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
5904 	eager = listener;
5905 	mutex_enter(&listener->tcp_eager_lock);
5906 	do {
5907 		eager = eager->tcp_eager_next_q;
5908 		if (eager == NULL) {
5909 			mutex_exit(&listener->tcp_eager_lock);
5910 			return (B_FALSE);
5911 		}
5912 	} while (eager->tcp_conn_req_seqnum != seqnum);
5913 
5914 	if (eager->tcp_closemp_used) {
5915 		mutex_exit(&listener->tcp_eager_lock);
5916 		return (B_TRUE);
5917 	}
5918 	eager->tcp_closemp_used = B_TRUE;
5919 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5920 	CONN_INC_REF(eager->tcp_connp);
5921 	mutex_exit(&listener->tcp_eager_lock);
5922 	mp = &eager->tcp_closemp;
5923 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
5924 	    eager->tcp_connp, NULL, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
5925 	return (B_TRUE);
5926 }
5927 
5928 /*
5929  * Reset any eager connection hanging off this listener
5930  * and then reclaim it's resources.
5931  */
5932 static void
5933 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
5934 {
5935 	tcp_t	*eager;
5936 	mblk_t	*mp;
5937 	tcp_stack_t	*tcps = listener->tcp_tcps;
5938 
5939 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
5940 
5941 	if (!q0_only) {
5942 		/* First cleanup q */
5943 		TCP_STAT(tcps, tcp_eager_blowoff_q);
5944 		eager = listener->tcp_eager_next_q;
5945 		while (eager != NULL) {
5946 			if (!eager->tcp_closemp_used) {
5947 				eager->tcp_closemp_used = B_TRUE;
5948 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5949 				CONN_INC_REF(eager->tcp_connp);
5950 				mp = &eager->tcp_closemp;
5951 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
5952 				    tcp_eager_kill, eager->tcp_connp, NULL,
5953 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
5954 			}
5955 			eager = eager->tcp_eager_next_q;
5956 		}
5957 	}
5958 	/* Then cleanup q0 */
5959 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
5960 	eager = listener->tcp_eager_next_q0;
5961 	while (eager != listener) {
5962 		if (!eager->tcp_closemp_used) {
5963 			eager->tcp_closemp_used = B_TRUE;
5964 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5965 			CONN_INC_REF(eager->tcp_connp);
5966 			mp = &eager->tcp_closemp;
5967 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
5968 			    tcp_eager_kill, eager->tcp_connp, NULL, SQ_FILL,
5969 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
5970 		}
5971 		eager = eager->tcp_eager_next_q0;
5972 	}
5973 }
5974 
5975 /*
5976  * If we are an eager connection hanging off a listener that hasn't
5977  * formally accepted the connection yet, get off his list and blow off
5978  * any data that we have accumulated.
5979  */
5980 static void
5981 tcp_eager_unlink(tcp_t *tcp)
5982 {
5983 	tcp_t	*listener = tcp->tcp_listener;
5984 
5985 	ASSERT(listener != NULL);
5986 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
5987 	if (tcp->tcp_eager_next_q0 != NULL) {
5988 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
5989 
5990 		/* Remove the eager tcp from q0 */
5991 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
5992 		    tcp->tcp_eager_prev_q0;
5993 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
5994 		    tcp->tcp_eager_next_q0;
5995 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
5996 		listener->tcp_conn_req_cnt_q0--;
5997 
5998 		tcp->tcp_eager_next_q0 = NULL;
5999 		tcp->tcp_eager_prev_q0 = NULL;
6000 
6001 		/*
6002 		 * Take the eager out, if it is in the list of droppable
6003 		 * eagers.
6004 		 */
6005 		MAKE_UNDROPPABLE(tcp);
6006 
6007 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6008 			/* we have timed out before */
6009 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6010 			listener->tcp_syn_rcvd_timeout--;
6011 		}
6012 	} else {
6013 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6014 		tcp_t	*prev = NULL;
6015 
6016 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6017 			if (tcpp[0] == tcp) {
6018 				if (listener->tcp_eager_last_q == tcp) {
6019 					/*
6020 					 * If we are unlinking the last
6021 					 * element on the list, adjust
6022 					 * tail pointer. Set tail pointer
6023 					 * to nil when list is empty.
6024 					 */
6025 					ASSERT(tcp->tcp_eager_next_q == NULL);
6026 					if (listener->tcp_eager_last_q ==
6027 					    listener->tcp_eager_next_q) {
6028 						listener->tcp_eager_last_q =
6029 						    NULL;
6030 					} else {
6031 						/*
6032 						 * We won't get here if there
6033 						 * is only one eager in the
6034 						 * list.
6035 						 */
6036 						ASSERT(prev != NULL);
6037 						listener->tcp_eager_last_q =
6038 						    prev;
6039 					}
6040 				}
6041 				tcpp[0] = tcp->tcp_eager_next_q;
6042 				tcp->tcp_eager_next_q = NULL;
6043 				tcp->tcp_eager_last_q = NULL;
6044 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6045 				listener->tcp_conn_req_cnt_q--;
6046 				break;
6047 			}
6048 			prev = tcpp[0];
6049 		}
6050 	}
6051 	tcp->tcp_listener = NULL;
6052 }
6053 
6054 /* Shorthand to generate and send TPI error acks to our client */
6055 static void
6056 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6057 {
6058 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6059 		putnext(tcp->tcp_connp->conn_rq, mp);
6060 }
6061 
6062 /* Shorthand to generate and send TPI error acks to our client */
6063 static void
6064 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6065     int t_error, int sys_error)
6066 {
6067 	struct T_error_ack	*teackp;
6068 
6069 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6070 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6071 		teackp = (struct T_error_ack *)mp->b_rptr;
6072 		teackp->ERROR_prim = primitive;
6073 		teackp->TLI_error = t_error;
6074 		teackp->UNIX_error = sys_error;
6075 		putnext(tcp->tcp_connp->conn_rq, mp);
6076 	}
6077 }
6078 
6079 /*
6080  * Note: No locks are held when inspecting tcp_g_*epriv_ports
6081  * but instead the code relies on:
6082  * - the fact that the address of the array and its size never changes
6083  * - the atomic assignment of the elements of the array
6084  */
6085 /* ARGSUSED */
6086 static int
6087 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
6088 {
6089 	int i;
6090 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6091 
6092 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6093 		if (tcps->tcps_g_epriv_ports[i] != 0)
6094 			(void) mi_mpprintf(mp, "%d ",
6095 			    tcps->tcps_g_epriv_ports[i]);
6096 	}
6097 	return (0);
6098 }
6099 
6100 /*
6101  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6102  * threads from changing it at the same time.
6103  */
6104 /* ARGSUSED */
6105 static int
6106 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6107     cred_t *cr)
6108 {
6109 	long	new_value;
6110 	int	i;
6111 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6112 
6113 	/*
6114 	 * Fail the request if the new value does not lie within the
6115 	 * port number limits.
6116 	 */
6117 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
6118 	    new_value <= 0 || new_value >= 65536) {
6119 		return (EINVAL);
6120 	}
6121 
6122 	mutex_enter(&tcps->tcps_epriv_port_lock);
6123 	/* Check if the value is already in the list */
6124 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6125 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
6126 			mutex_exit(&tcps->tcps_epriv_port_lock);
6127 			return (EEXIST);
6128 		}
6129 	}
6130 	/* Find an empty slot */
6131 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6132 		if (tcps->tcps_g_epriv_ports[i] == 0)
6133 			break;
6134 	}
6135 	if (i == tcps->tcps_g_num_epriv_ports) {
6136 		mutex_exit(&tcps->tcps_epriv_port_lock);
6137 		return (EOVERFLOW);
6138 	}
6139 	/* Set the new value */
6140 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
6141 	mutex_exit(&tcps->tcps_epriv_port_lock);
6142 	return (0);
6143 }
6144 
6145 /*
6146  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
6147  * threads from changing it at the same time.
6148  */
6149 /* ARGSUSED */
6150 static int
6151 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
6152     cred_t *cr)
6153 {
6154 	long	new_value;
6155 	int	i;
6156 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
6157 
6158 	/*
6159 	 * Fail the request if the new value does not lie within the
6160 	 * port number limits.
6161 	 */
6162 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
6163 	    new_value >= 65536) {
6164 		return (EINVAL);
6165 	}
6166 
6167 	mutex_enter(&tcps->tcps_epriv_port_lock);
6168 	/* Check that the value is already in the list */
6169 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
6170 		if (tcps->tcps_g_epriv_ports[i] == new_value)
6171 			break;
6172 	}
6173 	if (i == tcps->tcps_g_num_epriv_ports) {
6174 		mutex_exit(&tcps->tcps_epriv_port_lock);
6175 		return (ESRCH);
6176 	}
6177 	/* Clear the value */
6178 	tcps->tcps_g_epriv_ports[i] = 0;
6179 	mutex_exit(&tcps->tcps_epriv_port_lock);
6180 	return (0);
6181 }
6182 
6183 /* Return the TPI/TLI equivalent of our current tcp_state */
6184 static int
6185 tcp_tpistate(tcp_t *tcp)
6186 {
6187 	switch (tcp->tcp_state) {
6188 	case TCPS_IDLE:
6189 		return (TS_UNBND);
6190 	case TCPS_LISTEN:
6191 		/*
6192 		 * Return whether there are outstanding T_CONN_IND waiting
6193 		 * for the matching T_CONN_RES. Therefore don't count q0.
6194 		 */
6195 		if (tcp->tcp_conn_req_cnt_q > 0)
6196 			return (TS_WRES_CIND);
6197 		else
6198 			return (TS_IDLE);
6199 	case TCPS_BOUND:
6200 		return (TS_IDLE);
6201 	case TCPS_SYN_SENT:
6202 		return (TS_WCON_CREQ);
6203 	case TCPS_SYN_RCVD:
6204 		/*
6205 		 * Note: assumption: this has to the active open SYN_RCVD.
6206 		 * The passive instance is detached in SYN_RCVD stage of
6207 		 * incoming connection processing so we cannot get request
6208 		 * for T_info_ack on it.
6209 		 */
6210 		return (TS_WACK_CRES);
6211 	case TCPS_ESTABLISHED:
6212 		return (TS_DATA_XFER);
6213 	case TCPS_CLOSE_WAIT:
6214 		return (TS_WREQ_ORDREL);
6215 	case TCPS_FIN_WAIT_1:
6216 		return (TS_WIND_ORDREL);
6217 	case TCPS_FIN_WAIT_2:
6218 		return (TS_WIND_ORDREL);
6219 
6220 	case TCPS_CLOSING:
6221 	case TCPS_LAST_ACK:
6222 	case TCPS_TIME_WAIT:
6223 	case TCPS_CLOSED:
6224 		/*
6225 		 * Following TS_WACK_DREQ7 is a rendition of "not
6226 		 * yet TS_IDLE" TPI state. There is no best match to any
6227 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
6228 		 * choose a value chosen that will map to TLI/XTI level
6229 		 * state of TSTATECHNG (state is process of changing) which
6230 		 * captures what this dummy state represents.
6231 		 */
6232 		return (TS_WACK_DREQ7);
6233 	default:
6234 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
6235 		    tcp->tcp_state, tcp_display(tcp, NULL,
6236 		    DISP_PORT_ONLY));
6237 		return (TS_UNBND);
6238 	}
6239 }
6240 
6241 static void
6242 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
6243 {
6244 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6245 	conn_t		*connp = tcp->tcp_connp;
6246 
6247 	if (connp->conn_family == AF_INET6)
6248 		*tia = tcp_g_t_info_ack_v6;
6249 	else
6250 		*tia = tcp_g_t_info_ack;
6251 	tia->CURRENT_state = tcp_tpistate(tcp);
6252 	tia->OPT_size = tcp_max_optsize;
6253 	if (tcp->tcp_mss == 0) {
6254 		/* Not yet set - tcp_open does not set mss */
6255 		if (connp->conn_ipversion == IPV4_VERSION)
6256 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
6257 		else
6258 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
6259 	} else {
6260 		tia->TIDU_size = tcp->tcp_mss;
6261 	}
6262 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
6263 }
6264 
6265 static void
6266 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
6267     t_uscalar_t cap_bits1)
6268 {
6269 	tcap->CAP_bits1 = 0;
6270 
6271 	if (cap_bits1 & TC1_INFO) {
6272 		tcp_copy_info(&tcap->INFO_ack, tcp);
6273 		tcap->CAP_bits1 |= TC1_INFO;
6274 	}
6275 
6276 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
6277 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
6278 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
6279 	}
6280 
6281 }
6282 
6283 /*
6284  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
6285  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
6286  * tcp_g_t_info_ack.  The current state of the stream is copied from
6287  * tcp_state.
6288  */
6289 static void
6290 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
6291 {
6292 	t_uscalar_t		cap_bits1;
6293 	struct T_capability_ack	*tcap;
6294 
6295 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
6296 		freemsg(mp);
6297 		return;
6298 	}
6299 
6300 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
6301 
6302 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
6303 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
6304 	if (mp == NULL)
6305 		return;
6306 
6307 	tcap = (struct T_capability_ack *)mp->b_rptr;
6308 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
6309 
6310 	putnext(tcp->tcp_connp->conn_rq, mp);
6311 }
6312 
6313 /*
6314  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
6315  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
6316  * The current state of the stream is copied from tcp_state.
6317  */
6318 static void
6319 tcp_info_req(tcp_t *tcp, mblk_t *mp)
6320 {
6321 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
6322 	    T_INFO_ACK);
6323 	if (!mp) {
6324 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6325 		return;
6326 	}
6327 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
6328 	putnext(tcp->tcp_connp->conn_rq, mp);
6329 }
6330 
6331 /* Respond to the TPI addr request */
6332 static void
6333 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
6334 {
6335 	struct sockaddr *sa;
6336 	mblk_t	*ackmp;
6337 	struct T_addr_ack *taa;
6338 	conn_t	*connp = tcp->tcp_connp;
6339 	uint_t	addrlen;
6340 
6341 	/* Make it large enough for worst case */
6342 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
6343 	    2 * sizeof (sin6_t), 1);
6344 	if (ackmp == NULL) {
6345 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6346 		return;
6347 	}
6348 
6349 	taa = (struct T_addr_ack *)ackmp->b_rptr;
6350 
6351 	bzero(taa, sizeof (struct T_addr_ack));
6352 	ackmp->b_wptr = (uchar_t *)&taa[1];
6353 
6354 	taa->PRIM_type = T_ADDR_ACK;
6355 	ackmp->b_datap->db_type = M_PCPROTO;
6356 
6357 	if (connp->conn_family == AF_INET)
6358 		addrlen = sizeof (sin_t);
6359 	else
6360 		addrlen = sizeof (sin6_t);
6361 
6362 	/*
6363 	 * Note: Following code assumes 32 bit alignment of basic
6364 	 * data structures like sin_t and struct T_addr_ack.
6365 	 */
6366 	if (tcp->tcp_state >= TCPS_BOUND) {
6367 		/*
6368 		 * Fill in local address first
6369 		 */
6370 		taa->LOCADDR_offset = sizeof (*taa);
6371 		taa->LOCADDR_length = addrlen;
6372 		sa = (struct sockaddr *)&taa[1];
6373 		(void) conn_getsockname(connp, sa, &addrlen);
6374 		ackmp->b_wptr += addrlen;
6375 	}
6376 	if (tcp->tcp_state >= TCPS_SYN_RCVD) {
6377 		/*
6378 		 * Fill in Remote address
6379 		 */
6380 		taa->REMADDR_length = addrlen;
6381 		/* assumed 32-bit alignment */
6382 		taa->REMADDR_offset = taa->LOCADDR_offset + taa->LOCADDR_length;
6383 		sa = (struct sockaddr *)(ackmp->b_rptr + taa->REMADDR_offset);
6384 		(void) conn_getpeername(connp, sa, &addrlen);
6385 		ackmp->b_wptr += addrlen;
6386 	}
6387 	ASSERT(ackmp->b_wptr <= ackmp->b_datap->db_lim);
6388 	putnext(tcp->tcp_connp->conn_rq, ackmp);
6389 }
6390 
6391 /*
6392  * Handle reinitialization of a tcp structure.
6393  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
6394  */
6395 static void
6396 tcp_reinit(tcp_t *tcp)
6397 {
6398 	mblk_t		*mp;
6399 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6400 	conn_t		*connp  = tcp->tcp_connp;
6401 
6402 	TCP_STAT(tcps, tcp_reinit_calls);
6403 
6404 	/* tcp_reinit should never be called for detached tcp_t's */
6405 	ASSERT(tcp->tcp_listener == NULL);
6406 	ASSERT((connp->conn_family == AF_INET &&
6407 	    connp->conn_ipversion == IPV4_VERSION) ||
6408 	    (connp->conn_family == AF_INET6 &&
6409 	    (connp->conn_ipversion == IPV4_VERSION ||
6410 	    connp->conn_ipversion == IPV6_VERSION)));
6411 
6412 	/* Cancel outstanding timers */
6413 	tcp_timers_stop(tcp);
6414 
6415 	/*
6416 	 * Reset everything in the state vector, after updating global
6417 	 * MIB data from instance counters.
6418 	 */
6419 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
6420 	tcp->tcp_ibsegs = 0;
6421 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
6422 	tcp->tcp_obsegs = 0;
6423 
6424 	tcp_close_mpp(&tcp->tcp_xmit_head);
6425 	if (tcp->tcp_snd_zcopy_aware)
6426 		tcp_zcopy_notify(tcp);
6427 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
6428 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
6429 	mutex_enter(&tcp->tcp_non_sq_lock);
6430 	if (tcp->tcp_flow_stopped &&
6431 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
6432 		tcp_clrqfull(tcp);
6433 	}
6434 	mutex_exit(&tcp->tcp_non_sq_lock);
6435 	tcp_close_mpp(&tcp->tcp_reass_head);
6436 	tcp->tcp_reass_tail = NULL;
6437 	if (tcp->tcp_rcv_list != NULL) {
6438 		/* Free b_next chain */
6439 		tcp_close_mpp(&tcp->tcp_rcv_list);
6440 		tcp->tcp_rcv_last_head = NULL;
6441 		tcp->tcp_rcv_last_tail = NULL;
6442 		tcp->tcp_rcv_cnt = 0;
6443 	}
6444 	tcp->tcp_rcv_last_tail = NULL;
6445 
6446 	if ((mp = tcp->tcp_urp_mp) != NULL) {
6447 		freemsg(mp);
6448 		tcp->tcp_urp_mp = NULL;
6449 	}
6450 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
6451 		freemsg(mp);
6452 		tcp->tcp_urp_mark_mp = NULL;
6453 	}
6454 	if (tcp->tcp_fused_sigurg_mp != NULL) {
6455 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6456 		freeb(tcp->tcp_fused_sigurg_mp);
6457 		tcp->tcp_fused_sigurg_mp = NULL;
6458 	}
6459 	if (tcp->tcp_ordrel_mp != NULL) {
6460 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
6461 		freeb(tcp->tcp_ordrel_mp);
6462 		tcp->tcp_ordrel_mp = NULL;
6463 	}
6464 
6465 	/*
6466 	 * Following is a union with two members which are
6467 	 * identical types and size so the following cleanup
6468 	 * is enough.
6469 	 */
6470 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
6471 
6472 	CL_INET_DISCONNECT(connp);
6473 
6474 	/*
6475 	 * The connection can't be on the tcp_time_wait_head list
6476 	 * since it is not detached.
6477 	 */
6478 	ASSERT(tcp->tcp_time_wait_next == NULL);
6479 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6480 	ASSERT(tcp->tcp_time_wait_expire == 0);
6481 
6482 	if (tcp->tcp_kssl_pending) {
6483 		tcp->tcp_kssl_pending = B_FALSE;
6484 
6485 		/* Don't reset if the initialized by bind. */
6486 		if (tcp->tcp_kssl_ent != NULL) {
6487 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
6488 			    KSSL_NO_PROXY);
6489 		}
6490 	}
6491 	if (tcp->tcp_kssl_ctx != NULL) {
6492 		kssl_release_ctx(tcp->tcp_kssl_ctx);
6493 		tcp->tcp_kssl_ctx = NULL;
6494 	}
6495 
6496 	/*
6497 	 * Reset/preserve other values
6498 	 */
6499 	tcp_reinit_values(tcp);
6500 	ipcl_hash_remove(connp);
6501 	ixa_cleanup(connp->conn_ixa);
6502 	tcp_ipsec_cleanup(tcp);
6503 
6504 	connp->conn_laddr_v6 = connp->conn_bound_addr_v6;
6505 	connp->conn_saddr_v6 = connp->conn_bound_addr_v6;
6506 
6507 	if (tcp->tcp_conn_req_max != 0) {
6508 		/*
6509 		 * This is the case when a TLI program uses the same
6510 		 * transport end point to accept a connection.  This
6511 		 * makes the TCP both a listener and acceptor.  When
6512 		 * this connection is closed, we need to set the state
6513 		 * back to TCPS_LISTEN.  Make sure that the eager list
6514 		 * is reinitialized.
6515 		 *
6516 		 * Note that this stream is still bound to the four
6517 		 * tuples of the previous connection in IP.  If a new
6518 		 * SYN with different foreign address comes in, IP will
6519 		 * not find it and will send it to the global queue.  In
6520 		 * the global queue, TCP will do a tcp_lookup_listener()
6521 		 * to find this stream.  This works because this stream
6522 		 * is only removed from connected hash.
6523 		 *
6524 		 */
6525 		tcp->tcp_state = TCPS_LISTEN;
6526 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
6527 		tcp->tcp_eager_next_drop_q0 = tcp;
6528 		tcp->tcp_eager_prev_drop_q0 = tcp;
6529 		/*
6530 		 * Initially set conn_recv to tcp_input_listener_unbound to try
6531 		 * to pick a good squeue for the listener when the first SYN
6532 		 * arrives. tcp_input_listener_unbound sets it to
6533 		 * tcp_input_listener on that first SYN.
6534 		 */
6535 		connp->conn_recv = tcp_input_listener_unbound;
6536 
6537 		connp->conn_proto = IPPROTO_TCP;
6538 		connp->conn_faddr_v6 = ipv6_all_zeros;
6539 		connp->conn_fport = 0;
6540 
6541 		(void) ipcl_bind_insert(connp);
6542 	} else {
6543 		tcp->tcp_state = TCPS_BOUND;
6544 	}
6545 
6546 	/*
6547 	 * Initialize to default values
6548 	 */
6549 	tcp_init_values(tcp);
6550 
6551 	ASSERT(tcp->tcp_ptpbhn != NULL);
6552 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6553 	tcp->tcp_mss = connp->conn_ipversion != IPV4_VERSION ?
6554 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
6555 }
6556 
6557 /*
6558  * Force values to zero that need be zero.
6559  * Do not touch values asociated with the BOUND or LISTEN state
6560  * since the connection will end up in that state after the reinit.
6561  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
6562  * structure!
6563  */
6564 static void
6565 tcp_reinit_values(tcp)
6566 	tcp_t *tcp;
6567 {
6568 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6569 	conn_t		*connp = tcp->tcp_connp;
6570 
6571 #ifndef	lint
6572 #define	DONTCARE(x)
6573 #define	PRESERVE(x)
6574 #else
6575 #define	DONTCARE(x)	((x) = (x))
6576 #define	PRESERVE(x)	((x) = (x))
6577 #endif	/* lint */
6578 
6579 	PRESERVE(tcp->tcp_bind_hash_port);
6580 	PRESERVE(tcp->tcp_bind_hash);
6581 	PRESERVE(tcp->tcp_ptpbhn);
6582 	PRESERVE(tcp->tcp_acceptor_hash);
6583 	PRESERVE(tcp->tcp_ptpahn);
6584 
6585 	/* Should be ASSERT NULL on these with new code! */
6586 	ASSERT(tcp->tcp_time_wait_next == NULL);
6587 	ASSERT(tcp->tcp_time_wait_prev == NULL);
6588 	ASSERT(tcp->tcp_time_wait_expire == 0);
6589 	PRESERVE(tcp->tcp_state);
6590 	PRESERVE(connp->conn_rq);
6591 	PRESERVE(connp->conn_wq);
6592 
6593 	ASSERT(tcp->tcp_xmit_head == NULL);
6594 	ASSERT(tcp->tcp_xmit_last == NULL);
6595 	ASSERT(tcp->tcp_unsent == 0);
6596 	ASSERT(tcp->tcp_xmit_tail == NULL);
6597 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
6598 
6599 	tcp->tcp_snxt = 0;			/* Displayed in mib */
6600 	tcp->tcp_suna = 0;			/* Displayed in mib */
6601 	tcp->tcp_swnd = 0;
6602 	DONTCARE(tcp->tcp_cwnd);	/* Init in tcp_process_options */
6603 
6604 	ASSERT(tcp->tcp_ibsegs == 0);
6605 	ASSERT(tcp->tcp_obsegs == 0);
6606 
6607 	if (connp->conn_ht_iphc != NULL) {
6608 		kmem_free(connp->conn_ht_iphc, connp->conn_ht_iphc_allocated);
6609 		connp->conn_ht_iphc = NULL;
6610 		connp->conn_ht_iphc_allocated = 0;
6611 		connp->conn_ht_iphc_len = 0;
6612 		connp->conn_ht_ulp = NULL;
6613 		connp->conn_ht_ulp_len = 0;
6614 		tcp->tcp_ipha = NULL;
6615 		tcp->tcp_ip6h = NULL;
6616 		tcp->tcp_tcpha = NULL;
6617 	}
6618 
6619 	/* We clear any IP_OPTIONS and extension headers */
6620 	ip_pkt_free(&connp->conn_xmit_ipp);
6621 
6622 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
6623 	DONTCARE(tcp->tcp_ipha);
6624 	DONTCARE(tcp->tcp_ip6h);
6625 	DONTCARE(tcp->tcp_tcpha);
6626 	tcp->tcp_valid_bits = 0;
6627 
6628 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
6629 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
6630 	tcp->tcp_last_rcv_lbolt = 0;
6631 
6632 	tcp->tcp_init_cwnd = 0;
6633 
6634 	tcp->tcp_urp_last_valid = 0;
6635 	tcp->tcp_hard_binding = 0;
6636 
6637 	tcp->tcp_fin_acked = 0;
6638 	tcp->tcp_fin_rcvd = 0;
6639 	tcp->tcp_fin_sent = 0;
6640 	tcp->tcp_ordrel_done = 0;
6641 
6642 	tcp->tcp_detached = 0;
6643 
6644 	tcp->tcp_snd_ws_ok = B_FALSE;
6645 	tcp->tcp_snd_ts_ok = B_FALSE;
6646 	tcp->tcp_zero_win_probe = 0;
6647 
6648 	tcp->tcp_loopback = 0;
6649 	tcp->tcp_localnet = 0;
6650 	tcp->tcp_syn_defense = 0;
6651 	tcp->tcp_set_timer = 0;
6652 
6653 	tcp->tcp_active_open = 0;
6654 	tcp->tcp_rexmit = B_FALSE;
6655 	tcp->tcp_xmit_zc_clean = B_FALSE;
6656 
6657 	tcp->tcp_snd_sack_ok = B_FALSE;
6658 	tcp->tcp_hwcksum = B_FALSE;
6659 
6660 	DONTCARE(tcp->tcp_maxpsz_multiplier);	/* Init in tcp_init_values */
6661 
6662 	tcp->tcp_conn_def_q0 = 0;
6663 	tcp->tcp_ip_forward_progress = B_FALSE;
6664 	tcp->tcp_ecn_ok = B_FALSE;
6665 
6666 	tcp->tcp_cwr = B_FALSE;
6667 	tcp->tcp_ecn_echo_on = B_FALSE;
6668 	tcp->tcp_is_wnd_shrnk = B_FALSE;
6669 
6670 	if (tcp->tcp_sack_info != NULL) {
6671 		if (tcp->tcp_notsack_list != NULL) {
6672 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
6673 			    tcp);
6674 		}
6675 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
6676 		tcp->tcp_sack_info = NULL;
6677 	}
6678 
6679 	tcp->tcp_rcv_ws = 0;
6680 	tcp->tcp_snd_ws = 0;
6681 	tcp->tcp_ts_recent = 0;
6682 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
6683 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
6684 	tcp->tcp_initial_pmtu = 0;
6685 
6686 	ASSERT(tcp->tcp_reass_head == NULL);
6687 	ASSERT(tcp->tcp_reass_tail == NULL);
6688 
6689 	tcp->tcp_cwnd_cnt = 0;
6690 
6691 	ASSERT(tcp->tcp_rcv_list == NULL);
6692 	ASSERT(tcp->tcp_rcv_last_head == NULL);
6693 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
6694 	ASSERT(tcp->tcp_rcv_cnt == 0);
6695 
6696 	DONTCARE(tcp->tcp_cwnd_ssthresh); /* Init in tcp_set_destination */
6697 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
6698 	tcp->tcp_csuna = 0;
6699 
6700 	tcp->tcp_rto = 0;			/* Displayed in MIB */
6701 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
6702 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
6703 	tcp->tcp_rtt_update = 0;
6704 
6705 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6706 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
6707 
6708 	tcp->tcp_rack = 0;			/* Displayed in mib */
6709 	tcp->tcp_rack_cnt = 0;
6710 	tcp->tcp_rack_cur_max = 0;
6711 	tcp->tcp_rack_abs_max = 0;
6712 
6713 	tcp->tcp_max_swnd = 0;
6714 
6715 	ASSERT(tcp->tcp_listener == NULL);
6716 
6717 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
6718 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
6719 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
6720 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
6721 
6722 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
6723 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
6724 	PRESERVE(tcp->tcp_conn_req_max);
6725 	PRESERVE(tcp->tcp_conn_req_seqnum);
6726 
6727 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
6728 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
6729 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
6730 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
6731 
6732 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
6733 	ASSERT(tcp->tcp_urp_mp == NULL);
6734 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
6735 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
6736 
6737 	ASSERT(tcp->tcp_eager_next_q == NULL);
6738 	ASSERT(tcp->tcp_eager_last_q == NULL);
6739 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
6740 	    tcp->tcp_eager_prev_q0 == NULL) ||
6741 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
6742 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
6743 
6744 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
6745 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
6746 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
6747 
6748 	tcp->tcp_client_errno = 0;
6749 
6750 	DONTCARE(connp->conn_sum);		/* Init in tcp_init_values */
6751 
6752 	connp->conn_faddr_v6 = ipv6_all_zeros;	/* Displayed in MIB */
6753 
6754 	PRESERVE(connp->conn_bound_addr_v6);
6755 	tcp->tcp_last_sent_len = 0;
6756 	tcp->tcp_dupack_cnt = 0;
6757 
6758 	connp->conn_fport = 0;			/* Displayed in MIB */
6759 	PRESERVE(connp->conn_lport);
6760 
6761 	PRESERVE(tcp->tcp_acceptor_lockp);
6762 
6763 	ASSERT(tcp->tcp_ordrel_mp == NULL);
6764 	PRESERVE(tcp->tcp_acceptor_id);
6765 	DONTCARE(tcp->tcp_ipsec_overhead);
6766 
6767 	PRESERVE(connp->conn_family);
6768 	/* Remove any remnants of mapped address binding */
6769 	if (connp->conn_family == AF_INET6) {
6770 		connp->conn_ipversion = IPV6_VERSION;
6771 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
6772 	} else {
6773 		connp->conn_ipversion = IPV4_VERSION;
6774 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
6775 	}
6776 
6777 	connp->conn_bound_if = 0;
6778 	connp->conn_recv_ancillary.crb_all = 0;
6779 	tcp->tcp_recvifindex = 0;
6780 	tcp->tcp_recvhops = 0;
6781 	tcp->tcp_closed = 0;
6782 	tcp->tcp_cleandeathtag = 0;
6783 	if (tcp->tcp_hopopts != NULL) {
6784 		mi_free(tcp->tcp_hopopts);
6785 		tcp->tcp_hopopts = NULL;
6786 		tcp->tcp_hopoptslen = 0;
6787 	}
6788 	ASSERT(tcp->tcp_hopoptslen == 0);
6789 	if (tcp->tcp_dstopts != NULL) {
6790 		mi_free(tcp->tcp_dstopts);
6791 		tcp->tcp_dstopts = NULL;
6792 		tcp->tcp_dstoptslen = 0;
6793 	}
6794 	ASSERT(tcp->tcp_dstoptslen == 0);
6795 	if (tcp->tcp_rthdrdstopts != NULL) {
6796 		mi_free(tcp->tcp_rthdrdstopts);
6797 		tcp->tcp_rthdrdstopts = NULL;
6798 		tcp->tcp_rthdrdstoptslen = 0;
6799 	}
6800 	ASSERT(tcp->tcp_rthdrdstoptslen == 0);
6801 	if (tcp->tcp_rthdr != NULL) {
6802 		mi_free(tcp->tcp_rthdr);
6803 		tcp->tcp_rthdr = NULL;
6804 		tcp->tcp_rthdrlen = 0;
6805 	}
6806 	ASSERT(tcp->tcp_rthdrlen == 0);
6807 
6808 	/* Reset fusion-related fields */
6809 	tcp->tcp_fused = B_FALSE;
6810 	tcp->tcp_unfusable = B_FALSE;
6811 	tcp->tcp_fused_sigurg = B_FALSE;
6812 	tcp->tcp_loopback_peer = NULL;
6813 
6814 	tcp->tcp_lso = B_FALSE;
6815 
6816 	tcp->tcp_in_ack_unsent = 0;
6817 	tcp->tcp_cork = B_FALSE;
6818 	tcp->tcp_tconnind_started = B_FALSE;
6819 
6820 	PRESERVE(tcp->tcp_squeue_bytes);
6821 
6822 	ASSERT(tcp->tcp_kssl_ctx == NULL);
6823 	ASSERT(!tcp->tcp_kssl_pending);
6824 	PRESERVE(tcp->tcp_kssl_ent);
6825 
6826 	tcp->tcp_closemp_used = B_FALSE;
6827 
6828 	PRESERVE(tcp->tcp_rsrv_mp);
6829 	PRESERVE(tcp->tcp_rsrv_mp_lock);
6830 
6831 #ifdef DEBUG
6832 	DONTCARE(tcp->tcmp_stk[0]);
6833 #endif
6834 
6835 	PRESERVE(tcp->tcp_connid);
6836 
6837 	ASSERT(tcp->tcp_listen_cnt == NULL);
6838 	ASSERT(tcp->tcp_reass_tid == 0);
6839 
6840 #undef	DONTCARE
6841 #undef	PRESERVE
6842 }
6843 
6844 static void
6845 tcp_init_values(tcp_t *tcp)
6846 {
6847 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6848 	conn_t		*connp = tcp->tcp_connp;
6849 
6850 	ASSERT((connp->conn_family == AF_INET &&
6851 	    connp->conn_ipversion == IPV4_VERSION) ||
6852 	    (connp->conn_family == AF_INET6 &&
6853 	    (connp->conn_ipversion == IPV4_VERSION ||
6854 	    connp->conn_ipversion == IPV6_VERSION)));
6855 
6856 	/*
6857 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
6858 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
6859 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
6860 	 * during first few transmissions of a connection as seen in slow
6861 	 * links.
6862 	 */
6863 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
6864 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
6865 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
6866 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
6867 	    tcps->tcps_conn_grace_period;
6868 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
6869 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
6870 	tcp->tcp_timer_backoff = 0;
6871 	tcp->tcp_ms_we_have_waited = 0;
6872 	tcp->tcp_last_recv_time = ddi_get_lbolt();
6873 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
6874 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
6875 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
6876 
6877 	tcp->tcp_maxpsz_multiplier = tcps->tcps_maxpsz_multiplier;
6878 
6879 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
6880 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
6881 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
6882 	/*
6883 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
6884 	 * passive open.
6885 	 */
6886 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
6887 
6888 	tcp->tcp_naglim = tcps->tcps_naglim_def;
6889 
6890 	/* NOTE:  ISS is now set in tcp_set_destination(). */
6891 
6892 	/* Reset fusion-related fields */
6893 	tcp->tcp_fused = B_FALSE;
6894 	tcp->tcp_unfusable = B_FALSE;
6895 	tcp->tcp_fused_sigurg = B_FALSE;
6896 	tcp->tcp_loopback_peer = NULL;
6897 
6898 	/* We rebuild the header template on the next connect/conn_request */
6899 
6900 	connp->conn_mlp_type = mlptSingle;
6901 
6902 	/*
6903 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
6904 	 * down tcp_rwnd. tcp_set_destination() will set the right value later.
6905 	 */
6906 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
6907 	tcp->tcp_rwnd = connp->conn_rcvbuf;
6908 
6909 	tcp->tcp_cork = B_FALSE;
6910 	/*
6911 	 * Init the tcp_debug option if it wasn't already set.  This value
6912 	 * determines whether TCP
6913 	 * calls strlog() to print out debug messages.  Doing this
6914 	 * initialization here means that this value is not inherited thru
6915 	 * tcp_reinit().
6916 	 */
6917 	if (!connp->conn_debug)
6918 		connp->conn_debug = tcps->tcps_dbg;
6919 
6920 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
6921 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
6922 }
6923 
6924 /* At minimum we need 8 bytes in the TCP header for the lookup */
6925 #define	ICMP_MIN_TCP_HDR	8
6926 
6927 /*
6928  * tcp_icmp_input is called as conn_recvicmp to process ICMP error messages
6929  * passed up by IP. The message is always received on the correct tcp_t.
6930  * Assumes that IP has pulled up everything up to and including the ICMP header.
6931  */
6932 /* ARGSUSED2 */
6933 static void
6934 tcp_icmp_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
6935 {
6936 	conn_t		*connp = (conn_t *)arg1;
6937 	icmph_t		*icmph;
6938 	ipha_t		*ipha;
6939 	int		iph_hdr_length;
6940 	tcpha_t		*tcpha;
6941 	uint32_t	seg_seq;
6942 	tcp_t		*tcp = connp->conn_tcp;
6943 
6944 	/* Assume IP provides aligned packets */
6945 	ASSERT(OK_32PTR(mp->b_rptr));
6946 	ASSERT((MBLKL(mp) >= sizeof (ipha_t)));
6947 
6948 	/*
6949 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
6950 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
6951 	 */
6952 	if (!(ira->ira_flags & IRAF_IS_IPV4)) {
6953 		tcp_icmp_error_ipv6(tcp, mp, ira);
6954 		return;
6955 	}
6956 
6957 	/* Skip past the outer IP and ICMP headers */
6958 	iph_hdr_length = ira->ira_ip_hdr_length;
6959 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
6960 	/*
6961 	 * If we don't have the correct outer IP header length
6962 	 * or if we don't have a complete inner IP header
6963 	 * drop it.
6964 	 */
6965 	if (iph_hdr_length < sizeof (ipha_t) ||
6966 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
6967 noticmpv4:
6968 		freemsg(mp);
6969 		return;
6970 	}
6971 	ipha = (ipha_t *)&icmph[1];
6972 
6973 	/* Skip past the inner IP and find the ULP header */
6974 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
6975 	tcpha = (tcpha_t *)((char *)ipha + iph_hdr_length);
6976 	/*
6977 	 * If we don't have the correct inner IP header length or if the ULP
6978 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
6979 	 * bytes of TCP header, drop it.
6980 	 */
6981 	if (iph_hdr_length < sizeof (ipha_t) ||
6982 	    ipha->ipha_protocol != IPPROTO_TCP ||
6983 	    (uchar_t *)tcpha + ICMP_MIN_TCP_HDR > mp->b_wptr) {
6984 		goto noticmpv4;
6985 	}
6986 
6987 	seg_seq = ntohl(tcpha->tha_seq);
6988 	switch (icmph->icmph_type) {
6989 	case ICMP_DEST_UNREACHABLE:
6990 		switch (icmph->icmph_code) {
6991 		case ICMP_FRAGMENTATION_NEEDED:
6992 			/*
6993 			 * Update Path MTU, then try to send something out.
6994 			 */
6995 			tcp_update_pmtu(tcp, B_TRUE);
6996 			tcp_rexmit_after_error(tcp);
6997 			break;
6998 		case ICMP_PORT_UNREACHABLE:
6999 		case ICMP_PROTOCOL_UNREACHABLE:
7000 			switch (tcp->tcp_state) {
7001 			case TCPS_SYN_SENT:
7002 			case TCPS_SYN_RCVD:
7003 				/*
7004 				 * ICMP can snipe away incipient
7005 				 * TCP connections as long as
7006 				 * seq number is same as initial
7007 				 * send seq number.
7008 				 */
7009 				if (seg_seq == tcp->tcp_iss) {
7010 					(void) tcp_clean_death(tcp,
7011 					    ECONNREFUSED, 6);
7012 				}
7013 				break;
7014 			}
7015 			break;
7016 		case ICMP_HOST_UNREACHABLE:
7017 		case ICMP_NET_UNREACHABLE:
7018 			/* Record the error in case we finally time out. */
7019 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
7020 				tcp->tcp_client_errno = EHOSTUNREACH;
7021 			else
7022 				tcp->tcp_client_errno = ENETUNREACH;
7023 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
7024 				if (tcp->tcp_listener != NULL &&
7025 				    tcp->tcp_listener->tcp_syn_defense) {
7026 					/*
7027 					 * Ditch the half-open connection if we
7028 					 * suspect a SYN attack is under way.
7029 					 */
7030 					(void) tcp_clean_death(tcp,
7031 					    tcp->tcp_client_errno, 7);
7032 				}
7033 			}
7034 			break;
7035 		default:
7036 			break;
7037 		}
7038 		break;
7039 	case ICMP_SOURCE_QUENCH: {
7040 		/*
7041 		 * use a global boolean to control
7042 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
7043 		 * The default is false.
7044 		 */
7045 		if (tcp_icmp_source_quench) {
7046 			/*
7047 			 * Reduce the sending rate as if we got a
7048 			 * retransmit timeout
7049 			 */
7050 			uint32_t npkt;
7051 
7052 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
7053 			    tcp->tcp_mss;
7054 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
7055 			tcp->tcp_cwnd = tcp->tcp_mss;
7056 			tcp->tcp_cwnd_cnt = 0;
7057 		}
7058 		break;
7059 	}
7060 	}
7061 	freemsg(mp);
7062 }
7063 
7064 /*
7065  * CALLED OUTSIDE OF SQUEUE! It can not follow any pointers that tcp might
7066  * change. But it can refer to fields like tcp_suna and tcp_snxt.
7067  *
7068  * Function tcp_verifyicmp is called as conn_verifyicmp to verify the ICMP
7069  * error messages received by IP. The message is always received on the correct
7070  * tcp_t.
7071  */
7072 /* ARGSUSED */
7073 static boolean_t
7074 tcp_verifyicmp(conn_t *connp, void *arg2, icmph_t *icmph, icmp6_t *icmp6,
7075     ip_recv_attr_t *ira)
7076 {
7077 	tcpha_t		*tcpha = (tcpha_t *)arg2;
7078 	uint32_t	seq = ntohl(tcpha->tha_seq);
7079 	tcp_t		*tcp = connp->conn_tcp;
7080 
7081 	/*
7082 	 * TCP sequence number contained in payload of the ICMP error message
7083 	 * should be within the range SND.UNA <= SEG.SEQ < SND.NXT. Otherwise,
7084 	 * the message is either a stale ICMP error, or an attack from the
7085 	 * network. Fail the verification.
7086 	 */
7087 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
7088 		return (B_FALSE);
7089 
7090 	/* For "too big" we also check the ignore flag */
7091 	if (ira->ira_flags & IRAF_IS_IPV4) {
7092 		ASSERT(icmph != NULL);
7093 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
7094 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
7095 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7096 			return (B_FALSE);
7097 	} else {
7098 		ASSERT(icmp6 != NULL);
7099 		if (icmp6->icmp6_type == ICMP6_PACKET_TOO_BIG &&
7100 		    tcp->tcp_tcps->tcps_ignore_path_mtu)
7101 			return (B_FALSE);
7102 	}
7103 	return (B_TRUE);
7104 }
7105 
7106 /*
7107  * Update the TCP connection according to change of PMTU.
7108  *
7109  * Path MTU might have changed by either increase or decrease, so need to
7110  * adjust the MSS based on the value of ixa_pmtu. No need to handle tiny
7111  * or negative MSS, since tcp_mss_set() will do it.
7112  */
7113 static void
7114 tcp_update_pmtu(tcp_t *tcp, boolean_t decrease_only)
7115 {
7116 	uint32_t	pmtu;
7117 	int32_t		mss;
7118 	conn_t		*connp = tcp->tcp_connp;
7119 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
7120 	iaflags_t	ixaflags;
7121 
7122 	if (tcp->tcp_tcps->tcps_ignore_path_mtu)
7123 		return;
7124 
7125 	if (tcp->tcp_state < TCPS_ESTABLISHED)
7126 		return;
7127 
7128 	/*
7129 	 * Always call ip_get_pmtu() to make sure that IP has updated
7130 	 * ixa_flags properly.
7131 	 */
7132 	pmtu = ip_get_pmtu(ixa);
7133 	ixaflags = ixa->ixa_flags;
7134 
7135 	/*
7136 	 * Calculate the MSS by decreasing the PMTU by conn_ht_iphc_len and
7137 	 * IPsec overhead if applied. Make sure to use the most recent
7138 	 * IPsec information.
7139 	 */
7140 	mss = pmtu - connp->conn_ht_iphc_len - conn_ipsec_length(connp);
7141 
7142 	/*
7143 	 * Nothing to change, so just return.
7144 	 */
7145 	if (mss == tcp->tcp_mss)
7146 		return;
7147 
7148 	/*
7149 	 * Currently, for ICMP errors, only PMTU decrease is handled.
7150 	 */
7151 	if (mss > tcp->tcp_mss && decrease_only)
7152 		return;
7153 
7154 	DTRACE_PROBE2(tcp_update_pmtu, int32_t, tcp->tcp_mss, uint32_t, mss);
7155 
7156 	/*
7157 	 * Update ixa_fragsize and ixa_pmtu.
7158 	 */
7159 	ixa->ixa_fragsize = ixa->ixa_pmtu = pmtu;
7160 
7161 	/*
7162 	 * Adjust MSS and all relevant variables.
7163 	 */
7164 	tcp_mss_set(tcp, mss);
7165 
7166 	/*
7167 	 * If the PMTU is below the min size maintained by IP, then ip_get_pmtu
7168 	 * has set IXAF_PMTU_TOO_SMALL and cleared IXAF_PMTU_IPV4_DF. Since TCP
7169 	 * has a (potentially different) min size we do the same. Make sure to
7170 	 * clear IXAF_DONTFRAG, which is used by IP to decide whether to
7171 	 * fragment the packet.
7172 	 *
7173 	 * LSO over IPv6 can not be fragmented. So need to disable LSO
7174 	 * when IPv6 fragmentation is needed.
7175 	 */
7176 	if (mss < tcp->tcp_tcps->tcps_mss_min)
7177 		ixaflags |= IXAF_PMTU_TOO_SMALL;
7178 
7179 	if (ixaflags & IXAF_PMTU_TOO_SMALL)
7180 		ixaflags &= ~(IXAF_DONTFRAG | IXAF_PMTU_IPV4_DF);
7181 
7182 	if ((connp->conn_ipversion == IPV4_VERSION) &&
7183 	    !(ixaflags & IXAF_PMTU_IPV4_DF)) {
7184 		tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
7185 	}
7186 	ixa->ixa_flags = ixaflags;
7187 }
7188 
7189 /*
7190  * Do slow start retransmission after ICMP errors of PMTU changes.
7191  */
7192 static void
7193 tcp_rexmit_after_error(tcp_t *tcp)
7194 {
7195 	/*
7196 	 * All sent data has been acknowledged or no data left to send, just
7197 	 * to return.
7198 	 */
7199 	if (!SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) ||
7200 	    (tcp->tcp_xmit_head == NULL))
7201 		return;
7202 
7203 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) && (tcp->tcp_unsent == 0))
7204 		tcp->tcp_rexmit_max = tcp->tcp_fss;
7205 	else
7206 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
7207 
7208 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
7209 	tcp->tcp_rexmit = B_TRUE;
7210 	tcp->tcp_dupack_cnt = 0;
7211 	tcp->tcp_snd_burst = TCP_CWND_SS;
7212 	tcp_ss_rexmit(tcp);
7213 }
7214 
7215 /*
7216  * tcp_icmp_error_ipv6 is called from tcp_icmp_input to process ICMPv6
7217  * error messages passed up by IP.
7218  * Assumes that IP has pulled up all the extension headers as well
7219  * as the ICMPv6 header.
7220  */
7221 static void
7222 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, ip_recv_attr_t *ira)
7223 {
7224 	icmp6_t		*icmp6;
7225 	ip6_t		*ip6h;
7226 	uint16_t	iph_hdr_length = ira->ira_ip_hdr_length;
7227 	tcpha_t		*tcpha;
7228 	uint8_t		*nexthdrp;
7229 	uint32_t	seg_seq;
7230 
7231 	/*
7232 	 * Verify that we have a complete IP header.
7233 	 */
7234 	ASSERT((MBLKL(mp) >= sizeof (ip6_t)));
7235 
7236 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
7237 	ip6h = (ip6_t *)&icmp6[1];
7238 	/*
7239 	 * Verify if we have a complete ICMP and inner IP header.
7240 	 */
7241 	if ((uchar_t *)&ip6h[1] > mp->b_wptr) {
7242 noticmpv6:
7243 		freemsg(mp);
7244 		return;
7245 	}
7246 
7247 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
7248 		goto noticmpv6;
7249 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
7250 	/*
7251 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
7252 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
7253 	 * packet.
7254 	 */
7255 	if ((*nexthdrp != IPPROTO_TCP) ||
7256 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
7257 		goto noticmpv6;
7258 	}
7259 
7260 	seg_seq = ntohl(tcpha->tha_seq);
7261 	switch (icmp6->icmp6_type) {
7262 	case ICMP6_PACKET_TOO_BIG:
7263 		/*
7264 		 * Update Path MTU, then try to send something out.
7265 		 */
7266 		tcp_update_pmtu(tcp, B_TRUE);
7267 		tcp_rexmit_after_error(tcp);
7268 		break;
7269 	case ICMP6_DST_UNREACH:
7270 		switch (icmp6->icmp6_code) {
7271 		case ICMP6_DST_UNREACH_NOPORT:
7272 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7273 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7274 			    (seg_seq == tcp->tcp_iss)) {
7275 				(void) tcp_clean_death(tcp,
7276 				    ECONNREFUSED, 8);
7277 			}
7278 			break;
7279 		case ICMP6_DST_UNREACH_ADMIN:
7280 		case ICMP6_DST_UNREACH_NOROUTE:
7281 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
7282 		case ICMP6_DST_UNREACH_ADDR:
7283 			/* Record the error in case we finally time out. */
7284 			tcp->tcp_client_errno = EHOSTUNREACH;
7285 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
7286 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
7287 			    (seg_seq == tcp->tcp_iss)) {
7288 				if (tcp->tcp_listener != NULL &&
7289 				    tcp->tcp_listener->tcp_syn_defense) {
7290 					/*
7291 					 * Ditch the half-open connection if we
7292 					 * suspect a SYN attack is under way.
7293 					 */
7294 					(void) tcp_clean_death(tcp,
7295 					    tcp->tcp_client_errno, 9);
7296 				}
7297 			}
7298 
7299 
7300 			break;
7301 		default:
7302 			break;
7303 		}
7304 		break;
7305 	case ICMP6_PARAM_PROB:
7306 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
7307 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
7308 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
7309 		    (uchar_t *)nexthdrp) {
7310 			if (tcp->tcp_state == TCPS_SYN_SENT ||
7311 			    tcp->tcp_state == TCPS_SYN_RCVD) {
7312 				(void) tcp_clean_death(tcp,
7313 				    ECONNREFUSED, 10);
7314 			}
7315 			break;
7316 		}
7317 		break;
7318 
7319 	case ICMP6_TIME_EXCEEDED:
7320 	default:
7321 		break;
7322 	}
7323 	freemsg(mp);
7324 }
7325 
7326 /*
7327  * Notify IP that we are having trouble with this connection.  IP should
7328  * make note so it can potentially use a different IRE.
7329  */
7330 static void
7331 tcp_ip_notify(tcp_t *tcp)
7332 {
7333 	conn_t		*connp = tcp->tcp_connp;
7334 	ire_t		*ire;
7335 
7336 	/*
7337 	 * Note: in the case of source routing we want to blow away the
7338 	 * route to the first source route hop.
7339 	 */
7340 	ire = connp->conn_ixa->ixa_ire;
7341 	if (ire != NULL && !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
7342 		if (ire->ire_ipversion == IPV4_VERSION) {
7343 			/*
7344 			 * As per RFC 1122, we send an RTM_LOSING to inform
7345 			 * routing protocols.
7346 			 */
7347 			ip_rts_change(RTM_LOSING, ire->ire_addr,
7348 			    ire->ire_gateway_addr, ire->ire_mask,
7349 			    connp->conn_laddr_v4,  0, 0, 0,
7350 			    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA),
7351 			    ire->ire_ipst);
7352 		}
7353 		(void) ire_no_good(ire);
7354 	}
7355 }
7356 
7357 #pragma inline(tcp_send_data)
7358 
7359 /*
7360  * Timer callback routine for keepalive probe.  We do a fake resend of
7361  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
7362  * check to see if we have heard anything from the other end for the last
7363  * RTO period.  If we have, set the timer to expire for another
7364  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
7365  * RTO << 1 and check again when it expires.  Keep exponentially increasing
7366  * the timeout if we have not heard from the other side.  If for more than
7367  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
7368  * kill the connection unless the keepalive abort threshold is 0.  In
7369  * that case, we will probe "forever."
7370  */
7371 static void
7372 tcp_keepalive_killer(void *arg)
7373 {
7374 	mblk_t	*mp;
7375 	conn_t	*connp = (conn_t *)arg;
7376 	tcp_t  	*tcp = connp->conn_tcp;
7377 	int32_t	firetime;
7378 	int32_t	idletime;
7379 	int32_t	ka_intrvl;
7380 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7381 
7382 	tcp->tcp_ka_tid = 0;
7383 
7384 	if (tcp->tcp_fused)
7385 		return;
7386 
7387 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
7388 	ka_intrvl = tcp->tcp_ka_interval;
7389 
7390 	/*
7391 	 * Keepalive probe should only be sent if the application has not
7392 	 * done a close on the connection.
7393 	 */
7394 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
7395 		return;
7396 	}
7397 	/* Timer fired too early, restart it. */
7398 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
7399 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7400 		    MSEC_TO_TICK(ka_intrvl));
7401 		return;
7402 	}
7403 
7404 	idletime = TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time);
7405 	/*
7406 	 * If we have not heard from the other side for a long
7407 	 * time, kill the connection unless the keepalive abort
7408 	 * threshold is 0.  In that case, we will probe "forever."
7409 	 */
7410 	if (tcp->tcp_ka_abort_thres != 0 &&
7411 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
7412 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
7413 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
7414 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
7415 		return;
7416 	}
7417 
7418 	if (tcp->tcp_snxt == tcp->tcp_suna &&
7419 	    idletime >= ka_intrvl) {
7420 		/* Fake resend of last ACKed byte. */
7421 		mblk_t	*mp1 = allocb(1, BPRI_LO);
7422 
7423 		if (mp1 != NULL) {
7424 			*mp1->b_wptr++ = '\0';
7425 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
7426 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
7427 			freeb(mp1);
7428 			/*
7429 			 * if allocation failed, fall through to start the
7430 			 * timer back.
7431 			 */
7432 			if (mp != NULL) {
7433 				tcp_send_data(tcp, mp);
7434 				BUMP_MIB(&tcps->tcps_mib,
7435 				    tcpTimKeepaliveProbe);
7436 				if (tcp->tcp_ka_last_intrvl != 0) {
7437 					int max;
7438 					/*
7439 					 * We should probe again at least
7440 					 * in ka_intrvl, but not more than
7441 					 * tcp_rexmit_interval_max.
7442 					 */
7443 					max = tcps->tcps_rexmit_interval_max;
7444 					firetime = MIN(ka_intrvl - 1,
7445 					    tcp->tcp_ka_last_intrvl << 1);
7446 					if (firetime > max)
7447 						firetime = max;
7448 				} else {
7449 					firetime = tcp->tcp_rto;
7450 				}
7451 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
7452 				    tcp_keepalive_killer,
7453 				    MSEC_TO_TICK(firetime));
7454 				tcp->tcp_ka_last_intrvl = firetime;
7455 				return;
7456 			}
7457 		}
7458 	} else {
7459 		tcp->tcp_ka_last_intrvl = 0;
7460 	}
7461 
7462 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
7463 	if ((firetime = ka_intrvl - idletime) < 0) {
7464 		firetime = ka_intrvl;
7465 	}
7466 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
7467 	    MSEC_TO_TICK(firetime));
7468 }
7469 
7470 int
7471 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
7472 {
7473 	conn_t	*connp = tcp->tcp_connp;
7474 	queue_t	*q = connp->conn_rq;
7475 	int32_t	mss = tcp->tcp_mss;
7476 	int	maxpsz;
7477 
7478 	if (TCP_IS_DETACHED(tcp))
7479 		return (mss);
7480 	if (tcp->tcp_fused) {
7481 		maxpsz = tcp_fuse_maxpsz(tcp);
7482 		mss = INFPSZ;
7483 	} else if (tcp->tcp_maxpsz_multiplier == 0) {
7484 		/*
7485 		 * Set the sd_qn_maxpsz according to the socket send buffer
7486 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
7487 		 * instruct the stream head to copyin user data into contiguous
7488 		 * kernel-allocated buffers without breaking it up into smaller
7489 		 * chunks.  We round up the buffer size to the nearest SMSS.
7490 		 */
7491 		maxpsz = MSS_ROUNDUP(connp->conn_sndbuf, mss);
7492 		if (tcp->tcp_kssl_ctx == NULL)
7493 			mss = INFPSZ;
7494 		else
7495 			mss = SSL3_MAX_RECORD_LEN;
7496 	} else {
7497 		/*
7498 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
7499 		 * (and a multiple of the mss).  This instructs the stream
7500 		 * head to break down larger than SMSS writes into SMSS-
7501 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
7502 		 */
7503 		maxpsz = tcp->tcp_maxpsz_multiplier * mss;
7504 		if (maxpsz > connp->conn_sndbuf / 2) {
7505 			maxpsz = connp->conn_sndbuf / 2;
7506 			/* Round up to nearest mss */
7507 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
7508 		}
7509 	}
7510 
7511 	(void) proto_set_maxpsz(q, connp, maxpsz);
7512 	if (!(IPCL_IS_NONSTR(connp)))
7513 		connp->conn_wq->q_maxpsz = maxpsz;
7514 	if (set_maxblk)
7515 		(void) proto_set_tx_maxblk(q, connp, mss);
7516 	return (mss);
7517 }
7518 
7519 /*
7520  * Extract option values from a tcp header.  We put any found values into the
7521  * tcpopt struct and return a bitmask saying which options were found.
7522  */
7523 static int
7524 tcp_parse_options(tcpha_t *tcpha, tcp_opt_t *tcpopt)
7525 {
7526 	uchar_t		*endp;
7527 	int		len;
7528 	uint32_t	mss;
7529 	uchar_t		*up = (uchar_t *)tcpha;
7530 	int		found = 0;
7531 	int32_t		sack_len;
7532 	tcp_seq		sack_begin, sack_end;
7533 	tcp_t		*tcp;
7534 
7535 	endp = up + TCP_HDR_LENGTH(tcpha);
7536 	up += TCP_MIN_HEADER_LENGTH;
7537 	while (up < endp) {
7538 		len = endp - up;
7539 		switch (*up) {
7540 		case TCPOPT_EOL:
7541 			break;
7542 
7543 		case TCPOPT_NOP:
7544 			up++;
7545 			continue;
7546 
7547 		case TCPOPT_MAXSEG:
7548 			if (len < TCPOPT_MAXSEG_LEN ||
7549 			    up[1] != TCPOPT_MAXSEG_LEN)
7550 				break;
7551 
7552 			mss = BE16_TO_U16(up+2);
7553 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
7554 			tcpopt->tcp_opt_mss = mss;
7555 			found |= TCP_OPT_MSS_PRESENT;
7556 
7557 			up += TCPOPT_MAXSEG_LEN;
7558 			continue;
7559 
7560 		case TCPOPT_WSCALE:
7561 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
7562 				break;
7563 
7564 			if (up[2] > TCP_MAX_WINSHIFT)
7565 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
7566 			else
7567 				tcpopt->tcp_opt_wscale = up[2];
7568 			found |= TCP_OPT_WSCALE_PRESENT;
7569 
7570 			up += TCPOPT_WS_LEN;
7571 			continue;
7572 
7573 		case TCPOPT_SACK_PERMITTED:
7574 			if (len < TCPOPT_SACK_OK_LEN ||
7575 			    up[1] != TCPOPT_SACK_OK_LEN)
7576 				break;
7577 			found |= TCP_OPT_SACK_OK_PRESENT;
7578 			up += TCPOPT_SACK_OK_LEN;
7579 			continue;
7580 
7581 		case TCPOPT_SACK:
7582 			if (len <= 2 || up[1] <= 2 || len < up[1])
7583 				break;
7584 
7585 			/* If TCP is not interested in SACK blks... */
7586 			if ((tcp = tcpopt->tcp) == NULL) {
7587 				up += up[1];
7588 				continue;
7589 			}
7590 			sack_len = up[1] - TCPOPT_HEADER_LEN;
7591 			up += TCPOPT_HEADER_LEN;
7592 
7593 			/*
7594 			 * If the list is empty, allocate one and assume
7595 			 * nothing is sack'ed.
7596 			 */
7597 			ASSERT(tcp->tcp_sack_info != NULL);
7598 			if (tcp->tcp_notsack_list == NULL) {
7599 				tcp_notsack_update(&(tcp->tcp_notsack_list),
7600 				    tcp->tcp_suna, tcp->tcp_snxt,
7601 				    &(tcp->tcp_num_notsack_blk),
7602 				    &(tcp->tcp_cnt_notsack_list));
7603 
7604 				/*
7605 				 * Make sure tcp_notsack_list is not NULL.
7606 				 * This happens when kmem_alloc(KM_NOSLEEP)
7607 				 * returns NULL.
7608 				 */
7609 				if (tcp->tcp_notsack_list == NULL) {
7610 					up += sack_len;
7611 					continue;
7612 				}
7613 				tcp->tcp_fack = tcp->tcp_suna;
7614 			}
7615 
7616 			while (sack_len > 0) {
7617 				if (up + 8 > endp) {
7618 					up = endp;
7619 					break;
7620 				}
7621 				sack_begin = BE32_TO_U32(up);
7622 				up += 4;
7623 				sack_end = BE32_TO_U32(up);
7624 				up += 4;
7625 				sack_len -= 8;
7626 				/*
7627 				 * Bounds checking.  Make sure the SACK
7628 				 * info is within tcp_suna and tcp_snxt.
7629 				 * If this SACK blk is out of bound, ignore
7630 				 * it but continue to parse the following
7631 				 * blks.
7632 				 */
7633 				if (SEQ_LEQ(sack_end, sack_begin) ||
7634 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
7635 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
7636 					continue;
7637 				}
7638 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
7639 				    sack_begin, sack_end,
7640 				    &(tcp->tcp_num_notsack_blk),
7641 				    &(tcp->tcp_cnt_notsack_list));
7642 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
7643 					tcp->tcp_fack = sack_end;
7644 				}
7645 			}
7646 			found |= TCP_OPT_SACK_PRESENT;
7647 			continue;
7648 
7649 		case TCPOPT_TSTAMP:
7650 			if (len < TCPOPT_TSTAMP_LEN ||
7651 			    up[1] != TCPOPT_TSTAMP_LEN)
7652 				break;
7653 
7654 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
7655 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
7656 
7657 			found |= TCP_OPT_TSTAMP_PRESENT;
7658 
7659 			up += TCPOPT_TSTAMP_LEN;
7660 			continue;
7661 
7662 		default:
7663 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
7664 				break;
7665 			up += up[1];
7666 			continue;
7667 		}
7668 		break;
7669 	}
7670 	return (found);
7671 }
7672 
7673 /*
7674  * Set the MSS associated with a particular tcp based on its current value,
7675  * and a new one passed in. Observe minimums and maximums, and reset other
7676  * state variables that we want to view as multiples of MSS.
7677  *
7678  * The value of MSS could be either increased or descreased.
7679  */
7680 static void
7681 tcp_mss_set(tcp_t *tcp, uint32_t mss)
7682 {
7683 	uint32_t	mss_max;
7684 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7685 	conn_t		*connp = tcp->tcp_connp;
7686 
7687 	if (connp->conn_ipversion == IPV4_VERSION)
7688 		mss_max = tcps->tcps_mss_max_ipv4;
7689 	else
7690 		mss_max = tcps->tcps_mss_max_ipv6;
7691 
7692 	if (mss < tcps->tcps_mss_min)
7693 		mss = tcps->tcps_mss_min;
7694 	if (mss > mss_max)
7695 		mss = mss_max;
7696 	/*
7697 	 * Unless naglim has been set by our client to
7698 	 * a non-mss value, force naglim to track mss.
7699 	 * This can help to aggregate small writes.
7700 	 */
7701 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
7702 		tcp->tcp_naglim = mss;
7703 	/*
7704 	 * TCP should be able to buffer at least 4 MSS data for obvious
7705 	 * performance reason.
7706 	 */
7707 	if ((mss << 2) > connp->conn_sndbuf)
7708 		connp->conn_sndbuf = mss << 2;
7709 
7710 	/*
7711 	 * Set the send lowater to at least twice of MSS.
7712 	 */
7713 	if ((mss << 1) > connp->conn_sndlowat)
7714 		connp->conn_sndlowat = mss << 1;
7715 
7716 	/*
7717 	 * Update tcp_cwnd according to the new value of MSS. Keep the
7718 	 * previous ratio to preserve the transmit rate.
7719 	 */
7720 	tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
7721 	tcp->tcp_cwnd_cnt = 0;
7722 
7723 	tcp->tcp_mss = mss;
7724 	(void) tcp_maxpsz_set(tcp, B_TRUE);
7725 }
7726 
7727 /* For /dev/tcp aka AF_INET open */
7728 static int
7729 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7730 {
7731 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
7732 }
7733 
7734 /* For /dev/tcp6 aka AF_INET6 open */
7735 static int
7736 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
7737 {
7738 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
7739 }
7740 
7741 static conn_t *
7742 tcp_create_common(cred_t *credp, boolean_t isv6, boolean_t issocket,
7743     int *errorp)
7744 {
7745 	tcp_t		*tcp = NULL;
7746 	conn_t		*connp;
7747 	zoneid_t	zoneid;
7748 	tcp_stack_t	*tcps;
7749 	squeue_t	*sqp;
7750 
7751 	ASSERT(errorp != NULL);
7752 	/*
7753 	 * Find the proper zoneid and netstack.
7754 	 */
7755 	/*
7756 	 * Special case for install: miniroot needs to be able to
7757 	 * access files via NFS as though it were always in the
7758 	 * global zone.
7759 	 */
7760 	if (credp == kcred && nfs_global_client_only != 0) {
7761 		zoneid = GLOBAL_ZONEID;
7762 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
7763 		    netstack_tcp;
7764 		ASSERT(tcps != NULL);
7765 	} else {
7766 		netstack_t *ns;
7767 
7768 		ns = netstack_find_by_cred(credp);
7769 		ASSERT(ns != NULL);
7770 		tcps = ns->netstack_tcp;
7771 		ASSERT(tcps != NULL);
7772 
7773 		/*
7774 		 * For exclusive stacks we set the zoneid to zero
7775 		 * to make TCP operate as if in the global zone.
7776 		 */
7777 		if (tcps->tcps_netstack->netstack_stackid !=
7778 		    GLOBAL_NETSTACKID)
7779 			zoneid = GLOBAL_ZONEID;
7780 		else
7781 			zoneid = crgetzoneid(credp);
7782 	}
7783 
7784 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
7785 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
7786 	/*
7787 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
7788 	 * so we drop it by one.
7789 	 */
7790 	netstack_rele(tcps->tcps_netstack);
7791 	if (connp == NULL) {
7792 		*errorp = ENOSR;
7793 		return (NULL);
7794 	}
7795 	ASSERT(connp->conn_ixa->ixa_protocol == connp->conn_proto);
7796 
7797 	connp->conn_sqp = sqp;
7798 	connp->conn_initial_sqp = connp->conn_sqp;
7799 	connp->conn_ixa->ixa_sqp = connp->conn_sqp;
7800 	tcp = connp->conn_tcp;
7801 
7802 	/*
7803 	 * Besides asking IP to set the checksum for us, have conn_ip_output
7804 	 * to do the following checks when necessary:
7805 	 *
7806 	 * IXAF_VERIFY_SOURCE: drop packets when our outer source goes invalid
7807 	 * IXAF_VERIFY_PMTU: verify PMTU changes
7808 	 * IXAF_VERIFY_LSO: verify LSO capability changes
7809 	 */
7810 	connp->conn_ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE |
7811 	    IXAF_VERIFY_PMTU | IXAF_VERIFY_LSO;
7812 
7813 	if (!tcps->tcps_dev_flow_ctl)
7814 		connp->conn_ixa->ixa_flags |= IXAF_NO_DEV_FLOW_CTL;
7815 
7816 	if (isv6) {
7817 		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
7818 		connp->conn_ipversion = IPV6_VERSION;
7819 		connp->conn_family = AF_INET6;
7820 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7821 		connp->conn_default_ttl = tcps->tcps_ipv6_hoplimit;
7822 	} else {
7823 		connp->conn_ipversion = IPV4_VERSION;
7824 		connp->conn_family = AF_INET;
7825 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7826 		connp->conn_default_ttl = tcps->tcps_ipv4_ttl;
7827 	}
7828 	connp->conn_xmit_ipp.ipp_unicast_hops = connp->conn_default_ttl;
7829 
7830 	crhold(credp);
7831 	connp->conn_cred = credp;
7832 	connp->conn_cpid = curproc->p_pid;
7833 	connp->conn_open_time = ddi_get_lbolt64();
7834 
7835 	connp->conn_zoneid = zoneid;
7836 	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
7837 	connp->conn_ixa->ixa_zoneid = zoneid;
7838 	connp->conn_mlp_type = mlptSingle;
7839 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
7840 	ASSERT(tcp->tcp_tcps == tcps);
7841 
7842 	/*
7843 	 * If the caller has the process-wide flag set, then default to MAC
7844 	 * exempt mode.  This allows read-down to unlabeled hosts.
7845 	 */
7846 	if (getpflags(NET_MAC_AWARE, credp) != 0)
7847 		connp->conn_mac_mode = CONN_MAC_AWARE;
7848 
7849 	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);
7850 
7851 	if (issocket) {
7852 		tcp->tcp_issocket = 1;
7853 	}
7854 
7855 	connp->conn_rcvbuf = tcps->tcps_recv_hiwat;
7856 	connp->conn_sndbuf = tcps->tcps_xmit_hiwat;
7857 	connp->conn_sndlowat = tcps->tcps_xmit_lowat;
7858 	connp->conn_so_type = SOCK_STREAM;
7859 	connp->conn_wroff = connp->conn_ht_iphc_allocated +
7860 	    tcps->tcps_wroff_xtra;
7861 
7862 	SOCK_CONNID_INIT(tcp->tcp_connid);
7863 	tcp->tcp_state = TCPS_IDLE;
7864 	tcp_init_values(tcp);
7865 	return (connp);
7866 }
7867 
7868 static int
7869 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
7870     boolean_t isv6)
7871 {
7872 	tcp_t		*tcp = NULL;
7873 	conn_t		*connp = NULL;
7874 	int		err;
7875 	vmem_t		*minor_arena = NULL;
7876 	dev_t		conn_dev;
7877 	boolean_t	issocket;
7878 
7879 	if (q->q_ptr != NULL)
7880 		return (0);
7881 
7882 	if (sflag == MODOPEN)
7883 		return (EINVAL);
7884 
7885 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
7886 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
7887 		minor_arena = ip_minor_arena_la;
7888 	} else {
7889 		/*
7890 		 * Either minor numbers in the large arena were exhausted
7891 		 * or a non socket application is doing the open.
7892 		 * Try to allocate from the small arena.
7893 		 */
7894 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
7895 			return (EBUSY);
7896 		}
7897 		minor_arena = ip_minor_arena_sa;
7898 	}
7899 
7900 	ASSERT(minor_arena != NULL);
7901 
7902 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
7903 
7904 	if (flag & SO_FALLBACK) {
7905 		/*
7906 		 * Non streams socket needs a stream to fallback to
7907 		 */
7908 		RD(q)->q_ptr = (void *)conn_dev;
7909 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
7910 		WR(q)->q_ptr = (void *)minor_arena;
7911 		qprocson(q);
7912 		return (0);
7913 	} else if (flag & SO_ACCEPTOR) {
7914 		q->q_qinfo = &tcp_acceptor_rinit;
7915 		/*
7916 		 * the conn_dev and minor_arena will be subsequently used by
7917 		 * tcp_tli_accept() and tcp_tpi_close_accept() to figure out
7918 		 * the minor device number for this connection from the q_ptr.
7919 		 */
7920 		RD(q)->q_ptr = (void *)conn_dev;
7921 		WR(q)->q_qinfo = &tcp_acceptor_winit;
7922 		WR(q)->q_ptr = (void *)minor_arena;
7923 		qprocson(q);
7924 		return (0);
7925 	}
7926 
7927 	issocket = flag & SO_SOCKSTR;
7928 	connp = tcp_create_common(credp, isv6, issocket, &err);
7929 
7930 	if (connp == NULL) {
7931 		inet_minor_free(minor_arena, conn_dev);
7932 		q->q_ptr = WR(q)->q_ptr = NULL;
7933 		return (err);
7934 	}
7935 
7936 	connp->conn_rq = q;
7937 	connp->conn_wq = WR(q);
7938 	q->q_ptr = WR(q)->q_ptr = connp;
7939 
7940 	connp->conn_dev = conn_dev;
7941 	connp->conn_minor_arena = minor_arena;
7942 
7943 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
7944 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
7945 
7946 	tcp = connp->conn_tcp;
7947 
7948 	if (issocket) {
7949 		WR(q)->q_qinfo = &tcp_sock_winit;
7950 	} else {
7951 #ifdef  _ILP32
7952 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
7953 #else
7954 		tcp->tcp_acceptor_id = conn_dev;
7955 #endif  /* _ILP32 */
7956 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
7957 	}
7958 
7959 	/*
7960 	 * Put the ref for TCP. Ref for IP was already put
7961 	 * by ipcl_conn_create. Also Make the conn_t globally
7962 	 * visible to walkers
7963 	 */
7964 	mutex_enter(&connp->conn_lock);
7965 	CONN_INC_REF_LOCKED(connp);
7966 	ASSERT(connp->conn_ref == 2);
7967 	connp->conn_state_flags &= ~CONN_INCIPIENT;
7968 	mutex_exit(&connp->conn_lock);
7969 
7970 	qprocson(q);
7971 	return (0);
7972 }
7973 
7974 /*
7975  * Some TCP options can be "set" by requesting them in the option
7976  * buffer. This is needed for XTI feature test though we do not
7977  * allow it in general. We interpret that this mechanism is more
7978  * applicable to OSI protocols and need not be allowed in general.
7979  * This routine filters out options for which it is not allowed (most)
7980  * and lets through those (few) for which it is. [ The XTI interface
7981  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
7982  * ever implemented will have to be allowed here ].
7983  */
7984 static boolean_t
7985 tcp_allow_connopt_set(int level, int name)
7986 {
7987 
7988 	switch (level) {
7989 	case IPPROTO_TCP:
7990 		switch (name) {
7991 		case TCP_NODELAY:
7992 			return (B_TRUE);
7993 		default:
7994 			return (B_FALSE);
7995 		}
7996 		/*NOTREACHED*/
7997 	default:
7998 		return (B_FALSE);
7999 	}
8000 	/*NOTREACHED*/
8001 }
8002 
8003 /*
8004  * This routine gets default values of certain options whose default
8005  * values are maintained by protocol specific code
8006  */
8007 /* ARGSUSED */
8008 int
8009 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
8010 {
8011 	int32_t	*i1 = (int32_t *)ptr;
8012 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
8013 
8014 	switch (level) {
8015 	case IPPROTO_TCP:
8016 		switch (name) {
8017 		case TCP_NOTIFY_THRESHOLD:
8018 			*i1 = tcps->tcps_ip_notify_interval;
8019 			break;
8020 		case TCP_ABORT_THRESHOLD:
8021 			*i1 = tcps->tcps_ip_abort_interval;
8022 			break;
8023 		case TCP_CONN_NOTIFY_THRESHOLD:
8024 			*i1 = tcps->tcps_ip_notify_cinterval;
8025 			break;
8026 		case TCP_CONN_ABORT_THRESHOLD:
8027 			*i1 = tcps->tcps_ip_abort_cinterval;
8028 			break;
8029 		default:
8030 			return (-1);
8031 		}
8032 		break;
8033 	case IPPROTO_IP:
8034 		switch (name) {
8035 		case IP_TTL:
8036 			*i1 = tcps->tcps_ipv4_ttl;
8037 			break;
8038 		default:
8039 			return (-1);
8040 		}
8041 		break;
8042 	case IPPROTO_IPV6:
8043 		switch (name) {
8044 		case IPV6_UNICAST_HOPS:
8045 			*i1 = tcps->tcps_ipv6_hoplimit;
8046 			break;
8047 		default:
8048 			return (-1);
8049 		}
8050 		break;
8051 	default:
8052 		return (-1);
8053 	}
8054 	return (sizeof (int));
8055 }
8056 
8057 /*
8058  * TCP routine to get the values of options.
8059  */
8060 static int
8061 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
8062 {
8063 	int		*i1 = (int *)ptr;
8064 	tcp_t		*tcp = connp->conn_tcp;
8065 	conn_opt_arg_t	coas;
8066 	int		retval;
8067 
8068 	coas.coa_connp = connp;
8069 	coas.coa_ixa = connp->conn_ixa;
8070 	coas.coa_ipp = &connp->conn_xmit_ipp;
8071 	coas.coa_ancillary = B_FALSE;
8072 	coas.coa_changed = 0;
8073 
8074 	switch (level) {
8075 	case SOL_SOCKET:
8076 		switch (name) {
8077 		case SO_SND_COPYAVOID:
8078 			*i1 = tcp->tcp_snd_zcopy_on ?
8079 			    SO_SND_COPYAVOID : 0;
8080 			return (sizeof (int));
8081 		case SO_ACCEPTCONN:
8082 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
8083 			return (sizeof (int));
8084 		}
8085 		break;
8086 	case IPPROTO_TCP:
8087 		switch (name) {
8088 		case TCP_NODELAY:
8089 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
8090 			return (sizeof (int));
8091 		case TCP_MAXSEG:
8092 			*i1 = tcp->tcp_mss;
8093 			return (sizeof (int));
8094 		case TCP_NOTIFY_THRESHOLD:
8095 			*i1 = (int)tcp->tcp_first_timer_threshold;
8096 			return (sizeof (int));
8097 		case TCP_ABORT_THRESHOLD:
8098 			*i1 = tcp->tcp_second_timer_threshold;
8099 			return (sizeof (int));
8100 		case TCP_CONN_NOTIFY_THRESHOLD:
8101 			*i1 = tcp->tcp_first_ctimer_threshold;
8102 			return (sizeof (int));
8103 		case TCP_CONN_ABORT_THRESHOLD:
8104 			*i1 = tcp->tcp_second_ctimer_threshold;
8105 			return (sizeof (int));
8106 		case TCP_INIT_CWND:
8107 			*i1 = tcp->tcp_init_cwnd;
8108 			return (sizeof (int));
8109 		case TCP_KEEPALIVE_THRESHOLD:
8110 			*i1 = tcp->tcp_ka_interval;
8111 			return (sizeof (int));
8112 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8113 			*i1 = tcp->tcp_ka_abort_thres;
8114 			return (sizeof (int));
8115 		case TCP_CORK:
8116 			*i1 = tcp->tcp_cork;
8117 			return (sizeof (int));
8118 		}
8119 		break;
8120 	case IPPROTO_IP:
8121 		if (connp->conn_family != AF_INET)
8122 			return (-1);
8123 		switch (name) {
8124 		case IP_OPTIONS:
8125 		case T_IP_OPTIONS:
8126 			/* Caller ensures enough space */
8127 			return (ip_opt_get_user(connp, ptr));
8128 		default:
8129 			break;
8130 		}
8131 		break;
8132 
8133 	case IPPROTO_IPV6:
8134 		/*
8135 		 * IPPROTO_IPV6 options are only supported for sockets
8136 		 * that are using IPv6 on the wire.
8137 		 */
8138 		if (connp->conn_ipversion != IPV6_VERSION) {
8139 			return (-1);
8140 		}
8141 		switch (name) {
8142 		case IPV6_PATHMTU:
8143 			if (tcp->tcp_state < TCPS_ESTABLISHED)
8144 				return (-1);
8145 			break;
8146 		}
8147 		break;
8148 	}
8149 	mutex_enter(&connp->conn_lock);
8150 	retval = conn_opt_get(&coas, level, name, ptr);
8151 	mutex_exit(&connp->conn_lock);
8152 	return (retval);
8153 }
8154 
8155 /*
8156  * TCP routine to get the values of options.
8157  */
8158 int
8159 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
8160 {
8161 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
8162 }
8163 
8164 /* returns UNIX error, the optlen is a value-result arg */
8165 int
8166 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8167     void *optvalp, socklen_t *optlen, cred_t *cr)
8168 {
8169 	conn_t		*connp = (conn_t *)proto_handle;
8170 	squeue_t	*sqp = connp->conn_sqp;
8171 	int		error;
8172 	t_uscalar_t	max_optbuf_len;
8173 	void		*optvalp_buf;
8174 	int		len;
8175 
8176 	ASSERT(connp->conn_upper_handle != NULL);
8177 
8178 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
8179 	    tcp_opt_obj.odb_opt_des_arr,
8180 	    tcp_opt_obj.odb_opt_arr_cnt,
8181 	    B_FALSE, B_TRUE, cr);
8182 	if (error != 0) {
8183 		if (error < 0) {
8184 			error = proto_tlitosyserr(-error);
8185 		}
8186 		return (error);
8187 	}
8188 
8189 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
8190 
8191 	error = squeue_synch_enter(sqp, connp, NULL);
8192 	if (error == ENOMEM) {
8193 		kmem_free(optvalp_buf, max_optbuf_len);
8194 		return (ENOMEM);
8195 	}
8196 
8197 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
8198 	squeue_synch_exit(sqp, connp);
8199 
8200 	if (len == -1) {
8201 		kmem_free(optvalp_buf, max_optbuf_len);
8202 		return (EINVAL);
8203 	}
8204 
8205 	/*
8206 	 * update optlen and copy option value
8207 	 */
8208 	t_uscalar_t size = MIN(len, *optlen);
8209 
8210 	bcopy(optvalp_buf, optvalp, size);
8211 	bcopy(&size, optlen, sizeof (size));
8212 
8213 	kmem_free(optvalp_buf, max_optbuf_len);
8214 	return (0);
8215 }
8216 
8217 /*
8218  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
8219  * Parameters are assumed to be verified by the caller.
8220  */
8221 /* ARGSUSED */
8222 int
8223 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
8224     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8225     void *thisdg_attrs, cred_t *cr)
8226 {
8227 	tcp_t	*tcp = connp->conn_tcp;
8228 	int	*i1 = (int *)invalp;
8229 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
8230 	boolean_t checkonly;
8231 	int	reterr;
8232 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8233 	conn_opt_arg_t	coas;
8234 
8235 	coas.coa_connp = connp;
8236 	coas.coa_ixa = connp->conn_ixa;
8237 	coas.coa_ipp = &connp->conn_xmit_ipp;
8238 	coas.coa_ancillary = B_FALSE;
8239 	coas.coa_changed = 0;
8240 
8241 	switch (optset_context) {
8242 	case SETFN_OPTCOM_CHECKONLY:
8243 		checkonly = B_TRUE;
8244 		/*
8245 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
8246 		 * inlen != 0 implies value supplied and
8247 		 * 	we have to "pretend" to set it.
8248 		 * inlen == 0 implies that there is no
8249 		 * 	value part in T_CHECK request and just validation
8250 		 * done elsewhere should be enough, we just return here.
8251 		 */
8252 		if (inlen == 0) {
8253 			*outlenp = 0;
8254 			return (0);
8255 		}
8256 		break;
8257 	case SETFN_OPTCOM_NEGOTIATE:
8258 		checkonly = B_FALSE;
8259 		break;
8260 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
8261 	case SETFN_CONN_NEGOTIATE:
8262 		checkonly = B_FALSE;
8263 		/*
8264 		 * Negotiating local and "association-related" options
8265 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
8266 		 * primitives is allowed by XTI, but we choose
8267 		 * to not implement this style negotiation for Internet
8268 		 * protocols (We interpret it is a must for OSI world but
8269 		 * optional for Internet protocols) for all options.
8270 		 * [ Will do only for the few options that enable test
8271 		 * suites that our XTI implementation of this feature
8272 		 * works for transports that do allow it ]
8273 		 */
8274 		if (!tcp_allow_connopt_set(level, name)) {
8275 			*outlenp = 0;
8276 			return (EINVAL);
8277 		}
8278 		break;
8279 	default:
8280 		/*
8281 		 * We should never get here
8282 		 */
8283 		*outlenp = 0;
8284 		return (EINVAL);
8285 	}
8286 
8287 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
8288 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
8289 
8290 	/*
8291 	 * For TCP, we should have no ancillary data sent down
8292 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
8293 	 * has to be zero.
8294 	 */
8295 	ASSERT(thisdg_attrs == NULL);
8296 
8297 	/*
8298 	 * For fixed length options, no sanity check
8299 	 * of passed in length is done. It is assumed *_optcom_req()
8300 	 * routines do the right thing.
8301 	 */
8302 	switch (level) {
8303 	case SOL_SOCKET:
8304 		switch (name) {
8305 		case SO_KEEPALIVE:
8306 			if (checkonly) {
8307 				/* check only case */
8308 				break;
8309 			}
8310 
8311 			if (!onoff) {
8312 				if (connp->conn_keepalive) {
8313 					if (tcp->tcp_ka_tid != 0) {
8314 						(void) TCP_TIMER_CANCEL(tcp,
8315 						    tcp->tcp_ka_tid);
8316 						tcp->tcp_ka_tid = 0;
8317 					}
8318 					connp->conn_keepalive = 0;
8319 				}
8320 				break;
8321 			}
8322 			if (!connp->conn_keepalive) {
8323 				/* Crank up the keepalive timer */
8324 				tcp->tcp_ka_last_intrvl = 0;
8325 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8326 				    tcp_keepalive_killer,
8327 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
8328 				connp->conn_keepalive = 1;
8329 			}
8330 			break;
8331 		case SO_SNDBUF: {
8332 			if (*i1 > tcps->tcps_max_buf) {
8333 				*outlenp = 0;
8334 				return (ENOBUFS);
8335 			}
8336 			if (checkonly)
8337 				break;
8338 
8339 			connp->conn_sndbuf = *i1;
8340 			if (tcps->tcps_snd_lowat_fraction != 0) {
8341 				connp->conn_sndlowat = connp->conn_sndbuf /
8342 				    tcps->tcps_snd_lowat_fraction;
8343 			}
8344 			(void) tcp_maxpsz_set(tcp, B_TRUE);
8345 			/*
8346 			 * If we are flow-controlled, recheck the condition.
8347 			 * There are apps that increase SO_SNDBUF size when
8348 			 * flow-controlled (EWOULDBLOCK), and expect the flow
8349 			 * control condition to be lifted right away.
8350 			 */
8351 			mutex_enter(&tcp->tcp_non_sq_lock);
8352 			if (tcp->tcp_flow_stopped &&
8353 			    TCP_UNSENT_BYTES(tcp) < connp->conn_sndbuf) {
8354 				tcp_clrqfull(tcp);
8355 			}
8356 			mutex_exit(&tcp->tcp_non_sq_lock);
8357 			*outlenp = inlen;
8358 			return (0);
8359 		}
8360 		case SO_RCVBUF:
8361 			if (*i1 > tcps->tcps_max_buf) {
8362 				*outlenp = 0;
8363 				return (ENOBUFS);
8364 			}
8365 			/* Silently ignore zero */
8366 			if (!checkonly && *i1 != 0) {
8367 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
8368 				(void) tcp_rwnd_set(tcp, *i1);
8369 			}
8370 			/*
8371 			 * XXX should we return the rwnd here
8372 			 * and tcp_opt_get ?
8373 			 */
8374 			*outlenp = inlen;
8375 			return (0);
8376 		case SO_SND_COPYAVOID:
8377 			if (!checkonly) {
8378 				if (tcp->tcp_loopback ||
8379 				    (tcp->tcp_kssl_ctx != NULL) ||
8380 				    (onoff != 1) || !tcp_zcopy_check(tcp)) {
8381 					*outlenp = 0;
8382 					return (EOPNOTSUPP);
8383 				}
8384 				tcp->tcp_snd_zcopy_aware = 1;
8385 			}
8386 			*outlenp = inlen;
8387 			return (0);
8388 		}
8389 		break;
8390 	case IPPROTO_TCP:
8391 		switch (name) {
8392 		case TCP_NODELAY:
8393 			if (!checkonly)
8394 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
8395 			break;
8396 		case TCP_NOTIFY_THRESHOLD:
8397 			if (!checkonly)
8398 				tcp->tcp_first_timer_threshold = *i1;
8399 			break;
8400 		case TCP_ABORT_THRESHOLD:
8401 			if (!checkonly)
8402 				tcp->tcp_second_timer_threshold = *i1;
8403 			break;
8404 		case TCP_CONN_NOTIFY_THRESHOLD:
8405 			if (!checkonly)
8406 				tcp->tcp_first_ctimer_threshold = *i1;
8407 			break;
8408 		case TCP_CONN_ABORT_THRESHOLD:
8409 			if (!checkonly)
8410 				tcp->tcp_second_ctimer_threshold = *i1;
8411 			break;
8412 		case TCP_RECVDSTADDR:
8413 			if (tcp->tcp_state > TCPS_LISTEN) {
8414 				*outlenp = 0;
8415 				return (EOPNOTSUPP);
8416 			}
8417 			/* Setting done in conn_opt_set */
8418 			break;
8419 		case TCP_INIT_CWND: {
8420 			uint32_t init_cwnd = *((uint32_t *)invalp);
8421 
8422 			if (checkonly)
8423 				break;
8424 
8425 			/*
8426 			 * Only allow socket with network configuration
8427 			 * privilege to set the initial cwnd to be larger
8428 			 * than allowed by RFC 3390.
8429 			 */
8430 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
8431 				tcp->tcp_init_cwnd = init_cwnd;
8432 				break;
8433 			}
8434 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
8435 				*outlenp = 0;
8436 				return (reterr);
8437 			}
8438 			if (init_cwnd > TCP_MAX_INIT_CWND) {
8439 				*outlenp = 0;
8440 				return (EINVAL);
8441 			}
8442 			tcp->tcp_init_cwnd = init_cwnd;
8443 			break;
8444 		}
8445 		case TCP_KEEPALIVE_THRESHOLD:
8446 			if (checkonly)
8447 				break;
8448 
8449 			if (*i1 < tcps->tcps_keepalive_interval_low ||
8450 			    *i1 > tcps->tcps_keepalive_interval_high) {
8451 				*outlenp = 0;
8452 				return (EINVAL);
8453 			}
8454 			if (*i1 != tcp->tcp_ka_interval) {
8455 				tcp->tcp_ka_interval = *i1;
8456 				/*
8457 				 * Check if we need to restart the
8458 				 * keepalive timer.
8459 				 */
8460 				if (tcp->tcp_ka_tid != 0) {
8461 					ASSERT(connp->conn_keepalive);
8462 					(void) TCP_TIMER_CANCEL(tcp,
8463 					    tcp->tcp_ka_tid);
8464 					tcp->tcp_ka_last_intrvl = 0;
8465 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
8466 					    tcp_keepalive_killer,
8467 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
8468 				}
8469 			}
8470 			break;
8471 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
8472 			if (!checkonly) {
8473 				if (*i1 <
8474 				    tcps->tcps_keepalive_abort_interval_low ||
8475 				    *i1 >
8476 				    tcps->tcps_keepalive_abort_interval_high) {
8477 					*outlenp = 0;
8478 					return (EINVAL);
8479 				}
8480 				tcp->tcp_ka_abort_thres = *i1;
8481 			}
8482 			break;
8483 		case TCP_CORK:
8484 			if (!checkonly) {
8485 				/*
8486 				 * if tcp->tcp_cork was set and is now
8487 				 * being unset, we have to make sure that
8488 				 * the remaining data gets sent out. Also
8489 				 * unset tcp->tcp_cork so that tcp_wput_data()
8490 				 * can send data even if it is less than mss
8491 				 */
8492 				if (tcp->tcp_cork && onoff == 0 &&
8493 				    tcp->tcp_unsent > 0) {
8494 					tcp->tcp_cork = B_FALSE;
8495 					tcp_wput_data(tcp, NULL, B_FALSE);
8496 				}
8497 				tcp->tcp_cork = onoff;
8498 			}
8499 			break;
8500 		default:
8501 			break;
8502 		}
8503 		break;
8504 	case IPPROTO_IP:
8505 		if (connp->conn_family != AF_INET) {
8506 			*outlenp = 0;
8507 			return (EINVAL);
8508 		}
8509 		switch (name) {
8510 		case IP_SEC_OPT:
8511 			/*
8512 			 * We should not allow policy setting after
8513 			 * we start listening for connections.
8514 			 */
8515 			if (tcp->tcp_state == TCPS_LISTEN) {
8516 				return (EINVAL);
8517 			}
8518 			break;
8519 		}
8520 		break;
8521 	case IPPROTO_IPV6:
8522 		/*
8523 		 * IPPROTO_IPV6 options are only supported for sockets
8524 		 * that are using IPv6 on the wire.
8525 		 */
8526 		if (connp->conn_ipversion != IPV6_VERSION) {
8527 			*outlenp = 0;
8528 			return (EINVAL);
8529 		}
8530 
8531 		switch (name) {
8532 		case IPV6_RECVPKTINFO:
8533 			if (!checkonly) {
8534 				/* Force it to be sent up with the next msg */
8535 				tcp->tcp_recvifindex = 0;
8536 			}
8537 			break;
8538 		case IPV6_RECVTCLASS:
8539 			if (!checkonly) {
8540 				/* Force it to be sent up with the next msg */
8541 				tcp->tcp_recvtclass = 0xffffffffU;
8542 			}
8543 			break;
8544 		case IPV6_RECVHOPLIMIT:
8545 			if (!checkonly) {
8546 				/* Force it to be sent up with the next msg */
8547 				tcp->tcp_recvhops = 0xffffffffU;
8548 			}
8549 			break;
8550 		case IPV6_PKTINFO:
8551 			/* This is an extra check for TCP */
8552 			if (inlen == sizeof (struct in6_pktinfo)) {
8553 				struct in6_pktinfo *pkti;
8554 
8555 				pkti = (struct in6_pktinfo *)invalp;
8556 				/*
8557 				 * RFC 3542 states that ipi6_addr must be
8558 				 * the unspecified address when setting the
8559 				 * IPV6_PKTINFO sticky socket option on a
8560 				 * TCP socket.
8561 				 */
8562 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
8563 					return (EINVAL);
8564 			}
8565 			break;
8566 		case IPV6_SEC_OPT:
8567 			/*
8568 			 * We should not allow policy setting after
8569 			 * we start listening for connections.
8570 			 */
8571 			if (tcp->tcp_state == TCPS_LISTEN) {
8572 				return (EINVAL);
8573 			}
8574 			break;
8575 		}
8576 		break;
8577 	}
8578 	reterr = conn_opt_set(&coas, level, name, inlen, invalp,
8579 	    checkonly, cr);
8580 	if (reterr != 0) {
8581 		*outlenp = 0;
8582 		return (reterr);
8583 	}
8584 
8585 	/*
8586 	 * Common case of OK return with outval same as inval
8587 	 */
8588 	if (invalp != outvalp) {
8589 		/* don't trust bcopy for identical src/dst */
8590 		(void) bcopy(invalp, outvalp, inlen);
8591 	}
8592 	*outlenp = inlen;
8593 
8594 	if (coas.coa_changed & COA_HEADER_CHANGED) {
8595 		reterr = tcp_build_hdrs(tcp);
8596 		if (reterr != 0)
8597 			return (reterr);
8598 	}
8599 	if (coas.coa_changed & COA_ROUTE_CHANGED) {
8600 		in6_addr_t nexthop;
8601 
8602 		/*
8603 		 * If we are connected we re-cache the information.
8604 		 * We ignore errors to preserve BSD behavior.
8605 		 * Note that we don't redo IPsec policy lookup here
8606 		 * since the final destination (or source) didn't change.
8607 		 */
8608 		ip_attr_nexthop(&connp->conn_xmit_ipp, connp->conn_ixa,
8609 		    &connp->conn_faddr_v6, &nexthop);
8610 
8611 		if (!IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6) &&
8612 		    !IN6_IS_ADDR_V4MAPPED_ANY(&connp->conn_faddr_v6)) {
8613 			(void) ip_attr_connect(connp, connp->conn_ixa,
8614 			    &connp->conn_laddr_v6, &connp->conn_faddr_v6,
8615 			    &nexthop, connp->conn_fport, NULL, NULL,
8616 			    IPDF_VERIFY_DST);
8617 		}
8618 	}
8619 	if ((coas.coa_changed & COA_SNDBUF_CHANGED) && !IPCL_IS_NONSTR(connp)) {
8620 		connp->conn_wq->q_hiwat = connp->conn_sndbuf;
8621 	}
8622 	if (coas.coa_changed & COA_WROFF_CHANGED) {
8623 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8624 		    tcps->tcps_wroff_xtra;
8625 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8626 		    connp->conn_wroff);
8627 	}
8628 	if (coas.coa_changed & COA_OOBINLINE_CHANGED) {
8629 		if (IPCL_IS_NONSTR(connp))
8630 			proto_set_rx_oob_opt(connp, onoff);
8631 	}
8632 	return (0);
8633 }
8634 
8635 /* ARGSUSED */
8636 int
8637 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
8638     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
8639     void *thisdg_attrs, cred_t *cr)
8640 {
8641 	conn_t	*connp =  Q_TO_CONN(q);
8642 
8643 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
8644 	    outlenp, outvalp, thisdg_attrs, cr));
8645 }
8646 
8647 int
8648 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
8649     const void *optvalp, socklen_t optlen, cred_t *cr)
8650 {
8651 	conn_t		*connp = (conn_t *)proto_handle;
8652 	squeue_t	*sqp = connp->conn_sqp;
8653 	int		error;
8654 
8655 	ASSERT(connp->conn_upper_handle != NULL);
8656 	/*
8657 	 * Entering the squeue synchronously can result in a context switch,
8658 	 * which can cause a rather sever performance degradation. So we try to
8659 	 * handle whatever options we can without entering the squeue.
8660 	 */
8661 	if (level == IPPROTO_TCP) {
8662 		switch (option_name) {
8663 		case TCP_NODELAY:
8664 			if (optlen != sizeof (int32_t))
8665 				return (EINVAL);
8666 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
8667 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
8668 			    connp->conn_tcp->tcp_mss;
8669 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
8670 			return (0);
8671 		default:
8672 			break;
8673 		}
8674 	}
8675 
8676 	error = squeue_synch_enter(sqp, connp, NULL);
8677 	if (error == ENOMEM) {
8678 		return (ENOMEM);
8679 	}
8680 
8681 	error = proto_opt_check(level, option_name, optlen, NULL,
8682 	    tcp_opt_obj.odb_opt_des_arr,
8683 	    tcp_opt_obj.odb_opt_arr_cnt,
8684 	    B_TRUE, B_FALSE, cr);
8685 
8686 	if (error != 0) {
8687 		if (error < 0) {
8688 			error = proto_tlitosyserr(-error);
8689 		}
8690 		squeue_synch_exit(sqp, connp);
8691 		return (error);
8692 	}
8693 
8694 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
8695 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
8696 	    NULL, cr);
8697 	squeue_synch_exit(sqp, connp);
8698 
8699 	ASSERT(error >= 0);
8700 
8701 	return (error);
8702 }
8703 
8704 /*
8705  * Build/update the tcp header template (in conn_ht_iphc) based on
8706  * conn_xmit_ipp. The headers include ip6_t, any extension
8707  * headers, and the maximum size tcp header (to avoid reallocation
8708  * on the fly for additional tcp options).
8709  *
8710  * Assumes the caller has already set conn_{faddr,laddr,fport,lport,flowinfo}.
8711  * Returns failure if can't allocate memory.
8712  */
8713 static int
8714 tcp_build_hdrs(tcp_t *tcp)
8715 {
8716 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8717 	conn_t		*connp = tcp->tcp_connp;
8718 	char		buf[TCP_MAX_HDR_LENGTH];
8719 	uint_t		buflen;
8720 	uint_t		ulplen = TCP_MIN_HEADER_LENGTH;
8721 	uint_t		extralen = TCP_MAX_TCP_OPTIONS_LENGTH;
8722 	tcpha_t		*tcpha;
8723 	uint32_t	cksum;
8724 	int		error;
8725 
8726 	/*
8727 	 * We might be called after the connection is set up, and we might
8728 	 * have TS options already in the TCP header. Thus we  save any
8729 	 * existing tcp header.
8730 	 */
8731 	buflen = connp->conn_ht_ulp_len;
8732 	if (buflen != 0) {
8733 		bcopy(connp->conn_ht_ulp, buf, buflen);
8734 		extralen -= buflen - ulplen;
8735 		ulplen = buflen;
8736 	}
8737 
8738 	/* Grab lock to satisfy ASSERT; TCP is serialized using squeue */
8739 	mutex_enter(&connp->conn_lock);
8740 	error = conn_build_hdr_template(connp, ulplen, extralen,
8741 	    &connp->conn_laddr_v6, &connp->conn_faddr_v6, connp->conn_flowinfo);
8742 	mutex_exit(&connp->conn_lock);
8743 	if (error != 0)
8744 		return (error);
8745 
8746 	/*
8747 	 * Any routing header/option has been massaged. The checksum difference
8748 	 * is stored in conn_sum for later use.
8749 	 */
8750 	tcpha = (tcpha_t *)connp->conn_ht_ulp;
8751 	tcp->tcp_tcpha = tcpha;
8752 
8753 	/* restore any old tcp header */
8754 	if (buflen != 0) {
8755 		bcopy(buf, connp->conn_ht_ulp, buflen);
8756 	} else {
8757 		tcpha->tha_sum = 0;
8758 		tcpha->tha_offset_and_reserved = (5 << 4);
8759 	}
8760 	tcpha->tha_lport = connp->conn_lport;
8761 	tcpha->tha_fport = connp->conn_fport;
8762 
8763 	/*
8764 	 * IP wants our header length in the checksum field to
8765 	 * allow it to perform a single pseudo-header+checksum
8766 	 * calculation on behalf of TCP.
8767 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8768 	 */
8769 	cksum = sizeof (tcpha_t) + connp->conn_sum;
8770 	cksum = (cksum >> 16) + (cksum & 0xFFFF);
8771 	ASSERT(cksum < 0x10000);
8772 	tcpha->tha_sum = htons(cksum);
8773 
8774 	if (connp->conn_ipversion == IPV4_VERSION)
8775 		tcp->tcp_ipha = (ipha_t *)connp->conn_ht_iphc;
8776 	else
8777 		tcp->tcp_ip6h = (ip6_t *)connp->conn_ht_iphc;
8778 
8779 	if (connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra >
8780 	    connp->conn_wroff) {
8781 		connp->conn_wroff = connp->conn_ht_iphc_allocated +
8782 		    tcps->tcps_wroff_xtra;
8783 		(void) proto_set_tx_wroff(connp->conn_rq, connp,
8784 		    connp->conn_wroff);
8785 	}
8786 	return (0);
8787 }
8788 
8789 /* Get callback routine passed to nd_load by tcp_param_register */
8790 /* ARGSUSED */
8791 static int
8792 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
8793 {
8794 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8795 
8796 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
8797 	return (0);
8798 }
8799 
8800 /*
8801  * Walk through the param array specified registering each element with the
8802  * named dispatch handler.
8803  */
8804 static boolean_t
8805 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
8806 {
8807 	for (; cnt-- > 0; tcppa++) {
8808 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
8809 			if (!nd_load(ndp, tcppa->tcp_param_name,
8810 			    tcp_param_get, tcp_param_set,
8811 			    (caddr_t)tcppa)) {
8812 				nd_free(ndp);
8813 				return (B_FALSE);
8814 			}
8815 		}
8816 	}
8817 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
8818 	    KM_SLEEP);
8819 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
8820 	    sizeof (tcpparam_t));
8821 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
8822 	    tcp_param_get, tcp_param_set_aligned,
8823 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
8824 		nd_free(ndp);
8825 		return (B_FALSE);
8826 	}
8827 	if (!nd_load(ndp, "tcp_extra_priv_ports",
8828 	    tcp_extra_priv_ports_get, NULL, NULL)) {
8829 		nd_free(ndp);
8830 		return (B_FALSE);
8831 	}
8832 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
8833 	    NULL, tcp_extra_priv_ports_add, NULL)) {
8834 		nd_free(ndp);
8835 		return (B_FALSE);
8836 	}
8837 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
8838 	    NULL, tcp_extra_priv_ports_del, NULL)) {
8839 		nd_free(ndp);
8840 		return (B_FALSE);
8841 	}
8842 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
8843 	    tcp_1948_phrase_set, NULL)) {
8844 		nd_free(ndp);
8845 		return (B_FALSE);
8846 	}
8847 
8848 
8849 	if (!nd_load(ndp, "tcp_listener_limit_conf",
8850 	    tcp_listener_conf_get, NULL, NULL)) {
8851 		nd_free(ndp);
8852 		return (B_FALSE);
8853 	}
8854 	if (!nd_load(ndp, "tcp_listener_limit_conf_add",
8855 	    NULL, tcp_listener_conf_add, NULL)) {
8856 		nd_free(ndp);
8857 		return (B_FALSE);
8858 	}
8859 	if (!nd_load(ndp, "tcp_listener_limit_conf_del",
8860 	    NULL, tcp_listener_conf_del, NULL)) {
8861 		nd_free(ndp);
8862 		return (B_FALSE);
8863 	}
8864 
8865 	/*
8866 	 * Dummy ndd variables - only to convey obsolescence information
8867 	 * through printing of their name (no get or set routines)
8868 	 * XXX Remove in future releases ?
8869 	 */
8870 	if (!nd_load(ndp,
8871 	    "tcp_close_wait_interval(obsoleted - "
8872 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
8873 		nd_free(ndp);
8874 		return (B_FALSE);
8875 	}
8876 	return (B_TRUE);
8877 }
8878 
8879 /* ndd set routine for tcp_wroff_xtra. */
8880 /* ARGSUSED */
8881 static int
8882 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
8883     cred_t *cr)
8884 {
8885 	long new_value;
8886 	tcpparam_t *tcppa = (tcpparam_t *)cp;
8887 
8888 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8889 	    new_value < tcppa->tcp_param_min ||
8890 	    new_value > tcppa->tcp_param_max) {
8891 		return (EINVAL);
8892 	}
8893 	/*
8894 	 * Need to make sure new_value is a multiple of 4.  If it is not,
8895 	 * round it up.  For future 64 bit requirement, we actually make it
8896 	 * a multiple of 8.
8897 	 */
8898 	if (new_value & 0x7) {
8899 		new_value = (new_value & ~0x7) + 0x8;
8900 	}
8901 	tcppa->tcp_param_val = new_value;
8902 	return (0);
8903 }
8904 
8905 /* Set callback routine passed to nd_load by tcp_param_register */
8906 /* ARGSUSED */
8907 static int
8908 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
8909 {
8910 	long	new_value;
8911 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
8912 
8913 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
8914 	    new_value < tcppa->tcp_param_min ||
8915 	    new_value > tcppa->tcp_param_max) {
8916 		return (EINVAL);
8917 	}
8918 	tcppa->tcp_param_val = new_value;
8919 	return (0);
8920 }
8921 
8922 static void
8923 tcp_reass_timer(void *arg)
8924 {
8925 	conn_t *connp = (conn_t *)arg;
8926 	tcp_t *tcp = connp->conn_tcp;
8927 
8928 	tcp->tcp_reass_tid = 0;
8929 	if (tcp->tcp_reass_head == NULL)
8930 		return;
8931 	ASSERT(tcp->tcp_reass_tail != NULL);
8932 	tcp_sack_remove(tcp->tcp_sack_list, TCP_REASS_END(tcp->tcp_reass_tail),
8933 	    &tcp->tcp_num_sack_blk);
8934 	tcp_close_mpp(&tcp->tcp_reass_head);
8935 	tcp->tcp_reass_tail = NULL;
8936 }
8937 
8938 /*
8939  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
8940  * is filled, return as much as we can.  The message passed in may be
8941  * multi-part, chained using b_cont.  "start" is the starting sequence
8942  * number for this piece.
8943  */
8944 static mblk_t *
8945 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
8946 {
8947 	uint32_t	end;
8948 	mblk_t		*mp1;
8949 	mblk_t		*mp2;
8950 	mblk_t		*next_mp;
8951 	uint32_t	u1;
8952 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8953 
8954 
8955 	/* Walk through all the new pieces. */
8956 	do {
8957 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
8958 		    (uintptr_t)INT_MAX);
8959 		end = start + (int)(mp->b_wptr - mp->b_rptr);
8960 		next_mp = mp->b_cont;
8961 		if (start == end) {
8962 			/* Empty.  Blast it. */
8963 			freeb(mp);
8964 			continue;
8965 		}
8966 		mp->b_cont = NULL;
8967 		TCP_REASS_SET_SEQ(mp, start);
8968 		TCP_REASS_SET_END(mp, end);
8969 		mp1 = tcp->tcp_reass_tail;
8970 		if (!mp1) {
8971 			tcp->tcp_reass_tail = mp;
8972 			tcp->tcp_reass_head = mp;
8973 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
8974 			UPDATE_MIB(&tcps->tcps_mib,
8975 			    tcpInDataUnorderBytes, end - start);
8976 			continue;
8977 		}
8978 		/* New stuff completely beyond tail? */
8979 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
8980 			/* Link it on end. */
8981 			mp1->b_cont = mp;
8982 			tcp->tcp_reass_tail = mp;
8983 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
8984 			UPDATE_MIB(&tcps->tcps_mib,
8985 			    tcpInDataUnorderBytes, end - start);
8986 			continue;
8987 		}
8988 		mp1 = tcp->tcp_reass_head;
8989 		u1 = TCP_REASS_SEQ(mp1);
8990 		/* New stuff at the front? */
8991 		if (SEQ_LT(start, u1)) {
8992 			/* Yes... Check for overlap. */
8993 			mp->b_cont = mp1;
8994 			tcp->tcp_reass_head = mp;
8995 			tcp_reass_elim_overlap(tcp, mp);
8996 			continue;
8997 		}
8998 		/*
8999 		 * The new piece fits somewhere between the head and tail.
9000 		 * We find our slot, where mp1 precedes us and mp2 trails.
9001 		 */
9002 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
9003 			u1 = TCP_REASS_SEQ(mp2);
9004 			if (SEQ_LEQ(start, u1))
9005 				break;
9006 		}
9007 		/* Link ourselves in */
9008 		mp->b_cont = mp2;
9009 		mp1->b_cont = mp;
9010 
9011 		/* Trim overlap with following mblk(s) first */
9012 		tcp_reass_elim_overlap(tcp, mp);
9013 
9014 		/* Trim overlap with preceding mblk */
9015 		tcp_reass_elim_overlap(tcp, mp1);
9016 
9017 	} while (start = end, mp = next_mp);
9018 	mp1 = tcp->tcp_reass_head;
9019 	/* Anything ready to go? */
9020 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
9021 		return (NULL);
9022 	/* Eat what we can off the queue */
9023 	for (;;) {
9024 		mp = mp1->b_cont;
9025 		end = TCP_REASS_END(mp1);
9026 		TCP_REASS_SET_SEQ(mp1, 0);
9027 		TCP_REASS_SET_END(mp1, 0);
9028 		if (!mp) {
9029 			tcp->tcp_reass_tail = NULL;
9030 			break;
9031 		}
9032 		if (end != TCP_REASS_SEQ(mp)) {
9033 			mp1->b_cont = NULL;
9034 			break;
9035 		}
9036 		mp1 = mp;
9037 	}
9038 	mp1 = tcp->tcp_reass_head;
9039 	tcp->tcp_reass_head = mp;
9040 	return (mp1);
9041 }
9042 
9043 /* Eliminate any overlap that mp may have over later mblks */
9044 static void
9045 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
9046 {
9047 	uint32_t	end;
9048 	mblk_t		*mp1;
9049 	uint32_t	u1;
9050 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9051 
9052 	end = TCP_REASS_END(mp);
9053 	while ((mp1 = mp->b_cont) != NULL) {
9054 		u1 = TCP_REASS_SEQ(mp1);
9055 		if (!SEQ_GT(end, u1))
9056 			break;
9057 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
9058 			mp->b_wptr -= end - u1;
9059 			TCP_REASS_SET_END(mp, u1);
9060 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
9061 			UPDATE_MIB(&tcps->tcps_mib,
9062 			    tcpInDataPartDupBytes, end - u1);
9063 			break;
9064 		}
9065 		mp->b_cont = mp1->b_cont;
9066 		TCP_REASS_SET_SEQ(mp1, 0);
9067 		TCP_REASS_SET_END(mp1, 0);
9068 		freeb(mp1);
9069 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
9070 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
9071 	}
9072 	if (!mp1)
9073 		tcp->tcp_reass_tail = mp;
9074 }
9075 
9076 static uint_t
9077 tcp_rwnd_reopen(tcp_t *tcp)
9078 {
9079 	uint_t ret = 0;
9080 	uint_t thwin;
9081 	conn_t *connp = tcp->tcp_connp;
9082 
9083 	/* Learn the latest rwnd information that we sent to the other side. */
9084 	thwin = ((uint_t)ntohs(tcp->tcp_tcpha->tha_win))
9085 	    << tcp->tcp_rcv_ws;
9086 	/* This is peer's calculated send window (our receive window). */
9087 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
9088 	/*
9089 	 * Increase the receive window to max.  But we need to do receiver
9090 	 * SWS avoidance.  This means that we need to check the increase of
9091 	 * of receive window is at least 1 MSS.
9092 	 */
9093 	if (connp->conn_rcvbuf - thwin >= tcp->tcp_mss) {
9094 		/*
9095 		 * If the window that the other side knows is less than max
9096 		 * deferred acks segments, send an update immediately.
9097 		 */
9098 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
9099 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
9100 			ret = TH_ACK_NEEDED;
9101 		}
9102 		tcp->tcp_rwnd = connp->conn_rcvbuf;
9103 	}
9104 	return (ret);
9105 }
9106 
9107 /*
9108  * Send up all messages queued on tcp_rcv_list.
9109  */
9110 static uint_t
9111 tcp_rcv_drain(tcp_t *tcp)
9112 {
9113 	mblk_t *mp;
9114 	uint_t ret = 0;
9115 #ifdef DEBUG
9116 	uint_t cnt = 0;
9117 #endif
9118 	queue_t	*q = tcp->tcp_connp->conn_rq;
9119 
9120 	/* Can't drain on an eager connection */
9121 	if (tcp->tcp_listener != NULL)
9122 		return (ret);
9123 
9124 	/* Can't be a non-STREAMS connection */
9125 	ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
9126 
9127 	/* No need for the push timer now. */
9128 	if (tcp->tcp_push_tid != 0) {
9129 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
9130 		tcp->tcp_push_tid = 0;
9131 	}
9132 
9133 	/*
9134 	 * Handle two cases here: we are currently fused or we were
9135 	 * previously fused and have some urgent data to be delivered
9136 	 * upstream.  The latter happens because we either ran out of
9137 	 * memory or were detached and therefore sending the SIGURG was
9138 	 * deferred until this point.  In either case we pass control
9139 	 * over to tcp_fuse_rcv_drain() since it may need to complete
9140 	 * some work.
9141 	 */
9142 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
9143 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
9144 		    tcp->tcp_fused_sigurg_mp != NULL);
9145 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
9146 		    &tcp->tcp_fused_sigurg_mp))
9147 			return (ret);
9148 	}
9149 
9150 	while ((mp = tcp->tcp_rcv_list) != NULL) {
9151 		tcp->tcp_rcv_list = mp->b_next;
9152 		mp->b_next = NULL;
9153 #ifdef DEBUG
9154 		cnt += msgdsize(mp);
9155 #endif
9156 		/* Does this need SSL processing first? */
9157 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
9158 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
9159 			    mblk_t *, mp);
9160 			tcp_kssl_input(tcp, mp, NULL);
9161 			continue;
9162 		}
9163 		putnext(q, mp);
9164 	}
9165 #ifdef DEBUG
9166 	ASSERT(cnt == tcp->tcp_rcv_cnt);
9167 #endif
9168 	tcp->tcp_rcv_last_head = NULL;
9169 	tcp->tcp_rcv_last_tail = NULL;
9170 	tcp->tcp_rcv_cnt = 0;
9171 
9172 	if (canputnext(q))
9173 		return (tcp_rwnd_reopen(tcp));
9174 
9175 	return (ret);
9176 }
9177 
9178 /*
9179  * Queue data on tcp_rcv_list which is a b_next chain.
9180  * tcp_rcv_last_head/tail is the last element of this chain.
9181  * Each element of the chain is a b_cont chain.
9182  *
9183  * M_DATA messages are added to the current element.
9184  * Other messages are added as new (b_next) elements.
9185  */
9186 void
9187 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len, cred_t *cr)
9188 {
9189 	ASSERT(seg_len == msgdsize(mp));
9190 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
9191 
9192 	if (is_system_labeled()) {
9193 		ASSERT(cr != NULL || msg_getcred(mp, NULL) != NULL);
9194 		/*
9195 		 * Provide for protocols above TCP such as RPC. NOPID leaves
9196 		 * db_cpid unchanged.
9197 		 * The cred could have already been set.
9198 		 */
9199 		if (cr != NULL)
9200 			mblk_setcred(mp, cr, NOPID);
9201 	}
9202 
9203 	if (tcp->tcp_rcv_list == NULL) {
9204 		ASSERT(tcp->tcp_rcv_last_head == NULL);
9205 		tcp->tcp_rcv_list = mp;
9206 		tcp->tcp_rcv_last_head = mp;
9207 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
9208 		tcp->tcp_rcv_last_tail->b_cont = mp;
9209 	} else {
9210 		tcp->tcp_rcv_last_head->b_next = mp;
9211 		tcp->tcp_rcv_last_head = mp;
9212 	}
9213 
9214 	while (mp->b_cont)
9215 		mp = mp->b_cont;
9216 
9217 	tcp->tcp_rcv_last_tail = mp;
9218 	tcp->tcp_rcv_cnt += seg_len;
9219 	tcp->tcp_rwnd -= seg_len;
9220 }
9221 
9222 /* The minimum of smoothed mean deviation in RTO calculation. */
9223 #define	TCP_SD_MIN	400
9224 
9225 /*
9226  * Set RTO for this connection.  The formula is from Jacobson and Karels'
9227  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
9228  * are the same as those in Appendix A.2 of that paper.
9229  *
9230  * m = new measurement
9231  * sa = smoothed RTT average (8 * average estimates).
9232  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
9233  */
9234 static void
9235 tcp_set_rto(tcp_t *tcp, clock_t rtt)
9236 {
9237 	long m = TICK_TO_MSEC(rtt);
9238 	clock_t sa = tcp->tcp_rtt_sa;
9239 	clock_t sv = tcp->tcp_rtt_sd;
9240 	clock_t rto;
9241 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9242 
9243 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
9244 	tcp->tcp_rtt_update++;
9245 
9246 	/* tcp_rtt_sa is not 0 means this is a new sample. */
9247 	if (sa != 0) {
9248 		/*
9249 		 * Update average estimator:
9250 		 *	new rtt = 7/8 old rtt + 1/8 Error
9251 		 */
9252 
9253 		/* m is now Error in estimate. */
9254 		m -= sa >> 3;
9255 		if ((sa += m) <= 0) {
9256 			/*
9257 			 * Don't allow the smoothed average to be negative.
9258 			 * We use 0 to denote reinitialization of the
9259 			 * variables.
9260 			 */
9261 			sa = 1;
9262 		}
9263 
9264 		/*
9265 		 * Update deviation estimator:
9266 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
9267 		 */
9268 		if (m < 0)
9269 			m = -m;
9270 		m -= sv >> 2;
9271 		sv += m;
9272 	} else {
9273 		/*
9274 		 * This follows BSD's implementation.  So the reinitialized
9275 		 * RTO is 3 * m.  We cannot go less than 2 because if the
9276 		 * link is bandwidth dominated, doubling the window size
9277 		 * during slow start means doubling the RTT.  We want to be
9278 		 * more conservative when we reinitialize our estimates.  3
9279 		 * is just a convenient number.
9280 		 */
9281 		sa = m << 3;
9282 		sv = m << 1;
9283 	}
9284 	if (sv < TCP_SD_MIN) {
9285 		/*
9286 		 * We do not know that if sa captures the delay ACK
9287 		 * effect as in a long train of segments, a receiver
9288 		 * does not delay its ACKs.  So set the minimum of sv
9289 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
9290 		 * of BSD DATO.  That means the minimum of mean
9291 		 * deviation is 100 ms.
9292 		 *
9293 		 */
9294 		sv = TCP_SD_MIN;
9295 	}
9296 	tcp->tcp_rtt_sa = sa;
9297 	tcp->tcp_rtt_sd = sv;
9298 	/*
9299 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
9300 	 *
9301 	 * Add tcp_rexmit_interval extra in case of extreme environment
9302 	 * where the algorithm fails to work.  The default value of
9303 	 * tcp_rexmit_interval_extra should be 0.
9304 	 *
9305 	 * As we use a finer grained clock than BSD and update
9306 	 * RTO for every ACKs, add in another .25 of RTT to the
9307 	 * deviation of RTO to accomodate burstiness of 1/4 of
9308 	 * window size.
9309 	 */
9310 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
9311 
9312 	if (rto > tcps->tcps_rexmit_interval_max) {
9313 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
9314 	} else if (rto < tcps->tcps_rexmit_interval_min) {
9315 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
9316 	} else {
9317 		tcp->tcp_rto = rto;
9318 	}
9319 
9320 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
9321 	tcp->tcp_timer_backoff = 0;
9322 }
9323 
9324 /*
9325  * tcp_get_seg_mp() is called to get the pointer to a segment in the
9326  * send queue which starts at the given sequence number. If the given
9327  * sequence number is equal to last valid sequence number (tcp_snxt), the
9328  * returned mblk is the last valid mblk, and off is set to the length of
9329  * that mblk.
9330  *
9331  * send queue which starts at the given seq. no.
9332  *
9333  * Parameters:
9334  *	tcp_t *tcp: the tcp instance pointer.
9335  *	uint32_t seq: the starting seq. no of the requested segment.
9336  *	int32_t *off: after the execution, *off will be the offset to
9337  *		the returned mblk which points to the requested seq no.
9338  *		It is the caller's responsibility to send in a non-null off.
9339  *
9340  * Return:
9341  *	A mblk_t pointer pointing to the requested segment in send queue.
9342  */
9343 static mblk_t *
9344 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
9345 {
9346 	int32_t	cnt;
9347 	mblk_t	*mp;
9348 
9349 	/* Defensive coding.  Make sure we don't send incorrect data. */
9350 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GT(seq, tcp->tcp_snxt))
9351 		return (NULL);
9352 
9353 	cnt = seq - tcp->tcp_suna;
9354 	mp = tcp->tcp_xmit_head;
9355 	while (cnt > 0 && mp != NULL) {
9356 		cnt -= mp->b_wptr - mp->b_rptr;
9357 		if (cnt <= 0) {
9358 			cnt += mp->b_wptr - mp->b_rptr;
9359 			break;
9360 		}
9361 		mp = mp->b_cont;
9362 	}
9363 	ASSERT(mp != NULL);
9364 	*off = cnt;
9365 	return (mp);
9366 }
9367 
9368 /*
9369  * This function handles all retransmissions if SACK is enabled for this
9370  * connection.  First it calculates how many segments can be retransmitted
9371  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
9372  * segments.  A segment is eligible if sack_cnt for that segment is greater
9373  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
9374  * all eligible segments, it checks to see if TCP can send some new segments
9375  * (fast recovery).  If it can, set the appropriate flag for tcp_input_data().
9376  *
9377  * Parameters:
9378  *	tcp_t *tcp: the tcp structure of the connection.
9379  *	uint_t *flags: in return, appropriate value will be set for
9380  *	tcp_input_data().
9381  */
9382 static void
9383 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
9384 {
9385 	notsack_blk_t	*notsack_blk;
9386 	int32_t		usable_swnd;
9387 	int32_t		mss;
9388 	uint32_t	seg_len;
9389 	mblk_t		*xmit_mp;
9390 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9391 
9392 	ASSERT(tcp->tcp_sack_info != NULL);
9393 	ASSERT(tcp->tcp_notsack_list != NULL);
9394 	ASSERT(tcp->tcp_rexmit == B_FALSE);
9395 
9396 	/* Defensive coding in case there is a bug... */
9397 	if (tcp->tcp_notsack_list == NULL) {
9398 		return;
9399 	}
9400 	notsack_blk = tcp->tcp_notsack_list;
9401 	mss = tcp->tcp_mss;
9402 
9403 	/*
9404 	 * Limit the num of outstanding data in the network to be
9405 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
9406 	 */
9407 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9408 
9409 	/* At least retransmit 1 MSS of data. */
9410 	if (usable_swnd <= 0) {
9411 		usable_swnd = mss;
9412 	}
9413 
9414 	/* Make sure no new RTT samples will be taken. */
9415 	tcp->tcp_csuna = tcp->tcp_snxt;
9416 
9417 	notsack_blk = tcp->tcp_notsack_list;
9418 	while (usable_swnd > 0) {
9419 		mblk_t		*snxt_mp, *tmp_mp;
9420 		tcp_seq		begin = tcp->tcp_sack_snxt;
9421 		tcp_seq		end;
9422 		int32_t		off;
9423 
9424 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
9425 			if (SEQ_GT(notsack_blk->end, begin) &&
9426 			    (notsack_blk->sack_cnt >=
9427 			    tcps->tcps_dupack_fast_retransmit)) {
9428 				end = notsack_blk->end;
9429 				if (SEQ_LT(begin, notsack_blk->begin)) {
9430 					begin = notsack_blk->begin;
9431 				}
9432 				break;
9433 			}
9434 		}
9435 		/*
9436 		 * All holes are filled.  Manipulate tcp_cwnd to send more
9437 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
9438 		 * set to tcp_cwnd_ssthresh.
9439 		 */
9440 		if (notsack_blk == NULL) {
9441 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
9442 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
9443 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
9444 				ASSERT(tcp->tcp_cwnd > 0);
9445 				return;
9446 			} else {
9447 				usable_swnd = usable_swnd / mss;
9448 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
9449 				    MAX(usable_swnd * mss, mss);
9450 				*flags |= TH_XMIT_NEEDED;
9451 				return;
9452 			}
9453 		}
9454 
9455 		/*
9456 		 * Note that we may send more than usable_swnd allows here
9457 		 * because of round off, but no more than 1 MSS of data.
9458 		 */
9459 		seg_len = end - begin;
9460 		if (seg_len > mss)
9461 			seg_len = mss;
9462 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
9463 		ASSERT(snxt_mp != NULL);
9464 		/* This should not happen.  Defensive coding again... */
9465 		if (snxt_mp == NULL) {
9466 			return;
9467 		}
9468 
9469 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
9470 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
9471 		if (xmit_mp == NULL)
9472 			return;
9473 
9474 		usable_swnd -= seg_len;
9475 		tcp->tcp_pipe += seg_len;
9476 		tcp->tcp_sack_snxt = begin + seg_len;
9477 
9478 		tcp_send_data(tcp, xmit_mp);
9479 
9480 		/*
9481 		 * Update the send timestamp to avoid false retransmission.
9482 		 */
9483 		snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9484 
9485 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9486 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
9487 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
9488 		/*
9489 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
9490 		 * This happens when new data sent during fast recovery is
9491 		 * also lost.  If TCP retransmits those new data, it needs
9492 		 * to extend SACK recover phase to avoid starting another
9493 		 * fast retransmit/recovery unnecessarily.
9494 		 */
9495 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
9496 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
9497 		}
9498 	}
9499 }
9500 
9501 /*
9502  * tcp_ss_rexmit() is called to do slow start retransmission after a timeout
9503  * or ICMP errors.
9504  *
9505  * To limit the number of duplicate segments, we limit the number of segment
9506  * to be sent in one time to tcp_snd_burst, the burst variable.
9507  */
9508 static void
9509 tcp_ss_rexmit(tcp_t *tcp)
9510 {
9511 	uint32_t	snxt;
9512 	uint32_t	smax;
9513 	int32_t		win;
9514 	int32_t		mss;
9515 	int32_t		off;
9516 	int32_t		burst = tcp->tcp_snd_burst;
9517 	mblk_t		*snxt_mp;
9518 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9519 
9520 	/*
9521 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
9522 	 * all unack'ed segments.
9523 	 */
9524 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
9525 		smax = tcp->tcp_rexmit_max;
9526 		snxt = tcp->tcp_rexmit_nxt;
9527 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
9528 			snxt = tcp->tcp_suna;
9529 		}
9530 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
9531 		win -= snxt - tcp->tcp_suna;
9532 		mss = tcp->tcp_mss;
9533 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
9534 
9535 		while (SEQ_LT(snxt, smax) && (win > 0) &&
9536 		    (burst > 0) && (snxt_mp != NULL)) {
9537 			mblk_t	*xmit_mp;
9538 			mblk_t	*old_snxt_mp = snxt_mp;
9539 			uint32_t cnt = mss;
9540 
9541 			if (win < cnt) {
9542 				cnt = win;
9543 			}
9544 			if (SEQ_GT(snxt + cnt, smax)) {
9545 				cnt = smax - snxt;
9546 			}
9547 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
9548 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
9549 			if (xmit_mp == NULL)
9550 				return;
9551 
9552 			tcp_send_data(tcp, xmit_mp);
9553 
9554 			snxt += cnt;
9555 			win -= cnt;
9556 			/*
9557 			 * Update the send timestamp to avoid false
9558 			 * retransmission.
9559 			 */
9560 			old_snxt_mp->b_prev = (mblk_t *)ddi_get_lbolt();
9561 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
9562 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
9563 
9564 			tcp->tcp_rexmit_nxt = snxt;
9565 			burst--;
9566 		}
9567 		/*
9568 		 * If we have transmitted all we have at the time
9569 		 * we started the retranmission, we can leave
9570 		 * the rest of the job to tcp_wput_data().  But we
9571 		 * need to check the send window first.  If the
9572 		 * win is not 0, go on with tcp_wput_data().
9573 		 */
9574 		if (SEQ_LT(snxt, smax) || win == 0) {
9575 			return;
9576 		}
9577 	}
9578 	/* Only call tcp_wput_data() if there is data to be sent. */
9579 	if (tcp->tcp_unsent) {
9580 		tcp_wput_data(tcp, NULL, B_FALSE);
9581 	}
9582 }
9583 
9584 /*
9585  * Process all TCP option in SYN segment.  Note that this function should
9586  * be called after tcp_set_destination() is called so that the necessary info
9587  * from IRE is already set in the tcp structure.
9588  *
9589  * This function sets up the correct tcp_mss value according to the
9590  * MSS option value and our header size.  It also sets up the window scale
9591  * and timestamp values, and initialize SACK info blocks.  But it does not
9592  * change receive window size after setting the tcp_mss value.  The caller
9593  * should do the appropriate change.
9594  */
9595 void
9596 tcp_process_options(tcp_t *tcp, tcpha_t *tcpha)
9597 {
9598 	int options;
9599 	tcp_opt_t tcpopt;
9600 	uint32_t mss_max;
9601 	char *tmp_tcph;
9602 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9603 	conn_t		*connp = tcp->tcp_connp;
9604 
9605 	tcpopt.tcp = NULL;
9606 	options = tcp_parse_options(tcpha, &tcpopt);
9607 
9608 	/*
9609 	 * Process MSS option.  Note that MSS option value does not account
9610 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
9611 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
9612 	 * IPv6.
9613 	 */
9614 	if (!(options & TCP_OPT_MSS_PRESENT)) {
9615 		if (connp->conn_ipversion == IPV4_VERSION)
9616 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
9617 		else
9618 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
9619 	} else {
9620 		if (connp->conn_ipversion == IPV4_VERSION)
9621 			mss_max = tcps->tcps_mss_max_ipv4;
9622 		else
9623 			mss_max = tcps->tcps_mss_max_ipv6;
9624 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
9625 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
9626 		else if (tcpopt.tcp_opt_mss > mss_max)
9627 			tcpopt.tcp_opt_mss = mss_max;
9628 	}
9629 
9630 	/* Process Window Scale option. */
9631 	if (options & TCP_OPT_WSCALE_PRESENT) {
9632 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
9633 		tcp->tcp_snd_ws_ok = B_TRUE;
9634 	} else {
9635 		tcp->tcp_snd_ws = B_FALSE;
9636 		tcp->tcp_snd_ws_ok = B_FALSE;
9637 		tcp->tcp_rcv_ws = B_FALSE;
9638 	}
9639 
9640 	/* Process Timestamp option. */
9641 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
9642 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
9643 		tmp_tcph = (char *)tcp->tcp_tcpha;
9644 
9645 		tcp->tcp_snd_ts_ok = B_TRUE;
9646 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
9647 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
9648 		ASSERT(OK_32PTR(tmp_tcph));
9649 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
9650 
9651 		/* Fill in our template header with basic timestamp option. */
9652 		tmp_tcph += connp->conn_ht_ulp_len;
9653 		tmp_tcph[0] = TCPOPT_NOP;
9654 		tmp_tcph[1] = TCPOPT_NOP;
9655 		tmp_tcph[2] = TCPOPT_TSTAMP;
9656 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
9657 		connp->conn_ht_iphc_len += TCPOPT_REAL_TS_LEN;
9658 		connp->conn_ht_ulp_len += TCPOPT_REAL_TS_LEN;
9659 		tcp->tcp_tcpha->tha_offset_and_reserved += (3 << 4);
9660 	} else {
9661 		tcp->tcp_snd_ts_ok = B_FALSE;
9662 	}
9663 
9664 	/*
9665 	 * Process SACK options.  If SACK is enabled for this connection,
9666 	 * then allocate the SACK info structure.  Note the following ways
9667 	 * when tcp_snd_sack_ok is set to true.
9668 	 *
9669 	 * For active connection: in tcp_set_destination() called in
9670 	 * tcp_connect().
9671 	 *
9672 	 * For passive connection: in tcp_set_destination() called in
9673 	 * tcp_input_listener().
9674 	 *
9675 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
9676 	 * That check makes sure that if we did not send a SACK OK option,
9677 	 * we will not enable SACK for this connection even though the other
9678 	 * side sends us SACK OK option.  For active connection, the SACK
9679 	 * info structure has already been allocated.  So we need to free
9680 	 * it if SACK is disabled.
9681 	 */
9682 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
9683 	    (tcp->tcp_snd_sack_ok ||
9684 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
9685 		/* This should be true only in the passive case. */
9686 		if (tcp->tcp_sack_info == NULL) {
9687 			ASSERT(TCP_IS_DETACHED(tcp));
9688 			tcp->tcp_sack_info =
9689 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
9690 		}
9691 		if (tcp->tcp_sack_info == NULL) {
9692 			tcp->tcp_snd_sack_ok = B_FALSE;
9693 		} else {
9694 			tcp->tcp_snd_sack_ok = B_TRUE;
9695 			if (tcp->tcp_snd_ts_ok) {
9696 				tcp->tcp_max_sack_blk = 3;
9697 			} else {
9698 				tcp->tcp_max_sack_blk = 4;
9699 			}
9700 		}
9701 	} else {
9702 		/*
9703 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
9704 		 * no SACK info will be used for this
9705 		 * connection.  This assumes that SACK usage
9706 		 * permission is negotiated.  This may need
9707 		 * to be changed once this is clarified.
9708 		 */
9709 		if (tcp->tcp_sack_info != NULL) {
9710 			ASSERT(tcp->tcp_notsack_list == NULL);
9711 			kmem_cache_free(tcp_sack_info_cache,
9712 			    tcp->tcp_sack_info);
9713 			tcp->tcp_sack_info = NULL;
9714 		}
9715 		tcp->tcp_snd_sack_ok = B_FALSE;
9716 	}
9717 
9718 	/*
9719 	 * Now we know the exact TCP/IP header length, subtract
9720 	 * that from tcp_mss to get our side's MSS.
9721 	 */
9722 	tcp->tcp_mss -= connp->conn_ht_iphc_len;
9723 
9724 	/*
9725 	 * Here we assume that the other side's header size will be equal to
9726 	 * our header size.  We calculate the real MSS accordingly.  Need to
9727 	 * take into additional stuffs IPsec puts in.
9728 	 *
9729 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
9730 	 */
9731 	tcpopt.tcp_opt_mss -= connp->conn_ht_iphc_len +
9732 	    tcp->tcp_ipsec_overhead -
9733 	    ((connp->conn_ipversion == IPV4_VERSION ?
9734 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
9735 
9736 	/*
9737 	 * Set MSS to the smaller one of both ends of the connection.
9738 	 * We should not have called tcp_mss_set() before, but our
9739 	 * side of the MSS should have been set to a proper value
9740 	 * by tcp_set_destination().  tcp_mss_set() will also set up the
9741 	 * STREAM head parameters properly.
9742 	 *
9743 	 * If we have a larger-than-16-bit window but the other side
9744 	 * didn't want to do window scale, tcp_rwnd_set() will take
9745 	 * care of that.
9746 	 */
9747 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss));
9748 
9749 	/*
9750 	 * Initialize tcp_cwnd value. After tcp_mss_set(), tcp_mss has been
9751 	 * updated properly.
9752 	 */
9753 	SET_TCP_INIT_CWND(tcp, tcp->tcp_mss, tcps->tcps_slow_start_initial);
9754 }
9755 
9756 /*
9757  * Sends the T_CONN_IND to the listener. The caller calls this
9758  * functions via squeue to get inside the listener's perimeter
9759  * once the 3 way hand shake is done a T_CONN_IND needs to be
9760  * sent. As an optimization, the caller can call this directly
9761  * if listener's perimeter is same as eager's.
9762  */
9763 /* ARGSUSED */
9764 void
9765 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
9766 {
9767 	conn_t			*lconnp = (conn_t *)arg;
9768 	tcp_t			*listener = lconnp->conn_tcp;
9769 	tcp_t			*tcp;
9770 	struct T_conn_ind	*conn_ind;
9771 	ipaddr_t 		*addr_cache;
9772 	boolean_t		need_send_conn_ind = B_FALSE;
9773 	tcp_stack_t		*tcps = listener->tcp_tcps;
9774 
9775 	/* retrieve the eager */
9776 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
9777 	ASSERT(conn_ind->OPT_offset != 0 &&
9778 	    conn_ind->OPT_length == sizeof (intptr_t));
9779 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
9780 	    conn_ind->OPT_length);
9781 
9782 	/*
9783 	 * TLI/XTI applications will get confused by
9784 	 * sending eager as an option since it violates
9785 	 * the option semantics. So remove the eager as
9786 	 * option since TLI/XTI app doesn't need it anyway.
9787 	 */
9788 	if (!TCP_IS_SOCKET(listener)) {
9789 		conn_ind->OPT_length = 0;
9790 		conn_ind->OPT_offset = 0;
9791 	}
9792 	if (listener->tcp_state != TCPS_LISTEN) {
9793 		/*
9794 		 * If listener has closed, it would have caused a
9795 		 * a cleanup/blowoff to happen for the eager. We
9796 		 * just need to return.
9797 		 */
9798 		freemsg(mp);
9799 		return;
9800 	}
9801 
9802 
9803 	/*
9804 	 * if the conn_req_q is full defer passing up the
9805 	 * T_CONN_IND until space is availabe after t_accept()
9806 	 * processing
9807 	 */
9808 	mutex_enter(&listener->tcp_eager_lock);
9809 
9810 	/*
9811 	 * Take the eager out, if it is in the list of droppable eagers
9812 	 * as we are here because the 3W handshake is over.
9813 	 */
9814 	MAKE_UNDROPPABLE(tcp);
9815 
9816 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
9817 		tcp_t *tail;
9818 
9819 		/*
9820 		 * The eager already has an extra ref put in tcp_input_data
9821 		 * so that it stays till accept comes back even though it
9822 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
9823 		 */
9824 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
9825 		listener->tcp_conn_req_cnt_q0--;
9826 		listener->tcp_conn_req_cnt_q++;
9827 
9828 		/* Move from SYN_RCVD to ESTABLISHED list  */
9829 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9830 		    tcp->tcp_eager_prev_q0;
9831 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9832 		    tcp->tcp_eager_next_q0;
9833 		tcp->tcp_eager_prev_q0 = NULL;
9834 		tcp->tcp_eager_next_q0 = NULL;
9835 
9836 		/*
9837 		 * Insert at end of the queue because sockfs
9838 		 * sends down T_CONN_RES in chronological
9839 		 * order. Leaving the older conn indications
9840 		 * at front of the queue helps reducing search
9841 		 * time.
9842 		 */
9843 		tail = listener->tcp_eager_last_q;
9844 		if (tail != NULL)
9845 			tail->tcp_eager_next_q = tcp;
9846 		else
9847 			listener->tcp_eager_next_q = tcp;
9848 		listener->tcp_eager_last_q = tcp;
9849 		tcp->tcp_eager_next_q = NULL;
9850 		/*
9851 		 * Delay sending up the T_conn_ind until we are
9852 		 * done with the eager. Once we have have sent up
9853 		 * the T_conn_ind, the accept can potentially complete
9854 		 * any time and release the refhold we have on the eager.
9855 		 */
9856 		need_send_conn_ind = B_TRUE;
9857 	} else {
9858 		/*
9859 		 * Defer connection on q0 and set deferred
9860 		 * connection bit true
9861 		 */
9862 		tcp->tcp_conn_def_q0 = B_TRUE;
9863 
9864 		/* take tcp out of q0 ... */
9865 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
9866 		    tcp->tcp_eager_next_q0;
9867 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
9868 		    tcp->tcp_eager_prev_q0;
9869 
9870 		/* ... and place it at the end of q0 */
9871 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
9872 		tcp->tcp_eager_next_q0 = listener;
9873 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
9874 		listener->tcp_eager_prev_q0 = tcp;
9875 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
9876 	}
9877 
9878 	/* we have timed out before */
9879 	if (tcp->tcp_syn_rcvd_timeout != 0) {
9880 		tcp->tcp_syn_rcvd_timeout = 0;
9881 		listener->tcp_syn_rcvd_timeout--;
9882 		if (listener->tcp_syn_defense &&
9883 		    listener->tcp_syn_rcvd_timeout <=
9884 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
9885 		    10*MINUTES < TICK_TO_MSEC(ddi_get_lbolt64() -
9886 		    listener->tcp_last_rcv_lbolt)) {
9887 			/*
9888 			 * Turn off the defense mode if we
9889 			 * believe the SYN attack is over.
9890 			 */
9891 			listener->tcp_syn_defense = B_FALSE;
9892 			if (listener->tcp_ip_addr_cache) {
9893 				kmem_free((void *)listener->tcp_ip_addr_cache,
9894 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
9895 				listener->tcp_ip_addr_cache = NULL;
9896 			}
9897 		}
9898 	}
9899 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
9900 	if (addr_cache != NULL) {
9901 		/*
9902 		 * We have finished a 3-way handshake with this
9903 		 * remote host. This proves the IP addr is good.
9904 		 * Cache it!
9905 		 */
9906 		addr_cache[IP_ADDR_CACHE_HASH(tcp->tcp_connp->conn_faddr_v4)] =
9907 		    tcp->tcp_connp->conn_faddr_v4;
9908 	}
9909 	mutex_exit(&listener->tcp_eager_lock);
9910 	if (need_send_conn_ind)
9911 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
9912 }
9913 
9914 /*
9915  * Send the newconn notification to ulp. The eager is blown off if the
9916  * notification fails.
9917  */
9918 static void
9919 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
9920 {
9921 	if (IPCL_IS_NONSTR(lconnp)) {
9922 		cred_t	*cr;
9923 		pid_t	cpid = NOPID;
9924 
9925 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
9926 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
9927 		    lconnp->conn_tcp);
9928 
9929 		cr = msg_getcred(mp, &cpid);
9930 
9931 		/* Keep the message around in case of a fallback to TPI */
9932 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
9933 		/*
9934 		 * Notify the ULP about the newconn. It is guaranteed that no
9935 		 * tcp_accept() call will be made for the eager if the
9936 		 * notification fails, so it's safe to blow it off in that
9937 		 * case.
9938 		 *
9939 		 * The upper handle will be assigned when tcp_accept() is
9940 		 * called.
9941 		 */
9942 		if ((*lconnp->conn_upcalls->su_newconn)
9943 		    (lconnp->conn_upper_handle,
9944 		    (sock_lower_handle_t)econnp,
9945 		    &sock_tcp_downcalls, cr, cpid,
9946 		    &econnp->conn_upcalls) == NULL) {
9947 			/* Failed to allocate a socket */
9948 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
9949 			    tcpEstabResets);
9950 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
9951 			    econnp->conn_tcp->tcp_conn_req_seqnum);
9952 		}
9953 	} else {
9954 		putnext(lconnp->conn_rq, mp);
9955 	}
9956 }
9957 
9958 /*
9959  * Handle a packet that has been reclassified by TCP.
9960  * This function drops the ref on connp that the caller had.
9961  */
9962 static void
9963 tcp_reinput(conn_t *connp, mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst)
9964 {
9965 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
9966 
9967 	if (connp->conn_incoming_ifindex != 0 &&
9968 	    connp->conn_incoming_ifindex != ira->ira_ruifindex) {
9969 		freemsg(mp);
9970 		CONN_DEC_REF(connp);
9971 		return;
9972 	}
9973 
9974 	if (CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss) ||
9975 	    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
9976 		ip6_t *ip6h;
9977 		ipha_t *ipha;
9978 
9979 		if (ira->ira_flags & IRAF_IS_IPV4) {
9980 			ipha = (ipha_t *)mp->b_rptr;
9981 			ip6h = NULL;
9982 		} else {
9983 			ipha = NULL;
9984 			ip6h = (ip6_t *)mp->b_rptr;
9985 		}
9986 		mp = ipsec_check_inbound_policy(mp, connp, ipha, ip6h, ira);
9987 		if (mp == NULL) {
9988 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9989 			/* Note that mp is NULL */
9990 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
9991 			CONN_DEC_REF(connp);
9992 			return;
9993 		}
9994 	}
9995 
9996 	if (IPCL_IS_TCP(connp)) {
9997 		/*
9998 		 * do not drain, certain use cases can blow
9999 		 * the stack
10000 		 */
10001 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10002 		    connp->conn_recv, connp, ira,
10003 		    SQ_NODRAIN, SQTAG_IP_TCP_INPUT);
10004 	} else {
10005 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
10006 		(connp->conn_recv)(connp, mp, NULL,
10007 		    ira);
10008 		CONN_DEC_REF(connp);
10009 	}
10010 
10011 }
10012 
10013 boolean_t tcp_outbound_squeue_switch = B_FALSE;
10014 
10015 /*
10016  * Handle M_DATA messages from IP. Its called directly from IP via
10017  * squeue for received IP packets.
10018  *
10019  * The first argument is always the connp/tcp to which the mp belongs.
10020  * There are no exceptions to this rule. The caller has already put
10021  * a reference on this connp/tcp and once tcp_input_data() returns,
10022  * the squeue will do the refrele.
10023  *
10024  * The TH_SYN for the listener directly go to tcp_input_listener via
10025  * squeue. ICMP errors go directly to tcp_icmp_input().
10026  *
10027  * sqp: NULL = recursive, sqp != NULL means called from squeue
10028  */
10029 void
10030 tcp_input_data(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
10031 {
10032 	int32_t		bytes_acked;
10033 	int32_t		gap;
10034 	mblk_t		*mp1;
10035 	uint_t		flags;
10036 	uint32_t	new_swnd = 0;
10037 	uchar_t		*iphdr;
10038 	uchar_t		*rptr;
10039 	int32_t		rgap;
10040 	uint32_t	seg_ack;
10041 	int		seg_len;
10042 	uint_t		ip_hdr_len;
10043 	uint32_t	seg_seq;
10044 	tcpha_t		*tcpha;
10045 	int		urp;
10046 	tcp_opt_t	tcpopt;
10047 	ip_pkt_t	ipp;
10048 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
10049 	uint32_t	cwnd;
10050 	uint32_t	add;
10051 	int		npkt;
10052 	int		mss;
10053 	conn_t		*connp = (conn_t *)arg;
10054 	squeue_t	*sqp = (squeue_t *)arg2;
10055 	tcp_t		*tcp = connp->conn_tcp;
10056 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10057 
10058 	/*
10059 	 * RST from fused tcp loopback peer should trigger an unfuse.
10060 	 */
10061 	if (tcp->tcp_fused) {
10062 		TCP_STAT(tcps, tcp_fusion_aborted);
10063 		tcp_unfuse(tcp);
10064 	}
10065 
10066 	iphdr = mp->b_rptr;
10067 	rptr = mp->b_rptr;
10068 	ASSERT(OK_32PTR(rptr));
10069 
10070 	ip_hdr_len = ira->ira_ip_hdr_length;
10071 	if (connp->conn_recv_ancillary.crb_all != 0) {
10072 		/*
10073 		 * Record packet information in the ip_pkt_t
10074 		 */
10075 		ipp.ipp_fields = 0;
10076 		if (ira->ira_flags & IRAF_IS_IPV4) {
10077 			(void) ip_find_hdr_v4((ipha_t *)rptr, &ipp,
10078 			    B_FALSE);
10079 		} else {
10080 			uint8_t nexthdrp;
10081 
10082 			/*
10083 			 * IPv6 packets can only be received by applications
10084 			 * that are prepared to receive IPv6 addresses.
10085 			 * The IP fanout must ensure this.
10086 			 */
10087 			ASSERT(connp->conn_family == AF_INET6);
10088 
10089 			(void) ip_find_hdr_v6(mp, (ip6_t *)rptr, B_TRUE, &ipp,
10090 			    &nexthdrp);
10091 			ASSERT(nexthdrp == IPPROTO_TCP);
10092 
10093 			/* Could have caused a pullup? */
10094 			iphdr = mp->b_rptr;
10095 			rptr = mp->b_rptr;
10096 		}
10097 	}
10098 	ASSERT(DB_TYPE(mp) == M_DATA);
10099 	ASSERT(mp->b_next == NULL);
10100 
10101 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10102 	seg_seq = ntohl(tcpha->tha_seq);
10103 	seg_ack = ntohl(tcpha->tha_ack);
10104 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
10105 	seg_len = (int)(mp->b_wptr - rptr) -
10106 	    (ip_hdr_len + TCP_HDR_LENGTH(tcpha));
10107 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
10108 		do {
10109 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
10110 			    (uintptr_t)INT_MAX);
10111 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
10112 		} while ((mp1 = mp1->b_cont) != NULL &&
10113 		    mp1->b_datap->db_type == M_DATA);
10114 	}
10115 
10116 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
10117 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
10118 		    seg_len, tcpha, ira);
10119 		return;
10120 	}
10121 
10122 	if (sqp != NULL) {
10123 		/*
10124 		 * This is the correct place to update tcp_last_recv_time. Note
10125 		 * that it is also updated for tcp structure that belongs to
10126 		 * global and listener queues which do not really need updating.
10127 		 * But that should not cause any harm.  And it is updated for
10128 		 * all kinds of incoming segments, not only for data segments.
10129 		 */
10130 		tcp->tcp_last_recv_time = LBOLT_FASTPATH;
10131 	}
10132 
10133 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
10134 
10135 	BUMP_LOCAL(tcp->tcp_ibsegs);
10136 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10137 
10138 	if ((flags & TH_URG) && sqp != NULL) {
10139 		/*
10140 		 * TCP can't handle urgent pointers that arrive before
10141 		 * the connection has been accept()ed since it can't
10142 		 * buffer OOB data.  Discard segment if this happens.
10143 		 *
10144 		 * We can't just rely on a non-null tcp_listener to indicate
10145 		 * that the accept() has completed since unlinking of the
10146 		 * eager and completion of the accept are not atomic.
10147 		 * tcp_detached, when it is not set (B_FALSE) indicates
10148 		 * that the accept() has completed.
10149 		 *
10150 		 * Nor can it reassemble urgent pointers, so discard
10151 		 * if it's not the next segment expected.
10152 		 *
10153 		 * Otherwise, collapse chain into one mblk (discard if
10154 		 * that fails).  This makes sure the headers, retransmitted
10155 		 * data, and new data all are in the same mblk.
10156 		 */
10157 		ASSERT(mp != NULL);
10158 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
10159 			freemsg(mp);
10160 			return;
10161 		}
10162 		/* Update pointers into message */
10163 		iphdr = rptr = mp->b_rptr;
10164 		tcpha = (tcpha_t *)&rptr[ip_hdr_len];
10165 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
10166 			/*
10167 			 * Since we can't handle any data with this urgent
10168 			 * pointer that is out of sequence, we expunge
10169 			 * the data.  This allows us to still register
10170 			 * the urgent mark and generate the M_PCSIG,
10171 			 * which we can do.
10172 			 */
10173 			mp->b_wptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10174 			seg_len = 0;
10175 		}
10176 	}
10177 
10178 	switch (tcp->tcp_state) {
10179 	case TCPS_SYN_SENT:
10180 		if (connp->conn_final_sqp == NULL &&
10181 		    tcp_outbound_squeue_switch && sqp != NULL) {
10182 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
10183 			connp->conn_final_sqp = sqp;
10184 			if (connp->conn_final_sqp != connp->conn_sqp) {
10185 				DTRACE_PROBE1(conn__final__sqp__switch,
10186 				    conn_t *, connp);
10187 				CONN_INC_REF(connp);
10188 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
10189 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
10190 				    tcp_input_data, connp, ira, ip_squeue_flag,
10191 				    SQTAG_CONNECT_FINISH);
10192 				return;
10193 			}
10194 			DTRACE_PROBE1(conn__final__sqp__same, conn_t *, connp);
10195 		}
10196 		if (flags & TH_ACK) {
10197 			/*
10198 			 * Note that our stack cannot send data before a
10199 			 * connection is established, therefore the
10200 			 * following check is valid.  Otherwise, it has
10201 			 * to be changed.
10202 			 */
10203 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
10204 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10205 				freemsg(mp);
10206 				if (flags & TH_RST)
10207 					return;
10208 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
10209 				    tcp, seg_ack, 0, TH_RST);
10210 				return;
10211 			}
10212 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
10213 		}
10214 		if (flags & TH_RST) {
10215 			freemsg(mp);
10216 			if (flags & TH_ACK)
10217 				(void) tcp_clean_death(tcp,
10218 				    ECONNREFUSED, 13);
10219 			return;
10220 		}
10221 		if (!(flags & TH_SYN)) {
10222 			freemsg(mp);
10223 			return;
10224 		}
10225 
10226 		/* Process all TCP options. */
10227 		tcp_process_options(tcp, tcpha);
10228 		/*
10229 		 * The following changes our rwnd to be a multiple of the
10230 		 * MIN(peer MSS, our MSS) for performance reason.
10231 		 */
10232 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(connp->conn_rcvbuf,
10233 		    tcp->tcp_mss));
10234 
10235 		/* Is the other end ECN capable? */
10236 		if (tcp->tcp_ecn_ok) {
10237 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
10238 				tcp->tcp_ecn_ok = B_FALSE;
10239 			}
10240 		}
10241 		/*
10242 		 * Clear ECN flags because it may interfere with later
10243 		 * processing.
10244 		 */
10245 		flags &= ~(TH_ECE|TH_CWR);
10246 
10247 		tcp->tcp_irs = seg_seq;
10248 		tcp->tcp_rack = seg_seq;
10249 		tcp->tcp_rnxt = seg_seq + 1;
10250 		tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10251 		if (!TCP_IS_DETACHED(tcp)) {
10252 			/* Allocate room for SACK options if needed. */
10253 			connp->conn_wroff = connp->conn_ht_iphc_len;
10254 			if (tcp->tcp_snd_sack_ok)
10255 				connp->conn_wroff += TCPOPT_MAX_SACK_LEN;
10256 			if (!tcp->tcp_loopback)
10257 				connp->conn_wroff += tcps->tcps_wroff_xtra;
10258 
10259 			(void) proto_set_tx_wroff(connp->conn_rq, connp,
10260 			    connp->conn_wroff);
10261 		}
10262 		if (flags & TH_ACK) {
10263 			/*
10264 			 * If we can't get the confirmation upstream, pretend
10265 			 * we didn't even see this one.
10266 			 *
10267 			 * XXX: how can we pretend we didn't see it if we
10268 			 * have updated rnxt et. al.
10269 			 *
10270 			 * For loopback we defer sending up the T_CONN_CON
10271 			 * until after some checks below.
10272 			 */
10273 			mp1 = NULL;
10274 			/*
10275 			 * tcp_sendmsg() checks tcp_state without entering
10276 			 * the squeue so tcp_state should be updated before
10277 			 * sending up connection confirmation
10278 			 */
10279 			tcp->tcp_state = TCPS_ESTABLISHED;
10280 			if (!tcp_conn_con(tcp, iphdr, mp,
10281 			    tcp->tcp_loopback ? &mp1 : NULL, ira)) {
10282 				tcp->tcp_state = TCPS_SYN_SENT;
10283 				freemsg(mp);
10284 				return;
10285 			}
10286 			/* SYN was acked - making progress */
10287 			tcp->tcp_ip_forward_progress = B_TRUE;
10288 
10289 			/* One for the SYN */
10290 			tcp->tcp_suna = tcp->tcp_iss + 1;
10291 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
10292 
10293 			/*
10294 			 * If SYN was retransmitted, need to reset all
10295 			 * retransmission info.  This is because this
10296 			 * segment will be treated as a dup ACK.
10297 			 */
10298 			if (tcp->tcp_rexmit) {
10299 				tcp->tcp_rexmit = B_FALSE;
10300 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
10301 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
10302 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
10303 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
10304 				tcp->tcp_ms_we_have_waited = 0;
10305 
10306 				/*
10307 				 * Set tcp_cwnd back to 1 MSS, per
10308 				 * recommendation from
10309 				 * draft-floyd-incr-init-win-01.txt,
10310 				 * Increasing TCP's Initial Window.
10311 				 */
10312 				tcp->tcp_cwnd = tcp->tcp_mss;
10313 			}
10314 
10315 			tcp->tcp_swl1 = seg_seq;
10316 			tcp->tcp_swl2 = seg_ack;
10317 
10318 			new_swnd = ntohs(tcpha->tha_win);
10319 			tcp->tcp_swnd = new_swnd;
10320 			if (new_swnd > tcp->tcp_max_swnd)
10321 				tcp->tcp_max_swnd = new_swnd;
10322 
10323 			/*
10324 			 * Always send the three-way handshake ack immediately
10325 			 * in order to make the connection complete as soon as
10326 			 * possible on the accepting host.
10327 			 */
10328 			flags |= TH_ACK_NEEDED;
10329 
10330 			/*
10331 			 * Special case for loopback.  At this point we have
10332 			 * received SYN-ACK from the remote endpoint.  In
10333 			 * order to ensure that both endpoints reach the
10334 			 * fused state prior to any data exchange, the final
10335 			 * ACK needs to be sent before we indicate T_CONN_CON
10336 			 * to the module upstream.
10337 			 */
10338 			if (tcp->tcp_loopback) {
10339 				mblk_t *ack_mp;
10340 
10341 				ASSERT(!tcp->tcp_unfusable);
10342 				ASSERT(mp1 != NULL);
10343 				/*
10344 				 * For loopback, we always get a pure SYN-ACK
10345 				 * and only need to send back the final ACK
10346 				 * with no data (this is because the other
10347 				 * tcp is ours and we don't do T/TCP).  This
10348 				 * final ACK triggers the passive side to
10349 				 * perform fusion in ESTABLISHED state.
10350 				 */
10351 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
10352 					if (tcp->tcp_ack_tid != 0) {
10353 						(void) TCP_TIMER_CANCEL(tcp,
10354 						    tcp->tcp_ack_tid);
10355 						tcp->tcp_ack_tid = 0;
10356 					}
10357 					tcp_send_data(tcp, ack_mp);
10358 					BUMP_LOCAL(tcp->tcp_obsegs);
10359 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
10360 
10361 					if (!IPCL_IS_NONSTR(connp)) {
10362 						/* Send up T_CONN_CON */
10363 						if (ira->ira_cred != NULL) {
10364 							mblk_setcred(mp1,
10365 							    ira->ira_cred,
10366 							    ira->ira_cpid);
10367 						}
10368 						putnext(connp->conn_rq, mp1);
10369 					} else {
10370 						(*connp->conn_upcalls->
10371 						    su_connected)
10372 						    (connp->conn_upper_handle,
10373 						    tcp->tcp_connid,
10374 						    ira->ira_cred,
10375 						    ira->ira_cpid);
10376 						freemsg(mp1);
10377 					}
10378 
10379 					freemsg(mp);
10380 					return;
10381 				}
10382 				/*
10383 				 * Forget fusion; we need to handle more
10384 				 * complex cases below.  Send the deferred
10385 				 * T_CONN_CON message upstream and proceed
10386 				 * as usual.  Mark this tcp as not capable
10387 				 * of fusion.
10388 				 */
10389 				TCP_STAT(tcps, tcp_fusion_unfusable);
10390 				tcp->tcp_unfusable = B_TRUE;
10391 				if (!IPCL_IS_NONSTR(connp)) {
10392 					if (ira->ira_cred != NULL) {
10393 						mblk_setcred(mp1, ira->ira_cred,
10394 						    ira->ira_cpid);
10395 					}
10396 					putnext(connp->conn_rq, mp1);
10397 				} else {
10398 					(*connp->conn_upcalls->su_connected)
10399 					    (connp->conn_upper_handle,
10400 					    tcp->tcp_connid, ira->ira_cred,
10401 					    ira->ira_cpid);
10402 					freemsg(mp1);
10403 				}
10404 			}
10405 
10406 			/*
10407 			 * Check to see if there is data to be sent.  If
10408 			 * yes, set the transmit flag.  Then check to see
10409 			 * if received data processing needs to be done.
10410 			 * If not, go straight to xmit_check.  This short
10411 			 * cut is OK as we don't support T/TCP.
10412 			 */
10413 			if (tcp->tcp_unsent)
10414 				flags |= TH_XMIT_NEEDED;
10415 
10416 			if (seg_len == 0 && !(flags & TH_URG)) {
10417 				freemsg(mp);
10418 				goto xmit_check;
10419 			}
10420 
10421 			flags &= ~TH_SYN;
10422 			seg_seq++;
10423 			break;
10424 		}
10425 		tcp->tcp_state = TCPS_SYN_RCVD;
10426 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
10427 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
10428 		if (mp1 != NULL) {
10429 			tcp_send_data(tcp, mp1);
10430 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
10431 		}
10432 		freemsg(mp);
10433 		return;
10434 	case TCPS_SYN_RCVD:
10435 		if (flags & TH_ACK) {
10436 			/*
10437 			 * In this state, a SYN|ACK packet is either bogus
10438 			 * because the other side must be ACKing our SYN which
10439 			 * indicates it has seen the ACK for their SYN and
10440 			 * shouldn't retransmit it or we're crossing SYNs
10441 			 * on active open.
10442 			 */
10443 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
10444 				freemsg(mp);
10445 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
10446 				    tcp, seg_ack, 0, TH_RST);
10447 				return;
10448 			}
10449 			/*
10450 			 * NOTE: RFC 793 pg. 72 says this should be
10451 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
10452 			 * but that would mean we have an ack that ignored
10453 			 * our SYN.
10454 			 */
10455 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
10456 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
10457 				freemsg(mp);
10458 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
10459 				    tcp, seg_ack, 0, TH_RST);
10460 				return;
10461 			}
10462 			/*
10463 			 * No sane TCP stack will send such a small window
10464 			 * without receiving any data.  Just drop this invalid
10465 			 * ACK.  We also shorten the abort timeout in case
10466 			 * this is an attack.
10467 			 */
10468 			if (ntohs(tcpha->tha_win) <
10469 			    (tcp->tcp_mss >> tcp_init_wnd_shft)) {
10470 				freemsg(mp);
10471 				TCP_STAT(tcps, tcp_zwin_ack_syn);
10472 				tcp->tcp_second_ctimer_threshold =
10473 				    tcp_early_abort * SECONDS;
10474 				return;
10475 			}
10476 		}
10477 		break;
10478 	case TCPS_LISTEN:
10479 		/*
10480 		 * Only a TLI listener can come through this path when a
10481 		 * acceptor is going back to be a listener and a packet
10482 		 * for the acceptor hits the classifier. For a socket
10483 		 * listener, this can never happen because a listener
10484 		 * can never accept connection on itself and hence a
10485 		 * socket acceptor can not go back to being a listener.
10486 		 */
10487 		ASSERT(!TCP_IS_SOCKET(tcp));
10488 		/*FALLTHRU*/
10489 	case TCPS_CLOSED:
10490 	case TCPS_BOUND: {
10491 		conn_t	*new_connp;
10492 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
10493 
10494 		/*
10495 		 * Don't accept any input on a closed tcp as this TCP logically
10496 		 * does not exist on the system. Don't proceed further with
10497 		 * this TCP. For instance, this packet could trigger another
10498 		 * close of this tcp which would be disastrous for tcp_refcnt.
10499 		 * tcp_close_detached / tcp_clean_death / tcp_closei_local must
10500 		 * be called at most once on a TCP. In this case we need to
10501 		 * refeed the packet into the classifier and figure out where
10502 		 * the packet should go.
10503 		 */
10504 		new_connp = ipcl_classify(mp, ira, ipst);
10505 		if (new_connp != NULL) {
10506 			/* Drops ref on new_connp */
10507 			tcp_reinput(new_connp, mp, ira, ipst);
10508 			return;
10509 		}
10510 		/* We failed to classify. For now just drop the packet */
10511 		freemsg(mp);
10512 		return;
10513 	}
10514 	case TCPS_IDLE:
10515 		/*
10516 		 * Handle the case where the tcp_clean_death() has happened
10517 		 * on a connection (application hasn't closed yet) but a packet
10518 		 * was already queued on squeue before tcp_clean_death()
10519 		 * was processed. Calling tcp_clean_death() twice on same
10520 		 * connection can result in weird behaviour.
10521 		 */
10522 		freemsg(mp);
10523 		return;
10524 	default:
10525 		break;
10526 	}
10527 
10528 	/*
10529 	 * Already on the correct queue/perimeter.
10530 	 * If this is a detached connection and not an eager
10531 	 * connection hanging off a listener then new data
10532 	 * (past the FIN) will cause a reset.
10533 	 * We do a special check here where it
10534 	 * is out of the main line, rather than check
10535 	 * if we are detached every time we see new
10536 	 * data down below.
10537 	 */
10538 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
10539 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
10540 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
10541 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
10542 
10543 		freemsg(mp);
10544 		/*
10545 		 * This could be an SSL closure alert. We're detached so just
10546 		 * acknowledge it this last time.
10547 		 */
10548 		if (tcp->tcp_kssl_ctx != NULL) {
10549 			kssl_release_ctx(tcp->tcp_kssl_ctx);
10550 			tcp->tcp_kssl_ctx = NULL;
10551 
10552 			tcp->tcp_rnxt += seg_len;
10553 			tcp->tcp_tcpha->tha_ack = htonl(tcp->tcp_rnxt);
10554 			flags |= TH_ACK_NEEDED;
10555 			goto ack_check;
10556 		}
10557 
10558 		tcp_xmit_ctl("new data when detached", tcp,
10559 		    tcp->tcp_snxt, 0, TH_RST);
10560 		(void) tcp_clean_death(tcp, EPROTO, 12);
10561 		return;
10562 	}
10563 
10564 	mp->b_rptr = (uchar_t *)tcpha + TCP_HDR_LENGTH(tcpha);
10565 	urp = ntohs(tcpha->tha_urp) - TCP_OLD_URP_INTERPRETATION;
10566 	new_swnd = ntohs(tcpha->tha_win) <<
10567 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
10568 
10569 	if (tcp->tcp_snd_ts_ok) {
10570 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
10571 			/*
10572 			 * This segment is not acceptable.
10573 			 * Drop it and send back an ACK.
10574 			 */
10575 			freemsg(mp);
10576 			flags |= TH_ACK_NEEDED;
10577 			goto ack_check;
10578 		}
10579 	} else if (tcp->tcp_snd_sack_ok) {
10580 		ASSERT(tcp->tcp_sack_info != NULL);
10581 		tcpopt.tcp = tcp;
10582 		/*
10583 		 * SACK info in already updated in tcp_parse_options.  Ignore
10584 		 * all other TCP options...
10585 		 */
10586 		(void) tcp_parse_options(tcpha, &tcpopt);
10587 	}
10588 try_again:;
10589 	mss = tcp->tcp_mss;
10590 	gap = seg_seq - tcp->tcp_rnxt;
10591 	rgap = tcp->tcp_rwnd - (gap + seg_len);
10592 	/*
10593 	 * gap is the amount of sequence space between what we expect to see
10594 	 * and what we got for seg_seq.  A positive value for gap means
10595 	 * something got lost.  A negative value means we got some old stuff.
10596 	 */
10597 	if (gap < 0) {
10598 		/* Old stuff present.  Is the SYN in there? */
10599 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
10600 		    (seg_len != 0)) {
10601 			flags &= ~TH_SYN;
10602 			seg_seq++;
10603 			urp--;
10604 			/* Recompute the gaps after noting the SYN. */
10605 			goto try_again;
10606 		}
10607 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
10608 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
10609 		    (seg_len > -gap ? -gap : seg_len));
10610 		/* Remove the old stuff from seg_len. */
10611 		seg_len += gap;
10612 		/*
10613 		 * Anything left?
10614 		 * Make sure to check for unack'd FIN when rest of data
10615 		 * has been previously ack'd.
10616 		 */
10617 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
10618 			/*
10619 			 * Resets are only valid if they lie within our offered
10620 			 * window.  If the RST bit is set, we just ignore this
10621 			 * segment.
10622 			 */
10623 			if (flags & TH_RST) {
10624 				freemsg(mp);
10625 				return;
10626 			}
10627 
10628 			/*
10629 			 * The arriving of dup data packets indicate that we
10630 			 * may have postponed an ack for too long, or the other
10631 			 * side's RTT estimate is out of shape. Start acking
10632 			 * more often.
10633 			 */
10634 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
10635 			    tcp->tcp_rack_cnt >= 1 &&
10636 			    tcp->tcp_rack_abs_max > 2) {
10637 				tcp->tcp_rack_abs_max--;
10638 			}
10639 			tcp->tcp_rack_cur_max = 1;
10640 
10641 			/*
10642 			 * This segment is "unacceptable".  None of its
10643 			 * sequence space lies within our advertized window.
10644 			 *
10645 			 * Adjust seg_len to the original value for tracing.
10646 			 */
10647 			seg_len -= gap;
10648 			if (connp->conn_debug) {
10649 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
10650 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
10651 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
10652 				    "seg_len %d, rnxt %u, snxt %u, %s",
10653 				    gap, rgap, flags, seg_seq, seg_ack,
10654 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
10655 				    tcp_display(tcp, NULL,
10656 				    DISP_ADDR_AND_PORT));
10657 			}
10658 
10659 			/*
10660 			 * Arrange to send an ACK in response to the
10661 			 * unacceptable segment per RFC 793 page 69. There
10662 			 * is only one small difference between ours and the
10663 			 * acceptability test in the RFC - we accept ACK-only
10664 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
10665 			 * will be generated.
10666 			 *
10667 			 * Note that we have to ACK an ACK-only packet at least
10668 			 * for stacks that send 0-length keep-alives with
10669 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
10670 			 * section 4.2.3.6. As long as we don't ever generate
10671 			 * an unacceptable packet in response to an incoming
10672 			 * packet that is unacceptable, it should not cause
10673 			 * "ACK wars".
10674 			 */
10675 			flags |=  TH_ACK_NEEDED;
10676 
10677 			/*
10678 			 * Continue processing this segment in order to use the
10679 			 * ACK information it contains, but skip all other
10680 			 * sequence-number processing.	Processing the ACK
10681 			 * information is necessary in order to
10682 			 * re-synchronize connections that may have lost
10683 			 * synchronization.
10684 			 *
10685 			 * We clear seg_len and flag fields related to
10686 			 * sequence number processing as they are not
10687 			 * to be trusted for an unacceptable segment.
10688 			 */
10689 			seg_len = 0;
10690 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
10691 			goto process_ack;
10692 		}
10693 
10694 		/* Fix seg_seq, and chew the gap off the front. */
10695 		seg_seq = tcp->tcp_rnxt;
10696 		urp += gap;
10697 		do {
10698 			mblk_t	*mp2;
10699 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10700 			    (uintptr_t)UINT_MAX);
10701 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
10702 			if (gap > 0) {
10703 				mp->b_rptr = mp->b_wptr - gap;
10704 				break;
10705 			}
10706 			mp2 = mp;
10707 			mp = mp->b_cont;
10708 			freeb(mp2);
10709 		} while (gap < 0);
10710 		/*
10711 		 * If the urgent data has already been acknowledged, we
10712 		 * should ignore TH_URG below
10713 		 */
10714 		if (urp < 0)
10715 			flags &= ~TH_URG;
10716 	}
10717 	/*
10718 	 * rgap is the amount of stuff received out of window.  A negative
10719 	 * value is the amount out of window.
10720 	 */
10721 	if (rgap < 0) {
10722 		mblk_t	*mp2;
10723 
10724 		if (tcp->tcp_rwnd == 0) {
10725 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
10726 		} else {
10727 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
10728 			UPDATE_MIB(&tcps->tcps_mib,
10729 			    tcpInDataPastWinBytes, -rgap);
10730 		}
10731 
10732 		/*
10733 		 * seg_len does not include the FIN, so if more than
10734 		 * just the FIN is out of window, we act like we don't
10735 		 * see it.  (If just the FIN is out of window, rgap
10736 		 * will be zero and we will go ahead and acknowledge
10737 		 * the FIN.)
10738 		 */
10739 		flags &= ~TH_FIN;
10740 
10741 		/* Fix seg_len and make sure there is something left. */
10742 		seg_len += rgap;
10743 		if (seg_len <= 0) {
10744 			/*
10745 			 * Resets are only valid if they lie within our offered
10746 			 * window.  If the RST bit is set, we just ignore this
10747 			 * segment.
10748 			 */
10749 			if (flags & TH_RST) {
10750 				freemsg(mp);
10751 				return;
10752 			}
10753 
10754 			/* Per RFC 793, we need to send back an ACK. */
10755 			flags |= TH_ACK_NEEDED;
10756 
10757 			/*
10758 			 * Send SIGURG as soon as possible i.e. even
10759 			 * if the TH_URG was delivered in a window probe
10760 			 * packet (which will be unacceptable).
10761 			 *
10762 			 * We generate a signal if none has been generated
10763 			 * for this connection or if this is a new urgent
10764 			 * byte. Also send a zero-length "unmarked" message
10765 			 * to inform SIOCATMARK that this is not the mark.
10766 			 *
10767 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
10768 			 * is sent up. This plus the check for old data
10769 			 * (gap >= 0) handles the wraparound of the sequence
10770 			 * number space without having to always track the
10771 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
10772 			 * this max in its rcv_up variable).
10773 			 *
10774 			 * This prevents duplicate SIGURGS due to a "late"
10775 			 * zero-window probe when the T_EXDATA_IND has already
10776 			 * been sent up.
10777 			 */
10778 			if ((flags & TH_URG) &&
10779 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
10780 			    tcp->tcp_urp_last))) {
10781 				if (IPCL_IS_NONSTR(connp)) {
10782 					if (!TCP_IS_DETACHED(tcp)) {
10783 						(*connp->conn_upcalls->
10784 						    su_signal_oob)
10785 						    (connp->conn_upper_handle,
10786 						    urp);
10787 					}
10788 				} else {
10789 					mp1 = allocb(0, BPRI_MED);
10790 					if (mp1 == NULL) {
10791 						freemsg(mp);
10792 						return;
10793 					}
10794 					if (!TCP_IS_DETACHED(tcp) &&
10795 					    !putnextctl1(connp->conn_rq,
10796 					    M_PCSIG, SIGURG)) {
10797 						/* Try again on the rexmit. */
10798 						freemsg(mp1);
10799 						freemsg(mp);
10800 						return;
10801 					}
10802 					/*
10803 					 * If the next byte would be the mark
10804 					 * then mark with MARKNEXT else mark
10805 					 * with NOTMARKNEXT.
10806 					 */
10807 					if (gap == 0 && urp == 0)
10808 						mp1->b_flag |= MSGMARKNEXT;
10809 					else
10810 						mp1->b_flag |= MSGNOTMARKNEXT;
10811 					freemsg(tcp->tcp_urp_mark_mp);
10812 					tcp->tcp_urp_mark_mp = mp1;
10813 					flags |= TH_SEND_URP_MARK;
10814 				}
10815 				tcp->tcp_urp_last_valid = B_TRUE;
10816 				tcp->tcp_urp_last = urp + seg_seq;
10817 			}
10818 			/*
10819 			 * If this is a zero window probe, continue to
10820 			 * process the ACK part.  But we need to set seg_len
10821 			 * to 0 to avoid data processing.  Otherwise just
10822 			 * drop the segment and send back an ACK.
10823 			 */
10824 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
10825 				flags &= ~(TH_SYN | TH_URG);
10826 				seg_len = 0;
10827 				goto process_ack;
10828 			} else {
10829 				freemsg(mp);
10830 				goto ack_check;
10831 			}
10832 		}
10833 		/* Pitch out of window stuff off the end. */
10834 		rgap = seg_len;
10835 		mp2 = mp;
10836 		do {
10837 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
10838 			    (uintptr_t)INT_MAX);
10839 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
10840 			if (rgap < 0) {
10841 				mp2->b_wptr += rgap;
10842 				if ((mp1 = mp2->b_cont) != NULL) {
10843 					mp2->b_cont = NULL;
10844 					freemsg(mp1);
10845 				}
10846 				break;
10847 			}
10848 		} while ((mp2 = mp2->b_cont) != NULL);
10849 	}
10850 ok:;
10851 	/*
10852 	 * TCP should check ECN info for segments inside the window only.
10853 	 * Therefore the check should be done here.
10854 	 */
10855 	if (tcp->tcp_ecn_ok) {
10856 		if (flags & TH_CWR) {
10857 			tcp->tcp_ecn_echo_on = B_FALSE;
10858 		}
10859 		/*
10860 		 * Note that both ECN_CE and CWR can be set in the
10861 		 * same segment.  In this case, we once again turn
10862 		 * on ECN_ECHO.
10863 		 */
10864 		if (connp->conn_ipversion == IPV4_VERSION) {
10865 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
10866 
10867 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
10868 				tcp->tcp_ecn_echo_on = B_TRUE;
10869 			}
10870 		} else {
10871 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
10872 
10873 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
10874 			    htonl(IPH_ECN_CE << 20)) {
10875 				tcp->tcp_ecn_echo_on = B_TRUE;
10876 			}
10877 		}
10878 	}
10879 
10880 	/*
10881 	 * Check whether we can update tcp_ts_recent.  This test is
10882 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
10883 	 * Extensions for High Performance: An Update", Internet Draft.
10884 	 */
10885 	if (tcp->tcp_snd_ts_ok &&
10886 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
10887 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
10888 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
10889 		tcp->tcp_last_rcv_lbolt = LBOLT_FASTPATH64;
10890 	}
10891 
10892 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
10893 		/*
10894 		 * FIN in an out of order segment.  We record this in
10895 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
10896 		 * Clear the FIN so that any check on FIN flag will fail.
10897 		 * Remember that FIN also counts in the sequence number
10898 		 * space.  So we need to ack out of order FIN only segments.
10899 		 */
10900 		if (flags & TH_FIN) {
10901 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
10902 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
10903 			flags &= ~TH_FIN;
10904 			flags |= TH_ACK_NEEDED;
10905 		}
10906 		if (seg_len > 0) {
10907 			/* Fill in the SACK blk list. */
10908 			if (tcp->tcp_snd_sack_ok) {
10909 				ASSERT(tcp->tcp_sack_info != NULL);
10910 				tcp_sack_insert(tcp->tcp_sack_list,
10911 				    seg_seq, seg_seq + seg_len,
10912 				    &(tcp->tcp_num_sack_blk));
10913 			}
10914 
10915 			/*
10916 			 * Attempt reassembly and see if we have something
10917 			 * ready to go.
10918 			 */
10919 			mp = tcp_reass(tcp, mp, seg_seq);
10920 			/* Always ack out of order packets */
10921 			flags |= TH_ACK_NEEDED | TH_PUSH;
10922 			if (mp) {
10923 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
10924 				    (uintptr_t)INT_MAX);
10925 				seg_len = mp->b_cont ? msgdsize(mp) :
10926 				    (int)(mp->b_wptr - mp->b_rptr);
10927 				seg_seq = tcp->tcp_rnxt;
10928 				/*
10929 				 * A gap is filled and the seq num and len
10930 				 * of the gap match that of a previously
10931 				 * received FIN, put the FIN flag back in.
10932 				 */
10933 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
10934 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
10935 					flags |= TH_FIN;
10936 					tcp->tcp_valid_bits &=
10937 					    ~TCP_OFO_FIN_VALID;
10938 				}
10939 				if (tcp->tcp_reass_tid != 0) {
10940 					(void) TCP_TIMER_CANCEL(tcp,
10941 					    tcp->tcp_reass_tid);
10942 					/*
10943 					 * Restart the timer if there is still
10944 					 * data in the reassembly queue.
10945 					 */
10946 					if (tcp->tcp_reass_head != NULL) {
10947 						tcp->tcp_reass_tid = TCP_TIMER(
10948 						    tcp, tcp_reass_timer,
10949 						    MSEC_TO_TICK(
10950 						    tcps->tcps_reass_timeout));
10951 					} else {
10952 						tcp->tcp_reass_tid = 0;
10953 					}
10954 				}
10955 			} else {
10956 				/*
10957 				 * Keep going even with NULL mp.
10958 				 * There may be a useful ACK or something else
10959 				 * we don't want to miss.
10960 				 *
10961 				 * But TCP should not perform fast retransmit
10962 				 * because of the ack number.  TCP uses
10963 				 * seg_len == 0 to determine if it is a pure
10964 				 * ACK.  And this is not a pure ACK.
10965 				 */
10966 				seg_len = 0;
10967 				ofo_seg = B_TRUE;
10968 
10969 				if (tcps->tcps_reass_timeout != 0 &&
10970 				    tcp->tcp_reass_tid == 0) {
10971 					tcp->tcp_reass_tid = TCP_TIMER(tcp,
10972 					    tcp_reass_timer, MSEC_TO_TICK(
10973 					    tcps->tcps_reass_timeout));
10974 				}
10975 			}
10976 		}
10977 	} else if (seg_len > 0) {
10978 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
10979 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
10980 		/*
10981 		 * If an out of order FIN was received before, and the seq
10982 		 * num and len of the new segment match that of the FIN,
10983 		 * put the FIN flag back in.
10984 		 */
10985 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
10986 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
10987 			flags |= TH_FIN;
10988 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
10989 		}
10990 	}
10991 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
10992 	if (flags & TH_RST) {
10993 		freemsg(mp);
10994 		switch (tcp->tcp_state) {
10995 		case TCPS_SYN_RCVD:
10996 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
10997 			break;
10998 		case TCPS_ESTABLISHED:
10999 		case TCPS_FIN_WAIT_1:
11000 		case TCPS_FIN_WAIT_2:
11001 		case TCPS_CLOSE_WAIT:
11002 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
11003 			break;
11004 		case TCPS_CLOSING:
11005 		case TCPS_LAST_ACK:
11006 			(void) tcp_clean_death(tcp, 0, 16);
11007 			break;
11008 		default:
11009 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11010 			(void) tcp_clean_death(tcp, ENXIO, 17);
11011 			break;
11012 		}
11013 		return;
11014 	}
11015 	if (flags & TH_SYN) {
11016 		/*
11017 		 * See RFC 793, Page 71
11018 		 *
11019 		 * The seq number must be in the window as it should
11020 		 * be "fixed" above.  If it is outside window, it should
11021 		 * be already rejected.  Note that we allow seg_seq to be
11022 		 * rnxt + rwnd because we want to accept 0 window probe.
11023 		 */
11024 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
11025 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
11026 		freemsg(mp);
11027 		/*
11028 		 * If the ACK flag is not set, just use our snxt as the
11029 		 * seq number of the RST segment.
11030 		 */
11031 		if (!(flags & TH_ACK)) {
11032 			seg_ack = tcp->tcp_snxt;
11033 		}
11034 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
11035 		    TH_RST|TH_ACK);
11036 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
11037 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
11038 		return;
11039 	}
11040 	/*
11041 	 * urp could be -1 when the urp field in the packet is 0
11042 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
11043 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
11044 	 */
11045 	if (flags & TH_URG && urp >= 0) {
11046 		if (!tcp->tcp_urp_last_valid ||
11047 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
11048 			/*
11049 			 * Non-STREAMS sockets handle the urgent data a litte
11050 			 * differently from STREAMS based sockets. There is no
11051 			 * need to mark any mblks with the MSG{NOT,}MARKNEXT
11052 			 * flags to keep SIOCATMARK happy. Instead a
11053 			 * su_signal_oob upcall is made to update the mark.
11054 			 * Neither is a T_EXDATA_IND mblk needed to be
11055 			 * prepended to the urgent data. The urgent data is
11056 			 * delivered using the su_recv upcall, where we set
11057 			 * the MSG_OOB flag to indicate that it is urg data.
11058 			 *
11059 			 * Neither TH_SEND_URP_MARK nor TH_MARKNEXT_NEEDED
11060 			 * are used by non-STREAMS sockets.
11061 			 */
11062 			if (IPCL_IS_NONSTR(connp)) {
11063 				if (!TCP_IS_DETACHED(tcp)) {
11064 					(*connp->conn_upcalls->su_signal_oob)
11065 					    (connp->conn_upper_handle, urp);
11066 				}
11067 			} else {
11068 				/*
11069 				 * If we haven't generated the signal yet for
11070 				 * this urgent pointer value, do it now.  Also,
11071 				 * send up a zero-length M_DATA indicating
11072 				 * whether or not this is the mark. The latter
11073 				 * is not needed when a T_EXDATA_IND is sent up.
11074 				 * However, if there are allocation failures
11075 				 * this code relies on the sender retransmitting
11076 				 * and the socket code for determining the mark
11077 				 * should not block waiting for the peer to
11078 				 * transmit. Thus, for simplicity we always
11079 				 * send up the mark indication.
11080 				 */
11081 				mp1 = allocb(0, BPRI_MED);
11082 				if (mp1 == NULL) {
11083 					freemsg(mp);
11084 					return;
11085 				}
11086 				if (!TCP_IS_DETACHED(tcp) &&
11087 				    !putnextctl1(connp->conn_rq, M_PCSIG,
11088 				    SIGURG)) {
11089 					/* Try again on the rexmit. */
11090 					freemsg(mp1);
11091 					freemsg(mp);
11092 					return;
11093 				}
11094 				/*
11095 				 * Mark with NOTMARKNEXT for now.
11096 				 * The code below will change this to MARKNEXT
11097 				 * if we are at the mark.
11098 				 *
11099 				 * If there are allocation failures (e.g. in
11100 				 * dupmsg below) the next time tcp_input_data
11101 				 * sees the urgent segment it will send up the
11102 				 * MSGMARKNEXT message.
11103 				 */
11104 				mp1->b_flag |= MSGNOTMARKNEXT;
11105 				freemsg(tcp->tcp_urp_mark_mp);
11106 				tcp->tcp_urp_mark_mp = mp1;
11107 				flags |= TH_SEND_URP_MARK;
11108 #ifdef DEBUG
11109 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11110 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
11111 				    "last %x, %s",
11112 				    seg_seq, urp, tcp->tcp_urp_last,
11113 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11114 #endif /* DEBUG */
11115 			}
11116 			tcp->tcp_urp_last_valid = B_TRUE;
11117 			tcp->tcp_urp_last = urp + seg_seq;
11118 		} else if (tcp->tcp_urp_mark_mp != NULL) {
11119 			/*
11120 			 * An allocation failure prevented the previous
11121 			 * tcp_input_data from sending up the allocated
11122 			 * MSG*MARKNEXT message - send it up this time
11123 			 * around.
11124 			 */
11125 			flags |= TH_SEND_URP_MARK;
11126 		}
11127 
11128 		/*
11129 		 * If the urgent byte is in this segment, make sure that it is
11130 		 * all by itself.  This makes it much easier to deal with the
11131 		 * possibility of an allocation failure on the T_exdata_ind.
11132 		 * Note that seg_len is the number of bytes in the segment, and
11133 		 * urp is the offset into the segment of the urgent byte.
11134 		 * urp < seg_len means that the urgent byte is in this segment.
11135 		 */
11136 		if (urp < seg_len) {
11137 			if (seg_len != 1) {
11138 				uint32_t  tmp_rnxt;
11139 				/*
11140 				 * Break it up and feed it back in.
11141 				 * Re-attach the IP header.
11142 				 */
11143 				mp->b_rptr = iphdr;
11144 				if (urp > 0) {
11145 					/*
11146 					 * There is stuff before the urgent
11147 					 * byte.
11148 					 */
11149 					mp1 = dupmsg(mp);
11150 					if (!mp1) {
11151 						/*
11152 						 * Trim from urgent byte on.
11153 						 * The rest will come back.
11154 						 */
11155 						(void) adjmsg(mp,
11156 						    urp - seg_len);
11157 						tcp_input_data(connp,
11158 						    mp, NULL, ira);
11159 						return;
11160 					}
11161 					(void) adjmsg(mp1, urp - seg_len);
11162 					/* Feed this piece back in. */
11163 					tmp_rnxt = tcp->tcp_rnxt;
11164 					tcp_input_data(connp, mp1, NULL, ira);
11165 					/*
11166 					 * If the data passed back in was not
11167 					 * processed (ie: bad ACK) sending
11168 					 * the remainder back in will cause a
11169 					 * loop. In this case, drop the
11170 					 * packet and let the sender try
11171 					 * sending a good packet.
11172 					 */
11173 					if (tmp_rnxt == tcp->tcp_rnxt) {
11174 						freemsg(mp);
11175 						return;
11176 					}
11177 				}
11178 				if (urp != seg_len - 1) {
11179 					uint32_t  tmp_rnxt;
11180 					/*
11181 					 * There is stuff after the urgent
11182 					 * byte.
11183 					 */
11184 					mp1 = dupmsg(mp);
11185 					if (!mp1) {
11186 						/*
11187 						 * Trim everything beyond the
11188 						 * urgent byte.  The rest will
11189 						 * come back.
11190 						 */
11191 						(void) adjmsg(mp,
11192 						    urp + 1 - seg_len);
11193 						tcp_input_data(connp,
11194 						    mp, NULL, ira);
11195 						return;
11196 					}
11197 					(void) adjmsg(mp1, urp + 1 - seg_len);
11198 					tmp_rnxt = tcp->tcp_rnxt;
11199 					tcp_input_data(connp, mp1, NULL, ira);
11200 					/*
11201 					 * If the data passed back in was not
11202 					 * processed (ie: bad ACK) sending
11203 					 * the remainder back in will cause a
11204 					 * loop. In this case, drop the
11205 					 * packet and let the sender try
11206 					 * sending a good packet.
11207 					 */
11208 					if (tmp_rnxt == tcp->tcp_rnxt) {
11209 						freemsg(mp);
11210 						return;
11211 					}
11212 				}
11213 				tcp_input_data(connp, mp, NULL, ira);
11214 				return;
11215 			}
11216 			/*
11217 			 * This segment contains only the urgent byte.  We
11218 			 * have to allocate the T_exdata_ind, if we can.
11219 			 */
11220 			if (IPCL_IS_NONSTR(connp)) {
11221 				int error;
11222 
11223 				(*connp->conn_upcalls->su_recv)
11224 				    (connp->conn_upper_handle, mp, seg_len,
11225 				    MSG_OOB, &error, NULL);
11226 				/*
11227 				 * We should never be in middle of a
11228 				 * fallback, the squeue guarantees that.
11229 				 */
11230 				ASSERT(error != EOPNOTSUPP);
11231 				mp = NULL;
11232 				goto update_ack;
11233 			} else if (!tcp->tcp_urp_mp) {
11234 				struct T_exdata_ind *tei;
11235 				mp1 = allocb(sizeof (struct T_exdata_ind),
11236 				    BPRI_MED);
11237 				if (!mp1) {
11238 					/*
11239 					 * Sigh... It'll be back.
11240 					 * Generate any MSG*MARK message now.
11241 					 */
11242 					freemsg(mp);
11243 					seg_len = 0;
11244 					if (flags & TH_SEND_URP_MARK) {
11245 
11246 
11247 						ASSERT(tcp->tcp_urp_mark_mp);
11248 						tcp->tcp_urp_mark_mp->b_flag &=
11249 						    ~MSGNOTMARKNEXT;
11250 						tcp->tcp_urp_mark_mp->b_flag |=
11251 						    MSGMARKNEXT;
11252 					}
11253 					goto ack_check;
11254 				}
11255 				mp1->b_datap->db_type = M_PROTO;
11256 				tei = (struct T_exdata_ind *)mp1->b_rptr;
11257 				tei->PRIM_type = T_EXDATA_IND;
11258 				tei->MORE_flag = 0;
11259 				mp1->b_wptr = (uchar_t *)&tei[1];
11260 				tcp->tcp_urp_mp = mp1;
11261 #ifdef DEBUG
11262 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11263 				    "tcp_rput: allocated exdata_ind %s",
11264 				    tcp_display(tcp, NULL,
11265 				    DISP_PORT_ONLY));
11266 #endif /* DEBUG */
11267 				/*
11268 				 * There is no need to send a separate MSG*MARK
11269 				 * message since the T_EXDATA_IND will be sent
11270 				 * now.
11271 				 */
11272 				flags &= ~TH_SEND_URP_MARK;
11273 				freemsg(tcp->tcp_urp_mark_mp);
11274 				tcp->tcp_urp_mark_mp = NULL;
11275 			}
11276 			/*
11277 			 * Now we are all set.  On the next putnext upstream,
11278 			 * tcp_urp_mp will be non-NULL and will get prepended
11279 			 * to what has to be this piece containing the urgent
11280 			 * byte.  If for any reason we abort this segment below,
11281 			 * if it comes back, we will have this ready, or it
11282 			 * will get blown off in close.
11283 			 */
11284 		} else if (urp == seg_len) {
11285 			/*
11286 			 * The urgent byte is the next byte after this sequence
11287 			 * number. If this endpoint is non-STREAMS, then there
11288 			 * is nothing to do here since the socket has already
11289 			 * been notified about the urg pointer by the
11290 			 * su_signal_oob call above.
11291 			 *
11292 			 * In case of STREAMS, some more work might be needed.
11293 			 * If there is data it is marked with MSGMARKNEXT and
11294 			 * and any tcp_urp_mark_mp is discarded since it is not
11295 			 * needed. Otherwise, if the code above just allocated
11296 			 * a zero-length tcp_urp_mark_mp message, that message
11297 			 * is tagged with MSGMARKNEXT. Sending up these
11298 			 * MSGMARKNEXT messages makes SIOCATMARK work correctly
11299 			 * even though the T_EXDATA_IND will not be sent up
11300 			 * until the urgent byte arrives.
11301 			 */
11302 			if (!IPCL_IS_NONSTR(tcp->tcp_connp)) {
11303 				if (seg_len != 0) {
11304 					flags |= TH_MARKNEXT_NEEDED;
11305 					freemsg(tcp->tcp_urp_mark_mp);
11306 					tcp->tcp_urp_mark_mp = NULL;
11307 					flags &= ~TH_SEND_URP_MARK;
11308 				} else if (tcp->tcp_urp_mark_mp != NULL) {
11309 					flags |= TH_SEND_URP_MARK;
11310 					tcp->tcp_urp_mark_mp->b_flag &=
11311 					    ~MSGNOTMARKNEXT;
11312 					tcp->tcp_urp_mark_mp->b_flag |=
11313 					    MSGMARKNEXT;
11314 				}
11315 			}
11316 #ifdef DEBUG
11317 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11318 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
11319 			    seg_len, flags,
11320 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
11321 #endif /* DEBUG */
11322 		}
11323 #ifdef DEBUG
11324 		else {
11325 			/* Data left until we hit mark */
11326 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
11327 			    "tcp_rput: URP %d bytes left, %s",
11328 			    urp - seg_len, tcp_display(tcp, NULL,
11329 			    DISP_PORT_ONLY));
11330 		}
11331 #endif /* DEBUG */
11332 	}
11333 
11334 process_ack:
11335 	if (!(flags & TH_ACK)) {
11336 		freemsg(mp);
11337 		goto xmit_check;
11338 	}
11339 	}
11340 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
11341 
11342 	if (bytes_acked > 0)
11343 		tcp->tcp_ip_forward_progress = B_TRUE;
11344 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
11345 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
11346 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
11347 			/* 3-way handshake complete - pass up the T_CONN_IND */
11348 			tcp_t	*listener = tcp->tcp_listener;
11349 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
11350 
11351 			tcp->tcp_tconnind_started = B_TRUE;
11352 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
11353 			/*
11354 			 * We are here means eager is fine but it can
11355 			 * get a TH_RST at any point between now and till
11356 			 * accept completes and disappear. We need to
11357 			 * ensure that reference to eager is valid after
11358 			 * we get out of eager's perimeter. So we do
11359 			 * an extra refhold.
11360 			 */
11361 			CONN_INC_REF(connp);
11362 
11363 			/*
11364 			 * The listener also exists because of the refhold
11365 			 * done in tcp_input_listener. Its possible that it
11366 			 * might have closed. We will check that once we
11367 			 * get inside listeners context.
11368 			 */
11369 			CONN_INC_REF(listener->tcp_connp);
11370 			if (listener->tcp_connp->conn_sqp ==
11371 			    connp->conn_sqp) {
11372 				/*
11373 				 * We optimize by not calling an SQUEUE_ENTER
11374 				 * on the listener since we know that the
11375 				 * listener and eager squeues are the same.
11376 				 * We are able to make this check safely only
11377 				 * because neither the eager nor the listener
11378 				 * can change its squeue. Only an active connect
11379 				 * can change its squeue
11380 				 */
11381 				tcp_send_conn_ind(listener->tcp_connp, mp,
11382 				    listener->tcp_connp->conn_sqp);
11383 				CONN_DEC_REF(listener->tcp_connp);
11384 			} else if (!tcp->tcp_loopback) {
11385 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11386 				    mp, tcp_send_conn_ind,
11387 				    listener->tcp_connp, NULL, SQ_FILL,
11388 				    SQTAG_TCP_CONN_IND);
11389 			} else {
11390 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
11391 				    mp, tcp_send_conn_ind,
11392 				    listener->tcp_connp, NULL, SQ_PROCESS,
11393 				    SQTAG_TCP_CONN_IND);
11394 			}
11395 		}
11396 
11397 		/*
11398 		 * We are seeing the final ack in the three way
11399 		 * hand shake of a active open'ed connection
11400 		 * so we must send up a T_CONN_CON
11401 		 *
11402 		 * tcp_sendmsg() checks tcp_state without entering
11403 		 * the squeue so tcp_state should be updated before
11404 		 * sending up connection confirmation.
11405 		 */
11406 		tcp->tcp_state = TCPS_ESTABLISHED;
11407 		if (tcp->tcp_active_open) {
11408 			if (!tcp_conn_con(tcp, iphdr, mp, NULL, ira)) {
11409 				freemsg(mp);
11410 				tcp->tcp_state = TCPS_SYN_RCVD;
11411 				return;
11412 			}
11413 			/*
11414 			 * Don't fuse the loopback endpoints for
11415 			 * simultaneous active opens.
11416 			 */
11417 			if (tcp->tcp_loopback) {
11418 				TCP_STAT(tcps, tcp_fusion_unfusable);
11419 				tcp->tcp_unfusable = B_TRUE;
11420 			}
11421 		}
11422 
11423 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
11424 		bytes_acked--;
11425 		/* SYN was acked - making progress */
11426 		tcp->tcp_ip_forward_progress = B_TRUE;
11427 
11428 		/*
11429 		 * If SYN was retransmitted, need to reset all
11430 		 * retransmission info as this segment will be
11431 		 * treated as a dup ACK.
11432 		 */
11433 		if (tcp->tcp_rexmit) {
11434 			tcp->tcp_rexmit = B_FALSE;
11435 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11436 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
11437 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11438 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11439 			tcp->tcp_ms_we_have_waited = 0;
11440 			tcp->tcp_cwnd = mss;
11441 		}
11442 
11443 		/*
11444 		 * We set the send window to zero here.
11445 		 * This is needed if there is data to be
11446 		 * processed already on the queue.
11447 		 * Later (at swnd_update label), the
11448 		 * "new_swnd > tcp_swnd" condition is satisfied
11449 		 * the XMIT_NEEDED flag is set in the current
11450 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
11451 		 * called if there is already data on queue in
11452 		 * this state.
11453 		 */
11454 		tcp->tcp_swnd = 0;
11455 
11456 		if (new_swnd > tcp->tcp_max_swnd)
11457 			tcp->tcp_max_swnd = new_swnd;
11458 		tcp->tcp_swl1 = seg_seq;
11459 		tcp->tcp_swl2 = seg_ack;
11460 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
11461 
11462 		/* Fuse when both sides are in ESTABLISHED state */
11463 		if (tcp->tcp_loopback && do_tcp_fusion)
11464 			tcp_fuse(tcp, iphdr, tcpha);
11465 
11466 	}
11467 	/* This code follows 4.4BSD-Lite2 mostly. */
11468 	if (bytes_acked < 0)
11469 		goto est;
11470 
11471 	/*
11472 	 * If TCP is ECN capable and the congestion experience bit is
11473 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
11474 	 * done once per window (or more loosely, per RTT).
11475 	 */
11476 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
11477 		tcp->tcp_cwr = B_FALSE;
11478 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
11479 		if (!tcp->tcp_cwr) {
11480 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
11481 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
11482 			tcp->tcp_cwnd = npkt * mss;
11483 			/*
11484 			 * If the cwnd is 0, use the timer to clock out
11485 			 * new segments.  This is required by the ECN spec.
11486 			 */
11487 			if (npkt == 0) {
11488 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11489 				/*
11490 				 * This makes sure that when the ACK comes
11491 				 * back, we will increase tcp_cwnd by 1 MSS.
11492 				 */
11493 				tcp->tcp_cwnd_cnt = 0;
11494 			}
11495 			tcp->tcp_cwr = B_TRUE;
11496 			/*
11497 			 * This marks the end of the current window of in
11498 			 * flight data.  That is why we don't use
11499 			 * tcp_suna + tcp_swnd.  Only data in flight can
11500 			 * provide ECN info.
11501 			 */
11502 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11503 			tcp->tcp_ecn_cwr_sent = B_FALSE;
11504 		}
11505 	}
11506 
11507 	mp1 = tcp->tcp_xmit_head;
11508 	if (bytes_acked == 0) {
11509 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
11510 			int dupack_cnt;
11511 
11512 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
11513 			/*
11514 			 * Fast retransmit.  When we have seen exactly three
11515 			 * identical ACKs while we have unacked data
11516 			 * outstanding we take it as a hint that our peer
11517 			 * dropped something.
11518 			 *
11519 			 * If TCP is retransmitting, don't do fast retransmit.
11520 			 */
11521 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
11522 			    ! tcp->tcp_rexmit) {
11523 				/* Do Limited Transmit */
11524 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
11525 				    tcps->tcps_dupack_fast_retransmit) {
11526 					/*
11527 					 * RFC 3042
11528 					 *
11529 					 * What we need to do is temporarily
11530 					 * increase tcp_cwnd so that new
11531 					 * data can be sent if it is allowed
11532 					 * by the receive window (tcp_rwnd).
11533 					 * tcp_wput_data() will take care of
11534 					 * the rest.
11535 					 *
11536 					 * If the connection is SACK capable,
11537 					 * only do limited xmit when there
11538 					 * is SACK info.
11539 					 *
11540 					 * Note how tcp_cwnd is incremented.
11541 					 * The first dup ACK will increase
11542 					 * it by 1 MSS.  The second dup ACK
11543 					 * will increase it by 2 MSS.  This
11544 					 * means that only 1 new segment will
11545 					 * be sent for each dup ACK.
11546 					 */
11547 					if (tcp->tcp_unsent > 0 &&
11548 					    (!tcp->tcp_snd_sack_ok ||
11549 					    (tcp->tcp_snd_sack_ok &&
11550 					    tcp->tcp_notsack_list != NULL))) {
11551 						tcp->tcp_cwnd += mss <<
11552 						    (tcp->tcp_dupack_cnt - 1);
11553 						flags |= TH_LIMIT_XMIT;
11554 					}
11555 				} else if (dupack_cnt ==
11556 				    tcps->tcps_dupack_fast_retransmit) {
11557 
11558 				/*
11559 				 * If we have reduced tcp_ssthresh
11560 				 * because of ECN, do not reduce it again
11561 				 * unless it is already one window of data
11562 				 * away.  After one window of data, tcp_cwr
11563 				 * should then be cleared.  Note that
11564 				 * for non ECN capable connection, tcp_cwr
11565 				 * should always be false.
11566 				 *
11567 				 * Adjust cwnd since the duplicate
11568 				 * ack indicates that a packet was
11569 				 * dropped (due to congestion.)
11570 				 */
11571 				if (!tcp->tcp_cwr) {
11572 					npkt = ((tcp->tcp_snxt -
11573 					    tcp->tcp_suna) >> 1) / mss;
11574 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
11575 					    mss;
11576 					tcp->tcp_cwnd = (npkt +
11577 					    tcp->tcp_dupack_cnt) * mss;
11578 				}
11579 				if (tcp->tcp_ecn_ok) {
11580 					tcp->tcp_cwr = B_TRUE;
11581 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
11582 					tcp->tcp_ecn_cwr_sent = B_FALSE;
11583 				}
11584 
11585 				/*
11586 				 * We do Hoe's algorithm.  Refer to her
11587 				 * paper "Improving the Start-up Behavior
11588 				 * of a Congestion Control Scheme for TCP,"
11589 				 * appeared in SIGCOMM'96.
11590 				 *
11591 				 * Save highest seq no we have sent so far.
11592 				 * Be careful about the invisible FIN byte.
11593 				 */
11594 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
11595 				    (tcp->tcp_unsent == 0)) {
11596 					tcp->tcp_rexmit_max = tcp->tcp_fss;
11597 				} else {
11598 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
11599 				}
11600 
11601 				/*
11602 				 * Do not allow bursty traffic during.
11603 				 * fast recovery.  Refer to Fall and Floyd's
11604 				 * paper "Simulation-based Comparisons of
11605 				 * Tahoe, Reno and SACK TCP" (in CCR?)
11606 				 * This is a best current practise.
11607 				 */
11608 				tcp->tcp_snd_burst = TCP_CWND_SS;
11609 
11610 				/*
11611 				 * For SACK:
11612 				 * Calculate tcp_pipe, which is the
11613 				 * estimated number of bytes in
11614 				 * network.
11615 				 *
11616 				 * tcp_fack is the highest sack'ed seq num
11617 				 * TCP has received.
11618 				 *
11619 				 * tcp_pipe is explained in the above quoted
11620 				 * Fall and Floyd's paper.  tcp_fack is
11621 				 * explained in Mathis and Mahdavi's
11622 				 * "Forward Acknowledgment: Refining TCP
11623 				 * Congestion Control" in SIGCOMM '96.
11624 				 */
11625 				if (tcp->tcp_snd_sack_ok) {
11626 					ASSERT(tcp->tcp_sack_info != NULL);
11627 					if (tcp->tcp_notsack_list != NULL) {
11628 						tcp->tcp_pipe = tcp->tcp_snxt -
11629 						    tcp->tcp_fack;
11630 						tcp->tcp_sack_snxt = seg_ack;
11631 						flags |= TH_NEED_SACK_REXMIT;
11632 					} else {
11633 						/*
11634 						 * Always initialize tcp_pipe
11635 						 * even though we don't have
11636 						 * any SACK info.  If later
11637 						 * we get SACK info and
11638 						 * tcp_pipe is not initialized,
11639 						 * funny things will happen.
11640 						 */
11641 						tcp->tcp_pipe =
11642 						    tcp->tcp_cwnd_ssthresh;
11643 					}
11644 				} else {
11645 					flags |= TH_REXMIT_NEEDED;
11646 				} /* tcp_snd_sack_ok */
11647 
11648 				} else {
11649 					/*
11650 					 * Here we perform congestion
11651 					 * avoidance, but NOT slow start.
11652 					 * This is known as the Fast
11653 					 * Recovery Algorithm.
11654 					 */
11655 					if (tcp->tcp_snd_sack_ok &&
11656 					    tcp->tcp_notsack_list != NULL) {
11657 						flags |= TH_NEED_SACK_REXMIT;
11658 						tcp->tcp_pipe -= mss;
11659 						if (tcp->tcp_pipe < 0)
11660 							tcp->tcp_pipe = 0;
11661 					} else {
11662 					/*
11663 					 * We know that one more packet has
11664 					 * left the pipe thus we can update
11665 					 * cwnd.
11666 					 */
11667 					cwnd = tcp->tcp_cwnd + mss;
11668 					if (cwnd > tcp->tcp_cwnd_max)
11669 						cwnd = tcp->tcp_cwnd_max;
11670 					tcp->tcp_cwnd = cwnd;
11671 					if (tcp->tcp_unsent > 0)
11672 						flags |= TH_XMIT_NEEDED;
11673 					}
11674 				}
11675 			}
11676 		} else if (tcp->tcp_zero_win_probe) {
11677 			/*
11678 			 * If the window has opened, need to arrange
11679 			 * to send additional data.
11680 			 */
11681 			if (new_swnd != 0) {
11682 				/* tcp_suna != tcp_snxt */
11683 				/* Packet contains a window update */
11684 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
11685 				tcp->tcp_zero_win_probe = 0;
11686 				tcp->tcp_timer_backoff = 0;
11687 				tcp->tcp_ms_we_have_waited = 0;
11688 
11689 				/*
11690 				 * Transmit starting with tcp_suna since
11691 				 * the one byte probe is not ack'ed.
11692 				 * If TCP has sent more than one identical
11693 				 * probe, tcp_rexmit will be set.  That means
11694 				 * tcp_ss_rexmit() will send out the one
11695 				 * byte along with new data.  Otherwise,
11696 				 * fake the retransmission.
11697 				 */
11698 				flags |= TH_XMIT_NEEDED;
11699 				if (!tcp->tcp_rexmit) {
11700 					tcp->tcp_rexmit = B_TRUE;
11701 					tcp->tcp_dupack_cnt = 0;
11702 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
11703 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
11704 				}
11705 			}
11706 		}
11707 		goto swnd_update;
11708 	}
11709 
11710 	/*
11711 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
11712 	 * If the ACK value acks something that we have not yet sent, it might
11713 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
11714 	 * other side.
11715 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
11716 	 * state is handled above, so we can always just drop the segment and
11717 	 * send an ACK here.
11718 	 *
11719 	 * In the case where the peer shrinks the window, we see the new window
11720 	 * update, but all the data sent previously is queued up by the peer.
11721 	 * To account for this, in tcp_process_shrunk_swnd(), the sequence
11722 	 * number, which was already sent, and within window, is recorded.
11723 	 * tcp_snxt is then updated.
11724 	 *
11725 	 * If the window has previously shrunk, and an ACK for data not yet
11726 	 * sent, according to tcp_snxt is recieved, it may still be valid. If
11727 	 * the ACK is for data within the window at the time the window was
11728 	 * shrunk, then the ACK is acceptable. In this case tcp_snxt is set to
11729 	 * the sequence number ACK'ed.
11730 	 *
11731 	 * If the ACK covers all the data sent at the time the window was
11732 	 * shrunk, we can now set tcp_is_wnd_shrnk to B_FALSE.
11733 	 *
11734 	 * Should we send ACKs in response to ACK only segments?
11735 	 */
11736 
11737 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
11738 		if ((tcp->tcp_is_wnd_shrnk) &&
11739 		    (SEQ_LEQ(seg_ack, tcp->tcp_snxt_shrunk))) {
11740 			uint32_t data_acked_ahead_snxt;
11741 
11742 			data_acked_ahead_snxt = seg_ack - tcp->tcp_snxt;
11743 			tcp_update_xmit_tail(tcp, seg_ack);
11744 			tcp->tcp_unsent -= data_acked_ahead_snxt;
11745 		} else {
11746 			BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
11747 			/* drop the received segment */
11748 			freemsg(mp);
11749 
11750 			/*
11751 			 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
11752 			 * greater than 0, check if the number of such
11753 			 * bogus ACks is greater than that count.  If yes,
11754 			 * don't send back any ACK.  This prevents TCP from
11755 			 * getting into an ACK storm if somehow an attacker
11756 			 * successfully spoofs an acceptable segment to our
11757 			 * peer.  If this continues (count > 2 X threshold),
11758 			 * we should abort this connection.
11759 			 */
11760 			if (tcp_drop_ack_unsent_cnt > 0 &&
11761 			    ++tcp->tcp_in_ack_unsent >
11762 			    tcp_drop_ack_unsent_cnt) {
11763 				TCP_STAT(tcps, tcp_in_ack_unsent_drop);
11764 				if (tcp->tcp_in_ack_unsent > 2 *
11765 				    tcp_drop_ack_unsent_cnt) {
11766 					(void) tcp_clean_death(tcp, EPROTO, 20);
11767 				}
11768 				return;
11769 			}
11770 			mp = tcp_ack_mp(tcp);
11771 			if (mp != NULL) {
11772 				BUMP_LOCAL(tcp->tcp_obsegs);
11773 				BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
11774 				tcp_send_data(tcp, mp);
11775 			}
11776 			return;
11777 		}
11778 	} else if (tcp->tcp_is_wnd_shrnk && SEQ_GEQ(seg_ack,
11779 	    tcp->tcp_snxt_shrunk)) {
11780 			tcp->tcp_is_wnd_shrnk = B_FALSE;
11781 	}
11782 
11783 	/*
11784 	 * TCP gets a new ACK, update the notsack'ed list to delete those
11785 	 * blocks that are covered by this ACK.
11786 	 */
11787 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
11788 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
11789 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
11790 	}
11791 
11792 	/*
11793 	 * If we got an ACK after fast retransmit, check to see
11794 	 * if it is a partial ACK.  If it is not and the congestion
11795 	 * window was inflated to account for the other side's
11796 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
11797 	 */
11798 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
11799 		ASSERT(tcp->tcp_rexmit == B_FALSE);
11800 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
11801 			tcp->tcp_dupack_cnt = 0;
11802 			/*
11803 			 * Restore the orig tcp_cwnd_ssthresh after
11804 			 * fast retransmit phase.
11805 			 */
11806 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
11807 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
11808 			}
11809 			tcp->tcp_rexmit_max = seg_ack;
11810 			tcp->tcp_cwnd_cnt = 0;
11811 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
11812 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11813 
11814 			/*
11815 			 * Remove all notsack info to avoid confusion with
11816 			 * the next fast retrasnmit/recovery phase.
11817 			 */
11818 			if (tcp->tcp_snd_sack_ok &&
11819 			    tcp->tcp_notsack_list != NULL) {
11820 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list,
11821 				    tcp);
11822 			}
11823 		} else {
11824 			if (tcp->tcp_snd_sack_ok &&
11825 			    tcp->tcp_notsack_list != NULL) {
11826 				flags |= TH_NEED_SACK_REXMIT;
11827 				tcp->tcp_pipe -= mss;
11828 				if (tcp->tcp_pipe < 0)
11829 					tcp->tcp_pipe = 0;
11830 			} else {
11831 				/*
11832 				 * Hoe's algorithm:
11833 				 *
11834 				 * Retransmit the unack'ed segment and
11835 				 * restart fast recovery.  Note that we
11836 				 * need to scale back tcp_cwnd to the
11837 				 * original value when we started fast
11838 				 * recovery.  This is to prevent overly
11839 				 * aggressive behaviour in sending new
11840 				 * segments.
11841 				 */
11842 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
11843 				    tcps->tcps_dupack_fast_retransmit * mss;
11844 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
11845 				flags |= TH_REXMIT_NEEDED;
11846 			}
11847 		}
11848 	} else {
11849 		tcp->tcp_dupack_cnt = 0;
11850 		if (tcp->tcp_rexmit) {
11851 			/*
11852 			 * TCP is retranmitting.  If the ACK ack's all
11853 			 * outstanding data, update tcp_rexmit_max and
11854 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
11855 			 * to the correct value.
11856 			 *
11857 			 * Note that SEQ_LEQ() is used.  This is to avoid
11858 			 * unnecessary fast retransmit caused by dup ACKs
11859 			 * received when TCP does slow start retransmission
11860 			 * after a time out.  During this phase, TCP may
11861 			 * send out segments which are already received.
11862 			 * This causes dup ACKs to be sent back.
11863 			 */
11864 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
11865 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
11866 					tcp->tcp_rexmit_nxt = seg_ack;
11867 				}
11868 				if (seg_ack != tcp->tcp_rexmit_max) {
11869 					flags |= TH_XMIT_NEEDED;
11870 				}
11871 			} else {
11872 				tcp->tcp_rexmit = B_FALSE;
11873 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
11874 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
11875 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
11876 			}
11877 			tcp->tcp_ms_we_have_waited = 0;
11878 		}
11879 	}
11880 
11881 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
11882 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
11883 	tcp->tcp_suna = seg_ack;
11884 	if (tcp->tcp_zero_win_probe != 0) {
11885 		tcp->tcp_zero_win_probe = 0;
11886 		tcp->tcp_timer_backoff = 0;
11887 	}
11888 
11889 	/*
11890 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
11891 	 * Note that it cannot be the SYN being ack'ed.  The code flow
11892 	 * will not reach here.
11893 	 */
11894 	if (mp1 == NULL) {
11895 		goto fin_acked;
11896 	}
11897 
11898 	/*
11899 	 * Update the congestion window.
11900 	 *
11901 	 * If TCP is not ECN capable or TCP is ECN capable but the
11902 	 * congestion experience bit is not set, increase the tcp_cwnd as
11903 	 * usual.
11904 	 */
11905 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
11906 		cwnd = tcp->tcp_cwnd;
11907 		add = mss;
11908 
11909 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
11910 			/*
11911 			 * This is to prevent an increase of less than 1 MSS of
11912 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
11913 			 * may send out tinygrams in order to preserve mblk
11914 			 * boundaries.
11915 			 *
11916 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
11917 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
11918 			 * increased by 1 MSS for every RTTs.
11919 			 */
11920 			if (tcp->tcp_cwnd_cnt <= 0) {
11921 				tcp->tcp_cwnd_cnt = cwnd + add;
11922 			} else {
11923 				tcp->tcp_cwnd_cnt -= add;
11924 				add = 0;
11925 			}
11926 		}
11927 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
11928 	}
11929 
11930 	/* See if the latest urgent data has been acknowledged */
11931 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
11932 	    SEQ_GT(seg_ack, tcp->tcp_urg))
11933 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
11934 
11935 	/* Can we update the RTT estimates? */
11936 	if (tcp->tcp_snd_ts_ok) {
11937 		/* Ignore zero timestamp echo-reply. */
11938 		if (tcpopt.tcp_opt_ts_ecr != 0) {
11939 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
11940 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
11941 		}
11942 
11943 		/* If needed, restart the timer. */
11944 		if (tcp->tcp_set_timer == 1) {
11945 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11946 			tcp->tcp_set_timer = 0;
11947 		}
11948 		/*
11949 		 * Update tcp_csuna in case the other side stops sending
11950 		 * us timestamps.
11951 		 */
11952 		tcp->tcp_csuna = tcp->tcp_snxt;
11953 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
11954 		/*
11955 		 * An ACK sequence we haven't seen before, so get the RTT
11956 		 * and update the RTO. But first check if the timestamp is
11957 		 * valid to use.
11958 		 */
11959 		if ((mp1->b_next != NULL) &&
11960 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
11961 			tcp_set_rto(tcp, (int32_t)LBOLT_FASTPATH -
11962 			    (int32_t)(intptr_t)mp1->b_prev);
11963 		else
11964 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
11965 
11966 		/* Remeber the last sequence to be ACKed */
11967 		tcp->tcp_csuna = seg_ack;
11968 		if (tcp->tcp_set_timer == 1) {
11969 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
11970 			tcp->tcp_set_timer = 0;
11971 		}
11972 	} else {
11973 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
11974 	}
11975 
11976 	/* Eat acknowledged bytes off the xmit queue. */
11977 	for (;;) {
11978 		mblk_t	*mp2;
11979 		uchar_t	*wptr;
11980 
11981 		wptr = mp1->b_wptr;
11982 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
11983 		bytes_acked -= (int)(wptr - mp1->b_rptr);
11984 		if (bytes_acked < 0) {
11985 			mp1->b_rptr = wptr + bytes_acked;
11986 			/*
11987 			 * Set a new timestamp if all the bytes timed by the
11988 			 * old timestamp have been ack'ed.
11989 			 */
11990 			if (SEQ_GT(seg_ack,
11991 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
11992 				mp1->b_prev =
11993 				    (mblk_t *)(uintptr_t)LBOLT_FASTPATH;
11994 				mp1->b_next = NULL;
11995 			}
11996 			break;
11997 		}
11998 		mp1->b_next = NULL;
11999 		mp1->b_prev = NULL;
12000 		mp2 = mp1;
12001 		mp1 = mp1->b_cont;
12002 
12003 		/*
12004 		 * This notification is required for some zero-copy
12005 		 * clients to maintain a copy semantic. After the data
12006 		 * is ack'ed, client is safe to modify or reuse the buffer.
12007 		 */
12008 		if (tcp->tcp_snd_zcopy_aware &&
12009 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
12010 			tcp_zcopy_notify(tcp);
12011 		freeb(mp2);
12012 		if (bytes_acked == 0) {
12013 			if (mp1 == NULL) {
12014 				/* Everything is ack'ed, clear the tail. */
12015 				tcp->tcp_xmit_tail = NULL;
12016 				/*
12017 				 * Cancel the timer unless we are still
12018 				 * waiting for an ACK for the FIN packet.
12019 				 */
12020 				if (tcp->tcp_timer_tid != 0 &&
12021 				    tcp->tcp_snxt == tcp->tcp_suna) {
12022 					(void) TCP_TIMER_CANCEL(tcp,
12023 					    tcp->tcp_timer_tid);
12024 					tcp->tcp_timer_tid = 0;
12025 				}
12026 				goto pre_swnd_update;
12027 			}
12028 			if (mp2 != tcp->tcp_xmit_tail)
12029 				break;
12030 			tcp->tcp_xmit_tail = mp1;
12031 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12032 			    (uintptr_t)INT_MAX);
12033 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
12034 			    mp1->b_rptr);
12035 			break;
12036 		}
12037 		if (mp1 == NULL) {
12038 			/*
12039 			 * More was acked but there is nothing more
12040 			 * outstanding.  This means that the FIN was
12041 			 * just acked or that we're talking to a clown.
12042 			 */
12043 fin_acked:
12044 			ASSERT(tcp->tcp_fin_sent);
12045 			tcp->tcp_xmit_tail = NULL;
12046 			if (tcp->tcp_fin_sent) {
12047 				/* FIN was acked - making progress */
12048 				if (!tcp->tcp_fin_acked)
12049 					tcp->tcp_ip_forward_progress = B_TRUE;
12050 				tcp->tcp_fin_acked = B_TRUE;
12051 				if (tcp->tcp_linger_tid != 0 &&
12052 				    TCP_TIMER_CANCEL(tcp,
12053 				    tcp->tcp_linger_tid) >= 0) {
12054 					tcp_stop_lingering(tcp);
12055 					freemsg(mp);
12056 					mp = NULL;
12057 				}
12058 			} else {
12059 				/*
12060 				 * We should never get here because
12061 				 * we have already checked that the
12062 				 * number of bytes ack'ed should be
12063 				 * smaller than or equal to what we
12064 				 * have sent so far (it is the
12065 				 * acceptability check of the ACK).
12066 				 * We can only get here if the send
12067 				 * queue is corrupted.
12068 				 *
12069 				 * Terminate the connection and
12070 				 * panic the system.  It is better
12071 				 * for us to panic instead of
12072 				 * continuing to avoid other disaster.
12073 				 */
12074 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
12075 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
12076 				panic("Memory corruption "
12077 				    "detected for connection %s.",
12078 				    tcp_display(tcp, NULL,
12079 				    DISP_ADDR_AND_PORT));
12080 				/*NOTREACHED*/
12081 			}
12082 			goto pre_swnd_update;
12083 		}
12084 		ASSERT(mp2 != tcp->tcp_xmit_tail);
12085 	}
12086 	if (tcp->tcp_unsent) {
12087 		flags |= TH_XMIT_NEEDED;
12088 	}
12089 pre_swnd_update:
12090 	tcp->tcp_xmit_head = mp1;
12091 swnd_update:
12092 	/*
12093 	 * The following check is different from most other implementations.
12094 	 * For bi-directional transfer, when segments are dropped, the
12095 	 * "normal" check will not accept a window update in those
12096 	 * retransmitted segemnts.  Failing to do that, TCP may send out
12097 	 * segments which are outside receiver's window.  As TCP accepts
12098 	 * the ack in those retransmitted segments, if the window update in
12099 	 * the same segment is not accepted, TCP will incorrectly calculates
12100 	 * that it can send more segments.  This can create a deadlock
12101 	 * with the receiver if its window becomes zero.
12102 	 */
12103 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
12104 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
12105 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
12106 		/*
12107 		 * The criteria for update is:
12108 		 *
12109 		 * 1. the segment acknowledges some data.  Or
12110 		 * 2. the segment is new, i.e. it has a higher seq num. Or
12111 		 * 3. the segment is not old and the advertised window is
12112 		 * larger than the previous advertised window.
12113 		 */
12114 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
12115 			flags |= TH_XMIT_NEEDED;
12116 		tcp->tcp_swnd = new_swnd;
12117 		if (new_swnd > tcp->tcp_max_swnd)
12118 			tcp->tcp_max_swnd = new_swnd;
12119 		tcp->tcp_swl1 = seg_seq;
12120 		tcp->tcp_swl2 = seg_ack;
12121 	}
12122 est:
12123 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
12124 
12125 		switch (tcp->tcp_state) {
12126 		case TCPS_FIN_WAIT_1:
12127 			if (tcp->tcp_fin_acked) {
12128 				tcp->tcp_state = TCPS_FIN_WAIT_2;
12129 				/*
12130 				 * We implement the non-standard BSD/SunOS
12131 				 * FIN_WAIT_2 flushing algorithm.
12132 				 * If there is no user attached to this
12133 				 * TCP endpoint, then this TCP struct
12134 				 * could hang around forever in FIN_WAIT_2
12135 				 * state if the peer forgets to send us
12136 				 * a FIN.  To prevent this, we wait only
12137 				 * 2*MSL (a convenient time value) for
12138 				 * the FIN to arrive.  If it doesn't show up,
12139 				 * we flush the TCP endpoint.  This algorithm,
12140 				 * though a violation of RFC-793, has worked
12141 				 * for over 10 years in BSD systems.
12142 				 * Note: SunOS 4.x waits 675 seconds before
12143 				 * flushing the FIN_WAIT_2 connection.
12144 				 */
12145 				TCP_TIMER_RESTART(tcp,
12146 				    tcps->tcps_fin_wait_2_flush_interval);
12147 			}
12148 			break;
12149 		case TCPS_FIN_WAIT_2:
12150 			break;	/* Shutdown hook? */
12151 		case TCPS_LAST_ACK:
12152 			freemsg(mp);
12153 			if (tcp->tcp_fin_acked) {
12154 				(void) tcp_clean_death(tcp, 0, 19);
12155 				return;
12156 			}
12157 			goto xmit_check;
12158 		case TCPS_CLOSING:
12159 			if (tcp->tcp_fin_acked)
12160 				SET_TIME_WAIT(tcps, tcp, connp);
12161 			/*FALLTHRU*/
12162 		case TCPS_CLOSE_WAIT:
12163 			freemsg(mp);
12164 			goto xmit_check;
12165 		default:
12166 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
12167 			break;
12168 		}
12169 	}
12170 	if (flags & TH_FIN) {
12171 		/* Make sure we ack the fin */
12172 		flags |= TH_ACK_NEEDED;
12173 		if (!tcp->tcp_fin_rcvd) {
12174 			tcp->tcp_fin_rcvd = B_TRUE;
12175 			tcp->tcp_rnxt++;
12176 			tcpha = tcp->tcp_tcpha;
12177 			tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12178 
12179 			/*
12180 			 * Generate the ordrel_ind at the end unless we
12181 			 * are an eager guy.
12182 			 * In the eager case tcp_rsrv will do this when run
12183 			 * after tcp_accept is done.
12184 			 */
12185 			if (tcp->tcp_listener == NULL &&
12186 			    !TCP_IS_DETACHED(tcp) && !tcp->tcp_hard_binding)
12187 				flags |= TH_ORDREL_NEEDED;
12188 			switch (tcp->tcp_state) {
12189 			case TCPS_SYN_RCVD:
12190 			case TCPS_ESTABLISHED:
12191 				tcp->tcp_state = TCPS_CLOSE_WAIT;
12192 				/* Keepalive? */
12193 				break;
12194 			case TCPS_FIN_WAIT_1:
12195 				if (!tcp->tcp_fin_acked) {
12196 					tcp->tcp_state = TCPS_CLOSING;
12197 					break;
12198 				}
12199 				/* FALLTHRU */
12200 			case TCPS_FIN_WAIT_2:
12201 				SET_TIME_WAIT(tcps, tcp, connp);
12202 				if (seg_len) {
12203 					/*
12204 					 * implies data piggybacked on FIN.
12205 					 * break to handle data.
12206 					 */
12207 					break;
12208 				}
12209 				freemsg(mp);
12210 				goto ack_check;
12211 			}
12212 		}
12213 	}
12214 	if (mp == NULL)
12215 		goto xmit_check;
12216 	if (seg_len == 0) {
12217 		freemsg(mp);
12218 		goto xmit_check;
12219 	}
12220 	if (mp->b_rptr == mp->b_wptr) {
12221 		/*
12222 		 * The header has been consumed, so we remove the
12223 		 * zero-length mblk here.
12224 		 */
12225 		mp1 = mp;
12226 		mp = mp->b_cont;
12227 		freeb(mp1);
12228 	}
12229 update_ack:
12230 	tcpha = tcp->tcp_tcpha;
12231 	tcp->tcp_rack_cnt++;
12232 	{
12233 		uint32_t cur_max;
12234 
12235 		cur_max = tcp->tcp_rack_cur_max;
12236 		if (tcp->tcp_rack_cnt >= cur_max) {
12237 			/*
12238 			 * We have more unacked data than we should - send
12239 			 * an ACK now.
12240 			 */
12241 			flags |= TH_ACK_NEEDED;
12242 			cur_max++;
12243 			if (cur_max > tcp->tcp_rack_abs_max)
12244 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
12245 			else
12246 				tcp->tcp_rack_cur_max = cur_max;
12247 		} else if (TCP_IS_DETACHED(tcp)) {
12248 			/* We don't have an ACK timer for detached TCP. */
12249 			flags |= TH_ACK_NEEDED;
12250 		} else if (seg_len < mss) {
12251 			/*
12252 			 * If we get a segment that is less than an mss, and we
12253 			 * already have unacknowledged data, and the amount
12254 			 * unacknowledged is not a multiple of mss, then we
12255 			 * better generate an ACK now.  Otherwise, this may be
12256 			 * the tail piece of a transaction, and we would rather
12257 			 * wait for the response.
12258 			 */
12259 			uint32_t udif;
12260 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
12261 			    (uintptr_t)INT_MAX);
12262 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
12263 			if (udif && (udif % mss))
12264 				flags |= TH_ACK_NEEDED;
12265 			else
12266 				flags |= TH_ACK_TIMER_NEEDED;
12267 		} else {
12268 			/* Start delayed ack timer */
12269 			flags |= TH_ACK_TIMER_NEEDED;
12270 		}
12271 	}
12272 	tcp->tcp_rnxt += seg_len;
12273 	tcpha->tha_ack = htonl(tcp->tcp_rnxt);
12274 
12275 	if (mp == NULL)
12276 		goto xmit_check;
12277 
12278 	/* Update SACK list */
12279 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
12280 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
12281 		    &(tcp->tcp_num_sack_blk));
12282 	}
12283 
12284 	if (tcp->tcp_urp_mp) {
12285 		tcp->tcp_urp_mp->b_cont = mp;
12286 		mp = tcp->tcp_urp_mp;
12287 		tcp->tcp_urp_mp = NULL;
12288 		/* Ready for a new signal. */
12289 		tcp->tcp_urp_last_valid = B_FALSE;
12290 #ifdef DEBUG
12291 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12292 		    "tcp_rput: sending exdata_ind %s",
12293 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12294 #endif /* DEBUG */
12295 	}
12296 
12297 	/*
12298 	 * Check for ancillary data changes compared to last segment.
12299 	 */
12300 	if (connp->conn_recv_ancillary.crb_all != 0) {
12301 		mp = tcp_input_add_ancillary(tcp, mp, &ipp, ira);
12302 		if (mp == NULL)
12303 			return;
12304 	}
12305 
12306 	if (tcp->tcp_listener != NULL || tcp->tcp_hard_binding) {
12307 		/*
12308 		 * Side queue inbound data until the accept happens.
12309 		 * tcp_accept/tcp_rput drains this when the accept happens.
12310 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
12311 		 * T_EXDATA_IND) it is queued on b_next.
12312 		 * XXX Make urgent data use this. Requires:
12313 		 *	Removing tcp_listener check for TH_URG
12314 		 *	Making M_PCPROTO and MARK messages skip the eager case
12315 		 */
12316 
12317 		if (tcp->tcp_kssl_pending) {
12318 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
12319 			    mblk_t *, mp);
12320 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12321 		} else {
12322 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12323 		}
12324 	} else if (IPCL_IS_NONSTR(connp)) {
12325 		/*
12326 		 * Non-STREAMS socket
12327 		 *
12328 		 * Note that no KSSL processing is done here, because
12329 		 * KSSL is not supported for non-STREAMS sockets.
12330 		 */
12331 		boolean_t push = flags & (TH_PUSH|TH_FIN);
12332 		int error;
12333 
12334 		if ((*connp->conn_upcalls->su_recv)(
12335 		    connp->conn_upper_handle,
12336 		    mp, seg_len, 0, &error, &push) <= 0) {
12337 			/*
12338 			 * We should never be in middle of a
12339 			 * fallback, the squeue guarantees that.
12340 			 */
12341 			ASSERT(error != EOPNOTSUPP);
12342 			if (error == ENOSPC)
12343 				tcp->tcp_rwnd -= seg_len;
12344 		} else if (push) {
12345 			/* PUSH bit set and sockfs is not flow controlled */
12346 			flags |= tcp_rwnd_reopen(tcp);
12347 		}
12348 	} else {
12349 		/* STREAMS socket */
12350 		if (mp->b_datap->db_type != M_DATA ||
12351 		    (flags & TH_MARKNEXT_NEEDED)) {
12352 			if (tcp->tcp_rcv_list != NULL) {
12353 				flags |= tcp_rcv_drain(tcp);
12354 			}
12355 			ASSERT(tcp->tcp_rcv_list == NULL ||
12356 			    tcp->tcp_fused_sigurg);
12357 
12358 			if (flags & TH_MARKNEXT_NEEDED) {
12359 #ifdef DEBUG
12360 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12361 				    "tcp_rput: sending MSGMARKNEXT %s",
12362 				    tcp_display(tcp, NULL,
12363 				    DISP_PORT_ONLY));
12364 #endif /* DEBUG */
12365 				mp->b_flag |= MSGMARKNEXT;
12366 				flags &= ~TH_MARKNEXT_NEEDED;
12367 			}
12368 
12369 			/* Does this need SSL processing first? */
12370 			if ((tcp->tcp_kssl_ctx != NULL) &&
12371 			    (DB_TYPE(mp) == M_DATA)) {
12372 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
12373 				    mblk_t *, mp);
12374 				tcp_kssl_input(tcp, mp, ira->ira_cred);
12375 			} else {
12376 				if (is_system_labeled())
12377 					tcp_setcred_data(mp, ira);
12378 
12379 				putnext(connp->conn_rq, mp);
12380 				if (!canputnext(connp->conn_rq))
12381 					tcp->tcp_rwnd -= seg_len;
12382 			}
12383 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
12384 		    (DB_TYPE(mp) == M_DATA)) {
12385 			/* Does this need SSL processing first? */
12386 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
12387 			tcp_kssl_input(tcp, mp, ira->ira_cred);
12388 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
12389 		    tcp->tcp_rcv_cnt + seg_len >= connp->conn_rcvbuf >> 3) {
12390 			if (tcp->tcp_rcv_list != NULL) {
12391 				/*
12392 				 * Enqueue the new segment first and then
12393 				 * call tcp_rcv_drain() to send all data
12394 				 * up.  The other way to do this is to
12395 				 * send all queued data up and then call
12396 				 * putnext() to send the new segment up.
12397 				 * This way can remove the else part later
12398 				 * on.
12399 				 *
12400 				 * We don't do this to avoid one more call to
12401 				 * canputnext() as tcp_rcv_drain() needs to
12402 				 * call canputnext().
12403 				 */
12404 				tcp_rcv_enqueue(tcp, mp, seg_len,
12405 				    ira->ira_cred);
12406 				flags |= tcp_rcv_drain(tcp);
12407 			} else {
12408 				if (is_system_labeled())
12409 					tcp_setcred_data(mp, ira);
12410 
12411 				putnext(connp->conn_rq, mp);
12412 				if (!canputnext(connp->conn_rq))
12413 					tcp->tcp_rwnd -= seg_len;
12414 			}
12415 		} else {
12416 			/*
12417 			 * Enqueue all packets when processing an mblk
12418 			 * from the co queue and also enqueue normal packets.
12419 			 */
12420 			tcp_rcv_enqueue(tcp, mp, seg_len, ira->ira_cred);
12421 		}
12422 		/*
12423 		 * Make sure the timer is running if we have data waiting
12424 		 * for a push bit. This provides resiliency against
12425 		 * implementations that do not correctly generate push bits.
12426 		 */
12427 		if (tcp->tcp_rcv_list != NULL && tcp->tcp_push_tid == 0) {
12428 			/*
12429 			 * The connection may be closed at this point, so don't
12430 			 * do anything for a detached tcp.
12431 			 */
12432 			if (!TCP_IS_DETACHED(tcp))
12433 				tcp->tcp_push_tid = TCP_TIMER(tcp,
12434 				    tcp_push_timer,
12435 				    MSEC_TO_TICK(
12436 				    tcps->tcps_push_timer_interval));
12437 		}
12438 	}
12439 
12440 xmit_check:
12441 	/* Is there anything left to do? */
12442 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12443 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
12444 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
12445 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12446 		goto done;
12447 
12448 	/* Any transmit work to do and a non-zero window? */
12449 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
12450 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
12451 		if (flags & TH_REXMIT_NEEDED) {
12452 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
12453 
12454 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
12455 			if (snd_size > mss)
12456 				snd_size = mss;
12457 			if (snd_size > tcp->tcp_swnd)
12458 				snd_size = tcp->tcp_swnd;
12459 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
12460 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
12461 			    B_TRUE);
12462 
12463 			if (mp1 != NULL) {
12464 				tcp->tcp_xmit_head->b_prev =
12465 				    (mblk_t *)LBOLT_FASTPATH;
12466 				tcp->tcp_csuna = tcp->tcp_snxt;
12467 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12468 				UPDATE_MIB(&tcps->tcps_mib,
12469 				    tcpRetransBytes, snd_size);
12470 				tcp_send_data(tcp, mp1);
12471 			}
12472 		}
12473 		if (flags & TH_NEED_SACK_REXMIT) {
12474 			tcp_sack_rxmit(tcp, &flags);
12475 		}
12476 		/*
12477 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
12478 		 * out new segment.  Note that tcp_rexmit should not be
12479 		 * set, otherwise TH_LIMIT_XMIT should not be set.
12480 		 */
12481 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
12482 			if (!tcp->tcp_rexmit) {
12483 				tcp_wput_data(tcp, NULL, B_FALSE);
12484 			} else {
12485 				tcp_ss_rexmit(tcp);
12486 			}
12487 		}
12488 		/*
12489 		 * Adjust tcp_cwnd back to normal value after sending
12490 		 * new data segments.
12491 		 */
12492 		if (flags & TH_LIMIT_XMIT) {
12493 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
12494 			/*
12495 			 * This will restart the timer.  Restarting the
12496 			 * timer is used to avoid a timeout before the
12497 			 * limited transmitted segment's ACK gets back.
12498 			 */
12499 			if (tcp->tcp_xmit_head != NULL)
12500 				tcp->tcp_xmit_head->b_prev =
12501 				    (mblk_t *)LBOLT_FASTPATH;
12502 		}
12503 
12504 		/* Anything more to do? */
12505 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
12506 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
12507 			goto done;
12508 	}
12509 ack_check:
12510 	if (flags & TH_SEND_URP_MARK) {
12511 		ASSERT(tcp->tcp_urp_mark_mp);
12512 		ASSERT(!IPCL_IS_NONSTR(connp));
12513 		/*
12514 		 * Send up any queued data and then send the mark message
12515 		 */
12516 		if (tcp->tcp_rcv_list != NULL) {
12517 			flags |= tcp_rcv_drain(tcp);
12518 
12519 		}
12520 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12521 		mp1 = tcp->tcp_urp_mark_mp;
12522 		tcp->tcp_urp_mark_mp = NULL;
12523 		if (is_system_labeled())
12524 			tcp_setcred_data(mp1, ira);
12525 
12526 		putnext(connp->conn_rq, mp1);
12527 #ifdef DEBUG
12528 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
12529 		    "tcp_rput: sending zero-length %s %s",
12530 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
12531 		    "MSGNOTMARKNEXT"),
12532 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
12533 #endif /* DEBUG */
12534 		flags &= ~TH_SEND_URP_MARK;
12535 	}
12536 	if (flags & TH_ACK_NEEDED) {
12537 		/*
12538 		 * Time to send an ack for some reason.
12539 		 */
12540 		mp1 = tcp_ack_mp(tcp);
12541 
12542 		if (mp1 != NULL) {
12543 			tcp_send_data(tcp, mp1);
12544 			BUMP_LOCAL(tcp->tcp_obsegs);
12545 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
12546 		}
12547 		if (tcp->tcp_ack_tid != 0) {
12548 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
12549 			tcp->tcp_ack_tid = 0;
12550 		}
12551 	}
12552 	if (flags & TH_ACK_TIMER_NEEDED) {
12553 		/*
12554 		 * Arrange for deferred ACK or push wait timeout.
12555 		 * Start timer if it is not already running.
12556 		 */
12557 		if (tcp->tcp_ack_tid == 0) {
12558 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
12559 			    MSEC_TO_TICK(tcp->tcp_localnet ?
12560 			    (clock_t)tcps->tcps_local_dack_interval :
12561 			    (clock_t)tcps->tcps_deferred_ack_interval));
12562 		}
12563 	}
12564 	if (flags & TH_ORDREL_NEEDED) {
12565 		/*
12566 		 * Send up the ordrel_ind unless we are an eager guy.
12567 		 * In the eager case tcp_rsrv will do this when run
12568 		 * after tcp_accept is done.
12569 		 */
12570 		ASSERT(tcp->tcp_listener == NULL);
12571 		ASSERT(!tcp->tcp_detached);
12572 
12573 		if (IPCL_IS_NONSTR(connp)) {
12574 			ASSERT(tcp->tcp_ordrel_mp == NULL);
12575 			tcp->tcp_ordrel_done = B_TRUE;
12576 			(*connp->conn_upcalls->su_opctl)
12577 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
12578 			goto done;
12579 		}
12580 
12581 		if (tcp->tcp_rcv_list != NULL) {
12582 			/*
12583 			 * Push any mblk(s) enqueued from co processing.
12584 			 */
12585 			flags |= tcp_rcv_drain(tcp);
12586 		}
12587 		ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
12588 
12589 		mp1 = tcp->tcp_ordrel_mp;
12590 		tcp->tcp_ordrel_mp = NULL;
12591 		tcp->tcp_ordrel_done = B_TRUE;
12592 		putnext(connp->conn_rq, mp1);
12593 	}
12594 done:
12595 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
12596 }
12597 
12598 /*
12599  * This routine adjusts next-to-send sequence number variables, in the
12600  * case where the reciever has shrunk it's window.
12601  */
12602 static void
12603 tcp_update_xmit_tail(tcp_t *tcp, uint32_t snxt)
12604 {
12605 	mblk_t *xmit_tail;
12606 	int32_t offset;
12607 
12608 	tcp->tcp_snxt = snxt;
12609 
12610 	/* Get the mblk, and the offset in it, as per the shrunk window */
12611 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
12612 	ASSERT(xmit_tail != NULL);
12613 	tcp->tcp_xmit_tail = xmit_tail;
12614 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr -
12615 	    xmit_tail->b_rptr - offset;
12616 }
12617 
12618 /*
12619  * This function does PAWS protection check. Returns B_TRUE if the
12620  * segment passes the PAWS test, else returns B_FALSE.
12621  */
12622 boolean_t
12623 tcp_paws_check(tcp_t *tcp, tcpha_t *tcpha, tcp_opt_t *tcpoptp)
12624 {
12625 	uint8_t	flags;
12626 	int	options;
12627 	uint8_t *up;
12628 	conn_t	*connp = tcp->tcp_connp;
12629 
12630 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
12631 	/*
12632 	 * If timestamp option is aligned nicely, get values inline,
12633 	 * otherwise call general routine to parse.  Only do that
12634 	 * if timestamp is the only option.
12635 	 */
12636 	if (TCP_HDR_LENGTH(tcpha) == (uint32_t)TCP_MIN_HEADER_LENGTH +
12637 	    TCPOPT_REAL_TS_LEN &&
12638 	    OK_32PTR((up = ((uint8_t *)tcpha) +
12639 	    TCP_MIN_HEADER_LENGTH)) &&
12640 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
12641 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
12642 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
12643 
12644 		options = TCP_OPT_TSTAMP_PRESENT;
12645 	} else {
12646 		if (tcp->tcp_snd_sack_ok) {
12647 			tcpoptp->tcp = tcp;
12648 		} else {
12649 			tcpoptp->tcp = NULL;
12650 		}
12651 		options = tcp_parse_options(tcpha, tcpoptp);
12652 	}
12653 
12654 	if (options & TCP_OPT_TSTAMP_PRESENT) {
12655 		/*
12656 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
12657 		 * regardless of the timestamp, page 18 RFC 1323.bis.
12658 		 */
12659 		if ((flags & TH_RST) == 0 &&
12660 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
12661 		    tcp->tcp_ts_recent)) {
12662 			if (TSTMP_LT(LBOLT_FASTPATH64,
12663 			    tcp->tcp_last_rcv_lbolt + PAWS_TIMEOUT)) {
12664 				/* This segment is not acceptable. */
12665 				return (B_FALSE);
12666 			} else {
12667 				/*
12668 				 * Connection has been idle for
12669 				 * too long.  Reset the timestamp
12670 				 * and assume the segment is valid.
12671 				 */
12672 				tcp->tcp_ts_recent =
12673 				    tcpoptp->tcp_opt_ts_val;
12674 			}
12675 		}
12676 	} else {
12677 		/*
12678 		 * If we don't get a timestamp on every packet, we
12679 		 * figure we can't really trust 'em, so we stop sending
12680 		 * and parsing them.
12681 		 */
12682 		tcp->tcp_snd_ts_ok = B_FALSE;
12683 
12684 		connp->conn_ht_iphc_len -= TCPOPT_REAL_TS_LEN;
12685 		connp->conn_ht_ulp_len -= TCPOPT_REAL_TS_LEN;
12686 		tcp->tcp_tcpha->tha_offset_and_reserved -= (3 << 4);
12687 		/*
12688 		 * Adjust the tcp_mss and tcp_cwnd accordingly. We avoid
12689 		 * doing a slow start here so as to not to lose on the
12690 		 * transfer rate built up so far.
12691 		 */
12692 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN);
12693 		if (tcp->tcp_snd_sack_ok) {
12694 			ASSERT(tcp->tcp_sack_info != NULL);
12695 			tcp->tcp_max_sack_blk = 4;
12696 		}
12697 	}
12698 	return (B_TRUE);
12699 }
12700 
12701 /*
12702  * Attach ancillary data to a received TCP segments for the
12703  * ancillary pieces requested by the application that are
12704  * different than they were in the previous data segment.
12705  *
12706  * Save the "current" values once memory allocation is ok so that
12707  * when memory allocation fails we can just wait for the next data segment.
12708  */
12709 static mblk_t *
12710 tcp_input_add_ancillary(tcp_t *tcp, mblk_t *mp, ip_pkt_t *ipp,
12711     ip_recv_attr_t *ira)
12712 {
12713 	struct T_optdata_ind *todi;
12714 	int optlen;
12715 	uchar_t *optptr;
12716 	struct T_opthdr *toh;
12717 	crb_t addflag;	/* Which pieces to add */
12718 	mblk_t *mp1;
12719 	conn_t	*connp = tcp->tcp_connp;
12720 
12721 	optlen = 0;
12722 	addflag.crb_all = 0;
12723 	/* If app asked for pktinfo and the index has changed ... */
12724 	if (connp->conn_recv_ancillary.crb_ip_recvpktinfo &&
12725 	    ira->ira_ruifindex != tcp->tcp_recvifindex) {
12726 		optlen += sizeof (struct T_opthdr) +
12727 		    sizeof (struct in6_pktinfo);
12728 		addflag.crb_ip_recvpktinfo = 1;
12729 	}
12730 	/* If app asked for hoplimit and it has changed ... */
12731 	if (connp->conn_recv_ancillary.crb_ipv6_recvhoplimit &&
12732 	    ipp->ipp_hoplimit != tcp->tcp_recvhops) {
12733 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12734 		addflag.crb_ipv6_recvhoplimit = 1;
12735 	}
12736 	/* If app asked for tclass and it has changed ... */
12737 	if (connp->conn_recv_ancillary.crb_ipv6_recvtclass &&
12738 	    ipp->ipp_tclass != tcp->tcp_recvtclass) {
12739 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
12740 		addflag.crb_ipv6_recvtclass = 1;
12741 	}
12742 	/*
12743 	 * If app asked for hopbyhop headers and it has changed ...
12744 	 * For security labels, note that (1) security labels can't change on
12745 	 * a connected socket at all, (2) we're connected to at most one peer,
12746 	 * (3) if anything changes, then it must be some other extra option.
12747 	 */
12748 	if (connp->conn_recv_ancillary.crb_ipv6_recvhopopts &&
12749 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
12750 	    (ipp->ipp_fields & IPPF_HOPOPTS),
12751 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
12752 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen;
12753 		addflag.crb_ipv6_recvhopopts = 1;
12754 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
12755 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
12756 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
12757 			return (mp);
12758 	}
12759 	/* If app asked for dst headers before routing headers ... */
12760 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdrdstopts &&
12761 	    ip_cmpbuf(tcp->tcp_rthdrdstopts, tcp->tcp_rthdrdstoptslen,
12762 	    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12763 	    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen)) {
12764 		optlen += sizeof (struct T_opthdr) +
12765 		    ipp->ipp_rthdrdstoptslen;
12766 		addflag.crb_ipv6_recvrthdrdstopts = 1;
12767 		if (!ip_allocbuf((void **)&tcp->tcp_rthdrdstopts,
12768 		    &tcp->tcp_rthdrdstoptslen,
12769 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12770 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen))
12771 			return (mp);
12772 	}
12773 	/* If app asked for routing headers and it has changed ... */
12774 	if (connp->conn_recv_ancillary.crb_ipv6_recvrthdr &&
12775 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
12776 	    (ipp->ipp_fields & IPPF_RTHDR),
12777 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
12778 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
12779 		addflag.crb_ipv6_recvrthdr = 1;
12780 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
12781 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
12782 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
12783 			return (mp);
12784 	}
12785 	/* If app asked for dest headers and it has changed ... */
12786 	if ((connp->conn_recv_ancillary.crb_ipv6_recvdstopts ||
12787 	    connp->conn_recv_ancillary.crb_old_ipv6_recvdstopts) &&
12788 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
12789 	    (ipp->ipp_fields & IPPF_DSTOPTS),
12790 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
12791 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
12792 		addflag.crb_ipv6_recvdstopts = 1;
12793 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
12794 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
12795 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
12796 			return (mp);
12797 	}
12798 
12799 	if (optlen == 0) {
12800 		/* Nothing to add */
12801 		return (mp);
12802 	}
12803 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
12804 	if (mp1 == NULL) {
12805 		/*
12806 		 * Defer sending ancillary data until the next TCP segment
12807 		 * arrives.
12808 		 */
12809 		return (mp);
12810 	}
12811 	mp1->b_cont = mp;
12812 	mp = mp1;
12813 	mp->b_wptr += sizeof (*todi) + optlen;
12814 	mp->b_datap->db_type = M_PROTO;
12815 	todi = (struct T_optdata_ind *)mp->b_rptr;
12816 	todi->PRIM_type = T_OPTDATA_IND;
12817 	todi->DATA_flag = 1;	/* MORE data */
12818 	todi->OPT_length = optlen;
12819 	todi->OPT_offset = sizeof (*todi);
12820 	optptr = (uchar_t *)&todi[1];
12821 	/*
12822 	 * If app asked for pktinfo and the index has changed ...
12823 	 * Note that the local address never changes for the connection.
12824 	 */
12825 	if (addflag.crb_ip_recvpktinfo) {
12826 		struct in6_pktinfo *pkti;
12827 		uint_t ifindex;
12828 
12829 		ifindex = ira->ira_ruifindex;
12830 		toh = (struct T_opthdr *)optptr;
12831 		toh->level = IPPROTO_IPV6;
12832 		toh->name = IPV6_PKTINFO;
12833 		toh->len = sizeof (*toh) + sizeof (*pkti);
12834 		toh->status = 0;
12835 		optptr += sizeof (*toh);
12836 		pkti = (struct in6_pktinfo *)optptr;
12837 		pkti->ipi6_addr = connp->conn_laddr_v6;
12838 		pkti->ipi6_ifindex = ifindex;
12839 		optptr += sizeof (*pkti);
12840 		ASSERT(OK_32PTR(optptr));
12841 		/* Save as "last" value */
12842 		tcp->tcp_recvifindex = ifindex;
12843 	}
12844 	/* If app asked for hoplimit and it has changed ... */
12845 	if (addflag.crb_ipv6_recvhoplimit) {
12846 		toh = (struct T_opthdr *)optptr;
12847 		toh->level = IPPROTO_IPV6;
12848 		toh->name = IPV6_HOPLIMIT;
12849 		toh->len = sizeof (*toh) + sizeof (uint_t);
12850 		toh->status = 0;
12851 		optptr += sizeof (*toh);
12852 		*(uint_t *)optptr = ipp->ipp_hoplimit;
12853 		optptr += sizeof (uint_t);
12854 		ASSERT(OK_32PTR(optptr));
12855 		/* Save as "last" value */
12856 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
12857 	}
12858 	/* If app asked for tclass and it has changed ... */
12859 	if (addflag.crb_ipv6_recvtclass) {
12860 		toh = (struct T_opthdr *)optptr;
12861 		toh->level = IPPROTO_IPV6;
12862 		toh->name = IPV6_TCLASS;
12863 		toh->len = sizeof (*toh) + sizeof (uint_t);
12864 		toh->status = 0;
12865 		optptr += sizeof (*toh);
12866 		*(uint_t *)optptr = ipp->ipp_tclass;
12867 		optptr += sizeof (uint_t);
12868 		ASSERT(OK_32PTR(optptr));
12869 		/* Save as "last" value */
12870 		tcp->tcp_recvtclass = ipp->ipp_tclass;
12871 	}
12872 	if (addflag.crb_ipv6_recvhopopts) {
12873 		toh = (struct T_opthdr *)optptr;
12874 		toh->level = IPPROTO_IPV6;
12875 		toh->name = IPV6_HOPOPTS;
12876 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen;
12877 		toh->status = 0;
12878 		optptr += sizeof (*toh);
12879 		bcopy((uchar_t *)ipp->ipp_hopopts, optptr, ipp->ipp_hopoptslen);
12880 		optptr += ipp->ipp_hopoptslen;
12881 		ASSERT(OK_32PTR(optptr));
12882 		/* Save as last value */
12883 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
12884 		    (ipp->ipp_fields & IPPF_HOPOPTS),
12885 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
12886 	}
12887 	if (addflag.crb_ipv6_recvrthdrdstopts) {
12888 		toh = (struct T_opthdr *)optptr;
12889 		toh->level = IPPROTO_IPV6;
12890 		toh->name = IPV6_RTHDRDSTOPTS;
12891 		toh->len = sizeof (*toh) + ipp->ipp_rthdrdstoptslen;
12892 		toh->status = 0;
12893 		optptr += sizeof (*toh);
12894 		bcopy(ipp->ipp_rthdrdstopts, optptr, ipp->ipp_rthdrdstoptslen);
12895 		optptr += ipp->ipp_rthdrdstoptslen;
12896 		ASSERT(OK_32PTR(optptr));
12897 		/* Save as last value */
12898 		ip_savebuf((void **)&tcp->tcp_rthdrdstopts,
12899 		    &tcp->tcp_rthdrdstoptslen,
12900 		    (ipp->ipp_fields & IPPF_RTHDRDSTOPTS),
12901 		    ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
12902 	}
12903 	if (addflag.crb_ipv6_recvrthdr) {
12904 		toh = (struct T_opthdr *)optptr;
12905 		toh->level = IPPROTO_IPV6;
12906 		toh->name = IPV6_RTHDR;
12907 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
12908 		toh->status = 0;
12909 		optptr += sizeof (*toh);
12910 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
12911 		optptr += ipp->ipp_rthdrlen;
12912 		ASSERT(OK_32PTR(optptr));
12913 		/* Save as last value */
12914 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
12915 		    (ipp->ipp_fields & IPPF_RTHDR),
12916 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
12917 	}
12918 	if (addflag.crb_ipv6_recvdstopts) {
12919 		toh = (struct T_opthdr *)optptr;
12920 		toh->level = IPPROTO_IPV6;
12921 		toh->name = IPV6_DSTOPTS;
12922 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
12923 		toh->status = 0;
12924 		optptr += sizeof (*toh);
12925 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
12926 		optptr += ipp->ipp_dstoptslen;
12927 		ASSERT(OK_32PTR(optptr));
12928 		/* Save as last value */
12929 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
12930 		    (ipp->ipp_fields & IPPF_DSTOPTS),
12931 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
12932 	}
12933 	ASSERT(optptr == mp->b_wptr);
12934 	return (mp);
12935 }
12936 
12937 /* ARGSUSED */
12938 static void
12939 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
12940 {
12941 	conn_t	*connp = (conn_t *)arg;
12942 	tcp_t	*tcp = connp->conn_tcp;
12943 	queue_t	*q = connp->conn_rq;
12944 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12945 
12946 	ASSERT(!IPCL_IS_NONSTR(connp));
12947 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
12948 	tcp->tcp_rsrv_mp = mp;
12949 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
12950 
12951 	TCP_STAT(tcps, tcp_rsrv_calls);
12952 
12953 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
12954 		return;
12955 	}
12956 
12957 	if (tcp->tcp_fused) {
12958 		tcp_fuse_backenable(tcp);
12959 		return;
12960 	}
12961 
12962 	if (canputnext(q)) {
12963 		/* Not flow-controlled, open rwnd */
12964 		tcp->tcp_rwnd = connp->conn_rcvbuf;
12965 
12966 		/*
12967 		 * Send back a window update immediately if TCP is above
12968 		 * ESTABLISHED state and the increase of the rcv window
12969 		 * that the other side knows is at least 1 MSS after flow
12970 		 * control is lifted.
12971 		 */
12972 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
12973 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
12974 			tcp_xmit_ctl(NULL, tcp,
12975 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
12976 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
12977 		}
12978 	}
12979 }
12980 
12981 /*
12982  * The read side service routine is called mostly when we get back-enabled as a
12983  * result of flow control relief.  Since we don't actually queue anything in
12984  * TCP, we have no data to send out of here.  What we do is clear the receive
12985  * window, and send out a window update.
12986  */
12987 static void
12988 tcp_rsrv(queue_t *q)
12989 {
12990 	conn_t		*connp = Q_TO_CONN(q);
12991 	tcp_t		*tcp = connp->conn_tcp;
12992 	mblk_t		*mp;
12993 
12994 	/* No code does a putq on the read side */
12995 	ASSERT(q->q_first == NULL);
12996 
12997 	/*
12998 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
12999 	 * been run.  So just return.
13000 	 */
13001 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
13002 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
13003 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
13004 		return;
13005 	}
13006 	tcp->tcp_rsrv_mp = NULL;
13007 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
13008 
13009 	CONN_INC_REF(connp);
13010 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
13011 	    NULL, SQ_PROCESS, SQTAG_TCP_RSRV);
13012 }
13013 
13014 /*
13015  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
13016  * We do not allow the receive window to shrink.  After setting rwnd,
13017  * set the flow control hiwat of the stream.
13018  *
13019  * This function is called in 2 cases:
13020  *
13021  * 1) Before data transfer begins, in tcp_input_listener() for accepting a
13022  *    connection (passive open) and in tcp_input_data() for active connect.
13023  *    This is called after tcp_mss_set() when the desired MSS value is known.
13024  *    This makes sure that our window size is a mutiple of the other side's
13025  *    MSS.
13026  * 2) Handling SO_RCVBUF option.
13027  *
13028  * It is ASSUMED that the requested size is a multiple of the current MSS.
13029  *
13030  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
13031  * user requests so.
13032  */
13033 int
13034 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
13035 {
13036 	uint32_t	mss = tcp->tcp_mss;
13037 	uint32_t	old_max_rwnd;
13038 	uint32_t	max_transmittable_rwnd;
13039 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
13040 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13041 	conn_t		*connp = tcp->tcp_connp;
13042 
13043 	/*
13044 	 * Insist on a receive window that is at least
13045 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
13046 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
13047 	 * and delayed acknowledgement.
13048 	 */
13049 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
13050 
13051 	if (tcp->tcp_fused) {
13052 		size_t sth_hiwat;
13053 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
13054 
13055 		ASSERT(peer_tcp != NULL);
13056 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
13057 		if (!tcp_detached) {
13058 			(void) proto_set_rx_hiwat(connp->conn_rq, connp,
13059 			    sth_hiwat);
13060 			tcp_set_recv_threshold(tcp, sth_hiwat >> 3);
13061 		}
13062 
13063 		/*
13064 		 * In the fusion case, the maxpsz stream head value of
13065 		 * our peer is set according to its send buffer size
13066 		 * and our receive buffer size; since the latter may
13067 		 * have changed we need to update the peer's maxpsz.
13068 		 */
13069 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
13070 		return (sth_hiwat);
13071 	}
13072 
13073 	if (tcp_detached)
13074 		old_max_rwnd = tcp->tcp_rwnd;
13075 	else
13076 		old_max_rwnd = connp->conn_rcvbuf;
13077 
13078 
13079 	/*
13080 	 * If window size info has already been exchanged, TCP should not
13081 	 * shrink the window.  Shrinking window is doable if done carefully.
13082 	 * We may add that support later.  But so far there is not a real
13083 	 * need to do that.
13084 	 */
13085 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
13086 		/* MSS may have changed, do a round up again. */
13087 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
13088 	}
13089 
13090 	/*
13091 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
13092 	 * can be applied even before the window scale option is decided.
13093 	 */
13094 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
13095 	if (rwnd > max_transmittable_rwnd) {
13096 		rwnd = max_transmittable_rwnd -
13097 		    (max_transmittable_rwnd % mss);
13098 		if (rwnd < mss)
13099 			rwnd = max_transmittable_rwnd;
13100 		/*
13101 		 * If we're over the limit we may have to back down tcp_rwnd.
13102 		 * The increment below won't work for us. So we set all three
13103 		 * here and the increment below will have no effect.
13104 		 */
13105 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
13106 	}
13107 	if (tcp->tcp_localnet) {
13108 		tcp->tcp_rack_abs_max =
13109 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
13110 	} else {
13111 		/*
13112 		 * For a remote host on a different subnet (through a router),
13113 		 * we ack every other packet to be conforming to RFC1122.
13114 		 * tcp_deferred_acks_max is default to 2.
13115 		 */
13116 		tcp->tcp_rack_abs_max =
13117 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
13118 	}
13119 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
13120 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
13121 	else
13122 		tcp->tcp_rack_cur_max = 0;
13123 	/*
13124 	 * Increment the current rwnd by the amount the maximum grew (we
13125 	 * can not overwrite it since we might be in the middle of a
13126 	 * connection.)
13127 	 */
13128 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
13129 	connp->conn_rcvbuf = rwnd;
13130 
13131 	/* Are we already connected? */
13132 	if (tcp->tcp_tcpha != NULL) {
13133 		tcp->tcp_tcpha->tha_win =
13134 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
13135 	}
13136 
13137 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
13138 		tcp->tcp_cwnd_max = rwnd;
13139 
13140 	if (tcp_detached)
13141 		return (rwnd);
13142 
13143 	tcp_set_recv_threshold(tcp, rwnd >> 3);
13144 
13145 	(void) proto_set_rx_hiwat(connp->conn_rq, connp, rwnd);
13146 	return (rwnd);
13147 }
13148 
13149 /*
13150  * Return SNMP stuff in buffer in mpdata.
13151  */
13152 mblk_t *
13153 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
13154 {
13155 	mblk_t			*mpdata;
13156 	mblk_t			*mp_conn_ctl = NULL;
13157 	mblk_t			*mp_conn_tail;
13158 	mblk_t			*mp_attr_ctl = NULL;
13159 	mblk_t			*mp_attr_tail;
13160 	mblk_t			*mp6_conn_ctl = NULL;
13161 	mblk_t			*mp6_conn_tail;
13162 	mblk_t			*mp6_attr_ctl = NULL;
13163 	mblk_t			*mp6_attr_tail;
13164 	struct opthdr		*optp;
13165 	mib2_tcpConnEntry_t	tce;
13166 	mib2_tcp6ConnEntry_t	tce6;
13167 	mib2_transportMLPEntry_t mlp;
13168 	connf_t			*connfp;
13169 	int			i;
13170 	boolean_t 		ispriv;
13171 	zoneid_t 		zoneid;
13172 	int			v4_conn_idx;
13173 	int			v6_conn_idx;
13174 	conn_t			*connp = Q_TO_CONN(q);
13175 	tcp_stack_t		*tcps;
13176 	ip_stack_t		*ipst;
13177 	mblk_t			*mp2ctl;
13178 
13179 	/*
13180 	 * make a copy of the original message
13181 	 */
13182 	mp2ctl = copymsg(mpctl);
13183 
13184 	if (mpctl == NULL ||
13185 	    (mpdata = mpctl->b_cont) == NULL ||
13186 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
13187 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
13188 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
13189 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
13190 		freemsg(mp_conn_ctl);
13191 		freemsg(mp_attr_ctl);
13192 		freemsg(mp6_conn_ctl);
13193 		freemsg(mp6_attr_ctl);
13194 		freemsg(mpctl);
13195 		freemsg(mp2ctl);
13196 		return (NULL);
13197 	}
13198 
13199 	ipst = connp->conn_netstack->netstack_ip;
13200 	tcps = connp->conn_netstack->netstack_tcp;
13201 
13202 	/* build table of connections -- need count in fixed part */
13203 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
13204 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
13205 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
13206 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
13207 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
13208 
13209 	ispriv =
13210 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
13211 	zoneid = Q_TO_CONN(q)->conn_zoneid;
13212 
13213 	v4_conn_idx = v6_conn_idx = 0;
13214 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
13215 
13216 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
13217 		ipst = tcps->tcps_netstack->netstack_ip;
13218 
13219 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
13220 
13221 		connp = NULL;
13222 
13223 		while ((connp =
13224 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
13225 			tcp_t *tcp;
13226 			boolean_t needattr;
13227 
13228 			if (connp->conn_zoneid != zoneid)
13229 				continue;	/* not in this zone */
13230 
13231 			tcp = connp->conn_tcp;
13232 			UPDATE_MIB(&tcps->tcps_mib,
13233 			    tcpHCInSegs, tcp->tcp_ibsegs);
13234 			tcp->tcp_ibsegs = 0;
13235 			UPDATE_MIB(&tcps->tcps_mib,
13236 			    tcpHCOutSegs, tcp->tcp_obsegs);
13237 			tcp->tcp_obsegs = 0;
13238 
13239 			tce6.tcp6ConnState = tce.tcpConnState =
13240 			    tcp_snmp_state(tcp);
13241 			if (tce.tcpConnState == MIB2_TCP_established ||
13242 			    tce.tcpConnState == MIB2_TCP_closeWait)
13243 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
13244 
13245 			needattr = B_FALSE;
13246 			bzero(&mlp, sizeof (mlp));
13247 			if (connp->conn_mlp_type != mlptSingle) {
13248 				if (connp->conn_mlp_type == mlptShared ||
13249 				    connp->conn_mlp_type == mlptBoth)
13250 					mlp.tme_flags |= MIB2_TMEF_SHARED;
13251 				if (connp->conn_mlp_type == mlptPrivate ||
13252 				    connp->conn_mlp_type == mlptBoth)
13253 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
13254 				needattr = B_TRUE;
13255 			}
13256 			if (connp->conn_anon_mlp) {
13257 				mlp.tme_flags |= MIB2_TMEF_ANONMLP;
13258 				needattr = B_TRUE;
13259 			}
13260 			switch (connp->conn_mac_mode) {
13261 			case CONN_MAC_DEFAULT:
13262 				break;
13263 			case CONN_MAC_AWARE:
13264 				mlp.tme_flags |= MIB2_TMEF_MACEXEMPT;
13265 				needattr = B_TRUE;
13266 				break;
13267 			case CONN_MAC_IMPLICIT:
13268 				mlp.tme_flags |= MIB2_TMEF_MACIMPLICIT;
13269 				needattr = B_TRUE;
13270 				break;
13271 			}
13272 			if (connp->conn_ixa->ixa_tsl != NULL) {
13273 				ts_label_t *tsl;
13274 
13275 				tsl = connp->conn_ixa->ixa_tsl;
13276 				mlp.tme_flags |= MIB2_TMEF_IS_LABELED;
13277 				mlp.tme_doi = label2doi(tsl);
13278 				mlp.tme_label = *label2bslabel(tsl);
13279 				needattr = B_TRUE;
13280 			}
13281 
13282 			/* Create a message to report on IPv6 entries */
13283 			if (connp->conn_ipversion == IPV6_VERSION) {
13284 			tce6.tcp6ConnLocalAddress = connp->conn_laddr_v6;
13285 			tce6.tcp6ConnRemAddress = connp->conn_faddr_v6;
13286 			tce6.tcp6ConnLocalPort = ntohs(connp->conn_lport);
13287 			tce6.tcp6ConnRemPort = ntohs(connp->conn_fport);
13288 			if (connp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET) {
13289 				tce6.tcp6ConnIfIndex =
13290 				    connp->conn_ixa->ixa_scopeid;
13291 			} else {
13292 				tce6.tcp6ConnIfIndex = connp->conn_bound_if;
13293 			}
13294 			/* Don't want just anybody seeing these... */
13295 			if (ispriv) {
13296 				tce6.tcp6ConnEntryInfo.ce_snxt =
13297 				    tcp->tcp_snxt;
13298 				tce6.tcp6ConnEntryInfo.ce_suna =
13299 				    tcp->tcp_suna;
13300 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13301 				    tcp->tcp_rnxt;
13302 				tce6.tcp6ConnEntryInfo.ce_rack =
13303 				    tcp->tcp_rack;
13304 			} else {
13305 				/*
13306 				 * Netstat, unfortunately, uses this to
13307 				 * get send/receive queue sizes.  How to fix?
13308 				 * Why not compute the difference only?
13309 				 */
13310 				tce6.tcp6ConnEntryInfo.ce_snxt =
13311 				    tcp->tcp_snxt - tcp->tcp_suna;
13312 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
13313 				tce6.tcp6ConnEntryInfo.ce_rnxt =
13314 				    tcp->tcp_rnxt - tcp->tcp_rack;
13315 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
13316 			}
13317 
13318 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13319 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13320 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
13321 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
13322 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
13323 
13324 			tce6.tcp6ConnCreationProcess =
13325 			    (connp->conn_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
13326 			    connp->conn_cpid;
13327 			tce6.tcp6ConnCreationTime = connp->conn_open_time;
13328 
13329 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
13330 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
13331 
13332 			mlp.tme_connidx = v6_conn_idx++;
13333 			if (needattr)
13334 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
13335 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
13336 			}
13337 			/*
13338 			 * Create an IPv4 table entry for IPv4 entries and also
13339 			 * for IPv6 entries which are bound to in6addr_any
13340 			 * but don't have IPV6_V6ONLY set.
13341 			 * (i.e. anything an IPv4 peer could connect to)
13342 			 */
13343 			if (connp->conn_ipversion == IPV4_VERSION ||
13344 			    (tcp->tcp_state <= TCPS_LISTEN &&
13345 			    !connp->conn_ipv6_v6only &&
13346 			    IN6_IS_ADDR_UNSPECIFIED(&connp->conn_laddr_v6))) {
13347 				if (connp->conn_ipversion == IPV6_VERSION) {
13348 					tce.tcpConnRemAddress = INADDR_ANY;
13349 					tce.tcpConnLocalAddress = INADDR_ANY;
13350 				} else {
13351 					tce.tcpConnRemAddress =
13352 					    connp->conn_faddr_v4;
13353 					tce.tcpConnLocalAddress =
13354 					    connp->conn_laddr_v4;
13355 				}
13356 				tce.tcpConnLocalPort = ntohs(connp->conn_lport);
13357 				tce.tcpConnRemPort = ntohs(connp->conn_fport);
13358 				/* Don't want just anybody seeing these... */
13359 				if (ispriv) {
13360 					tce.tcpConnEntryInfo.ce_snxt =
13361 					    tcp->tcp_snxt;
13362 					tce.tcpConnEntryInfo.ce_suna =
13363 					    tcp->tcp_suna;
13364 					tce.tcpConnEntryInfo.ce_rnxt =
13365 					    tcp->tcp_rnxt;
13366 					tce.tcpConnEntryInfo.ce_rack =
13367 					    tcp->tcp_rack;
13368 				} else {
13369 					/*
13370 					 * Netstat, unfortunately, uses this to
13371 					 * get send/receive queue sizes.  How
13372 					 * to fix?
13373 					 * Why not compute the difference only?
13374 					 */
13375 					tce.tcpConnEntryInfo.ce_snxt =
13376 					    tcp->tcp_snxt - tcp->tcp_suna;
13377 					tce.tcpConnEntryInfo.ce_suna = 0;
13378 					tce.tcpConnEntryInfo.ce_rnxt =
13379 					    tcp->tcp_rnxt - tcp->tcp_rack;
13380 					tce.tcpConnEntryInfo.ce_rack = 0;
13381 				}
13382 
13383 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
13384 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
13385 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
13386 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
13387 				tce.tcpConnEntryInfo.ce_state =
13388 				    tcp->tcp_state;
13389 
13390 				tce.tcpConnCreationProcess =
13391 				    (connp->conn_cpid < 0) ?
13392 				    MIB2_UNKNOWN_PROCESS :
13393 				    connp->conn_cpid;
13394 				tce.tcpConnCreationTime = connp->conn_open_time;
13395 
13396 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
13397 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
13398 
13399 				mlp.tme_connidx = v4_conn_idx++;
13400 				if (needattr)
13401 					(void) snmp_append_data2(
13402 					    mp_attr_ctl->b_cont,
13403 					    &mp_attr_tail, (char *)&mlp,
13404 					    sizeof (mlp));
13405 			}
13406 		}
13407 	}
13408 
13409 	/* fixed length structure for IPv4 and IPv6 counters */
13410 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
13411 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
13412 	    sizeof (mib2_tcp6ConnEntry_t));
13413 	/* synchronize 32- and 64-bit counters */
13414 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
13415 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
13416 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
13417 	optp->level = MIB2_TCP;
13418 	optp->name = 0;
13419 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
13420 	    sizeof (tcps->tcps_mib));
13421 	optp->len = msgdsize(mpdata);
13422 	qreply(q, mpctl);
13423 
13424 	/* table of connections... */
13425 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
13426 	    sizeof (struct T_optmgmt_ack)];
13427 	optp->level = MIB2_TCP;
13428 	optp->name = MIB2_TCP_CONN;
13429 	optp->len = msgdsize(mp_conn_ctl->b_cont);
13430 	qreply(q, mp_conn_ctl);
13431 
13432 	/* table of MLP attributes... */
13433 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
13434 	    sizeof (struct T_optmgmt_ack)];
13435 	optp->level = MIB2_TCP;
13436 	optp->name = EXPER_XPORT_MLP;
13437 	optp->len = msgdsize(mp_attr_ctl->b_cont);
13438 	if (optp->len == 0)
13439 		freemsg(mp_attr_ctl);
13440 	else
13441 		qreply(q, mp_attr_ctl);
13442 
13443 	/* table of IPv6 connections... */
13444 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
13445 	    sizeof (struct T_optmgmt_ack)];
13446 	optp->level = MIB2_TCP6;
13447 	optp->name = MIB2_TCP6_CONN;
13448 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
13449 	qreply(q, mp6_conn_ctl);
13450 
13451 	/* table of IPv6 MLP attributes... */
13452 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
13453 	    sizeof (struct T_optmgmt_ack)];
13454 	optp->level = MIB2_TCP6;
13455 	optp->name = EXPER_XPORT_MLP;
13456 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
13457 	if (optp->len == 0)
13458 		freemsg(mp6_attr_ctl);
13459 	else
13460 		qreply(q, mp6_attr_ctl);
13461 	return (mp2ctl);
13462 }
13463 
13464 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
13465 /* ARGSUSED */
13466 int
13467 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
13468 {
13469 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
13470 
13471 	switch (level) {
13472 	case MIB2_TCP:
13473 		switch (name) {
13474 		case 13:
13475 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
13476 				return (0);
13477 			/* TODO: delete entry defined by tce */
13478 			return (1);
13479 		default:
13480 			return (0);
13481 		}
13482 	default:
13483 		return (1);
13484 	}
13485 }
13486 
13487 /* Translate TCP state to MIB2 TCP state. */
13488 static int
13489 tcp_snmp_state(tcp_t *tcp)
13490 {
13491 	if (tcp == NULL)
13492 		return (0);
13493 
13494 	switch (tcp->tcp_state) {
13495 	case TCPS_CLOSED:
13496 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
13497 	case TCPS_BOUND:
13498 		return (MIB2_TCP_closed);
13499 	case TCPS_LISTEN:
13500 		return (MIB2_TCP_listen);
13501 	case TCPS_SYN_SENT:
13502 		return (MIB2_TCP_synSent);
13503 	case TCPS_SYN_RCVD:
13504 		return (MIB2_TCP_synReceived);
13505 	case TCPS_ESTABLISHED:
13506 		return (MIB2_TCP_established);
13507 	case TCPS_CLOSE_WAIT:
13508 		return (MIB2_TCP_closeWait);
13509 	case TCPS_FIN_WAIT_1:
13510 		return (MIB2_TCP_finWait1);
13511 	case TCPS_CLOSING:
13512 		return (MIB2_TCP_closing);
13513 	case TCPS_LAST_ACK:
13514 		return (MIB2_TCP_lastAck);
13515 	case TCPS_FIN_WAIT_2:
13516 		return (MIB2_TCP_finWait2);
13517 	case TCPS_TIME_WAIT:
13518 		return (MIB2_TCP_timeWait);
13519 	default:
13520 		return (0);
13521 	}
13522 }
13523 
13524 /*
13525  * tcp_timer is the timer service routine.  It handles the retransmission,
13526  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
13527  * from the state of the tcp instance what kind of action needs to be done
13528  * at the time it is called.
13529  */
13530 static void
13531 tcp_timer(void *arg)
13532 {
13533 	mblk_t		*mp;
13534 	clock_t		first_threshold;
13535 	clock_t		second_threshold;
13536 	clock_t		ms;
13537 	uint32_t	mss;
13538 	conn_t		*connp = (conn_t *)arg;
13539 	tcp_t		*tcp = connp->conn_tcp;
13540 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13541 
13542 	tcp->tcp_timer_tid = 0;
13543 
13544 	if (tcp->tcp_fused)
13545 		return;
13546 
13547 	first_threshold =  tcp->tcp_first_timer_threshold;
13548 	second_threshold = tcp->tcp_second_timer_threshold;
13549 	switch (tcp->tcp_state) {
13550 	case TCPS_IDLE:
13551 	case TCPS_BOUND:
13552 	case TCPS_LISTEN:
13553 		return;
13554 	case TCPS_SYN_RCVD: {
13555 		tcp_t	*listener = tcp->tcp_listener;
13556 
13557 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
13558 			/* it's our first timeout */
13559 			tcp->tcp_syn_rcvd_timeout = 1;
13560 			mutex_enter(&listener->tcp_eager_lock);
13561 			listener->tcp_syn_rcvd_timeout++;
13562 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
13563 				/*
13564 				 * Make this eager available for drop if we
13565 				 * need to drop one to accomodate a new
13566 				 * incoming SYN request.
13567 				 */
13568 				MAKE_DROPPABLE(listener, tcp);
13569 			}
13570 			if (!listener->tcp_syn_defense &&
13571 			    (listener->tcp_syn_rcvd_timeout >
13572 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
13573 			    (tcps->tcps_conn_req_max_q0 > 200)) {
13574 				/* We may be under attack. Put on a defense. */
13575 				listener->tcp_syn_defense = B_TRUE;
13576 				cmn_err(CE_WARN, "High TCP connect timeout "
13577 				    "rate! System (port %d) may be under a "
13578 				    "SYN flood attack!",
13579 				    ntohs(listener->tcp_connp->conn_lport));
13580 
13581 				listener->tcp_ip_addr_cache = kmem_zalloc(
13582 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
13583 				    KM_NOSLEEP);
13584 			}
13585 			mutex_exit(&listener->tcp_eager_lock);
13586 		} else if (listener != NULL) {
13587 			mutex_enter(&listener->tcp_eager_lock);
13588 			tcp->tcp_syn_rcvd_timeout++;
13589 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
13590 			    !tcp->tcp_closemp_used) {
13591 				/*
13592 				 * This is our second timeout. Put the tcp in
13593 				 * the list of droppable eagers to allow it to
13594 				 * be dropped, if needed. We don't check
13595 				 * whether tcp_dontdrop is set or not to
13596 				 * protect ourselve from a SYN attack where a
13597 				 * remote host can spoof itself as one of the
13598 				 * good IP source and continue to hold
13599 				 * resources too long.
13600 				 */
13601 				MAKE_DROPPABLE(listener, tcp);
13602 			}
13603 			mutex_exit(&listener->tcp_eager_lock);
13604 		}
13605 	}
13606 		/* FALLTHRU */
13607 	case TCPS_SYN_SENT:
13608 		first_threshold =  tcp->tcp_first_ctimer_threshold;
13609 		second_threshold = tcp->tcp_second_ctimer_threshold;
13610 		break;
13611 	case TCPS_ESTABLISHED:
13612 	case TCPS_FIN_WAIT_1:
13613 	case TCPS_CLOSING:
13614 	case TCPS_CLOSE_WAIT:
13615 	case TCPS_LAST_ACK:
13616 		/* If we have data to rexmit */
13617 		if (tcp->tcp_suna != tcp->tcp_snxt) {
13618 			clock_t	time_to_wait;
13619 
13620 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
13621 			if (!tcp->tcp_xmit_head)
13622 				break;
13623 			time_to_wait = ddi_get_lbolt() -
13624 			    (clock_t)tcp->tcp_xmit_head->b_prev;
13625 			time_to_wait = tcp->tcp_rto -
13626 			    TICK_TO_MSEC(time_to_wait);
13627 			/*
13628 			 * If the timer fires too early, 1 clock tick earlier,
13629 			 * restart the timer.
13630 			 */
13631 			if (time_to_wait > msec_per_tick) {
13632 				TCP_STAT(tcps, tcp_timer_fire_early);
13633 				TCP_TIMER_RESTART(tcp, time_to_wait);
13634 				return;
13635 			}
13636 			/*
13637 			 * When we probe zero windows, we force the swnd open.
13638 			 * If our peer acks with a closed window swnd will be
13639 			 * set to zero by tcp_rput(). As long as we are
13640 			 * receiving acks tcp_rput will
13641 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
13642 			 * first and second interval actions.  NOTE: the timer
13643 			 * interval is allowed to continue its exponential
13644 			 * backoff.
13645 			 */
13646 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
13647 				if (connp->conn_debug) {
13648 					(void) strlog(TCP_MOD_ID, 0, 1,
13649 					    SL_TRACE, "tcp_timer: zero win");
13650 				}
13651 			} else {
13652 				/*
13653 				 * After retransmission, we need to do
13654 				 * slow start.  Set the ssthresh to one
13655 				 * half of current effective window and
13656 				 * cwnd to one MSS.  Also reset
13657 				 * tcp_cwnd_cnt.
13658 				 *
13659 				 * Note that if tcp_ssthresh is reduced because
13660 				 * of ECN, do not reduce it again unless it is
13661 				 * already one window of data away (tcp_cwr
13662 				 * should then be cleared) or this is a
13663 				 * timeout for a retransmitted segment.
13664 				 */
13665 				uint32_t npkt;
13666 
13667 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
13668 					npkt = ((tcp->tcp_timer_backoff ?
13669 					    tcp->tcp_cwnd_ssthresh :
13670 					    tcp->tcp_snxt -
13671 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
13672 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
13673 					    tcp->tcp_mss;
13674 				}
13675 				tcp->tcp_cwnd = tcp->tcp_mss;
13676 				tcp->tcp_cwnd_cnt = 0;
13677 				if (tcp->tcp_ecn_ok) {
13678 					tcp->tcp_cwr = B_TRUE;
13679 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
13680 					tcp->tcp_ecn_cwr_sent = B_FALSE;
13681 				}
13682 			}
13683 			break;
13684 		}
13685 		/*
13686 		 * We have something to send yet we cannot send.  The
13687 		 * reason can be:
13688 		 *
13689 		 * 1. Zero send window: we need to do zero window probe.
13690 		 * 2. Zero cwnd: because of ECN, we need to "clock out
13691 		 * segments.
13692 		 * 3. SWS avoidance: receiver may have shrunk window,
13693 		 * reset our knowledge.
13694 		 *
13695 		 * Note that condition 2 can happen with either 1 or
13696 		 * 3.  But 1 and 3 are exclusive.
13697 		 */
13698 		if (tcp->tcp_unsent != 0) {
13699 			/*
13700 			 * Should not hold the zero-copy messages for too long.
13701 			 */
13702 			if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13703 				tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13704 				    tcp->tcp_xmit_head, B_TRUE);
13705 
13706 			if (tcp->tcp_cwnd == 0) {
13707 				/*
13708 				 * Set tcp_cwnd to 1 MSS so that a
13709 				 * new segment can be sent out.  We
13710 				 * are "clocking out" new data when
13711 				 * the network is really congested.
13712 				 */
13713 				ASSERT(tcp->tcp_ecn_ok);
13714 				tcp->tcp_cwnd = tcp->tcp_mss;
13715 			}
13716 			if (tcp->tcp_swnd == 0) {
13717 				/* Extend window for zero window probe */
13718 				tcp->tcp_swnd++;
13719 				tcp->tcp_zero_win_probe = B_TRUE;
13720 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
13721 			} else {
13722 				/*
13723 				 * Handle timeout from sender SWS avoidance.
13724 				 * Reset our knowledge of the max send window
13725 				 * since the receiver might have reduced its
13726 				 * receive buffer.  Avoid setting tcp_max_swnd
13727 				 * to one since that will essentially disable
13728 				 * the SWS checks.
13729 				 *
13730 				 * Note that since we don't have a SWS
13731 				 * state variable, if the timeout is set
13732 				 * for ECN but not for SWS, this
13733 				 * code will also be executed.  This is
13734 				 * fine as tcp_max_swnd is updated
13735 				 * constantly and it will not affect
13736 				 * anything.
13737 				 */
13738 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
13739 			}
13740 			tcp_wput_data(tcp, NULL, B_FALSE);
13741 			return;
13742 		}
13743 		/* Is there a FIN that needs to be to re retransmitted? */
13744 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13745 		    !tcp->tcp_fin_acked)
13746 			break;
13747 		/* Nothing to do, return without restarting timer. */
13748 		TCP_STAT(tcps, tcp_timer_fire_miss);
13749 		return;
13750 	case TCPS_FIN_WAIT_2:
13751 		/*
13752 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
13753 		 * We waited some time for for peer's FIN, but it hasn't
13754 		 * arrived.  We flush the connection now to avoid
13755 		 * case where the peer has rebooted.
13756 		 */
13757 		if (TCP_IS_DETACHED(tcp)) {
13758 			(void) tcp_clean_death(tcp, 0, 23);
13759 		} else {
13760 			TCP_TIMER_RESTART(tcp,
13761 			    tcps->tcps_fin_wait_2_flush_interval);
13762 		}
13763 		return;
13764 	case TCPS_TIME_WAIT:
13765 		(void) tcp_clean_death(tcp, 0, 24);
13766 		return;
13767 	default:
13768 		if (connp->conn_debug) {
13769 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
13770 			    "tcp_timer: strange state (%d) %s",
13771 			    tcp->tcp_state, tcp_display(tcp, NULL,
13772 			    DISP_PORT_ONLY));
13773 		}
13774 		return;
13775 	}
13776 
13777 	/*
13778 	 * If the system is under memory pressure or the max number of
13779 	 * connections have been established for the listener, be more
13780 	 * aggressive in aborting connections.
13781 	 */
13782 	if (tcps->tcps_reclaim || (tcp->tcp_listen_cnt != NULL &&
13783 	    tcp->tcp_listen_cnt->tlc_cnt > tcp->tcp_listen_cnt->tlc_max)) {
13784 		second_threshold = tcp_early_abort * SECONDS;
13785 	}
13786 
13787 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
13788 		/*
13789 		 * Should not hold the zero-copy messages for too long.
13790 		 */
13791 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13792 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13793 			    tcp->tcp_xmit_head, B_TRUE);
13794 
13795 		/*
13796 		 * For zero window probe, we need to send indefinitely,
13797 		 * unless we have not heard from the other side for some
13798 		 * time...
13799 		 */
13800 		if ((tcp->tcp_zero_win_probe == 0) ||
13801 		    (TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time) >
13802 		    second_threshold)) {
13803 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
13804 			/*
13805 			 * If TCP is in SYN_RCVD state, send back a
13806 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
13807 			 * should be zero in TCPS_SYN_RCVD state.
13808 			 */
13809 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
13810 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
13811 				    "in SYN_RCVD",
13812 				    tcp, tcp->tcp_snxt,
13813 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
13814 			}
13815 			(void) tcp_clean_death(tcp,
13816 			    tcp->tcp_client_errno ?
13817 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
13818 			return;
13819 		} else {
13820 			/*
13821 			 * If the system is under memory pressure, we also
13822 			 * abort connection in zero window probing.
13823 			 */
13824 			if (tcps->tcps_reclaim) {
13825 				(void) tcp_clean_death(tcp,
13826 				    tcp->tcp_client_errno ?
13827 				    tcp->tcp_client_errno : ETIMEDOUT, 25);
13828 				return;
13829 			}
13830 			/*
13831 			 * Set tcp_ms_we_have_waited to second_threshold
13832 			 * so that in next timeout, we will do the above
13833 			 * check (ddi_get_lbolt() - tcp_last_recv_time).
13834 			 * This is also to avoid overflow.
13835 			 *
13836 			 * We don't need to decrement tcp_timer_backoff
13837 			 * to avoid overflow because it will be decremented
13838 			 * later if new timeout value is greater than
13839 			 * tcp_rexmit_interval_max.  In the case when
13840 			 * tcp_rexmit_interval_max is greater than
13841 			 * second_threshold, it means that we will wait
13842 			 * longer than second_threshold to send the next
13843 			 * window probe.
13844 			 */
13845 			tcp->tcp_ms_we_have_waited = second_threshold;
13846 		}
13847 	} else if (ms > first_threshold) {
13848 		/*
13849 		 * Should not hold the zero-copy messages for too long.
13850 		 */
13851 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
13852 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
13853 			    tcp->tcp_xmit_head, B_TRUE);
13854 
13855 		/*
13856 		 * We have been retransmitting for too long...  The RTT
13857 		 * we calculated is probably incorrect.  Reinitialize it.
13858 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
13859 		 * tcp_rtt_update so that we won't accidentally cache a
13860 		 * bad value.  But only do this if this is not a zero
13861 		 * window probe.
13862 		 */
13863 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
13864 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
13865 			    (tcp->tcp_rtt_sa >> 5);
13866 			tcp->tcp_rtt_sa = 0;
13867 			tcp_ip_notify(tcp);
13868 			tcp->tcp_rtt_update = 0;
13869 		}
13870 	}
13871 	tcp->tcp_timer_backoff++;
13872 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
13873 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
13874 	    tcps->tcps_rexmit_interval_min) {
13875 		/*
13876 		 * This means the original RTO is tcp_rexmit_interval_min.
13877 		 * So we will use tcp_rexmit_interval_min as the RTO value
13878 		 * and do the backoff.
13879 		 */
13880 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
13881 	} else {
13882 		ms <<= tcp->tcp_timer_backoff;
13883 	}
13884 	if (ms > tcps->tcps_rexmit_interval_max) {
13885 		ms = tcps->tcps_rexmit_interval_max;
13886 		/*
13887 		 * ms is at max, decrement tcp_timer_backoff to avoid
13888 		 * overflow.
13889 		 */
13890 		tcp->tcp_timer_backoff--;
13891 	}
13892 	tcp->tcp_ms_we_have_waited += ms;
13893 	if (tcp->tcp_zero_win_probe == 0) {
13894 		tcp->tcp_rto = ms;
13895 	}
13896 	TCP_TIMER_RESTART(tcp, ms);
13897 	/*
13898 	 * This is after a timeout and tcp_rto is backed off.  Set
13899 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
13900 	 * restart the timer with a correct value.
13901 	 */
13902 	tcp->tcp_set_timer = 1;
13903 	mss = tcp->tcp_snxt - tcp->tcp_suna;
13904 	if (mss > tcp->tcp_mss)
13905 		mss = tcp->tcp_mss;
13906 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
13907 		mss = tcp->tcp_swnd;
13908 
13909 	if ((mp = tcp->tcp_xmit_head) != NULL)
13910 		mp->b_prev = (mblk_t *)ddi_get_lbolt();
13911 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
13912 	    B_TRUE);
13913 
13914 	/*
13915 	 * When slow start after retransmission begins, start with
13916 	 * this seq no.  tcp_rexmit_max marks the end of special slow
13917 	 * start phase.  tcp_snd_burst controls how many segments
13918 	 * can be sent because of an ack.
13919 	 */
13920 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
13921 	tcp->tcp_snd_burst = TCP_CWND_SS;
13922 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
13923 	    (tcp->tcp_unsent == 0)) {
13924 		tcp->tcp_rexmit_max = tcp->tcp_fss;
13925 	} else {
13926 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
13927 	}
13928 	tcp->tcp_rexmit = B_TRUE;
13929 	tcp->tcp_dupack_cnt = 0;
13930 
13931 	/*
13932 	 * Remove all rexmit SACK blk to start from fresh.
13933 	 */
13934 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
13935 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
13936 	if (mp == NULL) {
13937 		return;
13938 	}
13939 
13940 	tcp->tcp_csuna = tcp->tcp_snxt;
13941 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
13942 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
13943 	tcp_send_data(tcp, mp);
13944 
13945 }
13946 
13947 static int
13948 tcp_do_unbind(conn_t *connp)
13949 {
13950 	tcp_t *tcp = connp->conn_tcp;
13951 
13952 	switch (tcp->tcp_state) {
13953 	case TCPS_BOUND:
13954 	case TCPS_LISTEN:
13955 		break;
13956 	default:
13957 		return (-TOUTSTATE);
13958 	}
13959 
13960 	/*
13961 	 * Need to clean up all the eagers since after the unbind, segments
13962 	 * will no longer be delivered to this listener stream.
13963 	 */
13964 	mutex_enter(&tcp->tcp_eager_lock);
13965 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
13966 		tcp_eager_cleanup(tcp, 0);
13967 	}
13968 	mutex_exit(&tcp->tcp_eager_lock);
13969 
13970 	/* Clean up the listener connection counter if necessary. */
13971 	if (tcp->tcp_listen_cnt != NULL)
13972 		TCP_DECR_LISTEN_CNT(tcp);
13973 	connp->conn_laddr_v6 = ipv6_all_zeros;
13974 	connp->conn_saddr_v6 = ipv6_all_zeros;
13975 	tcp_bind_hash_remove(tcp);
13976 	tcp->tcp_state = TCPS_IDLE;
13977 
13978 	ip_unbind(connp);
13979 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
13980 
13981 	return (0);
13982 }
13983 
13984 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
13985 static void
13986 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
13987 {
13988 	conn_t *connp = tcp->tcp_connp;
13989 	int error;
13990 
13991 	error = tcp_do_unbind(connp);
13992 	if (error > 0) {
13993 		tcp_err_ack(tcp, mp, TSYSERR, error);
13994 	} else if (error < 0) {
13995 		tcp_err_ack(tcp, mp, -error, 0);
13996 	} else {
13997 		/* Send M_FLUSH according to TPI */
13998 		(void) putnextctl1(connp->conn_rq, M_FLUSH, FLUSHRW);
13999 
14000 		mp = mi_tpi_ok_ack_alloc(mp);
14001 		if (mp != NULL)
14002 			putnext(connp->conn_rq, mp);
14003 	}
14004 }
14005 
14006 /*
14007  * Don't let port fall into the privileged range.
14008  * Since the extra privileged ports can be arbitrary we also
14009  * ensure that we exclude those from consideration.
14010  * tcp_g_epriv_ports is not sorted thus we loop over it until
14011  * there are no changes.
14012  *
14013  * Note: No locks are held when inspecting tcp_g_*epriv_ports
14014  * but instead the code relies on:
14015  * - the fact that the address of the array and its size never changes
14016  * - the atomic assignment of the elements of the array
14017  *
14018  * Returns 0 if there are no more ports available.
14019  *
14020  * TS note: skip multilevel ports.
14021  */
14022 static in_port_t
14023 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
14024 {
14025 	int i;
14026 	boolean_t restart = B_FALSE;
14027 	tcp_stack_t *tcps = tcp->tcp_tcps;
14028 
14029 	if (random && tcp_random_anon_port != 0) {
14030 		(void) random_get_pseudo_bytes((uint8_t *)&port,
14031 		    sizeof (in_port_t));
14032 		/*
14033 		 * Unless changed by a sys admin, the smallest anon port
14034 		 * is 32768 and the largest anon port is 65535.  It is
14035 		 * very likely (50%) for the random port to be smaller
14036 		 * than the smallest anon port.  When that happens,
14037 		 * add port % (anon port range) to the smallest anon
14038 		 * port to get the random port.  It should fall into the
14039 		 * valid anon port range.
14040 		 */
14041 		if (port < tcps->tcps_smallest_anon_port) {
14042 			port = tcps->tcps_smallest_anon_port +
14043 			    port % (tcps->tcps_largest_anon_port -
14044 			    tcps->tcps_smallest_anon_port);
14045 		}
14046 	}
14047 
14048 retry:
14049 	if (port < tcps->tcps_smallest_anon_port)
14050 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14051 
14052 	if (port > tcps->tcps_largest_anon_port) {
14053 		if (restart)
14054 			return (0);
14055 		restart = B_TRUE;
14056 		port = (in_port_t)tcps->tcps_smallest_anon_port;
14057 	}
14058 
14059 	if (port < tcps->tcps_smallest_nonpriv_port)
14060 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
14061 
14062 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
14063 		if (port == tcps->tcps_g_epriv_ports[i]) {
14064 			port++;
14065 			/*
14066 			 * Make sure whether the port is in the
14067 			 * valid range.
14068 			 */
14069 			goto retry;
14070 		}
14071 	}
14072 	if (is_system_labeled() &&
14073 	    (i = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred), port,
14074 	    IPPROTO_TCP, B_TRUE)) != 0) {
14075 		port = i;
14076 		goto retry;
14077 	}
14078 	return (port);
14079 }
14080 
14081 /*
14082  * Return the next anonymous port in the privileged port range for
14083  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
14084  * downwards.  This is the same behavior as documented in the userland
14085  * library call rresvport(3N).
14086  *
14087  * TS note: skip multilevel ports.
14088  */
14089 static in_port_t
14090 tcp_get_next_priv_port(const tcp_t *tcp)
14091 {
14092 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
14093 	in_port_t nextport;
14094 	boolean_t restart = B_FALSE;
14095 	tcp_stack_t *tcps = tcp->tcp_tcps;
14096 retry:
14097 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
14098 	    next_priv_port >= IPPORT_RESERVED) {
14099 		next_priv_port = IPPORT_RESERVED - 1;
14100 		if (restart)
14101 			return (0);
14102 		restart = B_TRUE;
14103 	}
14104 	if (is_system_labeled() &&
14105 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_connp->conn_cred),
14106 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
14107 		next_priv_port = nextport;
14108 		goto retry;
14109 	}
14110 	return (next_priv_port--);
14111 }
14112 
14113 /* The write side r/w procedure. */
14114 
14115 #if CCS_STATS
14116 struct {
14117 	struct {
14118 		int64_t count, bytes;
14119 	} tot, hit;
14120 } wrw_stats;
14121 #endif
14122 
14123 /*
14124  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
14125  * messages.
14126  */
14127 /* ARGSUSED */
14128 static void
14129 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14130 {
14131 	conn_t	*connp = (conn_t *)arg;
14132 	tcp_t	*tcp = connp->conn_tcp;
14133 
14134 	ASSERT(DB_TYPE(mp) != M_IOCTL);
14135 	/*
14136 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
14137 	 * Once the close starts, streamhead and sockfs will not let any data
14138 	 * packets come down (close ensures that there are no threads using the
14139 	 * queue and no new threads will come down) but since qprocsoff()
14140 	 * hasn't happened yet, a M_FLUSH or some non data message might
14141 	 * get reflected back (in response to our own FLUSHRW) and get
14142 	 * processed after tcp_close() is done. The conn would still be valid
14143 	 * because a ref would have added but we need to check the state
14144 	 * before actually processing the packet.
14145 	 */
14146 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
14147 		freemsg(mp);
14148 		return;
14149 	}
14150 
14151 	switch (DB_TYPE(mp)) {
14152 	case M_IOCDATA:
14153 		tcp_wput_iocdata(tcp, mp);
14154 		break;
14155 	case M_FLUSH:
14156 		tcp_wput_flush(tcp, mp);
14157 		break;
14158 	default:
14159 		ip_wput_nondata(connp->conn_wq, mp);
14160 		break;
14161 	}
14162 }
14163 
14164 /*
14165  * The TCP fast path write put procedure.
14166  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
14167  */
14168 /* ARGSUSED */
14169 void
14170 tcp_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14171 {
14172 	int		len;
14173 	int		hdrlen;
14174 	int		plen;
14175 	mblk_t		*mp1;
14176 	uchar_t		*rptr;
14177 	uint32_t	snxt;
14178 	tcpha_t		*tcpha;
14179 	struct datab	*db;
14180 	uint32_t	suna;
14181 	uint32_t	mss;
14182 	ipaddr_t	*dst;
14183 	ipaddr_t	*src;
14184 	uint32_t	sum;
14185 	int		usable;
14186 	conn_t		*connp = (conn_t *)arg;
14187 	tcp_t		*tcp = connp->conn_tcp;
14188 	uint32_t	msize;
14189 	tcp_stack_t	*tcps = tcp->tcp_tcps;
14190 	ip_xmit_attr_t	*ixa;
14191 	clock_t		now;
14192 
14193 	/*
14194 	 * Try and ASSERT the minimum possible references on the
14195 	 * conn early enough. Since we are executing on write side,
14196 	 * the connection is obviously not detached and that means
14197 	 * there is a ref each for TCP and IP. Since we are behind
14198 	 * the squeue, the minimum references needed are 3. If the
14199 	 * conn is in classifier hash list, there should be an
14200 	 * extra ref for that (we check both the possibilities).
14201 	 */
14202 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14203 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14204 
14205 	ASSERT(DB_TYPE(mp) == M_DATA);
14206 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
14207 
14208 	mutex_enter(&tcp->tcp_non_sq_lock);
14209 	tcp->tcp_squeue_bytes -= msize;
14210 	mutex_exit(&tcp->tcp_non_sq_lock);
14211 
14212 	/* Bypass tcp protocol for fused tcp loopback */
14213 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
14214 		return;
14215 
14216 	mss = tcp->tcp_mss;
14217 	/*
14218 	 * If ZEROCOPY has turned off, try not to send any zero-copy message
14219 	 * down. Do backoff, now.
14220 	 */
14221 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on)
14222 		mp = tcp_zcopy_backoff(tcp, mp, B_FALSE);
14223 
14224 
14225 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
14226 	len = (int)(mp->b_wptr - mp->b_rptr);
14227 
14228 	/*
14229 	 * Criteria for fast path:
14230 	 *
14231 	 *   1. no unsent data
14232 	 *   2. single mblk in request
14233 	 *   3. connection established
14234 	 *   4. data in mblk
14235 	 *   5. len <= mss
14236 	 *   6. no tcp_valid bits
14237 	 */
14238 	if ((tcp->tcp_unsent != 0) ||
14239 	    (tcp->tcp_cork) ||
14240 	    (mp->b_cont != NULL) ||
14241 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
14242 	    (len == 0) ||
14243 	    (len > mss) ||
14244 	    (tcp->tcp_valid_bits != 0)) {
14245 		tcp_wput_data(tcp, mp, B_FALSE);
14246 		return;
14247 	}
14248 
14249 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
14250 	ASSERT(tcp->tcp_fin_sent == 0);
14251 
14252 	/* queue new packet onto retransmission queue */
14253 	if (tcp->tcp_xmit_head == NULL) {
14254 		tcp->tcp_xmit_head = mp;
14255 	} else {
14256 		tcp->tcp_xmit_last->b_cont = mp;
14257 	}
14258 	tcp->tcp_xmit_last = mp;
14259 	tcp->tcp_xmit_tail = mp;
14260 
14261 	/* find out how much we can send */
14262 	/* BEGIN CSTYLED */
14263 	/*
14264 	 *    un-acked	   usable
14265 	 *  |--------------|-----------------|
14266 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
14267 	 */
14268 	/* END CSTYLED */
14269 
14270 	/* start sending from tcp_snxt */
14271 	snxt = tcp->tcp_snxt;
14272 
14273 	/*
14274 	 * Check to see if this connection has been idled for some
14275 	 * time and no ACK is expected.  If it is, we need to slow
14276 	 * start again to get back the connection's "self-clock" as
14277 	 * described in VJ's paper.
14278 	 *
14279 	 * Reinitialize tcp_cwnd after idle.
14280 	 */
14281 	now = LBOLT_FASTPATH;
14282 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
14283 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
14284 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
14285 	}
14286 
14287 	usable = tcp->tcp_swnd;		/* tcp window size */
14288 	if (usable > tcp->tcp_cwnd)
14289 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
14290 	usable -= snxt;		/* subtract stuff already sent */
14291 	suna = tcp->tcp_suna;
14292 	usable += suna;
14293 	/* usable can be < 0 if the congestion window is smaller */
14294 	if (len > usable) {
14295 		/* Can't send complete M_DATA in one shot */
14296 		goto slow;
14297 	}
14298 
14299 	mutex_enter(&tcp->tcp_non_sq_lock);
14300 	if (tcp->tcp_flow_stopped &&
14301 	    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
14302 		tcp_clrqfull(tcp);
14303 	}
14304 	mutex_exit(&tcp->tcp_non_sq_lock);
14305 
14306 	/*
14307 	 * determine if anything to send (Nagle).
14308 	 *
14309 	 *   1. len < tcp_mss (i.e. small)
14310 	 *   2. unacknowledged data present
14311 	 *   3. len < nagle limit
14312 	 *   4. last packet sent < nagle limit (previous packet sent)
14313 	 */
14314 	if ((len < mss) && (snxt != suna) &&
14315 	    (len < (int)tcp->tcp_naglim) &&
14316 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
14317 		/*
14318 		 * This was the first unsent packet and normally
14319 		 * mss < xmit_hiwater so there is no need to worry
14320 		 * about flow control. The next packet will go
14321 		 * through the flow control check in tcp_wput_data().
14322 		 */
14323 		/* leftover work from above */
14324 		tcp->tcp_unsent = len;
14325 		tcp->tcp_xmit_tail_unsent = len;
14326 
14327 		return;
14328 	}
14329 
14330 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
14331 
14332 	if (snxt == suna) {
14333 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14334 	}
14335 
14336 	/* we have always sent something */
14337 	tcp->tcp_rack_cnt = 0;
14338 
14339 	tcp->tcp_snxt = snxt + len;
14340 	tcp->tcp_rack = tcp->tcp_rnxt;
14341 
14342 	if ((mp1 = dupb(mp)) == 0)
14343 		goto no_memory;
14344 	mp->b_prev = (mblk_t *)(uintptr_t)now;
14345 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
14346 
14347 	/* adjust tcp header information */
14348 	tcpha = tcp->tcp_tcpha;
14349 	tcpha->tha_flags = (TH_ACK|TH_PUSH);
14350 
14351 	sum = len + connp->conn_ht_ulp_len + connp->conn_sum;
14352 	sum = (sum >> 16) + (sum & 0xFFFF);
14353 	tcpha->tha_sum = htons(sum);
14354 
14355 	tcpha->tha_seq = htonl(snxt);
14356 
14357 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
14358 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
14359 	BUMP_LOCAL(tcp->tcp_obsegs);
14360 
14361 	/* Update the latest receive window size in TCP header. */
14362 	tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
14363 
14364 	tcp->tcp_last_sent_len = (ushort_t)len;
14365 
14366 	plen = len + connp->conn_ht_iphc_len;
14367 
14368 	ixa = connp->conn_ixa;
14369 	ixa->ixa_pktlen = plen;
14370 
14371 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
14372 		tcp->tcp_ipha->ipha_length = htons(plen);
14373 	} else {
14374 		tcp->tcp_ip6h->ip6_plen = htons(plen - IPV6_HDR_LEN);
14375 	}
14376 
14377 	/* see if we need to allocate a mblk for the headers */
14378 	hdrlen = connp->conn_ht_iphc_len;
14379 	rptr = mp1->b_rptr - hdrlen;
14380 	db = mp1->b_datap;
14381 	if ((db->db_ref != 2) || rptr < db->db_base ||
14382 	    (!OK_32PTR(rptr))) {
14383 		/* NOTE: we assume allocb returns an OK_32PTR */
14384 		mp = allocb(hdrlen + tcps->tcps_wroff_xtra, BPRI_MED);
14385 		if (!mp) {
14386 			freemsg(mp1);
14387 			goto no_memory;
14388 		}
14389 		mp->b_cont = mp1;
14390 		mp1 = mp;
14391 		/* Leave room for Link Level header */
14392 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
14393 		mp1->b_wptr = &rptr[hdrlen];
14394 	}
14395 	mp1->b_rptr = rptr;
14396 
14397 	/* Fill in the timestamp option. */
14398 	if (tcp->tcp_snd_ts_ok) {
14399 		uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
14400 
14401 		U32_TO_BE32(llbolt,
14402 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
14403 		U32_TO_BE32(tcp->tcp_ts_recent,
14404 		    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
14405 	} else {
14406 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
14407 	}
14408 
14409 	/* copy header into outgoing packet */
14410 	dst = (ipaddr_t *)rptr;
14411 	src = (ipaddr_t *)connp->conn_ht_iphc;
14412 	dst[0] = src[0];
14413 	dst[1] = src[1];
14414 	dst[2] = src[2];
14415 	dst[3] = src[3];
14416 	dst[4] = src[4];
14417 	dst[5] = src[5];
14418 	dst[6] = src[6];
14419 	dst[7] = src[7];
14420 	dst[8] = src[8];
14421 	dst[9] = src[9];
14422 	if (hdrlen -= 40) {
14423 		hdrlen >>= 2;
14424 		dst += 10;
14425 		src += 10;
14426 		do {
14427 			*dst++ = *src++;
14428 		} while (--hdrlen);
14429 	}
14430 
14431 	/*
14432 	 * Set the ECN info in the TCP header.  Note that this
14433 	 * is not the template header.
14434 	 */
14435 	if (tcp->tcp_ecn_ok) {
14436 		SET_ECT(tcp, rptr);
14437 
14438 		tcpha = (tcpha_t *)(rptr + ixa->ixa_ip_hdr_length);
14439 		if (tcp->tcp_ecn_echo_on)
14440 			tcpha->tha_flags |= TH_ECE;
14441 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
14442 			tcpha->tha_flags |= TH_CWR;
14443 			tcp->tcp_ecn_cwr_sent = B_TRUE;
14444 		}
14445 	}
14446 
14447 	if (tcp->tcp_ip_forward_progress) {
14448 		tcp->tcp_ip_forward_progress = B_FALSE;
14449 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
14450 	} else {
14451 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
14452 	}
14453 	tcp_send_data(tcp, mp1);
14454 	return;
14455 
14456 	/*
14457 	 * If we ran out of memory, we pretend to have sent the packet
14458 	 * and that it was lost on the wire.
14459 	 */
14460 no_memory:
14461 	return;
14462 
14463 slow:
14464 	/* leftover work from above */
14465 	tcp->tcp_unsent = len;
14466 	tcp->tcp_xmit_tail_unsent = len;
14467 	tcp_wput_data(tcp, NULL, B_FALSE);
14468 }
14469 
14470 /*
14471  * This runs at the tail end of accept processing on the squeue of the
14472  * new connection.
14473  */
14474 /* ARGSUSED */
14475 void
14476 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14477 {
14478 	conn_t			*connp = (conn_t *)arg;
14479 	tcp_t			*tcp = connp->conn_tcp;
14480 	queue_t			*q = connp->conn_rq;
14481 	tcp_stack_t		*tcps = tcp->tcp_tcps;
14482 	/* socket options */
14483 	struct sock_proto_props	sopp;
14484 
14485 	/* We should just receive a single mblk that fits a T_discon_ind */
14486 	ASSERT(mp->b_cont == NULL);
14487 
14488 	/*
14489 	 * Drop the eager's ref on the listener, that was placed when
14490 	 * this eager began life in tcp_input_listener.
14491 	 */
14492 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
14493 	if (IPCL_IS_NONSTR(connp)) {
14494 		/* Safe to free conn_ind message */
14495 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
14496 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14497 	}
14498 
14499 	tcp->tcp_detached = B_FALSE;
14500 
14501 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
14502 		/*
14503 		 * Someone blewoff the eager before we could finish
14504 		 * the accept.
14505 		 *
14506 		 * The only reason eager exists it because we put in
14507 		 * a ref on it when conn ind went up. We need to send
14508 		 * a disconnect indication up while the last reference
14509 		 * on the eager will be dropped by the squeue when we
14510 		 * return.
14511 		 */
14512 		ASSERT(tcp->tcp_listener == NULL);
14513 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
14514 			if (IPCL_IS_NONSTR(connp)) {
14515 				ASSERT(tcp->tcp_issocket);
14516 				(*connp->conn_upcalls->su_disconnected)(
14517 				    connp->conn_upper_handle, tcp->tcp_connid,
14518 				    ECONNREFUSED);
14519 				freemsg(mp);
14520 			} else {
14521 				struct	T_discon_ind	*tdi;
14522 
14523 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
14524 				/*
14525 				 * Let us reuse the incoming mblk to avoid
14526 				 * memory allocation failure problems. We know
14527 				 * that the size of the incoming mblk i.e.
14528 				 * stroptions is greater than sizeof
14529 				 * T_discon_ind.
14530 				 */
14531 				ASSERT(DB_REF(mp) == 1);
14532 				ASSERT(MBLKSIZE(mp) >=
14533 				    sizeof (struct T_discon_ind));
14534 
14535 				DB_TYPE(mp) = M_PROTO;
14536 				((union T_primitives *)mp->b_rptr)->type =
14537 				    T_DISCON_IND;
14538 				tdi = (struct T_discon_ind *)mp->b_rptr;
14539 				if (tcp->tcp_issocket) {
14540 					tdi->DISCON_reason = ECONNREFUSED;
14541 					tdi->SEQ_number = 0;
14542 				} else {
14543 					tdi->DISCON_reason = ENOPROTOOPT;
14544 					tdi->SEQ_number =
14545 					    tcp->tcp_conn_req_seqnum;
14546 				}
14547 				mp->b_wptr = mp->b_rptr +
14548 				    sizeof (struct T_discon_ind);
14549 				putnext(q, mp);
14550 			}
14551 		}
14552 		tcp->tcp_hard_binding = B_FALSE;
14553 		return;
14554 	}
14555 
14556 	/*
14557 	 * This is the first time we run on the correct
14558 	 * queue after tcp_accept. So fix all the q parameters
14559 	 * here.
14560 	 */
14561 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
14562 	sopp.sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
14563 
14564 	sopp.sopp_rxhiwat = tcp->tcp_fused ?
14565 	    tcp_fuse_set_rcv_hiwat(tcp, connp->conn_rcvbuf) :
14566 	    connp->conn_rcvbuf;
14567 
14568 	/*
14569 	 * Determine what write offset value to use depending on SACK and
14570 	 * whether the endpoint is fused or not.
14571 	 */
14572 	if (tcp->tcp_fused) {
14573 		ASSERT(tcp->tcp_loopback);
14574 		ASSERT(tcp->tcp_loopback_peer != NULL);
14575 		/*
14576 		 * For fused tcp loopback, set the stream head's write
14577 		 * offset value to zero since we won't be needing any room
14578 		 * for TCP/IP headers.  This would also improve performance
14579 		 * since it would reduce the amount of work done by kmem.
14580 		 * Non-fused tcp loopback case is handled separately below.
14581 		 */
14582 		sopp.sopp_wroff = 0;
14583 		/*
14584 		 * Update the peer's transmit parameters according to
14585 		 * our recently calculated high water mark value.
14586 		 */
14587 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
14588 	} else if (tcp->tcp_snd_sack_ok) {
14589 		sopp.sopp_wroff = connp->conn_ht_iphc_allocated +
14590 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14591 	} else {
14592 		sopp.sopp_wroff = connp->conn_ht_iphc_len +
14593 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
14594 	}
14595 
14596 	/*
14597 	 * If this is endpoint is handling SSL, then reserve extra
14598 	 * offset and space at the end.
14599 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
14600 	 * overriding the previous setting. The extra cost of signing and
14601 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
14602 	 * instead of a single contiguous one by the stream head
14603 	 * largely outweighs the statistical reduction of ACKs, when
14604 	 * applicable. The peer will also save on decryption and verification
14605 	 * costs.
14606 	 */
14607 	if (tcp->tcp_kssl_ctx != NULL) {
14608 		sopp.sopp_wroff += SSL3_WROFFSET;
14609 
14610 		sopp.sopp_flags |= SOCKOPT_TAIL;
14611 		sopp.sopp_tail = SSL3_MAX_TAIL_LEN;
14612 
14613 		sopp.sopp_flags |= SOCKOPT_ZCOPY;
14614 		sopp.sopp_zcopyflag = ZCVMUNSAFE;
14615 
14616 		sopp.sopp_maxblk = SSL3_MAX_RECORD_LEN;
14617 	}
14618 
14619 	/* Send the options up */
14620 	if (IPCL_IS_NONSTR(connp)) {
14621 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14622 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14623 			ASSERT(sopp.sopp_flags & SOCKOPT_ZCOPY);
14624 		}
14625 		if (tcp->tcp_loopback) {
14626 			sopp.sopp_flags |= SOCKOPT_LOOPBACK;
14627 			sopp.sopp_loopback = B_TRUE;
14628 		}
14629 		(*connp->conn_upcalls->su_set_proto_props)
14630 		    (connp->conn_upper_handle, &sopp);
14631 		freemsg(mp);
14632 	} else {
14633 		/*
14634 		 * Let us reuse the incoming mblk to avoid
14635 		 * memory allocation failure problems. We know
14636 		 * that the size of the incoming mblk is at least
14637 		 * stroptions
14638 		 */
14639 		struct stroptions *stropt;
14640 
14641 		ASSERT(DB_REF(mp) == 1);
14642 		ASSERT(MBLKSIZE(mp) >= sizeof (struct stroptions));
14643 
14644 		DB_TYPE(mp) = M_SETOPTS;
14645 		stropt = (struct stroptions *)mp->b_rptr;
14646 		mp->b_wptr = mp->b_rptr + sizeof (struct stroptions);
14647 		stropt = (struct stroptions *)mp->b_rptr;
14648 		stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
14649 		stropt->so_hiwat = sopp.sopp_rxhiwat;
14650 		stropt->so_wroff = sopp.sopp_wroff;
14651 		stropt->so_maxblk = sopp.sopp_maxblk;
14652 
14653 		if (sopp.sopp_flags & SOCKOPT_TAIL) {
14654 			ASSERT(tcp->tcp_kssl_ctx != NULL);
14655 
14656 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
14657 			stropt->so_tail = sopp.sopp_tail;
14658 			stropt->so_copyopt = sopp.sopp_zcopyflag;
14659 		}
14660 
14661 		/* Send the options up */
14662 		putnext(q, mp);
14663 	}
14664 
14665 	/*
14666 	 * Pass up any data and/or a fin that has been received.
14667 	 *
14668 	 * Adjust receive window in case it had decreased
14669 	 * (because there is data <=> tcp_rcv_list != NULL)
14670 	 * while the connection was detached. Note that
14671 	 * in case the eager was flow-controlled, w/o this
14672 	 * code, the rwnd may never open up again!
14673 	 */
14674 	if (tcp->tcp_rcv_list != NULL) {
14675 		if (IPCL_IS_NONSTR(connp)) {
14676 			mblk_t *mp;
14677 			int space_left;
14678 			int error;
14679 			boolean_t push = B_TRUE;
14680 
14681 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
14682 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
14683 			    &push) >= 0) {
14684 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14685 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14686 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14687 					tcp_xmit_ctl(NULL,
14688 					    tcp, (tcp->tcp_swnd == 0) ?
14689 					    tcp->tcp_suna : tcp->tcp_snxt,
14690 					    tcp->tcp_rnxt, TH_ACK);
14691 				}
14692 			}
14693 			while ((mp = tcp->tcp_rcv_list) != NULL) {
14694 				push = B_TRUE;
14695 				tcp->tcp_rcv_list = mp->b_next;
14696 				mp->b_next = NULL;
14697 				space_left = (*connp->conn_upcalls->su_recv)
14698 				    (connp->conn_upper_handle, mp, msgdsize(mp),
14699 				    0, &error, &push);
14700 				if (space_left < 0) {
14701 					/*
14702 					 * We should never be in middle of a
14703 					 * fallback, the squeue guarantees that.
14704 					 */
14705 					ASSERT(error != EOPNOTSUPP);
14706 				}
14707 			}
14708 			tcp->tcp_rcv_last_head = NULL;
14709 			tcp->tcp_rcv_last_tail = NULL;
14710 			tcp->tcp_rcv_cnt = 0;
14711 		} else {
14712 			/* We drain directly in case of fused tcp loopback */
14713 
14714 			if (!tcp->tcp_fused && canputnext(q)) {
14715 				tcp->tcp_rwnd = connp->conn_rcvbuf;
14716 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
14717 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
14718 					tcp_xmit_ctl(NULL,
14719 					    tcp, (tcp->tcp_swnd == 0) ?
14720 					    tcp->tcp_suna : tcp->tcp_snxt,
14721 					    tcp->tcp_rnxt, TH_ACK);
14722 				}
14723 			}
14724 
14725 			(void) tcp_rcv_drain(tcp);
14726 		}
14727 
14728 		/*
14729 		 * For fused tcp loopback, back-enable peer endpoint
14730 		 * if it's currently flow-controlled.
14731 		 */
14732 		if (tcp->tcp_fused) {
14733 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
14734 
14735 			ASSERT(peer_tcp != NULL);
14736 			ASSERT(peer_tcp->tcp_fused);
14737 
14738 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
14739 			if (peer_tcp->tcp_flow_stopped) {
14740 				tcp_clrqfull(peer_tcp);
14741 				TCP_STAT(tcps, tcp_fusion_backenabled);
14742 			}
14743 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
14744 		}
14745 	}
14746 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
14747 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
14748 		tcp->tcp_ordrel_done = B_TRUE;
14749 		if (IPCL_IS_NONSTR(connp)) {
14750 			ASSERT(tcp->tcp_ordrel_mp == NULL);
14751 			(*connp->conn_upcalls->su_opctl)(
14752 			    connp->conn_upper_handle,
14753 			    SOCK_OPCTL_SHUT_RECV, 0);
14754 		} else {
14755 			mp = tcp->tcp_ordrel_mp;
14756 			tcp->tcp_ordrel_mp = NULL;
14757 			putnext(q, mp);
14758 		}
14759 	}
14760 	tcp->tcp_hard_binding = B_FALSE;
14761 
14762 	if (connp->conn_keepalive) {
14763 		tcp->tcp_ka_last_intrvl = 0;
14764 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
14765 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
14766 	}
14767 
14768 	/*
14769 	 * At this point, eager is fully established and will
14770 	 * have the following references -
14771 	 *
14772 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
14773 	 * 1 reference for the squeue which will be dropped by the squeue as
14774 	 *	soon as this function returns.
14775 	 * There will be 1 additonal reference for being in classifier
14776 	 *	hash list provided something bad hasn't happened.
14777 	 */
14778 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
14779 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
14780 }
14781 
14782 /*
14783  * The function called through squeue to get behind listener's perimeter to
14784  * send a deferred conn_ind.
14785  */
14786 /* ARGSUSED */
14787 void
14788 tcp_send_pending(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
14789 {
14790 	conn_t	*lconnp = (conn_t *)arg;
14791 	tcp_t *listener = lconnp->conn_tcp;
14792 	struct T_conn_ind *conn_ind;
14793 	tcp_t *tcp;
14794 
14795 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
14796 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
14797 	    conn_ind->OPT_length);
14798 
14799 	if (listener->tcp_state != TCPS_LISTEN) {
14800 		/*
14801 		 * If listener has closed, it would have caused a
14802 		 * a cleanup/blowoff to happen for the eager, so
14803 		 * we don't need to do anything more.
14804 		 */
14805 		freemsg(mp);
14806 		return;
14807 	}
14808 
14809 	tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
14810 }
14811 
14812 /*
14813  * Common to TPI and sockfs accept code.
14814  */
14815 /* ARGSUSED2 */
14816 static int
14817 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
14818 {
14819 	tcp_t *listener, *eager;
14820 	mblk_t *discon_mp;
14821 
14822 	listener = lconnp->conn_tcp;
14823 	ASSERT(listener->tcp_state == TCPS_LISTEN);
14824 	eager = econnp->conn_tcp;
14825 	ASSERT(eager->tcp_listener != NULL);
14826 
14827 	/*
14828 	 * Pre allocate the discon_ind mblk also. tcp_accept_finish will
14829 	 * use it if something failed.
14830 	 */
14831 	discon_mp = allocb(MAX(sizeof (struct T_discon_ind),
14832 	    sizeof (struct stroptions)), BPRI_HI);
14833 
14834 	if (discon_mp == NULL) {
14835 		return (-TPROTO);
14836 	}
14837 	eager->tcp_issocket = B_TRUE;
14838 
14839 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
14840 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
14841 	ASSERT(econnp->conn_netstack ==
14842 	    listener->tcp_connp->conn_netstack);
14843 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
14844 
14845 	/* Put the ref for IP */
14846 	CONN_INC_REF(econnp);
14847 
14848 	/*
14849 	 * We should have minimum of 3 references on the conn
14850 	 * at this point. One each for TCP and IP and one for
14851 	 * the T_conn_ind that was sent up when the 3-way handshake
14852 	 * completed. In the normal case we would also have another
14853 	 * reference (making a total of 4) for the conn being in the
14854 	 * classifier hash list. However the eager could have received
14855 	 * an RST subsequently and tcp_closei_local could have removed
14856 	 * the eager from the classifier hash list, hence we can't
14857 	 * assert that reference.
14858 	 */
14859 	ASSERT(econnp->conn_ref >= 3);
14860 
14861 	mutex_enter(&listener->tcp_eager_lock);
14862 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
14863 
14864 		tcp_t *tail;
14865 		tcp_t *tcp;
14866 		mblk_t *mp1;
14867 
14868 		tcp = listener->tcp_eager_prev_q0;
14869 		/*
14870 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
14871 		 * deferred T_conn_ind queue. We need to get to the head
14872 		 * of the queue in order to send up T_conn_ind the same
14873 		 * order as how the 3WHS is completed.
14874 		 */
14875 		while (tcp != listener) {
14876 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
14877 			    !tcp->tcp_kssl_pending)
14878 				break;
14879 			else
14880 				tcp = tcp->tcp_eager_prev_q0;
14881 		}
14882 		/* None of the pending eagers can be sent up now */
14883 		if (tcp == listener)
14884 			goto no_more_eagers;
14885 
14886 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
14887 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14888 		/* Move from q0 to q */
14889 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
14890 		listener->tcp_conn_req_cnt_q0--;
14891 		listener->tcp_conn_req_cnt_q++;
14892 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
14893 		    tcp->tcp_eager_prev_q0;
14894 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
14895 		    tcp->tcp_eager_next_q0;
14896 		tcp->tcp_eager_prev_q0 = NULL;
14897 		tcp->tcp_eager_next_q0 = NULL;
14898 		tcp->tcp_conn_def_q0 = B_FALSE;
14899 
14900 		/* Make sure the tcp isn't in the list of droppables */
14901 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
14902 		    tcp->tcp_eager_prev_drop_q0 == NULL);
14903 
14904 		/*
14905 		 * Insert at end of the queue because sockfs sends
14906 		 * down T_CONN_RES in chronological order. Leaving
14907 		 * the older conn indications at front of the queue
14908 		 * helps reducing search time.
14909 		 */
14910 		tail = listener->tcp_eager_last_q;
14911 		if (tail != NULL) {
14912 			tail->tcp_eager_next_q = tcp;
14913 		} else {
14914 			listener->tcp_eager_next_q = tcp;
14915 		}
14916 		listener->tcp_eager_last_q = tcp;
14917 		tcp->tcp_eager_next_q = NULL;
14918 
14919 		/* Need to get inside the listener perimeter */
14920 		CONN_INC_REF(listener->tcp_connp);
14921 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
14922 		    tcp_send_pending, listener->tcp_connp, NULL, SQ_FILL,
14923 		    SQTAG_TCP_SEND_PENDING);
14924 	}
14925 no_more_eagers:
14926 	tcp_eager_unlink(eager);
14927 	mutex_exit(&listener->tcp_eager_lock);
14928 
14929 	/*
14930 	 * At this point, the eager is detached from the listener
14931 	 * but we still have an extra refs on eager (apart from the
14932 	 * usual tcp references). The ref was placed in tcp_input_data
14933 	 * before sending the conn_ind in tcp_send_conn_ind.
14934 	 * The ref will be dropped in tcp_accept_finish().
14935 	 */
14936 	SQUEUE_ENTER_ONE(econnp->conn_sqp, discon_mp, tcp_accept_finish,
14937 	    econnp, NULL, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
14938 	return (0);
14939 }
14940 
14941 int
14942 tcp_accept(sock_lower_handle_t lproto_handle,
14943     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
14944     cred_t *cr)
14945 {
14946 	conn_t *lconnp, *econnp;
14947 	tcp_t *listener, *eager;
14948 
14949 	lconnp = (conn_t *)lproto_handle;
14950 	listener = lconnp->conn_tcp;
14951 	ASSERT(listener->tcp_state == TCPS_LISTEN);
14952 	econnp = (conn_t *)eproto_handle;
14953 	eager = econnp->conn_tcp;
14954 	ASSERT(eager->tcp_listener != NULL);
14955 
14956 	/*
14957 	 * It is OK to manipulate these fields outside the eager's squeue
14958 	 * because they will not start being used until tcp_accept_finish
14959 	 * has been called.
14960 	 */
14961 	ASSERT(lconnp->conn_upper_handle != NULL);
14962 	ASSERT(econnp->conn_upper_handle == NULL);
14963 	econnp->conn_upper_handle = sock_handle;
14964 	econnp->conn_upcalls = lconnp->conn_upcalls;
14965 	ASSERT(IPCL_IS_NONSTR(econnp));
14966 	return (tcp_accept_common(lconnp, econnp, cr));
14967 }
14968 
14969 
14970 /*
14971  * This is the STREAMS entry point for T_CONN_RES coming down on
14972  * Acceptor STREAM when  sockfs listener does accept processing.
14973  * Read the block comment on top of tcp_input_listener().
14974  */
14975 void
14976 tcp_tpi_accept(queue_t *q, mblk_t *mp)
14977 {
14978 	queue_t *rq = RD(q);
14979 	struct T_conn_res *conn_res;
14980 	tcp_t *eager;
14981 	tcp_t *listener;
14982 	struct T_ok_ack *ok;
14983 	t_scalar_t PRIM_type;
14984 	conn_t *econnp;
14985 	cred_t *cr;
14986 
14987 	ASSERT(DB_TYPE(mp) == M_PROTO);
14988 
14989 	/*
14990 	 * All Solaris components should pass a db_credp
14991 	 * for this TPI message, hence we ASSERT.
14992 	 * But in case there is some other M_PROTO that looks
14993 	 * like a TPI message sent by some other kernel
14994 	 * component, we check and return an error.
14995 	 */
14996 	cr = msg_getcred(mp, NULL);
14997 	ASSERT(cr != NULL);
14998 	if (cr == NULL) {
14999 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
15000 		if (mp != NULL)
15001 			putnext(rq, mp);
15002 		return;
15003 	}
15004 	conn_res = (struct T_conn_res *)mp->b_rptr;
15005 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
15006 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
15007 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15008 		if (mp != NULL)
15009 			putnext(rq, mp);
15010 		return;
15011 	}
15012 	switch (conn_res->PRIM_type) {
15013 	case O_T_CONN_RES:
15014 	case T_CONN_RES:
15015 		/*
15016 		 * We pass up an err ack if allocb fails. This will
15017 		 * cause sockfs to issue a T_DISCON_REQ which will cause
15018 		 * tcp_eager_blowoff to be called. sockfs will then call
15019 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
15020 		 * we need to do the allocb up here because we have to
15021 		 * make sure rq->q_qinfo->qi_qclose still points to the
15022 		 * correct function (tcp_tpi_close_accept) in case allocb
15023 		 * fails.
15024 		 */
15025 		bcopy(mp->b_rptr + conn_res->OPT_offset,
15026 		    &eager, conn_res->OPT_length);
15027 		PRIM_type = conn_res->PRIM_type;
15028 		mp->b_datap->db_type = M_PCPROTO;
15029 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
15030 		ok = (struct T_ok_ack *)mp->b_rptr;
15031 		ok->PRIM_type = T_OK_ACK;
15032 		ok->CORRECT_prim = PRIM_type;
15033 		econnp = eager->tcp_connp;
15034 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
15035 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
15036 		econnp->conn_rq = rq;
15037 		econnp->conn_wq = q;
15038 		rq->q_ptr = econnp;
15039 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
15040 		q->q_ptr = econnp;
15041 		q->q_qinfo = &tcp_winit;
15042 		listener = eager->tcp_listener;
15043 
15044 		if (tcp_accept_common(listener->tcp_connp,
15045 		    econnp, cr) < 0) {
15046 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
15047 			if (mp != NULL)
15048 				putnext(rq, mp);
15049 			return;
15050 		}
15051 
15052 		/*
15053 		 * Send the new local address also up to sockfs. There
15054 		 * should already be enough space in the mp that came
15055 		 * down from soaccept().
15056 		 */
15057 		if (econnp->conn_family == AF_INET) {
15058 			sin_t *sin;
15059 
15060 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15061 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
15062 			sin = (sin_t *)mp->b_wptr;
15063 			mp->b_wptr += sizeof (sin_t);
15064 			sin->sin_family = AF_INET;
15065 			sin->sin_port = econnp->conn_lport;
15066 			sin->sin_addr.s_addr = econnp->conn_laddr_v4;
15067 		} else {
15068 			sin6_t *sin6;
15069 
15070 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
15071 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
15072 			sin6 = (sin6_t *)mp->b_wptr;
15073 			mp->b_wptr += sizeof (sin6_t);
15074 			sin6->sin6_family = AF_INET6;
15075 			sin6->sin6_port = econnp->conn_lport;
15076 			sin6->sin6_addr = econnp->conn_laddr_v6;
15077 			if (econnp->conn_ipversion == IPV4_VERSION) {
15078 				sin6->sin6_flowinfo = 0;
15079 			} else {
15080 				ASSERT(eager->tcp_ip6h != NULL);
15081 				sin6->sin6_flowinfo =
15082 				    eager->tcp_ip6h->ip6_vcf &
15083 				    ~IPV6_VERS_AND_FLOW_MASK;
15084 			}
15085 			if (IN6_IS_ADDR_LINKSCOPE(&econnp->conn_laddr_v6) &&
15086 			    (econnp->conn_ixa->ixa_flags & IXAF_SCOPEID_SET)) {
15087 				sin6->sin6_scope_id =
15088 				    econnp->conn_ixa->ixa_scopeid;
15089 			} else {
15090 				sin6->sin6_scope_id = 0;
15091 			}
15092 			sin6->__sin6_src_id = 0;
15093 		}
15094 
15095 		putnext(rq, mp);
15096 		return;
15097 	default:
15098 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
15099 		if (mp != NULL)
15100 			putnext(rq, mp);
15101 		return;
15102 	}
15103 }
15104 
15105 /*
15106  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
15107  */
15108 static void
15109 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
15110 {
15111 	void	*data;
15112 	mblk_t	*datamp = mp->b_cont;
15113 	conn_t	*connp = Q_TO_CONN(q);
15114 	tcp_t	*tcp = connp->conn_tcp;
15115 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
15116 
15117 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
15118 		cmdp->cb_error = EPROTO;
15119 		qreply(q, mp);
15120 		return;
15121 	}
15122 
15123 	data = datamp->b_rptr;
15124 
15125 	switch (cmdp->cb_cmd) {
15126 	case TI_GETPEERNAME:
15127 		if (tcp->tcp_state < TCPS_SYN_RCVD)
15128 			cmdp->cb_error = ENOTCONN;
15129 		else
15130 			cmdp->cb_error = conn_getpeername(connp, data,
15131 			    &cmdp->cb_len);
15132 		break;
15133 	case TI_GETMYNAME:
15134 		cmdp->cb_error = conn_getsockname(connp, data, &cmdp->cb_len);
15135 		break;
15136 	default:
15137 		cmdp->cb_error = EINVAL;
15138 		break;
15139 	}
15140 
15141 	qreply(q, mp);
15142 }
15143 
15144 void
15145 tcp_wput(queue_t *q, mblk_t *mp)
15146 {
15147 	conn_t	*connp = Q_TO_CONN(q);
15148 	tcp_t	*tcp;
15149 	void (*output_proc)();
15150 	t_scalar_t type;
15151 	uchar_t *rptr;
15152 	struct iocblk	*iocp;
15153 	size_t size;
15154 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
15155 
15156 	ASSERT(connp->conn_ref >= 2);
15157 
15158 	switch (DB_TYPE(mp)) {
15159 	case M_DATA:
15160 		tcp = connp->conn_tcp;
15161 		ASSERT(tcp != NULL);
15162 
15163 		size = msgdsize(mp);
15164 
15165 		mutex_enter(&tcp->tcp_non_sq_lock);
15166 		tcp->tcp_squeue_bytes += size;
15167 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
15168 			tcp_setqfull(tcp);
15169 		}
15170 		mutex_exit(&tcp->tcp_non_sq_lock);
15171 
15172 		CONN_INC_REF(connp);
15173 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
15174 		    NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
15175 		return;
15176 
15177 	case M_CMD:
15178 		tcp_wput_cmdblk(q, mp);
15179 		return;
15180 
15181 	case M_PROTO:
15182 	case M_PCPROTO:
15183 		/*
15184 		 * if it is a snmp message, don't get behind the squeue
15185 		 */
15186 		tcp = connp->conn_tcp;
15187 		rptr = mp->b_rptr;
15188 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
15189 			type = ((union T_primitives *)rptr)->type;
15190 		} else {
15191 			if (connp->conn_debug) {
15192 				(void) strlog(TCP_MOD_ID, 0, 1,
15193 				    SL_ERROR|SL_TRACE,
15194 				    "tcp_wput_proto, dropping one...");
15195 			}
15196 			freemsg(mp);
15197 			return;
15198 		}
15199 		if (type == T_SVR4_OPTMGMT_REQ) {
15200 			/*
15201 			 * All Solaris components should pass a db_credp
15202 			 * for this TPI message, hence we ASSERT.
15203 			 * But in case there is some other M_PROTO that looks
15204 			 * like a TPI message sent by some other kernel
15205 			 * component, we check and return an error.
15206 			 */
15207 			cred_t	*cr = msg_getcred(mp, NULL);
15208 
15209 			ASSERT(cr != NULL);
15210 			if (cr == NULL) {
15211 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
15212 				return;
15213 			}
15214 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
15215 			    cr)) {
15216 				/*
15217 				 * This was a SNMP request
15218 				 */
15219 				return;
15220 			} else {
15221 				output_proc = tcp_wput_proto;
15222 			}
15223 		} else {
15224 			output_proc = tcp_wput_proto;
15225 		}
15226 		break;
15227 	case M_IOCTL:
15228 		/*
15229 		 * Most ioctls can be processed right away without going via
15230 		 * squeues - process them right here. Those that do require
15231 		 * squeue (currently _SIOCSOCKFALLBACK)
15232 		 * are processed by tcp_wput_ioctl().
15233 		 */
15234 		iocp = (struct iocblk *)mp->b_rptr;
15235 		tcp = connp->conn_tcp;
15236 
15237 		switch (iocp->ioc_cmd) {
15238 		case TCP_IOC_ABORT_CONN:
15239 			tcp_ioctl_abort_conn(q, mp);
15240 			return;
15241 		case TI_GETPEERNAME:
15242 		case TI_GETMYNAME:
15243 			mi_copyin(q, mp, NULL,
15244 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
15245 			return;
15246 		case ND_SET:
15247 			/* nd_getset does the necessary checks */
15248 		case ND_GET:
15249 			if (nd_getset(q, tcps->tcps_g_nd, mp)) {
15250 				qreply(q, mp);
15251 				return;
15252 			}
15253 			ip_wput_nondata(q, mp);
15254 			return;
15255 
15256 		default:
15257 			output_proc = tcp_wput_ioctl;
15258 			break;
15259 		}
15260 		break;
15261 	default:
15262 		output_proc = tcp_wput_nondata;
15263 		break;
15264 	}
15265 
15266 	CONN_INC_REF(connp);
15267 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
15268 	    NULL, tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
15269 }
15270 
15271 /*
15272  * Initial STREAMS write side put() procedure for sockets. It tries to
15273  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
15274  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
15275  * are handled by tcp_wput() as usual.
15276  *
15277  * All further messages will also be handled by tcp_wput() because we cannot
15278  * be sure that the above short cut is safe later.
15279  */
15280 static void
15281 tcp_wput_sock(queue_t *wq, mblk_t *mp)
15282 {
15283 	conn_t			*connp = Q_TO_CONN(wq);
15284 	tcp_t			*tcp = connp->conn_tcp;
15285 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
15286 
15287 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
15288 	wq->q_qinfo = &tcp_winit;
15289 
15290 	ASSERT(IPCL_IS_TCP(connp));
15291 	ASSERT(TCP_IS_SOCKET(tcp));
15292 
15293 	if (DB_TYPE(mp) == M_PCPROTO &&
15294 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
15295 	    car->PRIM_type == T_CAPABILITY_REQ) {
15296 		tcp_capability_req(tcp, mp);
15297 		return;
15298 	}
15299 
15300 	tcp_wput(wq, mp);
15301 }
15302 
15303 /* ARGSUSED */
15304 static void
15305 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
15306 {
15307 #ifdef DEBUG
15308 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
15309 #endif
15310 	freemsg(mp);
15311 }
15312 
15313 /*
15314  * Check the usability of ZEROCOPY. It's instead checking the flag set by IP.
15315  */
15316 static boolean_t
15317 tcp_zcopy_check(tcp_t *tcp)
15318 {
15319 	conn_t		*connp = tcp->tcp_connp;
15320 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
15321 	boolean_t	zc_enabled = B_FALSE;
15322 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15323 
15324 	if (do_tcpzcopy == 2)
15325 		zc_enabled = B_TRUE;
15326 	else if ((do_tcpzcopy == 1) && (ixa->ixa_flags & IXAF_ZCOPY_CAPAB))
15327 		zc_enabled = B_TRUE;
15328 
15329 	tcp->tcp_snd_zcopy_on = zc_enabled;
15330 	if (!TCP_IS_DETACHED(tcp)) {
15331 		if (zc_enabled) {
15332 			ixa->ixa_flags |= IXAF_VERIFY_ZCOPY;
15333 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15334 			    ZCVMSAFE);
15335 			TCP_STAT(tcps, tcp_zcopy_on);
15336 		} else {
15337 			ixa->ixa_flags &= ~IXAF_VERIFY_ZCOPY;
15338 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15339 			    ZCVMUNSAFE);
15340 			TCP_STAT(tcps, tcp_zcopy_off);
15341 		}
15342 	}
15343 	return (zc_enabled);
15344 }
15345 
15346 /*
15347  * Backoff from a zero-copy message by copying data to a new allocated
15348  * message and freeing the original desballoca'ed segmapped message.
15349  *
15350  * This function is called by following two callers:
15351  * 1. tcp_timer: fix_xmitlist is set to B_TRUE, because it's safe to free
15352  *    the origial desballoca'ed message and notify sockfs. This is in re-
15353  *    transmit state.
15354  * 2. tcp_output: fix_xmitlist is set to B_FALSE. Flag STRUIO_ZCNOTIFY need
15355  *    to be copied to new message.
15356  */
15357 static mblk_t *
15358 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, boolean_t fix_xmitlist)
15359 {
15360 	mblk_t		*nbp;
15361 	mblk_t		*head = NULL;
15362 	mblk_t		*tail = NULL;
15363 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15364 
15365 	ASSERT(bp != NULL);
15366 	while (bp != NULL) {
15367 		if (IS_VMLOANED_MBLK(bp)) {
15368 			TCP_STAT(tcps, tcp_zcopy_backoff);
15369 			if ((nbp = copyb(bp)) == NULL) {
15370 				tcp->tcp_xmit_zc_clean = B_FALSE;
15371 				if (tail != NULL)
15372 					tail->b_cont = bp;
15373 				return ((head == NULL) ? bp : head);
15374 			}
15375 
15376 			if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
15377 				if (fix_xmitlist)
15378 					tcp_zcopy_notify(tcp);
15379 				else
15380 					nbp->b_datap->db_struioflag |=
15381 					    STRUIO_ZCNOTIFY;
15382 			}
15383 			nbp->b_cont = bp->b_cont;
15384 
15385 			/*
15386 			 * Copy saved information and adjust tcp_xmit_tail
15387 			 * if needed.
15388 			 */
15389 			if (fix_xmitlist) {
15390 				nbp->b_prev = bp->b_prev;
15391 				nbp->b_next = bp->b_next;
15392 
15393 				if (tcp->tcp_xmit_tail == bp)
15394 					tcp->tcp_xmit_tail = nbp;
15395 			}
15396 
15397 			/* Free the original message. */
15398 			bp->b_prev = NULL;
15399 			bp->b_next = NULL;
15400 			freeb(bp);
15401 
15402 			bp = nbp;
15403 		}
15404 
15405 		if (head == NULL) {
15406 			head = bp;
15407 		}
15408 		if (tail == NULL) {
15409 			tail = bp;
15410 		} else {
15411 			tail->b_cont = bp;
15412 			tail = bp;
15413 		}
15414 
15415 		/* Move forward. */
15416 		bp = bp->b_cont;
15417 	}
15418 
15419 	if (fix_xmitlist) {
15420 		tcp->tcp_xmit_last = tail;
15421 		tcp->tcp_xmit_zc_clean = B_TRUE;
15422 	}
15423 
15424 	return (head);
15425 }
15426 
15427 static void
15428 tcp_zcopy_notify(tcp_t *tcp)
15429 {
15430 	struct stdata	*stp;
15431 	conn_t		*connp;
15432 
15433 	if (tcp->tcp_detached)
15434 		return;
15435 	connp = tcp->tcp_connp;
15436 	if (IPCL_IS_NONSTR(connp)) {
15437 		(*connp->conn_upcalls->su_zcopy_notify)
15438 		    (connp->conn_upper_handle);
15439 		return;
15440 	}
15441 	stp = STREAM(connp->conn_rq);
15442 	mutex_enter(&stp->sd_lock);
15443 	stp->sd_flag |= STZCNOTIFY;
15444 	cv_broadcast(&stp->sd_zcopy_wait);
15445 	mutex_exit(&stp->sd_lock);
15446 }
15447 
15448 /*
15449  * Update the TCP connection according to change of LSO capability.
15450  */
15451 static void
15452 tcp_update_lso(tcp_t *tcp, ip_xmit_attr_t *ixa)
15453 {
15454 	/*
15455 	 * We check against IPv4 header length to preserve the old behavior
15456 	 * of only enabling LSO when there are no IP options.
15457 	 * But this restriction might not be necessary at all. Before removing
15458 	 * it, need to verify how LSO is handled for source routing case, with
15459 	 * which IP does software checksum.
15460 	 *
15461 	 * For IPv6, whenever any extension header is needed, LSO is supressed.
15462 	 */
15463 	if (ixa->ixa_ip_hdr_length != ((ixa->ixa_flags & IXAF_IS_IPV4) ?
15464 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN))
15465 		return;
15466 
15467 	/*
15468 	 * Either the LSO capability newly became usable, or it has changed.
15469 	 */
15470 	if (ixa->ixa_flags & IXAF_LSO_CAPAB) {
15471 		ill_lso_capab_t	*lsoc = &ixa->ixa_lso_capab;
15472 
15473 		ASSERT(lsoc->ill_lso_max > 0);
15474 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH, lsoc->ill_lso_max);
15475 
15476 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15477 		    boolean_t, B_TRUE, uint32_t, tcp->tcp_lso_max);
15478 
15479 		/*
15480 		 * If LSO to be enabled, notify the STREAM header with larger
15481 		 * data block.
15482 		 */
15483 		if (!tcp->tcp_lso)
15484 			tcp->tcp_maxpsz_multiplier = 0;
15485 
15486 		tcp->tcp_lso = B_TRUE;
15487 		TCP_STAT(tcp->tcp_tcps, tcp_lso_enabled);
15488 	} else { /* LSO capability is not usable any more. */
15489 		DTRACE_PROBE3(tcp_update_lso, boolean_t, tcp->tcp_lso,
15490 		    boolean_t, B_FALSE, uint32_t, tcp->tcp_lso_max);
15491 
15492 		/*
15493 		 * If LSO to be disabled, notify the STREAM header with smaller
15494 		 * data block. And need to restore fragsize to PMTU.
15495 		 */
15496 		if (tcp->tcp_lso) {
15497 			tcp->tcp_maxpsz_multiplier =
15498 			    tcp->tcp_tcps->tcps_maxpsz_multiplier;
15499 			ixa->ixa_fragsize = ixa->ixa_pmtu;
15500 			tcp->tcp_lso = B_FALSE;
15501 			TCP_STAT(tcp->tcp_tcps, tcp_lso_disabled);
15502 		}
15503 	}
15504 
15505 	(void) tcp_maxpsz_set(tcp, B_TRUE);
15506 }
15507 
15508 /*
15509  * Update the TCP connection according to change of ZEROCOPY capability.
15510  */
15511 static void
15512 tcp_update_zcopy(tcp_t *tcp)
15513 {
15514 	conn_t		*connp = tcp->tcp_connp;
15515 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15516 
15517 	if (tcp->tcp_snd_zcopy_on) {
15518 		tcp->tcp_snd_zcopy_on = B_FALSE;
15519 		if (!TCP_IS_DETACHED(tcp)) {
15520 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15521 			    ZCVMUNSAFE);
15522 			TCP_STAT(tcps, tcp_zcopy_off);
15523 		}
15524 	} else {
15525 		tcp->tcp_snd_zcopy_on = B_TRUE;
15526 		if (!TCP_IS_DETACHED(tcp)) {
15527 			(void) proto_set_tx_copyopt(connp->conn_rq, connp,
15528 			    ZCVMSAFE);
15529 			TCP_STAT(tcps, tcp_zcopy_on);
15530 		}
15531 	}
15532 }
15533 
15534 /*
15535  * Notify function registered with ip_xmit_attr_t. It's called in the squeue
15536  * so it's safe to update the TCP connection.
15537  */
15538 /* ARGSUSED1 */
15539 static void
15540 tcp_notify(void *arg, ip_xmit_attr_t *ixa, ixa_notify_type_t ntype,
15541     ixa_notify_arg_t narg)
15542 {
15543 	tcp_t		*tcp = (tcp_t *)arg;
15544 	conn_t		*connp = tcp->tcp_connp;
15545 
15546 	switch (ntype) {
15547 	case IXAN_LSO:
15548 		tcp_update_lso(tcp, connp->conn_ixa);
15549 		break;
15550 	case IXAN_PMTU:
15551 		tcp_update_pmtu(tcp, B_FALSE);
15552 		break;
15553 	case IXAN_ZCOPY:
15554 		tcp_update_zcopy(tcp);
15555 		break;
15556 	default:
15557 		break;
15558 	}
15559 }
15560 
15561 static void
15562 tcp_send_data(tcp_t *tcp, mblk_t *mp)
15563 {
15564 	conn_t		*connp = tcp->tcp_connp;
15565 
15566 	/*
15567 	 * Check here to avoid sending zero-copy message down to IP when
15568 	 * ZEROCOPY capability has turned off. We only need to deal with
15569 	 * the race condition between sockfs and the notification here.
15570 	 * Since we have tried to backoff the tcp_xmit_head when turning
15571 	 * zero-copy off and new messages in tcp_output(), we simply drop
15572 	 * the dup'ed packet here and let tcp retransmit, if tcp_xmit_zc_clean
15573 	 * is not true.
15574 	 */
15575 	if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_snd_zcopy_on &&
15576 	    !tcp->tcp_xmit_zc_clean) {
15577 		ip_drop_output("TCP ZC was disabled but not clean", mp, NULL);
15578 		freemsg(mp);
15579 		return;
15580 	}
15581 
15582 	ASSERT(connp->conn_ixa->ixa_notify_cookie == connp->conn_tcp);
15583 	(void) conn_ip_output(mp, connp->conn_ixa);
15584 }
15585 
15586 /*
15587  * This handles the case when the receiver has shrunk its win. Per RFC 1122
15588  * if the receiver shrinks the window, i.e. moves the right window to the
15589  * left, the we should not send new data, but should retransmit normally the
15590  * old unacked data between suna and suna + swnd. We might has sent data
15591  * that is now outside the new window, pretend that we didn't send  it.
15592  */
15593 static void
15594 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
15595 {
15596 	uint32_t	snxt = tcp->tcp_snxt;
15597 
15598 	ASSERT(shrunk_count > 0);
15599 
15600 	if (!tcp->tcp_is_wnd_shrnk) {
15601 		tcp->tcp_snxt_shrunk = snxt;
15602 		tcp->tcp_is_wnd_shrnk = B_TRUE;
15603 	} else if (SEQ_GT(snxt, tcp->tcp_snxt_shrunk)) {
15604 		tcp->tcp_snxt_shrunk = snxt;
15605 	}
15606 
15607 	/* Pretend we didn't send the data outside the window */
15608 	snxt -= shrunk_count;
15609 
15610 	/* Reset all the values per the now shrunk window */
15611 	tcp_update_xmit_tail(tcp, snxt);
15612 	tcp->tcp_unsent += shrunk_count;
15613 
15614 	/*
15615 	 * If the SACK option is set, delete the entire list of
15616 	 * notsack'ed blocks.
15617 	 */
15618 	if (tcp->tcp_sack_info != NULL) {
15619 		if (tcp->tcp_notsack_list != NULL)
15620 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
15621 	}
15622 
15623 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
15624 		/*
15625 		 * Make sure the timer is running so that we will probe a zero
15626 		 * window.
15627 		 */
15628 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15629 }
15630 
15631 
15632 /*
15633  * The TCP normal data output path.
15634  * NOTE: the logic of the fast path is duplicated from this function.
15635  */
15636 static void
15637 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
15638 {
15639 	int		len;
15640 	mblk_t		*local_time;
15641 	mblk_t		*mp1;
15642 	uint32_t	snxt;
15643 	int		tail_unsent;
15644 	int		tcpstate;
15645 	int		usable = 0;
15646 	mblk_t		*xmit_tail;
15647 	int32_t		mss;
15648 	int32_t		num_sack_blk = 0;
15649 	int32_t		total_hdr_len;
15650 	int32_t		tcp_hdr_len;
15651 	int		rc;
15652 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15653 	conn_t		*connp = tcp->tcp_connp;
15654 	clock_t		now = LBOLT_FASTPATH;
15655 
15656 	tcpstate = tcp->tcp_state;
15657 	if (mp == NULL) {
15658 		/*
15659 		 * tcp_wput_data() with NULL mp should only be called when
15660 		 * there is unsent data.
15661 		 */
15662 		ASSERT(tcp->tcp_unsent > 0);
15663 		/* Really tacky... but we need this for detached closes. */
15664 		len = tcp->tcp_unsent;
15665 		goto data_null;
15666 	}
15667 
15668 #if CCS_STATS
15669 	wrw_stats.tot.count++;
15670 	wrw_stats.tot.bytes += msgdsize(mp);
15671 #endif
15672 	ASSERT(mp->b_datap->db_type == M_DATA);
15673 	/*
15674 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
15675 	 * or before a connection attempt has begun.
15676 	 */
15677 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
15678 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15679 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
15680 #ifdef DEBUG
15681 			cmn_err(CE_WARN,
15682 			    "tcp_wput_data: data after ordrel, %s",
15683 			    tcp_display(tcp, NULL,
15684 			    DISP_ADDR_AND_PORT));
15685 #else
15686 			if (connp->conn_debug) {
15687 				(void) strlog(TCP_MOD_ID, 0, 1,
15688 				    SL_TRACE|SL_ERROR,
15689 				    "tcp_wput_data: data after ordrel, %s\n",
15690 				    tcp_display(tcp, NULL,
15691 				    DISP_ADDR_AND_PORT));
15692 			}
15693 #endif /* DEBUG */
15694 		}
15695 		if (tcp->tcp_snd_zcopy_aware &&
15696 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15697 			tcp_zcopy_notify(tcp);
15698 		freemsg(mp);
15699 		mutex_enter(&tcp->tcp_non_sq_lock);
15700 		if (tcp->tcp_flow_stopped &&
15701 		    TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
15702 			tcp_clrqfull(tcp);
15703 		}
15704 		mutex_exit(&tcp->tcp_non_sq_lock);
15705 		return;
15706 	}
15707 
15708 	/* Strip empties */
15709 	for (;;) {
15710 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
15711 		    (uintptr_t)INT_MAX);
15712 		len = (int)(mp->b_wptr - mp->b_rptr);
15713 		if (len > 0)
15714 			break;
15715 		mp1 = mp;
15716 		mp = mp->b_cont;
15717 		freeb(mp1);
15718 		if (!mp) {
15719 			return;
15720 		}
15721 	}
15722 
15723 	/* If we are the first on the list ... */
15724 	if (tcp->tcp_xmit_head == NULL) {
15725 		tcp->tcp_xmit_head = mp;
15726 		tcp->tcp_xmit_tail = mp;
15727 		tcp->tcp_xmit_tail_unsent = len;
15728 	} else {
15729 		/* If tiny tx and room in txq tail, pullup to save mblks. */
15730 		struct datab *dp;
15731 
15732 		mp1 = tcp->tcp_xmit_last;
15733 		if (len < tcp_tx_pull_len &&
15734 		    (dp = mp1->b_datap)->db_ref == 1 &&
15735 		    dp->db_lim - mp1->b_wptr >= len) {
15736 			ASSERT(len > 0);
15737 			ASSERT(!mp1->b_cont);
15738 			if (len == 1) {
15739 				*mp1->b_wptr++ = *mp->b_rptr;
15740 			} else {
15741 				bcopy(mp->b_rptr, mp1->b_wptr, len);
15742 				mp1->b_wptr += len;
15743 			}
15744 			if (mp1 == tcp->tcp_xmit_tail)
15745 				tcp->tcp_xmit_tail_unsent += len;
15746 			mp1->b_cont = mp->b_cont;
15747 			if (tcp->tcp_snd_zcopy_aware &&
15748 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
15749 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
15750 			freeb(mp);
15751 			mp = mp1;
15752 		} else {
15753 			tcp->tcp_xmit_last->b_cont = mp;
15754 		}
15755 		len += tcp->tcp_unsent;
15756 	}
15757 
15758 	/* Tack on however many more positive length mblks we have */
15759 	if ((mp1 = mp->b_cont) != NULL) {
15760 		do {
15761 			int tlen;
15762 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
15763 			    (uintptr_t)INT_MAX);
15764 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
15765 			if (tlen <= 0) {
15766 				mp->b_cont = mp1->b_cont;
15767 				freeb(mp1);
15768 			} else {
15769 				len += tlen;
15770 				mp = mp1;
15771 			}
15772 		} while ((mp1 = mp->b_cont) != NULL);
15773 	}
15774 	tcp->tcp_xmit_last = mp;
15775 	tcp->tcp_unsent = len;
15776 
15777 	if (urgent)
15778 		usable = 1;
15779 
15780 data_null:
15781 	snxt = tcp->tcp_snxt;
15782 	xmit_tail = tcp->tcp_xmit_tail;
15783 	tail_unsent = tcp->tcp_xmit_tail_unsent;
15784 
15785 	/*
15786 	 * Note that tcp_mss has been adjusted to take into account the
15787 	 * timestamp option if applicable.  Because SACK options do not
15788 	 * appear in every TCP segments and they are of variable lengths,
15789 	 * they cannot be included in tcp_mss.  Thus we need to calculate
15790 	 * the actual segment length when we need to send a segment which
15791 	 * includes SACK options.
15792 	 */
15793 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15794 		int32_t	opt_len;
15795 
15796 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
15797 		    tcp->tcp_num_sack_blk);
15798 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
15799 		    2 + TCPOPT_HEADER_LEN;
15800 		mss = tcp->tcp_mss - opt_len;
15801 		total_hdr_len = connp->conn_ht_iphc_len + opt_len;
15802 		tcp_hdr_len = connp->conn_ht_ulp_len + opt_len;
15803 	} else {
15804 		mss = tcp->tcp_mss;
15805 		total_hdr_len = connp->conn_ht_iphc_len;
15806 		tcp_hdr_len = connp->conn_ht_ulp_len;
15807 	}
15808 
15809 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
15810 	    (TICK_TO_MSEC(now - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
15811 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
15812 	}
15813 	if (tcpstate == TCPS_SYN_RCVD) {
15814 		/*
15815 		 * The three-way connection establishment handshake is not
15816 		 * complete yet. We want to queue the data for transmission
15817 		 * after entering ESTABLISHED state (RFC793). A jump to
15818 		 * "done" label effectively leaves data on the queue.
15819 		 */
15820 		goto done;
15821 	} else {
15822 		int usable_r;
15823 
15824 		/*
15825 		 * In the special case when cwnd is zero, which can only
15826 		 * happen if the connection is ECN capable, return now.
15827 		 * New segments is sent using tcp_timer().  The timer
15828 		 * is set in tcp_input_data().
15829 		 */
15830 		if (tcp->tcp_cwnd == 0) {
15831 			/*
15832 			 * Note that tcp_cwnd is 0 before 3-way handshake is
15833 			 * finished.
15834 			 */
15835 			ASSERT(tcp->tcp_ecn_ok ||
15836 			    tcp->tcp_state < TCPS_ESTABLISHED);
15837 			return;
15838 		}
15839 
15840 		/* NOTE: trouble if xmitting while SYN not acked? */
15841 		usable_r = snxt - tcp->tcp_suna;
15842 		usable_r = tcp->tcp_swnd - usable_r;
15843 
15844 		/*
15845 		 * Check if the receiver has shrunk the window.  If
15846 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
15847 		 * cannot be set as there is unsent data, so FIN cannot
15848 		 * be sent out.  Otherwise, we need to take into account
15849 		 * of FIN as it consumes an "invisible" sequence number.
15850 		 */
15851 		ASSERT(tcp->tcp_fin_sent == 0);
15852 		if (usable_r < 0) {
15853 			/*
15854 			 * The receiver has shrunk the window and we have sent
15855 			 * -usable_r date beyond the window, re-adjust.
15856 			 *
15857 			 * If TCP window scaling is enabled, there can be
15858 			 * round down error as the advertised receive window
15859 			 * is actually right shifted n bits.  This means that
15860 			 * the lower n bits info is wiped out.  It will look
15861 			 * like the window is shrunk.  Do a check here to
15862 			 * see if the shrunk amount is actually within the
15863 			 * error in window calculation.  If it is, just
15864 			 * return.  Note that this check is inside the
15865 			 * shrunk window check.  This makes sure that even
15866 			 * though tcp_process_shrunk_swnd() is not called,
15867 			 * we will stop further processing.
15868 			 */
15869 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
15870 				tcp_process_shrunk_swnd(tcp, -usable_r);
15871 			}
15872 			return;
15873 		}
15874 
15875 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
15876 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
15877 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
15878 
15879 		/* usable = MIN(usable, unsent) */
15880 		if (usable_r > len)
15881 			usable_r = len;
15882 
15883 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
15884 		if (usable_r > 0) {
15885 			usable = usable_r;
15886 		} else {
15887 			/* Bypass all other unnecessary processing. */
15888 			goto done;
15889 		}
15890 	}
15891 
15892 	local_time = (mblk_t *)now;
15893 
15894 	/*
15895 	 * "Our" Nagle Algorithm.  This is not the same as in the old
15896 	 * BSD.  This is more in line with the true intent of Nagle.
15897 	 *
15898 	 * The conditions are:
15899 	 * 1. The amount of unsent data (or amount of data which can be
15900 	 *    sent, whichever is smaller) is less than Nagle limit.
15901 	 * 2. The last sent size is also less than Nagle limit.
15902 	 * 3. There is unack'ed data.
15903 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
15904 	 *    Nagle algorithm.  This reduces the probability that urgent
15905 	 *    bytes get "merged" together.
15906 	 * 5. The app has not closed the connection.  This eliminates the
15907 	 *    wait time of the receiving side waiting for the last piece of
15908 	 *    (small) data.
15909 	 *
15910 	 * If all are satisified, exit without sending anything.  Note
15911 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
15912 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
15913 	 * 4095).
15914 	 */
15915 	if (usable < (int)tcp->tcp_naglim &&
15916 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
15917 	    snxt != tcp->tcp_suna &&
15918 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
15919 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
15920 		goto done;
15921 	}
15922 
15923 	/*
15924 	 * If tcp_zero_win_probe is not set and the tcp->tcp_cork option
15925 	 * is set, then we have to force TCP not to send partial segment
15926 	 * (smaller than MSS bytes). We are calculating the usable now
15927 	 * based on full mss and will save the rest of remaining data for
15928 	 * later. When tcp_zero_win_probe is set, TCP needs to send out
15929 	 * something to do zero window probe.
15930 	 */
15931 	if (tcp->tcp_cork && !tcp->tcp_zero_win_probe) {
15932 		if (usable < mss)
15933 			goto done;
15934 		usable = (usable / mss) * mss;
15935 	}
15936 
15937 	/* Update the latest receive window size in TCP header. */
15938 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
15939 
15940 	/* Send the packet. */
15941 	rc = tcp_send(tcp, mss, total_hdr_len, tcp_hdr_len,
15942 	    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
15943 	    local_time);
15944 
15945 	/* Pretend that all we were trying to send really got sent */
15946 	if (rc < 0 && tail_unsent < 0) {
15947 		do {
15948 			xmit_tail = xmit_tail->b_cont;
15949 			xmit_tail->b_prev = local_time;
15950 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
15951 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
15952 			tail_unsent += (int)(xmit_tail->b_wptr -
15953 			    xmit_tail->b_rptr);
15954 		} while (tail_unsent < 0);
15955 	}
15956 done:;
15957 	tcp->tcp_xmit_tail = xmit_tail;
15958 	tcp->tcp_xmit_tail_unsent = tail_unsent;
15959 	len = tcp->tcp_snxt - snxt;
15960 	if (len) {
15961 		/*
15962 		 * If new data was sent, need to update the notsack
15963 		 * list, which is, afterall, data blocks that have
15964 		 * not been sack'ed by the receiver.  New data is
15965 		 * not sack'ed.
15966 		 */
15967 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
15968 			/* len is a negative value. */
15969 			tcp->tcp_pipe -= len;
15970 			tcp_notsack_update(&(tcp->tcp_notsack_list),
15971 			    tcp->tcp_snxt, snxt,
15972 			    &(tcp->tcp_num_notsack_blk),
15973 			    &(tcp->tcp_cnt_notsack_list));
15974 		}
15975 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
15976 		tcp->tcp_rack = tcp->tcp_rnxt;
15977 		tcp->tcp_rack_cnt = 0;
15978 		if ((snxt + len) == tcp->tcp_suna) {
15979 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15980 		}
15981 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
15982 		/*
15983 		 * Didn't send anything. Make sure the timer is running
15984 		 * so that we will probe a zero window.
15985 		 */
15986 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
15987 	}
15988 	/* Note that len is the amount we just sent but with a negative sign */
15989 	tcp->tcp_unsent += len;
15990 	mutex_enter(&tcp->tcp_non_sq_lock);
15991 	if (tcp->tcp_flow_stopped) {
15992 		if (TCP_UNSENT_BYTES(tcp) <= connp->conn_sndlowat) {
15993 			tcp_clrqfull(tcp);
15994 		}
15995 	} else if (TCP_UNSENT_BYTES(tcp) >= connp->conn_sndbuf) {
15996 		if (!(tcp->tcp_detached))
15997 			tcp_setqfull(tcp);
15998 	}
15999 	mutex_exit(&tcp->tcp_non_sq_lock);
16000 }
16001 
16002 /*
16003  * tcp_fill_header is called by tcp_send() to fill the outgoing TCP header
16004  * with the template header, as well as other options such as time-stamp,
16005  * ECN and/or SACK.
16006  */
16007 static void
16008 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
16009 {
16010 	tcpha_t *tcp_tmpl, *tcpha;
16011 	uint32_t *dst, *src;
16012 	int hdrlen;
16013 	conn_t *connp = tcp->tcp_connp;
16014 
16015 	ASSERT(OK_32PTR(rptr));
16016 
16017 	/* Template header */
16018 	tcp_tmpl = tcp->tcp_tcpha;
16019 
16020 	/* Header of outgoing packet */
16021 	tcpha = (tcpha_t *)(rptr + connp->conn_ixa->ixa_ip_hdr_length);
16022 
16023 	/* dst and src are opaque 32-bit fields, used for copying */
16024 	dst = (uint32_t *)rptr;
16025 	src = (uint32_t *)connp->conn_ht_iphc;
16026 	hdrlen = connp->conn_ht_iphc_len;
16027 
16028 	/* Fill time-stamp option if needed */
16029 	if (tcp->tcp_snd_ts_ok) {
16030 		U32_TO_BE32((uint32_t)now,
16031 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
16032 		U32_TO_BE32(tcp->tcp_ts_recent,
16033 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
16034 	} else {
16035 		ASSERT(connp->conn_ht_ulp_len == TCP_MIN_HEADER_LENGTH);
16036 	}
16037 
16038 	/*
16039 	 * Copy the template header; is this really more efficient than
16040 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
16041 	 * but perhaps not for other scenarios.
16042 	 */
16043 	dst[0] = src[0];
16044 	dst[1] = src[1];
16045 	dst[2] = src[2];
16046 	dst[3] = src[3];
16047 	dst[4] = src[4];
16048 	dst[5] = src[5];
16049 	dst[6] = src[6];
16050 	dst[7] = src[7];
16051 	dst[8] = src[8];
16052 	dst[9] = src[9];
16053 	if (hdrlen -= 40) {
16054 		hdrlen >>= 2;
16055 		dst += 10;
16056 		src += 10;
16057 		do {
16058 			*dst++ = *src++;
16059 		} while (--hdrlen);
16060 	}
16061 
16062 	/*
16063 	 * Set the ECN info in the TCP header if it is not a zero
16064 	 * window probe.  Zero window probe is only sent in
16065 	 * tcp_wput_data() and tcp_timer().
16066 	 */
16067 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
16068 		SET_ECT(tcp, rptr);
16069 
16070 		if (tcp->tcp_ecn_echo_on)
16071 			tcpha->tha_flags |= TH_ECE;
16072 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
16073 			tcpha->tha_flags |= TH_CWR;
16074 			tcp->tcp_ecn_cwr_sent = B_TRUE;
16075 		}
16076 	}
16077 
16078 	/* Fill in SACK options */
16079 	if (num_sack_blk > 0) {
16080 		uchar_t *wptr = rptr + connp->conn_ht_iphc_len;
16081 		sack_blk_t *tmp;
16082 		int32_t	i;
16083 
16084 		wptr[0] = TCPOPT_NOP;
16085 		wptr[1] = TCPOPT_NOP;
16086 		wptr[2] = TCPOPT_SACK;
16087 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
16088 		    sizeof (sack_blk_t);
16089 		wptr += TCPOPT_REAL_SACK_LEN;
16090 
16091 		tmp = tcp->tcp_sack_list;
16092 		for (i = 0; i < num_sack_blk; i++) {
16093 			U32_TO_BE32(tmp[i].begin, wptr);
16094 			wptr += sizeof (tcp_seq);
16095 			U32_TO_BE32(tmp[i].end, wptr);
16096 			wptr += sizeof (tcp_seq);
16097 		}
16098 		tcpha->tha_offset_and_reserved +=
16099 		    ((num_sack_blk * 2 + 1) << 4);
16100 	}
16101 }
16102 
16103 /*
16104  * tcp_send() is called by tcp_wput_data() and returns one of the following:
16105  *
16106  * -1 = failed allocation.
16107  *  0 = success; burst count reached, or usable send window is too small,
16108  *      and that we'd rather wait until later before sending again.
16109  */
16110 static int
16111 tcp_send(tcp_t *tcp, const int mss, const int total_hdr_len,
16112     const int tcp_hdr_len, const int num_sack_blk, int *usable,
16113     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time)
16114 {
16115 	int		num_burst_seg = tcp->tcp_snd_burst;
16116 	int		num_lso_seg = 1;
16117 	uint_t		lso_usable;
16118 	boolean_t	do_lso_send = B_FALSE;
16119 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16120 	conn_t		*connp = tcp->tcp_connp;
16121 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
16122 
16123 	/*
16124 	 * Check LSO possibility. The value of tcp->tcp_lso indicates whether
16125 	 * the underlying connection is LSO capable. Will check whether having
16126 	 * enough available data to initiate LSO transmission in the for(){}
16127 	 * loops.
16128 	 */
16129 	if (tcp->tcp_lso && (tcp->tcp_valid_bits & ~TCP_FSS_VALID) == 0)
16130 			do_lso_send = B_TRUE;
16131 
16132 	for (;;) {
16133 		struct datab	*db;
16134 		tcpha_t		*tcpha;
16135 		uint32_t	sum;
16136 		mblk_t		*mp, *mp1;
16137 		uchar_t		*rptr;
16138 		int		len;
16139 
16140 		/*
16141 		 * Burst count reached, return successfully.
16142 		 */
16143 		if (num_burst_seg == 0)
16144 			break;
16145 
16146 		/*
16147 		 * Calculate the maximum payload length we can send at one
16148 		 * time.
16149 		 */
16150 		if (do_lso_send) {
16151 			/*
16152 			 * Check whether be able to to do LSO for the current
16153 			 * available data.
16154 			 */
16155 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
16156 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
16157 				lso_usable = MIN(lso_usable,
16158 				    num_burst_seg * mss);
16159 
16160 				num_lso_seg = lso_usable / mss;
16161 				if (lso_usable % mss) {
16162 					num_lso_seg++;
16163 					tcp->tcp_last_sent_len = (ushort_t)
16164 					    (lso_usable % mss);
16165 				} else {
16166 					tcp->tcp_last_sent_len = (ushort_t)mss;
16167 				}
16168 			} else {
16169 				do_lso_send = B_FALSE;
16170 				num_lso_seg = 1;
16171 				lso_usable = mss;
16172 			}
16173 		}
16174 
16175 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
16176 #ifdef DEBUG
16177 		DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg, boolean_t,
16178 		    do_lso_send);
16179 #endif
16180 		/*
16181 		 * Adjust num_burst_seg here.
16182 		 */
16183 		num_burst_seg -= num_lso_seg;
16184 
16185 		len = mss;
16186 		if (len > *usable) {
16187 			ASSERT(do_lso_send == B_FALSE);
16188 
16189 			len = *usable;
16190 			if (len <= 0) {
16191 				/* Terminate the loop */
16192 				break;	/* success; too small */
16193 			}
16194 			/*
16195 			 * Sender silly-window avoidance.
16196 			 * Ignore this if we are going to send a
16197 			 * zero window probe out.
16198 			 *
16199 			 * TODO: force data into microscopic window?
16200 			 *	==> (!pushed || (unsent > usable))
16201 			 */
16202 			if (len < (tcp->tcp_max_swnd >> 1) &&
16203 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
16204 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
16205 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
16206 				/*
16207 				 * If the retransmit timer is not running
16208 				 * we start it so that we will retransmit
16209 				 * in the case when the receiver has
16210 				 * decremented the window.
16211 				 */
16212 				if (*snxt == tcp->tcp_snxt &&
16213 				    *snxt == tcp->tcp_suna) {
16214 					/*
16215 					 * We are not supposed to send
16216 					 * anything.  So let's wait a little
16217 					 * bit longer before breaking SWS
16218 					 * avoidance.
16219 					 *
16220 					 * What should the value be?
16221 					 * Suggestion: MAX(init rexmit time,
16222 					 * tcp->tcp_rto)
16223 					 */
16224 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16225 				}
16226 				break;	/* success; too small */
16227 			}
16228 		}
16229 
16230 		tcpha = tcp->tcp_tcpha;
16231 
16232 		/*
16233 		 * The reason to adjust len here is that we need to set flags
16234 		 * and calculate checksum.
16235 		 */
16236 		if (do_lso_send)
16237 			len = lso_usable;
16238 
16239 		*usable -= len; /* Approximate - can be adjusted later */
16240 		if (*usable > 0)
16241 			tcpha->tha_flags = TH_ACK;
16242 		else
16243 			tcpha->tha_flags = (TH_ACK | TH_PUSH);
16244 
16245 		/*
16246 		 * Prime pump for IP's checksumming on our behalf.
16247 		 * Include the adjustment for a source route if any.
16248 		 * In case of LSO, the partial pseudo-header checksum should
16249 		 * exclusive TCP length, so zero tha_sum before IP calculate
16250 		 * pseudo-header checksum for partial checksum offload.
16251 		 */
16252 		if (do_lso_send) {
16253 			sum = 0;
16254 		} else {
16255 			sum = len + tcp_hdr_len + connp->conn_sum;
16256 			sum = (sum >> 16) + (sum & 0xFFFF);
16257 		}
16258 		tcpha->tha_sum = htons(sum);
16259 		tcpha->tha_seq = htonl(*snxt);
16260 
16261 		/*
16262 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
16263 		 * set.  For the case when TCP_FSS_VALID is the only valid
16264 		 * bit (normal active close), branch off only when we think
16265 		 * that the FIN flag needs to be set.  Note for this case,
16266 		 * that (snxt + len) may not reflect the actual seg_len,
16267 		 * as len may be further reduced in tcp_xmit_mp().  If len
16268 		 * gets modified, we will end up here again.
16269 		 */
16270 		if (tcp->tcp_valid_bits != 0 &&
16271 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
16272 		    ((*snxt + len) == tcp->tcp_fss))) {
16273 			uchar_t		*prev_rptr;
16274 			uint32_t	prev_snxt = tcp->tcp_snxt;
16275 
16276 			if (*tail_unsent == 0) {
16277 				ASSERT((*xmit_tail)->b_cont != NULL);
16278 				*xmit_tail = (*xmit_tail)->b_cont;
16279 				prev_rptr = (*xmit_tail)->b_rptr;
16280 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
16281 				    (*xmit_tail)->b_rptr);
16282 			} else {
16283 				prev_rptr = (*xmit_tail)->b_rptr;
16284 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
16285 				    *tail_unsent;
16286 			}
16287 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
16288 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
16289 			/* Restore tcp_snxt so we get amount sent right. */
16290 			tcp->tcp_snxt = prev_snxt;
16291 			if (prev_rptr == (*xmit_tail)->b_rptr) {
16292 				/*
16293 				 * If the previous timestamp is still in use,
16294 				 * don't stomp on it.
16295 				 */
16296 				if ((*xmit_tail)->b_next == NULL) {
16297 					(*xmit_tail)->b_prev = local_time;
16298 					(*xmit_tail)->b_next =
16299 					    (mblk_t *)(uintptr_t)(*snxt);
16300 				}
16301 			} else
16302 				(*xmit_tail)->b_rptr = prev_rptr;
16303 
16304 			if (mp == NULL) {
16305 				return (-1);
16306 			}
16307 			mp1 = mp->b_cont;
16308 
16309 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
16310 				tcp->tcp_last_sent_len = (ushort_t)len;
16311 			while (mp1->b_cont) {
16312 				*xmit_tail = (*xmit_tail)->b_cont;
16313 				(*xmit_tail)->b_prev = local_time;
16314 				(*xmit_tail)->b_next =
16315 				    (mblk_t *)(uintptr_t)(*snxt);
16316 				mp1 = mp1->b_cont;
16317 			}
16318 			*snxt += len;
16319 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
16320 			BUMP_LOCAL(tcp->tcp_obsegs);
16321 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16322 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16323 			tcp_send_data(tcp, mp);
16324 			continue;
16325 		}
16326 
16327 		*snxt += len;	/* Adjust later if we don't send all of len */
16328 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
16329 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
16330 
16331 		if (*tail_unsent) {
16332 			/* Are the bytes above us in flight? */
16333 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
16334 			if (rptr != (*xmit_tail)->b_rptr) {
16335 				*tail_unsent -= len;
16336 				if (len <= mss) /* LSO is unusable */
16337 					tcp->tcp_last_sent_len = (ushort_t)len;
16338 				len += total_hdr_len;
16339 				ixa->ixa_pktlen = len;
16340 
16341 				if (ixa->ixa_flags & IXAF_IS_IPV4) {
16342 					tcp->tcp_ipha->ipha_length = htons(len);
16343 				} else {
16344 					tcp->tcp_ip6h->ip6_plen =
16345 					    htons(len - IPV6_HDR_LEN);
16346 				}
16347 
16348 				mp = dupb(*xmit_tail);
16349 				if (mp == NULL) {
16350 					return (-1);	/* out_of_mem */
16351 				}
16352 				mp->b_rptr = rptr;
16353 				/*
16354 				 * If the old timestamp is no longer in use,
16355 				 * sample a new timestamp now.
16356 				 */
16357 				if ((*xmit_tail)->b_next == NULL) {
16358 					(*xmit_tail)->b_prev = local_time;
16359 					(*xmit_tail)->b_next =
16360 					    (mblk_t *)(uintptr_t)(*snxt-len);
16361 				}
16362 				goto must_alloc;
16363 			}
16364 		} else {
16365 			*xmit_tail = (*xmit_tail)->b_cont;
16366 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
16367 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
16368 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
16369 			    (*xmit_tail)->b_rptr);
16370 		}
16371 
16372 		(*xmit_tail)->b_prev = local_time;
16373 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
16374 
16375 		*tail_unsent -= len;
16376 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
16377 			tcp->tcp_last_sent_len = (ushort_t)len;
16378 
16379 		len += total_hdr_len;
16380 		ixa->ixa_pktlen = len;
16381 
16382 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
16383 			tcp->tcp_ipha->ipha_length = htons(len);
16384 		} else {
16385 			tcp->tcp_ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
16386 		}
16387 
16388 		mp = dupb(*xmit_tail);
16389 		if (mp == NULL) {
16390 			return (-1);	/* out_of_mem */
16391 		}
16392 
16393 		len = total_hdr_len;
16394 		/*
16395 		 * There are four reasons to allocate a new hdr mblk:
16396 		 *  1) The bytes above us are in use by another packet
16397 		 *  2) We don't have good alignment
16398 		 *  3) The mblk is being shared
16399 		 *  4) We don't have enough room for a header
16400 		 */
16401 		rptr = mp->b_rptr - len;
16402 		if (!OK_32PTR(rptr) ||
16403 		    ((db = mp->b_datap), db->db_ref != 2) ||
16404 		    rptr < db->db_base) {
16405 			/* NOTE: we assume allocb returns an OK_32PTR */
16406 
16407 		must_alloc:;
16408 			mp1 = allocb(connp->conn_ht_iphc_allocated +
16409 			    tcps->tcps_wroff_xtra, BPRI_MED);
16410 			if (mp1 == NULL) {
16411 				freemsg(mp);
16412 				return (-1);	/* out_of_mem */
16413 			}
16414 			mp1->b_cont = mp;
16415 			mp = mp1;
16416 			/* Leave room for Link Level header */
16417 			len = total_hdr_len;
16418 			rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
16419 			mp->b_wptr = &rptr[len];
16420 		}
16421 
16422 		/*
16423 		 * Fill in the header using the template header, and add
16424 		 * options such as time-stamp, ECN and/or SACK, as needed.
16425 		 */
16426 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
16427 
16428 		mp->b_rptr = rptr;
16429 
16430 		if (*tail_unsent) {
16431 			int spill = *tail_unsent;
16432 
16433 			mp1 = mp->b_cont;
16434 			if (mp1 == NULL)
16435 				mp1 = mp;
16436 
16437 			/*
16438 			 * If we're a little short, tack on more mblks until
16439 			 * there is no more spillover.
16440 			 */
16441 			while (spill < 0) {
16442 				mblk_t *nmp;
16443 				int nmpsz;
16444 
16445 				nmp = (*xmit_tail)->b_cont;
16446 				nmpsz = MBLKL(nmp);
16447 
16448 				/*
16449 				 * Excess data in mblk; can we split it?
16450 				 * If LSO is enabled for the connection,
16451 				 * keep on splitting as this is a transient
16452 				 * send path.
16453 				 */
16454 				if (!do_lso_send && (spill + nmpsz > 0)) {
16455 					/*
16456 					 * Don't split if stream head was
16457 					 * told to break up larger writes
16458 					 * into smaller ones.
16459 					 */
16460 					if (tcp->tcp_maxpsz_multiplier > 0)
16461 						break;
16462 
16463 					/*
16464 					 * Next mblk is less than SMSS/2
16465 					 * rounded up to nearest 64-byte;
16466 					 * let it get sent as part of the
16467 					 * next segment.
16468 					 */
16469 					if (tcp->tcp_localnet &&
16470 					    !tcp->tcp_cork &&
16471 					    (nmpsz < roundup((mss >> 1), 64)))
16472 						break;
16473 				}
16474 
16475 				*xmit_tail = nmp;
16476 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
16477 				/* Stash for rtt use later */
16478 				(*xmit_tail)->b_prev = local_time;
16479 				(*xmit_tail)->b_next =
16480 				    (mblk_t *)(uintptr_t)(*snxt - len);
16481 				mp1->b_cont = dupb(*xmit_tail);
16482 				mp1 = mp1->b_cont;
16483 
16484 				spill += nmpsz;
16485 				if (mp1 == NULL) {
16486 					*tail_unsent = spill;
16487 					freemsg(mp);
16488 					return (-1);	/* out_of_mem */
16489 				}
16490 			}
16491 
16492 			/* Trim back any surplus on the last mblk */
16493 			if (spill >= 0) {
16494 				mp1->b_wptr -= spill;
16495 				*tail_unsent = spill;
16496 			} else {
16497 				/*
16498 				 * We did not send everything we could in
16499 				 * order to remain within the b_cont limit.
16500 				 */
16501 				*usable -= spill;
16502 				*snxt += spill;
16503 				tcp->tcp_last_sent_len += spill;
16504 				UPDATE_MIB(&tcps->tcps_mib,
16505 				    tcpOutDataBytes, spill);
16506 				/*
16507 				 * Adjust the checksum
16508 				 */
16509 				tcpha = (tcpha_t *)(rptr +
16510 				    ixa->ixa_ip_hdr_length);
16511 				sum += spill;
16512 				sum = (sum >> 16) + (sum & 0xFFFF);
16513 				tcpha->tha_sum = htons(sum);
16514 				if (connp->conn_ipversion == IPV4_VERSION) {
16515 					sum = ntohs(
16516 					    ((ipha_t *)rptr)->ipha_length) +
16517 					    spill;
16518 					((ipha_t *)rptr)->ipha_length =
16519 					    htons(sum);
16520 				} else {
16521 					sum = ntohs(
16522 					    ((ip6_t *)rptr)->ip6_plen) +
16523 					    spill;
16524 					((ip6_t *)rptr)->ip6_plen =
16525 					    htons(sum);
16526 				}
16527 				ixa->ixa_pktlen += spill;
16528 				*tail_unsent = 0;
16529 			}
16530 		}
16531 		if (tcp->tcp_ip_forward_progress) {
16532 			tcp->tcp_ip_forward_progress = B_FALSE;
16533 			ixa->ixa_flags |= IXAF_REACH_CONF;
16534 		} else {
16535 			ixa->ixa_flags &= ~IXAF_REACH_CONF;
16536 		}
16537 
16538 		/*
16539 		 * Append LSO information, both flags and mss, to the mp.
16540 		 */
16541 		if (do_lso_send) {
16542 			lso_info_set(mp, mss, HW_LSO);
16543 			ixa->ixa_fragsize = IP_MAXPACKET;
16544 			ixa->ixa_extra_ident = num_lso_seg - 1;
16545 
16546 			DTRACE_PROBE2(tcp_send_lso, int, num_lso_seg,
16547 			    boolean_t, B_TRUE);
16548 
16549 			tcp_send_data(tcp, mp);
16550 
16551 			/*
16552 			 * Restore values of ixa_fragsize and ixa_extra_ident.
16553 			 */
16554 			ixa->ixa_fragsize = ixa->ixa_pmtu;
16555 			ixa->ixa_extra_ident = 0;
16556 			tcp->tcp_obsegs += num_lso_seg;
16557 			TCP_STAT(tcps, tcp_lso_times);
16558 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
16559 		} else {
16560 			tcp_send_data(tcp, mp);
16561 			BUMP_LOCAL(tcp->tcp_obsegs);
16562 		}
16563 	}
16564 
16565 	return (0);
16566 }
16567 
16568 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
16569 static void
16570 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
16571 {
16572 	uchar_t	fval = *mp->b_rptr;
16573 	mblk_t	*tail;
16574 	conn_t	*connp = tcp->tcp_connp;
16575 	queue_t	*q = connp->conn_wq;
16576 
16577 	/* TODO: How should flush interact with urgent data? */
16578 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
16579 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
16580 		/*
16581 		 * Flush only data that has not yet been put on the wire.  If
16582 		 * we flush data that we have already transmitted, life, as we
16583 		 * know it, may come to an end.
16584 		 */
16585 		tail = tcp->tcp_xmit_tail;
16586 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
16587 		tcp->tcp_xmit_tail_unsent = 0;
16588 		tcp->tcp_unsent = 0;
16589 		if (tail->b_wptr != tail->b_rptr)
16590 			tail = tail->b_cont;
16591 		if (tail) {
16592 			mblk_t **excess = &tcp->tcp_xmit_head;
16593 			for (;;) {
16594 				mblk_t *mp1 = *excess;
16595 				if (mp1 == tail)
16596 					break;
16597 				tcp->tcp_xmit_tail = mp1;
16598 				tcp->tcp_xmit_last = mp1;
16599 				excess = &mp1->b_cont;
16600 			}
16601 			*excess = NULL;
16602 			tcp_close_mpp(&tail);
16603 			if (tcp->tcp_snd_zcopy_aware)
16604 				tcp_zcopy_notify(tcp);
16605 		}
16606 		/*
16607 		 * We have no unsent data, so unsent must be less than
16608 		 * conn_sndlowat, so re-enable flow.
16609 		 */
16610 		mutex_enter(&tcp->tcp_non_sq_lock);
16611 		if (tcp->tcp_flow_stopped) {
16612 			tcp_clrqfull(tcp);
16613 		}
16614 		mutex_exit(&tcp->tcp_non_sq_lock);
16615 	}
16616 	/*
16617 	 * TODO: you can't just flush these, you have to increase rwnd for one
16618 	 * thing.  For another, how should urgent data interact?
16619 	 */
16620 	if (fval & FLUSHR) {
16621 		*mp->b_rptr = fval & ~FLUSHW;
16622 		/* XXX */
16623 		qreply(q, mp);
16624 		return;
16625 	}
16626 	freemsg(mp);
16627 }
16628 
16629 /*
16630  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
16631  * messages.
16632  */
16633 static void
16634 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
16635 {
16636 	mblk_t		*mp1;
16637 	struct iocblk	*iocp = (struct iocblk *)mp->b_rptr;
16638 	STRUCT_HANDLE(strbuf, sb);
16639 	uint_t		addrlen;
16640 	conn_t		*connp = tcp->tcp_connp;
16641 	queue_t 	*q = connp->conn_wq;
16642 
16643 	/* Make sure it is one of ours. */
16644 	switch (iocp->ioc_cmd) {
16645 	case TI_GETMYNAME:
16646 	case TI_GETPEERNAME:
16647 		break;
16648 	default:
16649 		ip_wput_nondata(q, mp);
16650 		return;
16651 	}
16652 	switch (mi_copy_state(q, mp, &mp1)) {
16653 	case -1:
16654 		return;
16655 	case MI_COPY_CASE(MI_COPY_IN, 1):
16656 		break;
16657 	case MI_COPY_CASE(MI_COPY_OUT, 1):
16658 		/* Copy out the strbuf. */
16659 		mi_copyout(q, mp);
16660 		return;
16661 	case MI_COPY_CASE(MI_COPY_OUT, 2):
16662 		/* All done. */
16663 		mi_copy_done(q, mp, 0);
16664 		return;
16665 	default:
16666 		mi_copy_done(q, mp, EPROTO);
16667 		return;
16668 	}
16669 	/* Check alignment of the strbuf */
16670 	if (!OK_32PTR(mp1->b_rptr)) {
16671 		mi_copy_done(q, mp, EINVAL);
16672 		return;
16673 	}
16674 
16675 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
16676 
16677 	if (connp->conn_family == AF_INET)
16678 		addrlen = sizeof (sin_t);
16679 	else
16680 		addrlen = sizeof (sin6_t);
16681 
16682 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
16683 		mi_copy_done(q, mp, EINVAL);
16684 		return;
16685 	}
16686 
16687 	switch (iocp->ioc_cmd) {
16688 	case TI_GETMYNAME:
16689 		break;
16690 	case TI_GETPEERNAME:
16691 		if (tcp->tcp_state < TCPS_SYN_RCVD) {
16692 			mi_copy_done(q, mp, ENOTCONN);
16693 			return;
16694 		}
16695 		break;
16696 	}
16697 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
16698 	if (!mp1)
16699 		return;
16700 
16701 	STRUCT_FSET(sb, len, addrlen);
16702 	switch (((struct iocblk *)mp->b_rptr)->ioc_cmd) {
16703 	case TI_GETMYNAME:
16704 		(void) conn_getsockname(connp, (struct sockaddr *)mp1->b_wptr,
16705 		    &addrlen);
16706 		break;
16707 	case TI_GETPEERNAME:
16708 		(void) conn_getpeername(connp, (struct sockaddr *)mp1->b_wptr,
16709 		    &addrlen);
16710 		break;
16711 	}
16712 	mp1->b_wptr += addrlen;
16713 	/* Copy out the address */
16714 	mi_copyout(q, mp);
16715 }
16716 
16717 static void
16718 tcp_use_pure_tpi(tcp_t *tcp)
16719 {
16720 	conn_t		*connp = tcp->tcp_connp;
16721 
16722 #ifdef	_ILP32
16723 	tcp->tcp_acceptor_id = (t_uscalar_t)connp->conn_rq;
16724 #else
16725 	tcp->tcp_acceptor_id = connp->conn_dev;
16726 #endif
16727 	/*
16728 	 * Insert this socket into the acceptor hash.
16729 	 * We might need it for T_CONN_RES message
16730 	 */
16731 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
16732 
16733 	tcp->tcp_issocket = B_FALSE;
16734 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
16735 }
16736 
16737 /*
16738  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
16739  * messages.
16740  */
16741 /* ARGSUSED */
16742 static void
16743 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16744 {
16745 	conn_t 		*connp = (conn_t *)arg;
16746 	tcp_t		*tcp = connp->conn_tcp;
16747 	queue_t		*q = connp->conn_wq;
16748 	struct iocblk	*iocp;
16749 
16750 	ASSERT(DB_TYPE(mp) == M_IOCTL);
16751 	/*
16752 	 * Try and ASSERT the minimum possible references on the
16753 	 * conn early enough. Since we are executing on write side,
16754 	 * the connection is obviously not detached and that means
16755 	 * there is a ref each for TCP and IP. Since we are behind
16756 	 * the squeue, the minimum references needed are 3. If the
16757 	 * conn is in classifier hash list, there should be an
16758 	 * extra ref for that (we check both the possibilities).
16759 	 */
16760 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16761 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16762 
16763 	iocp = (struct iocblk *)mp->b_rptr;
16764 	switch (iocp->ioc_cmd) {
16765 	case _SIOCSOCKFALLBACK:
16766 		/*
16767 		 * Either sockmod is about to be popped and the socket
16768 		 * would now be treated as a plain stream, or a module
16769 		 * is about to be pushed so we could no longer use read-
16770 		 * side synchronous streams for fused loopback tcp.
16771 		 * Drain any queued data and disable direct sockfs
16772 		 * interface from now on.
16773 		 */
16774 		if (!tcp->tcp_issocket) {
16775 			DB_TYPE(mp) = M_IOCNAK;
16776 			iocp->ioc_error = EINVAL;
16777 		} else {
16778 			tcp_use_pure_tpi(tcp);
16779 			DB_TYPE(mp) = M_IOCACK;
16780 			iocp->ioc_error = 0;
16781 		}
16782 		iocp->ioc_count = 0;
16783 		iocp->ioc_rval = 0;
16784 		qreply(q, mp);
16785 		return;
16786 	}
16787 	ip_wput_nondata(q, mp);
16788 }
16789 
16790 /*
16791  * This routine is called by tcp_wput() to handle all TPI requests.
16792  */
16793 /* ARGSUSED */
16794 static void
16795 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
16796 {
16797 	conn_t		*connp = (conn_t *)arg;
16798 	tcp_t		*tcp = connp->conn_tcp;
16799 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
16800 	uchar_t		*rptr;
16801 	t_scalar_t	type;
16802 	cred_t		*cr;
16803 
16804 	/*
16805 	 * Try and ASSERT the minimum possible references on the
16806 	 * conn early enough. Since we are executing on write side,
16807 	 * the connection is obviously not detached and that means
16808 	 * there is a ref each for TCP and IP. Since we are behind
16809 	 * the squeue, the minimum references needed are 3. If the
16810 	 * conn is in classifier hash list, there should be an
16811 	 * extra ref for that (we check both the possibilities).
16812 	 */
16813 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
16814 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
16815 
16816 	rptr = mp->b_rptr;
16817 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
16818 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
16819 		type = ((union T_primitives *)rptr)->type;
16820 		if (type == T_EXDATA_REQ) {
16821 			tcp_output_urgent(connp, mp, arg2, NULL);
16822 		} else if (type != T_DATA_REQ) {
16823 			goto non_urgent_data;
16824 		} else {
16825 			/* TODO: options, flags, ... from user */
16826 			/* Set length to zero for reclamation below */
16827 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
16828 			freeb(mp);
16829 		}
16830 		return;
16831 	} else {
16832 		if (connp->conn_debug) {
16833 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
16834 			    "tcp_wput_proto, dropping one...");
16835 		}
16836 		freemsg(mp);
16837 		return;
16838 	}
16839 
16840 non_urgent_data:
16841 
16842 	switch ((int)tprim->type) {
16843 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
16844 		/*
16845 		 * save the kssl_ent_t from the next block, and convert this
16846 		 * back to a normal bind_req.
16847 		 */
16848 		if (mp->b_cont != NULL) {
16849 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
16850 
16851 			if (tcp->tcp_kssl_ent != NULL) {
16852 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
16853 				    KSSL_NO_PROXY);
16854 				tcp->tcp_kssl_ent = NULL;
16855 			}
16856 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
16857 			    sizeof (kssl_ent_t));
16858 			kssl_hold_ent(tcp->tcp_kssl_ent);
16859 			freemsg(mp->b_cont);
16860 			mp->b_cont = NULL;
16861 		}
16862 		tprim->type = T_BIND_REQ;
16863 
16864 	/* FALLTHROUGH */
16865 	case O_T_BIND_REQ:	/* bind request */
16866 	case T_BIND_REQ:	/* new semantics bind request */
16867 		tcp_tpi_bind(tcp, mp);
16868 		break;
16869 	case T_UNBIND_REQ:	/* unbind request */
16870 		tcp_tpi_unbind(tcp, mp);
16871 		break;
16872 	case O_T_CONN_RES:	/* old connection response XXX */
16873 	case T_CONN_RES:	/* connection response */
16874 		tcp_tli_accept(tcp, mp);
16875 		break;
16876 	case T_CONN_REQ:	/* connection request */
16877 		tcp_tpi_connect(tcp, mp);
16878 		break;
16879 	case T_DISCON_REQ:	/* disconnect request */
16880 		tcp_disconnect(tcp, mp);
16881 		break;
16882 	case T_CAPABILITY_REQ:
16883 		tcp_capability_req(tcp, mp);	/* capability request */
16884 		break;
16885 	case T_INFO_REQ:	/* information request */
16886 		tcp_info_req(tcp, mp);
16887 		break;
16888 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
16889 	case T_OPTMGMT_REQ:
16890 		/*
16891 		 * Note:  no support for snmpcom_req() through new
16892 		 * T_OPTMGMT_REQ. See comments in ip.c
16893 		 */
16894 
16895 		/*
16896 		 * All Solaris components should pass a db_credp
16897 		 * for this TPI message, hence we ASSERT.
16898 		 * But in case there is some other M_PROTO that looks
16899 		 * like a TPI message sent by some other kernel
16900 		 * component, we check and return an error.
16901 		 */
16902 		cr = msg_getcred(mp, NULL);
16903 		ASSERT(cr != NULL);
16904 		if (cr == NULL) {
16905 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
16906 			return;
16907 		}
16908 		/*
16909 		 * If EINPROGRESS is returned, the request has been queued
16910 		 * for subsequent processing by ip_restart_optmgmt(), which
16911 		 * will do the CONN_DEC_REF().
16912 		 */
16913 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
16914 			svr4_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
16915 		} else {
16916 			tpi_optcom_req(connp->conn_wq, mp, cr, &tcp_opt_obj);
16917 		}
16918 		break;
16919 
16920 	case T_UNITDATA_REQ:	/* unitdata request */
16921 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
16922 		break;
16923 	case T_ORDREL_REQ:	/* orderly release req */
16924 		freemsg(mp);
16925 
16926 		if (tcp->tcp_fused)
16927 			tcp_unfuse(tcp);
16928 
16929 		if (tcp_xmit_end(tcp) != 0) {
16930 			/*
16931 			 * We were crossing FINs and got a reset from
16932 			 * the other side. Just ignore it.
16933 			 */
16934 			if (connp->conn_debug) {
16935 				(void) strlog(TCP_MOD_ID, 0, 1,
16936 				    SL_ERROR|SL_TRACE,
16937 				    "tcp_wput_proto, T_ORDREL_REQ out of "
16938 				    "state %s",
16939 				    tcp_display(tcp, NULL,
16940 				    DISP_ADDR_AND_PORT));
16941 			}
16942 		}
16943 		break;
16944 	case T_ADDR_REQ:
16945 		tcp_addr_req(tcp, mp);
16946 		break;
16947 	default:
16948 		if (connp->conn_debug) {
16949 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
16950 			    "tcp_wput_proto, bogus TPI msg, type %d",
16951 			    tprim->type);
16952 		}
16953 		/*
16954 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
16955 		 * to recover.
16956 		 */
16957 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
16958 		break;
16959 	}
16960 }
16961 
16962 /*
16963  * The TCP write service routine should never be called...
16964  */
16965 /* ARGSUSED */
16966 static void
16967 tcp_wsrv(queue_t *q)
16968 {
16969 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16970 
16971 	TCP_STAT(tcps, tcp_wsrv_called);
16972 }
16973 
16974 /*
16975  * Send out a control packet on the tcp connection specified.  This routine
16976  * is typically called where we need a simple ACK or RST generated.
16977  */
16978 static void
16979 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
16980 {
16981 	uchar_t		*rptr;
16982 	tcpha_t		*tcpha;
16983 	ipha_t		*ipha = NULL;
16984 	ip6_t		*ip6h = NULL;
16985 	uint32_t	sum;
16986 	int		total_hdr_len;
16987 	int		ip_hdr_len;
16988 	mblk_t		*mp;
16989 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16990 	conn_t		*connp = tcp->tcp_connp;
16991 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
16992 
16993 	/*
16994 	 * Save sum for use in source route later.
16995 	 */
16996 	sum = connp->conn_ht_ulp_len + connp->conn_sum;
16997 	total_hdr_len = connp->conn_ht_iphc_len;
16998 	ip_hdr_len = ixa->ixa_ip_hdr_length;
16999 
17000 	/* If a text string is passed in with the request, pass it to strlog. */
17001 	if (str != NULL && connp->conn_debug) {
17002 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17003 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
17004 		    str, seq, ack, ctl);
17005 	}
17006 	mp = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17007 	    BPRI_MED);
17008 	if (mp == NULL) {
17009 		return;
17010 	}
17011 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
17012 	mp->b_rptr = rptr;
17013 	mp->b_wptr = &rptr[total_hdr_len];
17014 	bcopy(connp->conn_ht_iphc, rptr, total_hdr_len);
17015 
17016 	ixa->ixa_pktlen = total_hdr_len;
17017 
17018 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
17019 		ipha = (ipha_t *)rptr;
17020 		ipha->ipha_length = htons(total_hdr_len);
17021 	} else {
17022 		ip6h = (ip6_t *)rptr;
17023 		ip6h->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
17024 	}
17025 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17026 	tcpha->tha_flags = (uint8_t)ctl;
17027 	if (ctl & TH_RST) {
17028 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17029 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17030 		/*
17031 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
17032 		 */
17033 		if (tcp->tcp_snd_ts_ok &&
17034 		    tcp->tcp_state > TCPS_SYN_SENT) {
17035 			mp->b_wptr = &rptr[total_hdr_len - TCPOPT_REAL_TS_LEN];
17036 			*(mp->b_wptr) = TCPOPT_EOL;
17037 
17038 			ixa->ixa_pktlen = total_hdr_len - TCPOPT_REAL_TS_LEN;
17039 
17040 			if (connp->conn_ipversion == IPV4_VERSION) {
17041 				ipha->ipha_length = htons(total_hdr_len -
17042 				    TCPOPT_REAL_TS_LEN);
17043 			} else {
17044 				ip6h->ip6_plen = htons(total_hdr_len -
17045 				    IPV6_HDR_LEN - TCPOPT_REAL_TS_LEN);
17046 			}
17047 			tcpha->tha_offset_and_reserved -= (3 << 4);
17048 			sum -= TCPOPT_REAL_TS_LEN;
17049 		}
17050 	}
17051 	if (ctl & TH_ACK) {
17052 		if (tcp->tcp_snd_ts_ok) {
17053 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17054 
17055 			U32_TO_BE32(llbolt,
17056 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17057 			U32_TO_BE32(tcp->tcp_ts_recent,
17058 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17059 		}
17060 
17061 		/* Update the latest receive window size in TCP header. */
17062 		tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17063 		tcp->tcp_rack = ack;
17064 		tcp->tcp_rack_cnt = 0;
17065 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
17066 	}
17067 	BUMP_LOCAL(tcp->tcp_obsegs);
17068 	tcpha->tha_seq = htonl(seq);
17069 	tcpha->tha_ack = htonl(ack);
17070 	/*
17071 	 * Include the adjustment for a source route if any.
17072 	 */
17073 	sum = (sum >> 16) + (sum & 0xFFFF);
17074 	tcpha->tha_sum = htons(sum);
17075 	tcp_send_data(tcp, mp);
17076 }
17077 
17078 /*
17079  * If this routine returns B_TRUE, TCP can generate a RST in response
17080  * to a segment.  If it returns B_FALSE, TCP should not respond.
17081  */
17082 static boolean_t
17083 tcp_send_rst_chk(tcp_stack_t *tcps)
17084 {
17085 	int64_t	now;
17086 
17087 	/*
17088 	 * TCP needs to protect itself from generating too many RSTs.
17089 	 * This can be a DoS attack by sending us random segments
17090 	 * soliciting RSTs.
17091 	 *
17092 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
17093 	 * in each 1 second interval.  In this way, TCP still generate
17094 	 * RSTs in normal cases but when under attack, the impact is
17095 	 * limited.
17096 	 */
17097 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
17098 		now = ddi_get_lbolt64();
17099 		if (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
17100 		    1*SECONDS) {
17101 			tcps->tcps_last_rst_intrvl = now;
17102 			tcps->tcps_rst_cnt = 1;
17103 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
17104 			return (B_FALSE);
17105 		}
17106 	}
17107 	return (B_TRUE);
17108 }
17109 
17110 /*
17111  * Generate a reset based on an inbound packet, connp is set by caller
17112  * when RST is in response to an unexpected inbound packet for which
17113  * there is active tcp state in the system.
17114  *
17115  * IPSEC NOTE : Try to send the reply with the same protection as it came
17116  * in.  We have the ip_recv_attr_t which is reversed to form the ip_xmit_attr_t.
17117  * That way the packet will go out at the same level of protection as it
17118  * came in with.
17119  */
17120 static void
17121 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq, uint32_t ack, int ctl,
17122     ip_recv_attr_t *ira, ip_stack_t *ipst, conn_t *connp)
17123 {
17124 	ipha_t		*ipha = NULL;
17125 	ip6_t		*ip6h = NULL;
17126 	ushort_t	len;
17127 	tcpha_t		*tcpha;
17128 	int		i;
17129 	ipaddr_t	v4addr;
17130 	in6_addr_t	v6addr;
17131 	netstack_t	*ns = ipst->ips_netstack;
17132 	tcp_stack_t	*tcps = ns->netstack_tcp;
17133 	ip_xmit_attr_t	ixas, *ixa;
17134 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17135 	boolean_t	need_refrele = B_FALSE;		/* ixa_refrele(ixa) */
17136 	ushort_t	port;
17137 
17138 	if (!tcp_send_rst_chk(tcps)) {
17139 		TCP_STAT(tcps, tcp_rst_unsent);
17140 		freemsg(mp);
17141 		return;
17142 	}
17143 
17144 	/*
17145 	 * If connp != NULL we use conn_ixa to keep IP_NEXTHOP and other
17146 	 * options from the listener. In that case the caller must ensure that
17147 	 * we are running on the listener = connp squeue.
17148 	 *
17149 	 * We get a safe copy of conn_ixa so we don't need to restore anything
17150 	 * we or ip_output_simple might change in the ixa.
17151 	 */
17152 	if (connp != NULL) {
17153 		ASSERT(connp->conn_on_sqp);
17154 
17155 		ixa = conn_get_ixa_exclusive(connp);
17156 		if (ixa == NULL) {
17157 			TCP_STAT(tcps, tcp_rst_unsent);
17158 			freemsg(mp);
17159 			return;
17160 		}
17161 		need_refrele = B_TRUE;
17162 	} else {
17163 		bzero(&ixas, sizeof (ixas));
17164 		ixa = &ixas;
17165 		/*
17166 		 * IXAF_VERIFY_SOURCE is overkill since we know the
17167 		 * packet was for us.
17168 		 */
17169 		ixa->ixa_flags |= IXAF_SET_ULP_CKSUM | IXAF_VERIFY_SOURCE;
17170 		ixa->ixa_protocol = IPPROTO_TCP;
17171 		ixa->ixa_zoneid = ira->ira_zoneid;
17172 		ixa->ixa_ifindex = 0;
17173 		ixa->ixa_ipst = ipst;
17174 		ixa->ixa_cred = kcred;
17175 		ixa->ixa_cpid = NOPID;
17176 	}
17177 
17178 	if (str && tcps->tcps_dbg) {
17179 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
17180 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
17181 		    "flags 0x%x",
17182 		    str, seq, ack, ctl);
17183 	}
17184 	if (mp->b_datap->db_ref != 1) {
17185 		mblk_t *mp1 = copyb(mp);
17186 		freemsg(mp);
17187 		mp = mp1;
17188 		if (mp == NULL)
17189 			goto done;
17190 	} else if (mp->b_cont) {
17191 		freemsg(mp->b_cont);
17192 		mp->b_cont = NULL;
17193 		DB_CKSUMFLAGS(mp) = 0;
17194 	}
17195 	/*
17196 	 * We skip reversing source route here.
17197 	 * (for now we replace all IP options with EOL)
17198 	 */
17199 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17200 		ipha = (ipha_t *)mp->b_rptr;
17201 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
17202 			mp->b_rptr[i] = IPOPT_EOL;
17203 		/*
17204 		 * Make sure that src address isn't flagrantly invalid.
17205 		 * Not all broadcast address checking for the src address
17206 		 * is possible, since we don't know the netmask of the src
17207 		 * addr.  No check for destination address is done, since
17208 		 * IP will not pass up a packet with a broadcast dest
17209 		 * address to TCP.  Similar checks are done below for IPv6.
17210 		 */
17211 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
17212 		    CLASSD(ipha->ipha_src)) {
17213 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
17214 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17215 			freemsg(mp);
17216 			goto done;
17217 		}
17218 	} else {
17219 		ip6h = (ip6_t *)mp->b_rptr;
17220 
17221 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
17222 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
17223 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
17224 			ip_drop_input("ipIfStatsInDiscards", mp, NULL);
17225 			freemsg(mp);
17226 			goto done;
17227 		}
17228 
17229 		/* Remove any extension headers assuming partial overlay */
17230 		if (ip_hdr_len > IPV6_HDR_LEN) {
17231 			uint8_t *to;
17232 
17233 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
17234 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
17235 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
17236 			ip_hdr_len = IPV6_HDR_LEN;
17237 			ip6h = (ip6_t *)mp->b_rptr;
17238 			ip6h->ip6_nxt = IPPROTO_TCP;
17239 		}
17240 	}
17241 	tcpha = (tcpha_t *)&mp->b_rptr[ip_hdr_len];
17242 	if (tcpha->tha_flags & TH_RST) {
17243 		freemsg(mp);
17244 		goto done;
17245 	}
17246 	tcpha->tha_offset_and_reserved = (5 << 4);
17247 	len = ip_hdr_len + sizeof (tcpha_t);
17248 	mp->b_wptr = &mp->b_rptr[len];
17249 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17250 		ipha->ipha_length = htons(len);
17251 		/* Swap addresses */
17252 		v4addr = ipha->ipha_src;
17253 		ipha->ipha_src = ipha->ipha_dst;
17254 		ipha->ipha_dst = v4addr;
17255 		ipha->ipha_ident = 0;
17256 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
17257 		ixa->ixa_flags |= IXAF_IS_IPV4;
17258 		ixa->ixa_ip_hdr_length = ip_hdr_len;
17259 	} else {
17260 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
17261 		/* Swap addresses */
17262 		v6addr = ip6h->ip6_src;
17263 		ip6h->ip6_src = ip6h->ip6_dst;
17264 		ip6h->ip6_dst = v6addr;
17265 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
17266 		ixa->ixa_flags &= ~IXAF_IS_IPV4;
17267 
17268 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_dst)) {
17269 			ixa->ixa_flags |= IXAF_SCOPEID_SET;
17270 			ixa->ixa_scopeid = ira->ira_ruifindex;
17271 		}
17272 		ixa->ixa_ip_hdr_length = IPV6_HDR_LEN;
17273 	}
17274 	ixa->ixa_pktlen = len;
17275 
17276 	/* Swap the ports */
17277 	port = tcpha->tha_fport;
17278 	tcpha->tha_fport = tcpha->tha_lport;
17279 	tcpha->tha_lport = port;
17280 
17281 	tcpha->tha_ack = htonl(ack);
17282 	tcpha->tha_seq = htonl(seq);
17283 	tcpha->tha_win = 0;
17284 	tcpha->tha_sum = htons(sizeof (tcpha_t));
17285 	tcpha->tha_flags = (uint8_t)ctl;
17286 	if (ctl & TH_RST) {
17287 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
17288 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17289 	}
17290 
17291 	/* Discard any old label */
17292 	if (ixa->ixa_free_flags & IXA_FREE_TSL) {
17293 		ASSERT(ixa->ixa_tsl != NULL);
17294 		label_rele(ixa->ixa_tsl);
17295 		ixa->ixa_free_flags &= ~IXA_FREE_TSL;
17296 	}
17297 	ixa->ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
17298 
17299 	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
17300 		/*
17301 		 * Apply IPsec based on how IPsec was applied to
17302 		 * the packet that caused the RST.
17303 		 */
17304 		if (!ipsec_in_to_out(ira, ixa, mp, ipha, ip6h)) {
17305 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
17306 			/* Note: mp already consumed and ip_drop_packet done */
17307 			goto done;
17308 		}
17309 	} else {
17310 		/*
17311 		 * This is in clear. The RST message we are building
17312 		 * here should go out in clear, independent of our policy.
17313 		 */
17314 		ixa->ixa_flags |= IXAF_NO_IPSEC;
17315 	}
17316 
17317 	/*
17318 	 * NOTE:  one might consider tracing a TCP packet here, but
17319 	 * this function has no active TCP state and no tcp structure
17320 	 * that has a trace buffer.  If we traced here, we would have
17321 	 * to keep a local trace buffer in tcp_record_trace().
17322 	 */
17323 
17324 	(void) ip_output_simple(mp, ixa);
17325 done:
17326 	ixa_cleanup(ixa);
17327 	if (need_refrele) {
17328 		ASSERT(ixa != &ixas);
17329 		ixa_refrele(ixa);
17330 	}
17331 }
17332 
17333 /*
17334  * Initiate closedown sequence on an active connection.  (May be called as
17335  * writer.)  Return value zero for OK return, non-zero for error return.
17336  */
17337 static int
17338 tcp_xmit_end(tcp_t *tcp)
17339 {
17340 	mblk_t		*mp;
17341 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17342 	iulp_t		uinfo;
17343 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17344 	conn_t		*connp = tcp->tcp_connp;
17345 
17346 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
17347 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
17348 		/*
17349 		 * Invalid state, only states TCPS_SYN_RCVD,
17350 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
17351 		 */
17352 		return (-1);
17353 	}
17354 
17355 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
17356 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
17357 	/*
17358 	 * If there is nothing more unsent, send the FIN now.
17359 	 * Otherwise, it will go out with the last segment.
17360 	 */
17361 	if (tcp->tcp_unsent == 0) {
17362 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
17363 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
17364 
17365 		if (mp) {
17366 			tcp_send_data(tcp, mp);
17367 		} else {
17368 			/*
17369 			 * Couldn't allocate msg.  Pretend we got it out.
17370 			 * Wait for rexmit timeout.
17371 			 */
17372 			tcp->tcp_snxt = tcp->tcp_fss + 1;
17373 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17374 		}
17375 
17376 		/*
17377 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
17378 		 * changed.
17379 		 */
17380 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
17381 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
17382 		}
17383 	} else {
17384 		/*
17385 		 * If tcp->tcp_cork is set, then the data will not get sent,
17386 		 * so we have to check that and unset it first.
17387 		 */
17388 		if (tcp->tcp_cork)
17389 			tcp->tcp_cork = B_FALSE;
17390 		tcp_wput_data(tcp, NULL, B_FALSE);
17391 	}
17392 
17393 	/*
17394 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
17395 	 * is 0, don't update the cache.
17396 	 */
17397 	if (tcps->tcps_rtt_updates == 0 ||
17398 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
17399 		return (0);
17400 
17401 	/*
17402 	 * We do not have a good algorithm to update ssthresh at this time.
17403 	 * So don't do any update.
17404 	 */
17405 	bzero(&uinfo, sizeof (uinfo));
17406 	uinfo.iulp_rtt = tcp->tcp_rtt_sa;
17407 	uinfo.iulp_rtt_sd = tcp->tcp_rtt_sd;
17408 
17409 	/*
17410 	 * Note that uinfo is kept for conn_faddr in the DCE. Could update even
17411 	 * if source routed but we don't.
17412 	 */
17413 	if (connp->conn_ipversion == IPV4_VERSION) {
17414 		if (connp->conn_faddr_v4 !=  tcp->tcp_ipha->ipha_dst) {
17415 			return (0);
17416 		}
17417 		(void) dce_update_uinfo_v4(connp->conn_faddr_v4, &uinfo, ipst);
17418 	} else {
17419 		uint_t ifindex;
17420 
17421 		if (!(IN6_ARE_ADDR_EQUAL(&connp->conn_faddr_v6,
17422 		    &tcp->tcp_ip6h->ip6_dst))) {
17423 			return (0);
17424 		}
17425 		ifindex = 0;
17426 		if (IN6_IS_ADDR_LINKSCOPE(&connp->conn_faddr_v6)) {
17427 			ip_xmit_attr_t *ixa = connp->conn_ixa;
17428 
17429 			/*
17430 			 * If we are going to create a DCE we'd better have
17431 			 * an ifindex
17432 			 */
17433 			if (ixa->ixa_nce != NULL) {
17434 				ifindex = ixa->ixa_nce->nce_common->ncec_ill->
17435 				    ill_phyint->phyint_ifindex;
17436 			} else {
17437 				return (0);
17438 			}
17439 		}
17440 
17441 		(void) dce_update_uinfo(&connp->conn_faddr_v6, ifindex, &uinfo,
17442 		    ipst);
17443 	}
17444 	return (0);
17445 }
17446 
17447 /*
17448  * Generate a "no listener here" RST in response to an "unknown" segment.
17449  * connp is set by caller when RST is in response to an unexpected
17450  * inbound packet for which there is active tcp state in the system.
17451  * Note that we are reusing the incoming mp to construct the outgoing RST.
17452  */
17453 void
17454 tcp_xmit_listeners_reset(mblk_t *mp, ip_recv_attr_t *ira, ip_stack_t *ipst,
17455     conn_t *connp)
17456 {
17457 	uchar_t		*rptr;
17458 	uint32_t	seg_len;
17459 	tcpha_t		*tcpha;
17460 	uint32_t	seg_seq;
17461 	uint32_t	seg_ack;
17462 	uint_t		flags;
17463 	ipha_t 		*ipha;
17464 	ip6_t 		*ip6h;
17465 	boolean_t	policy_present;
17466 	netstack_t	*ns = ipst->ips_netstack;
17467 	tcp_stack_t	*tcps = ns->netstack_tcp;
17468 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
17469 	uint_t		ip_hdr_len = ira->ira_ip_hdr_length;
17470 
17471 	TCP_STAT(tcps, tcp_no_listener);
17472 
17473 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
17474 		policy_present = ipss->ipsec_inbound_v4_policy_present;
17475 		ipha = (ipha_t *)mp->b_rptr;
17476 		ip6h = NULL;
17477 	} else {
17478 		policy_present = ipss->ipsec_inbound_v6_policy_present;
17479 		ipha = NULL;
17480 		ip6h = (ip6_t *)mp->b_rptr;
17481 	}
17482 
17483 	if (policy_present) {
17484 		/*
17485 		 * The conn_t parameter is NULL because we already know
17486 		 * nobody's home.
17487 		 */
17488 		mp = ipsec_check_global_policy(mp, (conn_t *)NULL, ipha, ip6h,
17489 		    ira, ns);
17490 		if (mp == NULL)
17491 			return;
17492 	}
17493 	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
17494 		DTRACE_PROBE2(
17495 		    tx__ip__log__error__nolistener__tcp,
17496 		    char *, "Could not reply with RST to mp(1)",
17497 		    mblk_t *, mp);
17498 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
17499 		freemsg(mp);
17500 		return;
17501 	}
17502 
17503 	rptr = mp->b_rptr;
17504 
17505 	tcpha = (tcpha_t *)&rptr[ip_hdr_len];
17506 	seg_seq = ntohl(tcpha->tha_seq);
17507 	seg_ack = ntohl(tcpha->tha_ack);
17508 	flags = tcpha->tha_flags;
17509 
17510 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcpha) + ip_hdr_len);
17511 	if (flags & TH_RST) {
17512 		freemsg(mp);
17513 	} else if (flags & TH_ACK) {
17514 		tcp_xmit_early_reset("no tcp, reset", mp, seg_ack, 0, TH_RST,
17515 		    ira, ipst, connp);
17516 	} else {
17517 		if (flags & TH_SYN) {
17518 			seg_len++;
17519 		} else {
17520 			/*
17521 			 * Here we violate the RFC.  Note that a normal
17522 			 * TCP will never send a segment without the ACK
17523 			 * flag, except for RST or SYN segment.  This
17524 			 * segment is neither.  Just drop it on the
17525 			 * floor.
17526 			 */
17527 			freemsg(mp);
17528 			TCP_STAT(tcps, tcp_rst_unsent);
17529 			return;
17530 		}
17531 
17532 		tcp_xmit_early_reset("no tcp, reset/ack", mp, 0,
17533 		    seg_seq + seg_len, TH_RST | TH_ACK, ira, ipst, connp);
17534 	}
17535 }
17536 
17537 /*
17538  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
17539  * ip and tcp header ready to pass down to IP.  If the mp passed in is
17540  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
17541  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
17542  * otherwise it will dup partial mblks.)
17543  * Otherwise, an appropriate ACK packet will be generated.  This
17544  * routine is not usually called to send new data for the first time.  It
17545  * is mostly called out of the timer for retransmits, and to generate ACKs.
17546  *
17547  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
17548  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
17549  * of the original mblk chain will be returned in *offset and *end_mp.
17550  */
17551 mblk_t *
17552 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
17553     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
17554     boolean_t rexmit)
17555 {
17556 	int	data_length;
17557 	int32_t	off = 0;
17558 	uint_t	flags;
17559 	mblk_t	*mp1;
17560 	mblk_t	*mp2;
17561 	uchar_t	*rptr;
17562 	tcpha_t	*tcpha;
17563 	int32_t	num_sack_blk = 0;
17564 	int32_t	sack_opt_len = 0;
17565 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17566 	conn_t		*connp = tcp->tcp_connp;
17567 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
17568 
17569 	/* Allocate for our maximum TCP header + link-level */
17570 	mp1 = allocb(connp->conn_ht_iphc_allocated + tcps->tcps_wroff_xtra,
17571 	    BPRI_MED);
17572 	if (!mp1)
17573 		return (NULL);
17574 	data_length = 0;
17575 
17576 	/*
17577 	 * Note that tcp_mss has been adjusted to take into account the
17578 	 * timestamp option if applicable.  Because SACK options do not
17579 	 * appear in every TCP segments and they are of variable lengths,
17580 	 * they cannot be included in tcp_mss.  Thus we need to calculate
17581 	 * the actual segment length when we need to send a segment which
17582 	 * includes SACK options.
17583 	 */
17584 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
17585 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
17586 		    tcp->tcp_num_sack_blk);
17587 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
17588 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
17589 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
17590 			max_to_send -= sack_opt_len;
17591 	}
17592 
17593 	if (offset != NULL) {
17594 		off = *offset;
17595 		/* We use offset as an indicator that end_mp is not NULL. */
17596 		*end_mp = NULL;
17597 	}
17598 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
17599 		/* This could be faster with cooperation from downstream */
17600 		if (mp2 != mp1 && !sendall &&
17601 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
17602 		    max_to_send)
17603 			/*
17604 			 * Don't send the next mblk since the whole mblk
17605 			 * does not fit.
17606 			 */
17607 			break;
17608 		mp2->b_cont = dupb(mp);
17609 		mp2 = mp2->b_cont;
17610 		if (!mp2) {
17611 			freemsg(mp1);
17612 			return (NULL);
17613 		}
17614 		mp2->b_rptr += off;
17615 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
17616 		    (uintptr_t)INT_MAX);
17617 
17618 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
17619 		if (data_length > max_to_send) {
17620 			mp2->b_wptr -= data_length - max_to_send;
17621 			data_length = max_to_send;
17622 			off = mp2->b_wptr - mp->b_rptr;
17623 			break;
17624 		} else {
17625 			off = 0;
17626 		}
17627 	}
17628 	if (offset != NULL) {
17629 		*offset = off;
17630 		*end_mp = mp;
17631 	}
17632 	if (seg_len != NULL) {
17633 		*seg_len = data_length;
17634 	}
17635 
17636 	/* Update the latest receive window size in TCP header. */
17637 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
17638 
17639 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
17640 	mp1->b_rptr = rptr;
17641 	mp1->b_wptr = rptr + connp->conn_ht_iphc_len + sack_opt_len;
17642 	bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
17643 	tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
17644 	tcpha->tha_seq = htonl(seq);
17645 
17646 	/*
17647 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
17648 	 * that this function was called from tcp_wput_data. Thus, when called
17649 	 * to retransmit data the setting of the PUSH bit may appear some
17650 	 * what random in that it might get set when it should not. This
17651 	 * should not pose any performance issues.
17652 	 */
17653 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
17654 	    tcp->tcp_unsent == data_length)) {
17655 		flags = TH_ACK | TH_PUSH;
17656 	} else {
17657 		flags = TH_ACK;
17658 	}
17659 
17660 	if (tcp->tcp_ecn_ok) {
17661 		if (tcp->tcp_ecn_echo_on)
17662 			flags |= TH_ECE;
17663 
17664 		/*
17665 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
17666 		 * There is no TCP flow control for non-data segments, and
17667 		 * only data segment is transmitted reliably.
17668 		 */
17669 		if (data_length > 0 && !rexmit) {
17670 			SET_ECT(tcp, rptr);
17671 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17672 				flags |= TH_CWR;
17673 				tcp->tcp_ecn_cwr_sent = B_TRUE;
17674 			}
17675 		}
17676 	}
17677 
17678 	if (tcp->tcp_valid_bits) {
17679 		uint32_t u1;
17680 
17681 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
17682 		    seq == tcp->tcp_iss) {
17683 			uchar_t	*wptr;
17684 
17685 			/*
17686 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
17687 			 * TCP can only be in SYN-SENT, SYN-RCVD or
17688 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
17689 			 * our SYN is not ack'ed but the app closes this
17690 			 * TCP connection.
17691 			 */
17692 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
17693 			    tcp->tcp_state == TCPS_SYN_RCVD ||
17694 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
17695 
17696 			/*
17697 			 * Tack on the MSS option.  It is always needed
17698 			 * for both active and passive open.
17699 			 *
17700 			 * MSS option value should be interface MTU - MIN
17701 			 * TCP/IP header according to RFC 793 as it means
17702 			 * the maximum segment size TCP can receive.  But
17703 			 * to get around some broken middle boxes/end hosts
17704 			 * out there, we allow the option value to be the
17705 			 * same as the MSS option size on the peer side.
17706 			 * In this way, the other side will not send
17707 			 * anything larger than they can receive.
17708 			 *
17709 			 * Note that for SYN_SENT state, the ndd param
17710 			 * tcp_use_smss_as_mss_opt has no effect as we
17711 			 * don't know the peer's MSS option value. So
17712 			 * the only case we need to take care of is in
17713 			 * SYN_RCVD state, which is done later.
17714 			 */
17715 			wptr = mp1->b_wptr;
17716 			wptr[0] = TCPOPT_MAXSEG;
17717 			wptr[1] = TCPOPT_MAXSEG_LEN;
17718 			wptr += 2;
17719 			u1 = tcp->tcp_initial_pmtu -
17720 			    (connp->conn_ipversion == IPV4_VERSION ?
17721 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
17722 			    TCP_MIN_HEADER_LENGTH;
17723 			U16_TO_BE16(u1, wptr);
17724 			mp1->b_wptr = wptr + 2;
17725 			/* Update the offset to cover the additional word */
17726 			tcpha->tha_offset_and_reserved += (1 << 4);
17727 
17728 			/*
17729 			 * Note that the following way of filling in
17730 			 * TCP options are not optimal.  Some NOPs can
17731 			 * be saved.  But there is no need at this time
17732 			 * to optimize it.  When it is needed, we will
17733 			 * do it.
17734 			 */
17735 			switch (tcp->tcp_state) {
17736 			case TCPS_SYN_SENT:
17737 				flags = TH_SYN;
17738 
17739 				if (tcp->tcp_snd_ts_ok) {
17740 					uint32_t llbolt =
17741 					    (uint32_t)LBOLT_FASTPATH;
17742 
17743 					wptr = mp1->b_wptr;
17744 					wptr[0] = TCPOPT_NOP;
17745 					wptr[1] = TCPOPT_NOP;
17746 					wptr[2] = TCPOPT_TSTAMP;
17747 					wptr[3] = TCPOPT_TSTAMP_LEN;
17748 					wptr += 4;
17749 					U32_TO_BE32(llbolt, wptr);
17750 					wptr += 4;
17751 					ASSERT(tcp->tcp_ts_recent == 0);
17752 					U32_TO_BE32(0L, wptr);
17753 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
17754 					tcpha->tha_offset_and_reserved +=
17755 					    (3 << 4);
17756 				}
17757 
17758 				/*
17759 				 * Set up all the bits to tell other side
17760 				 * we are ECN capable.
17761 				 */
17762 				if (tcp->tcp_ecn_ok) {
17763 					flags |= (TH_ECE | TH_CWR);
17764 				}
17765 				break;
17766 			case TCPS_SYN_RCVD:
17767 				flags |= TH_SYN;
17768 
17769 				/*
17770 				 * Reset the MSS option value to be SMSS
17771 				 * We should probably add back the bytes
17772 				 * for timestamp option and IPsec.  We
17773 				 * don't do that as this is a workaround
17774 				 * for broken middle boxes/end hosts, it
17775 				 * is better for us to be more cautious.
17776 				 * They may not take these things into
17777 				 * account in their SMSS calculation.  Thus
17778 				 * the peer's calculated SMSS may be smaller
17779 				 * than what it can be.  This should be OK.
17780 				 */
17781 				if (tcps->tcps_use_smss_as_mss_opt) {
17782 					u1 = tcp->tcp_mss;
17783 					U16_TO_BE16(u1, wptr);
17784 				}
17785 
17786 				/*
17787 				 * If the other side is ECN capable, reply
17788 				 * that we are also ECN capable.
17789 				 */
17790 				if (tcp->tcp_ecn_ok)
17791 					flags |= TH_ECE;
17792 				break;
17793 			default:
17794 				/*
17795 				 * The above ASSERT() makes sure that this
17796 				 * must be FIN-WAIT-1 state.  Our SYN has
17797 				 * not been ack'ed so retransmit it.
17798 				 */
17799 				flags |= TH_SYN;
17800 				break;
17801 			}
17802 
17803 			if (tcp->tcp_snd_ws_ok) {
17804 				wptr = mp1->b_wptr;
17805 				wptr[0] =  TCPOPT_NOP;
17806 				wptr[1] =  TCPOPT_WSCALE;
17807 				wptr[2] =  TCPOPT_WS_LEN;
17808 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
17809 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
17810 				tcpha->tha_offset_and_reserved += (1 << 4);
17811 			}
17812 
17813 			if (tcp->tcp_snd_sack_ok) {
17814 				wptr = mp1->b_wptr;
17815 				wptr[0] = TCPOPT_NOP;
17816 				wptr[1] = TCPOPT_NOP;
17817 				wptr[2] = TCPOPT_SACK_PERMITTED;
17818 				wptr[3] = TCPOPT_SACK_OK_LEN;
17819 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
17820 				tcpha->tha_offset_and_reserved += (1 << 4);
17821 			}
17822 
17823 			/* allocb() of adequate mblk assures space */
17824 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
17825 			    (uintptr_t)INT_MAX);
17826 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
17827 			/*
17828 			 * Get IP set to checksum on our behalf
17829 			 * Include the adjustment for a source route if any.
17830 			 */
17831 			u1 += connp->conn_sum;
17832 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
17833 			tcpha->tha_sum = htons(u1);
17834 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17835 		}
17836 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17837 		    (seq + data_length) == tcp->tcp_fss) {
17838 			if (!tcp->tcp_fin_acked) {
17839 				flags |= TH_FIN;
17840 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
17841 			}
17842 			if (!tcp->tcp_fin_sent) {
17843 				tcp->tcp_fin_sent = B_TRUE;
17844 				switch (tcp->tcp_state) {
17845 				case TCPS_SYN_RCVD:
17846 				case TCPS_ESTABLISHED:
17847 					tcp->tcp_state = TCPS_FIN_WAIT_1;
17848 					break;
17849 				case TCPS_CLOSE_WAIT:
17850 					tcp->tcp_state = TCPS_LAST_ACK;
17851 					break;
17852 				}
17853 				if (tcp->tcp_suna == tcp->tcp_snxt)
17854 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17855 				tcp->tcp_snxt = tcp->tcp_fss + 1;
17856 			}
17857 		}
17858 		/*
17859 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
17860 		 * is smaller than seq, u1 will become a very huge value.
17861 		 * So the comparison will fail.  Also note that tcp_urp
17862 		 * should be positive, see RFC 793 page 17.
17863 		 */
17864 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
17865 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
17866 		    u1 < (uint32_t)(64 * 1024)) {
17867 			flags |= TH_URG;
17868 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
17869 			tcpha->tha_urp = htons(u1);
17870 		}
17871 	}
17872 	tcpha->tha_flags = (uchar_t)flags;
17873 	tcp->tcp_rack = tcp->tcp_rnxt;
17874 	tcp->tcp_rack_cnt = 0;
17875 
17876 	if (tcp->tcp_snd_ts_ok) {
17877 		if (tcp->tcp_state != TCPS_SYN_SENT) {
17878 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
17879 
17880 			U32_TO_BE32(llbolt,
17881 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
17882 			U32_TO_BE32(tcp->tcp_ts_recent,
17883 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
17884 		}
17885 	}
17886 
17887 	if (num_sack_blk > 0) {
17888 		uchar_t *wptr = (uchar_t *)tcpha + connp->conn_ht_ulp_len;
17889 		sack_blk_t *tmp;
17890 		int32_t	i;
17891 
17892 		wptr[0] = TCPOPT_NOP;
17893 		wptr[1] = TCPOPT_NOP;
17894 		wptr[2] = TCPOPT_SACK;
17895 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
17896 		    sizeof (sack_blk_t);
17897 		wptr += TCPOPT_REAL_SACK_LEN;
17898 
17899 		tmp = tcp->tcp_sack_list;
17900 		for (i = 0; i < num_sack_blk; i++) {
17901 			U32_TO_BE32(tmp[i].begin, wptr);
17902 			wptr += sizeof (tcp_seq);
17903 			U32_TO_BE32(tmp[i].end, wptr);
17904 			wptr += sizeof (tcp_seq);
17905 		}
17906 		tcpha->tha_offset_and_reserved += ((num_sack_blk * 2 + 1) << 4);
17907 	}
17908 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
17909 	data_length += (int)(mp1->b_wptr - rptr);
17910 
17911 	ixa->ixa_pktlen = data_length;
17912 
17913 	if (ixa->ixa_flags & IXAF_IS_IPV4) {
17914 		((ipha_t *)rptr)->ipha_length = htons(data_length);
17915 	} else {
17916 		ip6_t *ip6 = (ip6_t *)rptr;
17917 
17918 		ip6->ip6_plen = htons(data_length - IPV6_HDR_LEN);
17919 	}
17920 
17921 	/*
17922 	 * Prime pump for IP
17923 	 * Include the adjustment for a source route if any.
17924 	 */
17925 	data_length -= ixa->ixa_ip_hdr_length;
17926 	data_length += connp->conn_sum;
17927 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
17928 	tcpha->tha_sum = htons(data_length);
17929 	if (tcp->tcp_ip_forward_progress) {
17930 		tcp->tcp_ip_forward_progress = B_FALSE;
17931 		connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
17932 	} else {
17933 		connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
17934 	}
17935 	return (mp1);
17936 }
17937 
17938 /* This function handles the push timeout. */
17939 void
17940 tcp_push_timer(void *arg)
17941 {
17942 	conn_t	*connp = (conn_t *)arg;
17943 	tcp_t *tcp = connp->conn_tcp;
17944 
17945 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
17946 
17947 	ASSERT(tcp->tcp_listener == NULL);
17948 
17949 	ASSERT(!IPCL_IS_NONSTR(connp));
17950 
17951 	tcp->tcp_push_tid = 0;
17952 
17953 	if (tcp->tcp_rcv_list != NULL &&
17954 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
17955 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
17956 }
17957 
17958 /*
17959  * This function handles delayed ACK timeout.
17960  */
17961 static void
17962 tcp_ack_timer(void *arg)
17963 {
17964 	conn_t	*connp = (conn_t *)arg;
17965 	tcp_t *tcp = connp->conn_tcp;
17966 	mblk_t *mp;
17967 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17968 
17969 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
17970 
17971 	tcp->tcp_ack_tid = 0;
17972 
17973 	if (tcp->tcp_fused)
17974 		return;
17975 
17976 	/*
17977 	 * Do not send ACK if there is no outstanding unack'ed data.
17978 	 */
17979 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
17980 		return;
17981 	}
17982 
17983 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
17984 		/*
17985 		 * Make sure we don't allow deferred ACKs to result in
17986 		 * timer-based ACKing.  If we have held off an ACK
17987 		 * when there was more than an mss here, and the timer
17988 		 * goes off, we have to worry about the possibility
17989 		 * that the sender isn't doing slow-start, or is out
17990 		 * of step with us for some other reason.  We fall
17991 		 * permanently back in the direction of
17992 		 * ACK-every-other-packet as suggested in RFC 1122.
17993 		 */
17994 		if (tcp->tcp_rack_abs_max > 2)
17995 			tcp->tcp_rack_abs_max--;
17996 		tcp->tcp_rack_cur_max = 2;
17997 	}
17998 	mp = tcp_ack_mp(tcp);
17999 
18000 	if (mp != NULL) {
18001 		BUMP_LOCAL(tcp->tcp_obsegs);
18002 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
18003 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
18004 		tcp_send_data(tcp, mp);
18005 	}
18006 }
18007 
18008 
18009 /* Generate an ACK-only (no data) segment for a TCP endpoint */
18010 static mblk_t *
18011 tcp_ack_mp(tcp_t *tcp)
18012 {
18013 	uint32_t	seq_no;
18014 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18015 	conn_t		*connp = tcp->tcp_connp;
18016 
18017 	/*
18018 	 * There are a few cases to be considered while setting the sequence no.
18019 	 * Essentially, we can come here while processing an unacceptable pkt
18020 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
18021 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
18022 	 * If we are here for a zero window probe, stick with suna. In all
18023 	 * other cases, we check if suna + swnd encompasses snxt and set
18024 	 * the sequence number to snxt, if so. If snxt falls outside the
18025 	 * window (the receiver probably shrunk its window), we will go with
18026 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
18027 	 * receiver.
18028 	 */
18029 	if (tcp->tcp_zero_win_probe) {
18030 		seq_no = tcp->tcp_suna;
18031 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
18032 		ASSERT(tcp->tcp_swnd == 0);
18033 		seq_no = tcp->tcp_snxt;
18034 	} else {
18035 		seq_no = SEQ_GT(tcp->tcp_snxt,
18036 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
18037 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
18038 	}
18039 
18040 	if (tcp->tcp_valid_bits) {
18041 		/*
18042 		 * For the complex case where we have to send some
18043 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
18044 		 */
18045 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
18046 		    NULL, B_FALSE));
18047 	} else {
18048 		/* Generate a simple ACK */
18049 		int	data_length;
18050 		uchar_t	*rptr;
18051 		tcpha_t	*tcpha;
18052 		mblk_t	*mp1;
18053 		int32_t	total_hdr_len;
18054 		int32_t	tcp_hdr_len;
18055 		int32_t	num_sack_blk = 0;
18056 		int32_t sack_opt_len;
18057 		ip_xmit_attr_t *ixa = connp->conn_ixa;
18058 
18059 		/*
18060 		 * Allocate space for TCP + IP headers
18061 		 * and link-level header
18062 		 */
18063 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
18064 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
18065 			    tcp->tcp_num_sack_blk);
18066 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
18067 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
18068 			total_hdr_len = connp->conn_ht_iphc_len + sack_opt_len;
18069 			tcp_hdr_len = connp->conn_ht_ulp_len + sack_opt_len;
18070 		} else {
18071 			total_hdr_len = connp->conn_ht_iphc_len;
18072 			tcp_hdr_len = connp->conn_ht_ulp_len;
18073 		}
18074 		mp1 = allocb(total_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
18075 		if (!mp1)
18076 			return (NULL);
18077 
18078 		/* Update the latest receive window size in TCP header. */
18079 		tcp->tcp_tcpha->tha_win =
18080 		    htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
18081 		/* copy in prototype TCP + IP header */
18082 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
18083 		mp1->b_rptr = rptr;
18084 		mp1->b_wptr = rptr + total_hdr_len;
18085 		bcopy(connp->conn_ht_iphc, rptr, connp->conn_ht_iphc_len);
18086 
18087 		tcpha = (tcpha_t *)&rptr[ixa->ixa_ip_hdr_length];
18088 
18089 		/* Set the TCP sequence number. */
18090 		tcpha->tha_seq = htonl(seq_no);
18091 
18092 		/* Set up the TCP flag field. */
18093 		tcpha->tha_flags = (uchar_t)TH_ACK;
18094 		if (tcp->tcp_ecn_echo_on)
18095 			tcpha->tha_flags |= TH_ECE;
18096 
18097 		tcp->tcp_rack = tcp->tcp_rnxt;
18098 		tcp->tcp_rack_cnt = 0;
18099 
18100 		/* fill in timestamp option if in use */
18101 		if (tcp->tcp_snd_ts_ok) {
18102 			uint32_t llbolt = (uint32_t)LBOLT_FASTPATH;
18103 
18104 			U32_TO_BE32(llbolt,
18105 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+4);
18106 			U32_TO_BE32(tcp->tcp_ts_recent,
18107 			    (char *)tcpha + TCP_MIN_HEADER_LENGTH+8);
18108 		}
18109 
18110 		/* Fill in SACK options */
18111 		if (num_sack_blk > 0) {
18112 			uchar_t *wptr = (uchar_t *)tcpha +
18113 			    connp->conn_ht_ulp_len;
18114 			sack_blk_t *tmp;
18115 			int32_t	i;
18116 
18117 			wptr[0] = TCPOPT_NOP;
18118 			wptr[1] = TCPOPT_NOP;
18119 			wptr[2] = TCPOPT_SACK;
18120 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
18121 			    sizeof (sack_blk_t);
18122 			wptr += TCPOPT_REAL_SACK_LEN;
18123 
18124 			tmp = tcp->tcp_sack_list;
18125 			for (i = 0; i < num_sack_blk; i++) {
18126 				U32_TO_BE32(tmp[i].begin, wptr);
18127 				wptr += sizeof (tcp_seq);
18128 				U32_TO_BE32(tmp[i].end, wptr);
18129 				wptr += sizeof (tcp_seq);
18130 			}
18131 			tcpha->tha_offset_and_reserved +=
18132 			    ((num_sack_blk * 2 + 1) << 4);
18133 		}
18134 
18135 		ixa->ixa_pktlen = total_hdr_len;
18136 
18137 		if (ixa->ixa_flags & IXAF_IS_IPV4) {
18138 			((ipha_t *)rptr)->ipha_length = htons(total_hdr_len);
18139 		} else {
18140 			ip6_t *ip6 = (ip6_t *)rptr;
18141 
18142 			ip6->ip6_plen = htons(total_hdr_len - IPV6_HDR_LEN);
18143 		}
18144 
18145 		/*
18146 		 * Prime pump for checksum calculation in IP.  Include the
18147 		 * adjustment for a source route if any.
18148 		 */
18149 		data_length = tcp_hdr_len + connp->conn_sum;
18150 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
18151 		tcpha->tha_sum = htons(data_length);
18152 
18153 		if (tcp->tcp_ip_forward_progress) {
18154 			tcp->tcp_ip_forward_progress = B_FALSE;
18155 			connp->conn_ixa->ixa_flags |= IXAF_REACH_CONF;
18156 		} else {
18157 			connp->conn_ixa->ixa_flags &= ~IXAF_REACH_CONF;
18158 		}
18159 		return (mp1);
18160 	}
18161 }
18162 
18163 /*
18164  * Hash list insertion routine for tcp_t structures. Each hash bucket
18165  * contains a list of tcp_t entries, and each entry is bound to a unique
18166  * port. If there are multiple tcp_t's that are bound to the same port, then
18167  * one of them will be linked into the hash bucket list, and the rest will
18168  * hang off of that one entry. For each port, entries bound to a specific IP
18169  * address will be inserted before those those bound to INADDR_ANY.
18170  */
18171 static void
18172 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
18173 {
18174 	tcp_t	**tcpp;
18175 	tcp_t	*tcpnext;
18176 	tcp_t	*tcphash;
18177 	conn_t	*connp = tcp->tcp_connp;
18178 	conn_t	*connext;
18179 
18180 	if (tcp->tcp_ptpbhn != NULL) {
18181 		ASSERT(!caller_holds_lock);
18182 		tcp_bind_hash_remove(tcp);
18183 	}
18184 	tcpp = &tbf->tf_tcp;
18185 	if (!caller_holds_lock) {
18186 		mutex_enter(&tbf->tf_lock);
18187 	} else {
18188 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
18189 	}
18190 	tcphash = tcpp[0];
18191 	tcpnext = NULL;
18192 	if (tcphash != NULL) {
18193 		/* Look for an entry using the same port */
18194 		while ((tcphash = tcpp[0]) != NULL &&
18195 		    connp->conn_lport != tcphash->tcp_connp->conn_lport)
18196 			tcpp = &(tcphash->tcp_bind_hash);
18197 
18198 		/* The port was not found, just add to the end */
18199 		if (tcphash == NULL)
18200 			goto insert;
18201 
18202 		/*
18203 		 * OK, there already exists an entry bound to the
18204 		 * same port.
18205 		 *
18206 		 * If the new tcp bound to the INADDR_ANY address
18207 		 * and the first one in the list is not bound to
18208 		 * INADDR_ANY we skip all entries until we find the
18209 		 * first one bound to INADDR_ANY.
18210 		 * This makes sure that applications binding to a
18211 		 * specific address get preference over those binding to
18212 		 * INADDR_ANY.
18213 		 */
18214 		tcpnext = tcphash;
18215 		connext = tcpnext->tcp_connp;
18216 		tcphash = NULL;
18217 		if (V6_OR_V4_INADDR_ANY(connp->conn_bound_addr_v6) &&
18218 		    !V6_OR_V4_INADDR_ANY(connext->conn_bound_addr_v6)) {
18219 			while ((tcpnext = tcpp[0]) != NULL) {
18220 				connext = tcpnext->tcp_connp;
18221 				if (!V6_OR_V4_INADDR_ANY(
18222 				    connext->conn_bound_addr_v6))
18223 					tcpp = &(tcpnext->tcp_bind_hash_port);
18224 				else
18225 					break;
18226 			}
18227 			if (tcpnext != NULL) {
18228 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18229 				tcphash = tcpnext->tcp_bind_hash;
18230 				if (tcphash != NULL) {
18231 					tcphash->tcp_ptpbhn =
18232 					    &(tcp->tcp_bind_hash);
18233 					tcpnext->tcp_bind_hash = NULL;
18234 				}
18235 			}
18236 		} else {
18237 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
18238 			tcphash = tcpnext->tcp_bind_hash;
18239 			if (tcphash != NULL) {
18240 				tcphash->tcp_ptpbhn =
18241 				    &(tcp->tcp_bind_hash);
18242 				tcpnext->tcp_bind_hash = NULL;
18243 			}
18244 		}
18245 	}
18246 insert:
18247 	tcp->tcp_bind_hash_port = tcpnext;
18248 	tcp->tcp_bind_hash = tcphash;
18249 	tcp->tcp_ptpbhn = tcpp;
18250 	tcpp[0] = tcp;
18251 	if (!caller_holds_lock)
18252 		mutex_exit(&tbf->tf_lock);
18253 }
18254 
18255 /*
18256  * Hash list removal routine for tcp_t structures.
18257  */
18258 static void
18259 tcp_bind_hash_remove(tcp_t *tcp)
18260 {
18261 	tcp_t	*tcpnext;
18262 	kmutex_t *lockp;
18263 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18264 	conn_t		*connp = tcp->tcp_connp;
18265 
18266 	if (tcp->tcp_ptpbhn == NULL)
18267 		return;
18268 
18269 	/*
18270 	 * Extract the lock pointer in case there are concurrent
18271 	 * hash_remove's for this instance.
18272 	 */
18273 	ASSERT(connp->conn_lport != 0);
18274 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(
18275 	    connp->conn_lport)].tf_lock;
18276 
18277 	ASSERT(lockp != NULL);
18278 	mutex_enter(lockp);
18279 	if (tcp->tcp_ptpbhn) {
18280 		tcpnext = tcp->tcp_bind_hash_port;
18281 		if (tcpnext != NULL) {
18282 			tcp->tcp_bind_hash_port = NULL;
18283 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18284 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
18285 			if (tcpnext->tcp_bind_hash != NULL) {
18286 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
18287 				    &(tcpnext->tcp_bind_hash);
18288 				tcp->tcp_bind_hash = NULL;
18289 			}
18290 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
18291 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
18292 			tcp->tcp_bind_hash = NULL;
18293 		}
18294 		*tcp->tcp_ptpbhn = tcpnext;
18295 		tcp->tcp_ptpbhn = NULL;
18296 	}
18297 	mutex_exit(lockp);
18298 }
18299 
18300 
18301 /*
18302  * Hash list lookup routine for tcp_t structures.
18303  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
18304  */
18305 static tcp_t *
18306 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
18307 {
18308 	tf_t	*tf;
18309 	tcp_t	*tcp;
18310 
18311 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18312 	mutex_enter(&tf->tf_lock);
18313 	for (tcp = tf->tf_tcp; tcp != NULL;
18314 	    tcp = tcp->tcp_acceptor_hash) {
18315 		if (tcp->tcp_acceptor_id == id) {
18316 			CONN_INC_REF(tcp->tcp_connp);
18317 			mutex_exit(&tf->tf_lock);
18318 			return (tcp);
18319 		}
18320 	}
18321 	mutex_exit(&tf->tf_lock);
18322 	return (NULL);
18323 }
18324 
18325 
18326 /*
18327  * Hash list insertion routine for tcp_t structures.
18328  */
18329 void
18330 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
18331 {
18332 	tf_t	*tf;
18333 	tcp_t	**tcpp;
18334 	tcp_t	*tcpnext;
18335 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18336 
18337 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
18338 
18339 	if (tcp->tcp_ptpahn != NULL)
18340 		tcp_acceptor_hash_remove(tcp);
18341 	tcpp = &tf->tf_tcp;
18342 	mutex_enter(&tf->tf_lock);
18343 	tcpnext = tcpp[0];
18344 	if (tcpnext)
18345 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
18346 	tcp->tcp_acceptor_hash = tcpnext;
18347 	tcp->tcp_ptpahn = tcpp;
18348 	tcpp[0] = tcp;
18349 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
18350 	mutex_exit(&tf->tf_lock);
18351 }
18352 
18353 /*
18354  * Hash list removal routine for tcp_t structures.
18355  */
18356 static void
18357 tcp_acceptor_hash_remove(tcp_t *tcp)
18358 {
18359 	tcp_t	*tcpnext;
18360 	kmutex_t *lockp;
18361 
18362 	/*
18363 	 * Extract the lock pointer in case there are concurrent
18364 	 * hash_remove's for this instance.
18365 	 */
18366 	lockp = tcp->tcp_acceptor_lockp;
18367 
18368 	if (tcp->tcp_ptpahn == NULL)
18369 		return;
18370 
18371 	ASSERT(lockp != NULL);
18372 	mutex_enter(lockp);
18373 	if (tcp->tcp_ptpahn) {
18374 		tcpnext = tcp->tcp_acceptor_hash;
18375 		if (tcpnext) {
18376 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
18377 			tcp->tcp_acceptor_hash = NULL;
18378 		}
18379 		*tcp->tcp_ptpahn = tcpnext;
18380 		tcp->tcp_ptpahn = NULL;
18381 	}
18382 	mutex_exit(lockp);
18383 	tcp->tcp_acceptor_lockp = NULL;
18384 }
18385 
18386 /*
18387  * Type three generator adapted from the random() function in 4.4 BSD:
18388  */
18389 
18390 /*
18391  * Copyright (c) 1983, 1993
18392  *	The Regents of the University of California.  All rights reserved.
18393  *
18394  * Redistribution and use in source and binary forms, with or without
18395  * modification, are permitted provided that the following conditions
18396  * are met:
18397  * 1. Redistributions of source code must retain the above copyright
18398  *    notice, this list of conditions and the following disclaimer.
18399  * 2. Redistributions in binary form must reproduce the above copyright
18400  *    notice, this list of conditions and the following disclaimer in the
18401  *    documentation and/or other materials provided with the distribution.
18402  * 3. All advertising materials mentioning features or use of this software
18403  *    must display the following acknowledgement:
18404  *	This product includes software developed by the University of
18405  *	California, Berkeley and its contributors.
18406  * 4. Neither the name of the University nor the names of its contributors
18407  *    may be used to endorse or promote products derived from this software
18408  *    without specific prior written permission.
18409  *
18410  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18411  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18412  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18413  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18414  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18415  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
18416  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
18417  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
18418  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
18419  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
18420  * SUCH DAMAGE.
18421  */
18422 
18423 /* Type 3 -- x**31 + x**3 + 1 */
18424 #define	DEG_3		31
18425 #define	SEP_3		3
18426 
18427 
18428 /* Protected by tcp_random_lock */
18429 static int tcp_randtbl[DEG_3 + 1];
18430 
18431 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
18432 static int *tcp_random_rptr = &tcp_randtbl[1];
18433 
18434 static int *tcp_random_state = &tcp_randtbl[1];
18435 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
18436 
18437 kmutex_t tcp_random_lock;
18438 
18439 void
18440 tcp_random_init(void)
18441 {
18442 	int i;
18443 	hrtime_t hrt;
18444 	time_t wallclock;
18445 	uint64_t result;
18446 
18447 	/*
18448 	 * Use high-res timer and current time for seed.  Gethrtime() returns
18449 	 * a longlong, which may contain resolution down to nanoseconds.
18450 	 * The current time will either be a 32-bit or a 64-bit quantity.
18451 	 * XOR the two together in a 64-bit result variable.
18452 	 * Convert the result to a 32-bit value by multiplying the high-order
18453 	 * 32-bits by the low-order 32-bits.
18454 	 */
18455 
18456 	hrt = gethrtime();
18457 	(void) drv_getparm(TIME, &wallclock);
18458 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
18459 	mutex_enter(&tcp_random_lock);
18460 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
18461 	    (result & 0xffffffff);
18462 
18463 	for (i = 1; i < DEG_3; i++)
18464 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
18465 		    + 12345;
18466 	tcp_random_fptr = &tcp_random_state[SEP_3];
18467 	tcp_random_rptr = &tcp_random_state[0];
18468 	mutex_exit(&tcp_random_lock);
18469 	for (i = 0; i < 10 * DEG_3; i++)
18470 		(void) tcp_random();
18471 }
18472 
18473 /*
18474  * tcp_random: Return a random number in the range [1 - (128K + 1)].
18475  * This range is selected to be approximately centered on TCP_ISS / 2,
18476  * and easy to compute. We get this value by generating a 32-bit random
18477  * number, selecting out the high-order 17 bits, and then adding one so
18478  * that we never return zero.
18479  */
18480 int
18481 tcp_random(void)
18482 {
18483 	int i;
18484 
18485 	mutex_enter(&tcp_random_lock);
18486 	*tcp_random_fptr += *tcp_random_rptr;
18487 
18488 	/*
18489 	 * The high-order bits are more random than the low-order bits,
18490 	 * so we select out the high-order 17 bits and add one so that
18491 	 * we never return zero.
18492 	 */
18493 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
18494 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
18495 		tcp_random_fptr = tcp_random_state;
18496 		++tcp_random_rptr;
18497 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
18498 		tcp_random_rptr = tcp_random_state;
18499 
18500 	mutex_exit(&tcp_random_lock);
18501 	return (i);
18502 }
18503 
18504 static int
18505 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
18506     int *t_errorp, int *sys_errorp)
18507 {
18508 	int error;
18509 	int is_absreq_failure;
18510 	t_scalar_t *opt_lenp;
18511 	t_scalar_t opt_offset;
18512 	int prim_type;
18513 	struct T_conn_req *tcreqp;
18514 	struct T_conn_res *tcresp;
18515 	cred_t *cr;
18516 
18517 	/*
18518 	 * All Solaris components should pass a db_credp
18519 	 * for this TPI message, hence we ASSERT.
18520 	 * But in case there is some other M_PROTO that looks
18521 	 * like a TPI message sent by some other kernel
18522 	 * component, we check and return an error.
18523 	 */
18524 	cr = msg_getcred(mp, NULL);
18525 	ASSERT(cr != NULL);
18526 	if (cr == NULL)
18527 		return (-1);
18528 
18529 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
18530 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
18531 	    prim_type == T_CONN_RES);
18532 
18533 	switch (prim_type) {
18534 	case T_CONN_REQ:
18535 		tcreqp = (struct T_conn_req *)mp->b_rptr;
18536 		opt_offset = tcreqp->OPT_offset;
18537 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
18538 		break;
18539 	case O_T_CONN_RES:
18540 	case T_CONN_RES:
18541 		tcresp = (struct T_conn_res *)mp->b_rptr;
18542 		opt_offset = tcresp->OPT_offset;
18543 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
18544 		break;
18545 	}
18546 
18547 	*t_errorp = 0;
18548 	*sys_errorp = 0;
18549 	*do_disconnectp = 0;
18550 
18551 	error = tpi_optcom_buf(tcp->tcp_connp->conn_wq, mp, opt_lenp,
18552 	    opt_offset, cr, &tcp_opt_obj,
18553 	    NULL, &is_absreq_failure);
18554 
18555 	switch (error) {
18556 	case  0:		/* no error */
18557 		ASSERT(is_absreq_failure == 0);
18558 		return (0);
18559 	case ENOPROTOOPT:
18560 		*t_errorp = TBADOPT;
18561 		break;
18562 	case EACCES:
18563 		*t_errorp = TACCES;
18564 		break;
18565 	default:
18566 		*t_errorp = TSYSERR; *sys_errorp = error;
18567 		break;
18568 	}
18569 	if (is_absreq_failure != 0) {
18570 		/*
18571 		 * The connection request should get the local ack
18572 		 * T_OK_ACK and then a T_DISCON_IND.
18573 		 */
18574 		*do_disconnectp = 1;
18575 	}
18576 	return (-1);
18577 }
18578 
18579 /*
18580  * Split this function out so that if the secret changes, I'm okay.
18581  *
18582  * Initialize the tcp_iss_cookie and tcp_iss_key.
18583  */
18584 
18585 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
18586 
18587 static void
18588 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
18589 {
18590 	struct {
18591 		int32_t current_time;
18592 		uint32_t randnum;
18593 		uint16_t pad;
18594 		uint8_t ether[6];
18595 		uint8_t passwd[PASSWD_SIZE];
18596 	} tcp_iss_cookie;
18597 	time_t t;
18598 
18599 	/*
18600 	 * Start with the current absolute time.
18601 	 */
18602 	(void) drv_getparm(TIME, &t);
18603 	tcp_iss_cookie.current_time = t;
18604 
18605 	/*
18606 	 * XXX - Need a more random number per RFC 1750, not this crap.
18607 	 * OTOH, if what follows is pretty random, then I'm in better shape.
18608 	 */
18609 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
18610 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
18611 
18612 	/*
18613 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
18614 	 * as a good template.
18615 	 */
18616 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
18617 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
18618 
18619 	/*
18620 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
18621 	 */
18622 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
18623 
18624 	/*
18625 	 * See 4010593 if this section becomes a problem again,
18626 	 * but the local ethernet address is useful here.
18627 	 */
18628 	(void) localetheraddr(NULL,
18629 	    (struct ether_addr *)&tcp_iss_cookie.ether);
18630 
18631 	/*
18632 	 * Hash 'em all together.  The MD5Final is called per-connection.
18633 	 */
18634 	mutex_enter(&tcps->tcps_iss_key_lock);
18635 	MD5Init(&tcps->tcps_iss_key);
18636 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
18637 	    sizeof (tcp_iss_cookie));
18638 	mutex_exit(&tcps->tcps_iss_key_lock);
18639 }
18640 
18641 /*
18642  * Set the RFC 1948 pass phrase
18643  */
18644 /* ARGSUSED */
18645 static int
18646 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
18647     cred_t *cr)
18648 {
18649 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18650 
18651 	/*
18652 	 * Basically, value contains a new pass phrase.  Pass it along!
18653 	 */
18654 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
18655 	return (0);
18656 }
18657 
18658 /* ARGSUSED */
18659 static int
18660 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
18661 {
18662 	bzero(buf, sizeof (tcp_sack_info_t));
18663 	return (0);
18664 }
18665 
18666 /*
18667  * Called by IP when IP is loaded into the kernel
18668  */
18669 void
18670 tcp_ddi_g_init(void)
18671 {
18672 	tcp_timercache = kmem_cache_create("tcp_timercache",
18673 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
18674 	    NULL, NULL, NULL, NULL, NULL, 0);
18675 
18676 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
18677 	    sizeof (tcp_sack_info_t), 0,
18678 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
18679 
18680 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
18681 
18682 	/* Initialize the random number generator */
18683 	tcp_random_init();
18684 
18685 	/* A single callback independently of how many netstacks we have */
18686 	ip_squeue_init(tcp_squeue_add);
18687 
18688 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
18689 
18690 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
18691 
18692 	/*
18693 	 * We want to be informed each time a stack is created or
18694 	 * destroyed in the kernel, so we can maintain the
18695 	 * set of tcp_stack_t's.
18696 	 */
18697 	netstack_register(NS_TCP, tcp_stack_init, NULL, tcp_stack_fini);
18698 }
18699 
18700 
18701 #define	INET_NAME	"ip"
18702 
18703 /*
18704  * Initialize the TCP stack instance.
18705  */
18706 static void *
18707 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
18708 {
18709 	tcp_stack_t	*tcps;
18710 	tcpparam_t	*pa;
18711 	int		i;
18712 	int		error = 0;
18713 	major_t		major;
18714 
18715 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
18716 	tcps->tcps_netstack = ns;
18717 
18718 	/* Initialize locks */
18719 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
18720 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
18721 
18722 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
18723 	tcps->tcps_g_epriv_ports[0] = 2049;
18724 	tcps->tcps_g_epriv_ports[1] = 4045;
18725 	tcps->tcps_min_anonpriv_port = 512;
18726 
18727 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
18728 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
18729 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
18730 	    TCP_ACCEPTOR_FANOUT_SIZE, KM_SLEEP);
18731 
18732 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18733 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
18734 		    MUTEX_DEFAULT, NULL);
18735 	}
18736 
18737 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18738 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
18739 		    MUTEX_DEFAULT, NULL);
18740 	}
18741 
18742 	/* TCP's IPsec code calls the packet dropper. */
18743 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
18744 
18745 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
18746 	tcps->tcps_params = pa;
18747 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18748 
18749 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
18750 	    A_CNT(lcl_tcp_param_arr), tcps);
18751 
18752 	/*
18753 	 * Note: To really walk the device tree you need the devinfo
18754 	 * pointer to your device which is only available after probe/attach.
18755 	 * The following is safe only because it uses ddi_root_node()
18756 	 */
18757 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
18758 	    tcp_opt_obj.odb_opt_arr_cnt);
18759 
18760 	/*
18761 	 * Initialize RFC 1948 secret values.  This will probably be reset once
18762 	 * by the boot scripts.
18763 	 *
18764 	 * Use NULL name, as the name is caught by the new lockstats.
18765 	 *
18766 	 * Initialize with some random, non-guessable string, like the global
18767 	 * T_INFO_ACK.
18768 	 */
18769 
18770 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
18771 	    sizeof (tcp_g_t_info_ack), tcps);
18772 
18773 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
18774 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
18775 
18776 	major = mod_name_to_major(INET_NAME);
18777 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
18778 	ASSERT(error == 0);
18779 	tcps->tcps_ixa_cleanup_mp = allocb_wait(0, BPRI_MED, STR_NOSIG, NULL);
18780 	ASSERT(tcps->tcps_ixa_cleanup_mp != NULL);
18781 	cv_init(&tcps->tcps_ixa_cleanup_cv, NULL, CV_DEFAULT, NULL);
18782 	mutex_init(&tcps->tcps_ixa_cleanup_lock, NULL, MUTEX_DEFAULT, NULL);
18783 
18784 	mutex_init(&tcps->tcps_reclaim_lock, NULL, MUTEX_DEFAULT, NULL);
18785 	tcps->tcps_reclaim = B_FALSE;
18786 	tcps->tcps_reclaim_tid = 0;
18787 	tcps->tcps_reclaim_period = tcps->tcps_rexmit_interval_max * 3;
18788 
18789 	mutex_init(&tcps->tcps_listener_conf_lock, NULL, MUTEX_DEFAULT, NULL);
18790 	list_create(&tcps->tcps_listener_conf, sizeof (tcp_listener_t),
18791 	    offsetof(tcp_listener_t, tl_link));
18792 
18793 	return (tcps);
18794 }
18795 
18796 /*
18797  * Called when the IP module is about to be unloaded.
18798  */
18799 void
18800 tcp_ddi_g_destroy(void)
18801 {
18802 	tcp_g_kstat_fini(tcp_g_kstat);
18803 	tcp_g_kstat = NULL;
18804 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
18805 
18806 	mutex_destroy(&tcp_random_lock);
18807 
18808 	kmem_cache_destroy(tcp_timercache);
18809 	kmem_cache_destroy(tcp_sack_info_cache);
18810 
18811 	netstack_unregister(NS_TCP);
18812 }
18813 
18814 /*
18815  * Free the TCP stack instance.
18816  */
18817 static void
18818 tcp_stack_fini(netstackid_t stackid, void *arg)
18819 {
18820 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
18821 	int i;
18822 
18823 	freeb(tcps->tcps_ixa_cleanup_mp);
18824 	tcps->tcps_ixa_cleanup_mp = NULL;
18825 	cv_destroy(&tcps->tcps_ixa_cleanup_cv);
18826 	mutex_destroy(&tcps->tcps_ixa_cleanup_lock);
18827 
18828 	if (tcps->tcps_reclaim_tid != 0)
18829 		(void) untimeout(tcps->tcps_reclaim_tid);
18830 	mutex_destroy(&tcps->tcps_reclaim_lock);
18831 
18832 	tcp_listener_conf_cleanup(tcps);
18833 
18834 	nd_free(&tcps->tcps_g_nd);
18835 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
18836 	tcps->tcps_params = NULL;
18837 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
18838 	tcps->tcps_wroff_xtra_param = NULL;
18839 
18840 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
18841 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
18842 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
18843 	}
18844 
18845 	for (i = 0; i < TCP_ACCEPTOR_FANOUT_SIZE; i++) {
18846 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
18847 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
18848 	}
18849 
18850 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
18851 	tcps->tcps_bind_fanout = NULL;
18852 
18853 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) *
18854 	    TCP_ACCEPTOR_FANOUT_SIZE);
18855 	tcps->tcps_acceptor_fanout = NULL;
18856 
18857 	mutex_destroy(&tcps->tcps_iss_key_lock);
18858 	mutex_destroy(&tcps->tcps_epriv_port_lock);
18859 
18860 	ip_drop_unregister(&tcps->tcps_dropper);
18861 
18862 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
18863 	tcps->tcps_kstat = NULL;
18864 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
18865 
18866 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
18867 	tcps->tcps_mibkp = NULL;
18868 
18869 	ldi_ident_release(tcps->tcps_ldi_ident);
18870 	kmem_free(tcps, sizeof (*tcps));
18871 }
18872 
18873 /*
18874  * Generate ISS, taking into account NDD changes may happen halfway through.
18875  * (If the iss is not zero, set it.)
18876  */
18877 
18878 static void
18879 tcp_iss_init(tcp_t *tcp)
18880 {
18881 	MD5_CTX context;
18882 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
18883 	uint32_t answer[4];
18884 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18885 	conn_t		*connp = tcp->tcp_connp;
18886 
18887 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
18888 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
18889 	switch (tcps->tcps_strong_iss) {
18890 	case 2:
18891 		mutex_enter(&tcps->tcps_iss_key_lock);
18892 		context = tcps->tcps_iss_key;
18893 		mutex_exit(&tcps->tcps_iss_key_lock);
18894 		arg.ports = connp->conn_ports;
18895 		arg.src = connp->conn_laddr_v6;
18896 		arg.dst = connp->conn_faddr_v6;
18897 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
18898 		MD5Final((uchar_t *)answer, &context);
18899 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
18900 		/*
18901 		 * Now that we've hashed into a unique per-connection sequence
18902 		 * space, add a random increment per strong_iss == 1.  So I
18903 		 * guess we'll have to...
18904 		 */
18905 		/* FALLTHRU */
18906 	case 1:
18907 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
18908 		break;
18909 	default:
18910 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
18911 		break;
18912 	}
18913 	tcp->tcp_valid_bits = TCP_ISS_VALID;
18914 	tcp->tcp_fss = tcp->tcp_iss - 1;
18915 	tcp->tcp_suna = tcp->tcp_iss;
18916 	tcp->tcp_snxt = tcp->tcp_iss + 1;
18917 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
18918 	tcp->tcp_csuna = tcp->tcp_snxt;
18919 }
18920 
18921 /*
18922  * Exported routine for extracting active tcp connection status.
18923  *
18924  * This is used by the Solaris Cluster Networking software to
18925  * gather a list of connections that need to be forwarded to
18926  * specific nodes in the cluster when configuration changes occur.
18927  *
18928  * The callback is invoked for each tcp_t structure from all netstacks,
18929  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
18930  * from the netstack with the specified stack_id. Returning
18931  * non-zero from the callback routine terminates the search.
18932  */
18933 int
18934 cl_tcp_walk_list(netstackid_t stack_id,
18935     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
18936 {
18937 	netstack_handle_t nh;
18938 	netstack_t *ns;
18939 	int ret = 0;
18940 
18941 	if (stack_id >= 0) {
18942 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
18943 			return (EINVAL);
18944 
18945 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
18946 		    ns->netstack_tcp);
18947 		netstack_rele(ns);
18948 		return (ret);
18949 	}
18950 
18951 	netstack_next_init(&nh);
18952 	while ((ns = netstack_next(&nh)) != NULL) {
18953 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
18954 		    ns->netstack_tcp);
18955 		netstack_rele(ns);
18956 	}
18957 	netstack_next_fini(&nh);
18958 	return (ret);
18959 }
18960 
18961 static int
18962 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
18963     tcp_stack_t *tcps)
18964 {
18965 	tcp_t *tcp;
18966 	cl_tcp_info_t	cl_tcpi;
18967 	connf_t	*connfp;
18968 	conn_t	*connp;
18969 	int	i;
18970 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
18971 
18972 	ASSERT(callback != NULL);
18973 
18974 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
18975 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
18976 		connp = NULL;
18977 
18978 		while ((connp =
18979 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
18980 
18981 			tcp = connp->conn_tcp;
18982 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
18983 			cl_tcpi.cl_tcpi_ipversion = connp->conn_ipversion;
18984 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
18985 			cl_tcpi.cl_tcpi_lport = connp->conn_lport;
18986 			cl_tcpi.cl_tcpi_fport = connp->conn_fport;
18987 			cl_tcpi.cl_tcpi_laddr_v6 = connp->conn_laddr_v6;
18988 			cl_tcpi.cl_tcpi_faddr_v6 = connp->conn_faddr_v6;
18989 
18990 			/*
18991 			 * If the callback returns non-zero
18992 			 * we terminate the traversal.
18993 			 */
18994 			if ((*callback)(&cl_tcpi, arg) != 0) {
18995 				CONN_DEC_REF(tcp->tcp_connp);
18996 				return (1);
18997 			}
18998 		}
18999 	}
19000 
19001 	return (0);
19002 }
19003 
19004 /*
19005  * Macros used for accessing the different types of sockaddr
19006  * structures inside a tcp_ioc_abort_conn_t.
19007  */
19008 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
19009 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
19010 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
19011 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
19012 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
19013 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
19014 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
19015 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
19016 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
19017 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
19018 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
19019 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
19020 
19021 /*
19022  * Return the correct error code to mimic the behavior
19023  * of a connection reset.
19024  */
19025 #define	TCP_AC_GET_ERRCODE(state, err) {	\
19026 		switch ((state)) {		\
19027 		case TCPS_SYN_SENT:		\
19028 		case TCPS_SYN_RCVD:		\
19029 			(err) = ECONNREFUSED;	\
19030 			break;			\
19031 		case TCPS_ESTABLISHED:		\
19032 		case TCPS_FIN_WAIT_1:		\
19033 		case TCPS_FIN_WAIT_2:		\
19034 		case TCPS_CLOSE_WAIT:		\
19035 			(err) = ECONNRESET;	\
19036 			break;			\
19037 		case TCPS_CLOSING:		\
19038 		case TCPS_LAST_ACK:		\
19039 		case TCPS_TIME_WAIT:		\
19040 			(err) = 0;		\
19041 			break;			\
19042 		default:			\
19043 			(err) = ENXIO;		\
19044 		}				\
19045 	}
19046 
19047 /*
19048  * Check if a tcp structure matches the info in acp.
19049  */
19050 #define	TCP_AC_ADDR_MATCH(acp, connp, tcp)			\
19051 	(((acp)->ac_local.ss_family == AF_INET) ?		\
19052 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
19053 	TCP_AC_V4LOCAL((acp)) == (connp)->conn_laddr_v4) &&	\
19054 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
19055 	TCP_AC_V4REMOTE((acp)) == (connp)->conn_faddr_v4) &&	\
19056 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
19057 	TCP_AC_V4LPORT((acp)) == (connp)->conn_lport) &&	\
19058 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
19059 	TCP_AC_V4RPORT((acp)) == (connp)->conn_fport) &&	\
19060 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19061 	(acp)->ac_end >= (tcp)->tcp_state) :			\
19062 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
19063 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
19064 	&(connp)->conn_laddr_v6)) &&				\
19065 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
19066 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
19067 	&(connp)->conn_faddr_v6)) &&				\
19068 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
19069 	TCP_AC_V6LPORT((acp)) == (connp)->conn_lport) &&	\
19070 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
19071 	TCP_AC_V6RPORT((acp)) == (connp)->conn_fport) &&	\
19072 	(acp)->ac_start <= (tcp)->tcp_state &&			\
19073 	(acp)->ac_end >= (tcp)->tcp_state))
19074 
19075 #define	TCP_AC_MATCH(acp, connp, tcp)				\
19076 	(((acp)->ac_zoneid == ALL_ZONES ||			\
19077 	(acp)->ac_zoneid == (connp)->conn_zoneid) ?		\
19078 	TCP_AC_ADDR_MATCH(acp, connp, tcp) : 0)
19079 
19080 /*
19081  * Build a message containing a tcp_ioc_abort_conn_t structure
19082  * which is filled in with information from acp and tp.
19083  */
19084 static mblk_t *
19085 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
19086 {
19087 	mblk_t *mp;
19088 	tcp_ioc_abort_conn_t *tacp;
19089 
19090 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
19091 	if (mp == NULL)
19092 		return (NULL);
19093 
19094 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
19095 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
19096 	    sizeof (uint32_t));
19097 
19098 	tacp->ac_start = acp->ac_start;
19099 	tacp->ac_end = acp->ac_end;
19100 	tacp->ac_zoneid = acp->ac_zoneid;
19101 
19102 	if (acp->ac_local.ss_family == AF_INET) {
19103 		tacp->ac_local.ss_family = AF_INET;
19104 		tacp->ac_remote.ss_family = AF_INET;
19105 		TCP_AC_V4LOCAL(tacp) = tp->tcp_connp->conn_laddr_v4;
19106 		TCP_AC_V4REMOTE(tacp) = tp->tcp_connp->conn_faddr_v4;
19107 		TCP_AC_V4LPORT(tacp) = tp->tcp_connp->conn_lport;
19108 		TCP_AC_V4RPORT(tacp) = tp->tcp_connp->conn_fport;
19109 	} else {
19110 		tacp->ac_local.ss_family = AF_INET6;
19111 		tacp->ac_remote.ss_family = AF_INET6;
19112 		TCP_AC_V6LOCAL(tacp) = tp->tcp_connp->conn_laddr_v6;
19113 		TCP_AC_V6REMOTE(tacp) = tp->tcp_connp->conn_faddr_v6;
19114 		TCP_AC_V6LPORT(tacp) = tp->tcp_connp->conn_lport;
19115 		TCP_AC_V6RPORT(tacp) = tp->tcp_connp->conn_fport;
19116 	}
19117 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
19118 	return (mp);
19119 }
19120 
19121 /*
19122  * Print a tcp_ioc_abort_conn_t structure.
19123  */
19124 static void
19125 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
19126 {
19127 	char lbuf[128];
19128 	char rbuf[128];
19129 	sa_family_t af;
19130 	in_port_t lport, rport;
19131 	ushort_t logflags;
19132 
19133 	af = acp->ac_local.ss_family;
19134 
19135 	if (af == AF_INET) {
19136 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
19137 		    lbuf, 128);
19138 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
19139 		    rbuf, 128);
19140 		lport = ntohs(TCP_AC_V4LPORT(acp));
19141 		rport = ntohs(TCP_AC_V4RPORT(acp));
19142 	} else {
19143 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
19144 		    lbuf, 128);
19145 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
19146 		    rbuf, 128);
19147 		lport = ntohs(TCP_AC_V6LPORT(acp));
19148 		rport = ntohs(TCP_AC_V6RPORT(acp));
19149 	}
19150 
19151 	logflags = SL_TRACE | SL_NOTE;
19152 	/*
19153 	 * Don't print this message to the console if the operation was done
19154 	 * to a non-global zone.
19155 	 */
19156 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19157 		logflags |= SL_CONSOLE;
19158 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
19159 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
19160 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
19161 	    acp->ac_start, acp->ac_end);
19162 }
19163 
19164 /*
19165  * Called using SQ_FILL when a message built using
19166  * tcp_ioctl_abort_build_msg is put into a queue.
19167  * Note that when we get here there is no wildcard in acp any more.
19168  */
19169 /* ARGSUSED2 */
19170 static void
19171 tcp_ioctl_abort_handler(void *arg, mblk_t *mp, void *arg2,
19172     ip_recv_attr_t *dummy)
19173 {
19174 	conn_t			*connp = (conn_t *)arg;
19175 	tcp_t			*tcp = connp->conn_tcp;
19176 	tcp_ioc_abort_conn_t	*acp;
19177 
19178 	/*
19179 	 * Don't accept any input on a closed tcp as this TCP logically does
19180 	 * not exist on the system. Don't proceed further with this TCP.
19181 	 * For eg. this packet could trigger another close of this tcp
19182 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
19183 	 * tcp_clean_death / tcp_closei_local must be called at most once
19184 	 * on a TCP.
19185 	 */
19186 	if (tcp->tcp_state == TCPS_CLOSED ||
19187 	    tcp->tcp_state == TCPS_BOUND) {
19188 		freemsg(mp);
19189 		return;
19190 	}
19191 
19192 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
19193 	if (tcp->tcp_state <= acp->ac_end) {
19194 		/*
19195 		 * If we get here, we are already on the correct
19196 		 * squeue. This ioctl follows the following path
19197 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
19198 		 * ->tcp_ioctl_abort->squeue_enter (if on a
19199 		 * different squeue)
19200 		 */
19201 		int errcode;
19202 
19203 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
19204 		(void) tcp_clean_death(tcp, errcode, 26);
19205 	}
19206 	freemsg(mp);
19207 }
19208 
19209 /*
19210  * Abort all matching connections on a hash chain.
19211  */
19212 static int
19213 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
19214     boolean_t exact, tcp_stack_t *tcps)
19215 {
19216 	int nmatch, err = 0;
19217 	tcp_t *tcp;
19218 	MBLKP mp, last, listhead = NULL;
19219 	conn_t	*tconnp;
19220 	connf_t	*connfp;
19221 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19222 
19223 	connfp = &ipst->ips_ipcl_conn_fanout[index];
19224 
19225 startover:
19226 	nmatch = 0;
19227 
19228 	mutex_enter(&connfp->connf_lock);
19229 	for (tconnp = connfp->connf_head; tconnp != NULL;
19230 	    tconnp = tconnp->conn_next) {
19231 		tcp = tconnp->conn_tcp;
19232 		/*
19233 		 * We are missing a check on sin6_scope_id for linklocals here,
19234 		 * but current usage is just for aborting based on zoneid
19235 		 * for shared-IP zones.
19236 		 */
19237 		if (TCP_AC_MATCH(acp, tconnp, tcp)) {
19238 			CONN_INC_REF(tconnp);
19239 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
19240 			if (mp == NULL) {
19241 				err = ENOMEM;
19242 				CONN_DEC_REF(tconnp);
19243 				break;
19244 			}
19245 			mp->b_prev = (mblk_t *)tcp;
19246 
19247 			if (listhead == NULL) {
19248 				listhead = mp;
19249 				last = mp;
19250 			} else {
19251 				last->b_next = mp;
19252 				last = mp;
19253 			}
19254 			nmatch++;
19255 			if (exact)
19256 				break;
19257 		}
19258 
19259 		/* Avoid holding lock for too long. */
19260 		if (nmatch >= 500)
19261 			break;
19262 	}
19263 	mutex_exit(&connfp->connf_lock);
19264 
19265 	/* Pass mp into the correct tcp */
19266 	while ((mp = listhead) != NULL) {
19267 		listhead = listhead->b_next;
19268 		tcp = (tcp_t *)mp->b_prev;
19269 		mp->b_next = mp->b_prev = NULL;
19270 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp,
19271 		    tcp_ioctl_abort_handler, tcp->tcp_connp, NULL,
19272 		    SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
19273 	}
19274 
19275 	*count += nmatch;
19276 	if (nmatch >= 500 && err == 0)
19277 		goto startover;
19278 	return (err);
19279 }
19280 
19281 /*
19282  * Abort all connections that matches the attributes specified in acp.
19283  */
19284 static int
19285 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
19286 {
19287 	sa_family_t af;
19288 	uint32_t  ports;
19289 	uint16_t *pports;
19290 	int err = 0, count = 0;
19291 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
19292 	int index = -1;
19293 	ushort_t logflags;
19294 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19295 
19296 	af = acp->ac_local.ss_family;
19297 
19298 	if (af == AF_INET) {
19299 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
19300 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
19301 			pports = (uint16_t *)&ports;
19302 			pports[1] = TCP_AC_V4LPORT(acp);
19303 			pports[0] = TCP_AC_V4RPORT(acp);
19304 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
19305 		}
19306 	} else {
19307 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
19308 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
19309 			pports = (uint16_t *)&ports;
19310 			pports[1] = TCP_AC_V6LPORT(acp);
19311 			pports[0] = TCP_AC_V6RPORT(acp);
19312 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
19313 		}
19314 	}
19315 
19316 	/*
19317 	 * For cases where remote addr, local port, and remote port are non-
19318 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
19319 	 */
19320 	if (index != -1) {
19321 		err = tcp_ioctl_abort_bucket(acp, index,
19322 		    &count, exact, tcps);
19323 	} else {
19324 		/*
19325 		 * loop through all entries for wildcard case
19326 		 */
19327 		for (index = 0;
19328 		    index < ipst->ips_ipcl_conn_fanout_size;
19329 		    index++) {
19330 			err = tcp_ioctl_abort_bucket(acp, index,
19331 			    &count, exact, tcps);
19332 			if (err != 0)
19333 				break;
19334 		}
19335 	}
19336 
19337 	logflags = SL_TRACE | SL_NOTE;
19338 	/*
19339 	 * Don't print this message to the console if the operation was done
19340 	 * to a non-global zone.
19341 	 */
19342 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
19343 		logflags |= SL_CONSOLE;
19344 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
19345 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
19346 	if (err == 0 && count == 0)
19347 		err = ENOENT;
19348 	return (err);
19349 }
19350 
19351 /*
19352  * Process the TCP_IOC_ABORT_CONN ioctl request.
19353  */
19354 static void
19355 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
19356 {
19357 	int	err;
19358 	IOCP    iocp;
19359 	MBLKP   mp1;
19360 	sa_family_t laf, raf;
19361 	tcp_ioc_abort_conn_t *acp;
19362 	zone_t		*zptr;
19363 	conn_t		*connp = Q_TO_CONN(q);
19364 	zoneid_t	zoneid = connp->conn_zoneid;
19365 	tcp_t		*tcp = connp->conn_tcp;
19366 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19367 
19368 	iocp = (IOCP)mp->b_rptr;
19369 
19370 	if ((mp1 = mp->b_cont) == NULL ||
19371 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
19372 		err = EINVAL;
19373 		goto out;
19374 	}
19375 
19376 	/* check permissions */
19377 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19378 		err = EPERM;
19379 		goto out;
19380 	}
19381 
19382 	if (mp1->b_cont != NULL) {
19383 		freemsg(mp1->b_cont);
19384 		mp1->b_cont = NULL;
19385 	}
19386 
19387 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
19388 	laf = acp->ac_local.ss_family;
19389 	raf = acp->ac_remote.ss_family;
19390 
19391 	/* check that a zone with the supplied zoneid exists */
19392 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
19393 		zptr = zone_find_by_id(zoneid);
19394 		if (zptr != NULL) {
19395 			zone_rele(zptr);
19396 		} else {
19397 			err = EINVAL;
19398 			goto out;
19399 		}
19400 	}
19401 
19402 	/*
19403 	 * For exclusive stacks we set the zoneid to zero
19404 	 * to make TCP operate as if in the global zone.
19405 	 */
19406 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
19407 		acp->ac_zoneid = GLOBAL_ZONEID;
19408 
19409 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
19410 	    acp->ac_start > acp->ac_end || laf != raf ||
19411 	    (laf != AF_INET && laf != AF_INET6)) {
19412 		err = EINVAL;
19413 		goto out;
19414 	}
19415 
19416 	tcp_ioctl_abort_dump(acp);
19417 	err = tcp_ioctl_abort(acp, tcps);
19418 
19419 out:
19420 	if (mp1 != NULL) {
19421 		freemsg(mp1);
19422 		mp->b_cont = NULL;
19423 	}
19424 
19425 	if (err != 0)
19426 		miocnak(q, mp, 0, err);
19427 	else
19428 		miocack(q, mp, 0, 0);
19429 }
19430 
19431 /*
19432  * tcp_time_wait_processing() handles processing of incoming packets when
19433  * the tcp is in the TIME_WAIT state.
19434  * A TIME_WAIT tcp that has an associated open TCP stream is never put
19435  * on the time wait list.
19436  */
19437 void
19438 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
19439     uint32_t seg_ack, int seg_len, tcpha_t *tcpha, ip_recv_attr_t *ira)
19440 {
19441 	int32_t		bytes_acked;
19442 	int32_t		gap;
19443 	int32_t		rgap;
19444 	tcp_opt_t	tcpopt;
19445 	uint_t		flags;
19446 	uint32_t	new_swnd = 0;
19447 	conn_t		*nconnp;
19448 	conn_t		*connp = tcp->tcp_connp;
19449 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19450 
19451 	BUMP_LOCAL(tcp->tcp_ibsegs);
19452 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
19453 
19454 	flags = (unsigned int)tcpha->tha_flags & 0xFF;
19455 	new_swnd = ntohs(tcpha->tha_win) <<
19456 	    ((tcpha->tha_flags & TH_SYN) ? 0 : tcp->tcp_snd_ws);
19457 	if (tcp->tcp_snd_ts_ok) {
19458 		if (!tcp_paws_check(tcp, tcpha, &tcpopt)) {
19459 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19460 			    tcp->tcp_rnxt, TH_ACK);
19461 			goto done;
19462 		}
19463 	}
19464 	gap = seg_seq - tcp->tcp_rnxt;
19465 	rgap = tcp->tcp_rwnd - (gap + seg_len);
19466 	if (gap < 0) {
19467 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
19468 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
19469 		    (seg_len > -gap ? -gap : seg_len));
19470 		seg_len += gap;
19471 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
19472 			if (flags & TH_RST) {
19473 				goto done;
19474 			}
19475 			if ((flags & TH_FIN) && seg_len == -1) {
19476 				/*
19477 				 * When TCP receives a duplicate FIN in
19478 				 * TIME_WAIT state, restart the 2 MSL timer.
19479 				 * See page 73 in RFC 793. Make sure this TCP
19480 				 * is already on the TIME_WAIT list. If not,
19481 				 * just restart the timer.
19482 				 */
19483 				if (TCP_IS_DETACHED(tcp)) {
19484 					if (tcp_time_wait_remove(tcp, NULL) ==
19485 					    B_TRUE) {
19486 						tcp_time_wait_append(tcp);
19487 						TCP_DBGSTAT(tcps,
19488 						    tcp_rput_time_wait);
19489 					}
19490 				} else {
19491 					ASSERT(tcp != NULL);
19492 					TCP_TIMER_RESTART(tcp,
19493 					    tcps->tcps_time_wait_interval);
19494 				}
19495 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19496 				    tcp->tcp_rnxt, TH_ACK);
19497 				goto done;
19498 			}
19499 			flags |=  TH_ACK_NEEDED;
19500 			seg_len = 0;
19501 			goto process_ack;
19502 		}
19503 
19504 		/* Fix seg_seq, and chew the gap off the front. */
19505 		seg_seq = tcp->tcp_rnxt;
19506 	}
19507 
19508 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
19509 		/*
19510 		 * Make sure that when we accept the connection, pick
19511 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
19512 		 * old connection.
19513 		 *
19514 		 * The next ISS generated is equal to tcp_iss_incr_extra
19515 		 * + ISS_INCR/2 + other components depending on the
19516 		 * value of tcp_strong_iss.  We pre-calculate the new
19517 		 * ISS here and compare with tcp_snxt to determine if
19518 		 * we need to make adjustment to tcp_iss_incr_extra.
19519 		 *
19520 		 * The above calculation is ugly and is a
19521 		 * waste of CPU cycles...
19522 		 */
19523 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
19524 		int32_t adj;
19525 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
19526 
19527 		switch (tcps->tcps_strong_iss) {
19528 		case 2: {
19529 			/* Add time and MD5 components. */
19530 			uint32_t answer[4];
19531 			struct {
19532 				uint32_t ports;
19533 				in6_addr_t src;
19534 				in6_addr_t dst;
19535 			} arg;
19536 			MD5_CTX context;
19537 
19538 			mutex_enter(&tcps->tcps_iss_key_lock);
19539 			context = tcps->tcps_iss_key;
19540 			mutex_exit(&tcps->tcps_iss_key_lock);
19541 			arg.ports = connp->conn_ports;
19542 			/* We use MAPPED addresses in tcp_iss_init */
19543 			arg.src = connp->conn_laddr_v6;
19544 			arg.dst = connp->conn_faddr_v6;
19545 			MD5Update(&context, (uchar_t *)&arg,
19546 			    sizeof (arg));
19547 			MD5Final((uchar_t *)answer, &context);
19548 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
19549 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
19550 			break;
19551 		}
19552 		case 1:
19553 			/* Add time component and min random (i.e. 1). */
19554 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
19555 			break;
19556 		default:
19557 			/* Add only time component. */
19558 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
19559 			break;
19560 		}
19561 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
19562 			/*
19563 			 * New ISS not guaranteed to be ISS_INCR/2
19564 			 * ahead of the current tcp_snxt, so add the
19565 			 * difference to tcp_iss_incr_extra.
19566 			 */
19567 			tcps->tcps_iss_incr_extra += adj;
19568 		}
19569 		/*
19570 		 * If tcp_clean_death() can not perform the task now,
19571 		 * drop the SYN packet and let the other side re-xmit.
19572 		 * Otherwise pass the SYN packet back in, since the
19573 		 * old tcp state has been cleaned up or freed.
19574 		 */
19575 		if (tcp_clean_death(tcp, 0, 27) == -1)
19576 			goto done;
19577 		nconnp = ipcl_classify(mp, ira, ipst);
19578 		if (nconnp != NULL) {
19579 			TCP_STAT(tcps, tcp_time_wait_syn_success);
19580 			/* Drops ref on nconnp */
19581 			tcp_reinput(nconnp, mp, ira, ipst);
19582 			return;
19583 		}
19584 		goto done;
19585 	}
19586 
19587 	/*
19588 	 * rgap is the amount of stuff received out of window.  A negative
19589 	 * value is the amount out of window.
19590 	 */
19591 	if (rgap < 0) {
19592 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
19593 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
19594 		/* Fix seg_len and make sure there is something left. */
19595 		seg_len += rgap;
19596 		if (seg_len <= 0) {
19597 			if (flags & TH_RST) {
19598 				goto done;
19599 			}
19600 			flags |=  TH_ACK_NEEDED;
19601 			seg_len = 0;
19602 			goto process_ack;
19603 		}
19604 	}
19605 	/*
19606 	 * Check whether we can update tcp_ts_recent.  This test is
19607 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
19608 	 * Extensions for High Performance: An Update", Internet Draft.
19609 	 */
19610 	if (tcp->tcp_snd_ts_ok &&
19611 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
19612 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
19613 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
19614 		tcp->tcp_last_rcv_lbolt = ddi_get_lbolt64();
19615 	}
19616 
19617 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
19618 		/* Always ack out of order packets */
19619 		flags |= TH_ACK_NEEDED;
19620 		seg_len = 0;
19621 	} else if (seg_len > 0) {
19622 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
19623 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
19624 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
19625 	}
19626 	if (flags & TH_RST) {
19627 		(void) tcp_clean_death(tcp, 0, 28);
19628 		goto done;
19629 	}
19630 	if (flags & TH_SYN) {
19631 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
19632 		    TH_RST|TH_ACK);
19633 		/*
19634 		 * Do not delete the TCP structure if it is in
19635 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
19636 		 */
19637 		goto done;
19638 	}
19639 process_ack:
19640 	if (flags & TH_ACK) {
19641 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
19642 		if (bytes_acked <= 0) {
19643 			if (bytes_acked == 0 && seg_len == 0 &&
19644 			    new_swnd == tcp->tcp_swnd)
19645 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
19646 		} else {
19647 			/* Acks something not sent */
19648 			flags |= TH_ACK_NEEDED;
19649 		}
19650 	}
19651 	if (flags & TH_ACK_NEEDED) {
19652 		/*
19653 		 * Time to send an ack for some reason.
19654 		 */
19655 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
19656 		    tcp->tcp_rnxt, TH_ACK);
19657 	}
19658 done:
19659 	freemsg(mp);
19660 }
19661 
19662 /*
19663  * TCP Timers Implementation.
19664  */
19665 timeout_id_t
19666 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
19667 {
19668 	mblk_t *mp;
19669 	tcp_timer_t *tcpt;
19670 	tcp_t *tcp = connp->conn_tcp;
19671 
19672 	ASSERT(connp->conn_sqp != NULL);
19673 
19674 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
19675 
19676 	if (tcp->tcp_timercache == NULL) {
19677 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
19678 	} else {
19679 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
19680 		mp = tcp->tcp_timercache;
19681 		tcp->tcp_timercache = mp->b_next;
19682 		mp->b_next = NULL;
19683 		ASSERT(mp->b_wptr == NULL);
19684 	}
19685 
19686 	CONN_INC_REF(connp);
19687 	tcpt = (tcp_timer_t *)mp->b_rptr;
19688 	tcpt->connp = connp;
19689 	tcpt->tcpt_proc = f;
19690 	/*
19691 	 * TCP timers are normal timeouts. Plus, they do not require more than
19692 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
19693 	 * rounding up the expiration to the next resolution boundary, we can
19694 	 * batch timers in the callout subsystem to make TCP timers more
19695 	 * efficient. The roundup also protects short timers from expiring too
19696 	 * early before they have a chance to be cancelled.
19697 	 */
19698 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
19699 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
19700 
19701 	return ((timeout_id_t)mp);
19702 }
19703 
19704 static void
19705 tcp_timer_callback(void *arg)
19706 {
19707 	mblk_t *mp = (mblk_t *)arg;
19708 	tcp_timer_t *tcpt;
19709 	conn_t	*connp;
19710 
19711 	tcpt = (tcp_timer_t *)mp->b_rptr;
19712 	connp = tcpt->connp;
19713 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
19714 	    NULL, SQ_FILL, SQTAG_TCP_TIMER);
19715 }
19716 
19717 /* ARGSUSED */
19718 static void
19719 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
19720 {
19721 	tcp_timer_t *tcpt;
19722 	conn_t *connp = (conn_t *)arg;
19723 	tcp_t *tcp = connp->conn_tcp;
19724 
19725 	tcpt = (tcp_timer_t *)mp->b_rptr;
19726 	ASSERT(connp == tcpt->connp);
19727 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
19728 
19729 	/*
19730 	 * If the TCP has reached the closed state, don't proceed any
19731 	 * further. This TCP logically does not exist on the system.
19732 	 * tcpt_proc could for example access queues, that have already
19733 	 * been qprocoff'ed off.
19734 	 */
19735 	if (tcp->tcp_state != TCPS_CLOSED) {
19736 		(*tcpt->tcpt_proc)(connp);
19737 	} else {
19738 		tcp->tcp_timer_tid = 0;
19739 	}
19740 	tcp_timer_free(connp->conn_tcp, mp);
19741 }
19742 
19743 /*
19744  * There is potential race with untimeout and the handler firing at the same
19745  * time. The mblock may be freed by the handler while we are trying to use
19746  * it. But since both should execute on the same squeue, this race should not
19747  * occur.
19748  */
19749 clock_t
19750 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
19751 {
19752 	mblk_t	*mp = (mblk_t *)id;
19753 	tcp_timer_t *tcpt;
19754 	clock_t delta;
19755 
19756 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
19757 
19758 	if (mp == NULL)
19759 		return (-1);
19760 
19761 	tcpt = (tcp_timer_t *)mp->b_rptr;
19762 	ASSERT(tcpt->connp == connp);
19763 
19764 	delta = untimeout_default(tcpt->tcpt_tid, 0);
19765 
19766 	if (delta >= 0) {
19767 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
19768 		tcp_timer_free(connp->conn_tcp, mp);
19769 		CONN_DEC_REF(connp);
19770 	}
19771 
19772 	return (delta);
19773 }
19774 
19775 /*
19776  * Allocate space for the timer event. The allocation looks like mblk, but it is
19777  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
19778  *
19779  * Dealing with failures: If we can't allocate from the timer cache we try
19780  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
19781  * points to b_rptr.
19782  * If we can't allocate anything using allocb_tryhard(), we perform a last
19783  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
19784  * save the actual allocation size in b_datap.
19785  */
19786 mblk_t *
19787 tcp_timermp_alloc(int kmflags)
19788 {
19789 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
19790 	    kmflags & ~KM_PANIC);
19791 
19792 	if (mp != NULL) {
19793 		mp->b_next = mp->b_prev = NULL;
19794 		mp->b_rptr = (uchar_t *)(&mp[1]);
19795 		mp->b_wptr = NULL;
19796 		mp->b_datap = NULL;
19797 		mp->b_queue = NULL;
19798 		mp->b_cont = NULL;
19799 	} else if (kmflags & KM_PANIC) {
19800 		/*
19801 		 * Failed to allocate memory for the timer. Try allocating from
19802 		 * dblock caches.
19803 		 */
19804 		/* ipclassifier calls this from a constructor - hence no tcps */
19805 		TCP_G_STAT(tcp_timermp_allocfail);
19806 		mp = allocb_tryhard(sizeof (tcp_timer_t));
19807 		if (mp == NULL) {
19808 			size_t size = 0;
19809 			/*
19810 			 * Memory is really low. Try tryhard allocation.
19811 			 *
19812 			 * ipclassifier calls this from a constructor -
19813 			 * hence no tcps
19814 			 */
19815 			TCP_G_STAT(tcp_timermp_allocdblfail);
19816 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
19817 			    sizeof (tcp_timer_t), &size, kmflags);
19818 			mp->b_rptr = (uchar_t *)(&mp[1]);
19819 			mp->b_next = mp->b_prev = NULL;
19820 			mp->b_wptr = (uchar_t *)-1;
19821 			mp->b_datap = (dblk_t *)size;
19822 			mp->b_queue = NULL;
19823 			mp->b_cont = NULL;
19824 		}
19825 		ASSERT(mp->b_wptr != NULL);
19826 	}
19827 	/* ipclassifier calls this from a constructor - hence no tcps */
19828 	TCP_G_DBGSTAT(tcp_timermp_alloced);
19829 
19830 	return (mp);
19831 }
19832 
19833 /*
19834  * Free per-tcp timer cache.
19835  * It can only contain entries from tcp_timercache.
19836  */
19837 void
19838 tcp_timermp_free(tcp_t *tcp)
19839 {
19840 	mblk_t *mp;
19841 
19842 	while ((mp = tcp->tcp_timercache) != NULL) {
19843 		ASSERT(mp->b_wptr == NULL);
19844 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
19845 		kmem_cache_free(tcp_timercache, mp);
19846 	}
19847 }
19848 
19849 /*
19850  * Free timer event. Put it on the per-tcp timer cache if there is not too many
19851  * events there already (currently at most two events are cached).
19852  * If the event is not allocated from the timer cache, free it right away.
19853  */
19854 static void
19855 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
19856 {
19857 	mblk_t *mp1 = tcp->tcp_timercache;
19858 
19859 	if (mp->b_wptr != NULL) {
19860 		/*
19861 		 * This allocation is not from a timer cache, free it right
19862 		 * away.
19863 		 */
19864 		if (mp->b_wptr != (uchar_t *)-1)
19865 			freeb(mp);
19866 		else
19867 			kmem_free(mp, (size_t)mp->b_datap);
19868 	} else if (mp1 == NULL || mp1->b_next == NULL) {
19869 		/* Cache this timer block for future allocations */
19870 		mp->b_rptr = (uchar_t *)(&mp[1]);
19871 		mp->b_next = mp1;
19872 		tcp->tcp_timercache = mp;
19873 	} else {
19874 		kmem_cache_free(tcp_timercache, mp);
19875 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
19876 	}
19877 }
19878 
19879 /*
19880  * End of TCP Timers implementation.
19881  */
19882 
19883 /*
19884  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
19885  * on the specified backing STREAMS q. Note, the caller may make the
19886  * decision to call based on the tcp_t.tcp_flow_stopped value which
19887  * when check outside the q's lock is only an advisory check ...
19888  */
19889 void
19890 tcp_setqfull(tcp_t *tcp)
19891 {
19892 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19893 	conn_t	*connp = tcp->tcp_connp;
19894 
19895 	if (tcp->tcp_closed)
19896 		return;
19897 
19898 	conn_setqfull(connp, &tcp->tcp_flow_stopped);
19899 	if (tcp->tcp_flow_stopped)
19900 		TCP_STAT(tcps, tcp_flwctl_on);
19901 }
19902 
19903 void
19904 tcp_clrqfull(tcp_t *tcp)
19905 {
19906 	conn_t  *connp = tcp->tcp_connp;
19907 
19908 	if (tcp->tcp_closed)
19909 		return;
19910 	conn_clrqfull(connp, &tcp->tcp_flow_stopped);
19911 }
19912 
19913 /*
19914  * kstats related to squeues i.e. not per IP instance
19915  */
19916 static void *
19917 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
19918 {
19919 	kstat_t *ksp;
19920 
19921 	tcp_g_stat_t template = {
19922 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
19923 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
19924 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
19925 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
19926 	};
19927 
19928 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
19929 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
19930 	    KSTAT_FLAG_VIRTUAL);
19931 
19932 	if (ksp == NULL)
19933 		return (NULL);
19934 
19935 	bcopy(&template, tcp_g_statp, sizeof (template));
19936 	ksp->ks_data = (void *)tcp_g_statp;
19937 
19938 	kstat_install(ksp);
19939 	return (ksp);
19940 }
19941 
19942 static void
19943 tcp_g_kstat_fini(kstat_t *ksp)
19944 {
19945 	if (ksp != NULL) {
19946 		kstat_delete(ksp);
19947 	}
19948 }
19949 
19950 
19951 static void *
19952 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
19953 {
19954 	kstat_t *ksp;
19955 
19956 	tcp_stat_t template = {
19957 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
19958 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
19959 		{ "tcp_time_wait_syn_success",	KSTAT_DATA_UINT64 },
19960 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
19961 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
19962 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
19963 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
19964 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
19965 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
19966 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
19967 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
19968 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
19969 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
19970 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
19971 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
19972 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
19973 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
19974 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
19975 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
19976 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
19977 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
19978 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
19979 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
19980 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
19981 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
19982 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
19983 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
19984 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
19985 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
19986 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
19987 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
19988 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
19989 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
19990 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
19991 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
19992 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
19993 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
19994 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
19995 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
19996 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
19997 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
19998 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
19999 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
20000 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
20001 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
20002 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
20003 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
20004 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
20005 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
20006 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
20007 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
20008 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
20009 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
20010 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
20011 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
20012 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
20013 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
20014 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
20015 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
20016 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
20017 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
20018 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
20019 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
20020 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
20021 		{ "tcp_listen_cnt_drop",	KSTAT_DATA_UINT64 },
20022 		{ "tcp_listen_mem_drop",	KSTAT_DATA_UINT64 },
20023 		{ "tcp_zwin_ack_syn",		KSTAT_DATA_UINT64 },
20024 		{ "tcp_rst_unsent",		KSTAT_DATA_UINT64 }
20025 	};
20026 
20027 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
20028 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
20029 	    KSTAT_FLAG_VIRTUAL, stackid);
20030 
20031 	if (ksp == NULL)
20032 		return (NULL);
20033 
20034 	bcopy(&template, tcps_statisticsp, sizeof (template));
20035 	ksp->ks_data = (void *)tcps_statisticsp;
20036 	ksp->ks_private = (void *)(uintptr_t)stackid;
20037 
20038 	kstat_install(ksp);
20039 	return (ksp);
20040 }
20041 
20042 static void
20043 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
20044 {
20045 	if (ksp != NULL) {
20046 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20047 		kstat_delete_netstack(ksp, stackid);
20048 	}
20049 }
20050 
20051 /*
20052  * TCP Kstats implementation
20053  */
20054 static void *
20055 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
20056 {
20057 	kstat_t	*ksp;
20058 
20059 	tcp_named_kstat_t template = {
20060 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
20061 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
20062 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
20063 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
20064 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
20065 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
20066 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
20067 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
20068 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
20069 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
20070 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
20071 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
20072 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
20073 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
20074 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
20075 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
20076 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
20077 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
20078 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
20079 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
20080 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
20081 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
20082 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
20083 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
20084 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
20085 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
20086 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
20087 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
20088 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
20089 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
20090 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
20091 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
20092 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
20093 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
20094 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
20095 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
20096 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
20097 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
20098 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
20099 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
20100 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
20101 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
20102 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
20103 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
20104 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
20105 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
20106 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
20107 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
20108 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
20109 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
20110 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
20111 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
20112 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
20113 	};
20114 
20115 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
20116 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
20117 
20118 	if (ksp == NULL)
20119 		return (NULL);
20120 
20121 	template.rtoAlgorithm.value.ui32 = 4;
20122 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
20123 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
20124 	template.maxConn.value.i32 = -1;
20125 
20126 	bcopy(&template, ksp->ks_data, sizeof (template));
20127 	ksp->ks_update = tcp_kstat_update;
20128 	ksp->ks_private = (void *)(uintptr_t)stackid;
20129 
20130 	kstat_install(ksp);
20131 	return (ksp);
20132 }
20133 
20134 static void
20135 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
20136 {
20137 	if (ksp != NULL) {
20138 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
20139 		kstat_delete_netstack(ksp, stackid);
20140 	}
20141 }
20142 
20143 static int
20144 tcp_kstat_update(kstat_t *kp, int rw)
20145 {
20146 	tcp_named_kstat_t *tcpkp;
20147 	tcp_t		*tcp;
20148 	connf_t		*connfp;
20149 	conn_t		*connp;
20150 	int 		i;
20151 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
20152 	netstack_t	*ns;
20153 	tcp_stack_t	*tcps;
20154 	ip_stack_t	*ipst;
20155 
20156 	if ((kp == NULL) || (kp->ks_data == NULL))
20157 		return (EIO);
20158 
20159 	if (rw == KSTAT_WRITE)
20160 		return (EACCES);
20161 
20162 	ns = netstack_find_by_stackid(stackid);
20163 	if (ns == NULL)
20164 		return (-1);
20165 	tcps = ns->netstack_tcp;
20166 	if (tcps == NULL) {
20167 		netstack_rele(ns);
20168 		return (-1);
20169 	}
20170 
20171 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
20172 
20173 	tcpkp->currEstab.value.ui32 = 0;
20174 
20175 	ipst = ns->netstack_ip;
20176 
20177 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
20178 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
20179 		connp = NULL;
20180 		while ((connp =
20181 		    ipcl_get_next_conn(connfp, connp, IPCL_TCPCONN)) != NULL) {
20182 			tcp = connp->conn_tcp;
20183 			switch (tcp_snmp_state(tcp)) {
20184 			case MIB2_TCP_established:
20185 			case MIB2_TCP_closeWait:
20186 				tcpkp->currEstab.value.ui32++;
20187 				break;
20188 			}
20189 		}
20190 	}
20191 
20192 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
20193 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
20194 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
20195 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
20196 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
20197 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
20198 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
20199 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
20200 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
20201 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
20202 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
20203 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
20204 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
20205 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
20206 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
20207 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
20208 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
20209 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
20210 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
20211 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
20212 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
20213 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
20214 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
20215 	tcpkp->inDataInorderSegs.value.ui32 =
20216 	    tcps->tcps_mib.tcpInDataInorderSegs;
20217 	tcpkp->inDataInorderBytes.value.ui32 =
20218 	    tcps->tcps_mib.tcpInDataInorderBytes;
20219 	tcpkp->inDataUnorderSegs.value.ui32 =
20220 	    tcps->tcps_mib.tcpInDataUnorderSegs;
20221 	tcpkp->inDataUnorderBytes.value.ui32 =
20222 	    tcps->tcps_mib.tcpInDataUnorderBytes;
20223 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
20224 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
20225 	tcpkp->inDataPartDupSegs.value.ui32 =
20226 	    tcps->tcps_mib.tcpInDataPartDupSegs;
20227 	tcpkp->inDataPartDupBytes.value.ui32 =
20228 	    tcps->tcps_mib.tcpInDataPartDupBytes;
20229 	tcpkp->inDataPastWinSegs.value.ui32 =
20230 	    tcps->tcps_mib.tcpInDataPastWinSegs;
20231 	tcpkp->inDataPastWinBytes.value.ui32 =
20232 	    tcps->tcps_mib.tcpInDataPastWinBytes;
20233 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
20234 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
20235 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
20236 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
20237 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
20238 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
20239 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
20240 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
20241 	tcpkp->timKeepaliveProbe.value.ui32 =
20242 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
20243 	tcpkp->timKeepaliveDrop.value.ui32 =
20244 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
20245 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
20246 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
20247 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
20248 	tcpkp->outSackRetransSegs.value.ui32 =
20249 	    tcps->tcps_mib.tcpOutSackRetransSegs;
20250 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
20251 
20252 	netstack_rele(ns);
20253 	return (0);
20254 }
20255 
20256 static int
20257 tcp_squeue_switch(int val)
20258 {
20259 	int rval = SQ_FILL;
20260 
20261 	switch (val) {
20262 	case 1:
20263 		rval = SQ_NODRAIN;
20264 		break;
20265 	case 2:
20266 		rval = SQ_PROCESS;
20267 		break;
20268 	default:
20269 		break;
20270 	}
20271 	return (rval);
20272 }
20273 
20274 /*
20275  * This is called once for each squeue - globally for all stack
20276  * instances.
20277  */
20278 static void
20279 tcp_squeue_add(squeue_t *sqp)
20280 {
20281 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
20282 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
20283 
20284 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
20285 	tcp_time_wait->tcp_time_wait_tid =
20286 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
20287 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
20288 	    CALLOUT_FLAG_ROUNDUP);
20289 	if (tcp_free_list_max_cnt == 0) {
20290 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
20291 		    max_ncpus : boot_max_ncpus);
20292 
20293 		/*
20294 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
20295 		 */
20296 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
20297 		    (tcp_ncpus * sizeof (tcp_t) * 100);
20298 	}
20299 	tcp_time_wait->tcp_free_list_cnt = 0;
20300 }
20301 
20302 /*
20303  * On a labeled system we have some protocols above TCP, such as RPC, which
20304  * appear to assume that every mblk in a chain has a db_credp.
20305  */
20306 static void
20307 tcp_setcred_data(mblk_t *mp, ip_recv_attr_t *ira)
20308 {
20309 	ASSERT(is_system_labeled());
20310 	ASSERT(ira->ira_cred != NULL);
20311 
20312 	while (mp != NULL) {
20313 		mblk_setcred(mp, ira->ira_cred, NOPID);
20314 		mp = mp->b_cont;
20315 	}
20316 }
20317 
20318 static int
20319 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
20320     boolean_t bind_to_req_port_only, cred_t *cr)
20321 {
20322 	in_port_t	mlp_port;
20323 	mlp_type_t 	addrtype, mlptype;
20324 	boolean_t	user_specified;
20325 	in_port_t	allocated_port;
20326 	in_port_t	requested_port = *requested_port_ptr;
20327 	conn_t		*connp = tcp->tcp_connp;
20328 	zone_t		*zone;
20329 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20330 	in6_addr_t	v6addr = connp->conn_laddr_v6;
20331 
20332 	/*
20333 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
20334 	 */
20335 	ASSERT(cr != NULL);
20336 
20337 	/*
20338 	 * Get a valid port (within the anonymous range and should not
20339 	 * be a privileged one) to use if the user has not given a port.
20340 	 * If multiple threads are here, they may all start with
20341 	 * with the same initial port. But, it should be fine as long as
20342 	 * tcp_bindi will ensure that no two threads will be assigned
20343 	 * the same port.
20344 	 *
20345 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
20346 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
20347 	 * unless TCP_ANONPRIVBIND option is set.
20348 	 */
20349 	mlptype = mlptSingle;
20350 	mlp_port = requested_port;
20351 	if (requested_port == 0) {
20352 		requested_port = connp->conn_anon_priv_bind ?
20353 		    tcp_get_next_priv_port(tcp) :
20354 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
20355 		    tcp, B_TRUE);
20356 		if (requested_port == 0) {
20357 			return (-TNOADDR);
20358 		}
20359 		user_specified = B_FALSE;
20360 
20361 		/*
20362 		 * If the user went through one of the RPC interfaces to create
20363 		 * this socket and RPC is MLP in this zone, then give him an
20364 		 * anonymous MLP.
20365 		 */
20366 		if (connp->conn_anon_mlp && is_system_labeled()) {
20367 			zone = crgetzone(cr);
20368 			addrtype = tsol_mlp_addr_type(
20369 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20370 			    IPV6_VERSION, &v6addr,
20371 			    tcps->tcps_netstack->netstack_ip);
20372 			if (addrtype == mlptSingle) {
20373 				return (-TNOADDR);
20374 			}
20375 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20376 			    PMAPPORT, addrtype);
20377 			mlp_port = PMAPPORT;
20378 		}
20379 	} else {
20380 		int i;
20381 		boolean_t priv = B_FALSE;
20382 
20383 		/*
20384 		 * If the requested_port is in the well-known privileged range,
20385 		 * verify that the stream was opened by a privileged user.
20386 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
20387 		 * but instead the code relies on:
20388 		 * - the fact that the address of the array and its size never
20389 		 *   changes
20390 		 * - the atomic assignment of the elements of the array
20391 		 */
20392 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
20393 			priv = B_TRUE;
20394 		} else {
20395 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
20396 				if (requested_port ==
20397 				    tcps->tcps_g_epriv_ports[i]) {
20398 					priv = B_TRUE;
20399 					break;
20400 				}
20401 			}
20402 		}
20403 		if (priv) {
20404 			if (secpolicy_net_privaddr(cr, requested_port,
20405 			    IPPROTO_TCP) != 0) {
20406 				if (connp->conn_debug) {
20407 					(void) strlog(TCP_MOD_ID, 0, 1,
20408 					    SL_ERROR|SL_TRACE,
20409 					    "tcp_bind: no priv for port %d",
20410 					    requested_port);
20411 				}
20412 				return (-TACCES);
20413 			}
20414 		}
20415 		user_specified = B_TRUE;
20416 
20417 		connp = tcp->tcp_connp;
20418 		if (is_system_labeled()) {
20419 			zone = crgetzone(cr);
20420 			addrtype = tsol_mlp_addr_type(
20421 			    connp->conn_allzones ? ALL_ZONES : zone->zone_id,
20422 			    IPV6_VERSION, &v6addr,
20423 			    tcps->tcps_netstack->netstack_ip);
20424 			if (addrtype == mlptSingle) {
20425 				return (-TNOADDR);
20426 			}
20427 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
20428 			    requested_port, addrtype);
20429 		}
20430 	}
20431 
20432 	if (mlptype != mlptSingle) {
20433 		if (secpolicy_net_bindmlp(cr) != 0) {
20434 			if (connp->conn_debug) {
20435 				(void) strlog(TCP_MOD_ID, 0, 1,
20436 				    SL_ERROR|SL_TRACE,
20437 				    "tcp_bind: no priv for multilevel port %d",
20438 				    requested_port);
20439 			}
20440 			return (-TACCES);
20441 		}
20442 
20443 		/*
20444 		 * If we're specifically binding a shared IP address and the
20445 		 * port is MLP on shared addresses, then check to see if this
20446 		 * zone actually owns the MLP.  Reject if not.
20447 		 */
20448 		if (mlptype == mlptShared && addrtype == mlptShared) {
20449 			/*
20450 			 * No need to handle exclusive-stack zones since
20451 			 * ALL_ZONES only applies to the shared stack.
20452 			 */
20453 			zoneid_t mlpzone;
20454 
20455 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
20456 			    htons(mlp_port));
20457 			if (connp->conn_zoneid != mlpzone) {
20458 				if (connp->conn_debug) {
20459 					(void) strlog(TCP_MOD_ID, 0, 1,
20460 					    SL_ERROR|SL_TRACE,
20461 					    "tcp_bind: attempt to bind port "
20462 					    "%d on shared addr in zone %d "
20463 					    "(should be %d)",
20464 					    mlp_port, connp->conn_zoneid,
20465 					    mlpzone);
20466 				}
20467 				return (-TACCES);
20468 			}
20469 		}
20470 
20471 		if (!user_specified) {
20472 			int err;
20473 			err = tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20474 			    requested_port, B_TRUE);
20475 			if (err != 0) {
20476 				if (connp->conn_debug) {
20477 					(void) strlog(TCP_MOD_ID, 0, 1,
20478 					    SL_ERROR|SL_TRACE,
20479 					    "tcp_bind: cannot establish anon "
20480 					    "MLP for port %d",
20481 					    requested_port);
20482 				}
20483 				return (err);
20484 			}
20485 			connp->conn_anon_port = B_TRUE;
20486 		}
20487 		connp->conn_mlp_type = mlptype;
20488 	}
20489 
20490 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
20491 	    connp->conn_reuseaddr, B_FALSE, bind_to_req_port_only,
20492 	    user_specified);
20493 
20494 	if (allocated_port == 0) {
20495 		connp->conn_mlp_type = mlptSingle;
20496 		if (connp->conn_anon_port) {
20497 			connp->conn_anon_port = B_FALSE;
20498 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_proto,
20499 			    requested_port, B_FALSE);
20500 		}
20501 		if (bind_to_req_port_only) {
20502 			if (connp->conn_debug) {
20503 				(void) strlog(TCP_MOD_ID, 0, 1,
20504 				    SL_ERROR|SL_TRACE,
20505 				    "tcp_bind: requested addr busy");
20506 			}
20507 			return (-TADDRBUSY);
20508 		} else {
20509 			/* If we are out of ports, fail the bind. */
20510 			if (connp->conn_debug) {
20511 				(void) strlog(TCP_MOD_ID, 0, 1,
20512 				    SL_ERROR|SL_TRACE,
20513 				    "tcp_bind: out of ports?");
20514 			}
20515 			return (-TNOADDR);
20516 		}
20517 	}
20518 
20519 	/* Pass the allocated port back */
20520 	*requested_port_ptr = allocated_port;
20521 	return (0);
20522 }
20523 
20524 /*
20525  * Check the address and check/pick a local port number.
20526  */
20527 static int
20528 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20529     boolean_t bind_to_req_port_only)
20530 {
20531 	tcp_t	*tcp = connp->conn_tcp;
20532 	sin_t	*sin;
20533 	sin6_t  *sin6;
20534 	in_port_t	requested_port;
20535 	ipaddr_t	v4addr;
20536 	in6_addr_t	v6addr;
20537 	ip_laddr_t	laddr_type = IPVL_UNICAST_UP;	/* INADDR_ANY */
20538 	zoneid_t	zoneid = IPCL_ZONEID(connp);
20539 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
20540 	uint_t		scopeid = 0;
20541 	int		error = 0;
20542 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20543 
20544 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
20545 
20546 	if (tcp->tcp_state == TCPS_BOUND) {
20547 		return (0);
20548 	} else if (tcp->tcp_state > TCPS_BOUND) {
20549 		if (connp->conn_debug) {
20550 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20551 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20552 		}
20553 		return (-TOUTSTATE);
20554 	}
20555 
20556 	ASSERT(sa != NULL && len != 0);
20557 
20558 	if (!OK_32PTR((char *)sa)) {
20559 		if (connp->conn_debug) {
20560 			(void) strlog(TCP_MOD_ID, 0, 1,
20561 			    SL_ERROR|SL_TRACE,
20562 			    "tcp_bind: bad address parameter, "
20563 			    "address %p, len %d",
20564 			    (void *)sa, len);
20565 		}
20566 		return (-TPROTO);
20567 	}
20568 
20569 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
20570 	if (error != 0) {
20571 		return (error);
20572 	}
20573 
20574 	switch (len) {
20575 	case sizeof (sin_t):	/* Complete IPv4 address */
20576 		sin = (sin_t *)sa;
20577 		requested_port = ntohs(sin->sin_port);
20578 		v4addr = sin->sin_addr.s_addr;
20579 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
20580 		if (v4addr != INADDR_ANY) {
20581 			laddr_type = ip_laddr_verify_v4(v4addr, zoneid, ipst,
20582 			    B_FALSE);
20583 		}
20584 		break;
20585 
20586 	case sizeof (sin6_t): /* Complete IPv6 address */
20587 		sin6 = (sin6_t *)sa;
20588 		v6addr = sin6->sin6_addr;
20589 		requested_port = ntohs(sin6->sin6_port);
20590 		if (IN6_IS_ADDR_V4MAPPED(&v6addr)) {
20591 			if (connp->conn_ipv6_v6only)
20592 				return (EADDRNOTAVAIL);
20593 
20594 			IN6_V4MAPPED_TO_IPADDR(&v6addr, v4addr);
20595 			if (v4addr != INADDR_ANY) {
20596 				laddr_type = ip_laddr_verify_v4(v4addr,
20597 				    zoneid, ipst, B_FALSE);
20598 			}
20599 		} else {
20600 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6addr)) {
20601 				if (IN6_IS_ADDR_LINKSCOPE(&v6addr))
20602 					scopeid = sin6->sin6_scope_id;
20603 				laddr_type = ip_laddr_verify_v6(&v6addr,
20604 				    zoneid, ipst, B_FALSE, scopeid);
20605 			}
20606 		}
20607 		break;
20608 
20609 	default:
20610 		if (connp->conn_debug) {
20611 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20612 			    "tcp_bind: bad address length, %d", len);
20613 		}
20614 		return (EAFNOSUPPORT);
20615 		/* return (-TBADADDR); */
20616 	}
20617 
20618 	/* Is the local address a valid unicast address? */
20619 	if (laddr_type == IPVL_BAD)
20620 		return (EADDRNOTAVAIL);
20621 
20622 	connp->conn_bound_addr_v6 = v6addr;
20623 	if (scopeid != 0) {
20624 		ixa->ixa_flags |= IXAF_SCOPEID_SET;
20625 		ixa->ixa_scopeid = scopeid;
20626 		connp->conn_incoming_ifindex = scopeid;
20627 	} else {
20628 		ixa->ixa_flags &= ~IXAF_SCOPEID_SET;
20629 		connp->conn_incoming_ifindex = connp->conn_bound_if;
20630 	}
20631 
20632 	connp->conn_laddr_v6 = v6addr;
20633 	connp->conn_saddr_v6 = v6addr;
20634 
20635 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
20636 
20637 	error = tcp_bind_select_lport(tcp, &requested_port,
20638 	    bind_to_req_port_only, cr);
20639 	if (error != 0) {
20640 		connp->conn_laddr_v6 = ipv6_all_zeros;
20641 		connp->conn_saddr_v6 = ipv6_all_zeros;
20642 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
20643 	}
20644 	return (error);
20645 }
20646 
20647 /*
20648  * Return unix error is tli error is TSYSERR, otherwise return a negative
20649  * tli error.
20650  */
20651 int
20652 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
20653     boolean_t bind_to_req_port_only)
20654 {
20655 	int error;
20656 	tcp_t *tcp = connp->conn_tcp;
20657 
20658 	if (tcp->tcp_state >= TCPS_BOUND) {
20659 		if (connp->conn_debug) {
20660 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
20661 			    "tcp_bind: bad state, %d", tcp->tcp_state);
20662 		}
20663 		return (-TOUTSTATE);
20664 	}
20665 
20666 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
20667 	if (error != 0)
20668 		return (error);
20669 
20670 	ASSERT(tcp->tcp_state == TCPS_BOUND);
20671 	tcp->tcp_conn_req_max = 0;
20672 	return (0);
20673 }
20674 
20675 int
20676 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
20677     socklen_t len, cred_t *cr)
20678 {
20679 	int 		error;
20680 	conn_t		*connp = (conn_t *)proto_handle;
20681 	squeue_t	*sqp = connp->conn_sqp;
20682 
20683 	/* All Solaris components should pass a cred for this operation. */
20684 	ASSERT(cr != NULL);
20685 
20686 	ASSERT(sqp != NULL);
20687 	ASSERT(connp->conn_upper_handle != NULL);
20688 
20689 	error = squeue_synch_enter(sqp, connp, NULL);
20690 	if (error != 0) {
20691 		/* failed to enter */
20692 		return (ENOSR);
20693 	}
20694 
20695 	/* binding to a NULL address really means unbind */
20696 	if (sa == NULL) {
20697 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
20698 			error = tcp_do_unbind(connp);
20699 		else
20700 			error = EINVAL;
20701 	} else {
20702 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
20703 	}
20704 
20705 	squeue_synch_exit(sqp, connp);
20706 
20707 	if (error < 0) {
20708 		if (error == -TOUTSTATE)
20709 			error = EINVAL;
20710 		else
20711 			error = proto_tlitosyserr(-error);
20712 	}
20713 
20714 	return (error);
20715 }
20716 
20717 /*
20718  * If the return value from this function is positive, it's a UNIX error.
20719  * Otherwise, if it's negative, then the absolute value is a TLI error.
20720  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
20721  */
20722 int
20723 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
20724     cred_t *cr, pid_t pid)
20725 {
20726 	tcp_t		*tcp = connp->conn_tcp;
20727 	sin_t		*sin = (sin_t *)sa;
20728 	sin6_t		*sin6 = (sin6_t *)sa;
20729 	ipaddr_t	*dstaddrp;
20730 	in_port_t	dstport;
20731 	uint_t		srcid;
20732 	int		error;
20733 	uint32_t	mss;
20734 	mblk_t		*syn_mp;
20735 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20736 	int32_t		oldstate;
20737 	ip_xmit_attr_t	*ixa = connp->conn_ixa;
20738 
20739 	oldstate = tcp->tcp_state;
20740 
20741 	switch (len) {
20742 	default:
20743 		/*
20744 		 * Should never happen
20745 		 */
20746 		return (EINVAL);
20747 
20748 	case sizeof (sin_t):
20749 		sin = (sin_t *)sa;
20750 		if (sin->sin_port == 0) {
20751 			return (-TBADADDR);
20752 		}
20753 		if (connp->conn_ipv6_v6only) {
20754 			return (EAFNOSUPPORT);
20755 		}
20756 		break;
20757 
20758 	case sizeof (sin6_t):
20759 		sin6 = (sin6_t *)sa;
20760 		if (sin6->sin6_port == 0) {
20761 			return (-TBADADDR);
20762 		}
20763 		break;
20764 	}
20765 	/*
20766 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
20767 	 * make sure that the conn_ipversion is IPV4_VERSION.  We
20768 	 * need to this before we call tcp_bindi() so that the port lookup
20769 	 * code will look for ports in the correct port space (IPv4 and
20770 	 * IPv6 have separate port spaces).
20771 	 */
20772 	if (connp->conn_family == AF_INET6 &&
20773 	    connp->conn_ipversion == IPV6_VERSION &&
20774 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20775 		if (connp->conn_ipv6_v6only)
20776 			return (EADDRNOTAVAIL);
20777 
20778 		connp->conn_ipversion = IPV4_VERSION;
20779 	}
20780 
20781 	switch (tcp->tcp_state) {
20782 	case TCPS_LISTEN:
20783 		/*
20784 		 * Listening sockets are not allowed to issue connect().
20785 		 */
20786 		if (IPCL_IS_NONSTR(connp))
20787 			return (EOPNOTSUPP);
20788 		/* FALLTHRU */
20789 	case TCPS_IDLE:
20790 		/*
20791 		 * We support quick connect, refer to comments in
20792 		 * tcp_connect_*()
20793 		 */
20794 		/* FALLTHRU */
20795 	case TCPS_BOUND:
20796 		break;
20797 	default:
20798 		return (-TOUTSTATE);
20799 	}
20800 
20801 	/*
20802 	 * We update our cred/cpid based on the caller of connect
20803 	 */
20804 	if (connp->conn_cred != cr) {
20805 		crhold(cr);
20806 		crfree(connp->conn_cred);
20807 		connp->conn_cred = cr;
20808 	}
20809 	connp->conn_cpid = pid;
20810 
20811 	/* Cache things in the ixa without any refhold */
20812 	ixa->ixa_cred = cr;
20813 	ixa->ixa_cpid = pid;
20814 	if (is_system_labeled()) {
20815 		/* We need to restart with a label based on the cred */
20816 		ip_xmit_attr_restore_tsl(ixa, ixa->ixa_cred);
20817 	}
20818 
20819 	if (connp->conn_family == AF_INET6) {
20820 		if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
20821 			error = tcp_connect_ipv6(tcp, &sin6->sin6_addr,
20822 			    sin6->sin6_port, sin6->sin6_flowinfo,
20823 			    sin6->__sin6_src_id, sin6->sin6_scope_id);
20824 		} else {
20825 			/*
20826 			 * Destination adress is mapped IPv6 address.
20827 			 * Source bound address should be unspecified or
20828 			 * IPv6 mapped address as well.
20829 			 */
20830 			if (!IN6_IS_ADDR_UNSPECIFIED(
20831 			    &connp->conn_bound_addr_v6) &&
20832 			    !IN6_IS_ADDR_V4MAPPED(&connp->conn_bound_addr_v6)) {
20833 				return (EADDRNOTAVAIL);
20834 			}
20835 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
20836 			dstport = sin6->sin6_port;
20837 			srcid = sin6->__sin6_src_id;
20838 			error = tcp_connect_ipv4(tcp, dstaddrp, dstport,
20839 			    srcid);
20840 		}
20841 	} else {
20842 		dstaddrp = &sin->sin_addr.s_addr;
20843 		dstport = sin->sin_port;
20844 		srcid = 0;
20845 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid);
20846 	}
20847 
20848 	if (error != 0)
20849 		goto connect_failed;
20850 
20851 	CL_INET_CONNECT(connp, B_TRUE, error);
20852 	if (error != 0)
20853 		goto connect_failed;
20854 
20855 	/* connect succeeded */
20856 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
20857 	tcp->tcp_active_open = 1;
20858 
20859 	/*
20860 	 * tcp_set_destination() does not adjust for TCP/IP header length.
20861 	 */
20862 	mss = tcp->tcp_mss - connp->conn_ht_iphc_len;
20863 
20864 	/*
20865 	 * Just make sure our rwnd is at least rcvbuf * MSS large, and round up
20866 	 * to the nearest MSS.
20867 	 *
20868 	 * We do the round up here because we need to get the interface MTU
20869 	 * first before we can do the round up.
20870 	 */
20871 	tcp->tcp_rwnd = connp->conn_rcvbuf;
20872 	tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
20873 	    tcps->tcps_recv_hiwat_minmss * mss);
20874 	connp->conn_rcvbuf = tcp->tcp_rwnd;
20875 	tcp_set_ws_value(tcp);
20876 	tcp->tcp_tcpha->tha_win = htons(tcp->tcp_rwnd >> tcp->tcp_rcv_ws);
20877 	if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
20878 		tcp->tcp_snd_ws_ok = B_TRUE;
20879 
20880 	/*
20881 	 * Set tcp_snd_ts_ok to true
20882 	 * so that tcp_xmit_mp will
20883 	 * include the timestamp
20884 	 * option in the SYN segment.
20885 	 */
20886 	if (tcps->tcps_tstamp_always ||
20887 	    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
20888 		tcp->tcp_snd_ts_ok = B_TRUE;
20889 	}
20890 
20891 	/*
20892 	 * tcp_snd_sack_ok can be set in
20893 	 * tcp_set_destination() if the sack metric
20894 	 * is set.  So check it here also.
20895 	 */
20896 	if (tcps->tcps_sack_permitted == 2 ||
20897 	    tcp->tcp_snd_sack_ok) {
20898 		if (tcp->tcp_sack_info == NULL) {
20899 			tcp->tcp_sack_info = kmem_cache_alloc(
20900 			    tcp_sack_info_cache, KM_SLEEP);
20901 		}
20902 		tcp->tcp_snd_sack_ok = B_TRUE;
20903 	}
20904 
20905 	/*
20906 	 * Should we use ECN?  Note that the current
20907 	 * default value (SunOS 5.9) of tcp_ecn_permitted
20908 	 * is 1.  The reason for doing this is that there
20909 	 * are equipments out there that will drop ECN
20910 	 * enabled IP packets.  Setting it to 1 avoids
20911 	 * compatibility problems.
20912 	 */
20913 	if (tcps->tcps_ecn_permitted == 2)
20914 		tcp->tcp_ecn_ok = B_TRUE;
20915 
20916 	TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20917 	syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
20918 	    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
20919 	if (syn_mp != NULL) {
20920 		/*
20921 		 * We must bump the generation before sending the syn
20922 		 * to ensure that we use the right generation in case
20923 		 * this thread issues a "connected" up call.
20924 		 */
20925 		SOCK_CONNID_BUMP(tcp->tcp_connid);
20926 		tcp_send_data(tcp, syn_mp);
20927 	}
20928 
20929 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
20930 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
20931 	return (0);
20932 
20933 connect_failed:
20934 	connp->conn_faddr_v6 = ipv6_all_zeros;
20935 	connp->conn_fport = 0;
20936 	tcp->tcp_state = oldstate;
20937 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
20938 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
20939 	return (error);
20940 }
20941 
20942 int
20943 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
20944     socklen_t len, sock_connid_t *id, cred_t *cr)
20945 {
20946 	conn_t		*connp = (conn_t *)proto_handle;
20947 	squeue_t	*sqp = connp->conn_sqp;
20948 	int		error;
20949 
20950 	ASSERT(connp->conn_upper_handle != NULL);
20951 
20952 	/* All Solaris components should pass a cred for this operation. */
20953 	ASSERT(cr != NULL);
20954 
20955 	error = proto_verify_ip_addr(connp->conn_family, sa, len);
20956 	if (error != 0) {
20957 		return (error);
20958 	}
20959 
20960 	error = squeue_synch_enter(sqp, connp, NULL);
20961 	if (error != 0) {
20962 		/* failed to enter */
20963 		return (ENOSR);
20964 	}
20965 
20966 	/*
20967 	 * TCP supports quick connect, so no need to do an implicit bind
20968 	 */
20969 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
20970 	if (error == 0) {
20971 		*id = connp->conn_tcp->tcp_connid;
20972 	} else if (error < 0) {
20973 		if (error == -TOUTSTATE) {
20974 			switch (connp->conn_tcp->tcp_state) {
20975 			case TCPS_SYN_SENT:
20976 				error = EALREADY;
20977 				break;
20978 			case TCPS_ESTABLISHED:
20979 				error = EISCONN;
20980 				break;
20981 			case TCPS_LISTEN:
20982 				error = EOPNOTSUPP;
20983 				break;
20984 			default:
20985 				error = EINVAL;
20986 				break;
20987 			}
20988 		} else {
20989 			error = proto_tlitosyserr(-error);
20990 		}
20991 	}
20992 
20993 	if (connp->conn_tcp->tcp_loopback) {
20994 		struct sock_proto_props sopp;
20995 
20996 		sopp.sopp_flags = SOCKOPT_LOOPBACK;
20997 		sopp.sopp_loopback = B_TRUE;
20998 
20999 		(*connp->conn_upcalls->su_set_proto_props)(
21000 		    connp->conn_upper_handle, &sopp);
21001 	}
21002 done:
21003 	squeue_synch_exit(sqp, connp);
21004 
21005 	return ((error == 0) ? EINPROGRESS : error);
21006 }
21007 
21008 /* ARGSUSED */
21009 sock_lower_handle_t
21010 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
21011     uint_t *smodep, int *errorp, int flags, cred_t *credp)
21012 {
21013 	conn_t		*connp;
21014 	boolean_t	isv6 = family == AF_INET6;
21015 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
21016 	    (proto != 0 && proto != IPPROTO_TCP)) {
21017 		*errorp = EPROTONOSUPPORT;
21018 		return (NULL);
21019 	}
21020 
21021 	connp = tcp_create_common(credp, isv6, B_TRUE, errorp);
21022 	if (connp == NULL) {
21023 		return (NULL);
21024 	}
21025 
21026 	/*
21027 	 * Put the ref for TCP. Ref for IP was already put
21028 	 * by ipcl_conn_create. Also Make the conn_t globally
21029 	 * visible to walkers
21030 	 */
21031 	mutex_enter(&connp->conn_lock);
21032 	CONN_INC_REF_LOCKED(connp);
21033 	ASSERT(connp->conn_ref == 2);
21034 	connp->conn_state_flags &= ~CONN_INCIPIENT;
21035 
21036 	connp->conn_flags |= IPCL_NONSTR;
21037 	mutex_exit(&connp->conn_lock);
21038 
21039 	ASSERT(errorp != NULL);
21040 	*errorp = 0;
21041 	*sock_downcalls = &sock_tcp_downcalls;
21042 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
21043 	    SM_SENDFILESUPP;
21044 
21045 	return ((sock_lower_handle_t)connp);
21046 }
21047 
21048 /* ARGSUSED */
21049 void
21050 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
21051     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
21052 {
21053 	conn_t *connp = (conn_t *)proto_handle;
21054 	struct sock_proto_props sopp;
21055 
21056 	ASSERT(connp->conn_upper_handle == NULL);
21057 
21058 	/* All Solaris components should pass a cred for this operation. */
21059 	ASSERT(cr != NULL);
21060 
21061 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
21062 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
21063 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
21064 
21065 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
21066 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
21067 	sopp.sopp_maxpsz = INFPSZ;
21068 	sopp.sopp_maxblk = INFPSZ;
21069 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
21070 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
21071 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
21072 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
21073 	    tcp_rinfo.mi_minpsz;
21074 
21075 	connp->conn_upcalls = sock_upcalls;
21076 	connp->conn_upper_handle = sock_handle;
21077 
21078 	ASSERT(connp->conn_rcvbuf != 0 &&
21079 	    connp->conn_rcvbuf == connp->conn_tcp->tcp_rwnd);
21080 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
21081 }
21082 
21083 /* ARGSUSED */
21084 int
21085 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
21086 {
21087 	conn_t *connp = (conn_t *)proto_handle;
21088 
21089 	ASSERT(connp->conn_upper_handle != NULL);
21090 
21091 	/* All Solaris components should pass a cred for this operation. */
21092 	ASSERT(cr != NULL);
21093 
21094 	tcp_close_common(connp, flags);
21095 
21096 	ip_free_helper_stream(connp);
21097 
21098 	/*
21099 	 * Drop IP's reference on the conn. This is the last reference
21100 	 * on the connp if the state was less than established. If the
21101 	 * connection has gone into timewait state, then we will have
21102 	 * one ref for the TCP and one more ref (total of two) for the
21103 	 * classifier connected hash list (a timewait connections stays
21104 	 * in connected hash till closed).
21105 	 *
21106 	 * We can't assert the references because there might be other
21107 	 * transient reference places because of some walkers or queued
21108 	 * packets in squeue for the timewait state.
21109 	 */
21110 	CONN_DEC_REF(connp);
21111 	return (0);
21112 }
21113 
21114 /* ARGSUSED */
21115 int
21116 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
21117     cred_t *cr)
21118 {
21119 	tcp_t		*tcp;
21120 	uint32_t	msize;
21121 	conn_t *connp = (conn_t *)proto_handle;
21122 	int32_t		tcpstate;
21123 
21124 	/* All Solaris components should pass a cred for this operation. */
21125 	ASSERT(cr != NULL);
21126 
21127 	ASSERT(connp->conn_ref >= 2);
21128 	ASSERT(connp->conn_upper_handle != NULL);
21129 
21130 	if (msg->msg_controllen != 0) {
21131 		freemsg(mp);
21132 		return (EOPNOTSUPP);
21133 	}
21134 
21135 	switch (DB_TYPE(mp)) {
21136 	case M_DATA:
21137 		tcp = connp->conn_tcp;
21138 		ASSERT(tcp != NULL);
21139 
21140 		tcpstate = tcp->tcp_state;
21141 		if (tcpstate < TCPS_ESTABLISHED) {
21142 			freemsg(mp);
21143 			/*
21144 			 * We return ENOTCONN if the endpoint is trying to
21145 			 * connect or has never been connected, and EPIPE if it
21146 			 * has been disconnected. The connection id helps us
21147 			 * distinguish between the last two cases.
21148 			 */
21149 			return ((tcpstate == TCPS_SYN_SENT) ? ENOTCONN :
21150 			    ((tcp->tcp_connid > 0) ? EPIPE : ENOTCONN));
21151 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
21152 			freemsg(mp);
21153 			return (EPIPE);
21154 		}
21155 
21156 		msize = msgdsize(mp);
21157 
21158 		mutex_enter(&tcp->tcp_non_sq_lock);
21159 		tcp->tcp_squeue_bytes += msize;
21160 		/*
21161 		 * Squeue Flow Control
21162 		 */
21163 		if (TCP_UNSENT_BYTES(tcp) > connp->conn_sndbuf) {
21164 			tcp_setqfull(tcp);
21165 		}
21166 		mutex_exit(&tcp->tcp_non_sq_lock);
21167 
21168 		/*
21169 		 * The application may pass in an address in the msghdr, but
21170 		 * we ignore the address on connection-oriented sockets.
21171 		 * Just like BSD this code does not generate an error for
21172 		 * TCP (a CONNREQUIRED socket) when sending to an address
21173 		 * passed in with sendto/sendmsg. Instead the data is
21174 		 * delivered on the connection as if no address had been
21175 		 * supplied.
21176 		 */
21177 		CONN_INC_REF(connp);
21178 
21179 		if (msg->msg_flags & MSG_OOB) {
21180 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output_urgent,
21181 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21182 		} else {
21183 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
21184 			    connp, NULL, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
21185 		}
21186 
21187 		return (0);
21188 
21189 	default:
21190 		ASSERT(0);
21191 	}
21192 
21193 	freemsg(mp);
21194 	return (0);
21195 }
21196 
21197 /* ARGSUSED2 */
21198 void
21199 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21200 {
21201 	int len;
21202 	uint32_t msize;
21203 	conn_t *connp = (conn_t *)arg;
21204 	tcp_t *tcp = connp->conn_tcp;
21205 
21206 	msize = msgdsize(mp);
21207 
21208 	len = msize - 1;
21209 	if (len < 0) {
21210 		freemsg(mp);
21211 		return;
21212 	}
21213 
21214 	/*
21215 	 * Try to force urgent data out on the wire. Even if we have unsent
21216 	 * data this will at least send the urgent flag.
21217 	 * XXX does not handle more flag correctly.
21218 	 */
21219 	len += tcp->tcp_unsent;
21220 	len += tcp->tcp_snxt;
21221 	tcp->tcp_urg = len;
21222 	tcp->tcp_valid_bits |= TCP_URG_VALID;
21223 
21224 	/* Bypass tcp protocol for fused tcp loopback */
21225 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
21226 		return;
21227 
21228 	/* Strip off the T_EXDATA_REQ if the data is from TPI */
21229 	if (DB_TYPE(mp) != M_DATA) {
21230 		mblk_t *mp1 = mp;
21231 		ASSERT(!IPCL_IS_NONSTR(connp));
21232 		mp = mp->b_cont;
21233 		freeb(mp1);
21234 	}
21235 	tcp_wput_data(tcp, mp, B_TRUE);
21236 }
21237 
21238 /* ARGSUSED3 */
21239 int
21240 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21241     socklen_t *addrlenp, cred_t *cr)
21242 {
21243 	conn_t	*connp = (conn_t *)proto_handle;
21244 	tcp_t	*tcp = connp->conn_tcp;
21245 
21246 	ASSERT(connp->conn_upper_handle != NULL);
21247 	/* All Solaris components should pass a cred for this operation. */
21248 	ASSERT(cr != NULL);
21249 
21250 	ASSERT(tcp != NULL);
21251 	if (tcp->tcp_state < TCPS_SYN_RCVD)
21252 		return (ENOTCONN);
21253 
21254 	return (conn_getpeername(connp, addr, addrlenp));
21255 }
21256 
21257 /* ARGSUSED3 */
21258 int
21259 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
21260     socklen_t *addrlenp, cred_t *cr)
21261 {
21262 	conn_t	*connp = (conn_t *)proto_handle;
21263 
21264 	/* All Solaris components should pass a cred for this operation. */
21265 	ASSERT(cr != NULL);
21266 
21267 	ASSERT(connp->conn_upper_handle != NULL);
21268 	return (conn_getsockname(connp, addr, addrlenp));
21269 }
21270 
21271 /*
21272  * tcp_fallback
21273  *
21274  * A direct socket is falling back to using STREAMS. The queue
21275  * that is being passed down was created using tcp_open() with
21276  * the SO_FALLBACK flag set. As a result, the queue is not
21277  * associated with a conn, and the q_ptrs instead contain the
21278  * dev and minor area that should be used.
21279  *
21280  * The 'issocket' flag indicates whether the FireEngine
21281  * optimizations should be used. The common case would be that
21282  * optimizations are enabled, and they might be subsequently
21283  * disabled using the _SIOCSOCKFALLBACK ioctl.
21284  */
21285 
21286 /*
21287  * An active connection is falling back to TPI. Gather all the information
21288  * required by the STREAM head and TPI sonode and send it up.
21289  */
21290 void
21291 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
21292     boolean_t issocket, so_proto_quiesced_cb_t quiesced_cb)
21293 {
21294 	conn_t			*connp = tcp->tcp_connp;
21295 	struct stroptions	*stropt;
21296 	struct T_capability_ack tca;
21297 	struct sockaddr_in6	laddr, faddr;
21298 	socklen_t 		laddrlen, faddrlen;
21299 	short			opts;
21300 	int			error;
21301 	mblk_t			*mp;
21302 
21303 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
21304 	connp->conn_minor_arena = WR(q)->q_ptr;
21305 
21306 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
21307 
21308 	connp->conn_rq = RD(q);
21309 	connp->conn_wq = WR(q);
21310 
21311 	WR(q)->q_qinfo = &tcp_sock_winit;
21312 
21313 	if (!issocket)
21314 		tcp_use_pure_tpi(tcp);
21315 
21316 	/*
21317 	 * free the helper stream
21318 	 */
21319 	ip_free_helper_stream(connp);
21320 
21321 	/*
21322 	 * Notify the STREAM head about options
21323 	 */
21324 	DB_TYPE(stropt_mp) = M_SETOPTS;
21325 	stropt = (struct stroptions *)stropt_mp->b_rptr;
21326 	stropt_mp->b_wptr += sizeof (struct stroptions);
21327 	stropt->so_flags = SO_HIWAT | SO_WROFF | SO_MAXBLK;
21328 
21329 	stropt->so_wroff = connp->conn_ht_iphc_len + (tcp->tcp_loopback ? 0 :
21330 	    tcp->tcp_tcps->tcps_wroff_xtra);
21331 	if (tcp->tcp_snd_sack_ok)
21332 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
21333 	stropt->so_hiwat = connp->conn_rcvbuf;
21334 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
21335 
21336 	putnext(RD(q), stropt_mp);
21337 
21338 	/*
21339 	 * Collect the information needed to sync with the sonode
21340 	 */
21341 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
21342 
21343 	laddrlen = faddrlen = sizeof (sin6_t);
21344 	(void) tcp_getsockname((sock_lower_handle_t)connp,
21345 	    (struct sockaddr *)&laddr, &laddrlen, CRED());
21346 	error = tcp_getpeername((sock_lower_handle_t)connp,
21347 	    (struct sockaddr *)&faddr, &faddrlen, CRED());
21348 	if (error != 0)
21349 		faddrlen = 0;
21350 
21351 	opts = 0;
21352 	if (connp->conn_oobinline)
21353 		opts |= SO_OOBINLINE;
21354 	if (connp->conn_ixa->ixa_flags & IXAF_DONTROUTE)
21355 		opts |= SO_DONTROUTE;
21356 
21357 	/*
21358 	 * Notify the socket that the protocol is now quiescent,
21359 	 * and it's therefore safe move data from the socket
21360 	 * to the stream head.
21361 	 */
21362 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
21363 	    (struct sockaddr *)&laddr, laddrlen,
21364 	    (struct sockaddr *)&faddr, faddrlen, opts);
21365 
21366 	while ((mp = tcp->tcp_rcv_list) != NULL) {
21367 		tcp->tcp_rcv_list = mp->b_next;
21368 		mp->b_next = NULL;
21369 		/* We never do fallback for kernel RPC */
21370 		putnext(q, mp);
21371 	}
21372 	tcp->tcp_rcv_last_head = NULL;
21373 	tcp->tcp_rcv_last_tail = NULL;
21374 	tcp->tcp_rcv_cnt = 0;
21375 }
21376 
21377 /*
21378  * An eager is falling back to TPI. All we have to do is send
21379  * up a T_CONN_IND.
21380  */
21381 void
21382 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
21383 {
21384 	tcp_t *listener = eager->tcp_listener;
21385 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
21386 
21387 	ASSERT(listener != NULL);
21388 	ASSERT(mp != NULL);
21389 
21390 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
21391 
21392 	/*
21393 	 * TLI/XTI applications will get confused by
21394 	 * sending eager as an option since it violates
21395 	 * the option semantics. So remove the eager as
21396 	 * option since TLI/XTI app doesn't need it anyway.
21397 	 */
21398 	if (!direct_sockfs) {
21399 		struct T_conn_ind *conn_ind;
21400 
21401 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
21402 		conn_ind->OPT_length = 0;
21403 		conn_ind->OPT_offset = 0;
21404 	}
21405 
21406 	/*
21407 	 * Sockfs guarantees that the listener will not be closed
21408 	 * during fallback. So we can safely use the listener's queue.
21409 	 */
21410 	putnext(listener->tcp_connp->conn_rq, mp);
21411 }
21412 
21413 int
21414 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
21415     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
21416 {
21417 	tcp_t			*tcp;
21418 	conn_t 			*connp = (conn_t *)proto_handle;
21419 	int			error;
21420 	mblk_t			*stropt_mp;
21421 	mblk_t			*ordrel_mp;
21422 
21423 	tcp = connp->conn_tcp;
21424 
21425 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
21426 	    NULL);
21427 
21428 	/* Pre-allocate the T_ordrel_ind mblk. */
21429 	ASSERT(tcp->tcp_ordrel_mp == NULL);
21430 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
21431 	    STR_NOSIG, NULL);
21432 	ordrel_mp->b_datap->db_type = M_PROTO;
21433 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
21434 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
21435 
21436 	/*
21437 	 * Enter the squeue so that no new packets can come in
21438 	 */
21439 	error = squeue_synch_enter(connp->conn_sqp, connp, NULL);
21440 	if (error != 0) {
21441 		/* failed to enter, free all the pre-allocated messages. */
21442 		freeb(stropt_mp);
21443 		freeb(ordrel_mp);
21444 		/*
21445 		 * We cannot process the eager, so at least send out a
21446 		 * RST so the peer can reconnect.
21447 		 */
21448 		if (tcp->tcp_listener != NULL) {
21449 			(void) tcp_eager_blowoff(tcp->tcp_listener,
21450 			    tcp->tcp_conn_req_seqnum);
21451 		}
21452 		return (ENOMEM);
21453 	}
21454 
21455 	/*
21456 	 * Both endpoints must be of the same type (either STREAMS or
21457 	 * non-STREAMS) for fusion to be enabled. So if we are fused,
21458 	 * we have to unfuse.
21459 	 */
21460 	if (tcp->tcp_fused)
21461 		tcp_unfuse(tcp);
21462 
21463 	/*
21464 	 * No longer a direct socket
21465 	 */
21466 	connp->conn_flags &= ~IPCL_NONSTR;
21467 	tcp->tcp_ordrel_mp = ordrel_mp;
21468 
21469 	if (tcp->tcp_listener != NULL) {
21470 		/* The eager will deal with opts when accept() is called */
21471 		freeb(stropt_mp);
21472 		tcp_fallback_eager(tcp, direct_sockfs);
21473 	} else {
21474 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
21475 		    quiesced_cb);
21476 	}
21477 
21478 	/*
21479 	 * There should be atleast two ref's (IP + TCP)
21480 	 */
21481 	ASSERT(connp->conn_ref >= 2);
21482 	squeue_synch_exit(connp->conn_sqp, connp);
21483 
21484 	return (0);
21485 }
21486 
21487 /* ARGSUSED */
21488 static void
21489 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
21490 {
21491 	conn_t 	*connp = (conn_t *)arg;
21492 	tcp_t	*tcp = connp->conn_tcp;
21493 
21494 	freemsg(mp);
21495 
21496 	if (tcp->tcp_fused)
21497 		tcp_unfuse(tcp);
21498 
21499 	if (tcp_xmit_end(tcp) != 0) {
21500 		/*
21501 		 * We were crossing FINs and got a reset from
21502 		 * the other side. Just ignore it.
21503 		 */
21504 		if (connp->conn_debug) {
21505 			(void) strlog(TCP_MOD_ID, 0, 1,
21506 			    SL_ERROR|SL_TRACE,
21507 			    "tcp_shutdown_output() out of state %s",
21508 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
21509 		}
21510 	}
21511 }
21512 
21513 /* ARGSUSED */
21514 int
21515 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
21516 {
21517 	conn_t  *connp = (conn_t *)proto_handle;
21518 	tcp_t   *tcp = connp->conn_tcp;
21519 
21520 	ASSERT(connp->conn_upper_handle != NULL);
21521 
21522 	/* All Solaris components should pass a cred for this operation. */
21523 	ASSERT(cr != NULL);
21524 
21525 	/*
21526 	 * X/Open requires that we check the connected state.
21527 	 */
21528 	if (tcp->tcp_state < TCPS_SYN_SENT)
21529 		return (ENOTCONN);
21530 
21531 	/* shutdown the send side */
21532 	if (how != SHUT_RD) {
21533 		mblk_t *bp;
21534 
21535 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
21536 		CONN_INC_REF(connp);
21537 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
21538 		    connp, NULL, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
21539 
21540 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21541 		    SOCK_OPCTL_SHUT_SEND, 0);
21542 	}
21543 
21544 	/* shutdown the recv side */
21545 	if (how != SHUT_WR)
21546 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21547 		    SOCK_OPCTL_SHUT_RECV, 0);
21548 
21549 	return (0);
21550 }
21551 
21552 /*
21553  * SOP_LISTEN() calls into tcp_listen().
21554  */
21555 /* ARGSUSED */
21556 int
21557 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
21558 {
21559 	conn_t	*connp = (conn_t *)proto_handle;
21560 	int 	error;
21561 	squeue_t *sqp = connp->conn_sqp;
21562 
21563 	ASSERT(connp->conn_upper_handle != NULL);
21564 
21565 	/* All Solaris components should pass a cred for this operation. */
21566 	ASSERT(cr != NULL);
21567 
21568 	error = squeue_synch_enter(sqp, connp, NULL);
21569 	if (error != 0) {
21570 		/* failed to enter */
21571 		return (ENOBUFS);
21572 	}
21573 
21574 	error = tcp_do_listen(connp, NULL, 0, backlog, cr, FALSE);
21575 	if (error == 0) {
21576 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
21577 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
21578 	} else if (error < 0) {
21579 		if (error == -TOUTSTATE)
21580 			error = EINVAL;
21581 		else
21582 			error = proto_tlitosyserr(-error);
21583 	}
21584 	squeue_synch_exit(sqp, connp);
21585 	return (error);
21586 }
21587 
21588 static int
21589 tcp_do_listen(conn_t *connp, struct sockaddr *sa, socklen_t len,
21590     int backlog, cred_t *cr, boolean_t bind_to_req_port_only)
21591 {
21592 	tcp_t		*tcp = connp->conn_tcp;
21593 	int		error = 0;
21594 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21595 
21596 	/* All Solaris components should pass a cred for this operation. */
21597 	ASSERT(cr != NULL);
21598 
21599 	if (tcp->tcp_state >= TCPS_BOUND) {
21600 		if ((tcp->tcp_state == TCPS_BOUND ||
21601 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
21602 			/*
21603 			 * Handle listen() increasing backlog.
21604 			 * This is more "liberal" then what the TPI spec
21605 			 * requires but is needed to avoid a t_unbind
21606 			 * when handling listen() since the port number
21607 			 * might be "stolen" between the unbind and bind.
21608 			 */
21609 			goto do_listen;
21610 		}
21611 		if (connp->conn_debug) {
21612 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
21613 			    "tcp_listen: bad state, %d", tcp->tcp_state);
21614 		}
21615 		return (-TOUTSTATE);
21616 	} else {
21617 		if (sa == NULL) {
21618 			sin6_t	addr;
21619 			sin_t *sin;
21620 			sin6_t *sin6;
21621 
21622 			ASSERT(IPCL_IS_NONSTR(connp));
21623 			/* Do an implicit bind: Request for a generic port. */
21624 			if (connp->conn_family == AF_INET) {
21625 				len = sizeof (sin_t);
21626 				sin = (sin_t *)&addr;
21627 				*sin = sin_null;
21628 				sin->sin_family = AF_INET;
21629 			} else {
21630 				ASSERT(connp->conn_family == AF_INET6);
21631 				len = sizeof (sin6_t);
21632 				sin6 = (sin6_t *)&addr;
21633 				*sin6 = sin6_null;
21634 				sin6->sin6_family = AF_INET6;
21635 			}
21636 			sa = (struct sockaddr *)&addr;
21637 		}
21638 
21639 		error = tcp_bind_check(connp, sa, len, cr,
21640 		    bind_to_req_port_only);
21641 		if (error)
21642 			return (error);
21643 		/* Fall through and do the fanout insertion */
21644 	}
21645 
21646 do_listen:
21647 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
21648 	tcp->tcp_conn_req_max = backlog;
21649 	if (tcp->tcp_conn_req_max) {
21650 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
21651 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
21652 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
21653 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
21654 		/*
21655 		 * If this is a listener, do not reset the eager list
21656 		 * and other stuffs.  Note that we don't check if the
21657 		 * existing eager list meets the new tcp_conn_req_max
21658 		 * requirement.
21659 		 */
21660 		if (tcp->tcp_state != TCPS_LISTEN) {
21661 			tcp->tcp_state = TCPS_LISTEN;
21662 			/* Initialize the chain. Don't need the eager_lock */
21663 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
21664 			tcp->tcp_eager_next_drop_q0 = tcp;
21665 			tcp->tcp_eager_prev_drop_q0 = tcp;
21666 			tcp->tcp_second_ctimer_threshold =
21667 			    tcps->tcps_ip_abort_linterval;
21668 		}
21669 	}
21670 
21671 	/*
21672 	 * We need to make sure that the conn_recv is set to a non-null
21673 	 * value before we insert the conn into the classifier table.
21674 	 * This is to avoid a race with an incoming packet which does an
21675 	 * ipcl_classify().
21676 	 * We initially set it to tcp_input_listener_unbound to try to
21677 	 * pick a good squeue for the listener when the first SYN arrives.
21678 	 * tcp_input_listener_unbound sets it to tcp_input_listener on that
21679 	 * first SYN.
21680 	 */
21681 	connp->conn_recv = tcp_input_listener_unbound;
21682 
21683 	/* Insert the listener in the classifier table */
21684 	error = ip_laddr_fanout_insert(connp);
21685 	if (error != 0) {
21686 		/* Undo the bind - release the port number */
21687 		tcp->tcp_state = TCPS_IDLE;
21688 		connp->conn_bound_addr_v6 = ipv6_all_zeros;
21689 
21690 		connp->conn_laddr_v6 = ipv6_all_zeros;
21691 		connp->conn_saddr_v6 = ipv6_all_zeros;
21692 		connp->conn_ports = 0;
21693 
21694 		if (connp->conn_anon_port) {
21695 			zone_t		*zone;
21696 
21697 			zone = crgetzone(cr);
21698 			connp->conn_anon_port = B_FALSE;
21699 			(void) tsol_mlp_anon(zone, connp->conn_mlp_type,
21700 			    connp->conn_proto, connp->conn_lport, B_FALSE);
21701 		}
21702 		connp->conn_mlp_type = mlptSingle;
21703 
21704 		tcp_bind_hash_remove(tcp);
21705 		return (error);
21706 	} else {
21707 		/*
21708 		 * If there is a connection limit, allocate and initialize
21709 		 * the counter struct.  Note that since listen can be called
21710 		 * multiple times, the struct may have been allready allocated.
21711 		 */
21712 		if (!list_is_empty(&tcps->tcps_listener_conf) &&
21713 		    tcp->tcp_listen_cnt == NULL) {
21714 			tcp_listen_cnt_t *tlc;
21715 			uint32_t ratio;
21716 
21717 			ratio = tcp_find_listener_conf(tcps,
21718 			    ntohs(connp->conn_lport));
21719 			if (ratio != 0) {
21720 				uint32_t mem_ratio, tot_buf;
21721 
21722 				tlc = kmem_alloc(sizeof (tcp_listen_cnt_t),
21723 				    KM_SLEEP);
21724 				/*
21725 				 * Calculate the connection limit based on
21726 				 * the configured ratio and maxusers.  Maxusers
21727 				 * are calculated based on memory size,
21728 				 * ~ 1 user per MB.  Note that the conn_rcvbuf
21729 				 * and conn_sndbuf may change after a
21730 				 * connection is accepted.  So what we have
21731 				 * is only an approximation.
21732 				 */
21733 				if ((tot_buf = connp->conn_rcvbuf +
21734 				    connp->conn_sndbuf) < MB) {
21735 					mem_ratio = MB / tot_buf;
21736 					tlc->tlc_max = maxusers / ratio *
21737 					    mem_ratio;
21738 				} else {
21739 					mem_ratio = tot_buf / MB;
21740 					tlc->tlc_max = maxusers / ratio /
21741 					    mem_ratio;
21742 				}
21743 				/* At least we should allow two connections! */
21744 				if (tlc->tlc_max <= tcp_min_conn_listener)
21745 					tlc->tlc_max = tcp_min_conn_listener;
21746 				tlc->tlc_cnt = 1;
21747 				tlc->tlc_drop = 0;
21748 				tcp->tcp_listen_cnt = tlc;
21749 			}
21750 		}
21751 	}
21752 	return (error);
21753 }
21754 
21755 void
21756 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
21757 {
21758 	conn_t  *connp = (conn_t *)proto_handle;
21759 	tcp_t	*tcp = connp->conn_tcp;
21760 	mblk_t *mp;
21761 	int error;
21762 
21763 	ASSERT(connp->conn_upper_handle != NULL);
21764 
21765 	/*
21766 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_clr_flowctrl()
21767 	 * is currently running.
21768 	 */
21769 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21770 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
21771 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
21772 		return;
21773 	}
21774 	tcp->tcp_rsrv_mp = NULL;
21775 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21776 
21777 	error = squeue_synch_enter(connp->conn_sqp, connp, mp);
21778 	ASSERT(error == 0);
21779 
21780 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
21781 	tcp->tcp_rsrv_mp = mp;
21782 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
21783 
21784 	if (tcp->tcp_fused) {
21785 		tcp_fuse_backenable(tcp);
21786 	} else {
21787 		tcp->tcp_rwnd = connp->conn_rcvbuf;
21788 		/*
21789 		 * Send back a window update immediately if TCP is above
21790 		 * ESTABLISHED state and the increase of the rcv window
21791 		 * that the other side knows is at least 1 MSS after flow
21792 		 * control is lifted.
21793 		 */
21794 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
21795 		    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
21796 			tcp_xmit_ctl(NULL, tcp,
21797 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
21798 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
21799 		}
21800 	}
21801 
21802 	squeue_synch_exit(connp->conn_sqp, connp);
21803 }
21804 
21805 /* ARGSUSED */
21806 int
21807 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
21808     int mode, int32_t *rvalp, cred_t *cr)
21809 {
21810 	conn_t  	*connp = (conn_t *)proto_handle;
21811 	int		error;
21812 
21813 	ASSERT(connp->conn_upper_handle != NULL);
21814 
21815 	/* All Solaris components should pass a cred for this operation. */
21816 	ASSERT(cr != NULL);
21817 
21818 	/*
21819 	 * If we don't have a helper stream then create one.
21820 	 * ip_create_helper_stream takes care of locking the conn_t,
21821 	 * so this check for NULL is just a performance optimization.
21822 	 */
21823 	if (connp->conn_helper_info == NULL) {
21824 		tcp_stack_t *tcps = connp->conn_tcp->tcp_tcps;
21825 
21826 		/*
21827 		 * Create a helper stream for non-STREAMS socket.
21828 		 */
21829 		error = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
21830 		if (error != 0) {
21831 			ip0dbg(("tcp_ioctl: create of IP helper stream "
21832 			    "failed %d\n", error));
21833 			return (error);
21834 		}
21835 	}
21836 
21837 	switch (cmd) {
21838 		case ND_SET:
21839 		case ND_GET:
21840 		case _SIOCSOCKFALLBACK:
21841 		case TCP_IOC_ABORT_CONN:
21842 		case TI_GETPEERNAME:
21843 		case TI_GETMYNAME:
21844 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
21845 			    cmd));
21846 			error = EINVAL;
21847 			break;
21848 		default:
21849 			/*
21850 			 * Pass on to IP using helper stream
21851 			 */
21852 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
21853 			    cmd, arg, mode, cr, rvalp);
21854 			break;
21855 	}
21856 	return (error);
21857 }
21858 
21859 sock_downcalls_t sock_tcp_downcalls = {
21860 	tcp_activate,
21861 	tcp_accept,
21862 	tcp_bind,
21863 	tcp_listen,
21864 	tcp_connect,
21865 	tcp_getpeername,
21866 	tcp_getsockname,
21867 	tcp_getsockopt,
21868 	tcp_setsockopt,
21869 	tcp_sendmsg,
21870 	NULL,
21871 	NULL,
21872 	NULL,
21873 	tcp_shutdown,
21874 	tcp_clr_flowctrl,
21875 	tcp_ioctl,
21876 	tcp_close,
21877 };
21878 
21879 /*
21880  * Timeout function to reset the TCP stack variable tcps_reclaim to false.
21881  */
21882 static void
21883 tcp_reclaim_timer(void *arg)
21884 {
21885 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
21886 
21887 	mutex_enter(&tcps->tcps_reclaim_lock);
21888 	tcps->tcps_reclaim = B_FALSE;
21889 	tcps->tcps_reclaim_tid = 0;
21890 	mutex_exit(&tcps->tcps_reclaim_lock);
21891 	/* Only need to print this once. */
21892 	if (tcps->tcps_netstack->netstack_stackid == GLOBAL_ZONEID)
21893 		cmn_err(CE_WARN, "TCP defensive mode off\n");
21894 }
21895 
21896 /*
21897  * Kmem reclaim call back function.  When the system is under memory
21898  * pressure, we set the TCP stack variable tcps_reclaim to true.  This
21899  * variable is reset to false after tcps_reclaim_period msecs.  During this
21900  * period, TCP will be more aggressive in aborting connections not making
21901  * progress, meaning retransmitting for some time (tcp_early_abort seconds).
21902  * TCP will also not accept new connection request for those listeners whose
21903  * q or q0 is not empty.
21904  */
21905 /* ARGSUSED */
21906 void
21907 tcp_conn_reclaim(void *arg)
21908 {
21909 	netstack_handle_t nh;
21910 	netstack_t *ns;
21911 	tcp_stack_t *tcps;
21912 	boolean_t new = B_FALSE;
21913 
21914 	netstack_next_init(&nh);
21915 	while ((ns = netstack_next(&nh)) != NULL) {
21916 		tcps = ns->netstack_tcp;
21917 		mutex_enter(&tcps->tcps_reclaim_lock);
21918 		if (!tcps->tcps_reclaim) {
21919 			tcps->tcps_reclaim = B_TRUE;
21920 			tcps->tcps_reclaim_tid = timeout(tcp_reclaim_timer,
21921 			    tcps, MSEC_TO_TICK(tcps->tcps_reclaim_period));
21922 			new = B_TRUE;
21923 		}
21924 		mutex_exit(&tcps->tcps_reclaim_lock);
21925 		netstack_rele(ns);
21926 	}
21927 	netstack_next_fini(&nh);
21928 	if (new)
21929 		cmn_err(CE_WARN, "Memory pressure: TCP defensive mode on\n");
21930 }
21931 
21932 /*
21933  * Given a tcp_stack_t and a port (in host byte order), find a listener
21934  * configuration for that port and return the ratio.
21935  */
21936 static uint32_t
21937 tcp_find_listener_conf(tcp_stack_t *tcps, in_port_t port)
21938 {
21939 	tcp_listener_t	*tl;
21940 	uint32_t ratio = 0;
21941 
21942 	mutex_enter(&tcps->tcps_listener_conf_lock);
21943 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
21944 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
21945 		if (tl->tl_port == port) {
21946 			ratio = tl->tl_ratio;
21947 			break;
21948 		}
21949 	}
21950 	mutex_exit(&tcps->tcps_listener_conf_lock);
21951 	return (ratio);
21952 }
21953 
21954 /*
21955  * Ndd param helper routine to return the current list of listener limit
21956  * configuration.
21957  */
21958 /* ARGSUSED */
21959 static int
21960 tcp_listener_conf_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
21961 {
21962 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21963 	tcp_listener_t	*tl;
21964 
21965 	mutex_enter(&tcps->tcps_listener_conf_lock);
21966 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
21967 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
21968 		(void) mi_mpprintf(mp, "%d:%d ", tl->tl_port, tl->tl_ratio);
21969 	}
21970 	mutex_exit(&tcps->tcps_listener_conf_lock);
21971 	return (0);
21972 }
21973 
21974 /*
21975  * Ndd param helper routine to add a new listener limit configuration.
21976  */
21977 /* ARGSUSED */
21978 static int
21979 tcp_listener_conf_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
21980     cred_t *cr)
21981 {
21982 	tcp_listener_t	*new_tl;
21983 	tcp_listener_t	*tl;
21984 	long		lport;
21985 	long		ratio;
21986 	char		*colon;
21987 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
21988 
21989 	if (ddi_strtol(value, &colon, 10, &lport) != 0 || lport <= 0 ||
21990 	    lport > USHRT_MAX || *colon != ':') {
21991 		return (EINVAL);
21992 	}
21993 	if (ddi_strtol(colon + 1, NULL, 10, &ratio) != 0 || ratio <= 0)
21994 		return (EINVAL);
21995 
21996 	mutex_enter(&tcps->tcps_listener_conf_lock);
21997 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
21998 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
21999 		/* There is an existing entry, so update its ratio value. */
22000 		if (tl->tl_port == lport) {
22001 			tl->tl_ratio = ratio;
22002 			mutex_exit(&tcps->tcps_listener_conf_lock);
22003 			return (0);
22004 		}
22005 	}
22006 
22007 	if ((new_tl = kmem_alloc(sizeof (tcp_listener_t), KM_NOSLEEP)) ==
22008 	    NULL) {
22009 		mutex_exit(&tcps->tcps_listener_conf_lock);
22010 		return (ENOMEM);
22011 	}
22012 
22013 	new_tl->tl_port = lport;
22014 	new_tl->tl_ratio = ratio;
22015 	list_insert_tail(&tcps->tcps_listener_conf, new_tl);
22016 	mutex_exit(&tcps->tcps_listener_conf_lock);
22017 	return (0);
22018 }
22019 
22020 /*
22021  * Ndd param helper routine to remove a listener limit configuration.
22022  */
22023 /* ARGSUSED */
22024 static int
22025 tcp_listener_conf_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
22026     cred_t *cr)
22027 {
22028 	tcp_listener_t	*tl;
22029 	long		lport;
22030 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22031 
22032 	if (ddi_strtol(value, NULL, 10, &lport) != 0 || lport <= 0 ||
22033 	    lport > USHRT_MAX) {
22034 		return (EINVAL);
22035 	}
22036 	mutex_enter(&tcps->tcps_listener_conf_lock);
22037 	for (tl = list_head(&tcps->tcps_listener_conf); tl != NULL;
22038 	    tl = list_next(&tcps->tcps_listener_conf, tl)) {
22039 		if (tl->tl_port == lport) {
22040 			list_remove(&tcps->tcps_listener_conf, tl);
22041 			mutex_exit(&tcps->tcps_listener_conf_lock);
22042 			kmem_free(tl, sizeof (tcp_listener_t));
22043 			return (0);
22044 		}
22045 	}
22046 	mutex_exit(&tcps->tcps_listener_conf_lock);
22047 	return (ESRCH);
22048 }
22049 
22050 /*
22051  * To remove all listener limit configuration in a tcp_stack_t.
22052  */
22053 static void
22054 tcp_listener_conf_cleanup(tcp_stack_t *tcps)
22055 {
22056 	tcp_listener_t	*tl;
22057 
22058 	mutex_enter(&tcps->tcps_listener_conf_lock);
22059 	while ((tl = list_head(&tcps->tcps_listener_conf)) != NULL) {
22060 		list_remove(&tcps->tcps_listener_conf, tl);
22061 		kmem_free(tl, sizeof (tcp_listener_t));
22062 	}
22063 	mutex_destroy(&tcps->tcps_listener_conf_lock);
22064 	list_destroy(&tcps->tcps_listener_conf);
22065 }
22066