xref: /titanic_50/usr/src/uts/common/inet/tcp/tcp.c (revision 0b32bb8bde09d49065e395405874016d9a227861)
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 2008 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 #include <sys/strsun.h>
35 #define	_SUN_TPI_VERSION 2
36 #include <sys/tihdr.h>
37 #include <sys/timod.h>
38 #include <sys/ddi.h>
39 #include <sys/sunddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/xti_inet.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/sdt.h>
45 #include <sys/vtrace.h>
46 #include <sys/kmem.h>
47 #include <sys/ethernet.h>
48 #include <sys/cpuvar.h>
49 #include <sys/dlpi.h>
50 #include <sys/multidata.h>
51 #include <sys/multidata_impl.h>
52 #include <sys/pattr.h>
53 #include <sys/policy.h>
54 #include <sys/priv.h>
55 #include <sys/zone.h>
56 #include <sys/sunldi.h>
57 
58 #include <sys/errno.h>
59 #include <sys/signal.h>
60 #include <sys/socket.h>
61 #include <sys/sockio.h>
62 #include <sys/isa_defs.h>
63 #include <sys/md5.h>
64 #include <sys/random.h>
65 #include <sys/sodirect.h>
66 #include <sys/uio.h>
67 #include <sys/systm.h>
68 #include <netinet/in.h>
69 #include <netinet/tcp.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <net/if.h>
73 #include <net/route.h>
74 #include <inet/ipsec_impl.h>
75 
76 #include <inet/common.h>
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip_ndp.h>
81 #include <inet/mi.h>
82 #include <inet/mib2.h>
83 #include <inet/nd.h>
84 #include <inet/optcom.h>
85 #include <inet/snmpcom.h>
86 #include <inet/kstatcom.h>
87 #include <inet/tcp.h>
88 #include <inet/tcp_impl.h>
89 #include <net/pfkeyv2.h>
90 #include <inet/ipsec_info.h>
91 #include <inet/ipdrop.h>
92 
93 #include <inet/ipclassifier.h>
94 #include <inet/ip_ire.h>
95 #include <inet/ip_ftable.h>
96 #include <inet/ip_if.h>
97 #include <inet/ipp_common.h>
98 #include <inet/ip_netinfo.h>
99 #include <sys/squeue_impl.h>
100 #include <sys/squeue.h>
101 #include <inet/kssl/ksslapi.h>
102 #include <sys/tsol/label.h>
103 #include <sys/tsol/tnet.h>
104 #include <rpc/pmap_prot.h>
105 #include <sys/callo.h>
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_CONNTCP 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_conn_request(). But briefly, the squeue is picked by
176  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
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 provision for (AF_INET, SOCK_STREAM) sockets which
202  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
203  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
204  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
205  * check to send packets directly to tcp_rput_data via squeue. Everyone
206  * else comes through tcp_input() on the read side.
207  *
208  * We also make special provisions for sockfs by marking tcp_issocket
209  * whenever we have only sockfs on top of TCP. This allows us to skip
210  * putting the tcp in acceptor hash since a sockfs listener can never
211  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
212  * since eager has already been allocated and the accept now happens
213  * on acceptor STREAM. There is a big blob of comment on top of
214  * tcp_conn_request explaining the new accept. When socket is POP'd,
215  * sockfs sends us an ioctl to mark the fact and we go back to old
216  * behaviour. Once tcp_issocket is unset, its never set for the
217  * life of that connection.
218  *
219  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
220  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
221  * directly to the socket (sodirect) and start an asynchronous copyout
222  * to a user-land receive-side buffer (uioa) when a blocking socket read
223  * (e.g. read, recv, ...) is pending.
224  *
225  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
226  * NULL so points to an sodirect_t and if marked enabled then we enqueue
227  * all mblk_t's directly to the socket.
228  *
229  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
230  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
231  * copyout will be started directly to the user-land uio buffer. Also, as we
232  * have a pending read, TCP's push logic can take into account the number of
233  * bytes to be received and only awake the blocked read()er when the uioa_t
234  * byte count has been satisfied.
235  *
236  * IPsec notes :
237  *
238  * Since a packet is always executed on the correct TCP perimeter
239  * all IPsec processing is defered to IP including checking new
240  * connections and setting IPSEC policies for new connection. The
241  * only exception is tcp_xmit_listeners_reset() which is called
242  * directly from IP and needs to policy check to see if TH_RST
243  * can be sent out.
244  *
245  * PFHooks notes :
246  *
247  * For mdt case, one meta buffer contains multiple packets. Mblks for every
248  * packet are assembled and passed to the hooks. When packets are blocked,
249  * or boundary of any packet is changed, the mdt processing is stopped, and
250  * packets of the meta buffer are send to the IP path one by one.
251  */
252 
253 /*
254  * Values for squeue switch:
255  * 1: SQ_NODRAIN
256  * 2: SQ_PROCESS
257  * 3: SQ_FILL
258  */
259 int tcp_squeue_wput = 2;	/* /etc/systems */
260 int tcp_squeue_flag;
261 
262 /*
263  * Macros for sodirect:
264  *
265  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
266  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
267  * if it exists and is enabled, else to NULL. Note, in the current
268  * sodirect implementation the sod_lockp must not be held across any
269  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
270  * will result as sod_lockp is the streamhead stdata.sd_lock.
271  *
272  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
273  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
274  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
275  * being used when sodirect code paths should be.
276  */
277 
278 #define	SOD_PTR_ENTER(tcp, sodp)					\
279 	(sodp) = (tcp)->tcp_sodirect;					\
280 									\
281 	if ((sodp) != NULL) {						\
282 		mutex_enter((sodp)->sod_lockp);				\
283 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
284 			mutex_exit((sodp)->sod_lockp);			\
285 			(sodp) = NULL;					\
286 		}							\
287 	}
288 
289 #define	SOD_NOT_ENABLED(tcp)						\
290 	((tcp)->tcp_sodirect == NULL ||					\
291 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
292 
293 /*
294  * This controls how tiny a write must be before we try to copy it
295  * into the the mblk on the tail of the transmit queue.  Not much
296  * speedup is observed for values larger than sixteen.  Zero will
297  * disable the optimisation.
298  */
299 int tcp_tx_pull_len = 16;
300 
301 /*
302  * TCP Statistics.
303  *
304  * How TCP statistics work.
305  *
306  * There are two types of statistics invoked by two macros.
307  *
308  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
309  * supposed to be used in non MT-hot paths of the code.
310  *
311  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
312  * supposed to be used for DEBUG purposes and may be used on a hot path.
313  *
314  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
315  * (use "kstat tcp" to get them).
316  *
317  * There is also additional debugging facility that marks tcp_clean_death()
318  * instances and saves them in tcp_t structure. It is triggered by
319  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
320  * tcp_clean_death() calls that counts the number of times each tag was hit. It
321  * is triggered by TCP_CLD_COUNTERS define.
322  *
323  * How to add new counters.
324  *
325  * 1) Add a field in the tcp_stat structure describing your counter.
326  * 2) Add a line in the template in tcp_kstat2_init() with the name
327  *    of the counter.
328  *
329  *    IMPORTANT!! - make sure that both are in sync !!
330  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
331  *
332  * Please avoid using private counters which are not kstat-exported.
333  *
334  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
335  * in tcp_t structure.
336  *
337  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
338  */
339 
340 #ifndef TCP_DEBUG_COUNTER
341 #ifdef DEBUG
342 #define	TCP_DEBUG_COUNTER 1
343 #else
344 #define	TCP_DEBUG_COUNTER 0
345 #endif
346 #endif
347 
348 #define	TCP_CLD_COUNTERS 0
349 
350 #define	TCP_TAG_CLEAN_DEATH 1
351 #define	TCP_MAX_CLEAN_DEATH_TAG 32
352 
353 #ifdef lint
354 static int _lint_dummy_;
355 #endif
356 
357 #if TCP_CLD_COUNTERS
358 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
359 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
360 #elif defined(lint)
361 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
362 #else
363 #define	TCP_CLD_STAT(x)
364 #endif
365 
366 #if TCP_DEBUG_COUNTER
367 #define	TCP_DBGSTAT(tcps, x)	\
368 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
369 #define	TCP_G_DBGSTAT(x)	\
370 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
371 #elif defined(lint)
372 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
373 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
374 #else
375 #define	TCP_DBGSTAT(tcps, x)
376 #define	TCP_G_DBGSTAT(x)
377 #endif
378 
379 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
380 
381 tcp_g_stat_t	tcp_g_statistics;
382 kstat_t		*tcp_g_kstat;
383 
384 /*
385  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
386  * tcp write side.
387  */
388 #define	CALL_IP_WPUT(connp, q, mp) {					\
389 	tcp_stack_t	*tcps;						\
390 									\
391 	tcps = connp->conn_netstack->netstack_tcp;			\
392 	ASSERT(((q)->q_flag & QREADR) == 0);				\
393 	TCP_DBGSTAT(tcps, tcp_ip_output);				\
394 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
395 }
396 
397 /* Macros for timestamp comparisons */
398 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
399 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
400 
401 /*
402  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
403  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
404  * by adding three components: a time component which grows by 1 every 4096
405  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
406  * a per-connection component which grows by 125000 for every new connection;
407  * and an "extra" component that grows by a random amount centered
408  * approximately on 64000.  This causes the the ISS generator to cycle every
409  * 4.89 hours if no TCP connections are made, and faster if connections are
410  * made.
411  *
412  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
413  * components: a time component which grows by 250000 every second; and
414  * a per-connection component which grows by 125000 for every new connections.
415  *
416  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
417  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
418  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
419  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
420  * password.
421  */
422 #define	ISS_INCR	250000
423 #define	ISS_NSEC_SHT	12
424 
425 static sin_t	sin_null;	/* Zero address for quick clears */
426 static sin6_t	sin6_null;	/* Zero address for quick clears */
427 
428 /*
429  * This implementation follows the 4.3BSD interpretation of the urgent
430  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
431  * incompatible changes in protocols like telnet and rlogin.
432  */
433 #define	TCP_OLD_URP_INTERPRETATION	1
434 
435 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
436 	(TCP_IS_DETACHED(tcp) && \
437 	    (!(tcp)->tcp_hard_binding))
438 
439 /*
440  * TCP reassembly macros.  We hide starting and ending sequence numbers in
441  * b_next and b_prev of messages on the reassembly queue.  The messages are
442  * chained using b_cont.  These macros are used in tcp_reass() so we don't
443  * have to see the ugly casts and assignments.
444  */
445 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
446 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
447 					(mblk_t *)(uintptr_t)(u))
448 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
449 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
450 					(mblk_t *)(uintptr_t)(u))
451 
452 /*
453  * Implementation of TCP Timers.
454  * =============================
455  *
456  * INTERFACE:
457  *
458  * There are two basic functions dealing with tcp timers:
459  *
460  *	timeout_id_t	tcp_timeout(connp, func, time)
461  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
462  *	TCP_TIMER_RESTART(tcp, intvl)
463  *
464  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
465  * after 'time' ticks passed. The function called by timeout() must adhere to
466  * the same restrictions as a driver soft interrupt handler - it must not sleep
467  * or call other functions that might sleep. The value returned is the opaque
468  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
469  * cancel the request. The call to tcp_timeout() may fail in which case it
470  * returns zero. This is different from the timeout(9F) function which never
471  * fails.
472  *
473  * The call-back function 'func' always receives 'connp' as its single
474  * argument. It is always executed in the squeue corresponding to the tcp
475  * structure. The tcp structure is guaranteed to be present at the time the
476  * call-back is called.
477  *
478  * NOTE: The call-back function 'func' is never called if tcp is in
479  * 	the TCPS_CLOSED state.
480  *
481  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
482  * request. locks acquired by the call-back routine should not be held across
483  * the call to tcp_timeout_cancel() or a deadlock may result.
484  *
485  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
486  * Otherwise, it returns an integer value greater than or equal to 0. In
487  * particular, if the call-back function is already placed on the squeue, it can
488  * not be canceled.
489  *
490  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
491  * 	within squeue context corresponding to the tcp instance. Since the
492  *	call-back is also called via the same squeue, there are no race
493  *	conditions described in untimeout(9F) manual page since all calls are
494  *	strictly serialized.
495  *
496  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
497  *	stored in tcp_timer_tid and starts a new one using
498  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
499  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
500  *	field.
501  *
502  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
503  *	call-back may still be called, so it is possible tcp_timer() will be
504  *	called several times. This should not be a problem since tcp_timer()
505  *	should always check the tcp instance state.
506  *
507  *
508  * IMPLEMENTATION:
509  *
510  * TCP timers are implemented using three-stage process. The call to
511  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
512  * when the timer expires. The tcp_timer_callback() arranges the call of the
513  * tcp_timer_handler() function via squeue corresponding to the tcp
514  * instance. The tcp_timer_handler() calls actual requested timeout call-back
515  * and passes tcp instance as an argument to it. Information is passed between
516  * stages using the tcp_timer_t structure which contains the connp pointer, the
517  * tcp call-back to call and the timeout id returned by the timeout(9F).
518  *
519  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
520  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
521  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
522  * returns the pointer to this mblk.
523  *
524  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
525  * looks like a normal mblk without actual dblk attached to it.
526  *
527  * To optimize performance each tcp instance holds a small cache of timer
528  * mblocks. In the current implementation it caches up to two timer mblocks per
529  * tcp instance. The cache is preserved over tcp frees and is only freed when
530  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
531  * timer processing happens on a corresponding squeue, the cache manipulation
532  * does not require any locks. Experiments show that majority of timer mblocks
533  * allocations are satisfied from the tcp cache and do not involve kmem calls.
534  *
535  * The tcp_timeout() places a refhold on the connp instance which guarantees
536  * that it will be present at the time the call-back function fires. The
537  * tcp_timer_handler() drops the reference after calling the call-back, so the
538  * call-back function does not need to manipulate the references explicitly.
539  */
540 
541 typedef struct tcp_timer_s {
542 	conn_t	*connp;
543 	void 	(*tcpt_proc)(void *);
544 	callout_id_t   tcpt_tid;
545 } tcp_timer_t;
546 
547 static kmem_cache_t *tcp_timercache;
548 kmem_cache_t	*tcp_sack_info_cache;
549 kmem_cache_t	*tcp_iphc_cache;
550 
551 /*
552  * For scalability, we must not run a timer for every TCP connection
553  * in TIME_WAIT state.  To see why, consider (for time wait interval of
554  * 4 minutes):
555  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
556  *
557  * This list is ordered by time, so you need only delete from the head
558  * until you get to entries which aren't old enough to delete yet.
559  * The list consists of only the detached TIME_WAIT connections.
560  *
561  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
562  * becomes detached TIME_WAIT (either by changing the state and already
563  * being detached or the other way around). This means that the TIME_WAIT
564  * state can be extended (up to doubled) if the connection doesn't become
565  * detached for a long time.
566  *
567  * The list manipulations (including tcp_time_wait_next/prev)
568  * are protected by the tcp_time_wait_lock. The content of the
569  * detached TIME_WAIT connections is protected by the normal perimeters.
570  *
571  * This list is per squeue and squeues are shared across the tcp_stack_t's.
572  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
573  * and conn_netstack.
574  * The tcp_t's that are added to tcp_free_list are disassociated and
575  * have NULL tcp_tcps and conn_netstack pointers.
576  */
577 typedef struct tcp_squeue_priv_s {
578 	kmutex_t	tcp_time_wait_lock;
579 	callout_id_t	tcp_time_wait_tid;
580 	tcp_t		*tcp_time_wait_head;
581 	tcp_t		*tcp_time_wait_tail;
582 	tcp_t		*tcp_free_list;
583 	uint_t		tcp_free_list_cnt;
584 } tcp_squeue_priv_t;
585 
586 /*
587  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
588  * Running it every 5 seconds seems to give the best results.
589  */
590 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
591 
592 /*
593  * To prevent memory hog, limit the number of entries in tcp_free_list
594  * to 1% of available memory / number of cpus
595  */
596 uint_t tcp_free_list_max_cnt = 0;
597 
598 #define	TCP_XMIT_LOWATER	4096
599 #define	TCP_XMIT_HIWATER	49152
600 #define	TCP_RECV_LOWATER	2048
601 #define	TCP_RECV_HIWATER	49152
602 
603 /*
604  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
605  */
606 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
607 
608 #define	TIDUSZ	4096	/* transport interface data unit size */
609 
610 /*
611  * Bind hash list size and has function.  It has to be a power of 2 for
612  * hashing.
613  */
614 #define	TCP_BIND_FANOUT_SIZE	512
615 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
616 /*
617  * Size of listen and acceptor hash list.  It has to be a power of 2 for
618  * hashing.
619  */
620 #define	TCP_FANOUT_SIZE		256
621 
622 #ifdef	_ILP32
623 #define	TCP_ACCEPTOR_HASH(accid)					\
624 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
625 #else
626 #define	TCP_ACCEPTOR_HASH(accid)					\
627 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
628 #endif	/* _ILP32 */
629 
630 #define	IP_ADDR_CACHE_SIZE	2048
631 #define	IP_ADDR_CACHE_HASH(faddr)					\
632 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
633 
634 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
635 #define	TCP_HSP_HASH_SIZE 256
636 
637 #define	TCP_HSP_HASH(addr)					\
638 	(((addr>>24) ^ (addr >>16) ^			\
639 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
640 
641 /*
642  * TCP options struct returned from tcp_parse_options.
643  */
644 typedef struct tcp_opt_s {
645 	uint32_t	tcp_opt_mss;
646 	uint32_t	tcp_opt_wscale;
647 	uint32_t	tcp_opt_ts_val;
648 	uint32_t	tcp_opt_ts_ecr;
649 	tcp_t		*tcp;
650 } tcp_opt_t;
651 
652 /*
653  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
654  */
655 
656 #ifdef _BIG_ENDIAN
657 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
658 	(TCPOPT_TSTAMP << 8) | 10)
659 #else
660 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
661 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
662 #endif
663 
664 /*
665  * Flags returned from tcp_parse_options.
666  */
667 #define	TCP_OPT_MSS_PRESENT	1
668 #define	TCP_OPT_WSCALE_PRESENT	2
669 #define	TCP_OPT_TSTAMP_PRESENT	4
670 #define	TCP_OPT_SACK_OK_PRESENT	8
671 #define	TCP_OPT_SACK_PRESENT	16
672 
673 /* TCP option length */
674 #define	TCPOPT_NOP_LEN		1
675 #define	TCPOPT_MAXSEG_LEN	4
676 #define	TCPOPT_WS_LEN		3
677 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
678 #define	TCPOPT_TSTAMP_LEN	10
679 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
680 #define	TCPOPT_SACK_OK_LEN	2
681 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
682 #define	TCPOPT_REAL_SACK_LEN	4
683 #define	TCPOPT_MAX_SACK_LEN	36
684 #define	TCPOPT_HEADER_LEN	2
685 
686 /* TCP cwnd burst factor. */
687 #define	TCP_CWND_INFINITE	65535
688 #define	TCP_CWND_SS		3
689 #define	TCP_CWND_NORMAL		5
690 
691 /* Maximum TCP initial cwin (start/restart). */
692 #define	TCP_MAX_INIT_CWND	8
693 
694 /*
695  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
696  * either tcp_slow_start_initial or tcp_slow_start_after idle
697  * depending on the caller.  If the upper layer has not used the
698  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
699  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
700  * If the upper layer has changed set the tcp_init_cwnd, just use
701  * it to calculate the tcp_cwnd.
702  */
703 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
704 {									\
705 	if ((tcp)->tcp_init_cwnd == 0) {				\
706 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
707 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
708 	} else {							\
709 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
710 	}								\
711 	tcp->tcp_cwnd_cnt = 0;						\
712 }
713 
714 /* TCP Timer control structure */
715 typedef struct tcpt_s {
716 	pfv_t	tcpt_pfv;	/* The routine we are to call */
717 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
718 } tcpt_t;
719 
720 /* Host Specific Parameter structure */
721 typedef struct tcp_hsp {
722 	struct tcp_hsp	*tcp_hsp_next;
723 	in6_addr_t	tcp_hsp_addr_v6;
724 	in6_addr_t	tcp_hsp_subnet_v6;
725 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
726 	int32_t		tcp_hsp_sendspace;
727 	int32_t		tcp_hsp_recvspace;
728 	int32_t		tcp_hsp_tstamp;
729 } tcp_hsp_t;
730 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
731 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
732 
733 /*
734  * Functions called directly via squeue having a prototype of edesc_t.
735  */
736 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
737 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
738 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
739 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
740 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
741 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
742 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
743 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
744 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
745 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
746 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
747 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
748 
749 
750 /* Prototype for TCP functions */
751 static void	tcp_random_init(void);
752 int		tcp_random(void);
753 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
754 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
755 		    tcp_t *eager);
756 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
757 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
758     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
759     boolean_t user_specified);
760 static void	tcp_closei_local(tcp_t *tcp);
761 static void	tcp_close_detached(tcp_t *tcp);
762 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
763 			mblk_t *idmp, mblk_t **defermp);
764 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
765 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
766 		    in_port_t dstport, uint_t srcid);
767 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
768 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
769 		    uint32_t scope_id);
770 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
771 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
772 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
773 static char	*tcp_display(tcp_t *tcp, char *, char);
774 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
775 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
776 static void	tcp_eager_unlink(tcp_t *tcp);
777 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
778 		    int unixerr);
779 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
780 		    int tlierr, int unixerr);
781 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
782 		    cred_t *cr);
783 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
784 		    char *value, caddr_t cp, cred_t *cr);
785 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
786 		    char *value, caddr_t cp, cred_t *cr);
787 static int	tcp_tpistate(tcp_t *tcp);
788 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
789     int caller_holds_lock);
790 static void	tcp_bind_hash_remove(tcp_t *tcp);
791 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
792 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
793 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
794 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
795 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
796 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
797 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
798 void		tcp_g_q_setup(tcp_stack_t *);
799 void		tcp_g_q_create(tcp_stack_t *);
800 void		tcp_g_q_destroy(tcp_stack_t *);
801 static int	tcp_header_init_ipv4(tcp_t *tcp);
802 static int	tcp_header_init_ipv6(tcp_t *tcp);
803 int		tcp_init(tcp_t *tcp, queue_t *q);
804 static int	tcp_init_values(tcp_t *tcp);
805 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
806 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
807 		    t_scalar_t addr_length);
808 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
809 static void	tcp_ip_notify(tcp_t *tcp);
810 static mblk_t	*tcp_ire_mp(mblk_t *mp);
811 static void	tcp_iss_init(tcp_t *tcp);
812 static void	tcp_keepalive_killer(void *arg);
813 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
814 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
815 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
816 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
817 static boolean_t tcp_allow_connopt_set(int level, int name);
818 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
819 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
820 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
821 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
822 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
823 		    mblk_t *mblk);
824 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
825 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
826 		    uchar_t *ptr, uint_t len);
827 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
828 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
829     tcp_stack_t *);
830 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
831 		    caddr_t cp, cred_t *cr);
832 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
833 		    caddr_t cp, cred_t *cr);
834 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
835 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
836 		    caddr_t cp, cred_t *cr);
837 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
838 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
839 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
840 static void	tcp_reinit(tcp_t *tcp);
841 static void	tcp_reinit_values(tcp_t *tcp);
842 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
843 		    tcp_t *thisstream, cred_t *cr);
844 
845 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
846 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
847 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
848 static void	tcp_ss_rexmit(tcp_t *tcp);
849 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
850 static void	tcp_process_options(tcp_t *, tcph_t *);
851 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
852 static void	tcp_rsrv(queue_t *q);
853 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
854 static int	tcp_snmp_state(tcp_t *tcp);
855 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
856 		    cred_t *cr);
857 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
858 		    cred_t *cr);
859 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
860 		    cred_t *cr);
861 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
862 		    cred_t *cr);
863 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
864 		    cred_t *cr);
865 static void	tcp_timer(void *arg);
866 static void	tcp_timer_callback(void *);
867 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
868     boolean_t random);
869 static in_port_t tcp_get_next_priv_port(const tcp_t *);
870 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
871 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
872 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
873 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
874 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
875 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
876 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
877 		    const int num_sack_blk, int *usable, uint_t *snxt,
878 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
879 		    const int mdt_thres);
880 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
881 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
882 		    const int num_sack_blk, int *usable, uint_t *snxt,
883 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
884 		    const int mdt_thres);
885 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
886 		    int num_sack_blk);
887 static void	tcp_wsrv(queue_t *q);
888 static int	tcp_xmit_end(tcp_t *tcp);
889 static void	tcp_ack_timer(void *arg);
890 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
891 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
892 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
893 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
894 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
895 		    uint32_t ack, int ctl);
896 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
897 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
898 static int	setmaxps(queue_t *q, int maxpsz);
899 static void	tcp_set_rto(tcp_t *, time_t);
900 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
901 		    boolean_t, boolean_t);
902 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
903 		    boolean_t ipsec_mctl);
904 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
905 		    char *opt, int optlen);
906 static int	tcp_build_hdrs(queue_t *, tcp_t *);
907 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
908 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
909 		    tcph_t *tcph);
910 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
911 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
912 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
913 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
914 		    const boolean_t, const uint32_t, const uint32_t,
915 		    const uint32_t, const uint32_t, tcp_stack_t *);
916 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
917 		    const uint_t, const uint_t, boolean_t *);
918 static mblk_t	*tcp_lso_info_mp(mblk_t *);
919 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
920 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
921 extern mblk_t	*tcp_timermp_alloc(int);
922 extern void	tcp_timermp_free(tcp_t *);
923 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
924 static void	tcp_stop_lingering(tcp_t *tcp);
925 static void	tcp_close_linger_timeout(void *arg);
926 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
927 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
928 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
929 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
930 static void	tcp_g_kstat_fini(kstat_t *);
931 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
932 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
933 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
934 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
935 static int	tcp_kstat_update(kstat_t *kp, int rw);
936 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
937 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
938 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
939 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
940 			tcph_t *tcph, mblk_t *idmp);
941 static int	tcp_squeue_switch(int);
942 
943 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
944 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
945 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
946 static int	tcp_close(queue_t *, int);
947 static int	tcpclose_accept(queue_t *);
948 
949 static void	tcp_squeue_add(squeue_t *);
950 static boolean_t tcp_zcopy_check(tcp_t *);
951 static void	tcp_zcopy_notify(tcp_t *);
952 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
953 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
954 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
955 
956 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
957 
958 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
959 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
960 
961 /*
962  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
963  *
964  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
965  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
966  * (defined in tcp.h) needs to be filled in and passed into the kernel
967  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
968  * structure contains the four-tuple of a TCP connection and a range of TCP
969  * states (specified by ac_start and ac_end). The use of wildcard addresses
970  * and ports is allowed. Connections with a matching four tuple and a state
971  * within the specified range will be aborted. The valid states for the
972  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
973  * inclusive.
974  *
975  * An application which has its connection aborted by this ioctl will receive
976  * an error that is dependent on the connection state at the time of the abort.
977  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
978  * though a RST packet has been received.  If the connection state is equal to
979  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
980  * and all resources associated with the connection will be freed.
981  */
982 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
983 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
984 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
985 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
986 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
987 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
988     boolean_t, tcp_stack_t *);
989 
990 static struct module_info tcp_rinfo =  {
991 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
992 };
993 
994 static struct module_info tcp_winfo =  {
995 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
996 };
997 
998 /*
999  * Entry points for TCP as a device. The normal case which supports
1000  * the TCP functionality.
1001  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
1002  */
1003 struct qinit tcp_rinitv4 = {
1004 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, NULL, &tcp_rinfo
1005 };
1006 
1007 struct qinit tcp_rinitv6 = {
1008 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_close, NULL, &tcp_rinfo
1009 };
1010 
1011 struct qinit tcp_winit = {
1012 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1013 };
1014 
1015 /* Initial entry point for TCP in socket mode. */
1016 struct qinit tcp_sock_winit = {
1017 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1018 };
1019 
1020 /*
1021  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1022  * an accept. Avoid allocating data structures since eager has already
1023  * been created.
1024  */
1025 struct qinit tcp_acceptor_rinit = {
1026 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1027 };
1028 
1029 struct qinit tcp_acceptor_winit = {
1030 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1031 };
1032 
1033 /*
1034  * Entry points for TCP loopback (read side only)
1035  * The open routine is only used for reopens, thus no need to
1036  * have a separate one for tcp_openv6.
1037  */
1038 struct qinit tcp_loopback_rinit = {
1039 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, (pfi_t)0,
1040 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1041 };
1042 
1043 /* For AF_INET aka /dev/tcp */
1044 struct streamtab tcpinfov4 = {
1045 	&tcp_rinitv4, &tcp_winit
1046 };
1047 
1048 /* For AF_INET6 aka /dev/tcp6 */
1049 struct streamtab tcpinfov6 = {
1050 	&tcp_rinitv6, &tcp_winit
1051 };
1052 
1053 /*
1054  * Have to ensure that tcp_g_q_close is not done by an
1055  * interrupt thread.
1056  */
1057 static taskq_t *tcp_taskq;
1058 
1059 /* Setable only in /etc/system. Move to ndd? */
1060 boolean_t tcp_icmp_source_quench = B_FALSE;
1061 
1062 /*
1063  * Following assumes TPI alignment requirements stay along 32 bit
1064  * boundaries
1065  */
1066 #define	ROUNDUP32(x) \
1067 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1068 
1069 /* Template for response to info request. */
1070 static struct T_info_ack tcp_g_t_info_ack = {
1071 	T_INFO_ACK,		/* PRIM_type */
1072 	0,			/* TSDU_size */
1073 	T_INFINITE,		/* ETSDU_size */
1074 	T_INVALID,		/* CDATA_size */
1075 	T_INVALID,		/* DDATA_size */
1076 	sizeof (sin_t),		/* ADDR_size */
1077 	0,			/* OPT_size - not initialized here */
1078 	TIDUSZ,			/* TIDU_size */
1079 	T_COTS_ORD,		/* SERV_type */
1080 	TCPS_IDLE,		/* CURRENT_state */
1081 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1082 };
1083 
1084 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1085 	T_INFO_ACK,		/* PRIM_type */
1086 	0,			/* TSDU_size */
1087 	T_INFINITE,		/* ETSDU_size */
1088 	T_INVALID,		/* CDATA_size */
1089 	T_INVALID,		/* DDATA_size */
1090 	sizeof (sin6_t),	/* ADDR_size */
1091 	0,			/* OPT_size - not initialized here */
1092 	TIDUSZ,		/* TIDU_size */
1093 	T_COTS_ORD,		/* SERV_type */
1094 	TCPS_IDLE,		/* CURRENT_state */
1095 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1096 };
1097 
1098 #define	MS	1L
1099 #define	SECONDS	(1000 * MS)
1100 #define	MINUTES	(60 * SECONDS)
1101 #define	HOURS	(60 * MINUTES)
1102 #define	DAYS	(24 * HOURS)
1103 
1104 #define	PARAM_MAX (~(uint32_t)0)
1105 
1106 /* Max size IP datagram is 64k - 1 */
1107 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1108 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1109 /* Max of the above */
1110 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1111 
1112 /* Largest TCP port number */
1113 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1114 
1115 /*
1116  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1117  * layer header.  It has to be a multiple of 4.
1118  */
1119 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1120 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1121 
1122 /*
1123  * All of these are alterable, within the min/max values given, at run time.
1124  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1125  * per the TCP spec.
1126  */
1127 /* BEGIN CSTYLED */
1128 static tcpparam_t	lcl_tcp_param_arr[] = {
1129  /*min		max		value		name */
1130  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1131  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1132  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1133  { 1,		1024,		1,		"tcp_conn_req_min" },
1134  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1135  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1136  { 0,		10,		0,		"tcp_debug" },
1137  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1138  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1139  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1140  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1141  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1142  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1143  { 1,		255,		64,		"tcp_ipv4_ttl"},
1144  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1145  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1146  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1147  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1148  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1149  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1150  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1151  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1152  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1153  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1154  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1155  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1156  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1157  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1158  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1159  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1160  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1161  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1162  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1163  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1164  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1165  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1166  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1167 /*
1168  * Question:  What default value should I set for tcp_strong_iss?
1169  */
1170  { 0,		2,		1,		"tcp_strong_iss"},
1171  { 0,		65536,		20,		"tcp_rtt_updates"},
1172  { 0,		1,		1,		"tcp_wscale_always"},
1173  { 0,		1,		0,		"tcp_tstamp_always"},
1174  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1175  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1176  { 0,		16,		2,		"tcp_deferred_acks_max"},
1177  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1178  { 1,		4,		4,		"tcp_slow_start_initial"},
1179  { 0,		2,		2,		"tcp_sack_permitted"},
1180  { 0,		1,		1,		"tcp_compression_enabled"},
1181  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1182  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1183  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1184  { 0,		1,		0,		"tcp_rev_src_routes"},
1185  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1186  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1187  { 0,		16,		8,		"tcp_local_dacks_max"},
1188  { 0,		2,		1,		"tcp_ecn_permitted"},
1189  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1190  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1191  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1192  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1193  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1194 };
1195 /* END CSTYLED */
1196 
1197 /*
1198  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1199  * each header fragment in the header buffer.  Each parameter value has
1200  * to be a multiple of 4 (32-bit aligned).
1201  */
1202 static tcpparam_t lcl_tcp_mdt_head_param =
1203 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1204 static tcpparam_t lcl_tcp_mdt_tail_param =
1205 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1206 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1207 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1208 
1209 /*
1210  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1211  * the maximum number of payload buffers associated per Multidata.
1212  */
1213 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1214 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1215 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1216 
1217 /* Round up the value to the nearest mss. */
1218 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1219 
1220 /*
1221  * Set ECN capable transport (ECT) code point in IP header.
1222  *
1223  * Note that there are 2 ECT code points '01' and '10', which are called
1224  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1225  * point ECT(0) for TCP as described in RFC 2481.
1226  */
1227 #define	SET_ECT(tcp, iph) \
1228 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1229 		/* We need to clear the code point first. */ \
1230 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1231 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1232 	} else { \
1233 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1234 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1235 	}
1236 
1237 /*
1238  * The format argument to pass to tcp_display().
1239  * DISP_PORT_ONLY means that the returned string has only port info.
1240  * DISP_ADDR_AND_PORT means that the returned string also contains the
1241  * remote and local IP address.
1242  */
1243 #define	DISP_PORT_ONLY		1
1244 #define	DISP_ADDR_AND_PORT	2
1245 
1246 #define	NDD_TOO_QUICK_MSG \
1247 	"ndd get info rate too high for non-privileged users, try again " \
1248 	"later.\n"
1249 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1250 
1251 #define	IS_VMLOANED_MBLK(mp) \
1252 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1253 
1254 
1255 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1256 boolean_t tcp_mdt_chain = B_TRUE;
1257 
1258 /*
1259  * MDT threshold in the form of effective send MSS multiplier; we take
1260  * the MDT path if the amount of unsent data exceeds the threshold value
1261  * (default threshold is 1*SMSS).
1262  */
1263 uint_t tcp_mdt_smss_threshold = 1;
1264 
1265 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1266 
1267 /*
1268  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1269  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1270  * determined dynamically during tcp_adapt_ire(), which is the default.
1271  */
1272 boolean_t tcp_static_maxpsz = B_FALSE;
1273 
1274 /* Setable in /etc/system */
1275 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1276 uint32_t tcp_random_anon_port = 1;
1277 
1278 /*
1279  * To reach to an eager in Q0 which can be dropped due to an incoming
1280  * new SYN request when Q0 is full, a new doubly linked list is
1281  * introduced. This list allows to select an eager from Q0 in O(1) time.
1282  * This is needed to avoid spending too much time walking through the
1283  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1284  * this new list has to be a member of Q0.
1285  * This list is headed by listener's tcp_t. When the list is empty,
1286  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1287  * of listener's tcp_t point to listener's tcp_t itself.
1288  *
1289  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1290  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1291  * These macros do not affect the eager's membership to Q0.
1292  */
1293 
1294 
1295 #define	MAKE_DROPPABLE(listener, eager)					\
1296 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1297 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1298 		    = (eager);						\
1299 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1300 		(eager)->tcp_eager_next_drop_q0 =			\
1301 		    (listener)->tcp_eager_next_drop_q0;			\
1302 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1303 	}
1304 
1305 #define	MAKE_UNDROPPABLE(eager)						\
1306 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1307 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1308 		    = (eager)->tcp_eager_prev_drop_q0;			\
1309 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1310 		    = (eager)->tcp_eager_next_drop_q0;			\
1311 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1312 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1313 	}
1314 
1315 /*
1316  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1317  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1318  * data, TCP will not respond with an ACK.  RFC 793 requires that
1319  * TCP responds with an ACK for such a bogus ACK.  By not following
1320  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1321  * an attacker successfully spoofs an acceptable segment to our
1322  * peer; or when our peer is "confused."
1323  */
1324 uint32_t tcp_drop_ack_unsent_cnt = 10;
1325 
1326 /*
1327  * Hook functions to enable cluster networking
1328  * On non-clustered systems these vectors must always be NULL.
1329  */
1330 
1331 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1332 			    uint8_t *laddrp, in_port_t lport) = NULL;
1333 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1334 			    uint8_t *laddrp, in_port_t lport) = NULL;
1335 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1336 			    uint8_t *laddrp, in_port_t lport,
1337 			    uint8_t *faddrp, in_port_t fport) = NULL;
1338 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1339 			    uint8_t *laddrp, in_port_t lport,
1340 			    uint8_t *faddrp, in_port_t fport) = NULL;
1341 
1342 /*
1343  * The following are defined in ip.c
1344  */
1345 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1346 				uint8_t *laddrp);
1347 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1348 				uint8_t *laddrp, uint8_t *faddrp);
1349 
1350 #define	CL_INET_CONNECT(tcp)		{			\
1351 	if (cl_inet_connect != NULL) {				\
1352 		/*						\
1353 		 * Running in cluster mode - register active connection	\
1354 		 * information						\
1355 		 */							\
1356 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1357 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1358 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1359 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1360 				    (in_port_t)(tcp)->tcp_lport,	\
1361 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1362 				    (in_port_t)(tcp)->tcp_fport);	\
1363 			}						\
1364 		} else {						\
1365 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1366 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1367 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1368 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1369 				    (in_port_t)(tcp)->tcp_lport,	\
1370 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1371 				    (in_port_t)(tcp)->tcp_fport);	\
1372 			}						\
1373 		}							\
1374 	}								\
1375 }
1376 
1377 #define	CL_INET_DISCONNECT(tcp)	{				\
1378 	if (cl_inet_disconnect != NULL) {				\
1379 		/*							\
1380 		 * Running in cluster mode - deregister active		\
1381 		 * connection information				\
1382 		 */							\
1383 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1384 			if ((tcp)->tcp_ip_src != 0) {			\
1385 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1386 				    AF_INET,				\
1387 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1388 				    (in_port_t)(tcp)->tcp_lport,	\
1389 				    (uint8_t *)				\
1390 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1391 				    (in_port_t)(tcp)->tcp_fport);	\
1392 			}						\
1393 		} else {						\
1394 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1395 			    &(tcp)->tcp_ip_src_v6)) {			\
1396 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1397 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1398 				    (in_port_t)(tcp)->tcp_lport,	\
1399 				    (uint8_t *)				\
1400 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1401 				    (in_port_t)(tcp)->tcp_fport);	\
1402 			}						\
1403 		}							\
1404 	}								\
1405 }
1406 
1407 /*
1408  * Cluster networking hook for traversing current connection list.
1409  * This routine is used to extract the current list of live connections
1410  * which must continue to to be dispatched to this node.
1411  */
1412 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1413 
1414 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1415     void *arg, tcp_stack_t *tcps);
1416 
1417 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1418 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1419 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1420 	    ip6_t *, ip6h, int, 0);
1421 
1422 /*
1423  * Figure out the value of window scale opton.  Note that the rwnd is
1424  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1425  * We cannot find the scale value and then do a round up of tcp_rwnd
1426  * because the scale value may not be correct after that.
1427  *
1428  * Set the compiler flag to make this function inline.
1429  */
1430 static void
1431 tcp_set_ws_value(tcp_t *tcp)
1432 {
1433 	int i;
1434 	uint32_t rwnd = tcp->tcp_rwnd;
1435 
1436 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1437 	    i++, rwnd >>= 1)
1438 		;
1439 	tcp->tcp_rcv_ws = i;
1440 }
1441 
1442 /*
1443  * Remove a connection from the list of detached TIME_WAIT connections.
1444  * It returns B_FALSE if it can't remove the connection from the list
1445  * as the connection has already been removed from the list due to an
1446  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1447  */
1448 static boolean_t
1449 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1450 {
1451 	boolean_t	locked = B_FALSE;
1452 
1453 	if (tcp_time_wait == NULL) {
1454 		tcp_time_wait = *((tcp_squeue_priv_t **)
1455 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1456 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1457 		locked = B_TRUE;
1458 	} else {
1459 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1460 	}
1461 
1462 	if (tcp->tcp_time_wait_expire == 0) {
1463 		ASSERT(tcp->tcp_time_wait_next == NULL);
1464 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1465 		if (locked)
1466 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1467 		return (B_FALSE);
1468 	}
1469 	ASSERT(TCP_IS_DETACHED(tcp));
1470 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1471 
1472 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1473 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1474 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1475 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1476 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1477 			    NULL;
1478 		} else {
1479 			tcp_time_wait->tcp_time_wait_tail = NULL;
1480 		}
1481 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1482 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1483 		ASSERT(tcp->tcp_time_wait_next == NULL);
1484 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1485 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1486 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1487 	} else {
1488 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1489 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1490 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1491 		    tcp->tcp_time_wait_next;
1492 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1493 		    tcp->tcp_time_wait_prev;
1494 	}
1495 	tcp->tcp_time_wait_next = NULL;
1496 	tcp->tcp_time_wait_prev = NULL;
1497 	tcp->tcp_time_wait_expire = 0;
1498 
1499 	if (locked)
1500 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1501 	return (B_TRUE);
1502 }
1503 
1504 /*
1505  * Add a connection to the list of detached TIME_WAIT connections
1506  * and set its time to expire.
1507  */
1508 static void
1509 tcp_time_wait_append(tcp_t *tcp)
1510 {
1511 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1512 	tcp_squeue_priv_t *tcp_time_wait =
1513 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1514 	    SQPRIVATE_TCP));
1515 
1516 	tcp_timers_stop(tcp);
1517 
1518 	/* Freed above */
1519 	ASSERT(tcp->tcp_timer_tid == 0);
1520 	ASSERT(tcp->tcp_ack_tid == 0);
1521 
1522 	/* must have happened at the time of detaching the tcp */
1523 	ASSERT(tcp->tcp_ptpahn == NULL);
1524 	ASSERT(tcp->tcp_flow_stopped == 0);
1525 	ASSERT(tcp->tcp_time_wait_next == NULL);
1526 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1527 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1528 	ASSERT(tcp->tcp_listener == NULL);
1529 
1530 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1531 	/*
1532 	 * The value computed below in tcp->tcp_time_wait_expire may
1533 	 * appear negative or wrap around. That is ok since our
1534 	 * interest is only in the difference between the current lbolt
1535 	 * value and tcp->tcp_time_wait_expire. But the value should not
1536 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1537 	 * The corresponding comparison in tcp_time_wait_collector() uses
1538 	 * modular arithmetic.
1539 	 */
1540 	tcp->tcp_time_wait_expire +=
1541 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1542 	if (tcp->tcp_time_wait_expire == 0)
1543 		tcp->tcp_time_wait_expire = 1;
1544 
1545 	ASSERT(TCP_IS_DETACHED(tcp));
1546 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1547 	ASSERT(tcp->tcp_time_wait_next == NULL);
1548 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1549 	TCP_DBGSTAT(tcps, tcp_time_wait);
1550 
1551 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1552 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1553 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1554 		tcp_time_wait->tcp_time_wait_head = tcp;
1555 	} else {
1556 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1557 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1558 		    TCPS_TIME_WAIT);
1559 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1560 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1561 	}
1562 	tcp_time_wait->tcp_time_wait_tail = tcp;
1563 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1564 }
1565 
1566 /* ARGSUSED */
1567 void
1568 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1569 {
1570 	conn_t	*connp = (conn_t *)arg;
1571 	tcp_t	*tcp = connp->conn_tcp;
1572 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1573 
1574 	ASSERT(tcp != NULL);
1575 	if (tcp->tcp_state == TCPS_CLOSED) {
1576 		return;
1577 	}
1578 
1579 	ASSERT((tcp->tcp_family == AF_INET &&
1580 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1581 	    (tcp->tcp_family == AF_INET6 &&
1582 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1583 	    tcp->tcp_ipversion == IPV6_VERSION)));
1584 	ASSERT(!tcp->tcp_listener);
1585 
1586 	TCP_STAT(tcps, tcp_time_wait_reap);
1587 	ASSERT(TCP_IS_DETACHED(tcp));
1588 
1589 	/*
1590 	 * Because they have no upstream client to rebind or tcp_close()
1591 	 * them later, we axe the connection here and now.
1592 	 */
1593 	tcp_close_detached(tcp);
1594 }
1595 
1596 /*
1597  * Remove cached/latched IPsec references.
1598  */
1599 void
1600 tcp_ipsec_cleanup(tcp_t *tcp)
1601 {
1602 	conn_t		*connp = tcp->tcp_connp;
1603 
1604 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1605 
1606 	if (connp->conn_latch != NULL) {
1607 		IPLATCH_REFRELE(connp->conn_latch,
1608 		    connp->conn_netstack);
1609 		connp->conn_latch = NULL;
1610 	}
1611 	if (connp->conn_policy != NULL) {
1612 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1613 		connp->conn_policy = NULL;
1614 	}
1615 }
1616 
1617 /*
1618  * Cleaup before placing on free list.
1619  * Disassociate from the netstack/tcp_stack_t since the freelist
1620  * is per squeue and not per netstack.
1621  */
1622 void
1623 tcp_cleanup(tcp_t *tcp)
1624 {
1625 	mblk_t		*mp;
1626 	char		*tcp_iphc;
1627 	int		tcp_iphc_len;
1628 	int		tcp_hdr_grown;
1629 	tcp_sack_info_t	*tcp_sack_info;
1630 	conn_t		*connp = tcp->tcp_connp;
1631 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1632 	netstack_t	*ns = tcps->tcps_netstack;
1633 	mblk_t		*tcp_rsrv_mp;
1634 
1635 	tcp_bind_hash_remove(tcp);
1636 
1637 	/* Cleanup that which needs the netstack first */
1638 	tcp_ipsec_cleanup(tcp);
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 	conn_delete_ire(connp, NULL);
1655 
1656 	/*
1657 	 * Since we will bzero the entire structure, we need to
1658 	 * remove it and reinsert it in global hash list. We
1659 	 * know the walkers can't get to this conn because we
1660 	 * had set CONDEMNED flag earlier and checked reference
1661 	 * under conn_lock so walker won't pick it and when we
1662 	 * go the ipcl_globalhash_remove() below, no walker
1663 	 * can get to it.
1664 	 */
1665 	ipcl_globalhash_remove(connp);
1666 
1667 	/*
1668 	 * Now it is safe to decrement the reference counts.
1669 	 * This might be the last reference on the netstack and TCPS
1670 	 * in which case it will cause the tcp_g_q_close and
1671 	 * the freeing of the IP Instance.
1672 	 */
1673 	connp->conn_netstack = NULL;
1674 	netstack_rele(ns);
1675 	ASSERT(tcps != NULL);
1676 	tcp->tcp_tcps = NULL;
1677 	TCPS_REFRELE(tcps);
1678 
1679 	/* Save some state */
1680 	mp = tcp->tcp_timercache;
1681 
1682 	tcp_sack_info = tcp->tcp_sack_info;
1683 	tcp_iphc = tcp->tcp_iphc;
1684 	tcp_iphc_len = tcp->tcp_iphc_len;
1685 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1686 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1687 
1688 	if (connp->conn_cred != NULL) {
1689 		crfree(connp->conn_cred);
1690 		connp->conn_cred = NULL;
1691 	}
1692 	if (connp->conn_peercred != NULL) {
1693 		crfree(connp->conn_peercred);
1694 		connp->conn_peercred = NULL;
1695 	}
1696 	ipcl_conn_cleanup(connp);
1697 	connp->conn_flags = IPCL_TCPCONN;
1698 	bzero(tcp, sizeof (tcp_t));
1699 
1700 	/* restore the state */
1701 	tcp->tcp_timercache = mp;
1702 
1703 	tcp->tcp_sack_info = tcp_sack_info;
1704 	tcp->tcp_iphc = tcp_iphc;
1705 	tcp->tcp_iphc_len = tcp_iphc_len;
1706 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1707 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1708 
1709 	tcp->tcp_connp = connp;
1710 
1711 	ASSERT(connp->conn_tcp == tcp);
1712 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1713 	connp->conn_state_flags = CONN_INCIPIENT;
1714 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1715 	ASSERT(connp->conn_ref == 1);
1716 }
1717 
1718 /*
1719  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1720  * is done forwards from the head.
1721  * This walks all stack instances since
1722  * tcp_time_wait remains global across all stacks.
1723  */
1724 /* ARGSUSED */
1725 void
1726 tcp_time_wait_collector(void *arg)
1727 {
1728 	tcp_t *tcp;
1729 	clock_t now;
1730 	mblk_t *mp;
1731 	conn_t *connp;
1732 	kmutex_t *lock;
1733 	boolean_t removed;
1734 
1735 	squeue_t *sqp = (squeue_t *)arg;
1736 	tcp_squeue_priv_t *tcp_time_wait =
1737 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1738 
1739 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1740 	tcp_time_wait->tcp_time_wait_tid = 0;
1741 
1742 	if (tcp_time_wait->tcp_free_list != NULL &&
1743 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1744 		TCP_G_STAT(tcp_freelist_cleanup);
1745 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1746 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1747 			tcp->tcp_time_wait_next = NULL;
1748 			tcp_time_wait->tcp_free_list_cnt--;
1749 			ASSERT(tcp->tcp_tcps == NULL);
1750 			CONN_DEC_REF(tcp->tcp_connp);
1751 		}
1752 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1753 	}
1754 
1755 	/*
1756 	 * In order to reap time waits reliably, we should use a
1757 	 * source of time that is not adjustable by the user -- hence
1758 	 * the call to ddi_get_lbolt().
1759 	 */
1760 	now = ddi_get_lbolt();
1761 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1762 		/*
1763 		 * Compare times using modular arithmetic, since
1764 		 * lbolt can wrapover.
1765 		 */
1766 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1767 			break;
1768 		}
1769 
1770 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1771 		ASSERT(removed);
1772 
1773 		connp = tcp->tcp_connp;
1774 		ASSERT(connp->conn_fanout != NULL);
1775 		lock = &connp->conn_fanout->connf_lock;
1776 		/*
1777 		 * This is essentially a TW reclaim fast path optimization for
1778 		 * performance where the timewait collector checks under the
1779 		 * fanout lock (so that no one else can get access to the
1780 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1781 		 * the classifier hash list. If ref count is indeed 2, we can
1782 		 * just remove the conn under the fanout lock and avoid
1783 		 * cleaning up the conn under the squeue, provided that
1784 		 * clustering callbacks are not enabled. If clustering is
1785 		 * enabled, we need to make the clustering callback before
1786 		 * setting the CONDEMNED flag and after dropping all locks and
1787 		 * so we forego this optimization and fall back to the slow
1788 		 * path. Also please see the comments in tcp_closei_local
1789 		 * regarding the refcnt logic.
1790 		 *
1791 		 * Since we are holding the tcp_time_wait_lock, its better
1792 		 * not to block on the fanout_lock because other connections
1793 		 * can't add themselves to time_wait list. So we do a
1794 		 * tryenter instead of mutex_enter.
1795 		 */
1796 		if (mutex_tryenter(lock)) {
1797 			mutex_enter(&connp->conn_lock);
1798 			if ((connp->conn_ref == 2) &&
1799 			    (cl_inet_disconnect == NULL)) {
1800 				ipcl_hash_remove_locked(connp,
1801 				    connp->conn_fanout);
1802 				/*
1803 				 * Set the CONDEMNED flag now itself so that
1804 				 * the refcnt cannot increase due to any
1805 				 * walker. But we have still not cleaned up
1806 				 * conn_ire_cache. This is still ok since
1807 				 * we are going to clean it up in tcp_cleanup
1808 				 * immediately and any interface unplumb
1809 				 * thread will wait till the ire is blown away
1810 				 */
1811 				connp->conn_state_flags |= CONN_CONDEMNED;
1812 				mutex_exit(lock);
1813 				mutex_exit(&connp->conn_lock);
1814 				if (tcp_time_wait->tcp_free_list_cnt <
1815 				    tcp_free_list_max_cnt) {
1816 					/* Add to head of tcp_free_list */
1817 					mutex_exit(
1818 					    &tcp_time_wait->tcp_time_wait_lock);
1819 					tcp_cleanup(tcp);
1820 					ASSERT(connp->conn_latch == NULL);
1821 					ASSERT(connp->conn_policy == NULL);
1822 					ASSERT(tcp->tcp_tcps == NULL);
1823 					ASSERT(connp->conn_netstack == NULL);
1824 
1825 					mutex_enter(
1826 					    &tcp_time_wait->tcp_time_wait_lock);
1827 					tcp->tcp_time_wait_next =
1828 					    tcp_time_wait->tcp_free_list;
1829 					tcp_time_wait->tcp_free_list = tcp;
1830 					tcp_time_wait->tcp_free_list_cnt++;
1831 					continue;
1832 				} else {
1833 					/* Do not add to tcp_free_list */
1834 					mutex_exit(
1835 					    &tcp_time_wait->tcp_time_wait_lock);
1836 					tcp_bind_hash_remove(tcp);
1837 					conn_delete_ire(tcp->tcp_connp, NULL);
1838 					tcp_ipsec_cleanup(tcp);
1839 					CONN_DEC_REF(tcp->tcp_connp);
1840 				}
1841 			} else {
1842 				CONN_INC_REF_LOCKED(connp);
1843 				mutex_exit(lock);
1844 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1845 				mutex_exit(&connp->conn_lock);
1846 				/*
1847 				 * We can reuse the closemp here since conn has
1848 				 * detached (otherwise we wouldn't even be in
1849 				 * time_wait list). tcp_closemp_used can safely
1850 				 * be changed without taking a lock as no other
1851 				 * thread can concurrently access it at this
1852 				 * point in the connection lifecycle.
1853 				 */
1854 
1855 				if (tcp->tcp_closemp.b_prev == NULL)
1856 					tcp->tcp_closemp_used = B_TRUE;
1857 				else
1858 					cmn_err(CE_PANIC,
1859 					    "tcp_timewait_collector: "
1860 					    "concurrent use of tcp_closemp: "
1861 					    "connp %p tcp %p\n", (void *)connp,
1862 					    (void *)tcp);
1863 
1864 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1865 				mp = &tcp->tcp_closemp;
1866 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1867 				    tcp_timewait_output, connp,
1868 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1869 			}
1870 		} else {
1871 			mutex_enter(&connp->conn_lock);
1872 			CONN_INC_REF_LOCKED(connp);
1873 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1874 			mutex_exit(&connp->conn_lock);
1875 			/*
1876 			 * We can reuse the closemp here since conn has
1877 			 * detached (otherwise we wouldn't even be in
1878 			 * time_wait list). tcp_closemp_used can safely
1879 			 * be changed without taking a lock as no other
1880 			 * thread can concurrently access it at this
1881 			 * point in the connection lifecycle.
1882 			 */
1883 
1884 			if (tcp->tcp_closemp.b_prev == NULL)
1885 				tcp->tcp_closemp_used = B_TRUE;
1886 			else
1887 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1888 				    "concurrent use of tcp_closemp: "
1889 				    "connp %p tcp %p\n", (void *)connp,
1890 				    (void *)tcp);
1891 
1892 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1893 			mp = &tcp->tcp_closemp;
1894 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1895 			    tcp_timewait_output, connp,
1896 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1897 		}
1898 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1899 	}
1900 
1901 	if (tcp_time_wait->tcp_free_list != NULL)
1902 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1903 
1904 	tcp_time_wait->tcp_time_wait_tid =
1905 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1906 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1907 	    CALLOUT_FLAG_ROUNDUP);
1908 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1909 }
1910 /*
1911  * Reply to a clients T_CONN_RES TPI message. This function
1912  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1913  * on the acceptor STREAM and processed in tcp_wput_accept().
1914  * Read the block comment on top of tcp_conn_request().
1915  */
1916 static void
1917 tcp_accept(tcp_t *listener, mblk_t *mp)
1918 {
1919 	tcp_t	*acceptor;
1920 	tcp_t	*eager;
1921 	tcp_t   *tcp;
1922 	struct T_conn_res	*tcr;
1923 	t_uscalar_t	acceptor_id;
1924 	t_scalar_t	seqnum;
1925 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1926 	mblk_t	*ok_mp;
1927 	mblk_t	*mp1;
1928 	tcp_stack_t	*tcps = listener->tcp_tcps;
1929 
1930 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1931 		tcp_err_ack(listener, mp, TPROTO, 0);
1932 		return;
1933 	}
1934 	tcr = (struct T_conn_res *)mp->b_rptr;
1935 
1936 	/*
1937 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1938 	 * read side queue of the streams device underneath us i.e. the
1939 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1940 	 * look it up in the queue_hash.  Under LP64 it sends down the
1941 	 * minor_t of the accepting endpoint.
1942 	 *
1943 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1944 	 * fanout hash lock is held.
1945 	 * This prevents any thread from entering the acceptor queue from
1946 	 * below (since it has not been hard bound yet i.e. any inbound
1947 	 * packets will arrive on the listener or default tcp queue and
1948 	 * go through tcp_lookup).
1949 	 * The CONN_INC_REF will prevent the acceptor from closing.
1950 	 *
1951 	 * XXX It is still possible for a tli application to send down data
1952 	 * on the accepting stream while another thread calls t_accept.
1953 	 * This should not be a problem for well-behaved applications since
1954 	 * the T_OK_ACK is sent after the queue swapping is completed.
1955 	 *
1956 	 * If the accepting fd is the same as the listening fd, avoid
1957 	 * queue hash lookup since that will return an eager listener in a
1958 	 * already established state.
1959 	 */
1960 	acceptor_id = tcr->ACCEPTOR_id;
1961 	mutex_enter(&listener->tcp_eager_lock);
1962 	if (listener->tcp_acceptor_id == acceptor_id) {
1963 		eager = listener->tcp_eager_next_q;
1964 		/* only count how many T_CONN_INDs so don't count q0 */
1965 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1966 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1967 			mutex_exit(&listener->tcp_eager_lock);
1968 			tcp_err_ack(listener, mp, TBADF, 0);
1969 			return;
1970 		}
1971 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1972 			/* Throw away all the eagers on q0. */
1973 			tcp_eager_cleanup(listener, 1);
1974 		}
1975 		if (listener->tcp_syn_defense) {
1976 			listener->tcp_syn_defense = B_FALSE;
1977 			if (listener->tcp_ip_addr_cache != NULL) {
1978 				kmem_free(listener->tcp_ip_addr_cache,
1979 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1980 				listener->tcp_ip_addr_cache = NULL;
1981 			}
1982 		}
1983 		/*
1984 		 * Transfer tcp_conn_req_max to the eager so that when
1985 		 * a disconnect occurs we can revert the endpoint to the
1986 		 * listen state.
1987 		 */
1988 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1989 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1990 		/*
1991 		 * Get a reference on the acceptor just like the
1992 		 * tcp_acceptor_hash_lookup below.
1993 		 */
1994 		acceptor = listener;
1995 		CONN_INC_REF(acceptor->tcp_connp);
1996 	} else {
1997 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1998 		if (acceptor == NULL) {
1999 			if (listener->tcp_debug) {
2000 				(void) strlog(TCP_MOD_ID, 0, 1,
2001 				    SL_ERROR|SL_TRACE,
2002 				    "tcp_accept: did not find acceptor 0x%x\n",
2003 				    acceptor_id);
2004 			}
2005 			mutex_exit(&listener->tcp_eager_lock);
2006 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2007 			return;
2008 		}
2009 		/*
2010 		 * Verify acceptor state. The acceptable states for an acceptor
2011 		 * include TCPS_IDLE and TCPS_BOUND.
2012 		 */
2013 		switch (acceptor->tcp_state) {
2014 		case TCPS_IDLE:
2015 			/* FALLTHRU */
2016 		case TCPS_BOUND:
2017 			break;
2018 		default:
2019 			CONN_DEC_REF(acceptor->tcp_connp);
2020 			mutex_exit(&listener->tcp_eager_lock);
2021 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2022 			return;
2023 		}
2024 	}
2025 
2026 	/* The listener must be in TCPS_LISTEN */
2027 	if (listener->tcp_state != TCPS_LISTEN) {
2028 		CONN_DEC_REF(acceptor->tcp_connp);
2029 		mutex_exit(&listener->tcp_eager_lock);
2030 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2031 		return;
2032 	}
2033 
2034 	/*
2035 	 * Rendezvous with an eager connection request packet hanging off
2036 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2037 	 * tcp structure when the connection packet arrived in
2038 	 * tcp_conn_request().
2039 	 */
2040 	seqnum = tcr->SEQ_number;
2041 	eager = listener;
2042 	do {
2043 		eager = eager->tcp_eager_next_q;
2044 		if (eager == NULL) {
2045 			CONN_DEC_REF(acceptor->tcp_connp);
2046 			mutex_exit(&listener->tcp_eager_lock);
2047 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2048 			return;
2049 		}
2050 	} while (eager->tcp_conn_req_seqnum != seqnum);
2051 	mutex_exit(&listener->tcp_eager_lock);
2052 
2053 	/*
2054 	 * At this point, both acceptor and listener have 2 ref
2055 	 * that they begin with. Acceptor has one additional ref
2056 	 * we placed in lookup while listener has 3 additional
2057 	 * ref for being behind the squeue (tcp_accept() is
2058 	 * done on listener's squeue); being in classifier hash;
2059 	 * and eager's ref on listener.
2060 	 */
2061 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2062 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2063 
2064 	/*
2065 	 * The eager at this point is set in its own squeue and
2066 	 * could easily have been killed (tcp_accept_finish will
2067 	 * deal with that) because of a TH_RST so we can only
2068 	 * ASSERT for a single ref.
2069 	 */
2070 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2071 
2072 	/* Pre allocate the stroptions mblk also */
2073 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2074 	if (opt_mp == NULL) {
2075 		CONN_DEC_REF(acceptor->tcp_connp);
2076 		CONN_DEC_REF(eager->tcp_connp);
2077 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2078 		return;
2079 	}
2080 	DB_TYPE(opt_mp) = M_SETOPTS;
2081 	opt_mp->b_wptr += sizeof (struct stroptions);
2082 
2083 	/*
2084 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2085 	 * from listener to acceptor. The message is chained on opt_mp
2086 	 * which will be sent onto eager's squeue.
2087 	 */
2088 	if (listener->tcp_bound_if != 0) {
2089 		/* allocate optmgmt req */
2090 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2091 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2092 		    sizeof (int));
2093 		if (mp1 != NULL)
2094 			linkb(opt_mp, mp1);
2095 	}
2096 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2097 		uint_t on = 1;
2098 
2099 		/* allocate optmgmt req */
2100 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2101 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2102 		if (mp1 != NULL)
2103 			linkb(opt_mp, mp1);
2104 	}
2105 
2106 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2107 	if ((mp1 = copymsg(mp)) == NULL) {
2108 		CONN_DEC_REF(acceptor->tcp_connp);
2109 		CONN_DEC_REF(eager->tcp_connp);
2110 		freemsg(opt_mp);
2111 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2112 		return;
2113 	}
2114 
2115 	tcr = (struct T_conn_res *)mp1->b_rptr;
2116 
2117 	/*
2118 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2119 	 * which allocates a larger mblk and appends the new
2120 	 * local address to the ok_ack.  The address is copied by
2121 	 * soaccept() for getsockname().
2122 	 */
2123 	{
2124 		int extra;
2125 
2126 		extra = (eager->tcp_family == AF_INET) ?
2127 		    sizeof (sin_t) : sizeof (sin6_t);
2128 
2129 		/*
2130 		 * Try to re-use mp, if possible.  Otherwise, allocate
2131 		 * an mblk and return it as ok_mp.  In any case, mp
2132 		 * is no longer usable upon return.
2133 		 */
2134 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2135 			CONN_DEC_REF(acceptor->tcp_connp);
2136 			CONN_DEC_REF(eager->tcp_connp);
2137 			freemsg(opt_mp);
2138 			/* Original mp has been freed by now, so use mp1 */
2139 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2140 			return;
2141 		}
2142 
2143 		mp = NULL;	/* We should never use mp after this point */
2144 
2145 		switch (extra) {
2146 		case sizeof (sin_t): {
2147 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2148 
2149 				ok_mp->b_wptr += extra;
2150 				sin->sin_family = AF_INET;
2151 				sin->sin_port = eager->tcp_lport;
2152 				sin->sin_addr.s_addr =
2153 				    eager->tcp_ipha->ipha_src;
2154 				break;
2155 			}
2156 		case sizeof (sin6_t): {
2157 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2158 
2159 				ok_mp->b_wptr += extra;
2160 				sin6->sin6_family = AF_INET6;
2161 				sin6->sin6_port = eager->tcp_lport;
2162 				if (eager->tcp_ipversion == IPV4_VERSION) {
2163 					sin6->sin6_flowinfo = 0;
2164 					IN6_IPADDR_TO_V4MAPPED(
2165 					    eager->tcp_ipha->ipha_src,
2166 					    &sin6->sin6_addr);
2167 				} else {
2168 					ASSERT(eager->tcp_ip6h != NULL);
2169 					sin6->sin6_flowinfo =
2170 					    eager->tcp_ip6h->ip6_vcf &
2171 					    ~IPV6_VERS_AND_FLOW_MASK;
2172 					sin6->sin6_addr =
2173 					    eager->tcp_ip6h->ip6_src;
2174 				}
2175 				sin6->sin6_scope_id = 0;
2176 				sin6->__sin6_src_id = 0;
2177 				break;
2178 			}
2179 		default:
2180 			break;
2181 		}
2182 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2183 	}
2184 
2185 	/*
2186 	 * If there are no options we know that the T_CONN_RES will
2187 	 * succeed. However, we can't send the T_OK_ACK upstream until
2188 	 * the tcp_accept_swap is done since it would be dangerous to
2189 	 * let the application start using the new fd prior to the swap.
2190 	 */
2191 	tcp_accept_swap(listener, acceptor, eager);
2192 
2193 	/*
2194 	 * tcp_accept_swap unlinks eager from listener but does not drop
2195 	 * the eager's reference on the listener.
2196 	 */
2197 	ASSERT(eager->tcp_listener == NULL);
2198 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2199 
2200 	/*
2201 	 * The eager is now associated with its own queue. Insert in
2202 	 * the hash so that the connection can be reused for a future
2203 	 * T_CONN_RES.
2204 	 */
2205 	tcp_acceptor_hash_insert(acceptor_id, eager);
2206 
2207 	/*
2208 	 * We now do the processing of options with T_CONN_RES.
2209 	 * We delay till now since we wanted to have queue to pass to
2210 	 * option processing routines that points back to the right
2211 	 * instance structure which does not happen until after
2212 	 * tcp_accept_swap().
2213 	 *
2214 	 * Note:
2215 	 * The sanity of the logic here assumes that whatever options
2216 	 * are appropriate to inherit from listner=>eager are done
2217 	 * before this point, and whatever were to be overridden (or not)
2218 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2219 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2220 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2221 	 * This may not be true at this point in time but can be fixed
2222 	 * independently. This option processing code starts with
2223 	 * the instantiated acceptor instance and the final queue at
2224 	 * this point.
2225 	 */
2226 
2227 	if (tcr->OPT_length != 0) {
2228 		/* Options to process */
2229 		int t_error = 0;
2230 		int sys_error = 0;
2231 		int do_disconnect = 0;
2232 
2233 		if (tcp_conprim_opt_process(eager, mp1,
2234 		    &do_disconnect, &t_error, &sys_error) < 0) {
2235 			eager->tcp_accept_error = 1;
2236 			if (do_disconnect) {
2237 				/*
2238 				 * An option failed which does not allow
2239 				 * connection to be accepted.
2240 				 *
2241 				 * We allow T_CONN_RES to succeed and
2242 				 * put a T_DISCON_IND on the eager queue.
2243 				 */
2244 				ASSERT(t_error == 0 && sys_error == 0);
2245 				eager->tcp_send_discon_ind = 1;
2246 			} else {
2247 				ASSERT(t_error != 0);
2248 				freemsg(ok_mp);
2249 				/*
2250 				 * Original mp was either freed or set
2251 				 * to ok_mp above, so use mp1 instead.
2252 				 */
2253 				tcp_err_ack(listener, mp1, t_error, sys_error);
2254 				goto finish;
2255 			}
2256 		}
2257 		/*
2258 		 * Most likely success in setting options (except if
2259 		 * eager->tcp_send_discon_ind set).
2260 		 * mp1 option buffer represented by OPT_length/offset
2261 		 * potentially modified and contains results of setting
2262 		 * options at this point
2263 		 */
2264 	}
2265 
2266 	/* We no longer need mp1, since all options processing has passed */
2267 	freemsg(mp1);
2268 
2269 	putnext(listener->tcp_rq, ok_mp);
2270 
2271 	mutex_enter(&listener->tcp_eager_lock);
2272 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2273 		tcp_t	*tail;
2274 		mblk_t	*conn_ind;
2275 
2276 		/*
2277 		 * This path should not be executed if listener and
2278 		 * acceptor streams are the same.
2279 		 */
2280 		ASSERT(listener != acceptor);
2281 
2282 		tcp = listener->tcp_eager_prev_q0;
2283 		/*
2284 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2285 		 * deferred T_conn_ind queue. We need to get to the head of
2286 		 * the queue in order to send up T_conn_ind the same order as
2287 		 * how the 3WHS is completed.
2288 		 */
2289 		while (tcp != listener) {
2290 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2291 				break;
2292 			else
2293 				tcp = tcp->tcp_eager_prev_q0;
2294 		}
2295 		ASSERT(tcp != listener);
2296 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2297 		ASSERT(conn_ind != NULL);
2298 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2299 
2300 		/* Move from q0 to q */
2301 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2302 		listener->tcp_conn_req_cnt_q0--;
2303 		listener->tcp_conn_req_cnt_q++;
2304 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2305 		    tcp->tcp_eager_prev_q0;
2306 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2307 		    tcp->tcp_eager_next_q0;
2308 		tcp->tcp_eager_prev_q0 = NULL;
2309 		tcp->tcp_eager_next_q0 = NULL;
2310 		tcp->tcp_conn_def_q0 = B_FALSE;
2311 
2312 		/* Make sure the tcp isn't in the list of droppables */
2313 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2314 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2315 
2316 		/*
2317 		 * Insert at end of the queue because sockfs sends
2318 		 * down T_CONN_RES in chronological order. Leaving
2319 		 * the older conn indications at front of the queue
2320 		 * helps reducing search time.
2321 		 */
2322 		tail = listener->tcp_eager_last_q;
2323 		if (tail != NULL)
2324 			tail->tcp_eager_next_q = tcp;
2325 		else
2326 			listener->tcp_eager_next_q = tcp;
2327 		listener->tcp_eager_last_q = tcp;
2328 		tcp->tcp_eager_next_q = NULL;
2329 		mutex_exit(&listener->tcp_eager_lock);
2330 		putnext(tcp->tcp_rq, conn_ind);
2331 	} else {
2332 		mutex_exit(&listener->tcp_eager_lock);
2333 	}
2334 
2335 	/*
2336 	 * Done with the acceptor - free it
2337 	 *
2338 	 * Note: from this point on, no access to listener should be made
2339 	 * as listener can be equal to acceptor.
2340 	 */
2341 finish:
2342 	ASSERT(acceptor->tcp_detached);
2343 	ASSERT(tcps->tcps_g_q != NULL);
2344 	acceptor->tcp_rq = tcps->tcps_g_q;
2345 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2346 	(void) tcp_clean_death(acceptor, 0, 2);
2347 	CONN_DEC_REF(acceptor->tcp_connp);
2348 
2349 	/*
2350 	 * In case we already received a FIN we have to make tcp_rput send
2351 	 * the ordrel_ind. This will also send up a window update if the window
2352 	 * has opened up.
2353 	 *
2354 	 * In the normal case of a successful connection acceptance
2355 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2356 	 * indication that this was just accepted. This tells tcp_rput to
2357 	 * pass up any data queued in tcp_rcv_list.
2358 	 *
2359 	 * In the fringe case where options sent with T_CONN_RES failed and
2360 	 * we required, we would be indicating a T_DISCON_IND to blow
2361 	 * away this connection.
2362 	 */
2363 
2364 	/*
2365 	 * XXX: we currently have a problem if XTI application closes the
2366 	 * acceptor stream in between. This problem exists in on10-gate also
2367 	 * and is well know but nothing can be done short of major rewrite
2368 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2369 	 * eager same squeue as listener (we can distinguish non socket
2370 	 * listeners at the time of handling a SYN in tcp_conn_request)
2371 	 * and do most of the work that tcp_accept_finish does here itself
2372 	 * and then get behind the acceptor squeue to access the acceptor
2373 	 * queue.
2374 	 */
2375 	/*
2376 	 * We already have a ref on tcp so no need to do one before squeue_enter
2377 	 */
2378 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2379 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2380 }
2381 
2382 /*
2383  * Swap information between the eager and acceptor for a TLI/XTI client.
2384  * The sockfs accept is done on the acceptor stream and control goes
2385  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2386  * called. In either case, both the eager and listener are in their own
2387  * perimeter (squeue) and the code has to deal with potential race.
2388  *
2389  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2390  */
2391 static void
2392 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2393 {
2394 	conn_t	*econnp, *aconnp;
2395 
2396 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2397 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2398 	ASSERT(!eager->tcp_hard_bound);
2399 	ASSERT(!TCP_IS_SOCKET(acceptor));
2400 	ASSERT(!TCP_IS_SOCKET(eager));
2401 	ASSERT(!TCP_IS_SOCKET(listener));
2402 
2403 	acceptor->tcp_detached = B_TRUE;
2404 	/*
2405 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2406 	 * the acceptor id.
2407 	 */
2408 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2409 
2410 	/* remove eager from listen list... */
2411 	mutex_enter(&listener->tcp_eager_lock);
2412 	tcp_eager_unlink(eager);
2413 	ASSERT(eager->tcp_eager_next_q == NULL &&
2414 	    eager->tcp_eager_last_q == NULL);
2415 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2416 	    eager->tcp_eager_prev_q0 == NULL);
2417 	mutex_exit(&listener->tcp_eager_lock);
2418 	eager->tcp_rq = acceptor->tcp_rq;
2419 	eager->tcp_wq = acceptor->tcp_wq;
2420 
2421 	econnp = eager->tcp_connp;
2422 	aconnp = acceptor->tcp_connp;
2423 
2424 	eager->tcp_rq->q_ptr = econnp;
2425 	eager->tcp_wq->q_ptr = econnp;
2426 
2427 	/*
2428 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2429 	 * which might be a different squeue from our peer TCP instance.
2430 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2431 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2432 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2433 	 * above reach global visibility prior to the clearing of tcp_detached.
2434 	 */
2435 	membar_producer();
2436 	eager->tcp_detached = B_FALSE;
2437 
2438 	ASSERT(eager->tcp_ack_tid == 0);
2439 
2440 	econnp->conn_dev = aconnp->conn_dev;
2441 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2442 	ASSERT(econnp->conn_minor_arena != NULL);
2443 	if (eager->tcp_cred != NULL)
2444 		crfree(eager->tcp_cred);
2445 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2446 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2447 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2448 
2449 	aconnp->conn_cred = NULL;
2450 
2451 	econnp->conn_zoneid = aconnp->conn_zoneid;
2452 	econnp->conn_allzones = aconnp->conn_allzones;
2453 
2454 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2455 	aconnp->conn_mac_exempt = B_FALSE;
2456 
2457 	ASSERT(aconnp->conn_peercred == NULL);
2458 
2459 	/* Do the IPC initialization */
2460 	CONN_INC_REF(econnp);
2461 
2462 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2463 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2464 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2465 
2466 	/* Done with old IPC. Drop its ref on its connp */
2467 	CONN_DEC_REF(aconnp);
2468 }
2469 
2470 
2471 /*
2472  * Adapt to the information, such as rtt and rtt_sd, provided from the
2473  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2474  *
2475  * Checks for multicast and broadcast destination address.
2476  * Returns zero on failure; non-zero if ok.
2477  *
2478  * Note that the MSS calculation here is based on the info given in
2479  * the IRE.  We do not do any calculation based on TCP options.  They
2480  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2481  * knows which options to use.
2482  *
2483  * Note on how TCP gets its parameters for a connection.
2484  *
2485  * When a tcp_t structure is allocated, it gets all the default parameters.
2486  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2487  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2488  * default.
2489  *
2490  * An incoming SYN with a multicast or broadcast destination address, is dropped
2491  * in 1 of 2 places.
2492  *
2493  * 1. If the packet was received over the wire it is dropped in
2494  * ip_rput_process_broadcast()
2495  *
2496  * 2. If the packet was received through internal IP loopback, i.e. the packet
2497  * was generated and received on the same machine, it is dropped in
2498  * ip_wput_local()
2499  *
2500  * An incoming SYN with a multicast or broadcast source address is always
2501  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2502  * reject an attempt to connect to a broadcast or multicast (destination)
2503  * address.
2504  */
2505 static int
2506 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2507 {
2508 	tcp_hsp_t	*hsp;
2509 	ire_t		*ire;
2510 	ire_t		*sire = NULL;
2511 	iulp_t		*ire_uinfo = NULL;
2512 	uint32_t	mss_max;
2513 	uint32_t	mss;
2514 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2515 	conn_t		*connp = tcp->tcp_connp;
2516 	boolean_t	ire_cacheable = B_FALSE;
2517 	zoneid_t	zoneid = connp->conn_zoneid;
2518 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2519 	    MATCH_IRE_SECATTR;
2520 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2521 	ill_t		*ill = NULL;
2522 	boolean_t	incoming = (ire_mp == NULL);
2523 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2524 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2525 
2526 	ASSERT(connp->conn_ire_cache == NULL);
2527 
2528 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2529 
2530 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2531 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2532 			return (0);
2533 		}
2534 		/*
2535 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2536 		 * for the destination with the nexthop as gateway.
2537 		 * ire_ctable_lookup() is used because this particular
2538 		 * ire, if it exists, will be marked private.
2539 		 * If that is not available, use the interface ire
2540 		 * for the nexthop.
2541 		 *
2542 		 * TSol: tcp_update_label will detect label mismatches based
2543 		 * only on the destination's label, but that would not
2544 		 * detect label mismatches based on the security attributes
2545 		 * of routes or next hop gateway. Hence we need to pass the
2546 		 * label to ire_ftable_lookup below in order to locate the
2547 		 * right prefix (and/or) ire cache. Similarly we also need
2548 		 * pass the label to the ire_cache_lookup below to locate
2549 		 * the right ire that also matches on the label.
2550 		 */
2551 		if (tcp->tcp_connp->conn_nexthop_set) {
2552 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2553 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2554 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2555 			    ipst);
2556 			if (ire == NULL) {
2557 				ire = ire_ftable_lookup(
2558 				    tcp->tcp_connp->conn_nexthop_v4,
2559 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2560 				    tsl, match_flags, ipst);
2561 				if (ire == NULL)
2562 					return (0);
2563 			} else {
2564 				ire_uinfo = &ire->ire_uinfo;
2565 			}
2566 		} else {
2567 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2568 			    zoneid, tsl, ipst);
2569 			if (ire != NULL) {
2570 				ire_cacheable = B_TRUE;
2571 				ire_uinfo = (ire_mp != NULL) ?
2572 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2573 				    &ire->ire_uinfo;
2574 
2575 			} else {
2576 				if (ire_mp == NULL) {
2577 					ire = ire_ftable_lookup(
2578 					    tcp->tcp_connp->conn_rem,
2579 					    0, 0, 0, NULL, &sire, zoneid, 0,
2580 					    tsl, (MATCH_IRE_RECURSIVE |
2581 					    MATCH_IRE_DEFAULT), ipst);
2582 					if (ire == NULL)
2583 						return (0);
2584 					ire_uinfo = (sire != NULL) ?
2585 					    &sire->ire_uinfo :
2586 					    &ire->ire_uinfo;
2587 				} else {
2588 					ire = (ire_t *)ire_mp->b_rptr;
2589 					ire_uinfo =
2590 					    &((ire_t *)
2591 					    ire_mp->b_rptr)->ire_uinfo;
2592 				}
2593 			}
2594 		}
2595 		ASSERT(ire != NULL);
2596 
2597 		if ((ire->ire_src_addr == INADDR_ANY) ||
2598 		    (ire->ire_type & IRE_BROADCAST)) {
2599 			/*
2600 			 * ire->ire_mp is non null when ire_mp passed in is used
2601 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2602 			 */
2603 			if (ire->ire_mp == NULL)
2604 				ire_refrele(ire);
2605 			if (sire != NULL)
2606 				ire_refrele(sire);
2607 			return (0);
2608 		}
2609 
2610 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2611 			ipaddr_t src_addr;
2612 
2613 			/*
2614 			 * ip_bind_connected() has stored the correct source
2615 			 * address in conn_src.
2616 			 */
2617 			src_addr = tcp->tcp_connp->conn_src;
2618 			tcp->tcp_ipha->ipha_src = src_addr;
2619 			/*
2620 			 * Copy of the src addr. in tcp_t is needed
2621 			 * for the lookup funcs.
2622 			 */
2623 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2624 		}
2625 		/*
2626 		 * Set the fragment bit so that IP will tell us if the MTU
2627 		 * should change. IP tells us the latest setting of
2628 		 * ip_path_mtu_discovery through ire_frag_flag.
2629 		 */
2630 		if (ipst->ips_ip_path_mtu_discovery) {
2631 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2632 			    htons(IPH_DF);
2633 		}
2634 		/*
2635 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2636 		 * for IP_NEXTHOP. No cache ire has been found for the
2637 		 * destination and we are working with the nexthop's
2638 		 * interface ire. Since we need to forward all packets
2639 		 * to the nexthop first, we "blindly" set tcp_localnet
2640 		 * to false, eventhough the destination may also be
2641 		 * onlink.
2642 		 */
2643 		if (ire_uinfo == NULL)
2644 			tcp->tcp_localnet = 0;
2645 		else
2646 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2647 	} else {
2648 		/*
2649 		 * For incoming connection ire_mp = NULL
2650 		 * For outgoing connection ire_mp != NULL
2651 		 * Technically we should check conn_incoming_ill
2652 		 * when ire_mp is NULL and conn_outgoing_ill when
2653 		 * ire_mp is non-NULL. But this is performance
2654 		 * critical path and for IPV*_BOUND_IF, outgoing
2655 		 * and incoming ill are always set to the same value.
2656 		 */
2657 		ill_t	*dst_ill = NULL;
2658 		ipif_t  *dst_ipif = NULL;
2659 
2660 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2661 
2662 		if (connp->conn_outgoing_ill != NULL) {
2663 			/* Outgoing or incoming path */
2664 			int   err;
2665 
2666 			dst_ill = conn_get_held_ill(connp,
2667 			    &connp->conn_outgoing_ill, &err);
2668 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2669 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2670 				return (0);
2671 			}
2672 			match_flags |= MATCH_IRE_ILL;
2673 			dst_ipif = dst_ill->ill_ipif;
2674 		}
2675 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2676 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2677 
2678 		if (ire != NULL) {
2679 			ire_cacheable = B_TRUE;
2680 			ire_uinfo = (ire_mp != NULL) ?
2681 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2682 			    &ire->ire_uinfo;
2683 		} else {
2684 			if (ire_mp == NULL) {
2685 				ire = ire_ftable_lookup_v6(
2686 				    &tcp->tcp_connp->conn_remv6,
2687 				    0, 0, 0, dst_ipif, &sire, zoneid,
2688 				    0, tsl, match_flags, ipst);
2689 				if (ire == NULL) {
2690 					if (dst_ill != NULL)
2691 						ill_refrele(dst_ill);
2692 					return (0);
2693 				}
2694 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2695 				    &ire->ire_uinfo;
2696 			} else {
2697 				ire = (ire_t *)ire_mp->b_rptr;
2698 				ire_uinfo =
2699 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2700 			}
2701 		}
2702 		if (dst_ill != NULL)
2703 			ill_refrele(dst_ill);
2704 
2705 		ASSERT(ire != NULL);
2706 		ASSERT(ire_uinfo != NULL);
2707 
2708 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2709 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2710 			/*
2711 			 * ire->ire_mp is non null when ire_mp passed in is used
2712 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2713 			 */
2714 			if (ire->ire_mp == NULL)
2715 				ire_refrele(ire);
2716 			if (sire != NULL)
2717 				ire_refrele(sire);
2718 			return (0);
2719 		}
2720 
2721 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2722 			in6_addr_t	src_addr;
2723 
2724 			/*
2725 			 * ip_bind_connected_v6() has stored the correct source
2726 			 * address per IPv6 addr. selection policy in
2727 			 * conn_src_v6.
2728 			 */
2729 			src_addr = tcp->tcp_connp->conn_srcv6;
2730 
2731 			tcp->tcp_ip6h->ip6_src = src_addr;
2732 			/*
2733 			 * Copy of the src addr. in tcp_t is needed
2734 			 * for the lookup funcs.
2735 			 */
2736 			tcp->tcp_ip_src_v6 = src_addr;
2737 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2738 			    &connp->conn_srcv6));
2739 		}
2740 		tcp->tcp_localnet =
2741 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2742 	}
2743 
2744 	/*
2745 	 * This allows applications to fail quickly when connections are made
2746 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2747 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2748 	 */
2749 	if ((ire->ire_flags & RTF_REJECT) &&
2750 	    (ire->ire_flags & RTF_PRIVATE))
2751 		goto error;
2752 
2753 	/*
2754 	 * Make use of the cached rtt and rtt_sd values to calculate the
2755 	 * initial RTO.  Note that they are already initialized in
2756 	 * tcp_init_values().
2757 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2758 	 * IP_NEXTHOP, but instead are using the interface ire for the
2759 	 * nexthop, then we do not use the ire_uinfo from that ire to
2760 	 * do any initializations.
2761 	 */
2762 	if (ire_uinfo != NULL) {
2763 		if (ire_uinfo->iulp_rtt != 0) {
2764 			clock_t	rto;
2765 
2766 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2767 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2768 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2769 			    tcps->tcps_rexmit_interval_extra +
2770 			    (tcp->tcp_rtt_sa >> 5);
2771 
2772 			if (rto > tcps->tcps_rexmit_interval_max) {
2773 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2774 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2775 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2776 			} else {
2777 				tcp->tcp_rto = rto;
2778 			}
2779 		}
2780 		if (ire_uinfo->iulp_ssthresh != 0)
2781 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2782 		else
2783 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2784 		if (ire_uinfo->iulp_spipe > 0) {
2785 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2786 			    tcps->tcps_max_buf);
2787 			if (tcps->tcps_snd_lowat_fraction != 0)
2788 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2789 				    tcps->tcps_snd_lowat_fraction;
2790 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2791 		}
2792 		/*
2793 		 * Note that up till now, acceptor always inherits receive
2794 		 * window from the listener.  But if there is a metrics
2795 		 * associated with a host, we should use that instead of
2796 		 * inheriting it from listener. Thus we need to pass this
2797 		 * info back to the caller.
2798 		 */
2799 		if (ire_uinfo->iulp_rpipe > 0) {
2800 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2801 			    tcps->tcps_max_buf);
2802 		}
2803 
2804 		if (ire_uinfo->iulp_rtomax > 0) {
2805 			tcp->tcp_second_timer_threshold =
2806 			    ire_uinfo->iulp_rtomax;
2807 		}
2808 
2809 		/*
2810 		 * Use the metric option settings, iulp_tstamp_ok and
2811 		 * iulp_wscale_ok, only for active open. What this means
2812 		 * is that if the other side uses timestamp or window
2813 		 * scale option, TCP will also use those options. That
2814 		 * is for passive open.  If the application sets a
2815 		 * large window, window scale is enabled regardless of
2816 		 * the value in iulp_wscale_ok.  This is the behavior
2817 		 * since 2.6.  So we keep it.
2818 		 * The only case left in passive open processing is the
2819 		 * check for SACK.
2820 		 * For ECN, it should probably be like SACK.  But the
2821 		 * current value is binary, so we treat it like the other
2822 		 * cases.  The metric only controls active open.For passive
2823 		 * open, the ndd param, tcp_ecn_permitted, controls the
2824 		 * behavior.
2825 		 */
2826 		if (!tcp_detached) {
2827 			/*
2828 			 * The if check means that the following can only
2829 			 * be turned on by the metrics only IRE, but not off.
2830 			 */
2831 			if (ire_uinfo->iulp_tstamp_ok)
2832 				tcp->tcp_snd_ts_ok = B_TRUE;
2833 			if (ire_uinfo->iulp_wscale_ok)
2834 				tcp->tcp_snd_ws_ok = B_TRUE;
2835 			if (ire_uinfo->iulp_sack == 2)
2836 				tcp->tcp_snd_sack_ok = B_TRUE;
2837 			if (ire_uinfo->iulp_ecn_ok)
2838 				tcp->tcp_ecn_ok = B_TRUE;
2839 		} else {
2840 			/*
2841 			 * Passive open.
2842 			 *
2843 			 * As above, the if check means that SACK can only be
2844 			 * turned on by the metric only IRE.
2845 			 */
2846 			if (ire_uinfo->iulp_sack > 0) {
2847 				tcp->tcp_snd_sack_ok = B_TRUE;
2848 			}
2849 		}
2850 	}
2851 
2852 
2853 	/*
2854 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2855 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2856 	 * length of all those options exceeds 28 bytes.  But because
2857 	 * of the tcp_mss_min check below, we may not have a problem if
2858 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2859 	 * the negative problem still exists.  And the check defeats PMTUd.
2860 	 * In fact, if PMTUd finds that the MSS should be smaller than
2861 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2862 	 * value.
2863 	 *
2864 	 * We do not deal with that now.  All those problems related to
2865 	 * PMTUd will be fixed later.
2866 	 */
2867 	ASSERT(ire->ire_max_frag != 0);
2868 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2869 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2870 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2871 			mss = MIN(mss, IPV6_MIN_MTU);
2872 		}
2873 	}
2874 
2875 	/* Sanity check for MSS value. */
2876 	if (tcp->tcp_ipversion == IPV4_VERSION)
2877 		mss_max = tcps->tcps_mss_max_ipv4;
2878 	else
2879 		mss_max = tcps->tcps_mss_max_ipv6;
2880 
2881 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2882 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2883 		/*
2884 		 * After receiving an ICMPv6 "packet too big" message with a
2885 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2886 		 * will insert a 8-byte fragment header in every packet; we
2887 		 * reduce the MSS by that amount here.
2888 		 */
2889 		mss -= sizeof (ip6_frag_t);
2890 	}
2891 
2892 	if (tcp->tcp_ipsec_overhead == 0)
2893 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2894 
2895 	mss -= tcp->tcp_ipsec_overhead;
2896 
2897 	if (mss < tcps->tcps_mss_min)
2898 		mss = tcps->tcps_mss_min;
2899 	if (mss > mss_max)
2900 		mss = mss_max;
2901 
2902 	/* Note that this is the maximum MSS, excluding all options. */
2903 	tcp->tcp_mss = mss;
2904 
2905 	/*
2906 	 * Initialize the ISS here now that we have the full connection ID.
2907 	 * The RFC 1948 method of initial sequence number generation requires
2908 	 * knowledge of the full connection ID before setting the ISS.
2909 	 */
2910 
2911 	tcp_iss_init(tcp);
2912 
2913 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2914 		tcp->tcp_loopback = B_TRUE;
2915 
2916 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2917 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2918 	} else {
2919 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2920 	}
2921 
2922 	if (hsp != NULL) {
2923 		/* Only modify if we're going to make them bigger */
2924 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2925 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2926 			if (tcps->tcps_snd_lowat_fraction != 0)
2927 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2928 				    tcps->tcps_snd_lowat_fraction;
2929 		}
2930 
2931 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2932 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2933 		}
2934 
2935 		/* Copy timestamp flag only for active open */
2936 		if (!tcp_detached)
2937 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2938 	}
2939 
2940 	if (sire != NULL)
2941 		IRE_REFRELE(sire);
2942 
2943 	/*
2944 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2945 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2946 	 */
2947 	if (tcp->tcp_loopback ||
2948 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2949 		/*
2950 		 * For incoming, see if this tcp may be MDT-capable.  For
2951 		 * outgoing, this process has been taken care of through
2952 		 * tcp_rput_other.
2953 		 */
2954 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2955 		tcp->tcp_ire_ill_check_done = B_TRUE;
2956 	}
2957 
2958 	mutex_enter(&connp->conn_lock);
2959 	/*
2960 	 * Make sure that conn is not marked incipient
2961 	 * for incoming connections. A blind
2962 	 * removal of incipient flag is cheaper than
2963 	 * check and removal.
2964 	 */
2965 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2966 
2967 	/*
2968 	 * Must not cache forwarding table routes
2969 	 * or recache an IRE after the conn_t has
2970 	 * had conn_ire_cache cleared and is flagged
2971 	 * unusable, (see the CONN_CACHE_IRE() macro).
2972 	 */
2973 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2974 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2975 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2976 			connp->conn_ire_cache = ire;
2977 			IRE_UNTRACE_REF(ire);
2978 			rw_exit(&ire->ire_bucket->irb_lock);
2979 			mutex_exit(&connp->conn_lock);
2980 			return (1);
2981 		}
2982 		rw_exit(&ire->ire_bucket->irb_lock);
2983 	}
2984 	mutex_exit(&connp->conn_lock);
2985 
2986 	if (ire->ire_mp == NULL)
2987 		ire_refrele(ire);
2988 	return (1);
2989 
2990 error:
2991 	if (ire->ire_mp == NULL)
2992 		ire_refrele(ire);
2993 	if (sire != NULL)
2994 		ire_refrele(sire);
2995 	return (0);
2996 }
2997 
2998 /*
2999  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
3000  * O_T_BIND_REQ/T_BIND_REQ message.
3001  */
3002 static void
3003 tcp_bind(tcp_t *tcp, mblk_t *mp)
3004 {
3005 	sin_t	*sin;
3006 	sin6_t	*sin6;
3007 	mblk_t	*mp1;
3008 	in_port_t requested_port;
3009 	in_port_t allocated_port;
3010 	struct T_bind_req *tbr;
3011 	boolean_t	bind_to_req_port_only;
3012 	boolean_t	backlog_update = B_FALSE;
3013 	boolean_t	user_specified;
3014 	in6_addr_t	v6addr;
3015 	ipaddr_t	v4addr;
3016 	uint_t	origipversion;
3017 	int	err;
3018 	queue_t *q = tcp->tcp_wq;
3019 	conn_t	*connp = tcp->tcp_connp;
3020 	mlp_type_t addrtype, mlptype;
3021 	zone_t	*zone;
3022 	cred_t	*cr;
3023 	in_port_t mlp_port;
3024 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3025 
3026 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3027 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3028 		if (tcp->tcp_debug) {
3029 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3030 			    "tcp_bind: bad req, len %u",
3031 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3032 		}
3033 		tcp_err_ack(tcp, mp, TPROTO, 0);
3034 		return;
3035 	}
3036 	/* Make sure the largest address fits */
3037 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3038 	if (mp1 == NULL) {
3039 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3040 		return;
3041 	}
3042 	mp = mp1;
3043 	tbr = (struct T_bind_req *)mp->b_rptr;
3044 	if (tcp->tcp_state >= TCPS_BOUND) {
3045 		if ((tcp->tcp_state == TCPS_BOUND ||
3046 		    tcp->tcp_state == TCPS_LISTEN) &&
3047 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3048 		    tbr->CONIND_number > 0) {
3049 			/*
3050 			 * Handle listen() increasing CONIND_number.
3051 			 * This is more "liberal" then what the TPI spec
3052 			 * requires but is needed to avoid a t_unbind
3053 			 * when handling listen() since the port number
3054 			 * might be "stolen" between the unbind and bind.
3055 			 */
3056 			backlog_update = B_TRUE;
3057 			goto do_bind;
3058 		}
3059 		if (tcp->tcp_debug) {
3060 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3061 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3062 		}
3063 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3064 		return;
3065 	}
3066 	origipversion = tcp->tcp_ipversion;
3067 
3068 	switch (tbr->ADDR_length) {
3069 	case 0:			/* request for a generic port */
3070 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3071 		if (tcp->tcp_family == AF_INET) {
3072 			tbr->ADDR_length = sizeof (sin_t);
3073 			sin = (sin_t *)&tbr[1];
3074 			*sin = sin_null;
3075 			sin->sin_family = AF_INET;
3076 			mp->b_wptr = (uchar_t *)&sin[1];
3077 			tcp->tcp_ipversion = IPV4_VERSION;
3078 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3079 		} else {
3080 			ASSERT(tcp->tcp_family == AF_INET6);
3081 			tbr->ADDR_length = sizeof (sin6_t);
3082 			sin6 = (sin6_t *)&tbr[1];
3083 			*sin6 = sin6_null;
3084 			sin6->sin6_family = AF_INET6;
3085 			mp->b_wptr = (uchar_t *)&sin6[1];
3086 			tcp->tcp_ipversion = IPV6_VERSION;
3087 			V6_SET_ZERO(v6addr);
3088 		}
3089 		requested_port = 0;
3090 		break;
3091 
3092 	case sizeof (sin_t):	/* Complete IPv4 address */
3093 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3094 		    sizeof (sin_t));
3095 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3096 			if (tcp->tcp_debug) {
3097 				(void) strlog(TCP_MOD_ID, 0, 1,
3098 				    SL_ERROR|SL_TRACE,
3099 				    "tcp_bind: bad address parameter, "
3100 				    "offset %d, len %d",
3101 				    tbr->ADDR_offset, tbr->ADDR_length);
3102 			}
3103 			tcp_err_ack(tcp, mp, TPROTO, 0);
3104 			return;
3105 		}
3106 		/*
3107 		 * With sockets sockfs will accept bogus sin_family in
3108 		 * bind() and replace it with the family used in the socket
3109 		 * call.
3110 		 */
3111 		if (sin->sin_family != AF_INET ||
3112 		    tcp->tcp_family != AF_INET) {
3113 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3114 			return;
3115 		}
3116 		requested_port = ntohs(sin->sin_port);
3117 		tcp->tcp_ipversion = IPV4_VERSION;
3118 		v4addr = sin->sin_addr.s_addr;
3119 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3120 		break;
3121 
3122 	case sizeof (sin6_t): /* Complete IPv6 address */
3123 		sin6 = (sin6_t *)mi_offset_param(mp,
3124 		    tbr->ADDR_offset, sizeof (sin6_t));
3125 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3126 			if (tcp->tcp_debug) {
3127 				(void) strlog(TCP_MOD_ID, 0, 1,
3128 				    SL_ERROR|SL_TRACE,
3129 				    "tcp_bind: bad IPv6 address parameter, "
3130 				    "offset %d, len %d", tbr->ADDR_offset,
3131 				    tbr->ADDR_length);
3132 			}
3133 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3134 			return;
3135 		}
3136 		if (sin6->sin6_family != AF_INET6 ||
3137 		    tcp->tcp_family != AF_INET6) {
3138 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3139 			return;
3140 		}
3141 		requested_port = ntohs(sin6->sin6_port);
3142 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3143 		    IPV4_VERSION : IPV6_VERSION;
3144 		v6addr = sin6->sin6_addr;
3145 		break;
3146 
3147 	default:
3148 		if (tcp->tcp_debug) {
3149 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3150 			    "tcp_bind: bad address length, %d",
3151 			    tbr->ADDR_length);
3152 		}
3153 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3154 		return;
3155 	}
3156 	tcp->tcp_bound_source_v6 = v6addr;
3157 
3158 	/* Check for change in ipversion */
3159 	if (origipversion != tcp->tcp_ipversion) {
3160 		ASSERT(tcp->tcp_family == AF_INET6);
3161 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3162 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3163 		if (err) {
3164 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3165 			return;
3166 		}
3167 	}
3168 
3169 	/*
3170 	 * Initialize family specific fields. Copy of the src addr.
3171 	 * in tcp_t is needed for the lookup funcs.
3172 	 */
3173 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3174 		tcp->tcp_ip6h->ip6_src = v6addr;
3175 	} else {
3176 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3177 	}
3178 	tcp->tcp_ip_src_v6 = v6addr;
3179 
3180 	/*
3181 	 * For O_T_BIND_REQ:
3182 	 * Verify that the target port/addr is available, or choose
3183 	 * another.
3184 	 * For  T_BIND_REQ:
3185 	 * Verify that the target port/addr is available or fail.
3186 	 * In both cases when it succeeds the tcp is inserted in the
3187 	 * bind hash table. This ensures that the operation is atomic
3188 	 * under the lock on the hash bucket.
3189 	 */
3190 	bind_to_req_port_only = requested_port != 0 &&
3191 	    tbr->PRIM_type != O_T_BIND_REQ;
3192 	/*
3193 	 * Get a valid port (within the anonymous range and should not
3194 	 * be a privileged one) to use if the user has not given a port.
3195 	 * If multiple threads are here, they may all start with
3196 	 * with the same initial port. But, it should be fine as long as
3197 	 * tcp_bindi will ensure that no two threads will be assigned
3198 	 * the same port.
3199 	 *
3200 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3201 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3202 	 * unless TCP_ANONPRIVBIND option is set.
3203 	 */
3204 	mlptype = mlptSingle;
3205 	mlp_port = requested_port;
3206 	if (requested_port == 0) {
3207 		requested_port = tcp->tcp_anon_priv_bind ?
3208 		    tcp_get_next_priv_port(tcp) :
3209 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
3210 		    tcp, B_TRUE);
3211 		if (requested_port == 0) {
3212 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3213 			return;
3214 		}
3215 		user_specified = B_FALSE;
3216 
3217 		/*
3218 		 * If the user went through one of the RPC interfaces to create
3219 		 * this socket and RPC is MLP in this zone, then give him an
3220 		 * anonymous MLP.
3221 		 */
3222 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3223 		if (connp->conn_anon_mlp && is_system_labeled()) {
3224 			zone = crgetzone(cr);
3225 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3226 			    IPV6_VERSION, &v6addr,
3227 			    tcps->tcps_netstack->netstack_ip);
3228 			if (addrtype == mlptSingle) {
3229 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3230 				return;
3231 			}
3232 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3233 			    PMAPPORT, addrtype);
3234 			mlp_port = PMAPPORT;
3235 		}
3236 	} else {
3237 		int i;
3238 		boolean_t priv = B_FALSE;
3239 
3240 		/*
3241 		 * If the requested_port is in the well-known privileged range,
3242 		 * verify that the stream was opened by a privileged user.
3243 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3244 		 * but instead the code relies on:
3245 		 * - the fact that the address of the array and its size never
3246 		 *   changes
3247 		 * - the atomic assignment of the elements of the array
3248 		 */
3249 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3250 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
3251 			priv = B_TRUE;
3252 		} else {
3253 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
3254 				if (requested_port ==
3255 				    tcps->tcps_g_epriv_ports[i]) {
3256 					priv = B_TRUE;
3257 					break;
3258 				}
3259 			}
3260 		}
3261 		if (priv) {
3262 			if (secpolicy_net_privaddr(cr, requested_port,
3263 			    IPPROTO_TCP) != 0) {
3264 				if (tcp->tcp_debug) {
3265 					(void) strlog(TCP_MOD_ID, 0, 1,
3266 					    SL_ERROR|SL_TRACE,
3267 					    "tcp_bind: no priv for port %d",
3268 					    requested_port);
3269 				}
3270 				tcp_err_ack(tcp, mp, TACCES, 0);
3271 				return;
3272 			}
3273 		}
3274 		user_specified = B_TRUE;
3275 
3276 		if (is_system_labeled()) {
3277 			zone = crgetzone(cr);
3278 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3279 			    IPV6_VERSION, &v6addr,
3280 			    tcps->tcps_netstack->netstack_ip);
3281 			if (addrtype == mlptSingle) {
3282 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3283 				return;
3284 			}
3285 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3286 			    requested_port, addrtype);
3287 		}
3288 	}
3289 
3290 	if (mlptype != mlptSingle) {
3291 		if (secpolicy_net_bindmlp(cr) != 0) {
3292 			if (tcp->tcp_debug) {
3293 				(void) strlog(TCP_MOD_ID, 0, 1,
3294 				    SL_ERROR|SL_TRACE,
3295 				    "tcp_bind: no priv for multilevel port %d",
3296 				    requested_port);
3297 			}
3298 			tcp_err_ack(tcp, mp, TACCES, 0);
3299 			return;
3300 		}
3301 
3302 		/*
3303 		 * If we're specifically binding a shared IP address and the
3304 		 * port is MLP on shared addresses, then check to see if this
3305 		 * zone actually owns the MLP.  Reject if not.
3306 		 */
3307 		if (mlptype == mlptShared && addrtype == mlptShared) {
3308 			/*
3309 			 * No need to handle exclusive-stack zones since
3310 			 * ALL_ZONES only applies to the shared stack.
3311 			 */
3312 			zoneid_t mlpzone;
3313 
3314 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3315 			    htons(mlp_port));
3316 			if (connp->conn_zoneid != mlpzone) {
3317 				if (tcp->tcp_debug) {
3318 					(void) strlog(TCP_MOD_ID, 0, 1,
3319 					    SL_ERROR|SL_TRACE,
3320 					    "tcp_bind: attempt to bind port "
3321 					    "%d on shared addr in zone %d "
3322 					    "(should be %d)",
3323 					    mlp_port, connp->conn_zoneid,
3324 					    mlpzone);
3325 				}
3326 				tcp_err_ack(tcp, mp, TACCES, 0);
3327 				return;
3328 			}
3329 		}
3330 
3331 		if (!user_specified) {
3332 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3333 			    requested_port, B_TRUE);
3334 			if (err != 0) {
3335 				if (tcp->tcp_debug) {
3336 					(void) strlog(TCP_MOD_ID, 0, 1,
3337 					    SL_ERROR|SL_TRACE,
3338 					    "tcp_bind: cannot establish anon "
3339 					    "MLP for port %d",
3340 					    requested_port);
3341 				}
3342 				tcp_err_ack(tcp, mp, TSYSERR, err);
3343 				return;
3344 			}
3345 			connp->conn_anon_port = B_TRUE;
3346 		}
3347 		connp->conn_mlp_type = mlptype;
3348 	}
3349 
3350 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3351 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3352 
3353 	if (allocated_port == 0) {
3354 		connp->conn_mlp_type = mlptSingle;
3355 		if (connp->conn_anon_port) {
3356 			connp->conn_anon_port = B_FALSE;
3357 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3358 			    requested_port, B_FALSE);
3359 		}
3360 		if (bind_to_req_port_only) {
3361 			if (tcp->tcp_debug) {
3362 				(void) strlog(TCP_MOD_ID, 0, 1,
3363 				    SL_ERROR|SL_TRACE,
3364 				    "tcp_bind: requested addr busy");
3365 			}
3366 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3367 		} else {
3368 			/* If we are out of ports, fail the bind. */
3369 			if (tcp->tcp_debug) {
3370 				(void) strlog(TCP_MOD_ID, 0, 1,
3371 				    SL_ERROR|SL_TRACE,
3372 				    "tcp_bind: out of ports?");
3373 			}
3374 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3375 		}
3376 		return;
3377 	}
3378 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3379 do_bind:
3380 	if (!backlog_update) {
3381 		if (tcp->tcp_family == AF_INET)
3382 			sin->sin_port = htons(allocated_port);
3383 		else
3384 			sin6->sin6_port = htons(allocated_port);
3385 	}
3386 	if (tcp->tcp_family == AF_INET) {
3387 		if (tbr->CONIND_number != 0) {
3388 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3389 			    sizeof (sin_t));
3390 		} else {
3391 			/* Just verify the local IP address */
3392 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3393 		}
3394 	} else {
3395 		if (tbr->CONIND_number != 0) {
3396 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3397 			    sizeof (sin6_t));
3398 		} else {
3399 			/* Just verify the local IP address */
3400 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3401 			    IPV6_ADDR_LEN);
3402 		}
3403 	}
3404 	if (mp1 == NULL) {
3405 		if (connp->conn_anon_port) {
3406 			connp->conn_anon_port = B_FALSE;
3407 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3408 			    requested_port, B_FALSE);
3409 		}
3410 		connp->conn_mlp_type = mlptSingle;
3411 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3412 		return;
3413 	}
3414 
3415 	tbr->PRIM_type = T_BIND_ACK;
3416 	mp->b_datap->db_type = M_PCPROTO;
3417 
3418 	/* Chain in the reply mp for tcp_rput() */
3419 	mp1->b_cont = mp;
3420 	mp = mp1;
3421 
3422 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3423 	if (tcp->tcp_conn_req_max) {
3424 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
3425 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
3426 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
3427 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
3428 		/*
3429 		 * If this is a listener, do not reset the eager list
3430 		 * and other stuffs.  Note that we don't check if the
3431 		 * existing eager list meets the new tcp_conn_req_max
3432 		 * requirement.
3433 		 */
3434 		if (tcp->tcp_state != TCPS_LISTEN) {
3435 			tcp->tcp_state = TCPS_LISTEN;
3436 			/* Initialize the chain. Don't need the eager_lock */
3437 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3438 			tcp->tcp_eager_next_drop_q0 = tcp;
3439 			tcp->tcp_eager_prev_drop_q0 = tcp;
3440 			tcp->tcp_second_ctimer_threshold =
3441 			    tcps->tcps_ip_abort_linterval;
3442 		}
3443 	}
3444 
3445 	/*
3446 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3447 	 * processing continues in tcp_rput_other().
3448 	 *
3449 	 * We need to make sure that the conn_recv is set to a non-null
3450 	 * value before we insert the conn into the classifier table.
3451 	 * This is to avoid a race with an incoming packet which does an
3452 	 * ipcl_classify().
3453 	 */
3454 	connp->conn_recv = tcp_conn_request;
3455 	if (tcp->tcp_family == AF_INET6) {
3456 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3457 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3458 	} else {
3459 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3460 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3461 	}
3462 	/*
3463 	 * If the bind cannot complete immediately
3464 	 * IP will arrange to call tcp_rput_other
3465 	 * when the bind completes.
3466 	 */
3467 	if (mp != NULL) {
3468 		tcp_rput_other(tcp, mp);
3469 	} else {
3470 		/*
3471 		 * Bind will be resumed later. Need to ensure
3472 		 * that conn doesn't disappear when that happens.
3473 		 * This will be decremented in ip_resume_tcp_bind().
3474 		 */
3475 		CONN_INC_REF(tcp->tcp_connp);
3476 	}
3477 }
3478 
3479 
3480 /*
3481  * If the "bind_to_req_port_only" parameter is set, if the requested port
3482  * number is available, return it, If not return 0
3483  *
3484  * If "bind_to_req_port_only" parameter is not set and
3485  * If the requested port number is available, return it.  If not, return
3486  * the first anonymous port we happen across.  If no anonymous ports are
3487  * available, return 0. addr is the requested local address, if any.
3488  *
3489  * In either case, when succeeding update the tcp_t to record the port number
3490  * and insert it in the bind hash table.
3491  *
3492  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3493  * without setting SO_REUSEADDR. This is needed so that they
3494  * can be viewed as two independent transport protocols.
3495  */
3496 static in_port_t
3497 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3498     int reuseaddr, boolean_t quick_connect,
3499     boolean_t bind_to_req_port_only, boolean_t user_specified)
3500 {
3501 	/* number of times we have run around the loop */
3502 	int count = 0;
3503 	/* maximum number of times to run around the loop */
3504 	int loopmax;
3505 	conn_t *connp = tcp->tcp_connp;
3506 	zoneid_t zoneid = connp->conn_zoneid;
3507 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3508 
3509 	/*
3510 	 * Lookup for free addresses is done in a loop and "loopmax"
3511 	 * influences how long we spin in the loop
3512 	 */
3513 	if (bind_to_req_port_only) {
3514 		/*
3515 		 * If the requested port is busy, don't bother to look
3516 		 * for a new one. Setting loop maximum count to 1 has
3517 		 * that effect.
3518 		 */
3519 		loopmax = 1;
3520 	} else {
3521 		/*
3522 		 * If the requested port is busy, look for a free one
3523 		 * in the anonymous port range.
3524 		 * Set loopmax appropriately so that one does not look
3525 		 * forever in the case all of the anonymous ports are in use.
3526 		 */
3527 		if (tcp->tcp_anon_priv_bind) {
3528 			/*
3529 			 * loopmax =
3530 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3531 			 */
3532 			loopmax = IPPORT_RESERVED -
3533 			    tcps->tcps_min_anonpriv_port;
3534 		} else {
3535 			loopmax = (tcps->tcps_largest_anon_port -
3536 			    tcps->tcps_smallest_anon_port + 1);
3537 		}
3538 	}
3539 	do {
3540 		uint16_t	lport;
3541 		tf_t		*tbf;
3542 		tcp_t		*ltcp;
3543 		conn_t		*lconnp;
3544 
3545 		lport = htons(port);
3546 
3547 		/*
3548 		 * Ensure that the tcp_t is not currently in the bind hash.
3549 		 * Hold the lock on the hash bucket to ensure that
3550 		 * the duplicate check plus the insertion is an atomic
3551 		 * operation.
3552 		 *
3553 		 * This function does an inline lookup on the bind hash list
3554 		 * Make sure that we access only members of tcp_t
3555 		 * and that we don't look at tcp_tcp, since we are not
3556 		 * doing a CONN_INC_REF.
3557 		 */
3558 		tcp_bind_hash_remove(tcp);
3559 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3560 		mutex_enter(&tbf->tf_lock);
3561 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3562 		    ltcp = ltcp->tcp_bind_hash) {
3563 			boolean_t not_socket;
3564 			boolean_t exclbind;
3565 
3566 			if (lport != ltcp->tcp_lport)
3567 				continue;
3568 
3569 			lconnp = ltcp->tcp_connp;
3570 
3571 			/*
3572 			 * On a labeled system, we must treat bindings to ports
3573 			 * on shared IP addresses by sockets with MAC exemption
3574 			 * privilege as being in all zones, as there's
3575 			 * otherwise no way to identify the right receiver.
3576 			 */
3577 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3578 			    IPCL_ZONE_MATCH(connp,
3579 			    ltcp->tcp_connp->conn_zoneid)) &&
3580 			    !lconnp->conn_mac_exempt &&
3581 			    !connp->conn_mac_exempt)
3582 				continue;
3583 
3584 			/*
3585 			 * If TCP_EXCLBIND is set for either the bound or
3586 			 * binding endpoint, the semantics of bind
3587 			 * is changed according to the following.
3588 			 *
3589 			 * spec = specified address (v4 or v6)
3590 			 * unspec = unspecified address (v4 or v6)
3591 			 * A = specified addresses are different for endpoints
3592 			 *
3593 			 * bound	bind to		allowed
3594 			 * -------------------------------------
3595 			 * unspec	unspec		no
3596 			 * unspec	spec		no
3597 			 * spec		unspec		no
3598 			 * spec		spec		yes if A
3599 			 *
3600 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3601 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3602 			 *
3603 			 * Note:
3604 			 *
3605 			 * 1. Because of TLI semantics, an endpoint can go
3606 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3607 			 * TCPS_BOUND, depending on whether it is originally
3608 			 * a listener or not.  That is why we need to check
3609 			 * for states greater than or equal to TCPS_BOUND
3610 			 * here.
3611 			 *
3612 			 * 2. Ideally, we should only check for state equals
3613 			 * to TCPS_LISTEN. And the following check should be
3614 			 * added.
3615 			 *
3616 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3617 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3618 			 *		...
3619 			 * }
3620 			 *
3621 			 * The semantics will be changed to this.  If the
3622 			 * endpoint on the list is in state not equal to
3623 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3624 			 * set, let the bind succeed.
3625 			 *
3626 			 * Because of (1), we cannot do that for TLI
3627 			 * endpoints.  But we can do that for socket endpoints.
3628 			 * If in future, we can change this going back
3629 			 * semantics, we can use the above check for TLI also.
3630 			 */
3631 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3632 			    TCP_IS_SOCKET(tcp));
3633 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3634 
3635 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3636 			    (exclbind && (not_socket ||
3637 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3638 				if (V6_OR_V4_INADDR_ANY(
3639 				    ltcp->tcp_bound_source_v6) ||
3640 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3641 				    IN6_ARE_ADDR_EQUAL(laddr,
3642 				    &ltcp->tcp_bound_source_v6)) {
3643 					break;
3644 				}
3645 				continue;
3646 			}
3647 
3648 			/*
3649 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3650 			 * have disjoint port number spaces, if *_EXCLBIND
3651 			 * is not set and only if the application binds to a
3652 			 * specific port. We use the same autoassigned port
3653 			 * number space for IPv4 and IPv6 sockets.
3654 			 */
3655 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3656 			    bind_to_req_port_only)
3657 				continue;
3658 
3659 			/*
3660 			 * Ideally, we should make sure that the source
3661 			 * address, remote address, and remote port in the
3662 			 * four tuple for this tcp-connection is unique.
3663 			 * However, trying to find out the local source
3664 			 * address would require too much code duplication
3665 			 * with IP, since IP needs needs to have that code
3666 			 * to support userland TCP implementations.
3667 			 */
3668 			if (quick_connect &&
3669 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3670 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3671 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3672 			    &ltcp->tcp_remote_v6)))
3673 				continue;
3674 
3675 			if (!reuseaddr) {
3676 				/*
3677 				 * No socket option SO_REUSEADDR.
3678 				 * If existing port is bound to
3679 				 * a non-wildcard IP address
3680 				 * and the requesting stream is
3681 				 * bound to a distinct
3682 				 * different IP addresses
3683 				 * (non-wildcard, also), keep
3684 				 * going.
3685 				 */
3686 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3687 				    !V6_OR_V4_INADDR_ANY(
3688 				    ltcp->tcp_bound_source_v6) &&
3689 				    !IN6_ARE_ADDR_EQUAL(laddr,
3690 				    &ltcp->tcp_bound_source_v6))
3691 					continue;
3692 				if (ltcp->tcp_state >= TCPS_BOUND) {
3693 					/*
3694 					 * This port is being used and
3695 					 * its state is >= TCPS_BOUND,
3696 					 * so we can't bind to it.
3697 					 */
3698 					break;
3699 				}
3700 			} else {
3701 				/*
3702 				 * socket option SO_REUSEADDR is set on the
3703 				 * binding tcp_t.
3704 				 *
3705 				 * If two streams are bound to
3706 				 * same IP address or both addr
3707 				 * and bound source are wildcards
3708 				 * (INADDR_ANY), we want to stop
3709 				 * searching.
3710 				 * We have found a match of IP source
3711 				 * address and source port, which is
3712 				 * refused regardless of the
3713 				 * SO_REUSEADDR setting, so we break.
3714 				 */
3715 				if (IN6_ARE_ADDR_EQUAL(laddr,
3716 				    &ltcp->tcp_bound_source_v6) &&
3717 				    (ltcp->tcp_state == TCPS_LISTEN ||
3718 				    ltcp->tcp_state == TCPS_BOUND))
3719 					break;
3720 			}
3721 		}
3722 		if (ltcp != NULL) {
3723 			/* The port number is busy */
3724 			mutex_exit(&tbf->tf_lock);
3725 		} else {
3726 			/*
3727 			 * This port is ours. Insert in fanout and mark as
3728 			 * bound to prevent others from getting the port
3729 			 * number.
3730 			 */
3731 			tcp->tcp_state = TCPS_BOUND;
3732 			tcp->tcp_lport = htons(port);
3733 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3734 
3735 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3736 			    tcp->tcp_lport)] == tbf);
3737 			tcp_bind_hash_insert(tbf, tcp, 1);
3738 
3739 			mutex_exit(&tbf->tf_lock);
3740 
3741 			/*
3742 			 * We don't want tcp_next_port_to_try to "inherit"
3743 			 * a port number supplied by the user in a bind.
3744 			 */
3745 			if (user_specified)
3746 				return (port);
3747 
3748 			/*
3749 			 * This is the only place where tcp_next_port_to_try
3750 			 * is updated. After the update, it may or may not
3751 			 * be in the valid range.
3752 			 */
3753 			if (!tcp->tcp_anon_priv_bind)
3754 				tcps->tcps_next_port_to_try = port + 1;
3755 			return (port);
3756 		}
3757 
3758 		if (tcp->tcp_anon_priv_bind) {
3759 			port = tcp_get_next_priv_port(tcp);
3760 		} else {
3761 			if (count == 0 && user_specified) {
3762 				/*
3763 				 * We may have to return an anonymous port. So
3764 				 * get one to start with.
3765 				 */
3766 				port =
3767 				    tcp_update_next_port(
3768 				    tcps->tcps_next_port_to_try,
3769 				    tcp, B_TRUE);
3770 				user_specified = B_FALSE;
3771 			} else {
3772 				port = tcp_update_next_port(port + 1, tcp,
3773 				    B_FALSE);
3774 			}
3775 		}
3776 		if (port == 0)
3777 			break;
3778 
3779 		/*
3780 		 * Don't let this loop run forever in the case where
3781 		 * all of the anonymous ports are in use.
3782 		 */
3783 	} while (++count < loopmax);
3784 	return (0);
3785 }
3786 
3787 /*
3788  * tcp_clean_death / tcp_close_detached must not be called more than once
3789  * on a tcp. Thus every function that potentially calls tcp_clean_death
3790  * must check for the tcp state before calling tcp_clean_death.
3791  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3792  * tcp_timer_handler, all check for the tcp state.
3793  */
3794 /* ARGSUSED */
3795 void
3796 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3797 {
3798 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3799 
3800 	freemsg(mp);
3801 	if (tcp->tcp_state > TCPS_BOUND)
3802 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3803 		    ETIMEDOUT, 5);
3804 }
3805 
3806 /*
3807  * We are dying for some reason.  Try to do it gracefully.  (May be called
3808  * as writer.)
3809  *
3810  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3811  * done by a service procedure).
3812  * TBD - Should the return value distinguish between the tcp_t being
3813  * freed and it being reinitialized?
3814  */
3815 static int
3816 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3817 {
3818 	mblk_t	*mp;
3819 	queue_t	*q;
3820 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3821 	sodirect_t	*sodp;
3822 
3823 	TCP_CLD_STAT(tag);
3824 
3825 #if TCP_TAG_CLEAN_DEATH
3826 	tcp->tcp_cleandeathtag = tag;
3827 #endif
3828 
3829 	if (tcp->tcp_fused)
3830 		tcp_unfuse(tcp);
3831 
3832 	if (tcp->tcp_linger_tid != 0 &&
3833 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3834 		tcp_stop_lingering(tcp);
3835 	}
3836 
3837 	ASSERT(tcp != NULL);
3838 	ASSERT((tcp->tcp_family == AF_INET &&
3839 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3840 	    (tcp->tcp_family == AF_INET6 &&
3841 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3842 	    tcp->tcp_ipversion == IPV6_VERSION)));
3843 
3844 	if (TCP_IS_DETACHED(tcp)) {
3845 		if (tcp->tcp_hard_binding) {
3846 			/*
3847 			 * Its an eager that we are dealing with. We close the
3848 			 * eager but in case a conn_ind has already gone to the
3849 			 * listener, let tcp_accept_finish() send a discon_ind
3850 			 * to the listener and drop the last reference. If the
3851 			 * listener doesn't even know about the eager i.e. the
3852 			 * conn_ind hasn't gone up, blow away the eager and drop
3853 			 * the last reference as well. If the conn_ind has gone
3854 			 * up, state should be BOUND. tcp_accept_finish
3855 			 * will figure out that the connection has received a
3856 			 * RST and will send a DISCON_IND to the application.
3857 			 */
3858 			tcp_closei_local(tcp);
3859 			if (!tcp->tcp_tconnind_started) {
3860 				CONN_DEC_REF(tcp->tcp_connp);
3861 			} else {
3862 				tcp->tcp_state = TCPS_BOUND;
3863 			}
3864 		} else {
3865 			tcp_close_detached(tcp);
3866 		}
3867 		return (0);
3868 	}
3869 
3870 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3871 
3872 	/* If sodirect, not anymore */
3873 	SOD_PTR_ENTER(tcp, sodp);
3874 	if (sodp != NULL) {
3875 		tcp->tcp_sodirect = NULL;
3876 		mutex_exit(sodp->sod_lockp);
3877 	}
3878 
3879 	q = tcp->tcp_rq;
3880 
3881 	/* Trash all inbound data */
3882 	flushq(q, FLUSHALL);
3883 
3884 	/*
3885 	 * If we are at least part way open and there is error
3886 	 * (err==0 implies no error)
3887 	 * notify our client by a T_DISCON_IND.
3888 	 */
3889 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3890 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3891 		    !TCP_IS_SOCKET(tcp)) {
3892 			/*
3893 			 * Send M_FLUSH according to TPI. Because sockets will
3894 			 * (and must) ignore FLUSHR we do that only for TPI
3895 			 * endpoints and sockets in STREAMS mode.
3896 			 */
3897 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3898 		}
3899 		if (tcp->tcp_debug) {
3900 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3901 			    "tcp_clean_death: discon err %d", err);
3902 		}
3903 		mp = mi_tpi_discon_ind(NULL, err, 0);
3904 		if (mp != NULL) {
3905 			putnext(q, mp);
3906 		} else {
3907 			if (tcp->tcp_debug) {
3908 				(void) strlog(TCP_MOD_ID, 0, 1,
3909 				    SL_ERROR|SL_TRACE,
3910 				    "tcp_clean_death, sending M_ERROR");
3911 			}
3912 			(void) putnextctl1(q, M_ERROR, EPROTO);
3913 		}
3914 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3915 			/* SYN_SENT or SYN_RCVD */
3916 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3917 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3918 			/* ESTABLISHED or CLOSE_WAIT */
3919 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3920 		}
3921 	}
3922 
3923 	tcp_reinit(tcp);
3924 	return (-1);
3925 }
3926 
3927 /*
3928  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3929  * to expire, stop the wait and finish the close.
3930  */
3931 static void
3932 tcp_stop_lingering(tcp_t *tcp)
3933 {
3934 	clock_t	delta = 0;
3935 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3936 
3937 	tcp->tcp_linger_tid = 0;
3938 	if (tcp->tcp_state > TCPS_LISTEN) {
3939 		tcp_acceptor_hash_remove(tcp);
3940 		mutex_enter(&tcp->tcp_non_sq_lock);
3941 		if (tcp->tcp_flow_stopped) {
3942 			tcp_clrqfull(tcp);
3943 		}
3944 		mutex_exit(&tcp->tcp_non_sq_lock);
3945 
3946 		if (tcp->tcp_timer_tid != 0) {
3947 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3948 			tcp->tcp_timer_tid = 0;
3949 		}
3950 		/*
3951 		 * Need to cancel those timers which will not be used when
3952 		 * TCP is detached.  This has to be done before the tcp_wq
3953 		 * is set to the global queue.
3954 		 */
3955 		tcp_timers_stop(tcp);
3956 
3957 
3958 		tcp->tcp_detached = B_TRUE;
3959 		ASSERT(tcps->tcps_g_q != NULL);
3960 		tcp->tcp_rq = tcps->tcps_g_q;
3961 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3962 
3963 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3964 			tcp_time_wait_append(tcp);
3965 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3966 			goto finish;
3967 		}
3968 
3969 		/*
3970 		 * If delta is zero the timer event wasn't executed and was
3971 		 * successfully canceled. In this case we need to restart it
3972 		 * with the minimal delta possible.
3973 		 */
3974 		if (delta >= 0) {
3975 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3976 			    delta ? delta : 1);
3977 		}
3978 	} else {
3979 		tcp_closei_local(tcp);
3980 		CONN_DEC_REF(tcp->tcp_connp);
3981 	}
3982 finish:
3983 	/* Signal closing thread that it can complete close */
3984 	mutex_enter(&tcp->tcp_closelock);
3985 	tcp->tcp_detached = B_TRUE;
3986 	ASSERT(tcps->tcps_g_q != NULL);
3987 	tcp->tcp_rq = tcps->tcps_g_q;
3988 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3989 	tcp->tcp_closed = 1;
3990 	cv_signal(&tcp->tcp_closecv);
3991 	mutex_exit(&tcp->tcp_closelock);
3992 }
3993 
3994 /*
3995  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3996  * expires.
3997  */
3998 static void
3999 tcp_close_linger_timeout(void *arg)
4000 {
4001 	conn_t	*connp = (conn_t *)arg;
4002 	tcp_t 	*tcp = connp->conn_tcp;
4003 
4004 	tcp->tcp_client_errno = ETIMEDOUT;
4005 	tcp_stop_lingering(tcp);
4006 }
4007 
4008 static int
4009 tcp_close(queue_t *q, int flags)
4010 {
4011 	conn_t		*connp = Q_TO_CONN(q);
4012 	tcp_t		*tcp = connp->conn_tcp;
4013 	mblk_t 		*mp = &tcp->tcp_closemp;
4014 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4015 	mblk_t		*bp;
4016 
4017 	ASSERT(WR(q)->q_next == NULL);
4018 	ASSERT(connp->conn_ref >= 2);
4019 
4020 	/*
4021 	 * We are being closed as /dev/tcp or /dev/tcp6.
4022 	 *
4023 	 * Mark the conn as closing. ill_pending_mp_add will not
4024 	 * add any mp to the pending mp list, after this conn has
4025 	 * started closing. Same for sq_pending_mp_add
4026 	 */
4027 	mutex_enter(&connp->conn_lock);
4028 	connp->conn_state_flags |= CONN_CLOSING;
4029 	if (connp->conn_oper_pending_ill != NULL)
4030 		conn_ioctl_cleanup_reqd = B_TRUE;
4031 	CONN_INC_REF_LOCKED(connp);
4032 	mutex_exit(&connp->conn_lock);
4033 	tcp->tcp_closeflags = (uint8_t)flags;
4034 	ASSERT(connp->conn_ref >= 3);
4035 
4036 	/*
4037 	 * tcp_closemp_used is used below without any protection of a lock
4038 	 * as we don't expect any one else to use it concurrently at this
4039 	 * point otherwise it would be a major defect.
4040 	 */
4041 
4042 	if (mp->b_prev == NULL)
4043 		tcp->tcp_closemp_used = B_TRUE;
4044 	else
4045 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
4046 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
4047 
4048 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
4049 
4050 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
4051 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
4052 
4053 	mutex_enter(&tcp->tcp_closelock);
4054 	while (!tcp->tcp_closed) {
4055 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
4056 			/*
4057 			 * The cv_wait_sig() was interrupted. We now do the
4058 			 * following:
4059 			 *
4060 			 * 1) If the endpoint was lingering, we allow this
4061 			 * to be interrupted by cancelling the linger timeout
4062 			 * and closing normally.
4063 			 *
4064 			 * 2) Revert to calling cv_wait()
4065 			 *
4066 			 * We revert to using cv_wait() to avoid an
4067 			 * infinite loop which can occur if the calling
4068 			 * thread is higher priority than the squeue worker
4069 			 * thread and is bound to the same cpu.
4070 			 */
4071 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
4072 				mutex_exit(&tcp->tcp_closelock);
4073 				/* Entering squeue, bump ref count. */
4074 				CONN_INC_REF(connp);
4075 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
4076 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
4077 				    tcp_linger_interrupted, connp,
4078 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
4079 				mutex_enter(&tcp->tcp_closelock);
4080 			}
4081 			break;
4082 		}
4083 	}
4084 	while (!tcp->tcp_closed)
4085 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
4086 	mutex_exit(&tcp->tcp_closelock);
4087 
4088 	/*
4089 	 * In the case of listener streams that have eagers in the q or q0
4090 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4091 	 * tcp_wq of the eagers point to our queues. By waiting for the
4092 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4093 	 * up their queue pointers and also dropped their references to us.
4094 	 */
4095 	if (tcp->tcp_wait_for_eagers) {
4096 		mutex_enter(&connp->conn_lock);
4097 		while (connp->conn_ref != 1) {
4098 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4099 		}
4100 		mutex_exit(&connp->conn_lock);
4101 	}
4102 	/*
4103 	 * ioctl cleanup. The mp is queued in the
4104 	 * ill_pending_mp or in the sq_pending_mp.
4105 	 */
4106 	if (conn_ioctl_cleanup_reqd)
4107 		conn_ioctl_cleanup(connp);
4108 
4109 	qprocsoff(q);
4110 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4111 
4112 	tcp->tcp_cpid = -1;
4113 
4114 	/*
4115 	 * Drop IP's reference on the conn. This is the last reference
4116 	 * on the connp if the state was less than established. If the
4117 	 * connection has gone into timewait state, then we will have
4118 	 * one ref for the TCP and one more ref (total of two) for the
4119 	 * classifier connected hash list (a timewait connections stays
4120 	 * in connected hash till closed).
4121 	 *
4122 	 * We can't assert the references because there might be other
4123 	 * transient reference places because of some walkers or queued
4124 	 * packets in squeue for the timewait state.
4125 	 */
4126 	CONN_DEC_REF(connp);
4127 	q->q_ptr = WR(q)->q_ptr = NULL;
4128 	return (0);
4129 }
4130 
4131 static int
4132 tcpclose_accept(queue_t *q)
4133 {
4134 	vmem_t	*minor_arena;
4135 	dev_t	conn_dev;
4136 
4137 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4138 
4139 	/*
4140 	 * We had opened an acceptor STREAM for sockfs which is
4141 	 * now being closed due to some error.
4142 	 */
4143 	qprocsoff(q);
4144 
4145 	minor_arena = (vmem_t *)WR(q)->q_ptr;
4146 	conn_dev = (dev_t)RD(q)->q_ptr;
4147 	ASSERT(minor_arena != NULL);
4148 	ASSERT(conn_dev != 0);
4149 	inet_minor_free(minor_arena, conn_dev);
4150 	q->q_ptr = WR(q)->q_ptr = NULL;
4151 	return (0);
4152 }
4153 
4154 /*
4155  * Called by tcp_close() routine via squeue when lingering is
4156  * interrupted by a signal.
4157  */
4158 
4159 /* ARGSUSED */
4160 static void
4161 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4162 {
4163 	conn_t	*connp = (conn_t *)arg;
4164 	tcp_t	*tcp = connp->conn_tcp;
4165 
4166 	freeb(mp);
4167 	if (tcp->tcp_linger_tid != 0 &&
4168 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4169 		tcp_stop_lingering(tcp);
4170 		tcp->tcp_client_errno = EINTR;
4171 	}
4172 }
4173 
4174 /*
4175  * Called by streams close routine via squeues when our client blows off her
4176  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4177  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4178  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4179  * acked.
4180  *
4181  * NOTE: tcp_close potentially returns error when lingering.
4182  * However, the stream head currently does not pass these errors
4183  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4184  * errors to the application (from tsleep()) and not errors
4185  * like ECONNRESET caused by receiving a reset packet.
4186  */
4187 
4188 /* ARGSUSED */
4189 static void
4190 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4191 {
4192 	char	*msg;
4193 	conn_t	*connp = (conn_t *)arg;
4194 	tcp_t	*tcp = connp->conn_tcp;
4195 	clock_t	delta = 0;
4196 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4197 
4198 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4199 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4200 
4201 	mutex_enter(&tcp->tcp_eager_lock);
4202 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4203 		/* Cleanup for listener */
4204 		tcp_eager_cleanup(tcp, 0);
4205 		tcp->tcp_wait_for_eagers = 1;
4206 	}
4207 	mutex_exit(&tcp->tcp_eager_lock);
4208 
4209 	connp->conn_mdt_ok = B_FALSE;
4210 	tcp->tcp_mdt = B_FALSE;
4211 
4212 	connp->conn_lso_ok = B_FALSE;
4213 	tcp->tcp_lso = B_FALSE;
4214 
4215 	msg = NULL;
4216 	switch (tcp->tcp_state) {
4217 	case TCPS_CLOSED:
4218 	case TCPS_IDLE:
4219 	case TCPS_BOUND:
4220 	case TCPS_LISTEN:
4221 		break;
4222 	case TCPS_SYN_SENT:
4223 		msg = "tcp_close, during connect";
4224 		break;
4225 	case TCPS_SYN_RCVD:
4226 		/*
4227 		 * Close during the connect 3-way handshake
4228 		 * but here there may or may not be pending data
4229 		 * already on queue. Process almost same as in
4230 		 * the ESTABLISHED state.
4231 		 */
4232 		/* FALLTHRU */
4233 	default:
4234 		if (tcp->tcp_sodirect != NULL) {
4235 			/* Ok, no more sodirect */
4236 			tcp->tcp_sodirect = NULL;
4237 		}
4238 
4239 		if (tcp->tcp_fused)
4240 			tcp_unfuse(tcp);
4241 
4242 		/*
4243 		 * If SO_LINGER has set a zero linger time, abort the
4244 		 * connection with a reset.
4245 		 */
4246 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4247 			msg = "tcp_close, zero lingertime";
4248 			break;
4249 		}
4250 
4251 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4252 		/*
4253 		 * Abort connection if there is unread data queued.
4254 		 */
4255 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4256 			msg = "tcp_close, unread data";
4257 			break;
4258 		}
4259 		/*
4260 		 * tcp_hard_bound is now cleared thus all packets go through
4261 		 * tcp_lookup. This fact is used by tcp_detach below.
4262 		 *
4263 		 * We have done a qwait() above which could have possibly
4264 		 * drained more messages in turn causing transition to a
4265 		 * different state. Check whether we have to do the rest
4266 		 * of the processing or not.
4267 		 */
4268 		if (tcp->tcp_state <= TCPS_LISTEN)
4269 			break;
4270 
4271 		/*
4272 		 * Transmit the FIN before detaching the tcp_t.
4273 		 * After tcp_detach returns this queue/perimeter
4274 		 * no longer owns the tcp_t thus others can modify it.
4275 		 */
4276 		(void) tcp_xmit_end(tcp);
4277 
4278 		/*
4279 		 * If lingering on close then wait until the fin is acked,
4280 		 * the SO_LINGER time passes, or a reset is sent/received.
4281 		 */
4282 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4283 		    !(tcp->tcp_fin_acked) &&
4284 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4285 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4286 				tcp->tcp_client_errno = EWOULDBLOCK;
4287 			} else if (tcp->tcp_client_errno == 0) {
4288 
4289 				ASSERT(tcp->tcp_linger_tid == 0);
4290 
4291 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4292 				    tcp_close_linger_timeout,
4293 				    tcp->tcp_lingertime * hz);
4294 
4295 				/* tcp_close_linger_timeout will finish close */
4296 				if (tcp->tcp_linger_tid == 0)
4297 					tcp->tcp_client_errno = ENOSR;
4298 				else
4299 					return;
4300 			}
4301 
4302 			/*
4303 			 * Check if we need to detach or just close
4304 			 * the instance.
4305 			 */
4306 			if (tcp->tcp_state <= TCPS_LISTEN)
4307 				break;
4308 		}
4309 
4310 		/*
4311 		 * Make sure that no other thread will access the tcp_rq of
4312 		 * this instance (through lookups etc.) as tcp_rq will go
4313 		 * away shortly.
4314 		 */
4315 		tcp_acceptor_hash_remove(tcp);
4316 
4317 		mutex_enter(&tcp->tcp_non_sq_lock);
4318 		if (tcp->tcp_flow_stopped) {
4319 			tcp_clrqfull(tcp);
4320 		}
4321 		mutex_exit(&tcp->tcp_non_sq_lock);
4322 
4323 		if (tcp->tcp_timer_tid != 0) {
4324 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4325 			tcp->tcp_timer_tid = 0;
4326 		}
4327 		/*
4328 		 * Need to cancel those timers which will not be used when
4329 		 * TCP is detached.  This has to be done before the tcp_wq
4330 		 * is set to the global queue.
4331 		 */
4332 		tcp_timers_stop(tcp);
4333 
4334 		tcp->tcp_detached = B_TRUE;
4335 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4336 			tcp_time_wait_append(tcp);
4337 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4338 			ASSERT(connp->conn_ref >= 3);
4339 			goto finish;
4340 		}
4341 
4342 		/*
4343 		 * If delta is zero the timer event wasn't executed and was
4344 		 * successfully canceled. In this case we need to restart it
4345 		 * with the minimal delta possible.
4346 		 */
4347 		if (delta >= 0)
4348 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4349 			    delta ? delta : 1);
4350 
4351 		ASSERT(connp->conn_ref >= 3);
4352 		goto finish;
4353 	}
4354 
4355 	/* Detach did not complete. Still need to remove q from stream. */
4356 	if (msg) {
4357 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4358 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4359 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4360 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4361 		    tcp->tcp_state == TCPS_SYN_RCVD)
4362 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4363 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4364 	}
4365 
4366 	tcp_closei_local(tcp);
4367 	CONN_DEC_REF(connp);
4368 	ASSERT(connp->conn_ref >= 2);
4369 
4370 finish:
4371 	/*
4372 	 * Although packets are always processed on the correct
4373 	 * tcp's perimeter and access is serialized via squeue's,
4374 	 * IP still needs a queue when sending packets in time_wait
4375 	 * state so use WR(tcps_g_q) till ip_output() can be
4376 	 * changed to deal with just connp. For read side, we
4377 	 * could have set tcp_rq to NULL but there are some cases
4378 	 * in tcp_rput_data() from early days of this code which
4379 	 * do a putnext without checking if tcp is closed. Those
4380 	 * need to be identified before both tcp_rq and tcp_wq
4381 	 * can be set to NULL and tcps_g_q can disappear forever.
4382 	 */
4383 	mutex_enter(&tcp->tcp_closelock);
4384 	/*
4385 	 * Don't change the queues in the case of a listener that has
4386 	 * eagers in its q or q0. It could surprise the eagers.
4387 	 * Instead wait for the eagers outside the squeue.
4388 	 */
4389 	if (!tcp->tcp_wait_for_eagers) {
4390 		tcp->tcp_detached = B_TRUE;
4391 		/*
4392 		 * When default queue is closing we set tcps_g_q to NULL
4393 		 * after the close is done.
4394 		 */
4395 		ASSERT(tcps->tcps_g_q != NULL);
4396 		tcp->tcp_rq = tcps->tcps_g_q;
4397 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4398 	}
4399 
4400 	/* Signal tcp_close() to finish closing. */
4401 	tcp->tcp_closed = 1;
4402 	cv_signal(&tcp->tcp_closecv);
4403 	mutex_exit(&tcp->tcp_closelock);
4404 }
4405 
4406 
4407 /*
4408  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4409  * Some stream heads get upset if they see these later on as anything but NULL.
4410  */
4411 static void
4412 tcp_close_mpp(mblk_t **mpp)
4413 {
4414 	mblk_t	*mp;
4415 
4416 	if ((mp = *mpp) != NULL) {
4417 		do {
4418 			mp->b_next = NULL;
4419 			mp->b_prev = NULL;
4420 		} while ((mp = mp->b_cont) != NULL);
4421 
4422 		mp = *mpp;
4423 		*mpp = NULL;
4424 		freemsg(mp);
4425 	}
4426 }
4427 
4428 /* Do detached close. */
4429 static void
4430 tcp_close_detached(tcp_t *tcp)
4431 {
4432 	if (tcp->tcp_fused)
4433 		tcp_unfuse(tcp);
4434 
4435 	/*
4436 	 * Clustering code serializes TCP disconnect callbacks and
4437 	 * cluster tcp list walks by blocking a TCP disconnect callback
4438 	 * if a cluster tcp list walk is in progress. This ensures
4439 	 * accurate accounting of TCPs in the cluster code even though
4440 	 * the TCP list walk itself is not atomic.
4441 	 */
4442 	tcp_closei_local(tcp);
4443 	CONN_DEC_REF(tcp->tcp_connp);
4444 }
4445 
4446 /*
4447  * Stop all TCP timers, and free the timer mblks if requested.
4448  */
4449 void
4450 tcp_timers_stop(tcp_t *tcp)
4451 {
4452 	if (tcp->tcp_timer_tid != 0) {
4453 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4454 		tcp->tcp_timer_tid = 0;
4455 	}
4456 	if (tcp->tcp_ka_tid != 0) {
4457 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4458 		tcp->tcp_ka_tid = 0;
4459 	}
4460 	if (tcp->tcp_ack_tid != 0) {
4461 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4462 		tcp->tcp_ack_tid = 0;
4463 	}
4464 	if (tcp->tcp_push_tid != 0) {
4465 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4466 		tcp->tcp_push_tid = 0;
4467 	}
4468 }
4469 
4470 /*
4471  * The tcp_t is going away. Remove it from all lists and set it
4472  * to TCPS_CLOSED. The freeing up of memory is deferred until
4473  * tcp_inactive. This is needed since a thread in tcp_rput might have
4474  * done a CONN_INC_REF on this structure before it was removed from the
4475  * hashes.
4476  */
4477 static void
4478 tcp_closei_local(tcp_t *tcp)
4479 {
4480 	ire_t 	*ire;
4481 	conn_t	*connp = tcp->tcp_connp;
4482 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4483 
4484 	if (!TCP_IS_SOCKET(tcp))
4485 		tcp_acceptor_hash_remove(tcp);
4486 
4487 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4488 	tcp->tcp_ibsegs = 0;
4489 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4490 	tcp->tcp_obsegs = 0;
4491 
4492 	/*
4493 	 * If we are an eager connection hanging off a listener that
4494 	 * hasn't formally accepted the connection yet, get off his
4495 	 * list and blow off any data that we have accumulated.
4496 	 */
4497 	if (tcp->tcp_listener != NULL) {
4498 		tcp_t	*listener = tcp->tcp_listener;
4499 		mutex_enter(&listener->tcp_eager_lock);
4500 		/*
4501 		 * tcp_tconnind_started == B_TRUE means that the
4502 		 * conn_ind has already gone to listener. At
4503 		 * this point, eager will be closed but we
4504 		 * leave it in listeners eager list so that
4505 		 * if listener decides to close without doing
4506 		 * accept, we can clean this up. In tcp_wput_accept
4507 		 * we take care of the case of accept on closed
4508 		 * eager.
4509 		 */
4510 		if (!tcp->tcp_tconnind_started) {
4511 			tcp_eager_unlink(tcp);
4512 			mutex_exit(&listener->tcp_eager_lock);
4513 			/*
4514 			 * We don't want to have any pointers to the
4515 			 * listener queue, after we have released our
4516 			 * reference on the listener
4517 			 */
4518 			ASSERT(tcps->tcps_g_q != NULL);
4519 			tcp->tcp_rq = tcps->tcps_g_q;
4520 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4521 			CONN_DEC_REF(listener->tcp_connp);
4522 		} else {
4523 			mutex_exit(&listener->tcp_eager_lock);
4524 		}
4525 	}
4526 
4527 	/* Stop all the timers */
4528 	tcp_timers_stop(tcp);
4529 
4530 	if (tcp->tcp_state == TCPS_LISTEN) {
4531 		if (tcp->tcp_ip_addr_cache) {
4532 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4533 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4534 			tcp->tcp_ip_addr_cache = NULL;
4535 		}
4536 	}
4537 	mutex_enter(&tcp->tcp_non_sq_lock);
4538 	if (tcp->tcp_flow_stopped)
4539 		tcp_clrqfull(tcp);
4540 	mutex_exit(&tcp->tcp_non_sq_lock);
4541 
4542 	tcp_bind_hash_remove(tcp);
4543 	/*
4544 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4545 	 * is trying to remove this tcp from the time wait list, we will
4546 	 * block in tcp_time_wait_remove while trying to acquire the
4547 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4548 	 * requires the ipcl_hash_remove to be ordered after the
4549 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4550 	 */
4551 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4552 		(void) tcp_time_wait_remove(tcp, NULL);
4553 	CL_INET_DISCONNECT(tcp);
4554 	ipcl_hash_remove(connp);
4555 
4556 	/*
4557 	 * Delete the cached ire in conn_ire_cache and also mark
4558 	 * the conn as CONDEMNED
4559 	 */
4560 	mutex_enter(&connp->conn_lock);
4561 	connp->conn_state_flags |= CONN_CONDEMNED;
4562 	ire = connp->conn_ire_cache;
4563 	connp->conn_ire_cache = NULL;
4564 	mutex_exit(&connp->conn_lock);
4565 	if (ire != NULL)
4566 		IRE_REFRELE_NOTR(ire);
4567 
4568 	/* Need to cleanup any pending ioctls */
4569 	ASSERT(tcp->tcp_time_wait_next == NULL);
4570 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4571 	ASSERT(tcp->tcp_time_wait_expire == 0);
4572 	tcp->tcp_state = TCPS_CLOSED;
4573 
4574 	/* Release any SSL context */
4575 	if (tcp->tcp_kssl_ent != NULL) {
4576 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4577 		tcp->tcp_kssl_ent = NULL;
4578 	}
4579 	if (tcp->tcp_kssl_ctx != NULL) {
4580 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4581 		tcp->tcp_kssl_ctx = NULL;
4582 	}
4583 	tcp->tcp_kssl_pending = B_FALSE;
4584 
4585 	tcp_ipsec_cleanup(tcp);
4586 }
4587 
4588 /*
4589  * tcp is dying (called from ipcl_conn_destroy and error cases).
4590  * Free the tcp_t in either case.
4591  */
4592 void
4593 tcp_free(tcp_t *tcp)
4594 {
4595 	mblk_t	*mp;
4596 	ip6_pkt_t	*ipp;
4597 
4598 	ASSERT(tcp != NULL);
4599 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4600 
4601 	tcp->tcp_rq = NULL;
4602 	tcp->tcp_wq = NULL;
4603 
4604 	tcp_close_mpp(&tcp->tcp_xmit_head);
4605 	tcp_close_mpp(&tcp->tcp_reass_head);
4606 	if (tcp->tcp_rcv_list != NULL) {
4607 		/* Free b_next chain */
4608 		tcp_close_mpp(&tcp->tcp_rcv_list);
4609 	}
4610 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4611 		freemsg(mp);
4612 	}
4613 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4614 		freemsg(mp);
4615 	}
4616 
4617 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4618 		freeb(tcp->tcp_fused_sigurg_mp);
4619 		tcp->tcp_fused_sigurg_mp = NULL;
4620 	}
4621 
4622 	if (tcp->tcp_ordrel_mp != NULL) {
4623 		freeb(tcp->tcp_ordrel_mp);
4624 		tcp->tcp_ordrel_mp = NULL;
4625 	}
4626 
4627 	if (tcp->tcp_ordrel_mp != NULL) {
4628 		freeb(tcp->tcp_ordrel_mp);
4629 		tcp->tcp_ordrel_mp = NULL;
4630 	}
4631 
4632 	if (tcp->tcp_sack_info != NULL) {
4633 		if (tcp->tcp_notsack_list != NULL) {
4634 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4635 		}
4636 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4637 	}
4638 
4639 	if (tcp->tcp_hopopts != NULL) {
4640 		mi_free(tcp->tcp_hopopts);
4641 		tcp->tcp_hopopts = NULL;
4642 		tcp->tcp_hopoptslen = 0;
4643 	}
4644 	ASSERT(tcp->tcp_hopoptslen == 0);
4645 	if (tcp->tcp_dstopts != NULL) {
4646 		mi_free(tcp->tcp_dstopts);
4647 		tcp->tcp_dstopts = NULL;
4648 		tcp->tcp_dstoptslen = 0;
4649 	}
4650 	ASSERT(tcp->tcp_dstoptslen == 0);
4651 	if (tcp->tcp_rtdstopts != NULL) {
4652 		mi_free(tcp->tcp_rtdstopts);
4653 		tcp->tcp_rtdstopts = NULL;
4654 		tcp->tcp_rtdstoptslen = 0;
4655 	}
4656 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4657 	if (tcp->tcp_rthdr != NULL) {
4658 		mi_free(tcp->tcp_rthdr);
4659 		tcp->tcp_rthdr = NULL;
4660 		tcp->tcp_rthdrlen = 0;
4661 	}
4662 	ASSERT(tcp->tcp_rthdrlen == 0);
4663 
4664 	ipp = &tcp->tcp_sticky_ipp;
4665 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4666 	    IPPF_RTHDR))
4667 		ip6_pkt_free(ipp);
4668 
4669 	/*
4670 	 * Free memory associated with the tcp/ip header template.
4671 	 */
4672 
4673 	if (tcp->tcp_iphc != NULL)
4674 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4675 
4676 	/*
4677 	 * Following is really a blowing away a union.
4678 	 * It happens to have exactly two members of identical size
4679 	 * the following code is enough.
4680 	 */
4681 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4682 }
4683 
4684 
4685 /*
4686  * Put a connection confirmation message upstream built from the
4687  * address information within 'iph' and 'tcph'.  Report our success or failure.
4688  */
4689 static boolean_t
4690 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4691     mblk_t **defermp)
4692 {
4693 	sin_t	sin;
4694 	sin6_t	sin6;
4695 	mblk_t	*mp;
4696 	char	*optp = NULL;
4697 	int	optlen = 0;
4698 	cred_t	*cr;
4699 
4700 	if (defermp != NULL)
4701 		*defermp = NULL;
4702 
4703 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4704 		/*
4705 		 * Return in T_CONN_CON results of option negotiation through
4706 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4707 		 * negotiation, then what is received from remote end needs
4708 		 * to be taken into account but there is no such thing (yet?)
4709 		 * in our TCP/IP.
4710 		 * Note: We do not use mi_offset_param() here as
4711 		 * tcp_opts_conn_req contents do not directly come from
4712 		 * an application and are either generated in kernel or
4713 		 * from user input that was already verified.
4714 		 */
4715 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4716 		optp = (char *)(mp->b_rptr +
4717 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4718 		optlen = (int)
4719 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4720 	}
4721 
4722 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4723 		ipha_t *ipha = (ipha_t *)iphdr;
4724 
4725 		/* packet is IPv4 */
4726 		if (tcp->tcp_family == AF_INET) {
4727 			sin = sin_null;
4728 			sin.sin_addr.s_addr = ipha->ipha_src;
4729 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4730 			sin.sin_family = AF_INET;
4731 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4732 			    (int)sizeof (sin_t), optp, optlen);
4733 		} else {
4734 			sin6 = sin6_null;
4735 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4736 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4737 			sin6.sin6_family = AF_INET6;
4738 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4739 			    (int)sizeof (sin6_t), optp, optlen);
4740 
4741 		}
4742 	} else {
4743 		ip6_t	*ip6h = (ip6_t *)iphdr;
4744 
4745 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4746 		ASSERT(tcp->tcp_family == AF_INET6);
4747 		sin6 = sin6_null;
4748 		sin6.sin6_addr = ip6h->ip6_src;
4749 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4750 		sin6.sin6_family = AF_INET6;
4751 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4752 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4753 		    (int)sizeof (sin6_t), optp, optlen);
4754 	}
4755 
4756 	if (!mp)
4757 		return (B_FALSE);
4758 
4759 	if ((cr = DB_CRED(idmp)) != NULL) {
4760 		mblk_setcred(mp, cr);
4761 		DB_CPID(mp) = DB_CPID(idmp);
4762 	}
4763 
4764 	if (defermp == NULL)
4765 		putnext(tcp->tcp_rq, mp);
4766 	else
4767 		*defermp = mp;
4768 
4769 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4770 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4771 	return (B_TRUE);
4772 }
4773 
4774 /*
4775  * Defense for the SYN attack -
4776  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4777  *    one from the list of droppable eagers. This list is a subset of q0.
4778  *    see comments before the definition of MAKE_DROPPABLE().
4779  * 2. Don't drop a SYN request before its first timeout. This gives every
4780  *    request at least til the first timeout to complete its 3-way handshake.
4781  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4782  *    requests currently on the queue that has timed out. This will be used
4783  *    as an indicator of whether an attack is under way, so that appropriate
4784  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4785  *    either when eager goes into ESTABLISHED, or gets freed up.)
4786  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4787  *    # of timeout drops back to <= q0len/32 => SYN alert off
4788  */
4789 static boolean_t
4790 tcp_drop_q0(tcp_t *tcp)
4791 {
4792 	tcp_t	*eager;
4793 	mblk_t	*mp;
4794 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4795 
4796 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4797 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4798 
4799 	/* Pick oldest eager from the list of droppable eagers */
4800 	eager = tcp->tcp_eager_prev_drop_q0;
4801 
4802 	/* If list is empty. return B_FALSE */
4803 	if (eager == tcp) {
4804 		return (B_FALSE);
4805 	}
4806 
4807 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4808 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4809 		return (B_FALSE);
4810 
4811 	/*
4812 	 * Take this eager out from the list of droppable eagers since we are
4813 	 * going to drop it.
4814 	 */
4815 	MAKE_UNDROPPABLE(eager);
4816 
4817 	if (tcp->tcp_debug) {
4818 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4819 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4820 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4821 		    tcp->tcp_conn_req_cnt_q0,
4822 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4823 	}
4824 
4825 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4826 
4827 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4828 	CONN_INC_REF(eager->tcp_connp);
4829 
4830 	/* Mark the IRE created for this SYN request temporary */
4831 	tcp_ip_ire_mark_advice(eager);
4832 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4833 	    tcp_clean_death_wrapper, eager->tcp_connp,
4834 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4835 
4836 	return (B_TRUE);
4837 }
4838 
4839 int
4840 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4841     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4842 {
4843 	tcp_t 		*ltcp = lconnp->conn_tcp;
4844 	tcp_t		*tcp = connp->conn_tcp;
4845 	mblk_t		*tpi_mp;
4846 	ipha_t		*ipha;
4847 	ip6_t		*ip6h;
4848 	sin6_t 		sin6;
4849 	in6_addr_t 	v6dst;
4850 	int		err;
4851 	int		ifindex = 0;
4852 	cred_t		*cr;
4853 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4854 
4855 	if (ipvers == IPV4_VERSION) {
4856 		ipha = (ipha_t *)mp->b_rptr;
4857 
4858 		connp->conn_send = ip_output;
4859 		connp->conn_recv = tcp_input;
4860 
4861 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4862 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4863 
4864 		sin6 = sin6_null;
4865 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4866 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4867 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4868 		sin6.sin6_family = AF_INET6;
4869 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4870 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4871 		if (tcp->tcp_recvdstaddr) {
4872 			sin6_t	sin6d;
4873 
4874 			sin6d = sin6_null;
4875 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4876 			    &sin6d.sin6_addr);
4877 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4878 			sin6d.sin6_family = AF_INET;
4879 			tpi_mp = mi_tpi_extconn_ind(NULL,
4880 			    (char *)&sin6d, sizeof (sin6_t),
4881 			    (char *)&tcp,
4882 			    (t_scalar_t)sizeof (intptr_t),
4883 			    (char *)&sin6d, sizeof (sin6_t),
4884 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4885 		} else {
4886 			tpi_mp = mi_tpi_conn_ind(NULL,
4887 			    (char *)&sin6, sizeof (sin6_t),
4888 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4889 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4890 		}
4891 	} else {
4892 		ip6h = (ip6_t *)mp->b_rptr;
4893 
4894 		connp->conn_send = ip_output_v6;
4895 		connp->conn_recv = tcp_input;
4896 
4897 		connp->conn_srcv6 = ip6h->ip6_dst;
4898 		connp->conn_remv6 = ip6h->ip6_src;
4899 
4900 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4901 		ifindex = (int)DB_CKSUMSTUFF(mp);
4902 		DB_CKSUMSTUFF(mp) = 0;
4903 
4904 		sin6 = sin6_null;
4905 		sin6.sin6_addr = ip6h->ip6_src;
4906 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4907 		sin6.sin6_family = AF_INET6;
4908 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4909 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4910 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4911 
4912 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4913 			/* Pass up the scope_id of remote addr */
4914 			sin6.sin6_scope_id = ifindex;
4915 		} else {
4916 			sin6.sin6_scope_id = 0;
4917 		}
4918 		if (tcp->tcp_recvdstaddr) {
4919 			sin6_t	sin6d;
4920 
4921 			sin6d = sin6_null;
4922 			sin6.sin6_addr = ip6h->ip6_dst;
4923 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4924 			sin6d.sin6_family = AF_INET;
4925 			tpi_mp = mi_tpi_extconn_ind(NULL,
4926 			    (char *)&sin6d, sizeof (sin6_t),
4927 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4928 			    (char *)&sin6d, sizeof (sin6_t),
4929 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4930 		} else {
4931 			tpi_mp = mi_tpi_conn_ind(NULL,
4932 			    (char *)&sin6, sizeof (sin6_t),
4933 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4934 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4935 		}
4936 	}
4937 
4938 	if (tpi_mp == NULL)
4939 		return (ENOMEM);
4940 
4941 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4942 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4943 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4944 	connp->conn_fully_bound = B_FALSE;
4945 
4946 	/* Inherit information from the "parent" */
4947 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4948 	tcp->tcp_family = ltcp->tcp_family;
4949 	tcp->tcp_wq = ltcp->tcp_wq;
4950 	tcp->tcp_rq = ltcp->tcp_rq;
4951 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4952 	tcp->tcp_detached = B_TRUE;
4953 	if ((err = tcp_init_values(tcp)) != 0) {
4954 		freemsg(tpi_mp);
4955 		return (err);
4956 	}
4957 
4958 	if (ipvers == IPV4_VERSION) {
4959 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4960 			freemsg(tpi_mp);
4961 			return (err);
4962 		}
4963 		ASSERT(tcp->tcp_ipha != NULL);
4964 	} else {
4965 		/* ifindex must be already set */
4966 		ASSERT(ifindex != 0);
4967 
4968 		if (ltcp->tcp_bound_if != 0) {
4969 			/*
4970 			 * Set newtcp's bound_if equal to
4971 			 * listener's value. If ifindex is
4972 			 * not the same as ltcp->tcp_bound_if,
4973 			 * it must be a packet for the ipmp group
4974 			 * of interfaces
4975 			 */
4976 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4977 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4978 			tcp->tcp_bound_if = ifindex;
4979 		}
4980 
4981 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4982 		tcp->tcp_recvifindex = 0;
4983 		tcp->tcp_recvhops = 0xffffffffU;
4984 		ASSERT(tcp->tcp_ip6h != NULL);
4985 	}
4986 
4987 	tcp->tcp_lport = ltcp->tcp_lport;
4988 
4989 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4990 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4991 			/*
4992 			 * Listener had options of some sort; eager inherits.
4993 			 * Free up the eager template and allocate one
4994 			 * of the right size.
4995 			 */
4996 			if (tcp->tcp_hdr_grown) {
4997 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4998 			} else {
4999 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
5000 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
5001 			}
5002 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
5003 			    KM_NOSLEEP);
5004 			if (tcp->tcp_iphc == NULL) {
5005 				tcp->tcp_iphc_len = 0;
5006 				freemsg(tpi_mp);
5007 				return (ENOMEM);
5008 			}
5009 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
5010 			tcp->tcp_hdr_grown = B_TRUE;
5011 		}
5012 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5013 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5014 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5015 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
5016 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
5017 
5018 		/*
5019 		 * Copy the IP+TCP header template from listener to eager
5020 		 */
5021 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5022 		if (tcp->tcp_ipversion == IPV6_VERSION) {
5023 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
5024 			    IPPROTO_RAW) {
5025 				tcp->tcp_ip6h =
5026 				    (ip6_t *)(tcp->tcp_iphc +
5027 				    sizeof (ip6i_t));
5028 			} else {
5029 				tcp->tcp_ip6h =
5030 				    (ip6_t *)(tcp->tcp_iphc);
5031 			}
5032 			tcp->tcp_ipha = NULL;
5033 		} else {
5034 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5035 			tcp->tcp_ip6h = NULL;
5036 		}
5037 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5038 		    tcp->tcp_ip_hdr_len);
5039 	} else {
5040 		/*
5041 		 * only valid case when ipversion of listener and
5042 		 * eager differ is when listener is IPv6 and
5043 		 * eager is IPv4.
5044 		 * Eager header template has been initialized to the
5045 		 * maximum v4 header sizes, which includes space for
5046 		 * TCP and IP options.
5047 		 */
5048 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5049 		    (tcp->tcp_ipversion == IPV4_VERSION));
5050 		ASSERT(tcp->tcp_iphc_len >=
5051 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5052 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5053 		/* copy IP header fields individually */
5054 		tcp->tcp_ipha->ipha_ttl =
5055 		    ltcp->tcp_ip6h->ip6_hops;
5056 		bcopy(ltcp->tcp_tcph->th_lport,
5057 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5058 	}
5059 
5060 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5061 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5062 	    sizeof (in_port_t));
5063 
5064 	if (ltcp->tcp_lport == 0) {
5065 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5066 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5067 		    sizeof (in_port_t));
5068 	}
5069 
5070 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5071 		ASSERT(ipha != NULL);
5072 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5073 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5074 
5075 		/* Source routing option copyover (reverse it) */
5076 		if (tcps->tcps_rev_src_routes)
5077 			tcp_opt_reverse(tcp, ipha);
5078 	} else {
5079 		ASSERT(ip6h != NULL);
5080 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5081 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5082 	}
5083 
5084 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5085 	ASSERT(!tcp->tcp_tconnind_started);
5086 	/*
5087 	 * If the SYN contains a credential, it's a loopback packet; attach
5088 	 * the credential to the TPI message.
5089 	 */
5090 	if ((cr = DB_CRED(idmp)) != NULL) {
5091 		mblk_setcred(tpi_mp, cr);
5092 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5093 	}
5094 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5095 
5096 	/* Inherit the listener's SSL protection state */
5097 
5098 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5099 		kssl_hold_ent(tcp->tcp_kssl_ent);
5100 		tcp->tcp_kssl_pending = B_TRUE;
5101 	}
5102 
5103 	return (0);
5104 }
5105 
5106 
5107 int
5108 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5109     tcph_t *tcph, mblk_t *idmp)
5110 {
5111 	tcp_t 		*ltcp = lconnp->conn_tcp;
5112 	tcp_t		*tcp = connp->conn_tcp;
5113 	sin_t		sin;
5114 	mblk_t		*tpi_mp = NULL;
5115 	int		err;
5116 	cred_t		*cr;
5117 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5118 
5119 	sin = sin_null;
5120 	sin.sin_addr.s_addr = ipha->ipha_src;
5121 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5122 	sin.sin_family = AF_INET;
5123 	if (ltcp->tcp_recvdstaddr) {
5124 		sin_t	sind;
5125 
5126 		sind = sin_null;
5127 		sind.sin_addr.s_addr = ipha->ipha_dst;
5128 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5129 		sind.sin_family = AF_INET;
5130 		tpi_mp = mi_tpi_extconn_ind(NULL,
5131 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5132 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5133 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5134 	} else {
5135 		tpi_mp = mi_tpi_conn_ind(NULL,
5136 		    (char *)&sin, sizeof (sin_t),
5137 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5138 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5139 	}
5140 
5141 	if (tpi_mp == NULL) {
5142 		return (ENOMEM);
5143 	}
5144 
5145 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5146 	connp->conn_send = ip_output;
5147 	connp->conn_recv = tcp_input;
5148 	connp->conn_fully_bound = B_FALSE;
5149 
5150 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5151 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5152 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5153 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5154 
5155 	/* Inherit information from the "parent" */
5156 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5157 	tcp->tcp_family = ltcp->tcp_family;
5158 	tcp->tcp_wq = ltcp->tcp_wq;
5159 	tcp->tcp_rq = ltcp->tcp_rq;
5160 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
5161 	tcp->tcp_detached = B_TRUE;
5162 	if ((err = tcp_init_values(tcp)) != 0) {
5163 		freemsg(tpi_mp);
5164 		return (err);
5165 	}
5166 
5167 	/*
5168 	 * Let's make sure that eager tcp template has enough space to
5169 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5170 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5171 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5172 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5173 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5174 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5175 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5176 	 */
5177 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5178 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5179 
5180 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5181 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5182 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5183 	tcp->tcp_ttl = ltcp->tcp_ttl;
5184 	tcp->tcp_tos = ltcp->tcp_tos;
5185 
5186 	/* Copy the IP+TCP header template from listener to eager */
5187 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5188 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5189 	tcp->tcp_ip6h = NULL;
5190 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5191 	    tcp->tcp_ip_hdr_len);
5192 
5193 	/* Initialize the IP addresses and Ports */
5194 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5195 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5196 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5197 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5198 
5199 	/* Source routing option copyover (reverse it) */
5200 	if (tcps->tcps_rev_src_routes)
5201 		tcp_opt_reverse(tcp, ipha);
5202 
5203 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5204 	ASSERT(!tcp->tcp_tconnind_started);
5205 
5206 	/*
5207 	 * If the SYN contains a credential, it's a loopback packet; attach
5208 	 * the credential to the TPI message.
5209 	 */
5210 	if ((cr = DB_CRED(idmp)) != NULL) {
5211 		mblk_setcred(tpi_mp, cr);
5212 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5213 	}
5214 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5215 
5216 	/* Inherit the listener's SSL protection state */
5217 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5218 		kssl_hold_ent(tcp->tcp_kssl_ent);
5219 		tcp->tcp_kssl_pending = B_TRUE;
5220 	}
5221 
5222 	return (0);
5223 }
5224 
5225 /*
5226  * sets up conn for ipsec.
5227  * if the first mblk is M_CTL it is consumed and mpp is updated.
5228  * in case of error mpp is freed.
5229  */
5230 conn_t *
5231 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5232 {
5233 	conn_t 		*connp = tcp->tcp_connp;
5234 	conn_t 		*econnp;
5235 	squeue_t 	*new_sqp;
5236 	mblk_t 		*first_mp = *mpp;
5237 	mblk_t		*mp = *mpp;
5238 	boolean_t	mctl_present = B_FALSE;
5239 	uint_t		ipvers;
5240 
5241 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
5242 	if (econnp == NULL) {
5243 		freemsg(first_mp);
5244 		return (NULL);
5245 	}
5246 	if (DB_TYPE(mp) == M_CTL) {
5247 		if (mp->b_cont == NULL ||
5248 		    mp->b_cont->b_datap->db_type != M_DATA) {
5249 			freemsg(first_mp);
5250 			return (NULL);
5251 		}
5252 		mp = mp->b_cont;
5253 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5254 			freemsg(first_mp);
5255 			return (NULL);
5256 		}
5257 
5258 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5259 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5260 		mctl_present = B_TRUE;
5261 	} else {
5262 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5263 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5264 	}
5265 
5266 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5267 	DB_CKSUMSTART(mp) = 0;
5268 
5269 	ASSERT(OK_32PTR(mp->b_rptr));
5270 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5271 	if (ipvers == IPV4_VERSION) {
5272 		uint16_t  	*up;
5273 		uint32_t	ports;
5274 		ipha_t		*ipha;
5275 
5276 		ipha = (ipha_t *)mp->b_rptr;
5277 		up = (uint16_t *)((uchar_t *)ipha +
5278 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5279 		ports = *(uint32_t *)up;
5280 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5281 		    ipha->ipha_dst, ipha->ipha_src, ports);
5282 	} else {
5283 		uint16_t  	*up;
5284 		uint32_t	ports;
5285 		uint16_t	ip_hdr_len;
5286 		uint8_t		*nexthdrp;
5287 		ip6_t 		*ip6h;
5288 		tcph_t		*tcph;
5289 
5290 		ip6h = (ip6_t *)mp->b_rptr;
5291 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5292 			ip_hdr_len = IPV6_HDR_LEN;
5293 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5294 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5295 			CONN_DEC_REF(econnp);
5296 			freemsg(first_mp);
5297 			return (NULL);
5298 		}
5299 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5300 		up = (uint16_t *)tcph->th_lport;
5301 		ports = *(uint32_t *)up;
5302 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5303 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5304 	}
5305 
5306 	/*
5307 	 * The caller already ensured that there is a sqp present.
5308 	 */
5309 	econnp->conn_sqp = new_sqp;
5310 	econnp->conn_initial_sqp = new_sqp;
5311 
5312 	if (connp->conn_policy != NULL) {
5313 		ipsec_in_t *ii;
5314 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5315 		ASSERT(ii->ipsec_in_policy == NULL);
5316 		IPPH_REFHOLD(connp->conn_policy);
5317 		ii->ipsec_in_policy = connp->conn_policy;
5318 
5319 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5320 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5321 			CONN_DEC_REF(econnp);
5322 			freemsg(first_mp);
5323 			return (NULL);
5324 		}
5325 	}
5326 
5327 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5328 		CONN_DEC_REF(econnp);
5329 		freemsg(first_mp);
5330 		return (NULL);
5331 	}
5332 
5333 	/*
5334 	 * If we know we have some policy, pass the "IPSEC"
5335 	 * options size TCP uses this adjust the MSS.
5336 	 */
5337 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5338 	if (mctl_present) {
5339 		freeb(first_mp);
5340 		*mpp = mp;
5341 	}
5342 
5343 	return (econnp);
5344 }
5345 
5346 /*
5347  * tcp_get_conn/tcp_free_conn
5348  *
5349  * tcp_get_conn is used to get a clean tcp connection structure.
5350  * It tries to reuse the connections put on the freelist by the
5351  * time_wait_collector failing which it goes to kmem_cache. This
5352  * way has two benefits compared to just allocating from and
5353  * freeing to kmem_cache.
5354  * 1) The time_wait_collector can free (which includes the cleanup)
5355  * outside the squeue. So when the interrupt comes, we have a clean
5356  * connection sitting in the freelist. Obviously, this buys us
5357  * performance.
5358  *
5359  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5360  * has multiple disadvantages - tying up the squeue during alloc, and the
5361  * fact that IPSec policy initialization has to happen here which
5362  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5363  * But allocating the conn/tcp in IP land is also not the best since
5364  * we can't check the 'q' and 'q0' which are protected by squeue and
5365  * blindly allocate memory which might have to be freed here if we are
5366  * not allowed to accept the connection. By using the freelist and
5367  * putting the conn/tcp back in freelist, we don't pay a penalty for
5368  * allocating memory without checking 'q/q0' and freeing it if we can't
5369  * accept the connection.
5370  *
5371  * Care should be taken to put the conn back in the same squeue's freelist
5372  * from which it was allocated. Best results are obtained if conn is
5373  * allocated from listener's squeue and freed to the same. Time wait
5374  * collector will free up the freelist is the connection ends up sitting
5375  * there for too long.
5376  */
5377 void *
5378 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5379 {
5380 	tcp_t			*tcp = NULL;
5381 	conn_t			*connp = NULL;
5382 	squeue_t		*sqp = (squeue_t *)arg;
5383 	tcp_squeue_priv_t 	*tcp_time_wait;
5384 	netstack_t		*ns;
5385 
5386 	tcp_time_wait =
5387 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5388 
5389 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5390 	tcp = tcp_time_wait->tcp_free_list;
5391 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5392 	if (tcp != NULL) {
5393 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5394 		tcp_time_wait->tcp_free_list_cnt--;
5395 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5396 		tcp->tcp_time_wait_next = NULL;
5397 		connp = tcp->tcp_connp;
5398 		connp->conn_flags |= IPCL_REUSED;
5399 
5400 		ASSERT(tcp->tcp_tcps == NULL);
5401 		ASSERT(connp->conn_netstack == NULL);
5402 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5403 		ns = tcps->tcps_netstack;
5404 		netstack_hold(ns);
5405 		connp->conn_netstack = ns;
5406 		tcp->tcp_tcps = tcps;
5407 		TCPS_REFHOLD(tcps);
5408 		ipcl_globalhash_insert(connp);
5409 		return ((void *)connp);
5410 	}
5411 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5412 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5413 	    tcps->tcps_netstack)) == NULL)
5414 		return (NULL);
5415 	tcp = connp->conn_tcp;
5416 	/*
5417 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5418 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5419 	 */
5420 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5421 		ipcl_conn_destroy(connp);
5422 		return (NULL);
5423 	}
5424 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5425 	tcp->tcp_tcps = tcps;
5426 	TCPS_REFHOLD(tcps);
5427 
5428 	return ((void *)connp);
5429 }
5430 
5431 /*
5432  * Update the cached label for the given tcp_t.  This should be called once per
5433  * connection, and before any packets are sent or tcp_process_options is
5434  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5435  */
5436 static boolean_t
5437 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5438 {
5439 	conn_t *connp = tcp->tcp_connp;
5440 
5441 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5442 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5443 		int added;
5444 
5445 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5446 		    connp->conn_mac_exempt,
5447 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5448 			return (B_FALSE);
5449 
5450 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5451 		if (added == -1)
5452 			return (B_FALSE);
5453 		tcp->tcp_hdr_len += added;
5454 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5455 		tcp->tcp_ip_hdr_len += added;
5456 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5457 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5458 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5459 			    tcp->tcp_hdr_len);
5460 			if (added == -1)
5461 				return (B_FALSE);
5462 			tcp->tcp_hdr_len += added;
5463 			tcp->tcp_tcph = (tcph_t *)
5464 			    ((uchar_t *)tcp->tcp_tcph + added);
5465 			tcp->tcp_ip_hdr_len += added;
5466 		}
5467 	} else {
5468 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5469 
5470 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5471 		    connp->conn_mac_exempt,
5472 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5473 			return (B_FALSE);
5474 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5475 		    &tcp->tcp_label_len, optbuf) != 0)
5476 			return (B_FALSE);
5477 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5478 			return (B_FALSE);
5479 	}
5480 
5481 	connp->conn_ulp_labeled = 1;
5482 
5483 	return (B_TRUE);
5484 }
5485 
5486 /* BEGIN CSTYLED */
5487 /*
5488  *
5489  * The sockfs ACCEPT path:
5490  * =======================
5491  *
5492  * The eager is now established in its own perimeter as soon as SYN is
5493  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5494  * completes the accept processing on the acceptor STREAM. The sending
5495  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5496  * listener but a TLI/XTI listener completes the accept processing
5497  * on the listener perimeter.
5498  *
5499  * Common control flow for 3 way handshake:
5500  * ----------------------------------------
5501  *
5502  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5503  *					-> tcp_conn_request()
5504  *
5505  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5506  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5507  *
5508  * Sockfs ACCEPT Path:
5509  * -------------------
5510  *
5511  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5512  * as STREAM entry point)
5513  *
5514  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5515  *
5516  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5517  * association (we are not behind eager's squeue but sockfs is protecting us
5518  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5519  * is changed to point at tcp_wput().
5520  *
5521  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5522  * listener (done on listener's perimeter).
5523  *
5524  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5525  * accept.
5526  *
5527  * TLI/XTI client ACCEPT path:
5528  * ---------------------------
5529  *
5530  * soaccept() sends T_CONN_RES on the listener STREAM.
5531  *
5532  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5533  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5534  *
5535  * Locks:
5536  * ======
5537  *
5538  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5539  * and listeners->tcp_eager_next_q.
5540  *
5541  * Referencing:
5542  * ============
5543  *
5544  * 1) We start out in tcp_conn_request by eager placing a ref on
5545  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5546  *
5547  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5548  * doing so we place a ref on the eager. This ref is finally dropped at the
5549  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5550  * reference is dropped by the squeue framework.
5551  *
5552  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5553  *
5554  * The reference must be released by the same entity that added the reference
5555  * In the above scheme, the eager is the entity that adds and releases the
5556  * references. Note that tcp_accept_finish executes in the squeue of the eager
5557  * (albeit after it is attached to the acceptor stream). Though 1. executes
5558  * in the listener's squeue, the eager is nascent at this point and the
5559  * reference can be considered to have been added on behalf of the eager.
5560  *
5561  * Eager getting a Reset or listener closing:
5562  * ==========================================
5563  *
5564  * Once the listener and eager are linked, the listener never does the unlink.
5565  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5566  * a message on all eager perimeter. The eager then does the unlink, clears
5567  * any pointers to the listener's queue and drops the reference to the
5568  * listener. The listener waits in tcp_close outside the squeue until its
5569  * refcount has dropped to 1. This ensures that the listener has waited for
5570  * all eagers to clear their association with the listener.
5571  *
5572  * Similarly, if eager decides to go away, it can unlink itself and close.
5573  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5574  * the reference to eager is still valid because of the extra ref we put
5575  * in tcp_send_conn_ind.
5576  *
5577  * Listener can always locate the eager under the protection
5578  * of the listener->tcp_eager_lock, and then do a refhold
5579  * on the eager during the accept processing.
5580  *
5581  * The acceptor stream accesses the eager in the accept processing
5582  * based on the ref placed on eager before sending T_conn_ind.
5583  * The only entity that can negate this refhold is a listener close
5584  * which is mutually exclusive with an active acceptor stream.
5585  *
5586  * Eager's reference on the listener
5587  * ===================================
5588  *
5589  * If the accept happens (even on a closed eager) the eager drops its
5590  * reference on the listener at the start of tcp_accept_finish. If the
5591  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5592  * the reference is dropped in tcp_closei_local. If the listener closes,
5593  * the reference is dropped in tcp_eager_kill. In all cases the reference
5594  * is dropped while executing in the eager's context (squeue).
5595  */
5596 /* END CSTYLED */
5597 
5598 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5599 
5600 /*
5601  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5602  * tcp_rput_data will not see any SYN packets.
5603  */
5604 /* ARGSUSED */
5605 void
5606 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5607 {
5608 	tcph_t		*tcph;
5609 	uint32_t	seg_seq;
5610 	tcp_t		*eager;
5611 	uint_t		ipvers;
5612 	ipha_t		*ipha;
5613 	ip6_t		*ip6h;
5614 	int		err;
5615 	conn_t		*econnp = NULL;
5616 	squeue_t	*new_sqp;
5617 	mblk_t		*mp1;
5618 	uint_t 		ip_hdr_len;
5619 	conn_t		*connp = (conn_t *)arg;
5620 	tcp_t		*tcp = connp->conn_tcp;
5621 	cred_t		*credp;
5622 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5623 	ip_stack_t	*ipst;
5624 
5625 	if (tcp->tcp_state != TCPS_LISTEN)
5626 		goto error2;
5627 
5628 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5629 
5630 	mutex_enter(&tcp->tcp_eager_lock);
5631 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5632 		mutex_exit(&tcp->tcp_eager_lock);
5633 		TCP_STAT(tcps, tcp_listendrop);
5634 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5635 		if (tcp->tcp_debug) {
5636 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5637 			    "tcp_conn_request: listen backlog (max=%d) "
5638 			    "overflow (%d pending) on %s",
5639 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5640 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5641 		}
5642 		goto error2;
5643 	}
5644 
5645 	if (tcp->tcp_conn_req_cnt_q0 >=
5646 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5647 		/*
5648 		 * Q0 is full. Drop a pending half-open req from the queue
5649 		 * to make room for the new SYN req. Also mark the time we
5650 		 * drop a SYN.
5651 		 *
5652 		 * A more aggressive defense against SYN attack will
5653 		 * be to set the "tcp_syn_defense" flag now.
5654 		 */
5655 		TCP_STAT(tcps, tcp_listendropq0);
5656 		tcp->tcp_last_rcv_lbolt = lbolt64;
5657 		if (!tcp_drop_q0(tcp)) {
5658 			mutex_exit(&tcp->tcp_eager_lock);
5659 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5660 			if (tcp->tcp_debug) {
5661 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5662 				    "tcp_conn_request: listen half-open queue "
5663 				    "(max=%d) full (%d pending) on %s",
5664 				    tcps->tcps_conn_req_max_q0,
5665 				    tcp->tcp_conn_req_cnt_q0,
5666 				    tcp_display(tcp, NULL,
5667 				    DISP_PORT_ONLY));
5668 			}
5669 			goto error2;
5670 		}
5671 	}
5672 	mutex_exit(&tcp->tcp_eager_lock);
5673 
5674 	/*
5675 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5676 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5677 	 * link local address.  If IPSec is enabled, db_struioflag has
5678 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5679 	 * otherwise an error case if neither of them is set.
5680 	 */
5681 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5682 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5683 		DB_CKSUMSTART(mp) = 0;
5684 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5685 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5686 		if (econnp == NULL)
5687 			goto error2;
5688 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5689 		econnp->conn_sqp = new_sqp;
5690 		econnp->conn_initial_sqp = new_sqp;
5691 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5692 		/*
5693 		 * mp is updated in tcp_get_ipsec_conn().
5694 		 */
5695 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5696 		if (econnp == NULL) {
5697 			/*
5698 			 * mp freed by tcp_get_ipsec_conn.
5699 			 */
5700 			return;
5701 		}
5702 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5703 	} else {
5704 		goto error2;
5705 	}
5706 
5707 	ASSERT(DB_TYPE(mp) == M_DATA);
5708 
5709 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5710 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5711 	ASSERT(OK_32PTR(mp->b_rptr));
5712 	if (ipvers == IPV4_VERSION) {
5713 		ipha = (ipha_t *)mp->b_rptr;
5714 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5715 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5716 	} else {
5717 		ip6h = (ip6_t *)mp->b_rptr;
5718 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5719 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5720 	}
5721 
5722 	if (tcp->tcp_family == AF_INET) {
5723 		ASSERT(ipvers == IPV4_VERSION);
5724 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5725 	} else {
5726 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5727 	}
5728 
5729 	if (err)
5730 		goto error3;
5731 
5732 	eager = econnp->conn_tcp;
5733 
5734 	/*
5735 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5736 	 * will always have that to send up.  Otherwise, we need to do
5737 	 * special handling in case the allocation fails at that time.
5738 	 */
5739 	ASSERT(eager->tcp_ordrel_mp == NULL);
5740 	if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5741 		goto error3;
5742 
5743 	/* Inherit various TCP parameters from the listener */
5744 	eager->tcp_naglim = tcp->tcp_naglim;
5745 	eager->tcp_first_timer_threshold =
5746 	    tcp->tcp_first_timer_threshold;
5747 	eager->tcp_second_timer_threshold =
5748 	    tcp->tcp_second_timer_threshold;
5749 
5750 	eager->tcp_first_ctimer_threshold =
5751 	    tcp->tcp_first_ctimer_threshold;
5752 	eager->tcp_second_ctimer_threshold =
5753 	    tcp->tcp_second_ctimer_threshold;
5754 
5755 	/*
5756 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5757 	 * If it does not, the eager's receive window will be set to the
5758 	 * listener's receive window later in this function.
5759 	 */
5760 	eager->tcp_rwnd = 0;
5761 
5762 	/*
5763 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5764 	 * calling tcp_process_options() where tcp_mss_set() is called
5765 	 * to set the initial cwnd.
5766 	 */
5767 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5768 
5769 	/*
5770 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5771 	 * zone id before the accept is completed in tcp_wput_accept().
5772 	 */
5773 	econnp->conn_zoneid = connp->conn_zoneid;
5774 	econnp->conn_allzones = connp->conn_allzones;
5775 
5776 	/* Copy nexthop information from listener to eager */
5777 	if (connp->conn_nexthop_set) {
5778 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5779 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5780 	}
5781 
5782 	/*
5783 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5784 	 * eager is accepted
5785 	 */
5786 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5787 	crhold(credp);
5788 
5789 	/*
5790 	 * If the caller has the process-wide flag set, then default to MAC
5791 	 * exempt mode.  This allows read-down to unlabeled hosts.
5792 	 */
5793 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5794 		econnp->conn_mac_exempt = B_TRUE;
5795 
5796 	if (is_system_labeled()) {
5797 		cred_t *cr;
5798 
5799 		if (connp->conn_mlp_type != mlptSingle) {
5800 			cr = econnp->conn_peercred = DB_CRED(mp);
5801 			if (cr != NULL)
5802 				crhold(cr);
5803 			else
5804 				cr = econnp->conn_cred;
5805 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5806 			    econnp, cred_t *, cr)
5807 		} else {
5808 			cr = econnp->conn_cred;
5809 			DTRACE_PROBE2(syn_accept, conn_t *,
5810 			    econnp, cred_t *, cr)
5811 		}
5812 
5813 		if (!tcp_update_label(eager, cr)) {
5814 			DTRACE_PROBE3(
5815 			    tx__ip__log__error__connrequest__tcp,
5816 			    char *, "eager connp(1) label on SYN mp(2) failed",
5817 			    conn_t *, econnp, mblk_t *, mp);
5818 			goto error3;
5819 		}
5820 	}
5821 
5822 	eager->tcp_hard_binding = B_TRUE;
5823 
5824 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5825 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5826 
5827 	CL_INET_CONNECT(eager);
5828 
5829 	/*
5830 	 * No need to check for multicast destination since ip will only pass
5831 	 * up multicasts to those that have expressed interest
5832 	 * TODO: what about rejecting broadcasts?
5833 	 * Also check that source is not a multicast or broadcast address.
5834 	 */
5835 	eager->tcp_state = TCPS_SYN_RCVD;
5836 
5837 
5838 	/*
5839 	 * There should be no ire in the mp as we are being called after
5840 	 * receiving the SYN.
5841 	 */
5842 	ASSERT(tcp_ire_mp(mp) == NULL);
5843 
5844 	/*
5845 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5846 	 */
5847 
5848 	if (tcp_adapt_ire(eager, NULL) == 0) {
5849 		/* Undo the bind_hash_insert */
5850 		tcp_bind_hash_remove(eager);
5851 		goto error3;
5852 	}
5853 
5854 	/* Process all TCP options. */
5855 	tcp_process_options(eager, tcph);
5856 
5857 	/* Is the other end ECN capable? */
5858 	if (tcps->tcps_ecn_permitted >= 1 &&
5859 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5860 		eager->tcp_ecn_ok = B_TRUE;
5861 	}
5862 
5863 	/*
5864 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5865 	 * window size changed via SO_RCVBUF option.  First round up the
5866 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5867 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5868 	 * setting.
5869 	 *
5870 	 * Note if there is a rpipe metric associated with the remote host,
5871 	 * we should not inherit receive window size from listener.
5872 	 */
5873 	eager->tcp_rwnd = MSS_ROUNDUP(
5874 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5875 	    eager->tcp_rwnd), eager->tcp_mss);
5876 	if (eager->tcp_snd_ws_ok)
5877 		tcp_set_ws_value(eager);
5878 	/*
5879 	 * Note that this is the only place tcp_rwnd_set() is called for
5880 	 * accepting a connection.  We need to call it here instead of
5881 	 * after the 3-way handshake because we need to tell the other
5882 	 * side our rwnd in the SYN-ACK segment.
5883 	 */
5884 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5885 
5886 	/*
5887 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5888 	 * via soaccept()->soinheritoptions() which essentially applies
5889 	 * all the listener options to the new STREAM. The options that we
5890 	 * need to take care of are:
5891 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5892 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5893 	 * SO_SNDBUF, SO_RCVBUF.
5894 	 *
5895 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5896 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5897 	 *		tcp_maxpsz_set() gets called later from
5898 	 *		tcp_accept_finish(), the option takes effect.
5899 	 *
5900 	 */
5901 	/* Set the TCP options */
5902 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5903 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5904 	eager->tcp_oobinline = tcp->tcp_oobinline;
5905 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5906 	eager->tcp_broadcast = tcp->tcp_broadcast;
5907 	eager->tcp_useloopback = tcp->tcp_useloopback;
5908 	eager->tcp_dontroute = tcp->tcp_dontroute;
5909 	eager->tcp_linger = tcp->tcp_linger;
5910 	eager->tcp_lingertime = tcp->tcp_lingertime;
5911 	if (tcp->tcp_ka_enabled)
5912 		eager->tcp_ka_enabled = 1;
5913 
5914 	/* Set the IP options */
5915 	econnp->conn_broadcast = connp->conn_broadcast;
5916 	econnp->conn_loopback = connp->conn_loopback;
5917 	econnp->conn_dontroute = connp->conn_dontroute;
5918 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5919 
5920 	/* Put a ref on the listener for the eager. */
5921 	CONN_INC_REF(connp);
5922 	mutex_enter(&tcp->tcp_eager_lock);
5923 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5924 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5925 	tcp->tcp_eager_next_q0 = eager;
5926 	eager->tcp_eager_prev_q0 = tcp;
5927 
5928 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5929 	eager->tcp_listener = tcp;
5930 	eager->tcp_saved_listener = tcp;
5931 
5932 	/*
5933 	 * Tag this detached tcp vector for later retrieval
5934 	 * by our listener client in tcp_accept().
5935 	 */
5936 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5937 	tcp->tcp_conn_req_cnt_q0++;
5938 	if (++tcp->tcp_conn_req_seqnum == -1) {
5939 		/*
5940 		 * -1 is "special" and defined in TPI as something
5941 		 * that should never be used in T_CONN_IND
5942 		 */
5943 		++tcp->tcp_conn_req_seqnum;
5944 	}
5945 	mutex_exit(&tcp->tcp_eager_lock);
5946 
5947 	if (tcp->tcp_syn_defense) {
5948 		/* Don't drop the SYN that comes from a good IP source */
5949 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5950 		if (addr_cache != NULL && eager->tcp_remote ==
5951 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5952 			eager->tcp_dontdrop = B_TRUE;
5953 		}
5954 	}
5955 
5956 	/*
5957 	 * We need to insert the eager in its own perimeter but as soon
5958 	 * as we do that, we expose the eager to the classifier and
5959 	 * should not touch any field outside the eager's perimeter.
5960 	 * So do all the work necessary before inserting the eager
5961 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5962 	 * will succeed but undo everything if it fails.
5963 	 */
5964 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5965 	eager->tcp_irs = seg_seq;
5966 	eager->tcp_rack = seg_seq;
5967 	eager->tcp_rnxt = seg_seq + 1;
5968 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5969 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5970 	eager->tcp_state = TCPS_SYN_RCVD;
5971 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5972 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5973 	if (mp1 == NULL) {
5974 		/*
5975 		 * Increment the ref count as we are going to
5976 		 * enqueueing an mp in squeue
5977 		 */
5978 		CONN_INC_REF(econnp);
5979 		goto error;
5980 	}
5981 	DB_CPID(mp1) = tcp->tcp_cpid;
5982 	eager->tcp_cpid = tcp->tcp_cpid;
5983 	eager->tcp_open_time = lbolt64;
5984 
5985 	/*
5986 	 * We need to start the rto timer. In normal case, we start
5987 	 * the timer after sending the packet on the wire (or at
5988 	 * least believing that packet was sent by waiting for
5989 	 * CALL_IP_WPUT() to return). Since this is the first packet
5990 	 * being sent on the wire for the eager, our initial tcp_rto
5991 	 * is at least tcp_rexmit_interval_min which is a fairly
5992 	 * large value to allow the algorithm to adjust slowly to large
5993 	 * fluctuations of RTT during first few transmissions.
5994 	 *
5995 	 * Starting the timer first and then sending the packet in this
5996 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5997 	 * is of the order of several 100ms and starting the timer
5998 	 * first and then sending the packet will result in difference
5999 	 * of few micro seconds.
6000 	 *
6001 	 * Without this optimization, we are forced to hold the fanout
6002 	 * lock across the ipcl_bind_insert() and sending the packet
6003 	 * so that we don't race against an incoming packet (maybe RST)
6004 	 * for this eager.
6005 	 *
6006 	 * It is necessary to acquire an extra reference on the eager
6007 	 * at this point and hold it until after tcp_send_data() to
6008 	 * ensure against an eager close race.
6009 	 */
6010 
6011 	CONN_INC_REF(eager->tcp_connp);
6012 
6013 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
6014 
6015 	/*
6016 	 * Insert the eager in its own perimeter now. We are ready to deal
6017 	 * with any packets on eager.
6018 	 */
6019 	if (eager->tcp_ipversion == IPV4_VERSION) {
6020 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
6021 			goto error;
6022 		}
6023 	} else {
6024 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
6025 			goto error;
6026 		}
6027 	}
6028 
6029 	/* mark conn as fully-bound */
6030 	econnp->conn_fully_bound = B_TRUE;
6031 
6032 	/* Send the SYN-ACK */
6033 	tcp_send_data(eager, eager->tcp_wq, mp1);
6034 	CONN_DEC_REF(eager->tcp_connp);
6035 	freemsg(mp);
6036 
6037 	return;
6038 error:
6039 	freemsg(mp1);
6040 	eager->tcp_closemp_used = B_TRUE;
6041 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6042 	mp1 = &eager->tcp_closemp;
6043 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
6044 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
6045 
6046 	/*
6047 	 * If a connection already exists, send the mp to that connections so
6048 	 * that it can be appropriately dealt with.
6049 	 */
6050 	ipst = tcps->tcps_netstack->netstack_ip;
6051 
6052 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
6053 		if (!IPCL_IS_CONNECTED(econnp)) {
6054 			/*
6055 			 * Something bad happened. ipcl_conn_insert()
6056 			 * failed because a connection already existed
6057 			 * in connected hash but we can't find it
6058 			 * anymore (someone blew it away). Just
6059 			 * free this message and hopefully remote
6060 			 * will retransmit at which time the SYN can be
6061 			 * treated as a new connection or dealth with
6062 			 * a TH_RST if a connection already exists.
6063 			 */
6064 			CONN_DEC_REF(econnp);
6065 			freemsg(mp);
6066 		} else {
6067 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
6068 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
6069 		}
6070 	} else {
6071 		/* Nobody wants this packet */
6072 		freemsg(mp);
6073 	}
6074 	return;
6075 error3:
6076 	CONN_DEC_REF(econnp);
6077 error2:
6078 	freemsg(mp);
6079 }
6080 
6081 /*
6082  * In an ideal case of vertical partition in NUMA architecture, its
6083  * beneficial to have the listener and all the incoming connections
6084  * tied to the same squeue. The other constraint is that incoming
6085  * connections should be tied to the squeue attached to interrupted
6086  * CPU for obvious locality reason so this leaves the listener to
6087  * be tied to the same squeue. Our only problem is that when listener
6088  * is binding, the CPU that will get interrupted by the NIC whose
6089  * IP address the listener is binding to is not even known. So
6090  * the code below allows us to change that binding at the time the
6091  * CPU is interrupted by virtue of incoming connection's squeue.
6092  *
6093  * This is usefull only in case of a listener bound to a specific IP
6094  * address. For other kind of listeners, they get bound the
6095  * very first time and there is no attempt to rebind them.
6096  */
6097 void
6098 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6099 {
6100 	conn_t		*connp = (conn_t *)arg;
6101 	squeue_t	*sqp = (squeue_t *)arg2;
6102 	squeue_t	*new_sqp;
6103 	uint32_t	conn_flags;
6104 
6105 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6106 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
6107 	} else {
6108 		goto done;
6109 	}
6110 
6111 	if (connp->conn_fanout == NULL)
6112 		goto done;
6113 
6114 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6115 		mutex_enter(&connp->conn_fanout->connf_lock);
6116 		mutex_enter(&connp->conn_lock);
6117 		/*
6118 		 * No one from read or write side can access us now
6119 		 * except for already queued packets on this squeue.
6120 		 * But since we haven't changed the squeue yet, they
6121 		 * can't execute. If they are processed after we have
6122 		 * changed the squeue, they are sent back to the
6123 		 * correct squeue down below.
6124 		 * But a listner close can race with processing of
6125 		 * incoming SYN. If incoming SYN processing changes
6126 		 * the squeue then the listener close which is waiting
6127 		 * to enter the squeue would operate on the wrong
6128 		 * squeue. Hence we don't change the squeue here unless
6129 		 * the refcount is exactly the minimum refcount. The
6130 		 * minimum refcount of 4 is counted as - 1 each for
6131 		 * TCP and IP, 1 for being in the classifier hash, and
6132 		 * 1 for the mblk being processed.
6133 		 */
6134 
6135 		if (connp->conn_ref != 4 ||
6136 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
6137 			mutex_exit(&connp->conn_lock);
6138 			mutex_exit(&connp->conn_fanout->connf_lock);
6139 			goto done;
6140 		}
6141 		if (connp->conn_sqp != new_sqp) {
6142 			while (connp->conn_sqp != new_sqp)
6143 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6144 		}
6145 
6146 		do {
6147 			conn_flags = connp->conn_flags;
6148 			conn_flags |= IPCL_FULLY_BOUND;
6149 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6150 			    conn_flags);
6151 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6152 
6153 		mutex_exit(&connp->conn_fanout->connf_lock);
6154 		mutex_exit(&connp->conn_lock);
6155 	}
6156 
6157 done:
6158 	if (connp->conn_sqp != sqp) {
6159 		CONN_INC_REF(connp);
6160 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
6161 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
6162 	} else {
6163 		tcp_conn_request(connp, mp, sqp);
6164 	}
6165 }
6166 
6167 /*
6168  * Successful connect request processing begins when our client passes
6169  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6170  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6171  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6172  *   upstream <- tcp_rput()                <- IP
6173  * After various error checks are completed, tcp_connect() lays
6174  * the target address and port into the composite header template,
6175  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6176  * request followed by an IRE request, and passes the three mblk message
6177  * down to IP looking like this:
6178  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6179  * Processing continues in tcp_rput() when we receive the following message:
6180  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6181  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6182  * to fire off the connection request, and then passes the T_OK_ACK mblk
6183  * upstream that we filled in below.  There are, of course, numerous
6184  * error conditions along the way which truncate the processing described
6185  * above.
6186  */
6187 static void
6188 tcp_connect(tcp_t *tcp, mblk_t *mp)
6189 {
6190 	sin_t		*sin;
6191 	sin6_t		*sin6;
6192 	queue_t		*q = tcp->tcp_wq;
6193 	struct T_conn_req	*tcr;
6194 	ipaddr_t	*dstaddrp;
6195 	in_port_t	dstport;
6196 	uint_t		srcid;
6197 
6198 	tcr = (struct T_conn_req *)mp->b_rptr;
6199 
6200 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6201 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6202 		tcp_err_ack(tcp, mp, TPROTO, 0);
6203 		return;
6204 	}
6205 
6206 	/*
6207 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
6208 	 * will always have that to send up.  Otherwise, we need to do
6209 	 * special handling in case the allocation fails at that time.
6210 	 * If the end point is TPI, the tcp_t can be reused and the
6211 	 * tcp_ordrel_mp may be allocated already.
6212 	 */
6213 	if (tcp->tcp_ordrel_mp == NULL) {
6214 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
6215 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6216 			return;
6217 		}
6218 	}
6219 
6220 	/*
6221 	 * Determine packet type based on type of address passed in
6222 	 * the request should contain an IPv4 or IPv6 address.
6223 	 * Make sure that address family matches the type of
6224 	 * family of the the address passed down
6225 	 */
6226 	switch (tcr->DEST_length) {
6227 	default:
6228 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6229 		return;
6230 
6231 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6232 		/*
6233 		 * XXX: The check for valid DEST_length was not there
6234 		 * in earlier releases and some buggy
6235 		 * TLI apps (e.g Sybase) got away with not feeding
6236 		 * in sin_zero part of address.
6237 		 * We allow that bug to keep those buggy apps humming.
6238 		 * Test suites require the check on DEST_length.
6239 		 * We construct a new mblk with valid DEST_length
6240 		 * free the original so the rest of the code does
6241 		 * not have to keep track of this special shorter
6242 		 * length address case.
6243 		 */
6244 		mblk_t *nmp;
6245 		struct T_conn_req *ntcr;
6246 		sin_t *nsin;
6247 
6248 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6249 		    tcr->OPT_length, BPRI_HI);
6250 		if (nmp == NULL) {
6251 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6252 			return;
6253 		}
6254 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6255 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6256 		ntcr->PRIM_type = T_CONN_REQ;
6257 		ntcr->DEST_length = sizeof (sin_t);
6258 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6259 
6260 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6261 		*nsin = sin_null;
6262 		/* Get pointer to shorter address to copy from original mp */
6263 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6264 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6265 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6266 			freemsg(nmp);
6267 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6268 			return;
6269 		}
6270 		nsin->sin_family = sin->sin_family;
6271 		nsin->sin_port = sin->sin_port;
6272 		nsin->sin_addr = sin->sin_addr;
6273 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6274 		nmp->b_wptr = (uchar_t *)&nsin[1];
6275 		if (tcr->OPT_length != 0) {
6276 			ntcr->OPT_length = tcr->OPT_length;
6277 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6278 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6279 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6280 			    tcr->OPT_length);
6281 			nmp->b_wptr += tcr->OPT_length;
6282 		}
6283 		freemsg(mp);	/* original mp freed */
6284 		mp = nmp;	/* re-initialize original variables */
6285 		tcr = ntcr;
6286 	}
6287 	/* FALLTHRU */
6288 
6289 	case sizeof (sin_t):
6290 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6291 		    sizeof (sin_t));
6292 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6293 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6294 			return;
6295 		}
6296 		if (tcp->tcp_family != AF_INET ||
6297 		    sin->sin_family != AF_INET) {
6298 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6299 			return;
6300 		}
6301 		if (sin->sin_port == 0) {
6302 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6303 			return;
6304 		}
6305 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6306 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6307 			return;
6308 		}
6309 
6310 		break;
6311 
6312 	case sizeof (sin6_t):
6313 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6314 		    sizeof (sin6_t));
6315 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6316 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6317 			return;
6318 		}
6319 		if (tcp->tcp_family != AF_INET6 ||
6320 		    sin6->sin6_family != AF_INET6) {
6321 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6322 			return;
6323 		}
6324 		if (sin6->sin6_port == 0) {
6325 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6326 			return;
6327 		}
6328 		break;
6329 	}
6330 	/*
6331 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6332 	 * should key on their sequence number and cut them loose.
6333 	 */
6334 
6335 	/*
6336 	 * If options passed in, feed it for verification and handling
6337 	 */
6338 	if (tcr->OPT_length != 0) {
6339 		mblk_t	*ok_mp;
6340 		mblk_t	*discon_mp;
6341 		mblk_t  *conn_opts_mp;
6342 		int t_error, sys_error, do_disconnect;
6343 
6344 		conn_opts_mp = NULL;
6345 
6346 		if (tcp_conprim_opt_process(tcp, mp,
6347 		    &do_disconnect, &t_error, &sys_error) < 0) {
6348 			if (do_disconnect) {
6349 				ASSERT(t_error == 0 && sys_error == 0);
6350 				discon_mp = mi_tpi_discon_ind(NULL,
6351 				    ECONNREFUSED, 0);
6352 				if (!discon_mp) {
6353 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6354 					    TSYSERR, ENOMEM);
6355 					return;
6356 				}
6357 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6358 				if (!ok_mp) {
6359 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6360 					    TSYSERR, ENOMEM);
6361 					return;
6362 				}
6363 				qreply(q, ok_mp);
6364 				qreply(q, discon_mp); /* no flush! */
6365 			} else {
6366 				ASSERT(t_error != 0);
6367 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6368 				    sys_error);
6369 			}
6370 			return;
6371 		}
6372 		/*
6373 		 * Success in setting options, the mp option buffer represented
6374 		 * by OPT_length/offset has been potentially modified and
6375 		 * contains results of option processing. We copy it in
6376 		 * another mp to save it for potentially influencing returning
6377 		 * it in T_CONN_CONN.
6378 		 */
6379 		if (tcr->OPT_length != 0) { /* there are resulting options */
6380 			conn_opts_mp = copyb(mp);
6381 			if (!conn_opts_mp) {
6382 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6383 				    TSYSERR, ENOMEM);
6384 				return;
6385 			}
6386 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6387 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6388 			/*
6389 			 * Note:
6390 			 * These resulting option negotiation can include any
6391 			 * end-to-end negotiation options but there no such
6392 			 * thing (yet?) in our TCP/IP.
6393 			 */
6394 		}
6395 	}
6396 
6397 	/*
6398 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6399 	 * make sure that the template IP header in the tcp structure is an
6400 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6401 	 * need to this before we call tcp_bindi() so that the port lookup
6402 	 * code will look for ports in the correct port space (IPv4 and
6403 	 * IPv6 have separate port spaces).
6404 	 */
6405 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6406 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6407 		int err = 0;
6408 
6409 		err = tcp_header_init_ipv4(tcp);
6410 		if (err != 0) {
6411 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6412 			goto connect_failed;
6413 		}
6414 		if (tcp->tcp_lport != 0)
6415 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6416 	}
6417 
6418 	if (tcp->tcp_issocket) {
6419 		/*
6420 		 * TCP is _D_SODIRECT and sockfs is directly above so save
6421 		 * the shared sonode sodirect_t pointer (if any) to enable
6422 		 * TCP sodirect.
6423 		 */
6424 		tcp->tcp_sodirect = SOD_QTOSODP(tcp->tcp_rq);
6425 	}
6426 
6427 	switch (tcp->tcp_state) {
6428 	case TCPS_IDLE:
6429 		/*
6430 		 * We support quick connect, refer to comments in
6431 		 * tcp_connect_*()
6432 		 */
6433 		/* FALLTHRU */
6434 	case TCPS_BOUND:
6435 	case TCPS_LISTEN:
6436 		if (tcp->tcp_family == AF_INET6) {
6437 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6438 				tcp_connect_ipv6(tcp, mp,
6439 				    &sin6->sin6_addr,
6440 				    sin6->sin6_port, sin6->sin6_flowinfo,
6441 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6442 				return;
6443 			}
6444 			/*
6445 			 * Destination adress is mapped IPv6 address.
6446 			 * Source bound address should be unspecified or
6447 			 * IPv6 mapped address as well.
6448 			 */
6449 			if (!IN6_IS_ADDR_UNSPECIFIED(
6450 			    &tcp->tcp_bound_source_v6) &&
6451 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6452 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6453 				    EADDRNOTAVAIL);
6454 				break;
6455 			}
6456 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6457 			dstport = sin6->sin6_port;
6458 			srcid = sin6->__sin6_src_id;
6459 		} else {
6460 			dstaddrp = &sin->sin_addr.s_addr;
6461 			dstport = sin->sin_port;
6462 			srcid = 0;
6463 		}
6464 
6465 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6466 		return;
6467 	default:
6468 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6469 		break;
6470 	}
6471 	/*
6472 	 * Note: Code below is the "failure" case
6473 	 */
6474 	/* return error ack and blow away saved option results if any */
6475 connect_failed:
6476 	if (mp != NULL)
6477 		putnext(tcp->tcp_rq, mp);
6478 	else {
6479 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6480 		    TSYSERR, ENOMEM);
6481 	}
6482 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6483 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6484 }
6485 
6486 /*
6487  * Handle connect to IPv4 destinations, including connections for AF_INET6
6488  * sockets connecting to IPv4 mapped IPv6 destinations.
6489  */
6490 static void
6491 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6492     uint_t srcid)
6493 {
6494 	tcph_t	*tcph;
6495 	mblk_t	*mp1;
6496 	ipaddr_t dstaddr = *dstaddrp;
6497 	int32_t	oldstate;
6498 	uint16_t lport;
6499 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6500 
6501 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6502 
6503 	/* Check for attempt to connect to INADDR_ANY */
6504 	if (dstaddr == INADDR_ANY)  {
6505 		/*
6506 		 * SunOS 4.x and 4.3 BSD allow an application
6507 		 * to connect a TCP socket to INADDR_ANY.
6508 		 * When they do this, the kernel picks the
6509 		 * address of one interface and uses it
6510 		 * instead.  The kernel usually ends up
6511 		 * picking the address of the loopback
6512 		 * interface.  This is an undocumented feature.
6513 		 * However, we provide the same thing here
6514 		 * in order to have source and binary
6515 		 * compatibility with SunOS 4.x.
6516 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6517 		 * generate the T_CONN_CON.
6518 		 */
6519 		dstaddr = htonl(INADDR_LOOPBACK);
6520 		*dstaddrp = dstaddr;
6521 	}
6522 
6523 	/* Handle __sin6_src_id if socket not bound to an IP address */
6524 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6525 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6526 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6527 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6528 		    tcp->tcp_ipha->ipha_src);
6529 	}
6530 
6531 	/*
6532 	 * Don't let an endpoint connect to itself.  Note that
6533 	 * the test here does not catch the case where the
6534 	 * source IP addr was left unspecified by the user. In
6535 	 * this case, the source addr is set in tcp_adapt_ire()
6536 	 * using the reply to the T_BIND message that we send
6537 	 * down to IP here and the check is repeated in tcp_rput_other.
6538 	 */
6539 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6540 	    dstport == tcp->tcp_lport) {
6541 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6542 		goto failed;
6543 	}
6544 
6545 	tcp->tcp_ipha->ipha_dst = dstaddr;
6546 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6547 
6548 	/*
6549 	 * Massage a source route if any putting the first hop
6550 	 * in iph_dst. Compute a starting value for the checksum which
6551 	 * takes into account that the original iph_dst should be
6552 	 * included in the checksum but that ip will include the
6553 	 * first hop in the source route in the tcp checksum.
6554 	 */
6555 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6556 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6557 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6558 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6559 	if ((int)tcp->tcp_sum < 0)
6560 		tcp->tcp_sum--;
6561 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6562 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6563 	    (tcp->tcp_sum >> 16));
6564 	tcph = tcp->tcp_tcph;
6565 	*(uint16_t *)tcph->th_fport = dstport;
6566 	tcp->tcp_fport = dstport;
6567 
6568 	oldstate = tcp->tcp_state;
6569 	/*
6570 	 * At this point the remote destination address and remote port fields
6571 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6572 	 * have to see which state tcp was in so we can take apropriate action.
6573 	 */
6574 	if (oldstate == TCPS_IDLE) {
6575 		/*
6576 		 * We support a quick connect capability here, allowing
6577 		 * clients to transition directly from IDLE to SYN_SENT
6578 		 * tcp_bindi will pick an unused port, insert the connection
6579 		 * in the bind hash and transition to BOUND state.
6580 		 */
6581 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6582 		    tcp, B_TRUE);
6583 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6584 		    B_FALSE, B_FALSE);
6585 		if (lport == 0) {
6586 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6587 			goto failed;
6588 		}
6589 	}
6590 	tcp->tcp_state = TCPS_SYN_SENT;
6591 
6592 	/*
6593 	 * TODO: allow data with connect requests
6594 	 * by unlinking M_DATA trailers here and
6595 	 * linking them in behind the T_OK_ACK mblk.
6596 	 * The tcp_rput() bind ack handler would then
6597 	 * feed them to tcp_wput_data() rather than call
6598 	 * tcp_timer().
6599 	 */
6600 	mp = mi_tpi_ok_ack_alloc(mp);
6601 	if (!mp) {
6602 		tcp->tcp_state = oldstate;
6603 		goto failed;
6604 	}
6605 	if (tcp->tcp_family == AF_INET) {
6606 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6607 		    sizeof (ipa_conn_t));
6608 	} else {
6609 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6610 		    sizeof (ipa6_conn_t));
6611 	}
6612 	if (mp1) {
6613 		/*
6614 		 * We need to make sure that the conn_recv is set to a non-null
6615 		 * value before we insert the conn_t into the classifier table.
6616 		 * This is to avoid a race with an incoming packet which does
6617 		 * an ipcl_classify().
6618 		 */
6619 		tcp->tcp_connp->conn_recv = tcp_input;
6620 
6621 		/* Hang onto the T_OK_ACK for later. */
6622 		linkb(mp1, mp);
6623 		mblk_setcred(mp1, tcp->tcp_cred);
6624 		if (tcp->tcp_family == AF_INET)
6625 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6626 		else {
6627 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6628 			    &tcp->tcp_sticky_ipp);
6629 		}
6630 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6631 		tcp->tcp_active_open = 1;
6632 		/*
6633 		 * If the bind cannot complete immediately
6634 		 * IP will arrange to call tcp_rput_other
6635 		 * when the bind completes.
6636 		 */
6637 		if (mp1 != NULL)
6638 			tcp_rput_other(tcp, mp1);
6639 		return;
6640 	}
6641 	/* Error case */
6642 	tcp->tcp_state = oldstate;
6643 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6644 
6645 failed:
6646 	/* return error ack and blow away saved option results if any */
6647 	if (mp != NULL)
6648 		putnext(tcp->tcp_rq, mp);
6649 	else {
6650 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6651 		    TSYSERR, ENOMEM);
6652 	}
6653 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6654 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6655 
6656 }
6657 
6658 /*
6659  * Handle connect to IPv6 destinations.
6660  */
6661 static void
6662 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6663     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6664 {
6665 	tcph_t	*tcph;
6666 	mblk_t	*mp1;
6667 	ip6_rthdr_t *rth;
6668 	int32_t  oldstate;
6669 	uint16_t lport;
6670 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6671 
6672 	ASSERT(tcp->tcp_family == AF_INET6);
6673 
6674 	/*
6675 	 * If we're here, it means that the destination address is a native
6676 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6677 	 * reason why it might not be IPv6 is if the socket was bound to an
6678 	 * IPv4-mapped IPv6 address.
6679 	 */
6680 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6681 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6682 		goto failed;
6683 	}
6684 
6685 	/*
6686 	 * Interpret a zero destination to mean loopback.
6687 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6688 	 * generate the T_CONN_CON.
6689 	 */
6690 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6691 		*dstaddrp = ipv6_loopback;
6692 	}
6693 
6694 	/* Handle __sin6_src_id if socket not bound to an IP address */
6695 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6696 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6697 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6698 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6699 	}
6700 
6701 	/*
6702 	 * Take care of the scope_id now and add ip6i_t
6703 	 * if ip6i_t is not already allocated through TCP
6704 	 * sticky options. At this point tcp_ip6h does not
6705 	 * have dst info, thus use dstaddrp.
6706 	 */
6707 	if (scope_id != 0 &&
6708 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6709 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6710 		ip6i_t  *ip6i;
6711 
6712 		ipp->ipp_ifindex = scope_id;
6713 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6714 
6715 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6716 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6717 			/* Already allocated */
6718 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6719 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6720 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6721 		} else {
6722 			int reterr;
6723 
6724 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6725 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6726 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6727 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6728 			if (reterr != 0)
6729 				goto failed;
6730 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6731 		}
6732 	}
6733 
6734 	/*
6735 	 * Don't let an endpoint connect to itself.  Note that
6736 	 * the test here does not catch the case where the
6737 	 * source IP addr was left unspecified by the user. In
6738 	 * this case, the source addr is set in tcp_adapt_ire()
6739 	 * using the reply to the T_BIND message that we send
6740 	 * down to IP here and the check is repeated in tcp_rput_other.
6741 	 */
6742 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6743 	    (dstport == tcp->tcp_lport)) {
6744 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6745 		goto failed;
6746 	}
6747 
6748 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6749 	tcp->tcp_remote_v6 = *dstaddrp;
6750 	tcp->tcp_ip6h->ip6_vcf =
6751 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6752 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6753 
6754 
6755 	/*
6756 	 * Massage a routing header (if present) putting the first hop
6757 	 * in ip6_dst. Compute a starting value for the checksum which
6758 	 * takes into account that the original ip6_dst should be
6759 	 * included in the checksum but that ip will include the
6760 	 * first hop in the source route in the tcp checksum.
6761 	 */
6762 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6763 	if (rth != NULL) {
6764 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6765 		    tcps->tcps_netstack);
6766 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6767 		    (tcp->tcp_sum >> 16));
6768 	} else {
6769 		tcp->tcp_sum = 0;
6770 	}
6771 
6772 	tcph = tcp->tcp_tcph;
6773 	*(uint16_t *)tcph->th_fport = dstport;
6774 	tcp->tcp_fport = dstport;
6775 
6776 	oldstate = tcp->tcp_state;
6777 	/*
6778 	 * At this point the remote destination address and remote port fields
6779 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6780 	 * have to see which state tcp was in so we can take apropriate action.
6781 	 */
6782 	if (oldstate == TCPS_IDLE) {
6783 		/*
6784 		 * We support a quick connect capability here, allowing
6785 		 * clients to transition directly from IDLE to SYN_SENT
6786 		 * tcp_bindi will pick an unused port, insert the connection
6787 		 * in the bind hash and transition to BOUND state.
6788 		 */
6789 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6790 		    tcp, B_TRUE);
6791 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6792 		    B_FALSE, B_FALSE);
6793 		if (lport == 0) {
6794 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6795 			goto failed;
6796 		}
6797 	}
6798 	tcp->tcp_state = TCPS_SYN_SENT;
6799 	/*
6800 	 * TODO: allow data with connect requests
6801 	 * by unlinking M_DATA trailers here and
6802 	 * linking them in behind the T_OK_ACK mblk.
6803 	 * The tcp_rput() bind ack handler would then
6804 	 * feed them to tcp_wput_data() rather than call
6805 	 * tcp_timer().
6806 	 */
6807 	mp = mi_tpi_ok_ack_alloc(mp);
6808 	if (!mp) {
6809 		tcp->tcp_state = oldstate;
6810 		goto failed;
6811 	}
6812 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6813 	if (mp1) {
6814 		/*
6815 		 * We need to make sure that the conn_recv is set to a non-null
6816 		 * value before we insert the conn_t into the classifier table.
6817 		 * This is to avoid a race with an incoming packet which does
6818 		 * an ipcl_classify().
6819 		 */
6820 		tcp->tcp_connp->conn_recv = tcp_input;
6821 
6822 		/* Hang onto the T_OK_ACK for later. */
6823 		linkb(mp1, mp);
6824 		mblk_setcred(mp1, tcp->tcp_cred);
6825 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6826 		    &tcp->tcp_sticky_ipp);
6827 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6828 		tcp->tcp_active_open = 1;
6829 		/* ip_bind_v6() may return ACK or ERROR */
6830 		if (mp1 != NULL)
6831 			tcp_rput_other(tcp, mp1);
6832 		return;
6833 	}
6834 	/* Error case */
6835 	tcp->tcp_state = oldstate;
6836 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6837 
6838 failed:
6839 	/* return error ack and blow away saved option results if any */
6840 	if (mp != NULL)
6841 		putnext(tcp->tcp_rq, mp);
6842 	else {
6843 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6844 		    TSYSERR, ENOMEM);
6845 	}
6846 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6847 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6848 }
6849 
6850 /*
6851  * We need a stream q for detached closing tcp connections
6852  * to use.  Our client hereby indicates that this q is the
6853  * one to use.
6854  */
6855 static void
6856 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6857 {
6858 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6859 	queue_t	*q = tcp->tcp_wq;
6860 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6861 
6862 #ifdef NS_DEBUG
6863 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6864 	    tcps->tcps_netstack->netstack_stackid);
6865 #endif
6866 	mp->b_datap->db_type = M_IOCACK;
6867 	iocp->ioc_count = 0;
6868 	mutex_enter(&tcps->tcps_g_q_lock);
6869 	if (tcps->tcps_g_q != NULL) {
6870 		mutex_exit(&tcps->tcps_g_q_lock);
6871 		iocp->ioc_error = EALREADY;
6872 	} else {
6873 		mblk_t *mp1;
6874 
6875 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6876 		if (mp1 == NULL) {
6877 			mutex_exit(&tcps->tcps_g_q_lock);
6878 			iocp->ioc_error = ENOMEM;
6879 		} else {
6880 			tcps->tcps_g_q = tcp->tcp_rq;
6881 			mutex_exit(&tcps->tcps_g_q_lock);
6882 			iocp->ioc_error = 0;
6883 			iocp->ioc_rval = 0;
6884 			/*
6885 			 * We are passing tcp_sticky_ipp as NULL
6886 			 * as it is not useful for tcp_default queue
6887 			 *
6888 			 * Set conn_recv just in case.
6889 			 */
6890 			tcp->tcp_connp->conn_recv = tcp_conn_request;
6891 
6892 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6893 			if (mp1 != NULL)
6894 				tcp_rput_other(tcp, mp1);
6895 		}
6896 	}
6897 	qreply(q, mp);
6898 }
6899 
6900 /*
6901  * Our client hereby directs us to reject the connection request
6902  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6903  * of sending the appropriate RST, not an ICMP error.
6904  */
6905 static void
6906 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6907 {
6908 	tcp_t	*ltcp = NULL;
6909 	t_scalar_t seqnum;
6910 	conn_t	*connp;
6911 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6912 
6913 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6914 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6915 		tcp_err_ack(tcp, mp, TPROTO, 0);
6916 		return;
6917 	}
6918 
6919 	/*
6920 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6921 	 * when the stream is in BOUND state. Do not send a reset,
6922 	 * since the destination IP address is not valid, and it can
6923 	 * be the initialized value of all zeros (broadcast address).
6924 	 *
6925 	 * If TCP has sent down a bind request to IP and has not
6926 	 * received the reply, reject the request.  Otherwise, TCP
6927 	 * will be confused.
6928 	 */
6929 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6930 		if (tcp->tcp_debug) {
6931 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6932 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6933 		}
6934 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6935 		return;
6936 	}
6937 
6938 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6939 
6940 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6941 
6942 		/*
6943 		 * According to TPI, for non-listeners, ignore seqnum
6944 		 * and disconnect.
6945 		 * Following interpretation of -1 seqnum is historical
6946 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6947 		 * a valid seqnum should not be -1).
6948 		 *
6949 		 *	-1 means disconnect everything
6950 		 *	regardless even on a listener.
6951 		 */
6952 
6953 		int old_state = tcp->tcp_state;
6954 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6955 
6956 		/*
6957 		 * The connection can't be on the tcp_time_wait_head list
6958 		 * since it is not detached.
6959 		 */
6960 		ASSERT(tcp->tcp_time_wait_next == NULL);
6961 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6962 		ASSERT(tcp->tcp_time_wait_expire == 0);
6963 		ltcp = NULL;
6964 		/*
6965 		 * If it used to be a listener, check to make sure no one else
6966 		 * has taken the port before switching back to LISTEN state.
6967 		 */
6968 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6969 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6970 			    tcp->tcp_ipha->ipha_src,
6971 			    tcp->tcp_connp->conn_zoneid, ipst);
6972 			if (connp != NULL)
6973 				ltcp = connp->conn_tcp;
6974 		} else {
6975 			/* Allow tcp_bound_if listeners? */
6976 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6977 			    &tcp->tcp_ip6h->ip6_src, 0,
6978 			    tcp->tcp_connp->conn_zoneid, ipst);
6979 			if (connp != NULL)
6980 				ltcp = connp->conn_tcp;
6981 		}
6982 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6983 			tcp->tcp_state = TCPS_LISTEN;
6984 		} else if (old_state > TCPS_BOUND) {
6985 			tcp->tcp_conn_req_max = 0;
6986 			tcp->tcp_state = TCPS_BOUND;
6987 		}
6988 		if (ltcp != NULL)
6989 			CONN_DEC_REF(ltcp->tcp_connp);
6990 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6991 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6992 		} else if (old_state == TCPS_ESTABLISHED ||
6993 		    old_state == TCPS_CLOSE_WAIT) {
6994 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6995 		}
6996 
6997 		if (tcp->tcp_fused)
6998 			tcp_unfuse(tcp);
6999 
7000 		mutex_enter(&tcp->tcp_eager_lock);
7001 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
7002 		    (tcp->tcp_conn_req_cnt_q != 0)) {
7003 			tcp_eager_cleanup(tcp, 0);
7004 		}
7005 		mutex_exit(&tcp->tcp_eager_lock);
7006 
7007 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
7008 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
7009 
7010 		tcp_reinit(tcp);
7011 
7012 		if (old_state >= TCPS_ESTABLISHED) {
7013 			/* Send M_FLUSH according to TPI */
7014 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7015 		}
7016 		mp = mi_tpi_ok_ack_alloc(mp);
7017 		if (mp)
7018 			putnext(tcp->tcp_rq, mp);
7019 		return;
7020 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
7021 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
7022 		return;
7023 	}
7024 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
7025 		/* Send M_FLUSH according to TPI */
7026 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7027 	}
7028 	mp = mi_tpi_ok_ack_alloc(mp);
7029 	if (mp)
7030 		putnext(tcp->tcp_rq, mp);
7031 }
7032 
7033 /*
7034  * Diagnostic routine used to return a string associated with the tcp state.
7035  * Note that if the caller does not supply a buffer, it will use an internal
7036  * static string.  This means that if multiple threads call this function at
7037  * the same time, output can be corrupted...  Note also that this function
7038  * does not check the size of the supplied buffer.  The caller has to make
7039  * sure that it is big enough.
7040  */
7041 static char *
7042 tcp_display(tcp_t *tcp, char *sup_buf, char format)
7043 {
7044 	char		buf1[30];
7045 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
7046 	char		*buf;
7047 	char		*cp;
7048 	in6_addr_t	local, remote;
7049 	char		local_addrbuf[INET6_ADDRSTRLEN];
7050 	char		remote_addrbuf[INET6_ADDRSTRLEN];
7051 
7052 	if (sup_buf != NULL)
7053 		buf = sup_buf;
7054 	else
7055 		buf = priv_buf;
7056 
7057 	if (tcp == NULL)
7058 		return ("NULL_TCP");
7059 	switch (tcp->tcp_state) {
7060 	case TCPS_CLOSED:
7061 		cp = "TCP_CLOSED";
7062 		break;
7063 	case TCPS_IDLE:
7064 		cp = "TCP_IDLE";
7065 		break;
7066 	case TCPS_BOUND:
7067 		cp = "TCP_BOUND";
7068 		break;
7069 	case TCPS_LISTEN:
7070 		cp = "TCP_LISTEN";
7071 		break;
7072 	case TCPS_SYN_SENT:
7073 		cp = "TCP_SYN_SENT";
7074 		break;
7075 	case TCPS_SYN_RCVD:
7076 		cp = "TCP_SYN_RCVD";
7077 		break;
7078 	case TCPS_ESTABLISHED:
7079 		cp = "TCP_ESTABLISHED";
7080 		break;
7081 	case TCPS_CLOSE_WAIT:
7082 		cp = "TCP_CLOSE_WAIT";
7083 		break;
7084 	case TCPS_FIN_WAIT_1:
7085 		cp = "TCP_FIN_WAIT_1";
7086 		break;
7087 	case TCPS_CLOSING:
7088 		cp = "TCP_CLOSING";
7089 		break;
7090 	case TCPS_LAST_ACK:
7091 		cp = "TCP_LAST_ACK";
7092 		break;
7093 	case TCPS_FIN_WAIT_2:
7094 		cp = "TCP_FIN_WAIT_2";
7095 		break;
7096 	case TCPS_TIME_WAIT:
7097 		cp = "TCP_TIME_WAIT";
7098 		break;
7099 	default:
7100 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7101 		cp = buf1;
7102 		break;
7103 	}
7104 	switch (format) {
7105 	case DISP_ADDR_AND_PORT:
7106 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7107 			/*
7108 			 * Note that we use the remote address in the tcp_b
7109 			 * structure.  This means that it will print out
7110 			 * the real destination address, not the next hop's
7111 			 * address if source routing is used.
7112 			 */
7113 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7114 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7115 
7116 		} else {
7117 			local = tcp->tcp_ip_src_v6;
7118 			remote = tcp->tcp_remote_v6;
7119 		}
7120 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7121 		    sizeof (local_addrbuf));
7122 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7123 		    sizeof (remote_addrbuf));
7124 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7125 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7126 		    ntohs(tcp->tcp_fport), cp);
7127 		break;
7128 	case DISP_PORT_ONLY:
7129 	default:
7130 		(void) mi_sprintf(buf, "[%u, %u] %s",
7131 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7132 		break;
7133 	}
7134 
7135 	return (buf);
7136 }
7137 
7138 /*
7139  * Called via squeue to get on to eager's perimeter. It sends a
7140  * TH_RST if eager is in the fanout table. The listener wants the
7141  * eager to disappear either by means of tcp_eager_blowoff() or
7142  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
7143  * called (via squeue) if the eager cannot be inserted in the
7144  * fanout table in tcp_conn_request().
7145  */
7146 /* ARGSUSED */
7147 void
7148 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7149 {
7150 	conn_t	*econnp = (conn_t *)arg;
7151 	tcp_t	*eager = econnp->conn_tcp;
7152 	tcp_t	*listener = eager->tcp_listener;
7153 	tcp_stack_t	*tcps = eager->tcp_tcps;
7154 
7155 	/*
7156 	 * We could be called because listener is closing. Since
7157 	 * the eager is using listener's queue's, its not safe.
7158 	 * Better use the default queue just to send the TH_RST
7159 	 * out.
7160 	 */
7161 	ASSERT(tcps->tcps_g_q != NULL);
7162 	eager->tcp_rq = tcps->tcps_g_q;
7163 	eager->tcp_wq = WR(tcps->tcps_g_q);
7164 
7165 	/*
7166 	 * An eager's conn_fanout will be NULL if it's a duplicate
7167 	 * for an existing 4-tuples in the conn fanout table.
7168 	 * We don't want to send an RST out in such case.
7169 	 */
7170 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
7171 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7172 		    eager, eager->tcp_snxt, 0, TH_RST);
7173 	}
7174 
7175 	/* We are here because listener wants this eager gone */
7176 	if (listener != NULL) {
7177 		mutex_enter(&listener->tcp_eager_lock);
7178 		tcp_eager_unlink(eager);
7179 		if (eager->tcp_tconnind_started) {
7180 			/*
7181 			 * The eager has sent a conn_ind up to the
7182 			 * listener but listener decides to close
7183 			 * instead. We need to drop the extra ref
7184 			 * placed on eager in tcp_rput_data() before
7185 			 * sending the conn_ind to listener.
7186 			 */
7187 			CONN_DEC_REF(econnp);
7188 		}
7189 		mutex_exit(&listener->tcp_eager_lock);
7190 		CONN_DEC_REF(listener->tcp_connp);
7191 	}
7192 
7193 	if (eager->tcp_state > TCPS_BOUND)
7194 		tcp_close_detached(eager);
7195 }
7196 
7197 /*
7198  * Reset any eager connection hanging off this listener marked
7199  * with 'seqnum' and then reclaim it's resources.
7200  */
7201 static boolean_t
7202 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7203 {
7204 	tcp_t	*eager;
7205 	mblk_t 	*mp;
7206 	tcp_stack_t	*tcps = listener->tcp_tcps;
7207 
7208 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
7209 	eager = listener;
7210 	mutex_enter(&listener->tcp_eager_lock);
7211 	do {
7212 		eager = eager->tcp_eager_next_q;
7213 		if (eager == NULL) {
7214 			mutex_exit(&listener->tcp_eager_lock);
7215 			return (B_FALSE);
7216 		}
7217 	} while (eager->tcp_conn_req_seqnum != seqnum);
7218 
7219 	if (eager->tcp_closemp_used) {
7220 		mutex_exit(&listener->tcp_eager_lock);
7221 		return (B_TRUE);
7222 	}
7223 	eager->tcp_closemp_used = B_TRUE;
7224 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7225 	CONN_INC_REF(eager->tcp_connp);
7226 	mutex_exit(&listener->tcp_eager_lock);
7227 	mp = &eager->tcp_closemp;
7228 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7229 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
7230 	return (B_TRUE);
7231 }
7232 
7233 /*
7234  * Reset any eager connection hanging off this listener
7235  * and then reclaim it's resources.
7236  */
7237 static void
7238 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7239 {
7240 	tcp_t	*eager;
7241 	mblk_t	*mp;
7242 	tcp_stack_t	*tcps = listener->tcp_tcps;
7243 
7244 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7245 
7246 	if (!q0_only) {
7247 		/* First cleanup q */
7248 		TCP_STAT(tcps, tcp_eager_blowoff_q);
7249 		eager = listener->tcp_eager_next_q;
7250 		while (eager != NULL) {
7251 			if (!eager->tcp_closemp_used) {
7252 				eager->tcp_closemp_used = B_TRUE;
7253 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7254 				CONN_INC_REF(eager->tcp_connp);
7255 				mp = &eager->tcp_closemp;
7256 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
7257 				    tcp_eager_kill, eager->tcp_connp,
7258 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
7259 			}
7260 			eager = eager->tcp_eager_next_q;
7261 		}
7262 	}
7263 	/* Then cleanup q0 */
7264 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
7265 	eager = listener->tcp_eager_next_q0;
7266 	while (eager != listener) {
7267 		if (!eager->tcp_closemp_used) {
7268 			eager->tcp_closemp_used = B_TRUE;
7269 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7270 			CONN_INC_REF(eager->tcp_connp);
7271 			mp = &eager->tcp_closemp;
7272 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
7273 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
7274 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
7275 		}
7276 		eager = eager->tcp_eager_next_q0;
7277 	}
7278 }
7279 
7280 /*
7281  * If we are an eager connection hanging off a listener that hasn't
7282  * formally accepted the connection yet, get off his list and blow off
7283  * any data that we have accumulated.
7284  */
7285 static void
7286 tcp_eager_unlink(tcp_t *tcp)
7287 {
7288 	tcp_t	*listener = tcp->tcp_listener;
7289 
7290 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7291 	ASSERT(listener != NULL);
7292 	if (tcp->tcp_eager_next_q0 != NULL) {
7293 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7294 
7295 		/* Remove the eager tcp from q0 */
7296 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7297 		    tcp->tcp_eager_prev_q0;
7298 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7299 		    tcp->tcp_eager_next_q0;
7300 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7301 		listener->tcp_conn_req_cnt_q0--;
7302 
7303 		tcp->tcp_eager_next_q0 = NULL;
7304 		tcp->tcp_eager_prev_q0 = NULL;
7305 
7306 		/*
7307 		 * Take the eager out, if it is in the list of droppable
7308 		 * eagers.
7309 		 */
7310 		MAKE_UNDROPPABLE(tcp);
7311 
7312 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7313 			/* we have timed out before */
7314 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7315 			listener->tcp_syn_rcvd_timeout--;
7316 		}
7317 	} else {
7318 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7319 		tcp_t	*prev = NULL;
7320 
7321 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7322 			if (tcpp[0] == tcp) {
7323 				if (listener->tcp_eager_last_q == tcp) {
7324 					/*
7325 					 * If we are unlinking the last
7326 					 * element on the list, adjust
7327 					 * tail pointer. Set tail pointer
7328 					 * to nil when list is empty.
7329 					 */
7330 					ASSERT(tcp->tcp_eager_next_q == NULL);
7331 					if (listener->tcp_eager_last_q ==
7332 					    listener->tcp_eager_next_q) {
7333 						listener->tcp_eager_last_q =
7334 						    NULL;
7335 					} else {
7336 						/*
7337 						 * We won't get here if there
7338 						 * is only one eager in the
7339 						 * list.
7340 						 */
7341 						ASSERT(prev != NULL);
7342 						listener->tcp_eager_last_q =
7343 						    prev;
7344 					}
7345 				}
7346 				tcpp[0] = tcp->tcp_eager_next_q;
7347 				tcp->tcp_eager_next_q = NULL;
7348 				tcp->tcp_eager_last_q = NULL;
7349 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7350 				listener->tcp_conn_req_cnt_q--;
7351 				break;
7352 			}
7353 			prev = tcpp[0];
7354 		}
7355 	}
7356 	tcp->tcp_listener = NULL;
7357 }
7358 
7359 /* Shorthand to generate and send TPI error acks to our client */
7360 static void
7361 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7362 {
7363 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7364 		putnext(tcp->tcp_rq, mp);
7365 }
7366 
7367 /* Shorthand to generate and send TPI error acks to our client */
7368 static void
7369 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7370     int t_error, int sys_error)
7371 {
7372 	struct T_error_ack	*teackp;
7373 
7374 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7375 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7376 		teackp = (struct T_error_ack *)mp->b_rptr;
7377 		teackp->ERROR_prim = primitive;
7378 		teackp->TLI_error = t_error;
7379 		teackp->UNIX_error = sys_error;
7380 		putnext(tcp->tcp_rq, mp);
7381 	}
7382 }
7383 
7384 /*
7385  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7386  * but instead the code relies on:
7387  * - the fact that the address of the array and its size never changes
7388  * - the atomic assignment of the elements of the array
7389  */
7390 /* ARGSUSED */
7391 static int
7392 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7393 {
7394 	int i;
7395 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7396 
7397 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7398 		if (tcps->tcps_g_epriv_ports[i] != 0)
7399 			(void) mi_mpprintf(mp, "%d ",
7400 			    tcps->tcps_g_epriv_ports[i]);
7401 	}
7402 	return (0);
7403 }
7404 
7405 /*
7406  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7407  * threads from changing it at the same time.
7408  */
7409 /* ARGSUSED */
7410 static int
7411 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7412     cred_t *cr)
7413 {
7414 	long	new_value;
7415 	int	i;
7416 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7417 
7418 	/*
7419 	 * Fail the request if the new value does not lie within the
7420 	 * port number limits.
7421 	 */
7422 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7423 	    new_value <= 0 || new_value >= 65536) {
7424 		return (EINVAL);
7425 	}
7426 
7427 	mutex_enter(&tcps->tcps_epriv_port_lock);
7428 	/* Check if the value is already in the list */
7429 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7430 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7431 			mutex_exit(&tcps->tcps_epriv_port_lock);
7432 			return (EEXIST);
7433 		}
7434 	}
7435 	/* Find an empty slot */
7436 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7437 		if (tcps->tcps_g_epriv_ports[i] == 0)
7438 			break;
7439 	}
7440 	if (i == tcps->tcps_g_num_epriv_ports) {
7441 		mutex_exit(&tcps->tcps_epriv_port_lock);
7442 		return (EOVERFLOW);
7443 	}
7444 	/* Set the new value */
7445 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7446 	mutex_exit(&tcps->tcps_epriv_port_lock);
7447 	return (0);
7448 }
7449 
7450 /*
7451  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7452  * threads from changing it at the same time.
7453  */
7454 /* ARGSUSED */
7455 static int
7456 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7457     cred_t *cr)
7458 {
7459 	long	new_value;
7460 	int	i;
7461 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7462 
7463 	/*
7464 	 * Fail the request if the new value does not lie within the
7465 	 * port number limits.
7466 	 */
7467 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7468 	    new_value >= 65536) {
7469 		return (EINVAL);
7470 	}
7471 
7472 	mutex_enter(&tcps->tcps_epriv_port_lock);
7473 	/* Check that the value is already in the list */
7474 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7475 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7476 			break;
7477 	}
7478 	if (i == tcps->tcps_g_num_epriv_ports) {
7479 		mutex_exit(&tcps->tcps_epriv_port_lock);
7480 		return (ESRCH);
7481 	}
7482 	/* Clear the value */
7483 	tcps->tcps_g_epriv_ports[i] = 0;
7484 	mutex_exit(&tcps->tcps_epriv_port_lock);
7485 	return (0);
7486 }
7487 
7488 /* Return the TPI/TLI equivalent of our current tcp_state */
7489 static int
7490 tcp_tpistate(tcp_t *tcp)
7491 {
7492 	switch (tcp->tcp_state) {
7493 	case TCPS_IDLE:
7494 		return (TS_UNBND);
7495 	case TCPS_LISTEN:
7496 		/*
7497 		 * Return whether there are outstanding T_CONN_IND waiting
7498 		 * for the matching T_CONN_RES. Therefore don't count q0.
7499 		 */
7500 		if (tcp->tcp_conn_req_cnt_q > 0)
7501 			return (TS_WRES_CIND);
7502 		else
7503 			return (TS_IDLE);
7504 	case TCPS_BOUND:
7505 		return (TS_IDLE);
7506 	case TCPS_SYN_SENT:
7507 		return (TS_WCON_CREQ);
7508 	case TCPS_SYN_RCVD:
7509 		/*
7510 		 * Note: assumption: this has to the active open SYN_RCVD.
7511 		 * The passive instance is detached in SYN_RCVD stage of
7512 		 * incoming connection processing so we cannot get request
7513 		 * for T_info_ack on it.
7514 		 */
7515 		return (TS_WACK_CRES);
7516 	case TCPS_ESTABLISHED:
7517 		return (TS_DATA_XFER);
7518 	case TCPS_CLOSE_WAIT:
7519 		return (TS_WREQ_ORDREL);
7520 	case TCPS_FIN_WAIT_1:
7521 		return (TS_WIND_ORDREL);
7522 	case TCPS_FIN_WAIT_2:
7523 		return (TS_WIND_ORDREL);
7524 
7525 	case TCPS_CLOSING:
7526 	case TCPS_LAST_ACK:
7527 	case TCPS_TIME_WAIT:
7528 	case TCPS_CLOSED:
7529 		/*
7530 		 * Following TS_WACK_DREQ7 is a rendition of "not
7531 		 * yet TS_IDLE" TPI state. There is no best match to any
7532 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7533 		 * choose a value chosen that will map to TLI/XTI level
7534 		 * state of TSTATECHNG (state is process of changing) which
7535 		 * captures what this dummy state represents.
7536 		 */
7537 		return (TS_WACK_DREQ7);
7538 	default:
7539 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7540 		    tcp->tcp_state, tcp_display(tcp, NULL,
7541 		    DISP_PORT_ONLY));
7542 		return (TS_UNBND);
7543 	}
7544 }
7545 
7546 static void
7547 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7548 {
7549 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7550 
7551 	if (tcp->tcp_family == AF_INET6)
7552 		*tia = tcp_g_t_info_ack_v6;
7553 	else
7554 		*tia = tcp_g_t_info_ack;
7555 	tia->CURRENT_state = tcp_tpistate(tcp);
7556 	tia->OPT_size = tcp_max_optsize;
7557 	if (tcp->tcp_mss == 0) {
7558 		/* Not yet set - tcp_open does not set mss */
7559 		if (tcp->tcp_ipversion == IPV4_VERSION)
7560 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7561 		else
7562 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7563 	} else {
7564 		tia->TIDU_size = tcp->tcp_mss;
7565 	}
7566 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7567 }
7568 
7569 /*
7570  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7571  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7572  * tcp_g_t_info_ack.  The current state of the stream is copied from
7573  * tcp_state.
7574  */
7575 static void
7576 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7577 {
7578 	t_uscalar_t		cap_bits1;
7579 	struct T_capability_ack	*tcap;
7580 
7581 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7582 		freemsg(mp);
7583 		return;
7584 	}
7585 
7586 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7587 
7588 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7589 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7590 	if (mp == NULL)
7591 		return;
7592 
7593 	tcap = (struct T_capability_ack *)mp->b_rptr;
7594 	tcap->CAP_bits1 = 0;
7595 
7596 	if (cap_bits1 & TC1_INFO) {
7597 		tcp_copy_info(&tcap->INFO_ack, tcp);
7598 		tcap->CAP_bits1 |= TC1_INFO;
7599 	}
7600 
7601 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7602 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7603 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7604 	}
7605 
7606 	putnext(tcp->tcp_rq, mp);
7607 }
7608 
7609 /*
7610  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7611  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7612  * The current state of the stream is copied from tcp_state.
7613  */
7614 static void
7615 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7616 {
7617 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7618 	    T_INFO_ACK);
7619 	if (!mp) {
7620 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7621 		return;
7622 	}
7623 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7624 	putnext(tcp->tcp_rq, mp);
7625 }
7626 
7627 /* Respond to the TPI addr request */
7628 static void
7629 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7630 {
7631 	sin_t	*sin;
7632 	mblk_t	*ackmp;
7633 	struct T_addr_ack *taa;
7634 
7635 	/* Make it large enough for worst case */
7636 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7637 	    2 * sizeof (sin6_t), 1);
7638 	if (ackmp == NULL) {
7639 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7640 		return;
7641 	}
7642 
7643 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7644 		tcp_addr_req_ipv6(tcp, ackmp);
7645 		return;
7646 	}
7647 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7648 
7649 	bzero(taa, sizeof (struct T_addr_ack));
7650 	ackmp->b_wptr = (uchar_t *)&taa[1];
7651 
7652 	taa->PRIM_type = T_ADDR_ACK;
7653 	ackmp->b_datap->db_type = M_PCPROTO;
7654 
7655 	/*
7656 	 * Note: Following code assumes 32 bit alignment of basic
7657 	 * data structures like sin_t and struct T_addr_ack.
7658 	 */
7659 	if (tcp->tcp_state >= TCPS_BOUND) {
7660 		/*
7661 		 * Fill in local address
7662 		 */
7663 		taa->LOCADDR_length = sizeof (sin_t);
7664 		taa->LOCADDR_offset = sizeof (*taa);
7665 
7666 		sin = (sin_t *)&taa[1];
7667 
7668 		/* Fill zeroes and then intialize non-zero fields */
7669 		*sin = sin_null;
7670 
7671 		sin->sin_family = AF_INET;
7672 
7673 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7674 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7675 
7676 		ackmp->b_wptr = (uchar_t *)&sin[1];
7677 
7678 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7679 			/*
7680 			 * Fill in Remote address
7681 			 */
7682 			taa->REMADDR_length = sizeof (sin_t);
7683 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7684 			    taa->LOCADDR_length);
7685 
7686 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7687 			*sin = sin_null;
7688 			sin->sin_family = AF_INET;
7689 			sin->sin_addr.s_addr = tcp->tcp_remote;
7690 			sin->sin_port = tcp->tcp_fport;
7691 
7692 			ackmp->b_wptr = (uchar_t *)&sin[1];
7693 		}
7694 	}
7695 	putnext(tcp->tcp_rq, ackmp);
7696 }
7697 
7698 /* Assumes that tcp_addr_req gets enough space and alignment */
7699 static void
7700 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7701 {
7702 	sin6_t	*sin6;
7703 	struct T_addr_ack *taa;
7704 
7705 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7706 	ASSERT(OK_32PTR(ackmp->b_rptr));
7707 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7708 	    2 * sizeof (sin6_t));
7709 
7710 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7711 
7712 	bzero(taa, sizeof (struct T_addr_ack));
7713 	ackmp->b_wptr = (uchar_t *)&taa[1];
7714 
7715 	taa->PRIM_type = T_ADDR_ACK;
7716 	ackmp->b_datap->db_type = M_PCPROTO;
7717 
7718 	/*
7719 	 * Note: Following code assumes 32 bit alignment of basic
7720 	 * data structures like sin6_t and struct T_addr_ack.
7721 	 */
7722 	if (tcp->tcp_state >= TCPS_BOUND) {
7723 		/*
7724 		 * Fill in local address
7725 		 */
7726 		taa->LOCADDR_length = sizeof (sin6_t);
7727 		taa->LOCADDR_offset = sizeof (*taa);
7728 
7729 		sin6 = (sin6_t *)&taa[1];
7730 		*sin6 = sin6_null;
7731 
7732 		sin6->sin6_family = AF_INET6;
7733 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7734 		sin6->sin6_port = tcp->tcp_lport;
7735 
7736 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7737 
7738 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7739 			/*
7740 			 * Fill in Remote address
7741 			 */
7742 			taa->REMADDR_length = sizeof (sin6_t);
7743 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7744 			    taa->LOCADDR_length);
7745 
7746 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7747 			*sin6 = sin6_null;
7748 			sin6->sin6_family = AF_INET6;
7749 			sin6->sin6_flowinfo =
7750 			    tcp->tcp_ip6h->ip6_vcf &
7751 			    ~IPV6_VERS_AND_FLOW_MASK;
7752 			sin6->sin6_addr = tcp->tcp_remote_v6;
7753 			sin6->sin6_port = tcp->tcp_fport;
7754 
7755 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7756 		}
7757 	}
7758 	putnext(tcp->tcp_rq, ackmp);
7759 }
7760 
7761 /*
7762  * Handle reinitialization of a tcp structure.
7763  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7764  */
7765 static void
7766 tcp_reinit(tcp_t *tcp)
7767 {
7768 	mblk_t	*mp;
7769 	int 	err;
7770 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7771 
7772 	TCP_STAT(tcps, tcp_reinit_calls);
7773 
7774 	/* tcp_reinit should never be called for detached tcp_t's */
7775 	ASSERT(tcp->tcp_listener == NULL);
7776 	ASSERT((tcp->tcp_family == AF_INET &&
7777 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7778 	    (tcp->tcp_family == AF_INET6 &&
7779 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7780 	    tcp->tcp_ipversion == IPV6_VERSION)));
7781 
7782 	/* Cancel outstanding timers */
7783 	tcp_timers_stop(tcp);
7784 
7785 	/*
7786 	 * Reset everything in the state vector, after updating global
7787 	 * MIB data from instance counters.
7788 	 */
7789 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7790 	tcp->tcp_ibsegs = 0;
7791 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7792 	tcp->tcp_obsegs = 0;
7793 
7794 	tcp_close_mpp(&tcp->tcp_xmit_head);
7795 	if (tcp->tcp_snd_zcopy_aware)
7796 		tcp_zcopy_notify(tcp);
7797 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7798 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7799 	mutex_enter(&tcp->tcp_non_sq_lock);
7800 	if (tcp->tcp_flow_stopped &&
7801 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7802 		tcp_clrqfull(tcp);
7803 	}
7804 	mutex_exit(&tcp->tcp_non_sq_lock);
7805 	tcp_close_mpp(&tcp->tcp_reass_head);
7806 	tcp->tcp_reass_tail = NULL;
7807 	if (tcp->tcp_rcv_list != NULL) {
7808 		/* Free b_next chain */
7809 		tcp_close_mpp(&tcp->tcp_rcv_list);
7810 		tcp->tcp_rcv_last_head = NULL;
7811 		tcp->tcp_rcv_last_tail = NULL;
7812 		tcp->tcp_rcv_cnt = 0;
7813 	}
7814 	tcp->tcp_rcv_last_tail = NULL;
7815 
7816 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7817 		freemsg(mp);
7818 		tcp->tcp_urp_mp = NULL;
7819 	}
7820 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7821 		freemsg(mp);
7822 		tcp->tcp_urp_mark_mp = NULL;
7823 	}
7824 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7825 		freeb(tcp->tcp_fused_sigurg_mp);
7826 		tcp->tcp_fused_sigurg_mp = NULL;
7827 	}
7828 	if (tcp->tcp_ordrel_mp != NULL) {
7829 		freeb(tcp->tcp_ordrel_mp);
7830 		tcp->tcp_ordrel_mp = NULL;
7831 	}
7832 
7833 	/*
7834 	 * Following is a union with two members which are
7835 	 * identical types and size so the following cleanup
7836 	 * is enough.
7837 	 */
7838 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7839 
7840 	CL_INET_DISCONNECT(tcp);
7841 
7842 	/*
7843 	 * The connection can't be on the tcp_time_wait_head list
7844 	 * since it is not detached.
7845 	 */
7846 	ASSERT(tcp->tcp_time_wait_next == NULL);
7847 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7848 	ASSERT(tcp->tcp_time_wait_expire == 0);
7849 
7850 	if (tcp->tcp_kssl_pending) {
7851 		tcp->tcp_kssl_pending = B_FALSE;
7852 
7853 		/* Don't reset if the initialized by bind. */
7854 		if (tcp->tcp_kssl_ent != NULL) {
7855 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7856 			    KSSL_NO_PROXY);
7857 		}
7858 	}
7859 	if (tcp->tcp_kssl_ctx != NULL) {
7860 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7861 		tcp->tcp_kssl_ctx = NULL;
7862 	}
7863 
7864 	/*
7865 	 * Reset/preserve other values
7866 	 */
7867 	tcp_reinit_values(tcp);
7868 	ipcl_hash_remove(tcp->tcp_connp);
7869 	conn_delete_ire(tcp->tcp_connp, NULL);
7870 	tcp_ipsec_cleanup(tcp);
7871 
7872 	if (tcp->tcp_conn_req_max != 0) {
7873 		/*
7874 		 * This is the case when a TLI program uses the same
7875 		 * transport end point to accept a connection.  This
7876 		 * makes the TCP both a listener and acceptor.  When
7877 		 * this connection is closed, we need to set the state
7878 		 * back to TCPS_LISTEN.  Make sure that the eager list
7879 		 * is reinitialized.
7880 		 *
7881 		 * Note that this stream is still bound to the four
7882 		 * tuples of the previous connection in IP.  If a new
7883 		 * SYN with different foreign address comes in, IP will
7884 		 * not find it and will send it to the global queue.  In
7885 		 * the global queue, TCP will do a tcp_lookup_listener()
7886 		 * to find this stream.  This works because this stream
7887 		 * is only removed from connected hash.
7888 		 *
7889 		 */
7890 		tcp->tcp_state = TCPS_LISTEN;
7891 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7892 		tcp->tcp_eager_next_drop_q0 = tcp;
7893 		tcp->tcp_eager_prev_drop_q0 = tcp;
7894 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7895 		if (tcp->tcp_family == AF_INET6) {
7896 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7897 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7898 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7899 		} else {
7900 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7901 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7902 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7903 		}
7904 	} else {
7905 		tcp->tcp_state = TCPS_BOUND;
7906 	}
7907 
7908 	/*
7909 	 * Initialize to default values
7910 	 * Can't fail since enough header template space already allocated
7911 	 * at open().
7912 	 */
7913 	err = tcp_init_values(tcp);
7914 	ASSERT(err == 0);
7915 	/* Restore state in tcp_tcph */
7916 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7917 	if (tcp->tcp_ipversion == IPV4_VERSION)
7918 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7919 	else
7920 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7921 	/*
7922 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7923 	 * since the lookup funcs can only lookup on tcp_t
7924 	 */
7925 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7926 
7927 	ASSERT(tcp->tcp_ptpbhn != NULL);
7928 	tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7929 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7930 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7931 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7932 }
7933 
7934 /*
7935  * Force values to zero that need be zero.
7936  * Do not touch values asociated with the BOUND or LISTEN state
7937  * since the connection will end up in that state after the reinit.
7938  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7939  * structure!
7940  */
7941 static void
7942 tcp_reinit_values(tcp)
7943 	tcp_t *tcp;
7944 {
7945 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7946 
7947 #ifndef	lint
7948 #define	DONTCARE(x)
7949 #define	PRESERVE(x)
7950 #else
7951 #define	DONTCARE(x)	((x) = (x))
7952 #define	PRESERVE(x)	((x) = (x))
7953 #endif	/* lint */
7954 
7955 	PRESERVE(tcp->tcp_bind_hash);
7956 	PRESERVE(tcp->tcp_ptpbhn);
7957 	PRESERVE(tcp->tcp_acceptor_hash);
7958 	PRESERVE(tcp->tcp_ptpahn);
7959 
7960 	/* Should be ASSERT NULL on these with new code! */
7961 	ASSERT(tcp->tcp_time_wait_next == NULL);
7962 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7963 	ASSERT(tcp->tcp_time_wait_expire == 0);
7964 	PRESERVE(tcp->tcp_state);
7965 	PRESERVE(tcp->tcp_rq);
7966 	PRESERVE(tcp->tcp_wq);
7967 
7968 	ASSERT(tcp->tcp_xmit_head == NULL);
7969 	ASSERT(tcp->tcp_xmit_last == NULL);
7970 	ASSERT(tcp->tcp_unsent == 0);
7971 	ASSERT(tcp->tcp_xmit_tail == NULL);
7972 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7973 
7974 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7975 	tcp->tcp_suna = 0;			/* Displayed in mib */
7976 	tcp->tcp_swnd = 0;
7977 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7978 
7979 	ASSERT(tcp->tcp_ibsegs == 0);
7980 	ASSERT(tcp->tcp_obsegs == 0);
7981 
7982 	if (tcp->tcp_iphc != NULL) {
7983 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7984 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7985 	}
7986 
7987 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7988 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7989 	DONTCARE(tcp->tcp_ipha);
7990 	DONTCARE(tcp->tcp_ip6h);
7991 	DONTCARE(tcp->tcp_ip_hdr_len);
7992 	DONTCARE(tcp->tcp_tcph);
7993 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7994 	tcp->tcp_valid_bits = 0;
7995 
7996 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7997 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7998 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7999 	tcp->tcp_last_rcv_lbolt = 0;
8000 
8001 	tcp->tcp_init_cwnd = 0;
8002 
8003 	tcp->tcp_urp_last_valid = 0;
8004 	tcp->tcp_hard_binding = 0;
8005 	tcp->tcp_hard_bound = 0;
8006 	PRESERVE(tcp->tcp_cred);
8007 	PRESERVE(tcp->tcp_cpid);
8008 	PRESERVE(tcp->tcp_open_time);
8009 	PRESERVE(tcp->tcp_exclbind);
8010 
8011 	tcp->tcp_fin_acked = 0;
8012 	tcp->tcp_fin_rcvd = 0;
8013 	tcp->tcp_fin_sent = 0;
8014 	tcp->tcp_ordrel_done = 0;
8015 
8016 	tcp->tcp_debug = 0;
8017 	tcp->tcp_dontroute = 0;
8018 	tcp->tcp_broadcast = 0;
8019 
8020 	tcp->tcp_useloopback = 0;
8021 	tcp->tcp_reuseaddr = 0;
8022 	tcp->tcp_oobinline = 0;
8023 	tcp->tcp_dgram_errind = 0;
8024 
8025 	tcp->tcp_detached = 0;
8026 	tcp->tcp_bind_pending = 0;
8027 	tcp->tcp_unbind_pending = 0;
8028 
8029 	tcp->tcp_snd_ws_ok = B_FALSE;
8030 	tcp->tcp_snd_ts_ok = B_FALSE;
8031 	tcp->tcp_linger = 0;
8032 	tcp->tcp_ka_enabled = 0;
8033 	tcp->tcp_zero_win_probe = 0;
8034 
8035 	tcp->tcp_loopback = 0;
8036 	tcp->tcp_refuse = 0;
8037 	tcp->tcp_localnet = 0;
8038 	tcp->tcp_syn_defense = 0;
8039 	tcp->tcp_set_timer = 0;
8040 
8041 	tcp->tcp_active_open = 0;
8042 	tcp->tcp_rexmit = B_FALSE;
8043 	tcp->tcp_xmit_zc_clean = B_FALSE;
8044 
8045 	tcp->tcp_snd_sack_ok = B_FALSE;
8046 	PRESERVE(tcp->tcp_recvdstaddr);
8047 	tcp->tcp_hwcksum = B_FALSE;
8048 
8049 	tcp->tcp_ire_ill_check_done = B_FALSE;
8050 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
8051 
8052 	tcp->tcp_mdt = B_FALSE;
8053 	tcp->tcp_mdt_hdr_head = 0;
8054 	tcp->tcp_mdt_hdr_tail = 0;
8055 
8056 	tcp->tcp_conn_def_q0 = 0;
8057 	tcp->tcp_ip_forward_progress = B_FALSE;
8058 	tcp->tcp_anon_priv_bind = 0;
8059 	tcp->tcp_ecn_ok = B_FALSE;
8060 
8061 	tcp->tcp_cwr = B_FALSE;
8062 	tcp->tcp_ecn_echo_on = B_FALSE;
8063 
8064 	if (tcp->tcp_sack_info != NULL) {
8065 		if (tcp->tcp_notsack_list != NULL) {
8066 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
8067 		}
8068 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
8069 		tcp->tcp_sack_info = NULL;
8070 	}
8071 
8072 	tcp->tcp_rcv_ws = 0;
8073 	tcp->tcp_snd_ws = 0;
8074 	tcp->tcp_ts_recent = 0;
8075 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
8076 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
8077 	tcp->tcp_if_mtu = 0;
8078 
8079 	ASSERT(tcp->tcp_reass_head == NULL);
8080 	ASSERT(tcp->tcp_reass_tail == NULL);
8081 
8082 	tcp->tcp_cwnd_cnt = 0;
8083 
8084 	ASSERT(tcp->tcp_rcv_list == NULL);
8085 	ASSERT(tcp->tcp_rcv_last_head == NULL);
8086 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
8087 	ASSERT(tcp->tcp_rcv_cnt == 0);
8088 
8089 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8090 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8091 	tcp->tcp_csuna = 0;
8092 
8093 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8094 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8095 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8096 	tcp->tcp_rtt_update = 0;
8097 
8098 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8099 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8100 
8101 	tcp->tcp_rack = 0;			/* Displayed in mib */
8102 	tcp->tcp_rack_cnt = 0;
8103 	tcp->tcp_rack_cur_max = 0;
8104 	tcp->tcp_rack_abs_max = 0;
8105 
8106 	tcp->tcp_max_swnd = 0;
8107 
8108 	ASSERT(tcp->tcp_listener == NULL);
8109 
8110 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8111 
8112 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8113 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8114 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8115 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8116 
8117 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8118 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8119 	PRESERVE(tcp->tcp_conn_req_max);
8120 	PRESERVE(tcp->tcp_conn_req_seqnum);
8121 
8122 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8123 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8124 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8125 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8126 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8127 
8128 	tcp->tcp_lingertime = 0;
8129 
8130 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8131 	ASSERT(tcp->tcp_urp_mp == NULL);
8132 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8133 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8134 
8135 	ASSERT(tcp->tcp_eager_next_q == NULL);
8136 	ASSERT(tcp->tcp_eager_last_q == NULL);
8137 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8138 	    tcp->tcp_eager_prev_q0 == NULL) ||
8139 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8140 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8141 
8142 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
8143 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
8144 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
8145 
8146 	tcp->tcp_client_errno = 0;
8147 
8148 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8149 
8150 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8151 
8152 	PRESERVE(tcp->tcp_bound_source_v6);
8153 	tcp->tcp_last_sent_len = 0;
8154 	tcp->tcp_dupack_cnt = 0;
8155 
8156 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8157 	PRESERVE(tcp->tcp_lport);
8158 
8159 	PRESERVE(tcp->tcp_acceptor_lockp);
8160 
8161 	ASSERT(tcp->tcp_ordrel_mp == NULL);
8162 	PRESERVE(tcp->tcp_acceptor_id);
8163 	DONTCARE(tcp->tcp_ipsec_overhead);
8164 
8165 	PRESERVE(tcp->tcp_family);
8166 	if (tcp->tcp_family == AF_INET6) {
8167 		tcp->tcp_ipversion = IPV6_VERSION;
8168 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
8169 	} else {
8170 		tcp->tcp_ipversion = IPV4_VERSION;
8171 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
8172 	}
8173 
8174 	tcp->tcp_bound_if = 0;
8175 	tcp->tcp_ipv6_recvancillary = 0;
8176 	tcp->tcp_recvifindex = 0;
8177 	tcp->tcp_recvhops = 0;
8178 	tcp->tcp_closed = 0;
8179 	tcp->tcp_cleandeathtag = 0;
8180 	if (tcp->tcp_hopopts != NULL) {
8181 		mi_free(tcp->tcp_hopopts);
8182 		tcp->tcp_hopopts = NULL;
8183 		tcp->tcp_hopoptslen = 0;
8184 	}
8185 	ASSERT(tcp->tcp_hopoptslen == 0);
8186 	if (tcp->tcp_dstopts != NULL) {
8187 		mi_free(tcp->tcp_dstopts);
8188 		tcp->tcp_dstopts = NULL;
8189 		tcp->tcp_dstoptslen = 0;
8190 	}
8191 	ASSERT(tcp->tcp_dstoptslen == 0);
8192 	if (tcp->tcp_rtdstopts != NULL) {
8193 		mi_free(tcp->tcp_rtdstopts);
8194 		tcp->tcp_rtdstopts = NULL;
8195 		tcp->tcp_rtdstoptslen = 0;
8196 	}
8197 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8198 	if (tcp->tcp_rthdr != NULL) {
8199 		mi_free(tcp->tcp_rthdr);
8200 		tcp->tcp_rthdr = NULL;
8201 		tcp->tcp_rthdrlen = 0;
8202 	}
8203 	ASSERT(tcp->tcp_rthdrlen == 0);
8204 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8205 
8206 	/* Reset fusion-related fields */
8207 	tcp->tcp_fused = B_FALSE;
8208 	tcp->tcp_unfusable = B_FALSE;
8209 	tcp->tcp_fused_sigurg = B_FALSE;
8210 	tcp->tcp_direct_sockfs = B_FALSE;
8211 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8212 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8213 	tcp->tcp_loopback_peer = NULL;
8214 	tcp->tcp_fuse_rcv_hiwater = 0;
8215 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8216 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8217 
8218 	tcp->tcp_lso = B_FALSE;
8219 
8220 	tcp->tcp_in_ack_unsent = 0;
8221 	tcp->tcp_cork = B_FALSE;
8222 	tcp->tcp_tconnind_started = B_FALSE;
8223 
8224 	PRESERVE(tcp->tcp_squeue_bytes);
8225 
8226 	ASSERT(tcp->tcp_kssl_ctx == NULL);
8227 	ASSERT(!tcp->tcp_kssl_pending);
8228 	PRESERVE(tcp->tcp_kssl_ent);
8229 
8230 	/* Sodirect */
8231 	tcp->tcp_sodirect = NULL;
8232 
8233 	tcp->tcp_closemp_used = B_FALSE;
8234 
8235 	PRESERVE(tcp->tcp_rsrv_mp);
8236 	PRESERVE(tcp->tcp_rsrv_mp_lock);
8237 
8238 #ifdef DEBUG
8239 	DONTCARE(tcp->tcmp_stk[0]);
8240 #endif
8241 
8242 
8243 #undef	DONTCARE
8244 #undef	PRESERVE
8245 }
8246 
8247 /*
8248  * Allocate necessary resources and initialize state vector.
8249  * Guaranteed not to fail so that when an error is returned,
8250  * the caller doesn't need to do any additional cleanup.
8251  */
8252 int
8253 tcp_init(tcp_t *tcp, queue_t *q)
8254 {
8255 	int	err;
8256 
8257 	tcp->tcp_rq = q;
8258 	tcp->tcp_wq = WR(q);
8259 	tcp->tcp_state = TCPS_IDLE;
8260 	if ((err = tcp_init_values(tcp)) != 0)
8261 		tcp_timers_stop(tcp);
8262 	return (err);
8263 }
8264 
8265 static int
8266 tcp_init_values(tcp_t *tcp)
8267 {
8268 	int	err;
8269 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8270 
8271 	ASSERT((tcp->tcp_family == AF_INET &&
8272 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8273 	    (tcp->tcp_family == AF_INET6 &&
8274 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8275 	    tcp->tcp_ipversion == IPV6_VERSION)));
8276 
8277 	/*
8278 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8279 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8280 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8281 	 * during first few transmissions of a connection as seen in slow
8282 	 * links.
8283 	 */
8284 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
8285 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
8286 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8287 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8288 	    tcps->tcps_conn_grace_period;
8289 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
8290 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
8291 	tcp->tcp_timer_backoff = 0;
8292 	tcp->tcp_ms_we_have_waited = 0;
8293 	tcp->tcp_last_recv_time = lbolt;
8294 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
8295 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8296 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8297 
8298 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
8299 
8300 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
8301 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
8302 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
8303 	/*
8304 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8305 	 * passive open.
8306 	 */
8307 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
8308 
8309 	tcp->tcp_naglim = tcps->tcps_naglim_def;
8310 
8311 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8312 
8313 	tcp->tcp_mdt_hdr_head = 0;
8314 	tcp->tcp_mdt_hdr_tail = 0;
8315 
8316 	/* Reset fusion-related fields */
8317 	tcp->tcp_fused = B_FALSE;
8318 	tcp->tcp_unfusable = B_FALSE;
8319 	tcp->tcp_fused_sigurg = B_FALSE;
8320 	tcp->tcp_direct_sockfs = B_FALSE;
8321 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8322 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8323 	tcp->tcp_loopback_peer = NULL;
8324 	tcp->tcp_fuse_rcv_hiwater = 0;
8325 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8326 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8327 
8328 	/* Sodirect */
8329 	tcp->tcp_sodirect = NULL;
8330 
8331 	/* Initialize the header template */
8332 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8333 		err = tcp_header_init_ipv4(tcp);
8334 	} else {
8335 		err = tcp_header_init_ipv6(tcp);
8336 	}
8337 	if (err)
8338 		return (err);
8339 
8340 	/*
8341 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8342 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8343 	 */
8344 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8345 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8346 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8347 
8348 	tcp->tcp_cork = B_FALSE;
8349 	/*
8350 	 * Init the tcp_debug option.  This value determines whether TCP
8351 	 * calls strlog() to print out debug messages.  Doing this
8352 	 * initialization here means that this value is not inherited thru
8353 	 * tcp_reinit().
8354 	 */
8355 	tcp->tcp_debug = tcps->tcps_dbg;
8356 
8357 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8358 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8359 
8360 	return (0);
8361 }
8362 
8363 /*
8364  * Initialize the IPv4 header. Loses any record of any IP options.
8365  */
8366 static int
8367 tcp_header_init_ipv4(tcp_t *tcp)
8368 {
8369 	tcph_t		*tcph;
8370 	uint32_t	sum;
8371 	conn_t		*connp;
8372 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8373 
8374 	/*
8375 	 * This is a simple initialization. If there's
8376 	 * already a template, it should never be too small,
8377 	 * so reuse it.  Otherwise, allocate space for the new one.
8378 	 */
8379 	if (tcp->tcp_iphc == NULL) {
8380 		ASSERT(tcp->tcp_iphc_len == 0);
8381 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8382 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8383 		if (tcp->tcp_iphc == NULL) {
8384 			tcp->tcp_iphc_len = 0;
8385 			return (ENOMEM);
8386 		}
8387 	}
8388 
8389 	/* options are gone; may need a new label */
8390 	connp = tcp->tcp_connp;
8391 	connp->conn_mlp_type = mlptSingle;
8392 	connp->conn_ulp_labeled = !is_system_labeled();
8393 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8394 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8395 	tcp->tcp_ip6h = NULL;
8396 	tcp->tcp_ipversion = IPV4_VERSION;
8397 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8398 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8399 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8400 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8401 	tcp->tcp_ipha->ipha_version_and_hdr_length
8402 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8403 	tcp->tcp_ipha->ipha_ident = 0;
8404 
8405 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8406 	tcp->tcp_tos = 0;
8407 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8408 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8409 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8410 
8411 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8412 	tcp->tcp_tcph = tcph;
8413 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8414 	/*
8415 	 * IP wants our header length in the checksum field to
8416 	 * allow it to perform a single pseudo-header+checksum
8417 	 * calculation on behalf of TCP.
8418 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8419 	 */
8420 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8421 	sum = (sum >> 16) + (sum & 0xFFFF);
8422 	U16_TO_ABE16(sum, tcph->th_sum);
8423 	return (0);
8424 }
8425 
8426 /*
8427  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8428  */
8429 static int
8430 tcp_header_init_ipv6(tcp_t *tcp)
8431 {
8432 	tcph_t	*tcph;
8433 	uint32_t	sum;
8434 	conn_t	*connp;
8435 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8436 
8437 	/*
8438 	 * This is a simple initialization. If there's
8439 	 * already a template, it should never be too small,
8440 	 * so reuse it. Otherwise, allocate space for the new one.
8441 	 * Ensure that there is enough space to "downgrade" the tcp_t
8442 	 * to an IPv4 tcp_t. This requires having space for a full load
8443 	 * of IPv4 options, as well as a full load of TCP options
8444 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8445 	 * than a v6 header and a TCP header with a full load of TCP options
8446 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8447 	 * We want to avoid reallocation in the "downgraded" case when
8448 	 * processing outbound IPv4 options.
8449 	 */
8450 	if (tcp->tcp_iphc == NULL) {
8451 		ASSERT(tcp->tcp_iphc_len == 0);
8452 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8453 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8454 		if (tcp->tcp_iphc == NULL) {
8455 			tcp->tcp_iphc_len = 0;
8456 			return (ENOMEM);
8457 		}
8458 	}
8459 
8460 	/* options are gone; may need a new label */
8461 	connp = tcp->tcp_connp;
8462 	connp->conn_mlp_type = mlptSingle;
8463 	connp->conn_ulp_labeled = !is_system_labeled();
8464 
8465 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8466 	tcp->tcp_ipversion = IPV6_VERSION;
8467 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8468 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8469 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8470 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8471 	tcp->tcp_ipha = NULL;
8472 
8473 	/* Initialize the header template */
8474 
8475 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8476 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8477 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8478 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8479 
8480 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8481 	tcp->tcp_tcph = tcph;
8482 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8483 	/*
8484 	 * IP wants our header length in the checksum field to
8485 	 * allow it to perform a single psuedo-header+checksum
8486 	 * calculation on behalf of TCP.
8487 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8488 	 */
8489 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8490 	sum = (sum >> 16) + (sum & 0xFFFF);
8491 	U16_TO_ABE16(sum, tcph->th_sum);
8492 	return (0);
8493 }
8494 
8495 /* At minimum we need 8 bytes in the TCP header for the lookup */
8496 #define	ICMP_MIN_TCP_HDR	8
8497 
8498 /*
8499  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8500  * passed up by IP. The message is always received on the correct tcp_t.
8501  * Assumes that IP has pulled up everything up to and including the ICMP header.
8502  */
8503 void
8504 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8505 {
8506 	icmph_t *icmph;
8507 	ipha_t	*ipha;
8508 	int	iph_hdr_length;
8509 	tcph_t	*tcph;
8510 	boolean_t ipsec_mctl = B_FALSE;
8511 	boolean_t secure;
8512 	mblk_t *first_mp = mp;
8513 	int32_t new_mss;
8514 	uint32_t ratio;
8515 	size_t mp_size = MBLKL(mp);
8516 	uint32_t seg_seq;
8517 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8518 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8519 
8520 	/* Assume IP provides aligned packets - otherwise toss */
8521 	if (!OK_32PTR(mp->b_rptr)) {
8522 		freemsg(mp);
8523 		return;
8524 	}
8525 
8526 	/*
8527 	 * Since ICMP errors are normal data marked with M_CTL when sent
8528 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8529 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8530 	 */
8531 	if ((mp_size == sizeof (ipsec_info_t)) &&
8532 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8533 		ASSERT(mp->b_cont != NULL);
8534 		mp = mp->b_cont;
8535 		/* IP should have done this */
8536 		ASSERT(OK_32PTR(mp->b_rptr));
8537 		mp_size = MBLKL(mp);
8538 		ipsec_mctl = B_TRUE;
8539 	}
8540 
8541 	/*
8542 	 * Verify that we have a complete outer IP header. If not, drop it.
8543 	 */
8544 	if (mp_size < sizeof (ipha_t)) {
8545 noticmpv4:
8546 		freemsg(first_mp);
8547 		return;
8548 	}
8549 
8550 	ipha = (ipha_t *)mp->b_rptr;
8551 	/*
8552 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8553 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8554 	 */
8555 	switch (IPH_HDR_VERSION(ipha)) {
8556 	case IPV6_VERSION:
8557 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8558 		return;
8559 	case IPV4_VERSION:
8560 		break;
8561 	default:
8562 		goto noticmpv4;
8563 	}
8564 
8565 	/* Skip past the outer IP and ICMP headers */
8566 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8567 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8568 	/*
8569 	 * If we don't have the correct outer IP header length or if the ULP
8570 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8571 	 * send it upstream.
8572 	 */
8573 	if (iph_hdr_length < sizeof (ipha_t) ||
8574 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8575 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8576 		goto noticmpv4;
8577 	}
8578 	ipha = (ipha_t *)&icmph[1];
8579 
8580 	/* Skip past the inner IP and find the ULP header */
8581 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8582 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8583 	/*
8584 	 * If we don't have the correct inner IP header length or if the ULP
8585 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8586 	 * bytes of TCP header, drop it.
8587 	 */
8588 	if (iph_hdr_length < sizeof (ipha_t) ||
8589 	    ipha->ipha_protocol != IPPROTO_TCP ||
8590 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8591 		goto noticmpv4;
8592 	}
8593 
8594 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8595 		if (ipsec_mctl) {
8596 			secure = ipsec_in_is_secure(first_mp);
8597 		} else {
8598 			secure = B_FALSE;
8599 		}
8600 		if (secure) {
8601 			/*
8602 			 * If we are willing to accept this in clear
8603 			 * we don't have to verify policy.
8604 			 */
8605 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8606 				if (!tcp_check_policy(tcp, first_mp,
8607 				    ipha, NULL, secure, ipsec_mctl)) {
8608 					/*
8609 					 * tcp_check_policy called
8610 					 * ip_drop_packet() on failure.
8611 					 */
8612 					return;
8613 				}
8614 			}
8615 		}
8616 	} else if (ipsec_mctl) {
8617 		/*
8618 		 * This is a hard_bound connection. IP has already
8619 		 * verified policy. We don't have to do it again.
8620 		 */
8621 		freeb(first_mp);
8622 		first_mp = mp;
8623 		ipsec_mctl = B_FALSE;
8624 	}
8625 
8626 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8627 	/*
8628 	 * TCP SHOULD check that the TCP sequence number contained in
8629 	 * payload of the ICMP error message is within the range
8630 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8631 	 */
8632 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8633 		/*
8634 		 * The ICMP message is bogus, just drop it.  But if this is
8635 		 * an ICMP too big message, IP has already changed
8636 		 * the ire_max_frag to the bogus value.  We need to change
8637 		 * it back.
8638 		 */
8639 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8640 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8641 			conn_t *connp = tcp->tcp_connp;
8642 			ire_t *ire;
8643 			int flag;
8644 
8645 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8646 				flag = tcp->tcp_ipha->
8647 				    ipha_fragment_offset_and_flags;
8648 			} else {
8649 				flag = 0;
8650 			}
8651 			mutex_enter(&connp->conn_lock);
8652 			if ((ire = connp->conn_ire_cache) != NULL) {
8653 				mutex_enter(&ire->ire_lock);
8654 				mutex_exit(&connp->conn_lock);
8655 				ire->ire_max_frag = tcp->tcp_if_mtu;
8656 				ire->ire_frag_flag |= flag;
8657 				mutex_exit(&ire->ire_lock);
8658 			} else {
8659 				mutex_exit(&connp->conn_lock);
8660 			}
8661 		}
8662 		goto noticmpv4;
8663 	}
8664 
8665 	switch (icmph->icmph_type) {
8666 	case ICMP_DEST_UNREACHABLE:
8667 		switch (icmph->icmph_code) {
8668 		case ICMP_FRAGMENTATION_NEEDED:
8669 			/*
8670 			 * Reduce the MSS based on the new MTU.  This will
8671 			 * eliminate any fragmentation locally.
8672 			 * N.B.  There may well be some funny side-effects on
8673 			 * the local send policy and the remote receive policy.
8674 			 * Pending further research, we provide
8675 			 * tcp_ignore_path_mtu just in case this proves
8676 			 * disastrous somewhere.
8677 			 *
8678 			 * After updating the MSS, retransmit part of the
8679 			 * dropped segment using the new mss by calling
8680 			 * tcp_wput_data().  Need to adjust all those
8681 			 * params to make sure tcp_wput_data() work properly.
8682 			 */
8683 			if (tcps->tcps_ignore_path_mtu ||
8684 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8685 				break;
8686 
8687 			/*
8688 			 * Decrease the MSS by time stamp options
8689 			 * IP options and IPSEC options. tcp_hdr_len
8690 			 * includes time stamp option and IP option
8691 			 * length.  Note that new_mss may be negative
8692 			 * if tcp_ipsec_overhead is large and the
8693 			 * icmph_du_mtu is the minimum value, which is 68.
8694 			 */
8695 			new_mss = ntohs(icmph->icmph_du_mtu) -
8696 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8697 
8698 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8699 			    new_mss);
8700 
8701 			/*
8702 			 * Only update the MSS if the new one is
8703 			 * smaller than the previous one.  This is
8704 			 * to avoid problems when getting multiple
8705 			 * ICMP errors for the same MTU.
8706 			 */
8707 			if (new_mss >= tcp->tcp_mss)
8708 				break;
8709 
8710 			/*
8711 			 * Note that we are using the template header's DF
8712 			 * bit in the fast path sending.  So we need to compare
8713 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8714 			 * And stop doing IPv4 PMTUd if new_mss is less than
8715 			 * MAX(tcps_mss_min, ip_pmtu_min).
8716 			 */
8717 			if (new_mss < tcps->tcps_mss_min ||
8718 			    new_mss < ipst->ips_ip_pmtu_min) {
8719 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8720 				    0;
8721 			}
8722 
8723 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8724 			ASSERT(ratio >= 1);
8725 			tcp_mss_set(tcp, new_mss, B_TRUE);
8726 
8727 			/*
8728 			 * Make sure we have something to
8729 			 * send.
8730 			 */
8731 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8732 			    (tcp->tcp_xmit_head != NULL)) {
8733 				/*
8734 				 * Shrink tcp_cwnd in
8735 				 * proportion to the old MSS/new MSS.
8736 				 */
8737 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8738 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8739 				    (tcp->tcp_unsent == 0)) {
8740 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8741 				} else {
8742 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8743 				}
8744 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8745 				tcp->tcp_rexmit = B_TRUE;
8746 				tcp->tcp_dupack_cnt = 0;
8747 				tcp->tcp_snd_burst = TCP_CWND_SS;
8748 				tcp_ss_rexmit(tcp);
8749 			}
8750 			break;
8751 		case ICMP_PORT_UNREACHABLE:
8752 		case ICMP_PROTOCOL_UNREACHABLE:
8753 			switch (tcp->tcp_state) {
8754 			case TCPS_SYN_SENT:
8755 			case TCPS_SYN_RCVD:
8756 				/*
8757 				 * ICMP can snipe away incipient
8758 				 * TCP connections as long as
8759 				 * seq number is same as initial
8760 				 * send seq number.
8761 				 */
8762 				if (seg_seq == tcp->tcp_iss) {
8763 					(void) tcp_clean_death(tcp,
8764 					    ECONNREFUSED, 6);
8765 				}
8766 				break;
8767 			}
8768 			break;
8769 		case ICMP_HOST_UNREACHABLE:
8770 		case ICMP_NET_UNREACHABLE:
8771 			/* Record the error in case we finally time out. */
8772 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8773 				tcp->tcp_client_errno = EHOSTUNREACH;
8774 			else
8775 				tcp->tcp_client_errno = ENETUNREACH;
8776 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8777 				if (tcp->tcp_listener != NULL &&
8778 				    tcp->tcp_listener->tcp_syn_defense) {
8779 					/*
8780 					 * Ditch the half-open connection if we
8781 					 * suspect a SYN attack is under way.
8782 					 */
8783 					tcp_ip_ire_mark_advice(tcp);
8784 					(void) tcp_clean_death(tcp,
8785 					    tcp->tcp_client_errno, 7);
8786 				}
8787 			}
8788 			break;
8789 		default:
8790 			break;
8791 		}
8792 		break;
8793 	case ICMP_SOURCE_QUENCH: {
8794 		/*
8795 		 * use a global boolean to control
8796 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8797 		 * The default is false.
8798 		 */
8799 		if (tcp_icmp_source_quench) {
8800 			/*
8801 			 * Reduce the sending rate as if we got a
8802 			 * retransmit timeout
8803 			 */
8804 			uint32_t npkt;
8805 
8806 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8807 			    tcp->tcp_mss;
8808 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8809 			tcp->tcp_cwnd = tcp->tcp_mss;
8810 			tcp->tcp_cwnd_cnt = 0;
8811 		}
8812 		break;
8813 	}
8814 	}
8815 	freemsg(first_mp);
8816 }
8817 
8818 /*
8819  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8820  * error messages passed up by IP.
8821  * Assumes that IP has pulled up all the extension headers as well
8822  * as the ICMPv6 header.
8823  */
8824 static void
8825 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8826 {
8827 	icmp6_t *icmp6;
8828 	ip6_t	*ip6h;
8829 	uint16_t	iph_hdr_length;
8830 	tcpha_t	*tcpha;
8831 	uint8_t	*nexthdrp;
8832 	uint32_t new_mss;
8833 	uint32_t ratio;
8834 	boolean_t secure;
8835 	mblk_t *first_mp = mp;
8836 	size_t mp_size;
8837 	uint32_t seg_seq;
8838 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8839 
8840 	/*
8841 	 * The caller has determined if this is an IPSEC_IN packet and
8842 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8843 	 */
8844 	if (ipsec_mctl)
8845 		mp = mp->b_cont;
8846 
8847 	mp_size = MBLKL(mp);
8848 
8849 	/*
8850 	 * Verify that we have a complete IP header. If not, send it upstream.
8851 	 */
8852 	if (mp_size < sizeof (ip6_t)) {
8853 noticmpv6:
8854 		freemsg(first_mp);
8855 		return;
8856 	}
8857 
8858 	/*
8859 	 * Verify this is an ICMPV6 packet, else send it upstream.
8860 	 */
8861 	ip6h = (ip6_t *)mp->b_rptr;
8862 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8863 		iph_hdr_length = IPV6_HDR_LEN;
8864 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8865 	    &nexthdrp) ||
8866 	    *nexthdrp != IPPROTO_ICMPV6) {
8867 		goto noticmpv6;
8868 	}
8869 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8870 	ip6h = (ip6_t *)&icmp6[1];
8871 	/*
8872 	 * Verify if we have a complete ICMP and inner IP header.
8873 	 */
8874 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8875 		goto noticmpv6;
8876 
8877 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8878 		goto noticmpv6;
8879 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8880 	/*
8881 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8882 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8883 	 * packet.
8884 	 */
8885 	if ((*nexthdrp != IPPROTO_TCP) ||
8886 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8887 		goto noticmpv6;
8888 	}
8889 
8890 	/*
8891 	 * ICMP errors come on the right queue or come on
8892 	 * listener/global queue for detached connections and
8893 	 * get switched to the right queue. If it comes on the
8894 	 * right queue, policy check has already been done by IP
8895 	 * and thus free the first_mp without verifying the policy.
8896 	 * If it has come for a non-hard bound connection, we need
8897 	 * to verify policy as IP may not have done it.
8898 	 */
8899 	if (!tcp->tcp_hard_bound) {
8900 		if (ipsec_mctl) {
8901 			secure = ipsec_in_is_secure(first_mp);
8902 		} else {
8903 			secure = B_FALSE;
8904 		}
8905 		if (secure) {
8906 			/*
8907 			 * If we are willing to accept this in clear
8908 			 * we don't have to verify policy.
8909 			 */
8910 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8911 				if (!tcp_check_policy(tcp, first_mp,
8912 				    NULL, ip6h, secure, ipsec_mctl)) {
8913 					/*
8914 					 * tcp_check_policy called
8915 					 * ip_drop_packet() on failure.
8916 					 */
8917 					return;
8918 				}
8919 			}
8920 		}
8921 	} else if (ipsec_mctl) {
8922 		/*
8923 		 * This is a hard_bound connection. IP has already
8924 		 * verified policy. We don't have to do it again.
8925 		 */
8926 		freeb(first_mp);
8927 		first_mp = mp;
8928 		ipsec_mctl = B_FALSE;
8929 	}
8930 
8931 	seg_seq = ntohl(tcpha->tha_seq);
8932 	/*
8933 	 * TCP SHOULD check that the TCP sequence number contained in
8934 	 * payload of the ICMP error message is within the range
8935 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8936 	 */
8937 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8938 		/*
8939 		 * If the ICMP message is bogus, should we kill the
8940 		 * connection, or should we just drop the bogus ICMP
8941 		 * message? It would probably make more sense to just
8942 		 * drop the message so that if this one managed to get
8943 		 * in, the real connection should not suffer.
8944 		 */
8945 		goto noticmpv6;
8946 	}
8947 
8948 	switch (icmp6->icmp6_type) {
8949 	case ICMP6_PACKET_TOO_BIG:
8950 		/*
8951 		 * Reduce the MSS based on the new MTU.  This will
8952 		 * eliminate any fragmentation locally.
8953 		 * N.B.  There may well be some funny side-effects on
8954 		 * the local send policy and the remote receive policy.
8955 		 * Pending further research, we provide
8956 		 * tcp_ignore_path_mtu just in case this proves
8957 		 * disastrous somewhere.
8958 		 *
8959 		 * After updating the MSS, retransmit part of the
8960 		 * dropped segment using the new mss by calling
8961 		 * tcp_wput_data().  Need to adjust all those
8962 		 * params to make sure tcp_wput_data() work properly.
8963 		 */
8964 		if (tcps->tcps_ignore_path_mtu)
8965 			break;
8966 
8967 		/*
8968 		 * Decrease the MSS by time stamp options
8969 		 * IP options and IPSEC options. tcp_hdr_len
8970 		 * includes time stamp option and IP option
8971 		 * length.
8972 		 */
8973 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8974 		    tcp->tcp_ipsec_overhead;
8975 
8976 		/*
8977 		 * Only update the MSS if the new one is
8978 		 * smaller than the previous one.  This is
8979 		 * to avoid problems when getting multiple
8980 		 * ICMP errors for the same MTU.
8981 		 */
8982 		if (new_mss >= tcp->tcp_mss)
8983 			break;
8984 
8985 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8986 		ASSERT(ratio >= 1);
8987 		tcp_mss_set(tcp, new_mss, B_TRUE);
8988 
8989 		/*
8990 		 * Make sure we have something to
8991 		 * send.
8992 		 */
8993 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8994 		    (tcp->tcp_xmit_head != NULL)) {
8995 			/*
8996 			 * Shrink tcp_cwnd in
8997 			 * proportion to the old MSS/new MSS.
8998 			 */
8999 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
9000 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
9001 			    (tcp->tcp_unsent == 0)) {
9002 				tcp->tcp_rexmit_max = tcp->tcp_fss;
9003 			} else {
9004 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
9005 			}
9006 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
9007 			tcp->tcp_rexmit = B_TRUE;
9008 			tcp->tcp_dupack_cnt = 0;
9009 			tcp->tcp_snd_burst = TCP_CWND_SS;
9010 			tcp_ss_rexmit(tcp);
9011 		}
9012 		break;
9013 
9014 	case ICMP6_DST_UNREACH:
9015 		switch (icmp6->icmp6_code) {
9016 		case ICMP6_DST_UNREACH_NOPORT:
9017 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9018 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9019 			    (seg_seq == tcp->tcp_iss)) {
9020 				(void) tcp_clean_death(tcp,
9021 				    ECONNREFUSED, 8);
9022 			}
9023 			break;
9024 
9025 		case ICMP6_DST_UNREACH_ADMIN:
9026 		case ICMP6_DST_UNREACH_NOROUTE:
9027 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
9028 		case ICMP6_DST_UNREACH_ADDR:
9029 			/* Record the error in case we finally time out. */
9030 			tcp->tcp_client_errno = EHOSTUNREACH;
9031 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9032 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9033 			    (seg_seq == tcp->tcp_iss)) {
9034 				if (tcp->tcp_listener != NULL &&
9035 				    tcp->tcp_listener->tcp_syn_defense) {
9036 					/*
9037 					 * Ditch the half-open connection if we
9038 					 * suspect a SYN attack is under way.
9039 					 */
9040 					tcp_ip_ire_mark_advice(tcp);
9041 					(void) tcp_clean_death(tcp,
9042 					    tcp->tcp_client_errno, 9);
9043 				}
9044 			}
9045 
9046 
9047 			break;
9048 		default:
9049 			break;
9050 		}
9051 		break;
9052 
9053 	case ICMP6_PARAM_PROB:
9054 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
9055 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
9056 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
9057 		    (uchar_t *)nexthdrp) {
9058 			if (tcp->tcp_state == TCPS_SYN_SENT ||
9059 			    tcp->tcp_state == TCPS_SYN_RCVD) {
9060 				(void) tcp_clean_death(tcp,
9061 				    ECONNREFUSED, 10);
9062 			}
9063 			break;
9064 		}
9065 		break;
9066 
9067 	case ICMP6_TIME_EXCEEDED:
9068 	default:
9069 		break;
9070 	}
9071 	freemsg(first_mp);
9072 }
9073 
9074 /*
9075  * IP recognizes seven kinds of bind requests:
9076  *
9077  * - A zero-length address binds only to the protocol number.
9078  *
9079  * - A 4-byte address is treated as a request to
9080  * validate that the address is a valid local IPv4
9081  * address, appropriate for an application to bind to.
9082  * IP does the verification, but does not make any note
9083  * of the address at this time.
9084  *
9085  * - A 16-byte address contains is treated as a request
9086  * to validate a local IPv6 address, as the 4-byte
9087  * address case above.
9088  *
9089  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
9090  * use it for the inbound fanout of packets.
9091  *
9092  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
9093  * use it for the inbound fanout of packets.
9094  *
9095  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
9096  * information consisting of local and remote addresses
9097  * and ports.  In this case, the addresses are both
9098  * validated as appropriate for this operation, and, if
9099  * so, the information is retained for use in the
9100  * inbound fanout.
9101  *
9102  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
9103  * fanout information, like the 12-byte case above.
9104  *
9105  * IP will also fill in the IRE request mblk with information
9106  * regarding our peer.  In all cases, we notify IP of our protocol
9107  * type by appending a single protocol byte to the bind request.
9108  */
9109 static mblk_t *
9110 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
9111 {
9112 	char	*cp;
9113 	mblk_t	*mp;
9114 	struct T_bind_req *tbr;
9115 	ipa_conn_t	*ac;
9116 	ipa6_conn_t	*ac6;
9117 	sin_t		*sin;
9118 	sin6_t		*sin6;
9119 
9120 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9121 	ASSERT((tcp->tcp_family == AF_INET &&
9122 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9123 	    (tcp->tcp_family == AF_INET6 &&
9124 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9125 	    tcp->tcp_ipversion == IPV6_VERSION)));
9126 
9127 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9128 	if (!mp)
9129 		return (mp);
9130 	mp->b_datap->db_type = M_PROTO;
9131 	tbr = (struct T_bind_req *)mp->b_rptr;
9132 	tbr->PRIM_type = bind_prim;
9133 	tbr->ADDR_offset = sizeof (*tbr);
9134 	tbr->CONIND_number = 0;
9135 	tbr->ADDR_length = addr_length;
9136 	cp = (char *)&tbr[1];
9137 	switch (addr_length) {
9138 	case sizeof (ipa_conn_t):
9139 		ASSERT(tcp->tcp_family == AF_INET);
9140 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9141 
9142 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9143 		if (mp->b_cont == NULL) {
9144 			freemsg(mp);
9145 			return (NULL);
9146 		}
9147 		mp->b_cont->b_wptr += sizeof (ire_t);
9148 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9149 
9150 		/* cp known to be 32 bit aligned */
9151 		ac = (ipa_conn_t *)cp;
9152 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9153 		ac->ac_faddr = tcp->tcp_remote;
9154 		ac->ac_fport = tcp->tcp_fport;
9155 		ac->ac_lport = tcp->tcp_lport;
9156 		tcp->tcp_hard_binding = 1;
9157 		break;
9158 
9159 	case sizeof (ipa6_conn_t):
9160 		ASSERT(tcp->tcp_family == AF_INET6);
9161 
9162 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9163 		if (mp->b_cont == NULL) {
9164 			freemsg(mp);
9165 			return (NULL);
9166 		}
9167 		mp->b_cont->b_wptr += sizeof (ire_t);
9168 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9169 
9170 		/* cp known to be 32 bit aligned */
9171 		ac6 = (ipa6_conn_t *)cp;
9172 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9173 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9174 			    &ac6->ac6_laddr);
9175 		} else {
9176 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9177 		}
9178 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9179 		ac6->ac6_fport = tcp->tcp_fport;
9180 		ac6->ac6_lport = tcp->tcp_lport;
9181 		tcp->tcp_hard_binding = 1;
9182 		break;
9183 
9184 	case sizeof (sin_t):
9185 		/*
9186 		 * NOTE: IPV6_ADDR_LEN also has same size.
9187 		 * Use family to discriminate.
9188 		 */
9189 		if (tcp->tcp_family == AF_INET) {
9190 			sin = (sin_t *)cp;
9191 
9192 			*sin = sin_null;
9193 			sin->sin_family = AF_INET;
9194 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9195 			sin->sin_port = tcp->tcp_lport;
9196 			break;
9197 		} else {
9198 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9199 		}
9200 		break;
9201 
9202 	case sizeof (sin6_t):
9203 		ASSERT(tcp->tcp_family == AF_INET6);
9204 		sin6 = (sin6_t *)cp;
9205 
9206 		*sin6 = sin6_null;
9207 		sin6->sin6_family = AF_INET6;
9208 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9209 		sin6->sin6_port = tcp->tcp_lport;
9210 		break;
9211 
9212 	case IP_ADDR_LEN:
9213 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9214 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9215 		break;
9216 
9217 	}
9218 	/* Add protocol number to end */
9219 	cp[addr_length] = (char)IPPROTO_TCP;
9220 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9221 	return (mp);
9222 }
9223 
9224 /*
9225  * Notify IP that we are having trouble with this connection.  IP should
9226  * blow the IRE away and start over.
9227  */
9228 static void
9229 tcp_ip_notify(tcp_t *tcp)
9230 {
9231 	struct iocblk	*iocp;
9232 	ipid_t	*ipid;
9233 	mblk_t	*mp;
9234 
9235 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9236 	if (tcp->tcp_ipversion == IPV6_VERSION)
9237 		return;
9238 
9239 	mp = mkiocb(IP_IOCTL);
9240 	if (mp == NULL)
9241 		return;
9242 
9243 	iocp = (struct iocblk *)mp->b_rptr;
9244 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9245 
9246 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9247 	if (!mp->b_cont) {
9248 		freeb(mp);
9249 		return;
9250 	}
9251 
9252 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9253 	mp->b_cont->b_wptr += iocp->ioc_count;
9254 	bzero(ipid, sizeof (*ipid));
9255 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9256 	ipid->ipid_ire_type = IRE_CACHE;
9257 	ipid->ipid_addr_offset = sizeof (ipid_t);
9258 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9259 	/*
9260 	 * Note: in the case of source routing we want to blow away the
9261 	 * route to the first source route hop.
9262 	 */
9263 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9264 	    sizeof (tcp->tcp_ipha->ipha_dst));
9265 
9266 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9267 }
9268 
9269 /* Unlink and return any mblk that looks like it contains an ire */
9270 static mblk_t *
9271 tcp_ire_mp(mblk_t *mp)
9272 {
9273 	mblk_t	*prev_mp;
9274 
9275 	for (;;) {
9276 		prev_mp = mp;
9277 		mp = mp->b_cont;
9278 		if (mp == NULL)
9279 			break;
9280 		switch (DB_TYPE(mp)) {
9281 		case IRE_DB_TYPE:
9282 		case IRE_DB_REQ_TYPE:
9283 			if (prev_mp != NULL)
9284 				prev_mp->b_cont = mp->b_cont;
9285 			mp->b_cont = NULL;
9286 			return (mp);
9287 		default:
9288 			break;
9289 		}
9290 	}
9291 	return (mp);
9292 }
9293 
9294 /*
9295  * Timer callback routine for keepalive probe.  We do a fake resend of
9296  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9297  * check to see if we have heard anything from the other end for the last
9298  * RTO period.  If we have, set the timer to expire for another
9299  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9300  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9301  * the timeout if we have not heard from the other side.  If for more than
9302  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9303  * kill the connection unless the keepalive abort threshold is 0.  In
9304  * that case, we will probe "forever."
9305  */
9306 static void
9307 tcp_keepalive_killer(void *arg)
9308 {
9309 	mblk_t	*mp;
9310 	conn_t	*connp = (conn_t *)arg;
9311 	tcp_t  	*tcp = connp->conn_tcp;
9312 	int32_t	firetime;
9313 	int32_t	idletime;
9314 	int32_t	ka_intrvl;
9315 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9316 
9317 	tcp->tcp_ka_tid = 0;
9318 
9319 	if (tcp->tcp_fused)
9320 		return;
9321 
9322 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
9323 	ka_intrvl = tcp->tcp_ka_interval;
9324 
9325 	/*
9326 	 * Keepalive probe should only be sent if the application has not
9327 	 * done a close on the connection.
9328 	 */
9329 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9330 		return;
9331 	}
9332 	/* Timer fired too early, restart it. */
9333 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9334 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9335 		    MSEC_TO_TICK(ka_intrvl));
9336 		return;
9337 	}
9338 
9339 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9340 	/*
9341 	 * If we have not heard from the other side for a long
9342 	 * time, kill the connection unless the keepalive abort
9343 	 * threshold is 0.  In that case, we will probe "forever."
9344 	 */
9345 	if (tcp->tcp_ka_abort_thres != 0 &&
9346 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9347 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
9348 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9349 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9350 		return;
9351 	}
9352 
9353 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9354 	    idletime >= ka_intrvl) {
9355 		/* Fake resend of last ACKed byte. */
9356 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9357 
9358 		if (mp1 != NULL) {
9359 			*mp1->b_wptr++ = '\0';
9360 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9361 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9362 			freeb(mp1);
9363 			/*
9364 			 * if allocation failed, fall through to start the
9365 			 * timer back.
9366 			 */
9367 			if (mp != NULL) {
9368 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9369 				BUMP_MIB(&tcps->tcps_mib,
9370 				    tcpTimKeepaliveProbe);
9371 				if (tcp->tcp_ka_last_intrvl != 0) {
9372 					int max;
9373 					/*
9374 					 * We should probe again at least
9375 					 * in ka_intrvl, but not more than
9376 					 * tcp_rexmit_interval_max.
9377 					 */
9378 					max = tcps->tcps_rexmit_interval_max;
9379 					firetime = MIN(ka_intrvl - 1,
9380 					    tcp->tcp_ka_last_intrvl << 1);
9381 					if (firetime > max)
9382 						firetime = max;
9383 				} else {
9384 					firetime = tcp->tcp_rto;
9385 				}
9386 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9387 				    tcp_keepalive_killer,
9388 				    MSEC_TO_TICK(firetime));
9389 				tcp->tcp_ka_last_intrvl = firetime;
9390 				return;
9391 			}
9392 		}
9393 	} else {
9394 		tcp->tcp_ka_last_intrvl = 0;
9395 	}
9396 
9397 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9398 	if ((firetime = ka_intrvl - idletime) < 0) {
9399 		firetime = ka_intrvl;
9400 	}
9401 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9402 	    MSEC_TO_TICK(firetime));
9403 }
9404 
9405 int
9406 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9407 {
9408 	queue_t	*q = tcp->tcp_rq;
9409 	int32_t	mss = tcp->tcp_mss;
9410 	int	maxpsz;
9411 
9412 	if (TCP_IS_DETACHED(tcp))
9413 		return (mss);
9414 
9415 	if (tcp->tcp_fused) {
9416 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9417 		mss = INFPSZ;
9418 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
9419 		/*
9420 		 * Set the sd_qn_maxpsz according to the socket send buffer
9421 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9422 		 * instruct the stream head to copyin user data into contiguous
9423 		 * kernel-allocated buffers without breaking it up into smaller
9424 		 * chunks.  We round up the buffer size to the nearest SMSS.
9425 		 */
9426 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9427 		if (tcp->tcp_kssl_ctx == NULL)
9428 			mss = INFPSZ;
9429 		else
9430 			mss = SSL3_MAX_RECORD_LEN;
9431 	} else {
9432 		/*
9433 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9434 		 * (and a multiple of the mss).  This instructs the stream
9435 		 * head to break down larger than SMSS writes into SMSS-
9436 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9437 		 */
9438 		maxpsz = tcp->tcp_maxpsz * mss;
9439 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9440 			maxpsz = tcp->tcp_xmit_hiwater/2;
9441 			/* Round up to nearest mss */
9442 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9443 		}
9444 	}
9445 	(void) setmaxps(q, maxpsz);
9446 	tcp->tcp_wq->q_maxpsz = maxpsz;
9447 
9448 	if (set_maxblk)
9449 		(void) mi_set_sth_maxblk(q, mss);
9450 
9451 	return (mss);
9452 }
9453 
9454 /*
9455  * Extract option values from a tcp header.  We put any found values into the
9456  * tcpopt struct and return a bitmask saying which options were found.
9457  */
9458 static int
9459 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9460 {
9461 	uchar_t		*endp;
9462 	int		len;
9463 	uint32_t	mss;
9464 	uchar_t		*up = (uchar_t *)tcph;
9465 	int		found = 0;
9466 	int32_t		sack_len;
9467 	tcp_seq		sack_begin, sack_end;
9468 	tcp_t		*tcp;
9469 
9470 	endp = up + TCP_HDR_LENGTH(tcph);
9471 	up += TCP_MIN_HEADER_LENGTH;
9472 	while (up < endp) {
9473 		len = endp - up;
9474 		switch (*up) {
9475 		case TCPOPT_EOL:
9476 			break;
9477 
9478 		case TCPOPT_NOP:
9479 			up++;
9480 			continue;
9481 
9482 		case TCPOPT_MAXSEG:
9483 			if (len < TCPOPT_MAXSEG_LEN ||
9484 			    up[1] != TCPOPT_MAXSEG_LEN)
9485 				break;
9486 
9487 			mss = BE16_TO_U16(up+2);
9488 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9489 			tcpopt->tcp_opt_mss = mss;
9490 			found |= TCP_OPT_MSS_PRESENT;
9491 
9492 			up += TCPOPT_MAXSEG_LEN;
9493 			continue;
9494 
9495 		case TCPOPT_WSCALE:
9496 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9497 				break;
9498 
9499 			if (up[2] > TCP_MAX_WINSHIFT)
9500 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9501 			else
9502 				tcpopt->tcp_opt_wscale = up[2];
9503 			found |= TCP_OPT_WSCALE_PRESENT;
9504 
9505 			up += TCPOPT_WS_LEN;
9506 			continue;
9507 
9508 		case TCPOPT_SACK_PERMITTED:
9509 			if (len < TCPOPT_SACK_OK_LEN ||
9510 			    up[1] != TCPOPT_SACK_OK_LEN)
9511 				break;
9512 			found |= TCP_OPT_SACK_OK_PRESENT;
9513 			up += TCPOPT_SACK_OK_LEN;
9514 			continue;
9515 
9516 		case TCPOPT_SACK:
9517 			if (len <= 2 || up[1] <= 2 || len < up[1])
9518 				break;
9519 
9520 			/* If TCP is not interested in SACK blks... */
9521 			if ((tcp = tcpopt->tcp) == NULL) {
9522 				up += up[1];
9523 				continue;
9524 			}
9525 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9526 			up += TCPOPT_HEADER_LEN;
9527 
9528 			/*
9529 			 * If the list is empty, allocate one and assume
9530 			 * nothing is sack'ed.
9531 			 */
9532 			ASSERT(tcp->tcp_sack_info != NULL);
9533 			if (tcp->tcp_notsack_list == NULL) {
9534 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9535 				    tcp->tcp_suna, tcp->tcp_snxt,
9536 				    &(tcp->tcp_num_notsack_blk),
9537 				    &(tcp->tcp_cnt_notsack_list));
9538 
9539 				/*
9540 				 * Make sure tcp_notsack_list is not NULL.
9541 				 * This happens when kmem_alloc(KM_NOSLEEP)
9542 				 * returns NULL.
9543 				 */
9544 				if (tcp->tcp_notsack_list == NULL) {
9545 					up += sack_len;
9546 					continue;
9547 				}
9548 				tcp->tcp_fack = tcp->tcp_suna;
9549 			}
9550 
9551 			while (sack_len > 0) {
9552 				if (up + 8 > endp) {
9553 					up = endp;
9554 					break;
9555 				}
9556 				sack_begin = BE32_TO_U32(up);
9557 				up += 4;
9558 				sack_end = BE32_TO_U32(up);
9559 				up += 4;
9560 				sack_len -= 8;
9561 				/*
9562 				 * Bounds checking.  Make sure the SACK
9563 				 * info is within tcp_suna and tcp_snxt.
9564 				 * If this SACK blk is out of bound, ignore
9565 				 * it but continue to parse the following
9566 				 * blks.
9567 				 */
9568 				if (SEQ_LEQ(sack_end, sack_begin) ||
9569 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9570 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9571 					continue;
9572 				}
9573 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9574 				    sack_begin, sack_end,
9575 				    &(tcp->tcp_num_notsack_blk),
9576 				    &(tcp->tcp_cnt_notsack_list));
9577 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9578 					tcp->tcp_fack = sack_end;
9579 				}
9580 			}
9581 			found |= TCP_OPT_SACK_PRESENT;
9582 			continue;
9583 
9584 		case TCPOPT_TSTAMP:
9585 			if (len < TCPOPT_TSTAMP_LEN ||
9586 			    up[1] != TCPOPT_TSTAMP_LEN)
9587 				break;
9588 
9589 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9590 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9591 
9592 			found |= TCP_OPT_TSTAMP_PRESENT;
9593 
9594 			up += TCPOPT_TSTAMP_LEN;
9595 			continue;
9596 
9597 		default:
9598 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9599 				break;
9600 			up += up[1];
9601 			continue;
9602 		}
9603 		break;
9604 	}
9605 	return (found);
9606 }
9607 
9608 /*
9609  * Set the mss associated with a particular tcp based on its current value,
9610  * and a new one passed in. Observe minimums and maximums, and reset
9611  * other state variables that we want to view as multiples of mss.
9612  *
9613  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9614  * highwater marks etc. need to be initialized or adjusted.
9615  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9616  *    packet arrives.
9617  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9618  *    ICMP6_PACKET_TOO_BIG arrives.
9619  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9620  *    to increase the MSS to use the extra bytes available.
9621  *
9622  * Callers except tcp_paws_check() ensure that they only reduce mss.
9623  */
9624 static void
9625 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9626 {
9627 	uint32_t	mss_max;
9628 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9629 
9630 	if (tcp->tcp_ipversion == IPV4_VERSION)
9631 		mss_max = tcps->tcps_mss_max_ipv4;
9632 	else
9633 		mss_max = tcps->tcps_mss_max_ipv6;
9634 
9635 	if (mss < tcps->tcps_mss_min)
9636 		mss = tcps->tcps_mss_min;
9637 	if (mss > mss_max)
9638 		mss = mss_max;
9639 	/*
9640 	 * Unless naglim has been set by our client to
9641 	 * a non-mss value, force naglim to track mss.
9642 	 * This can help to aggregate small writes.
9643 	 */
9644 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9645 		tcp->tcp_naglim = mss;
9646 	/*
9647 	 * TCP should be able to buffer at least 4 MSS data for obvious
9648 	 * performance reason.
9649 	 */
9650 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9651 		tcp->tcp_xmit_hiwater = mss << 2;
9652 
9653 	if (do_ss) {
9654 		/*
9655 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9656 		 * changing due to a reduction in MTU, presumably as a
9657 		 * result of a new path component, reset cwnd to its
9658 		 * "initial" value, as a multiple of the new mss.
9659 		 */
9660 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9661 	} else {
9662 		/*
9663 		 * Called by tcp_paws_check(), the mss increased
9664 		 * marginally to allow use of space previously taken
9665 		 * by the timestamp option. It would be inappropriate
9666 		 * to apply slow start or tcp_init_cwnd values to
9667 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9668 		 */
9669 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9670 		tcp->tcp_cwnd_cnt = 0;
9671 	}
9672 	tcp->tcp_mss = mss;
9673 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9674 }
9675 
9676 /* For /dev/tcp aka AF_INET open */
9677 static int
9678 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9679 {
9680 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9681 }
9682 
9683 /* For /dev/tcp6 aka AF_INET6 open */
9684 static int
9685 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9686 {
9687 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9688 }
9689 
9690 static int
9691 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9692     boolean_t isv6)
9693 {
9694 	tcp_t		*tcp = NULL;
9695 	conn_t		*connp;
9696 	int		err;
9697 	vmem_t		*minor_arena = NULL;
9698 	dev_t		conn_dev;
9699 	zoneid_t	zoneid;
9700 	tcp_stack_t	*tcps = NULL;
9701 
9702 	if (q->q_ptr != NULL)
9703 		return (0);
9704 
9705 	if (sflag == MODOPEN)
9706 		return (EINVAL);
9707 
9708 	if (!(flag & SO_ACCEPTOR)) {
9709 		/*
9710 		 * Special case for install: miniroot needs to be able to
9711 		 * access files via NFS as though it were always in the
9712 		 * global zone.
9713 		 */
9714 		if (credp == kcred && nfs_global_client_only != 0) {
9715 			zoneid = GLOBAL_ZONEID;
9716 			tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9717 			    netstack_tcp;
9718 			ASSERT(tcps != NULL);
9719 		} else {
9720 			netstack_t *ns;
9721 
9722 			ns = netstack_find_by_cred(credp);
9723 			ASSERT(ns != NULL);
9724 			tcps = ns->netstack_tcp;
9725 			ASSERT(tcps != NULL);
9726 
9727 			/*
9728 			 * For exclusive stacks we set the zoneid to zero
9729 			 * to make TCP operate as if in the global zone.
9730 			 */
9731 			if (tcps->tcps_netstack->netstack_stackid !=
9732 			    GLOBAL_NETSTACKID)
9733 				zoneid = GLOBAL_ZONEID;
9734 			else
9735 				zoneid = crgetzoneid(credp);
9736 		}
9737 		/*
9738 		 * For stackid zero this is done from strplumb.c, but
9739 		 * non-zero stackids are handled here.
9740 		 */
9741 		if (tcps->tcps_g_q == NULL &&
9742 		    tcps->tcps_netstack->netstack_stackid !=
9743 		    GLOBAL_NETSTACKID) {
9744 			tcp_g_q_setup(tcps);
9745 		}
9746 	}
9747 
9748 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9749 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9750 		minor_arena = ip_minor_arena_la;
9751 	} else {
9752 		/*
9753 		 * Either minor numbers in the large arena were exhausted
9754 		 * or a non socket application is doing the open.
9755 		 * Try to allocate from the small arena.
9756 		 */
9757 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9758 			if (tcps != NULL)
9759 				netstack_rele(tcps->tcps_netstack);
9760 			return (EBUSY);
9761 		}
9762 		minor_arena = ip_minor_arena_sa;
9763 	}
9764 	ASSERT(minor_arena != NULL);
9765 
9766 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9767 
9768 	if (flag & SO_ACCEPTOR) {
9769 		/* No netstack_find_by_cred, hence no netstack_rele needed */
9770 		ASSERT(tcps == NULL);
9771 		q->q_qinfo = &tcp_acceptor_rinit;
9772 		/*
9773 		 * the conn_dev and minor_arena will be subsequently used by
9774 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9775 		 * minor device number for this connection from the q_ptr.
9776 		 */
9777 		RD(q)->q_ptr = (void *)conn_dev;
9778 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9779 		WR(q)->q_ptr = (void *)minor_arena;
9780 		qprocson(q);
9781 		return (0);
9782 	}
9783 
9784 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9785 	/*
9786 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9787 	 * so we drop it by one.
9788 	 */
9789 	netstack_rele(tcps->tcps_netstack);
9790 	if (connp == NULL) {
9791 		inet_minor_free(minor_arena, conn_dev);
9792 		q->q_ptr = NULL;
9793 		return (ENOSR);
9794 	}
9795 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9796 	connp->conn_initial_sqp = connp->conn_sqp;
9797 	tcp = connp->conn_tcp;
9798 
9799 	q->q_ptr = WR(q)->q_ptr = connp;
9800 	if (isv6) {
9801 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9802 		connp->conn_send = ip_output_v6;
9803 		connp->conn_af_isv6 = B_TRUE;
9804 		connp->conn_pkt_isv6 = B_TRUE;
9805 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9806 		tcp->tcp_ipversion = IPV6_VERSION;
9807 		tcp->tcp_family = AF_INET6;
9808 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9809 	} else {
9810 		connp->conn_flags |= IPCL_TCP4;
9811 		connp->conn_send = ip_output;
9812 		connp->conn_af_isv6 = B_FALSE;
9813 		connp->conn_pkt_isv6 = B_FALSE;
9814 		tcp->tcp_ipversion = IPV4_VERSION;
9815 		tcp->tcp_family = AF_INET;
9816 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9817 	}
9818 
9819 	/*
9820 	 * TCP keeps a copy of cred for cache locality reasons but
9821 	 * we put a reference only once. If connp->conn_cred
9822 	 * becomes invalid, tcp_cred should also be set to NULL.
9823 	 */
9824 	tcp->tcp_cred = connp->conn_cred = credp;
9825 	crhold(connp->conn_cred);
9826 	tcp->tcp_cpid = curproc->p_pid;
9827 	tcp->tcp_open_time = lbolt64;
9828 	connp->conn_zoneid = zoneid;
9829 	connp->conn_mlp_type = mlptSingle;
9830 	connp->conn_ulp_labeled = !is_system_labeled();
9831 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9832 	ASSERT(tcp->tcp_tcps == tcps);
9833 
9834 	/*
9835 	 * If the caller has the process-wide flag set, then default to MAC
9836 	 * exempt mode.  This allows read-down to unlabeled hosts.
9837 	 */
9838 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9839 		connp->conn_mac_exempt = B_TRUE;
9840 
9841 	connp->conn_dev = conn_dev;
9842 	connp->conn_minor_arena = minor_arena;
9843 
9844 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9845 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9846 
9847 	if (flag & SO_SOCKSTR) {
9848 		/*
9849 		 * No need to insert a socket in tcp acceptor hash.
9850 		 * If it was a socket acceptor stream, we dealt with
9851 		 * it above. A socket listener can never accept a
9852 		 * connection and doesn't need acceptor_id.
9853 		 */
9854 		connp->conn_flags |= IPCL_SOCKET;
9855 		tcp->tcp_issocket = 1;
9856 		WR(q)->q_qinfo = &tcp_sock_winit;
9857 	} else {
9858 #ifdef	_ILP32
9859 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9860 #else
9861 		tcp->tcp_acceptor_id = conn_dev;
9862 #endif	/* _ILP32 */
9863 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9864 	}
9865 
9866 	err = tcp_init(tcp, q);
9867 	if (err != 0) {
9868 		inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
9869 		tcp_acceptor_hash_remove(tcp);
9870 		CONN_DEC_REF(connp);
9871 		q->q_ptr = WR(q)->q_ptr = NULL;
9872 		return (err);
9873 	}
9874 
9875 	RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9876 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9877 
9878 	/* Non-zero default values */
9879 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9880 	/*
9881 	 * Put the ref for TCP. Ref for IP was already put
9882 	 * by ipcl_conn_create. Also Make the conn_t globally
9883 	 * visible to walkers
9884 	 */
9885 	mutex_enter(&connp->conn_lock);
9886 	CONN_INC_REF_LOCKED(connp);
9887 	ASSERT(connp->conn_ref == 2);
9888 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9889 	mutex_exit(&connp->conn_lock);
9890 
9891 	qprocson(q);
9892 	return (0);
9893 }
9894 
9895 /*
9896  * Some TCP options can be "set" by requesting them in the option
9897  * buffer. This is needed for XTI feature test though we do not
9898  * allow it in general. We interpret that this mechanism is more
9899  * applicable to OSI protocols and need not be allowed in general.
9900  * This routine filters out options for which it is not allowed (most)
9901  * and lets through those (few) for which it is. [ The XTI interface
9902  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9903  * ever implemented will have to be allowed here ].
9904  */
9905 static boolean_t
9906 tcp_allow_connopt_set(int level, int name)
9907 {
9908 
9909 	switch (level) {
9910 	case IPPROTO_TCP:
9911 		switch (name) {
9912 		case TCP_NODELAY:
9913 			return (B_TRUE);
9914 		default:
9915 			return (B_FALSE);
9916 		}
9917 		/*NOTREACHED*/
9918 	default:
9919 		return (B_FALSE);
9920 	}
9921 	/*NOTREACHED*/
9922 }
9923 
9924 /*
9925  * This routine gets default values of certain options whose default
9926  * values are maintained by protocol specific code
9927  */
9928 /* ARGSUSED */
9929 int
9930 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9931 {
9932 	int32_t	*i1 = (int32_t *)ptr;
9933 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9934 
9935 	switch (level) {
9936 	case IPPROTO_TCP:
9937 		switch (name) {
9938 		case TCP_NOTIFY_THRESHOLD:
9939 			*i1 = tcps->tcps_ip_notify_interval;
9940 			break;
9941 		case TCP_ABORT_THRESHOLD:
9942 			*i1 = tcps->tcps_ip_abort_interval;
9943 			break;
9944 		case TCP_CONN_NOTIFY_THRESHOLD:
9945 			*i1 = tcps->tcps_ip_notify_cinterval;
9946 			break;
9947 		case TCP_CONN_ABORT_THRESHOLD:
9948 			*i1 = tcps->tcps_ip_abort_cinterval;
9949 			break;
9950 		default:
9951 			return (-1);
9952 		}
9953 		break;
9954 	case IPPROTO_IP:
9955 		switch (name) {
9956 		case IP_TTL:
9957 			*i1 = tcps->tcps_ipv4_ttl;
9958 			break;
9959 		default:
9960 			return (-1);
9961 		}
9962 		break;
9963 	case IPPROTO_IPV6:
9964 		switch (name) {
9965 		case IPV6_UNICAST_HOPS:
9966 			*i1 = tcps->tcps_ipv6_hoplimit;
9967 			break;
9968 		default:
9969 			return (-1);
9970 		}
9971 		break;
9972 	default:
9973 		return (-1);
9974 	}
9975 	return (sizeof (int));
9976 }
9977 
9978 
9979 /*
9980  * TCP routine to get the values of options.
9981  */
9982 int
9983 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9984 {
9985 	int		*i1 = (int *)ptr;
9986 	conn_t		*connp = Q_TO_CONN(q);
9987 	tcp_t		*tcp = connp->conn_tcp;
9988 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9989 
9990 	switch (level) {
9991 	case SOL_SOCKET:
9992 		switch (name) {
9993 		case SO_LINGER:	{
9994 			struct linger *lgr = (struct linger *)ptr;
9995 
9996 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9997 			lgr->l_linger = tcp->tcp_lingertime;
9998 			}
9999 			return (sizeof (struct linger));
10000 		case SO_DEBUG:
10001 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
10002 			break;
10003 		case SO_KEEPALIVE:
10004 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
10005 			break;
10006 		case SO_DONTROUTE:
10007 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
10008 			break;
10009 		case SO_USELOOPBACK:
10010 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
10011 			break;
10012 		case SO_BROADCAST:
10013 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
10014 			break;
10015 		case SO_REUSEADDR:
10016 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
10017 			break;
10018 		case SO_OOBINLINE:
10019 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
10020 			break;
10021 		case SO_DGRAM_ERRIND:
10022 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
10023 			break;
10024 		case SO_TYPE:
10025 			*i1 = SOCK_STREAM;
10026 			break;
10027 		case SO_SNDBUF:
10028 			*i1 = tcp->tcp_xmit_hiwater;
10029 			break;
10030 		case SO_RCVBUF:
10031 			*i1 = RD(q)->q_hiwat;
10032 			break;
10033 		case SO_SND_COPYAVOID:
10034 			*i1 = tcp->tcp_snd_zcopy_on ?
10035 			    SO_SND_COPYAVOID : 0;
10036 			break;
10037 		case SO_ALLZONES:
10038 			*i1 = connp->conn_allzones ? 1 : 0;
10039 			break;
10040 		case SO_ANON_MLP:
10041 			*i1 = connp->conn_anon_mlp;
10042 			break;
10043 		case SO_MAC_EXEMPT:
10044 			*i1 = connp->conn_mac_exempt;
10045 			break;
10046 		case SO_EXCLBIND:
10047 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
10048 			break;
10049 		case SO_PROTOTYPE:
10050 			*i1 = IPPROTO_TCP;
10051 			break;
10052 		case SO_DOMAIN:
10053 			*i1 = tcp->tcp_family;
10054 			break;
10055 		default:
10056 			return (-1);
10057 		}
10058 		break;
10059 	case IPPROTO_TCP:
10060 		switch (name) {
10061 		case TCP_NODELAY:
10062 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
10063 			break;
10064 		case TCP_MAXSEG:
10065 			*i1 = tcp->tcp_mss;
10066 			break;
10067 		case TCP_NOTIFY_THRESHOLD:
10068 			*i1 = (int)tcp->tcp_first_timer_threshold;
10069 			break;
10070 		case TCP_ABORT_THRESHOLD:
10071 			*i1 = tcp->tcp_second_timer_threshold;
10072 			break;
10073 		case TCP_CONN_NOTIFY_THRESHOLD:
10074 			*i1 = tcp->tcp_first_ctimer_threshold;
10075 			break;
10076 		case TCP_CONN_ABORT_THRESHOLD:
10077 			*i1 = tcp->tcp_second_ctimer_threshold;
10078 			break;
10079 		case TCP_RECVDSTADDR:
10080 			*i1 = tcp->tcp_recvdstaddr;
10081 			break;
10082 		case TCP_ANONPRIVBIND:
10083 			*i1 = tcp->tcp_anon_priv_bind;
10084 			break;
10085 		case TCP_EXCLBIND:
10086 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
10087 			break;
10088 		case TCP_INIT_CWND:
10089 			*i1 = tcp->tcp_init_cwnd;
10090 			break;
10091 		case TCP_KEEPALIVE_THRESHOLD:
10092 			*i1 = tcp->tcp_ka_interval;
10093 			break;
10094 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10095 			*i1 = tcp->tcp_ka_abort_thres;
10096 			break;
10097 		case TCP_CORK:
10098 			*i1 = tcp->tcp_cork;
10099 			break;
10100 		default:
10101 			return (-1);
10102 		}
10103 		break;
10104 	case IPPROTO_IP:
10105 		if (tcp->tcp_family != AF_INET)
10106 			return (-1);
10107 		switch (name) {
10108 		case IP_OPTIONS:
10109 		case T_IP_OPTIONS: {
10110 			/*
10111 			 * This is compatible with BSD in that in only return
10112 			 * the reverse source route with the final destination
10113 			 * as the last entry. The first 4 bytes of the option
10114 			 * will contain the final destination.
10115 			 */
10116 			int	opt_len;
10117 
10118 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
10119 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
10120 			ASSERT(opt_len >= 0);
10121 			/* Caller ensures enough space */
10122 			if (opt_len > 0) {
10123 				/*
10124 				 * TODO: Do we have to handle getsockopt on an
10125 				 * initiator as well?
10126 				 */
10127 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
10128 			}
10129 			return (0);
10130 			}
10131 		case IP_TOS:
10132 		case T_IP_TOS:
10133 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10134 			break;
10135 		case IP_TTL:
10136 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10137 			break;
10138 		case IP_NEXTHOP:
10139 			/* Handled at IP level */
10140 			return (-EINVAL);
10141 		default:
10142 			return (-1);
10143 		}
10144 		break;
10145 	case IPPROTO_IPV6:
10146 		/*
10147 		 * IPPROTO_IPV6 options are only supported for sockets
10148 		 * that are using IPv6 on the wire.
10149 		 */
10150 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10151 			return (-1);
10152 		}
10153 		switch (name) {
10154 		case IPV6_UNICAST_HOPS:
10155 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10156 			break;	/* goto sizeof (int) option return */
10157 		case IPV6_BOUND_IF:
10158 			/* Zero if not set */
10159 			*i1 = tcp->tcp_bound_if;
10160 			break;	/* goto sizeof (int) option return */
10161 		case IPV6_RECVPKTINFO:
10162 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10163 				*i1 = 1;
10164 			else
10165 				*i1 = 0;
10166 			break;	/* goto sizeof (int) option return */
10167 		case IPV6_RECVTCLASS:
10168 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10169 				*i1 = 1;
10170 			else
10171 				*i1 = 0;
10172 			break;	/* goto sizeof (int) option return */
10173 		case IPV6_RECVHOPLIMIT:
10174 			if (tcp->tcp_ipv6_recvancillary &
10175 			    TCP_IPV6_RECVHOPLIMIT)
10176 				*i1 = 1;
10177 			else
10178 				*i1 = 0;
10179 			break;	/* goto sizeof (int) option return */
10180 		case IPV6_RECVHOPOPTS:
10181 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10182 				*i1 = 1;
10183 			else
10184 				*i1 = 0;
10185 			break;	/* goto sizeof (int) option return */
10186 		case IPV6_RECVDSTOPTS:
10187 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10188 				*i1 = 1;
10189 			else
10190 				*i1 = 0;
10191 			break;	/* goto sizeof (int) option return */
10192 		case _OLD_IPV6_RECVDSTOPTS:
10193 			if (tcp->tcp_ipv6_recvancillary &
10194 			    TCP_OLD_IPV6_RECVDSTOPTS)
10195 				*i1 = 1;
10196 			else
10197 				*i1 = 0;
10198 			break;	/* goto sizeof (int) option return */
10199 		case IPV6_RECVRTHDR:
10200 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10201 				*i1 = 1;
10202 			else
10203 				*i1 = 0;
10204 			break;	/* goto sizeof (int) option return */
10205 		case IPV6_RECVRTHDRDSTOPTS:
10206 			if (tcp->tcp_ipv6_recvancillary &
10207 			    TCP_IPV6_RECVRTDSTOPTS)
10208 				*i1 = 1;
10209 			else
10210 				*i1 = 0;
10211 			break;	/* goto sizeof (int) option return */
10212 		case IPV6_PKTINFO: {
10213 			/* XXX assumes that caller has room for max size! */
10214 			struct in6_pktinfo *pkti;
10215 
10216 			pkti = (struct in6_pktinfo *)ptr;
10217 			if (ipp->ipp_fields & IPPF_IFINDEX)
10218 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10219 			else
10220 				pkti->ipi6_ifindex = 0;
10221 			if (ipp->ipp_fields & IPPF_ADDR)
10222 				pkti->ipi6_addr = ipp->ipp_addr;
10223 			else
10224 				pkti->ipi6_addr = ipv6_all_zeros;
10225 			return (sizeof (struct in6_pktinfo));
10226 		}
10227 		case IPV6_TCLASS:
10228 			if (ipp->ipp_fields & IPPF_TCLASS)
10229 				*i1 = ipp->ipp_tclass;
10230 			else
10231 				*i1 = IPV6_FLOW_TCLASS(
10232 				    IPV6_DEFAULT_VERS_AND_FLOW);
10233 			break;	/* goto sizeof (int) option return */
10234 		case IPV6_NEXTHOP: {
10235 			sin6_t *sin6 = (sin6_t *)ptr;
10236 
10237 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10238 				return (0);
10239 			*sin6 = sin6_null;
10240 			sin6->sin6_family = AF_INET6;
10241 			sin6->sin6_addr = ipp->ipp_nexthop;
10242 			return (sizeof (sin6_t));
10243 		}
10244 		case IPV6_HOPOPTS:
10245 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10246 				return (0);
10247 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
10248 				return (0);
10249 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
10250 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
10251 			if (tcp->tcp_label_len > 0) {
10252 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
10253 				ptr[1] = (ipp->ipp_hopoptslen -
10254 				    tcp->tcp_label_len + 7) / 8 - 1;
10255 			}
10256 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
10257 		case IPV6_RTHDRDSTOPTS:
10258 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10259 				return (0);
10260 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10261 			return (ipp->ipp_rtdstoptslen);
10262 		case IPV6_RTHDR:
10263 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10264 				return (0);
10265 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10266 			return (ipp->ipp_rthdrlen);
10267 		case IPV6_DSTOPTS:
10268 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10269 				return (0);
10270 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10271 			return (ipp->ipp_dstoptslen);
10272 		case IPV6_SRC_PREFERENCES:
10273 			return (ip6_get_src_preferences(connp,
10274 			    (uint32_t *)ptr));
10275 		case IPV6_PATHMTU: {
10276 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10277 
10278 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10279 				return (-1);
10280 
10281 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10282 			    connp->conn_fport, mtuinfo,
10283 			    connp->conn_netstack));
10284 		}
10285 		default:
10286 			return (-1);
10287 		}
10288 		break;
10289 	default:
10290 		return (-1);
10291 	}
10292 	return (sizeof (int));
10293 }
10294 
10295 /*
10296  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10297  * Parameters are assumed to be verified by the caller.
10298  */
10299 /* ARGSUSED */
10300 int
10301 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10302     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10303     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10304 {
10305 	conn_t	*connp = Q_TO_CONN(q);
10306 	tcp_t	*tcp = connp->conn_tcp;
10307 	int	*i1 = (int *)invalp;
10308 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10309 	boolean_t checkonly;
10310 	int	reterr;
10311 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
10312 
10313 	switch (optset_context) {
10314 	case SETFN_OPTCOM_CHECKONLY:
10315 		checkonly = B_TRUE;
10316 		/*
10317 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10318 		 * inlen != 0 implies value supplied and
10319 		 * 	we have to "pretend" to set it.
10320 		 * inlen == 0 implies that there is no
10321 		 * 	value part in T_CHECK request and just validation
10322 		 * done elsewhere should be enough, we just return here.
10323 		 */
10324 		if (inlen == 0) {
10325 			*outlenp = 0;
10326 			return (0);
10327 		}
10328 		break;
10329 	case SETFN_OPTCOM_NEGOTIATE:
10330 		checkonly = B_FALSE;
10331 		break;
10332 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10333 	case SETFN_CONN_NEGOTIATE:
10334 		checkonly = B_FALSE;
10335 		/*
10336 		 * Negotiating local and "association-related" options
10337 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10338 		 * primitives is allowed by XTI, but we choose
10339 		 * to not implement this style negotiation for Internet
10340 		 * protocols (We interpret it is a must for OSI world but
10341 		 * optional for Internet protocols) for all options.
10342 		 * [ Will do only for the few options that enable test
10343 		 * suites that our XTI implementation of this feature
10344 		 * works for transports that do allow it ]
10345 		 */
10346 		if (!tcp_allow_connopt_set(level, name)) {
10347 			*outlenp = 0;
10348 			return (EINVAL);
10349 		}
10350 		break;
10351 	default:
10352 		/*
10353 		 * We should never get here
10354 		 */
10355 		*outlenp = 0;
10356 		return (EINVAL);
10357 	}
10358 
10359 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10360 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10361 
10362 	/*
10363 	 * For TCP, we should have no ancillary data sent down
10364 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10365 	 * has to be zero.
10366 	 */
10367 	ASSERT(thisdg_attrs == NULL);
10368 
10369 	/*
10370 	 * For fixed length options, no sanity check
10371 	 * of passed in length is done. It is assumed *_optcom_req()
10372 	 * routines do the right thing.
10373 	 */
10374 
10375 	switch (level) {
10376 	case SOL_SOCKET:
10377 		switch (name) {
10378 		case SO_LINGER: {
10379 			struct linger *lgr = (struct linger *)invalp;
10380 
10381 			if (!checkonly) {
10382 				if (lgr->l_onoff) {
10383 					tcp->tcp_linger = 1;
10384 					tcp->tcp_lingertime = lgr->l_linger;
10385 				} else {
10386 					tcp->tcp_linger = 0;
10387 					tcp->tcp_lingertime = 0;
10388 				}
10389 				/* struct copy */
10390 				*(struct linger *)outvalp = *lgr;
10391 			} else {
10392 				if (!lgr->l_onoff) {
10393 					((struct linger *)
10394 					    outvalp)->l_onoff = 0;
10395 					((struct linger *)
10396 					    outvalp)->l_linger = 0;
10397 				} else {
10398 					/* struct copy */
10399 					*(struct linger *)outvalp = *lgr;
10400 				}
10401 			}
10402 			*outlenp = sizeof (struct linger);
10403 			return (0);
10404 		}
10405 		case SO_DEBUG:
10406 			if (!checkonly)
10407 				tcp->tcp_debug = onoff;
10408 			break;
10409 		case SO_KEEPALIVE:
10410 			if (checkonly) {
10411 				/* T_CHECK case */
10412 				break;
10413 			}
10414 
10415 			if (!onoff) {
10416 				if (tcp->tcp_ka_enabled) {
10417 					if (tcp->tcp_ka_tid != 0) {
10418 						(void) TCP_TIMER_CANCEL(tcp,
10419 						    tcp->tcp_ka_tid);
10420 						tcp->tcp_ka_tid = 0;
10421 					}
10422 					tcp->tcp_ka_enabled = 0;
10423 				}
10424 				break;
10425 			}
10426 			if (!tcp->tcp_ka_enabled) {
10427 				/* Crank up the keepalive timer */
10428 				tcp->tcp_ka_last_intrvl = 0;
10429 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10430 				    tcp_keepalive_killer,
10431 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10432 				tcp->tcp_ka_enabled = 1;
10433 			}
10434 			break;
10435 		case SO_DONTROUTE:
10436 			/*
10437 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10438 			 * only of interest to IP.  We track them here only so
10439 			 * that we can report their current value.
10440 			 */
10441 			if (!checkonly) {
10442 				tcp->tcp_dontroute = onoff;
10443 				tcp->tcp_connp->conn_dontroute = onoff;
10444 			}
10445 			break;
10446 		case SO_USELOOPBACK:
10447 			if (!checkonly) {
10448 				tcp->tcp_useloopback = onoff;
10449 				tcp->tcp_connp->conn_loopback = onoff;
10450 			}
10451 			break;
10452 		case SO_BROADCAST:
10453 			if (!checkonly) {
10454 				tcp->tcp_broadcast = onoff;
10455 				tcp->tcp_connp->conn_broadcast = onoff;
10456 			}
10457 			break;
10458 		case SO_REUSEADDR:
10459 			if (!checkonly) {
10460 				tcp->tcp_reuseaddr = onoff;
10461 				tcp->tcp_connp->conn_reuseaddr = onoff;
10462 			}
10463 			break;
10464 		case SO_OOBINLINE:
10465 			if (!checkonly)
10466 				tcp->tcp_oobinline = onoff;
10467 			break;
10468 		case SO_DGRAM_ERRIND:
10469 			if (!checkonly)
10470 				tcp->tcp_dgram_errind = onoff;
10471 			break;
10472 		case SO_SNDBUF: {
10473 			if (*i1 > tcps->tcps_max_buf) {
10474 				*outlenp = 0;
10475 				return (ENOBUFS);
10476 			}
10477 			if (checkonly)
10478 				break;
10479 
10480 			tcp->tcp_xmit_hiwater = *i1;
10481 			if (tcps->tcps_snd_lowat_fraction != 0)
10482 				tcp->tcp_xmit_lowater =
10483 				    tcp->tcp_xmit_hiwater /
10484 				    tcps->tcps_snd_lowat_fraction;
10485 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10486 			/*
10487 			 * If we are flow-controlled, recheck the condition.
10488 			 * There are apps that increase SO_SNDBUF size when
10489 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10490 			 * control condition to be lifted right away.
10491 			 */
10492 			mutex_enter(&tcp->tcp_non_sq_lock);
10493 			if (tcp->tcp_flow_stopped &&
10494 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10495 				tcp_clrqfull(tcp);
10496 			}
10497 			mutex_exit(&tcp->tcp_non_sq_lock);
10498 			break;
10499 		}
10500 		case SO_RCVBUF:
10501 			if (*i1 > tcps->tcps_max_buf) {
10502 				*outlenp = 0;
10503 				return (ENOBUFS);
10504 			}
10505 			/* Silently ignore zero */
10506 			if (!checkonly && *i1 != 0) {
10507 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10508 				(void) tcp_rwnd_set(tcp, *i1);
10509 			}
10510 			/*
10511 			 * XXX should we return the rwnd here
10512 			 * and tcp_opt_get ?
10513 			 */
10514 			break;
10515 		case SO_SND_COPYAVOID:
10516 			if (!checkonly) {
10517 				/* we only allow enable at most once for now */
10518 				if (tcp->tcp_loopback ||
10519 				    (tcp->tcp_kssl_ctx != NULL) ||
10520 				    (!tcp->tcp_snd_zcopy_aware &&
10521 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10522 					*outlenp = 0;
10523 					return (EOPNOTSUPP);
10524 				}
10525 				tcp->tcp_snd_zcopy_aware = 1;
10526 			}
10527 			break;
10528 		case SO_ALLZONES:
10529 			/* Pass option along to IP level for handling */
10530 			return (-EINVAL);
10531 		case SO_ANON_MLP:
10532 			/* Pass option along to IP level for handling */
10533 			return (-EINVAL);
10534 		case SO_MAC_EXEMPT:
10535 			/* Pass option along to IP level for handling */
10536 			return (-EINVAL);
10537 		case SO_EXCLBIND:
10538 			if (!checkonly)
10539 				tcp->tcp_exclbind = onoff;
10540 			break;
10541 		default:
10542 			*outlenp = 0;
10543 			return (EINVAL);
10544 		}
10545 		break;
10546 	case IPPROTO_TCP:
10547 		switch (name) {
10548 		case TCP_NODELAY:
10549 			if (!checkonly)
10550 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10551 			break;
10552 		case TCP_NOTIFY_THRESHOLD:
10553 			if (!checkonly)
10554 				tcp->tcp_first_timer_threshold = *i1;
10555 			break;
10556 		case TCP_ABORT_THRESHOLD:
10557 			if (!checkonly)
10558 				tcp->tcp_second_timer_threshold = *i1;
10559 			break;
10560 		case TCP_CONN_NOTIFY_THRESHOLD:
10561 			if (!checkonly)
10562 				tcp->tcp_first_ctimer_threshold = *i1;
10563 			break;
10564 		case TCP_CONN_ABORT_THRESHOLD:
10565 			if (!checkonly)
10566 				tcp->tcp_second_ctimer_threshold = *i1;
10567 			break;
10568 		case TCP_RECVDSTADDR:
10569 			if (tcp->tcp_state > TCPS_LISTEN)
10570 				return (EOPNOTSUPP);
10571 			if (!checkonly)
10572 				tcp->tcp_recvdstaddr = onoff;
10573 			break;
10574 		case TCP_ANONPRIVBIND:
10575 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10576 			    IPPROTO_TCP)) != 0) {
10577 				*outlenp = 0;
10578 				return (reterr);
10579 			}
10580 			if (!checkonly) {
10581 				tcp->tcp_anon_priv_bind = onoff;
10582 			}
10583 			break;
10584 		case TCP_EXCLBIND:
10585 			if (!checkonly)
10586 				tcp->tcp_exclbind = onoff;
10587 			break;	/* goto sizeof (int) option return */
10588 		case TCP_INIT_CWND: {
10589 			uint32_t init_cwnd = *((uint32_t *)invalp);
10590 
10591 			if (checkonly)
10592 				break;
10593 
10594 			/*
10595 			 * Only allow socket with network configuration
10596 			 * privilege to set the initial cwnd to be larger
10597 			 * than allowed by RFC 3390.
10598 			 */
10599 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10600 				tcp->tcp_init_cwnd = init_cwnd;
10601 				break;
10602 			}
10603 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10604 				*outlenp = 0;
10605 				return (reterr);
10606 			}
10607 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10608 				*outlenp = 0;
10609 				return (EINVAL);
10610 			}
10611 			tcp->tcp_init_cwnd = init_cwnd;
10612 			break;
10613 		}
10614 		case TCP_KEEPALIVE_THRESHOLD:
10615 			if (checkonly)
10616 				break;
10617 
10618 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10619 			    *i1 > tcps->tcps_keepalive_interval_high) {
10620 				*outlenp = 0;
10621 				return (EINVAL);
10622 			}
10623 			if (*i1 != tcp->tcp_ka_interval) {
10624 				tcp->tcp_ka_interval = *i1;
10625 				/*
10626 				 * Check if we need to restart the
10627 				 * keepalive timer.
10628 				 */
10629 				if (tcp->tcp_ka_tid != 0) {
10630 					ASSERT(tcp->tcp_ka_enabled);
10631 					(void) TCP_TIMER_CANCEL(tcp,
10632 					    tcp->tcp_ka_tid);
10633 					tcp->tcp_ka_last_intrvl = 0;
10634 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10635 					    tcp_keepalive_killer,
10636 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10637 				}
10638 			}
10639 			break;
10640 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10641 			if (!checkonly) {
10642 				if (*i1 <
10643 				    tcps->tcps_keepalive_abort_interval_low ||
10644 				    *i1 >
10645 				    tcps->tcps_keepalive_abort_interval_high) {
10646 					*outlenp = 0;
10647 					return (EINVAL);
10648 				}
10649 				tcp->tcp_ka_abort_thres = *i1;
10650 			}
10651 			break;
10652 		case TCP_CORK:
10653 			if (!checkonly) {
10654 				/*
10655 				 * if tcp->tcp_cork was set and is now
10656 				 * being unset, we have to make sure that
10657 				 * the remaining data gets sent out. Also
10658 				 * unset tcp->tcp_cork so that tcp_wput_data()
10659 				 * can send data even if it is less than mss
10660 				 */
10661 				if (tcp->tcp_cork && onoff == 0 &&
10662 				    tcp->tcp_unsent > 0) {
10663 					tcp->tcp_cork = B_FALSE;
10664 					tcp_wput_data(tcp, NULL, B_FALSE);
10665 				}
10666 				tcp->tcp_cork = onoff;
10667 			}
10668 			break;
10669 		default:
10670 			*outlenp = 0;
10671 			return (EINVAL);
10672 		}
10673 		break;
10674 	case IPPROTO_IP:
10675 		if (tcp->tcp_family != AF_INET) {
10676 			*outlenp = 0;
10677 			return (ENOPROTOOPT);
10678 		}
10679 		switch (name) {
10680 		case IP_OPTIONS:
10681 		case T_IP_OPTIONS:
10682 			reterr = tcp_opt_set_header(tcp, checkonly,
10683 			    invalp, inlen);
10684 			if (reterr) {
10685 				*outlenp = 0;
10686 				return (reterr);
10687 			}
10688 			/* OK return - copy input buffer into output buffer */
10689 			if (invalp != outvalp) {
10690 				/* don't trust bcopy for identical src/dst */
10691 				bcopy(invalp, outvalp, inlen);
10692 			}
10693 			*outlenp = inlen;
10694 			return (0);
10695 		case IP_TOS:
10696 		case T_IP_TOS:
10697 			if (!checkonly) {
10698 				tcp->tcp_ipha->ipha_type_of_service =
10699 				    (uchar_t)*i1;
10700 				tcp->tcp_tos = (uchar_t)*i1;
10701 			}
10702 			break;
10703 		case IP_TTL:
10704 			if (!checkonly) {
10705 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10706 				tcp->tcp_ttl = (uchar_t)*i1;
10707 			}
10708 			break;
10709 		case IP_BOUND_IF:
10710 		case IP_NEXTHOP:
10711 			/* Handled at the IP level */
10712 			return (-EINVAL);
10713 		case IP_SEC_OPT:
10714 			/*
10715 			 * We should not allow policy setting after
10716 			 * we start listening for connections.
10717 			 */
10718 			if (tcp->tcp_state == TCPS_LISTEN) {
10719 				return (EINVAL);
10720 			} else {
10721 				/* Handled at the IP level */
10722 				return (-EINVAL);
10723 			}
10724 		default:
10725 			*outlenp = 0;
10726 			return (EINVAL);
10727 		}
10728 		break;
10729 	case IPPROTO_IPV6: {
10730 		ip6_pkt_t		*ipp;
10731 
10732 		/*
10733 		 * IPPROTO_IPV6 options are only supported for sockets
10734 		 * that are using IPv6 on the wire.
10735 		 */
10736 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10737 			*outlenp = 0;
10738 			return (ENOPROTOOPT);
10739 		}
10740 		/*
10741 		 * Only sticky options; no ancillary data
10742 		 */
10743 		ASSERT(thisdg_attrs == NULL);
10744 		ipp = &tcp->tcp_sticky_ipp;
10745 
10746 		switch (name) {
10747 		case IPV6_UNICAST_HOPS:
10748 			/* -1 means use default */
10749 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10750 				*outlenp = 0;
10751 				return (EINVAL);
10752 			}
10753 			if (!checkonly) {
10754 				if (*i1 == -1) {
10755 					tcp->tcp_ip6h->ip6_hops =
10756 					    ipp->ipp_unicast_hops =
10757 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10758 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10759 					/* Pass modified value to IP. */
10760 					*i1 = tcp->tcp_ip6h->ip6_hops;
10761 				} else {
10762 					tcp->tcp_ip6h->ip6_hops =
10763 					    ipp->ipp_unicast_hops =
10764 					    (uint8_t)*i1;
10765 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10766 				}
10767 				reterr = tcp_build_hdrs(q, tcp);
10768 				if (reterr != 0)
10769 					return (reterr);
10770 			}
10771 			break;
10772 		case IPV6_BOUND_IF:
10773 			if (!checkonly) {
10774 				int error = 0;
10775 
10776 				tcp->tcp_bound_if = *i1;
10777 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10778 				    B_TRUE, checkonly, level, name, mblk);
10779 				if (error != 0) {
10780 					*outlenp = 0;
10781 					return (error);
10782 				}
10783 			}
10784 			break;
10785 		/*
10786 		 * Set boolean switches for ancillary data delivery
10787 		 */
10788 		case IPV6_RECVPKTINFO:
10789 			if (!checkonly) {
10790 				if (onoff)
10791 					tcp->tcp_ipv6_recvancillary |=
10792 					    TCP_IPV6_RECVPKTINFO;
10793 				else
10794 					tcp->tcp_ipv6_recvancillary &=
10795 					    ~TCP_IPV6_RECVPKTINFO;
10796 				/* Force it to be sent up with the next msg */
10797 				tcp->tcp_recvifindex = 0;
10798 			}
10799 			break;
10800 		case IPV6_RECVTCLASS:
10801 			if (!checkonly) {
10802 				if (onoff)
10803 					tcp->tcp_ipv6_recvancillary |=
10804 					    TCP_IPV6_RECVTCLASS;
10805 				else
10806 					tcp->tcp_ipv6_recvancillary &=
10807 					    ~TCP_IPV6_RECVTCLASS;
10808 			}
10809 			break;
10810 		case IPV6_RECVHOPLIMIT:
10811 			if (!checkonly) {
10812 				if (onoff)
10813 					tcp->tcp_ipv6_recvancillary |=
10814 					    TCP_IPV6_RECVHOPLIMIT;
10815 				else
10816 					tcp->tcp_ipv6_recvancillary &=
10817 					    ~TCP_IPV6_RECVHOPLIMIT;
10818 				/* Force it to be sent up with the next msg */
10819 				tcp->tcp_recvhops = 0xffffffffU;
10820 			}
10821 			break;
10822 		case IPV6_RECVHOPOPTS:
10823 			if (!checkonly) {
10824 				if (onoff)
10825 					tcp->tcp_ipv6_recvancillary |=
10826 					    TCP_IPV6_RECVHOPOPTS;
10827 				else
10828 					tcp->tcp_ipv6_recvancillary &=
10829 					    ~TCP_IPV6_RECVHOPOPTS;
10830 			}
10831 			break;
10832 		case IPV6_RECVDSTOPTS:
10833 			if (!checkonly) {
10834 				if (onoff)
10835 					tcp->tcp_ipv6_recvancillary |=
10836 					    TCP_IPV6_RECVDSTOPTS;
10837 				else
10838 					tcp->tcp_ipv6_recvancillary &=
10839 					    ~TCP_IPV6_RECVDSTOPTS;
10840 			}
10841 			break;
10842 		case _OLD_IPV6_RECVDSTOPTS:
10843 			if (!checkonly) {
10844 				if (onoff)
10845 					tcp->tcp_ipv6_recvancillary |=
10846 					    TCP_OLD_IPV6_RECVDSTOPTS;
10847 				else
10848 					tcp->tcp_ipv6_recvancillary &=
10849 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10850 			}
10851 			break;
10852 		case IPV6_RECVRTHDR:
10853 			if (!checkonly) {
10854 				if (onoff)
10855 					tcp->tcp_ipv6_recvancillary |=
10856 					    TCP_IPV6_RECVRTHDR;
10857 				else
10858 					tcp->tcp_ipv6_recvancillary &=
10859 					    ~TCP_IPV6_RECVRTHDR;
10860 			}
10861 			break;
10862 		case IPV6_RECVRTHDRDSTOPTS:
10863 			if (!checkonly) {
10864 				if (onoff)
10865 					tcp->tcp_ipv6_recvancillary |=
10866 					    TCP_IPV6_RECVRTDSTOPTS;
10867 				else
10868 					tcp->tcp_ipv6_recvancillary &=
10869 					    ~TCP_IPV6_RECVRTDSTOPTS;
10870 			}
10871 			break;
10872 		case IPV6_PKTINFO:
10873 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10874 				return (EINVAL);
10875 			if (checkonly)
10876 				break;
10877 
10878 			if (inlen == 0) {
10879 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10880 			} else {
10881 				struct in6_pktinfo *pkti;
10882 
10883 				pkti = (struct in6_pktinfo *)invalp;
10884 				/*
10885 				 * RFC 3542 states that ipi6_addr must be
10886 				 * the unspecified address when setting the
10887 				 * IPV6_PKTINFO sticky socket option on a
10888 				 * TCP socket.
10889 				 */
10890 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10891 					return (EINVAL);
10892 				/*
10893 				 * ip6_set_pktinfo() validates the source
10894 				 * address and interface index.
10895 				 */
10896 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10897 				    pkti, mblk);
10898 				if (reterr != 0)
10899 					return (reterr);
10900 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10901 				ipp->ipp_addr = pkti->ipi6_addr;
10902 				if (ipp->ipp_ifindex != 0)
10903 					ipp->ipp_fields |= IPPF_IFINDEX;
10904 				else
10905 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10906 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10907 					ipp->ipp_fields |= IPPF_ADDR;
10908 				else
10909 					ipp->ipp_fields &= ~IPPF_ADDR;
10910 			}
10911 			reterr = tcp_build_hdrs(q, tcp);
10912 			if (reterr != 0)
10913 				return (reterr);
10914 			break;
10915 		case IPV6_TCLASS:
10916 			if (inlen != 0 && inlen != sizeof (int))
10917 				return (EINVAL);
10918 			if (checkonly)
10919 				break;
10920 
10921 			if (inlen == 0) {
10922 				ipp->ipp_fields &= ~IPPF_TCLASS;
10923 			} else {
10924 				if (*i1 > 255 || *i1 < -1)
10925 					return (EINVAL);
10926 				if (*i1 == -1) {
10927 					ipp->ipp_tclass = 0;
10928 					*i1 = 0;
10929 				} else {
10930 					ipp->ipp_tclass = *i1;
10931 				}
10932 				ipp->ipp_fields |= IPPF_TCLASS;
10933 			}
10934 			reterr = tcp_build_hdrs(q, tcp);
10935 			if (reterr != 0)
10936 				return (reterr);
10937 			break;
10938 		case IPV6_NEXTHOP:
10939 			/*
10940 			 * IP will verify that the nexthop is reachable
10941 			 * and fail for sticky options.
10942 			 */
10943 			if (inlen != 0 && inlen != sizeof (sin6_t))
10944 				return (EINVAL);
10945 			if (checkonly)
10946 				break;
10947 
10948 			if (inlen == 0) {
10949 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10950 			} else {
10951 				sin6_t *sin6 = (sin6_t *)invalp;
10952 
10953 				if (sin6->sin6_family != AF_INET6)
10954 					return (EAFNOSUPPORT);
10955 				if (IN6_IS_ADDR_V4MAPPED(
10956 				    &sin6->sin6_addr))
10957 					return (EADDRNOTAVAIL);
10958 				ipp->ipp_nexthop = sin6->sin6_addr;
10959 				if (!IN6_IS_ADDR_UNSPECIFIED(
10960 				    &ipp->ipp_nexthop))
10961 					ipp->ipp_fields |= IPPF_NEXTHOP;
10962 				else
10963 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10964 			}
10965 			reterr = tcp_build_hdrs(q, tcp);
10966 			if (reterr != 0)
10967 				return (reterr);
10968 			break;
10969 		case IPV6_HOPOPTS: {
10970 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10971 
10972 			/*
10973 			 * Sanity checks - minimum size, size a multiple of
10974 			 * eight bytes, and matching size passed in.
10975 			 */
10976 			if (inlen != 0 &&
10977 			    inlen != (8 * (hopts->ip6h_len + 1)))
10978 				return (EINVAL);
10979 
10980 			if (checkonly)
10981 				break;
10982 
10983 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10984 			    (uchar_t **)&ipp->ipp_hopopts,
10985 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10986 			if (reterr != 0)
10987 				return (reterr);
10988 			if (ipp->ipp_hopoptslen == 0)
10989 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10990 			else
10991 				ipp->ipp_fields |= IPPF_HOPOPTS;
10992 			reterr = tcp_build_hdrs(q, tcp);
10993 			if (reterr != 0)
10994 				return (reterr);
10995 			break;
10996 		}
10997 		case IPV6_RTHDRDSTOPTS: {
10998 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10999 
11000 			/*
11001 			 * Sanity checks - minimum size, size a multiple of
11002 			 * eight bytes, and matching size passed in.
11003 			 */
11004 			if (inlen != 0 &&
11005 			    inlen != (8 * (dopts->ip6d_len + 1)))
11006 				return (EINVAL);
11007 
11008 			if (checkonly)
11009 				break;
11010 
11011 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
11012 			    (uchar_t **)&ipp->ipp_rtdstopts,
11013 			    &ipp->ipp_rtdstoptslen, 0);
11014 			if (reterr != 0)
11015 				return (reterr);
11016 			if (ipp->ipp_rtdstoptslen == 0)
11017 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
11018 			else
11019 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
11020 			reterr = tcp_build_hdrs(q, tcp);
11021 			if (reterr != 0)
11022 				return (reterr);
11023 			break;
11024 		}
11025 		case IPV6_DSTOPTS: {
11026 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
11027 
11028 			/*
11029 			 * Sanity checks - minimum size, size a multiple of
11030 			 * eight bytes, and matching size passed in.
11031 			 */
11032 			if (inlen != 0 &&
11033 			    inlen != (8 * (dopts->ip6d_len + 1)))
11034 				return (EINVAL);
11035 
11036 			if (checkonly)
11037 				break;
11038 
11039 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
11040 			    (uchar_t **)&ipp->ipp_dstopts,
11041 			    &ipp->ipp_dstoptslen, 0);
11042 			if (reterr != 0)
11043 				return (reterr);
11044 			if (ipp->ipp_dstoptslen == 0)
11045 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
11046 			else
11047 				ipp->ipp_fields |= IPPF_DSTOPTS;
11048 			reterr = tcp_build_hdrs(q, tcp);
11049 			if (reterr != 0)
11050 				return (reterr);
11051 			break;
11052 		}
11053 		case IPV6_RTHDR: {
11054 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
11055 
11056 			/*
11057 			 * Sanity checks - minimum size, size a multiple of
11058 			 * eight bytes, and matching size passed in.
11059 			 */
11060 			if (inlen != 0 &&
11061 			    inlen != (8 * (rt->ip6r_len + 1)))
11062 				return (EINVAL);
11063 
11064 			if (checkonly)
11065 				break;
11066 
11067 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
11068 			    (uchar_t **)&ipp->ipp_rthdr,
11069 			    &ipp->ipp_rthdrlen, 0);
11070 			if (reterr != 0)
11071 				return (reterr);
11072 			if (ipp->ipp_rthdrlen == 0)
11073 				ipp->ipp_fields &= ~IPPF_RTHDR;
11074 			else
11075 				ipp->ipp_fields |= IPPF_RTHDR;
11076 			reterr = tcp_build_hdrs(q, tcp);
11077 			if (reterr != 0)
11078 				return (reterr);
11079 			break;
11080 		}
11081 		case IPV6_V6ONLY:
11082 			if (!checkonly)
11083 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
11084 			break;
11085 		case IPV6_USE_MIN_MTU:
11086 			if (inlen != sizeof (int))
11087 				return (EINVAL);
11088 
11089 			if (*i1 < -1 || *i1 > 1)
11090 				return (EINVAL);
11091 
11092 			if (checkonly)
11093 				break;
11094 
11095 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
11096 			ipp->ipp_use_min_mtu = *i1;
11097 			break;
11098 		case IPV6_BOUND_PIF:
11099 			/* Handled at the IP level */
11100 			return (-EINVAL);
11101 		case IPV6_SEC_OPT:
11102 			/*
11103 			 * We should not allow policy setting after
11104 			 * we start listening for connections.
11105 			 */
11106 			if (tcp->tcp_state == TCPS_LISTEN) {
11107 				return (EINVAL);
11108 			} else {
11109 				/* Handled at the IP level */
11110 				return (-EINVAL);
11111 			}
11112 		case IPV6_SRC_PREFERENCES:
11113 			if (inlen != sizeof (uint32_t))
11114 				return (EINVAL);
11115 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
11116 			    *(uint32_t *)invalp);
11117 			if (reterr != 0) {
11118 				*outlenp = 0;
11119 				return (reterr);
11120 			}
11121 			break;
11122 		default:
11123 			*outlenp = 0;
11124 			return (EINVAL);
11125 		}
11126 		break;
11127 	}		/* end IPPROTO_IPV6 */
11128 	default:
11129 		*outlenp = 0;
11130 		return (EINVAL);
11131 	}
11132 	/*
11133 	 * Common case of OK return with outval same as inval
11134 	 */
11135 	if (invalp != outvalp) {
11136 		/* don't trust bcopy for identical src/dst */
11137 		(void) bcopy(invalp, outvalp, inlen);
11138 	}
11139 	*outlenp = inlen;
11140 	return (0);
11141 }
11142 
11143 /*
11144  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11145  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11146  * headers, and the maximum size tcp header (to avoid reallocation
11147  * on the fly for additional tcp options).
11148  * Returns failure if can't allocate memory.
11149  */
11150 static int
11151 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11152 {
11153 	char	*hdrs;
11154 	uint_t	hdrs_len;
11155 	ip6i_t	*ip6i;
11156 	char	buf[TCP_MAX_HDR_LENGTH];
11157 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11158 	in6_addr_t src, dst;
11159 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11160 
11161 	/*
11162 	 * save the existing tcp header and source/dest IP addresses
11163 	 */
11164 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11165 	src = tcp->tcp_ip6h->ip6_src;
11166 	dst = tcp->tcp_ip6h->ip6_dst;
11167 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11168 	ASSERT(hdrs_len != 0);
11169 	if (hdrs_len > tcp->tcp_iphc_len) {
11170 		/* Need to reallocate */
11171 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11172 		if (hdrs == NULL)
11173 			return (ENOMEM);
11174 		if (tcp->tcp_iphc != NULL) {
11175 			if (tcp->tcp_hdr_grown) {
11176 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11177 			} else {
11178 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11179 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11180 			}
11181 			tcp->tcp_iphc_len = 0;
11182 		}
11183 		ASSERT(tcp->tcp_iphc_len == 0);
11184 		tcp->tcp_iphc = hdrs;
11185 		tcp->tcp_iphc_len = hdrs_len;
11186 		tcp->tcp_hdr_grown = B_TRUE;
11187 	}
11188 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11189 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11190 
11191 	/* Set header fields not in ipp */
11192 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11193 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11194 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11195 	} else {
11196 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11197 	}
11198 	/*
11199 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11200 	 *
11201 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11202 	 */
11203 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11204 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11205 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11206 
11207 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11208 
11209 	tcp->tcp_ip6h->ip6_src = src;
11210 	tcp->tcp_ip6h->ip6_dst = dst;
11211 
11212 	/*
11213 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11214 	 * the default value for TCP.
11215 	 */
11216 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11217 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
11218 
11219 	/*
11220 	 * If we're setting extension headers after a connection
11221 	 * has been established, and if we have a routing header
11222 	 * among the extension headers, call ip_massage_options_v6 to
11223 	 * manipulate the routing header/ip6_dst set the checksum
11224 	 * difference in the tcp header template.
11225 	 * (This happens in tcp_connect_ipv6 if the routing header
11226 	 * is set prior to the connect.)
11227 	 * Set the tcp_sum to zero first in case we've cleared a
11228 	 * routing header or don't have one at all.
11229 	 */
11230 	tcp->tcp_sum = 0;
11231 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11232 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11233 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11234 		    (uint8_t *)tcp->tcp_tcph);
11235 		if (rth != NULL) {
11236 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11237 			    rth, tcps->tcps_netstack);
11238 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11239 			    (tcp->tcp_sum >> 16));
11240 		}
11241 	}
11242 
11243 	/* Try to get everything in a single mblk */
11244 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcps->tcps_wroff_xtra);
11245 	return (0);
11246 }
11247 
11248 /*
11249  * Transfer any source route option from ipha to buf/dst in reversed form.
11250  */
11251 static int
11252 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11253 {
11254 	ipoptp_t	opts;
11255 	uchar_t		*opt;
11256 	uint8_t		optval;
11257 	uint8_t		optlen;
11258 	uint32_t	len = 0;
11259 
11260 	for (optval = ipoptp_first(&opts, ipha);
11261 	    optval != IPOPT_EOL;
11262 	    optval = ipoptp_next(&opts)) {
11263 		opt = opts.ipoptp_cur;
11264 		optlen = opts.ipoptp_len;
11265 		switch (optval) {
11266 			int	off1, off2;
11267 		case IPOPT_SSRR:
11268 		case IPOPT_LSRR:
11269 
11270 			/* Reverse source route */
11271 			/*
11272 			 * First entry should be the next to last one in the
11273 			 * current source route (the last entry is our
11274 			 * address.)
11275 			 * The last entry should be the final destination.
11276 			 */
11277 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11278 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11279 			off1 = IPOPT_MINOFF_SR - 1;
11280 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11281 			if (off2 < 0) {
11282 				/* No entries in source route */
11283 				break;
11284 			}
11285 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11286 			/*
11287 			 * Note: use src since ipha has not had its src
11288 			 * and dst reversed (it is in the state it was
11289 			 * received.
11290 			 */
11291 			bcopy(&ipha->ipha_src, buf + off2,
11292 			    IP_ADDR_LEN);
11293 			off2 -= IP_ADDR_LEN;
11294 
11295 			while (off2 > 0) {
11296 				bcopy(opt + off2, buf + off1,
11297 				    IP_ADDR_LEN);
11298 				off1 += IP_ADDR_LEN;
11299 				off2 -= IP_ADDR_LEN;
11300 			}
11301 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11302 			buf += optlen;
11303 			len += optlen;
11304 			break;
11305 		}
11306 	}
11307 done:
11308 	/* Pad the resulting options */
11309 	while (len & 0x3) {
11310 		*buf++ = IPOPT_EOL;
11311 		len++;
11312 	}
11313 	return (len);
11314 }
11315 
11316 
11317 /*
11318  * Extract and revert a source route from ipha (if any)
11319  * and then update the relevant fields in both tcp_t and the standard header.
11320  */
11321 static void
11322 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11323 {
11324 	char	buf[TCP_MAX_HDR_LENGTH];
11325 	uint_t	tcph_len;
11326 	int	len;
11327 
11328 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11329 	len = IPH_HDR_LENGTH(ipha);
11330 	if (len == IP_SIMPLE_HDR_LENGTH)
11331 		/* Nothing to do */
11332 		return;
11333 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11334 	    (len & 0x3))
11335 		return;
11336 
11337 	tcph_len = tcp->tcp_tcp_hdr_len;
11338 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11339 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11340 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11341 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11342 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11343 	len += IP_SIMPLE_HDR_LENGTH;
11344 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11345 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11346 	if ((int)tcp->tcp_sum < 0)
11347 		tcp->tcp_sum--;
11348 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11349 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11350 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11351 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11352 	tcp->tcp_ip_hdr_len = len;
11353 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11354 	    (IP_VERSION << 4) | (len >> 2);
11355 	len += tcph_len;
11356 	tcp->tcp_hdr_len = len;
11357 }
11358 
11359 /*
11360  * Copy the standard header into its new location,
11361  * lay in the new options and then update the relevant
11362  * fields in both tcp_t and the standard header.
11363  */
11364 static int
11365 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11366 {
11367 	uint_t	tcph_len;
11368 	uint8_t	*ip_optp;
11369 	tcph_t	*new_tcph;
11370 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11371 
11372 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11373 		return (EINVAL);
11374 
11375 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11376 		return (EINVAL);
11377 
11378 	if (checkonly) {
11379 		/*
11380 		 * do not really set, just pretend to - T_CHECK
11381 		 */
11382 		return (0);
11383 	}
11384 
11385 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11386 	if (tcp->tcp_label_len > 0) {
11387 		int padlen;
11388 		uint8_t opt;
11389 
11390 		/* convert list termination to no-ops */
11391 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11392 		ip_optp += ip_optp[IPOPT_OLEN];
11393 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11394 		while (--padlen >= 0)
11395 			*ip_optp++ = opt;
11396 	}
11397 	tcph_len = tcp->tcp_tcp_hdr_len;
11398 	new_tcph = (tcph_t *)(ip_optp + len);
11399 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11400 	tcp->tcp_tcph = new_tcph;
11401 	bcopy(ptr, ip_optp, len);
11402 
11403 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11404 
11405 	tcp->tcp_ip_hdr_len = len;
11406 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11407 	    (IP_VERSION << 4) | (len >> 2);
11408 	tcp->tcp_hdr_len = len + tcph_len;
11409 	if (!TCP_IS_DETACHED(tcp)) {
11410 		/* Always allocate room for all options. */
11411 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11412 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11413 	}
11414 	return (0);
11415 }
11416 
11417 /* Get callback routine passed to nd_load by tcp_param_register */
11418 /* ARGSUSED */
11419 static int
11420 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11421 {
11422 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11423 
11424 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11425 	return (0);
11426 }
11427 
11428 /*
11429  * Walk through the param array specified registering each element with the
11430  * named dispatch handler.
11431  */
11432 static boolean_t
11433 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11434 {
11435 	for (; cnt-- > 0; tcppa++) {
11436 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11437 			if (!nd_load(ndp, tcppa->tcp_param_name,
11438 			    tcp_param_get, tcp_param_set,
11439 			    (caddr_t)tcppa)) {
11440 				nd_free(ndp);
11441 				return (B_FALSE);
11442 			}
11443 		}
11444 	}
11445 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11446 	    KM_SLEEP);
11447 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11448 	    sizeof (tcpparam_t));
11449 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11450 	    tcp_param_get, tcp_param_set_aligned,
11451 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11452 		nd_free(ndp);
11453 		return (B_FALSE);
11454 	}
11455 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11456 	    KM_SLEEP);
11457 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11458 	    sizeof (tcpparam_t));
11459 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11460 	    tcp_param_get, tcp_param_set_aligned,
11461 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11462 		nd_free(ndp);
11463 		return (B_FALSE);
11464 	}
11465 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11466 	    KM_SLEEP);
11467 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11468 	    sizeof (tcpparam_t));
11469 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11470 	    tcp_param_get, tcp_param_set_aligned,
11471 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11472 		nd_free(ndp);
11473 		return (B_FALSE);
11474 	}
11475 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11476 	    KM_SLEEP);
11477 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11478 	    sizeof (tcpparam_t));
11479 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11480 	    tcp_param_get, tcp_param_set_aligned,
11481 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11482 		nd_free(ndp);
11483 		return (B_FALSE);
11484 	}
11485 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11486 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11487 		nd_free(ndp);
11488 		return (B_FALSE);
11489 	}
11490 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11491 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11492 		nd_free(ndp);
11493 		return (B_FALSE);
11494 	}
11495 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11496 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11497 		nd_free(ndp);
11498 		return (B_FALSE);
11499 	}
11500 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11501 	    NULL)) {
11502 		nd_free(ndp);
11503 		return (B_FALSE);
11504 	}
11505 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11506 	    NULL, NULL)) {
11507 		nd_free(ndp);
11508 		return (B_FALSE);
11509 	}
11510 	if (!nd_load(ndp, "tcp_listen_hash",
11511 	    tcp_listen_hash_report, NULL, NULL)) {
11512 		nd_free(ndp);
11513 		return (B_FALSE);
11514 	}
11515 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11516 	    NULL, NULL)) {
11517 		nd_free(ndp);
11518 		return (B_FALSE);
11519 	}
11520 	if (!nd_load(ndp, "tcp_acceptor_hash",
11521 	    tcp_acceptor_hash_report, NULL, NULL)) {
11522 		nd_free(ndp);
11523 		return (B_FALSE);
11524 	}
11525 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11526 	    tcp_1948_phrase_set, NULL)) {
11527 		nd_free(ndp);
11528 		return (B_FALSE);
11529 	}
11530 	/*
11531 	 * Dummy ndd variables - only to convey obsolescence information
11532 	 * through printing of their name (no get or set routines)
11533 	 * XXX Remove in future releases ?
11534 	 */
11535 	if (!nd_load(ndp,
11536 	    "tcp_close_wait_interval(obsoleted - "
11537 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11538 		nd_free(ndp);
11539 		return (B_FALSE);
11540 	}
11541 	return (B_TRUE);
11542 }
11543 
11544 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11545 /* ARGSUSED */
11546 static int
11547 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11548     cred_t *cr)
11549 {
11550 	long new_value;
11551 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11552 
11553 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11554 	    new_value < tcppa->tcp_param_min ||
11555 	    new_value > tcppa->tcp_param_max) {
11556 		return (EINVAL);
11557 	}
11558 	/*
11559 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11560 	 * round it up.  For future 64 bit requirement, we actually make it
11561 	 * a multiple of 8.
11562 	 */
11563 	if (new_value & 0x7) {
11564 		new_value = (new_value & ~0x7) + 0x8;
11565 	}
11566 	tcppa->tcp_param_val = new_value;
11567 	return (0);
11568 }
11569 
11570 /* Set callback routine passed to nd_load by tcp_param_register */
11571 /* ARGSUSED */
11572 static int
11573 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11574 {
11575 	long	new_value;
11576 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11577 
11578 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11579 	    new_value < tcppa->tcp_param_min ||
11580 	    new_value > tcppa->tcp_param_max) {
11581 		return (EINVAL);
11582 	}
11583 	tcppa->tcp_param_val = new_value;
11584 	return (0);
11585 }
11586 
11587 /*
11588  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11589  * is filled, return as much as we can.  The message passed in may be
11590  * multi-part, chained using b_cont.  "start" is the starting sequence
11591  * number for this piece.
11592  */
11593 static mblk_t *
11594 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11595 {
11596 	uint32_t	end;
11597 	mblk_t		*mp1;
11598 	mblk_t		*mp2;
11599 	mblk_t		*next_mp;
11600 	uint32_t	u1;
11601 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11602 
11603 	/* Walk through all the new pieces. */
11604 	do {
11605 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11606 		    (uintptr_t)INT_MAX);
11607 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11608 		next_mp = mp->b_cont;
11609 		if (start == end) {
11610 			/* Empty.  Blast it. */
11611 			freeb(mp);
11612 			continue;
11613 		}
11614 		mp->b_cont = NULL;
11615 		TCP_REASS_SET_SEQ(mp, start);
11616 		TCP_REASS_SET_END(mp, end);
11617 		mp1 = tcp->tcp_reass_tail;
11618 		if (!mp1) {
11619 			tcp->tcp_reass_tail = mp;
11620 			tcp->tcp_reass_head = mp;
11621 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11622 			UPDATE_MIB(&tcps->tcps_mib,
11623 			    tcpInDataUnorderBytes, end - start);
11624 			continue;
11625 		}
11626 		/* New stuff completely beyond tail? */
11627 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11628 			/* Link it on end. */
11629 			mp1->b_cont = mp;
11630 			tcp->tcp_reass_tail = mp;
11631 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11632 			UPDATE_MIB(&tcps->tcps_mib,
11633 			    tcpInDataUnorderBytes, end - start);
11634 			continue;
11635 		}
11636 		mp1 = tcp->tcp_reass_head;
11637 		u1 = TCP_REASS_SEQ(mp1);
11638 		/* New stuff at the front? */
11639 		if (SEQ_LT(start, u1)) {
11640 			/* Yes... Check for overlap. */
11641 			mp->b_cont = mp1;
11642 			tcp->tcp_reass_head = mp;
11643 			tcp_reass_elim_overlap(tcp, mp);
11644 			continue;
11645 		}
11646 		/*
11647 		 * The new piece fits somewhere between the head and tail.
11648 		 * We find our slot, where mp1 precedes us and mp2 trails.
11649 		 */
11650 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11651 			u1 = TCP_REASS_SEQ(mp2);
11652 			if (SEQ_LEQ(start, u1))
11653 				break;
11654 		}
11655 		/* Link ourselves in */
11656 		mp->b_cont = mp2;
11657 		mp1->b_cont = mp;
11658 
11659 		/* Trim overlap with following mblk(s) first */
11660 		tcp_reass_elim_overlap(tcp, mp);
11661 
11662 		/* Trim overlap with preceding mblk */
11663 		tcp_reass_elim_overlap(tcp, mp1);
11664 
11665 	} while (start = end, mp = next_mp);
11666 	mp1 = tcp->tcp_reass_head;
11667 	/* Anything ready to go? */
11668 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11669 		return (NULL);
11670 	/* Eat what we can off the queue */
11671 	for (;;) {
11672 		mp = mp1->b_cont;
11673 		end = TCP_REASS_END(mp1);
11674 		TCP_REASS_SET_SEQ(mp1, 0);
11675 		TCP_REASS_SET_END(mp1, 0);
11676 		if (!mp) {
11677 			tcp->tcp_reass_tail = NULL;
11678 			break;
11679 		}
11680 		if (end != TCP_REASS_SEQ(mp)) {
11681 			mp1->b_cont = NULL;
11682 			break;
11683 		}
11684 		mp1 = mp;
11685 	}
11686 	mp1 = tcp->tcp_reass_head;
11687 	tcp->tcp_reass_head = mp;
11688 	return (mp1);
11689 }
11690 
11691 /* Eliminate any overlap that mp may have over later mblks */
11692 static void
11693 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11694 {
11695 	uint32_t	end;
11696 	mblk_t		*mp1;
11697 	uint32_t	u1;
11698 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11699 
11700 	end = TCP_REASS_END(mp);
11701 	while ((mp1 = mp->b_cont) != NULL) {
11702 		u1 = TCP_REASS_SEQ(mp1);
11703 		if (!SEQ_GT(end, u1))
11704 			break;
11705 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11706 			mp->b_wptr -= end - u1;
11707 			TCP_REASS_SET_END(mp, u1);
11708 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11709 			UPDATE_MIB(&tcps->tcps_mib,
11710 			    tcpInDataPartDupBytes, end - u1);
11711 			break;
11712 		}
11713 		mp->b_cont = mp1->b_cont;
11714 		TCP_REASS_SET_SEQ(mp1, 0);
11715 		TCP_REASS_SET_END(mp1, 0);
11716 		freeb(mp1);
11717 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11718 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11719 	}
11720 	if (!mp1)
11721 		tcp->tcp_reass_tail = mp;
11722 }
11723 
11724 /*
11725  * Send up all messages queued on tcp_rcv_list.
11726  */
11727 static uint_t
11728 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11729 {
11730 	mblk_t *mp;
11731 	uint_t ret = 0;
11732 	uint_t thwin;
11733 #ifdef DEBUG
11734 	uint_t cnt = 0;
11735 #endif
11736 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11737 
11738 	/* Can't drain on an eager connection */
11739 	if (tcp->tcp_listener != NULL)
11740 		return (ret);
11741 
11742 	/* Can't be sodirect enabled */
11743 	ASSERT(SOD_NOT_ENABLED(tcp));
11744 
11745 	/* No need for the push timer now. */
11746 	if (tcp->tcp_push_tid != 0) {
11747 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11748 		tcp->tcp_push_tid = 0;
11749 	}
11750 
11751 	/*
11752 	 * Handle two cases here: we are currently fused or we were
11753 	 * previously fused and have some urgent data to be delivered
11754 	 * upstream.  The latter happens because we either ran out of
11755 	 * memory or were detached and therefore sending the SIGURG was
11756 	 * deferred until this point.  In either case we pass control
11757 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11758 	 * some work.
11759 	 */
11760 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11761 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11762 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11763 		    &tcp->tcp_fused_sigurg_mp))
11764 			return (ret);
11765 	}
11766 
11767 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11768 		tcp->tcp_rcv_list = mp->b_next;
11769 		mp->b_next = NULL;
11770 #ifdef DEBUG
11771 		cnt += msgdsize(mp);
11772 #endif
11773 		/* Does this need SSL processing first? */
11774 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11775 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11776 			    mblk_t *, mp);
11777 			tcp_kssl_input(tcp, mp);
11778 			continue;
11779 		}
11780 		putnext(q, mp);
11781 	}
11782 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11783 	tcp->tcp_rcv_last_head = NULL;
11784 	tcp->tcp_rcv_last_tail = NULL;
11785 	tcp->tcp_rcv_cnt = 0;
11786 
11787 	/* Learn the latest rwnd information that we sent to the other side. */
11788 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11789 	    << tcp->tcp_rcv_ws;
11790 	/* This is peer's calculated send window (our receive window). */
11791 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11792 	/*
11793 	 * Increase the receive window to max.  But we need to do receiver
11794 	 * SWS avoidance.  This means that we need to check the increase of
11795 	 * of receive window is at least 1 MSS.
11796 	 */
11797 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11798 		/*
11799 		 * If the window that the other side knows is less than max
11800 		 * deferred acks segments, send an update immediately.
11801 		 */
11802 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11803 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11804 			ret = TH_ACK_NEEDED;
11805 		}
11806 		tcp->tcp_rwnd = q->q_hiwat;
11807 	}
11808 	return (ret);
11809 }
11810 
11811 /*
11812  * Queue data on tcp_rcv_list which is a b_next chain.
11813  * tcp_rcv_last_head/tail is the last element of this chain.
11814  * Each element of the chain is a b_cont chain.
11815  *
11816  * M_DATA messages are added to the current element.
11817  * Other messages are added as new (b_next) elements.
11818  */
11819 void
11820 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11821 {
11822 	ASSERT(seg_len == msgdsize(mp));
11823 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11824 
11825 	if (tcp->tcp_rcv_list == NULL) {
11826 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11827 		tcp->tcp_rcv_list = mp;
11828 		tcp->tcp_rcv_last_head = mp;
11829 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11830 		tcp->tcp_rcv_last_tail->b_cont = mp;
11831 	} else {
11832 		tcp->tcp_rcv_last_head->b_next = mp;
11833 		tcp->tcp_rcv_last_head = mp;
11834 	}
11835 
11836 	while (mp->b_cont)
11837 		mp = mp->b_cont;
11838 
11839 	tcp->tcp_rcv_last_tail = mp;
11840 	tcp->tcp_rcv_cnt += seg_len;
11841 	tcp->tcp_rwnd -= seg_len;
11842 }
11843 
11844 /*
11845  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11846  * above, in addition when uioa is enabled schedule an asynchronous uio
11847  * prior to enqueuing. They implement the combinhed semantics of the
11848  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11849  * canputnext(), i.e. flow-control with backenable.
11850  *
11851  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11852  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11853  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11854  *
11855  * Must be called with sodp->sod_lockp held and will return with the lock
11856  * released.
11857  */
11858 static uint_t
11859 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11860 {
11861 	queue_t		*q = tcp->tcp_rq;
11862 	uint_t		thwin;
11863 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11864 	uint_t		ret = 0;
11865 
11866 	/* Can't be an eager connection */
11867 	ASSERT(tcp->tcp_listener == NULL);
11868 
11869 	/* Caller must have lock held */
11870 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11871 
11872 	/* Sodirect mode so must not be a tcp_rcv_list */
11873 	ASSERT(tcp->tcp_rcv_list == NULL);
11874 
11875 	if (SOD_QFULL(sodp)) {
11876 		/* Q is full, mark Q for need backenable */
11877 		SOD_QSETBE(sodp);
11878 	}
11879 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11880 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11881 	    << tcp->tcp_rcv_ws;
11882 	/* This is peer's calculated send window (our available rwnd). */
11883 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11884 	/*
11885 	 * Increase the receive window to max.  But we need to do receiver
11886 	 * SWS avoidance.  This means that we need to check the increase of
11887 	 * of receive window is at least 1 MSS.
11888 	 */
11889 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11890 		/*
11891 		 * If the window that the other side knows is less than max
11892 		 * deferred acks segments, send an update immediately.
11893 		 */
11894 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11895 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11896 			ret = TH_ACK_NEEDED;
11897 		}
11898 		tcp->tcp_rwnd = q->q_hiwat;
11899 	}
11900 
11901 	if (!SOD_QEMPTY(sodp)) {
11902 		/* Wakeup to socket */
11903 		sodp->sod_state &= SOD_WAKE_CLR;
11904 		sodp->sod_state |= SOD_WAKE_DONE;
11905 		(sodp->sod_wakeup)(sodp);
11906 		/* wakeup() does the mutex_ext() */
11907 	} else {
11908 		/* Q is empty, no need to wake */
11909 		sodp->sod_state &= SOD_WAKE_CLR;
11910 		sodp->sod_state |= SOD_WAKE_NOT;
11911 		mutex_exit(sodp->sod_lockp);
11912 	}
11913 
11914 	/* No need for the push timer now. */
11915 	if (tcp->tcp_push_tid != 0) {
11916 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11917 		tcp->tcp_push_tid = 0;
11918 	}
11919 
11920 	return (ret);
11921 }
11922 
11923 /*
11924  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11925  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11926  * to the user-land buffer and flag the mblk_t as such.
11927  *
11928  * Also, handle tcp_rwnd.
11929  */
11930 uint_t
11931 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11932 {
11933 	uioa_t		*uioap = &sodp->sod_uioa;
11934 	boolean_t	qfull;
11935 	uint_t		thwin;
11936 
11937 	/* Can't be an eager connection */
11938 	ASSERT(tcp->tcp_listener == NULL);
11939 
11940 	/* Caller must have lock held */
11941 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11942 
11943 	/* Sodirect mode so must not be a tcp_rcv_list */
11944 	ASSERT(tcp->tcp_rcv_list == NULL);
11945 
11946 	/* Passed in segment length must be equal to mblk_t chain data size */
11947 	ASSERT(seg_len == msgdsize(mp));
11948 
11949 	if (DB_TYPE(mp) != M_DATA) {
11950 		/* Only process M_DATA mblk_t's */
11951 		goto enq;
11952 	}
11953 	if (uioap->uioa_state & UIOA_ENABLED) {
11954 		/* Uioa is enabled */
11955 		mblk_t		*mp1 = mp;
11956 		mblk_t		*lmp = NULL;
11957 
11958 		if (seg_len > uioap->uio_resid) {
11959 			/*
11960 			 * There isn't enough uio space for the mblk_t chain
11961 			 * so disable uioa such that this and any additional
11962 			 * mblk_t data is handled by the socket and schedule
11963 			 * the socket for wakeup to finish this uioa.
11964 			 */
11965 			uioap->uioa_state &= UIOA_CLR;
11966 			uioap->uioa_state |= UIOA_FINI;
11967 			if (sodp->sod_state & SOD_WAKE_NOT) {
11968 				sodp->sod_state &= SOD_WAKE_CLR;
11969 				sodp->sod_state |= SOD_WAKE_NEED;
11970 			}
11971 			goto enq;
11972 		}
11973 		do {
11974 			uint32_t	len = MBLKL(mp1);
11975 
11976 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11977 				/* Scheduled, mark dblk_t as such */
11978 				DB_FLAGS(mp1) |= DBLK_UIOA;
11979 			} else {
11980 				/* Error, turn off async processing */
11981 				uioap->uioa_state &= UIOA_CLR;
11982 				uioap->uioa_state |= UIOA_FINI;
11983 				break;
11984 			}
11985 			lmp = mp1;
11986 		} while ((mp1 = mp1->b_cont) != NULL);
11987 
11988 		if (mp1 != NULL || uioap->uio_resid == 0) {
11989 			/*
11990 			 * Not all mblk_t(s) uioamoved (error) or all uio
11991 			 * space has been consumed so schedule the socket
11992 			 * for wakeup to finish this uio.
11993 			 */
11994 			sodp->sod_state &= SOD_WAKE_CLR;
11995 			sodp->sod_state |= SOD_WAKE_NEED;
11996 
11997 			/* Break the mblk chain if neccessary. */
11998 			if (mp1 != NULL && lmp != NULL) {
11999 				mp->b_next = mp1;
12000 				lmp->b_cont = NULL;
12001 			}
12002 		}
12003 	} else if (uioap->uioa_state & UIOA_FINI) {
12004 		/*
12005 		 * Post UIO_ENABLED waiting for socket to finish processing
12006 		 * so just enqueue and update tcp_rwnd.
12007 		 */
12008 		if (SOD_QFULL(sodp))
12009 			tcp->tcp_rwnd -= seg_len;
12010 	} else if (sodp->sod_want > 0) {
12011 		/*
12012 		 * Uioa isn't enabled but sodirect has a pending read().
12013 		 */
12014 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
12015 			if (sodp->sod_state & SOD_WAKE_NOT) {
12016 				/* Schedule socket for wakeup */
12017 				sodp->sod_state &= SOD_WAKE_CLR;
12018 				sodp->sod_state |= SOD_WAKE_NEED;
12019 			}
12020 			tcp->tcp_rwnd -= seg_len;
12021 		}
12022 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
12023 		/*
12024 		 * No pending sodirect read() so used the default
12025 		 * TCP push logic to guess that a push is needed.
12026 		 */
12027 		if (sodp->sod_state & SOD_WAKE_NOT) {
12028 			/* Schedule socket for wakeup */
12029 			sodp->sod_state &= SOD_WAKE_CLR;
12030 			sodp->sod_state |= SOD_WAKE_NEED;
12031 		}
12032 		tcp->tcp_rwnd -= seg_len;
12033 	} else {
12034 		/* Just update tcp_rwnd */
12035 		tcp->tcp_rwnd -= seg_len;
12036 	}
12037 enq:
12038 	qfull = SOD_QFULL(sodp);
12039 
12040 	(sodp->sod_enqueue)(sodp, mp);
12041 
12042 	if (! qfull && SOD_QFULL(sodp)) {
12043 		/* Wasn't QFULL, now QFULL, need back-enable */
12044 		SOD_QSETBE(sodp);
12045 	}
12046 
12047 	/*
12048 	 * Check to see if remote avail swnd < mss due to delayed ACK,
12049 	 * first get advertised rwnd.
12050 	 */
12051 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
12052 	/* Minus delayed ACK count */
12053 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
12054 	if (thwin < tcp->tcp_mss) {
12055 		/* Remote avail swnd < mss, need ACK now */
12056 		return (TH_ACK_NEEDED);
12057 	}
12058 
12059 	return (0);
12060 }
12061 
12062 /*
12063  * DEFAULT TCP ENTRY POINT via squeue on READ side.
12064  *
12065  * This is the default entry function into TCP on the read side. TCP is
12066  * always entered via squeue i.e. using squeue's for mutual exclusion.
12067  * When classifier does a lookup to find the tcp, it also puts a reference
12068  * on the conn structure associated so the tcp is guaranteed to exist
12069  * when we come here. We still need to check the state because it might
12070  * as well has been closed. The squeue processing function i.e. squeue_enter,
12071  * is responsible for doing the CONN_DEC_REF.
12072  *
12073  * Apart from the default entry point, IP also sends packets directly to
12074  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
12075  * connections.
12076  */
12077 boolean_t tcp_outbound_squeue_switch = B_FALSE;
12078 void
12079 tcp_input(void *arg, mblk_t *mp, void *arg2)
12080 {
12081 	conn_t	*connp = (conn_t *)arg;
12082 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
12083 
12084 	/* arg2 is the sqp */
12085 	ASSERT(arg2 != NULL);
12086 	ASSERT(mp != NULL);
12087 
12088 	/*
12089 	 * Don't accept any input on a closed tcp as this TCP logically does
12090 	 * not exist on the system. Don't proceed further with this TCP.
12091 	 * For eg. this packet could trigger another close of this tcp
12092 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
12093 	 * tcp_clean_death / tcp_closei_local must be called at most once
12094 	 * on a TCP. In this case we need to refeed the packet into the
12095 	 * classifier and figure out where the packet should go. Need to
12096 	 * preserve the recv_ill somehow. Until we figure that out, for
12097 	 * now just drop the packet if we can't classify the packet.
12098 	 */
12099 	if (tcp->tcp_state == TCPS_CLOSED ||
12100 	    tcp->tcp_state == TCPS_BOUND) {
12101 		conn_t	*new_connp;
12102 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
12103 
12104 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
12105 		if (new_connp != NULL) {
12106 			tcp_reinput(new_connp, mp, arg2);
12107 			return;
12108 		}
12109 		/* We failed to classify. For now just drop the packet */
12110 		freemsg(mp);
12111 		return;
12112 	}
12113 
12114 	if (DB_TYPE(mp) != M_DATA) {
12115 		tcp_rput_common(tcp, mp);
12116 		return;
12117 	}
12118 
12119 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
12120 		squeue_t	*final_sqp;
12121 
12122 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
12123 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
12124 		DB_CKSUMSTART(mp) = 0;
12125 		if (tcp->tcp_state == TCPS_SYN_SENT &&
12126 		    connp->conn_final_sqp == NULL &&
12127 		    tcp_outbound_squeue_switch) {
12128 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
12129 			connp->conn_final_sqp = final_sqp;
12130 			if (connp->conn_final_sqp != connp->conn_sqp) {
12131 				CONN_INC_REF(connp);
12132 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
12133 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
12134 				    tcp_rput_data, connp, ip_squeue_flag,
12135 				    SQTAG_CONNECT_FINISH);
12136 				return;
12137 			}
12138 		}
12139 	}
12140 	tcp_rput_data(connp, mp, arg2);
12141 }
12142 
12143 /*
12144  * The read side put procedure.
12145  * The packets passed up by ip are assume to be aligned according to
12146  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
12147  */
12148 static void
12149 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
12150 {
12151 	/*
12152 	 * tcp_rput_data() does not expect M_CTL except for the case
12153 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
12154 	 * type. Need to make sure that any other M_CTLs don't make
12155 	 * it to tcp_rput_data since it is not expecting any and doesn't
12156 	 * check for it.
12157 	 */
12158 	if (DB_TYPE(mp) == M_CTL) {
12159 		switch (*(uint32_t *)(mp->b_rptr)) {
12160 		case TCP_IOC_ABORT_CONN:
12161 			/*
12162 			 * Handle connection abort request.
12163 			 */
12164 			tcp_ioctl_abort_handler(tcp, mp);
12165 			return;
12166 		case IPSEC_IN:
12167 			/*
12168 			 * Only secure icmp arrive in TCP and they
12169 			 * don't go through data path.
12170 			 */
12171 			tcp_icmp_error(tcp, mp);
12172 			return;
12173 		case IN_PKTINFO:
12174 			/*
12175 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
12176 			 * sockets that are receiving IPv4 traffic. tcp
12177 			 */
12178 			ASSERT(tcp->tcp_family == AF_INET6);
12179 			ASSERT(tcp->tcp_ipv6_recvancillary &
12180 			    TCP_IPV6_RECVPKTINFO);
12181 			tcp_rput_data(tcp->tcp_connp, mp,
12182 			    tcp->tcp_connp->conn_sqp);
12183 			return;
12184 		case MDT_IOC_INFO_UPDATE:
12185 			/*
12186 			 * Handle Multidata information update; the
12187 			 * following routine will free the message.
12188 			 */
12189 			if (tcp->tcp_connp->conn_mdt_ok) {
12190 				tcp_mdt_update(tcp,
12191 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
12192 				    B_FALSE);
12193 			}
12194 			freemsg(mp);
12195 			return;
12196 		case LSO_IOC_INFO_UPDATE:
12197 			/*
12198 			 * Handle LSO information update; the following
12199 			 * routine will free the message.
12200 			 */
12201 			if (tcp->tcp_connp->conn_lso_ok) {
12202 				tcp_lso_update(tcp,
12203 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
12204 			}
12205 			freemsg(mp);
12206 			return;
12207 		default:
12208 			/*
12209 			 * tcp_icmp_err() will process the M_CTL packets.
12210 			 * Non-ICMP packets, if any, will be discarded in
12211 			 * tcp_icmp_err(). We will process the ICMP packet
12212 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
12213 			 * incoming ICMP packet may result in changing
12214 			 * the tcp_mss, which we would need if we have
12215 			 * packets to retransmit.
12216 			 */
12217 			tcp_icmp_error(tcp, mp);
12218 			return;
12219 		}
12220 	}
12221 
12222 	/* No point processing the message if tcp is already closed */
12223 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
12224 		freemsg(mp);
12225 		return;
12226 	}
12227 
12228 	tcp_rput_other(tcp, mp);
12229 }
12230 
12231 
12232 /* The minimum of smoothed mean deviation in RTO calculation. */
12233 #define	TCP_SD_MIN	400
12234 
12235 /*
12236  * Set RTO for this connection.  The formula is from Jacobson and Karels'
12237  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
12238  * are the same as those in Appendix A.2 of that paper.
12239  *
12240  * m = new measurement
12241  * sa = smoothed RTT average (8 * average estimates).
12242  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
12243  */
12244 static void
12245 tcp_set_rto(tcp_t *tcp, clock_t rtt)
12246 {
12247 	long m = TICK_TO_MSEC(rtt);
12248 	clock_t sa = tcp->tcp_rtt_sa;
12249 	clock_t sv = tcp->tcp_rtt_sd;
12250 	clock_t rto;
12251 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12252 
12253 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
12254 	tcp->tcp_rtt_update++;
12255 
12256 	/* tcp_rtt_sa is not 0 means this is a new sample. */
12257 	if (sa != 0) {
12258 		/*
12259 		 * Update average estimator:
12260 		 *	new rtt = 7/8 old rtt + 1/8 Error
12261 		 */
12262 
12263 		/* m is now Error in estimate. */
12264 		m -= sa >> 3;
12265 		if ((sa += m) <= 0) {
12266 			/*
12267 			 * Don't allow the smoothed average to be negative.
12268 			 * We use 0 to denote reinitialization of the
12269 			 * variables.
12270 			 */
12271 			sa = 1;
12272 		}
12273 
12274 		/*
12275 		 * Update deviation estimator:
12276 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
12277 		 */
12278 		if (m < 0)
12279 			m = -m;
12280 		m -= sv >> 2;
12281 		sv += m;
12282 	} else {
12283 		/*
12284 		 * This follows BSD's implementation.  So the reinitialized
12285 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12286 		 * link is bandwidth dominated, doubling the window size
12287 		 * during slow start means doubling the RTT.  We want to be
12288 		 * more conservative when we reinitialize our estimates.  3
12289 		 * is just a convenient number.
12290 		 */
12291 		sa = m << 3;
12292 		sv = m << 1;
12293 	}
12294 	if (sv < TCP_SD_MIN) {
12295 		/*
12296 		 * We do not know that if sa captures the delay ACK
12297 		 * effect as in a long train of segments, a receiver
12298 		 * does not delay its ACKs.  So set the minimum of sv
12299 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12300 		 * of BSD DATO.  That means the minimum of mean
12301 		 * deviation is 100 ms.
12302 		 *
12303 		 */
12304 		sv = TCP_SD_MIN;
12305 	}
12306 	tcp->tcp_rtt_sa = sa;
12307 	tcp->tcp_rtt_sd = sv;
12308 	/*
12309 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12310 	 *
12311 	 * Add tcp_rexmit_interval extra in case of extreme environment
12312 	 * where the algorithm fails to work.  The default value of
12313 	 * tcp_rexmit_interval_extra should be 0.
12314 	 *
12315 	 * As we use a finer grained clock than BSD and update
12316 	 * RTO for every ACKs, add in another .25 of RTT to the
12317 	 * deviation of RTO to accomodate burstiness of 1/4 of
12318 	 * window size.
12319 	 */
12320 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12321 
12322 	if (rto > tcps->tcps_rexmit_interval_max) {
12323 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12324 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12325 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12326 	} else {
12327 		tcp->tcp_rto = rto;
12328 	}
12329 
12330 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12331 	tcp->tcp_timer_backoff = 0;
12332 }
12333 
12334 /*
12335  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12336  * send queue which starts at the given seq. no.
12337  *
12338  * Parameters:
12339  *	tcp_t *tcp: the tcp instance pointer.
12340  *	uint32_t seq: the starting seq. no of the requested segment.
12341  *	int32_t *off: after the execution, *off will be the offset to
12342  *		the returned mblk which points to the requested seq no.
12343  *		It is the caller's responsibility to send in a non-null off.
12344  *
12345  * Return:
12346  *	A mblk_t pointer pointing to the requested segment in send queue.
12347  */
12348 static mblk_t *
12349 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12350 {
12351 	int32_t	cnt;
12352 	mblk_t	*mp;
12353 
12354 	/* Defensive coding.  Make sure we don't send incorrect data. */
12355 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12356 		return (NULL);
12357 
12358 	cnt = seq - tcp->tcp_suna;
12359 	mp = tcp->tcp_xmit_head;
12360 	while (cnt > 0 && mp != NULL) {
12361 		cnt -= mp->b_wptr - mp->b_rptr;
12362 		if (cnt < 0) {
12363 			cnt += mp->b_wptr - mp->b_rptr;
12364 			break;
12365 		}
12366 		mp = mp->b_cont;
12367 	}
12368 	ASSERT(mp != NULL);
12369 	*off = cnt;
12370 	return (mp);
12371 }
12372 
12373 /*
12374  * This function handles all retransmissions if SACK is enabled for this
12375  * connection.  First it calculates how many segments can be retransmitted
12376  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12377  * segments.  A segment is eligible if sack_cnt for that segment is greater
12378  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12379  * all eligible segments, it checks to see if TCP can send some new segments
12380  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12381  *
12382  * Parameters:
12383  *	tcp_t *tcp: the tcp structure of the connection.
12384  *	uint_t *flags: in return, appropriate value will be set for
12385  *	tcp_rput_data().
12386  */
12387 static void
12388 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12389 {
12390 	notsack_blk_t	*notsack_blk;
12391 	int32_t		usable_swnd;
12392 	int32_t		mss;
12393 	uint32_t	seg_len;
12394 	mblk_t		*xmit_mp;
12395 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12396 
12397 	ASSERT(tcp->tcp_sack_info != NULL);
12398 	ASSERT(tcp->tcp_notsack_list != NULL);
12399 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12400 
12401 	/* Defensive coding in case there is a bug... */
12402 	if (tcp->tcp_notsack_list == NULL) {
12403 		return;
12404 	}
12405 	notsack_blk = tcp->tcp_notsack_list;
12406 	mss = tcp->tcp_mss;
12407 
12408 	/*
12409 	 * Limit the num of outstanding data in the network to be
12410 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12411 	 */
12412 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12413 
12414 	/* At least retransmit 1 MSS of data. */
12415 	if (usable_swnd <= 0) {
12416 		usable_swnd = mss;
12417 	}
12418 
12419 	/* Make sure no new RTT samples will be taken. */
12420 	tcp->tcp_csuna = tcp->tcp_snxt;
12421 
12422 	notsack_blk = tcp->tcp_notsack_list;
12423 	while (usable_swnd > 0) {
12424 		mblk_t		*snxt_mp, *tmp_mp;
12425 		tcp_seq		begin = tcp->tcp_sack_snxt;
12426 		tcp_seq		end;
12427 		int32_t		off;
12428 
12429 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12430 			if (SEQ_GT(notsack_blk->end, begin) &&
12431 			    (notsack_blk->sack_cnt >=
12432 			    tcps->tcps_dupack_fast_retransmit)) {
12433 				end = notsack_blk->end;
12434 				if (SEQ_LT(begin, notsack_blk->begin)) {
12435 					begin = notsack_blk->begin;
12436 				}
12437 				break;
12438 			}
12439 		}
12440 		/*
12441 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12442 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12443 		 * set to tcp_cwnd_ssthresh.
12444 		 */
12445 		if (notsack_blk == NULL) {
12446 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12447 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12448 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12449 				ASSERT(tcp->tcp_cwnd > 0);
12450 				return;
12451 			} else {
12452 				usable_swnd = usable_swnd / mss;
12453 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12454 				    MAX(usable_swnd * mss, mss);
12455 				*flags |= TH_XMIT_NEEDED;
12456 				return;
12457 			}
12458 		}
12459 
12460 		/*
12461 		 * Note that we may send more than usable_swnd allows here
12462 		 * because of round off, but no more than 1 MSS of data.
12463 		 */
12464 		seg_len = end - begin;
12465 		if (seg_len > mss)
12466 			seg_len = mss;
12467 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12468 		ASSERT(snxt_mp != NULL);
12469 		/* This should not happen.  Defensive coding again... */
12470 		if (snxt_mp == NULL) {
12471 			return;
12472 		}
12473 
12474 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12475 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12476 		if (xmit_mp == NULL)
12477 			return;
12478 
12479 		usable_swnd -= seg_len;
12480 		tcp->tcp_pipe += seg_len;
12481 		tcp->tcp_sack_snxt = begin + seg_len;
12482 
12483 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12484 
12485 		/*
12486 		 * Update the send timestamp to avoid false retransmission.
12487 		 */
12488 		snxt_mp->b_prev = (mblk_t *)lbolt;
12489 
12490 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12491 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12492 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12493 		/*
12494 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12495 		 * This happens when new data sent during fast recovery is
12496 		 * also lost.  If TCP retransmits those new data, it needs
12497 		 * to extend SACK recover phase to avoid starting another
12498 		 * fast retransmit/recovery unnecessarily.
12499 		 */
12500 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12501 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12502 		}
12503 	}
12504 }
12505 
12506 /*
12507  * This function handles policy checking at TCP level for non-hard_bound/
12508  * detached connections.
12509  */
12510 static boolean_t
12511 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12512     boolean_t secure, boolean_t mctl_present)
12513 {
12514 	ipsec_latch_t *ipl = NULL;
12515 	ipsec_action_t *act = NULL;
12516 	mblk_t *data_mp;
12517 	ipsec_in_t *ii;
12518 	const char *reason;
12519 	kstat_named_t *counter;
12520 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12521 	ipsec_stack_t	*ipss;
12522 	ip_stack_t	*ipst;
12523 
12524 	ASSERT(mctl_present || !secure);
12525 
12526 	ASSERT((ipha == NULL && ip6h != NULL) ||
12527 	    (ip6h == NULL && ipha != NULL));
12528 
12529 	/*
12530 	 * We don't necessarily have an ipsec_in_act action to verify
12531 	 * policy because of assymetrical policy where we have only
12532 	 * outbound policy and no inbound policy (possible with global
12533 	 * policy).
12534 	 */
12535 	if (!secure) {
12536 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12537 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12538 			return (B_TRUE);
12539 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12540 		    "tcp_check_policy", ipha, ip6h, secure,
12541 		    tcps->tcps_netstack);
12542 		ipss = tcps->tcps_netstack->netstack_ipsec;
12543 
12544 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12545 		    DROPPER(ipss, ipds_tcp_clear),
12546 		    &tcps->tcps_dropper);
12547 		return (B_FALSE);
12548 	}
12549 
12550 	/*
12551 	 * We have a secure packet.
12552 	 */
12553 	if (act == NULL) {
12554 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12555 		    "tcp_check_policy", ipha, ip6h, secure,
12556 		    tcps->tcps_netstack);
12557 		ipss = tcps->tcps_netstack->netstack_ipsec;
12558 
12559 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12560 		    DROPPER(ipss, ipds_tcp_secure),
12561 		    &tcps->tcps_dropper);
12562 		return (B_FALSE);
12563 	}
12564 
12565 	/*
12566 	 * XXX This whole routine is currently incorrect.  ipl should
12567 	 * be set to the latch pointer, but is currently not set, so
12568 	 * we initialize it to NULL to avoid picking up random garbage.
12569 	 */
12570 	if (ipl == NULL)
12571 		return (B_TRUE);
12572 
12573 	data_mp = first_mp->b_cont;
12574 
12575 	ii = (ipsec_in_t *)first_mp->b_rptr;
12576 
12577 	ipst = tcps->tcps_netstack->netstack_ip;
12578 
12579 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12580 	    &counter, tcp->tcp_connp)) {
12581 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12582 		return (B_TRUE);
12583 	}
12584 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12585 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12586 	    reason);
12587 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12588 
12589 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12590 	    &tcps->tcps_dropper);
12591 	return (B_FALSE);
12592 }
12593 
12594 /*
12595  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12596  * retransmission after a timeout.
12597  *
12598  * To limit the number of duplicate segments, we limit the number of segment
12599  * to be sent in one time to tcp_snd_burst, the burst variable.
12600  */
12601 static void
12602 tcp_ss_rexmit(tcp_t *tcp)
12603 {
12604 	uint32_t	snxt;
12605 	uint32_t	smax;
12606 	int32_t		win;
12607 	int32_t		mss;
12608 	int32_t		off;
12609 	int32_t		burst = tcp->tcp_snd_burst;
12610 	mblk_t		*snxt_mp;
12611 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12612 
12613 	/*
12614 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12615 	 * all unack'ed segments.
12616 	 */
12617 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12618 		smax = tcp->tcp_rexmit_max;
12619 		snxt = tcp->tcp_rexmit_nxt;
12620 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12621 			snxt = tcp->tcp_suna;
12622 		}
12623 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12624 		win -= snxt - tcp->tcp_suna;
12625 		mss = tcp->tcp_mss;
12626 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12627 
12628 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12629 		    (burst > 0) && (snxt_mp != NULL)) {
12630 			mblk_t	*xmit_mp;
12631 			mblk_t	*old_snxt_mp = snxt_mp;
12632 			uint32_t cnt = mss;
12633 
12634 			if (win < cnt) {
12635 				cnt = win;
12636 			}
12637 			if (SEQ_GT(snxt + cnt, smax)) {
12638 				cnt = smax - snxt;
12639 			}
12640 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12641 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12642 			if (xmit_mp == NULL)
12643 				return;
12644 
12645 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12646 
12647 			snxt += cnt;
12648 			win -= cnt;
12649 			/*
12650 			 * Update the send timestamp to avoid false
12651 			 * retransmission.
12652 			 */
12653 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12654 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12655 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12656 
12657 			tcp->tcp_rexmit_nxt = snxt;
12658 			burst--;
12659 		}
12660 		/*
12661 		 * If we have transmitted all we have at the time
12662 		 * we started the retranmission, we can leave
12663 		 * the rest of the job to tcp_wput_data().  But we
12664 		 * need to check the send window first.  If the
12665 		 * win is not 0, go on with tcp_wput_data().
12666 		 */
12667 		if (SEQ_LT(snxt, smax) || win == 0) {
12668 			return;
12669 		}
12670 	}
12671 	/* Only call tcp_wput_data() if there is data to be sent. */
12672 	if (tcp->tcp_unsent) {
12673 		tcp_wput_data(tcp, NULL, B_FALSE);
12674 	}
12675 }
12676 
12677 /*
12678  * Process all TCP option in SYN segment.  Note that this function should
12679  * be called after tcp_adapt_ire() is called so that the necessary info
12680  * from IRE is already set in the tcp structure.
12681  *
12682  * This function sets up the correct tcp_mss value according to the
12683  * MSS option value and our header size.  It also sets up the window scale
12684  * and timestamp values, and initialize SACK info blocks.  But it does not
12685  * change receive window size after setting the tcp_mss value.  The caller
12686  * should do the appropriate change.
12687  */
12688 void
12689 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12690 {
12691 	int options;
12692 	tcp_opt_t tcpopt;
12693 	uint32_t mss_max;
12694 	char *tmp_tcph;
12695 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12696 
12697 	tcpopt.tcp = NULL;
12698 	options = tcp_parse_options(tcph, &tcpopt);
12699 
12700 	/*
12701 	 * Process MSS option.  Note that MSS option value does not account
12702 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12703 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12704 	 * IPv6.
12705 	 */
12706 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12707 		if (tcp->tcp_ipversion == IPV4_VERSION)
12708 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12709 		else
12710 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12711 	} else {
12712 		if (tcp->tcp_ipversion == IPV4_VERSION)
12713 			mss_max = tcps->tcps_mss_max_ipv4;
12714 		else
12715 			mss_max = tcps->tcps_mss_max_ipv6;
12716 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12717 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12718 		else if (tcpopt.tcp_opt_mss > mss_max)
12719 			tcpopt.tcp_opt_mss = mss_max;
12720 	}
12721 
12722 	/* Process Window Scale option. */
12723 	if (options & TCP_OPT_WSCALE_PRESENT) {
12724 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12725 		tcp->tcp_snd_ws_ok = B_TRUE;
12726 	} else {
12727 		tcp->tcp_snd_ws = B_FALSE;
12728 		tcp->tcp_snd_ws_ok = B_FALSE;
12729 		tcp->tcp_rcv_ws = B_FALSE;
12730 	}
12731 
12732 	/* Process Timestamp option. */
12733 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12734 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12735 		tmp_tcph = (char *)tcp->tcp_tcph;
12736 
12737 		tcp->tcp_snd_ts_ok = B_TRUE;
12738 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12739 		tcp->tcp_last_rcv_lbolt = lbolt64;
12740 		ASSERT(OK_32PTR(tmp_tcph));
12741 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12742 
12743 		/* Fill in our template header with basic timestamp option. */
12744 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12745 		tmp_tcph[0] = TCPOPT_NOP;
12746 		tmp_tcph[1] = TCPOPT_NOP;
12747 		tmp_tcph[2] = TCPOPT_TSTAMP;
12748 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12749 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12750 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12751 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12752 	} else {
12753 		tcp->tcp_snd_ts_ok = B_FALSE;
12754 	}
12755 
12756 	/*
12757 	 * Process SACK options.  If SACK is enabled for this connection,
12758 	 * then allocate the SACK info structure.  Note the following ways
12759 	 * when tcp_snd_sack_ok is set to true.
12760 	 *
12761 	 * For active connection: in tcp_adapt_ire() called in
12762 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12763 	 * is checked.
12764 	 *
12765 	 * For passive connection: in tcp_adapt_ire() called in
12766 	 * tcp_accept_comm().
12767 	 *
12768 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12769 	 * That check makes sure that if we did not send a SACK OK option,
12770 	 * we will not enable SACK for this connection even though the other
12771 	 * side sends us SACK OK option.  For active connection, the SACK
12772 	 * info structure has already been allocated.  So we need to free
12773 	 * it if SACK is disabled.
12774 	 */
12775 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12776 	    (tcp->tcp_snd_sack_ok ||
12777 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12778 		/* This should be true only in the passive case. */
12779 		if (tcp->tcp_sack_info == NULL) {
12780 			ASSERT(TCP_IS_DETACHED(tcp));
12781 			tcp->tcp_sack_info =
12782 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12783 		}
12784 		if (tcp->tcp_sack_info == NULL) {
12785 			tcp->tcp_snd_sack_ok = B_FALSE;
12786 		} else {
12787 			tcp->tcp_snd_sack_ok = B_TRUE;
12788 			if (tcp->tcp_snd_ts_ok) {
12789 				tcp->tcp_max_sack_blk = 3;
12790 			} else {
12791 				tcp->tcp_max_sack_blk = 4;
12792 			}
12793 		}
12794 	} else {
12795 		/*
12796 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12797 		 * no SACK info will be used for this
12798 		 * connection.  This assumes that SACK usage
12799 		 * permission is negotiated.  This may need
12800 		 * to be changed once this is clarified.
12801 		 */
12802 		if (tcp->tcp_sack_info != NULL) {
12803 			ASSERT(tcp->tcp_notsack_list == NULL);
12804 			kmem_cache_free(tcp_sack_info_cache,
12805 			    tcp->tcp_sack_info);
12806 			tcp->tcp_sack_info = NULL;
12807 		}
12808 		tcp->tcp_snd_sack_ok = B_FALSE;
12809 	}
12810 
12811 	/*
12812 	 * Now we know the exact TCP/IP header length, subtract
12813 	 * that from tcp_mss to get our side's MSS.
12814 	 */
12815 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12816 	/*
12817 	 * Here we assume that the other side's header size will be equal to
12818 	 * our header size.  We calculate the real MSS accordingly.  Need to
12819 	 * take into additional stuffs IPsec puts in.
12820 	 *
12821 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12822 	 */
12823 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12824 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12825 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12826 
12827 	/*
12828 	 * Set MSS to the smaller one of both ends of the connection.
12829 	 * We should not have called tcp_mss_set() before, but our
12830 	 * side of the MSS should have been set to a proper value
12831 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12832 	 * STREAM head parameters properly.
12833 	 *
12834 	 * If we have a larger-than-16-bit window but the other side
12835 	 * didn't want to do window scale, tcp_rwnd_set() will take
12836 	 * care of that.
12837 	 */
12838 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12839 }
12840 
12841 /*
12842  * Sends the T_CONN_IND to the listener. The caller calls this
12843  * functions via squeue to get inside the listener's perimeter
12844  * once the 3 way hand shake is done a T_CONN_IND needs to be
12845  * sent. As an optimization, the caller can call this directly
12846  * if listener's perimeter is same as eager's.
12847  */
12848 /* ARGSUSED */
12849 void
12850 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12851 {
12852 	conn_t			*lconnp = (conn_t *)arg;
12853 	tcp_t			*listener = lconnp->conn_tcp;
12854 	tcp_t			*tcp;
12855 	struct T_conn_ind	*conn_ind;
12856 	ipaddr_t 		*addr_cache;
12857 	boolean_t		need_send_conn_ind = B_FALSE;
12858 	tcp_stack_t		*tcps = listener->tcp_tcps;
12859 
12860 	/* retrieve the eager */
12861 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12862 	ASSERT(conn_ind->OPT_offset != 0 &&
12863 	    conn_ind->OPT_length == sizeof (intptr_t));
12864 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12865 	    conn_ind->OPT_length);
12866 
12867 	/*
12868 	 * TLI/XTI applications will get confused by
12869 	 * sending eager as an option since it violates
12870 	 * the option semantics. So remove the eager as
12871 	 * option since TLI/XTI app doesn't need it anyway.
12872 	 */
12873 	if (!TCP_IS_SOCKET(listener)) {
12874 		conn_ind->OPT_length = 0;
12875 		conn_ind->OPT_offset = 0;
12876 	}
12877 	if (listener->tcp_state == TCPS_CLOSED ||
12878 	    TCP_IS_DETACHED(listener)) {
12879 		/*
12880 		 * If listener has closed, it would have caused a
12881 		 * a cleanup/blowoff to happen for the eager. We
12882 		 * just need to return.
12883 		 */
12884 		freemsg(mp);
12885 		return;
12886 	}
12887 
12888 
12889 	/*
12890 	 * if the conn_req_q is full defer passing up the
12891 	 * T_CONN_IND until space is availabe after t_accept()
12892 	 * processing
12893 	 */
12894 	mutex_enter(&listener->tcp_eager_lock);
12895 
12896 	/*
12897 	 * Take the eager out, if it is in the list of droppable eagers
12898 	 * as we are here because the 3W handshake is over.
12899 	 */
12900 	MAKE_UNDROPPABLE(tcp);
12901 
12902 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12903 		tcp_t *tail;
12904 
12905 		/*
12906 		 * The eager already has an extra ref put in tcp_rput_data
12907 		 * so that it stays till accept comes back even though it
12908 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12909 		 */
12910 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12911 		listener->tcp_conn_req_cnt_q0--;
12912 		listener->tcp_conn_req_cnt_q++;
12913 
12914 		/* Move from SYN_RCVD to ESTABLISHED list  */
12915 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12916 		    tcp->tcp_eager_prev_q0;
12917 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12918 		    tcp->tcp_eager_next_q0;
12919 		tcp->tcp_eager_prev_q0 = NULL;
12920 		tcp->tcp_eager_next_q0 = NULL;
12921 
12922 		/*
12923 		 * Insert at end of the queue because sockfs
12924 		 * sends down T_CONN_RES in chronological
12925 		 * order. Leaving the older conn indications
12926 		 * at front of the queue helps reducing search
12927 		 * time.
12928 		 */
12929 		tail = listener->tcp_eager_last_q;
12930 		if (tail != NULL)
12931 			tail->tcp_eager_next_q = tcp;
12932 		else
12933 			listener->tcp_eager_next_q = tcp;
12934 		listener->tcp_eager_last_q = tcp;
12935 		tcp->tcp_eager_next_q = NULL;
12936 		/*
12937 		 * Delay sending up the T_conn_ind until we are
12938 		 * done with the eager. Once we have have sent up
12939 		 * the T_conn_ind, the accept can potentially complete
12940 		 * any time and release the refhold we have on the eager.
12941 		 */
12942 		need_send_conn_ind = B_TRUE;
12943 	} else {
12944 		/*
12945 		 * Defer connection on q0 and set deferred
12946 		 * connection bit true
12947 		 */
12948 		tcp->tcp_conn_def_q0 = B_TRUE;
12949 
12950 		/* take tcp out of q0 ... */
12951 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12952 		    tcp->tcp_eager_next_q0;
12953 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12954 		    tcp->tcp_eager_prev_q0;
12955 
12956 		/* ... and place it at the end of q0 */
12957 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12958 		tcp->tcp_eager_next_q0 = listener;
12959 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12960 		listener->tcp_eager_prev_q0 = tcp;
12961 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12962 	}
12963 
12964 	/* we have timed out before */
12965 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12966 		tcp->tcp_syn_rcvd_timeout = 0;
12967 		listener->tcp_syn_rcvd_timeout--;
12968 		if (listener->tcp_syn_defense &&
12969 		    listener->tcp_syn_rcvd_timeout <=
12970 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12971 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12972 		    listener->tcp_last_rcv_lbolt)) {
12973 			/*
12974 			 * Turn off the defense mode if we
12975 			 * believe the SYN attack is over.
12976 			 */
12977 			listener->tcp_syn_defense = B_FALSE;
12978 			if (listener->tcp_ip_addr_cache) {
12979 				kmem_free((void *)listener->tcp_ip_addr_cache,
12980 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12981 				listener->tcp_ip_addr_cache = NULL;
12982 			}
12983 		}
12984 	}
12985 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12986 	if (addr_cache != NULL) {
12987 		/*
12988 		 * We have finished a 3-way handshake with this
12989 		 * remote host. This proves the IP addr is good.
12990 		 * Cache it!
12991 		 */
12992 		addr_cache[IP_ADDR_CACHE_HASH(
12993 		    tcp->tcp_remote)] = tcp->tcp_remote;
12994 	}
12995 	mutex_exit(&listener->tcp_eager_lock);
12996 	if (need_send_conn_ind)
12997 		putnext(listener->tcp_rq, mp);
12998 }
12999 
13000 mblk_t *
13001 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
13002     uint_t *ifindexp, ip6_pkt_t *ippp)
13003 {
13004 	ip_pktinfo_t	*pinfo;
13005 	ip6_t		*ip6h;
13006 	uchar_t		*rptr;
13007 	mblk_t		*first_mp = mp;
13008 	boolean_t	mctl_present = B_FALSE;
13009 	uint_t 		ifindex = 0;
13010 	ip6_pkt_t	ipp;
13011 	uint_t		ipvers;
13012 	uint_t		ip_hdr_len;
13013 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13014 
13015 	rptr = mp->b_rptr;
13016 	ASSERT(OK_32PTR(rptr));
13017 	ASSERT(tcp != NULL);
13018 	ipp.ipp_fields = 0;
13019 
13020 	switch DB_TYPE(mp) {
13021 	case M_CTL:
13022 		mp = mp->b_cont;
13023 		if (mp == NULL) {
13024 			freemsg(first_mp);
13025 			return (NULL);
13026 		}
13027 		if (DB_TYPE(mp) != M_DATA) {
13028 			freemsg(first_mp);
13029 			return (NULL);
13030 		}
13031 		mctl_present = B_TRUE;
13032 		break;
13033 	case M_DATA:
13034 		break;
13035 	default:
13036 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
13037 		freemsg(mp);
13038 		return (NULL);
13039 	}
13040 	ipvers = IPH_HDR_VERSION(rptr);
13041 	if (ipvers == IPV4_VERSION) {
13042 		if (tcp == NULL) {
13043 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
13044 			goto done;
13045 		}
13046 
13047 		ipp.ipp_fields |= IPPF_HOPLIMIT;
13048 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
13049 
13050 		/*
13051 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
13052 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
13053 		 */
13054 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
13055 		    mctl_present) {
13056 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
13057 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
13058 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
13059 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
13060 				ipp.ipp_fields |= IPPF_IFINDEX;
13061 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
13062 				ifindex = pinfo->ip_pkt_ifindex;
13063 			}
13064 			freeb(first_mp);
13065 			mctl_present = B_FALSE;
13066 		}
13067 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13068 	} else {
13069 		ip6h = (ip6_t *)rptr;
13070 
13071 		ASSERT(ipvers == IPV6_VERSION);
13072 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
13073 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
13074 		ipp.ipp_hoplimit = ip6h->ip6_hops;
13075 
13076 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
13077 			uint8_t	nexthdrp;
13078 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13079 
13080 			/* Look for ifindex information */
13081 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
13082 				ip6i_t *ip6i = (ip6i_t *)ip6h;
13083 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
13084 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13085 					freemsg(first_mp);
13086 					return (NULL);
13087 				}
13088 
13089 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
13090 					ASSERT(ip6i->ip6i_ifindex != 0);
13091 					ipp.ipp_fields |= IPPF_IFINDEX;
13092 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
13093 					ifindex = ip6i->ip6i_ifindex;
13094 				}
13095 				rptr = (uchar_t *)&ip6i[1];
13096 				mp->b_rptr = rptr;
13097 				if (rptr == mp->b_wptr) {
13098 					mblk_t *mp1;
13099 					mp1 = mp->b_cont;
13100 					freeb(mp);
13101 					mp = mp1;
13102 					rptr = mp->b_rptr;
13103 				}
13104 				if (MBLKL(mp) < IPV6_HDR_LEN +
13105 				    sizeof (tcph_t)) {
13106 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13107 					freemsg(first_mp);
13108 					return (NULL);
13109 				}
13110 				ip6h = (ip6_t *)rptr;
13111 			}
13112 
13113 			/*
13114 			 * Find any potentially interesting extension headers
13115 			 * as well as the length of the IPv6 + extension
13116 			 * headers.
13117 			 */
13118 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
13119 			/* Verify if this is a TCP packet */
13120 			if (nexthdrp != IPPROTO_TCP) {
13121 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13122 				freemsg(first_mp);
13123 				return (NULL);
13124 			}
13125 		} else {
13126 			ip_hdr_len = IPV6_HDR_LEN;
13127 		}
13128 	}
13129 
13130 done:
13131 	if (ipversp != NULL)
13132 		*ipversp = ipvers;
13133 	if (ip_hdr_lenp != NULL)
13134 		*ip_hdr_lenp = ip_hdr_len;
13135 	if (ippp != NULL)
13136 		*ippp = ipp;
13137 	if (ifindexp != NULL)
13138 		*ifindexp = ifindex;
13139 	if (mctl_present) {
13140 		freeb(first_mp);
13141 	}
13142 	return (mp);
13143 }
13144 
13145 /*
13146  * Handle M_DATA messages from IP. Its called directly from IP via
13147  * squeue for AF_INET type sockets fast path. No M_CTL are expected
13148  * in this path.
13149  *
13150  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
13151  * v4 and v6), we are called through tcp_input() and a M_CTL can
13152  * be present for options but tcp_find_pktinfo() deals with it. We
13153  * only expect M_DATA packets after tcp_find_pktinfo() is done.
13154  *
13155  * The first argument is always the connp/tcp to which the mp belongs.
13156  * There are no exceptions to this rule. The caller has already put
13157  * a reference on this connp/tcp and once tcp_rput_data() returns,
13158  * the squeue will do the refrele.
13159  *
13160  * The TH_SYN for the listener directly go to tcp_conn_request via
13161  * squeue.
13162  *
13163  * sqp: NULL = recursive, sqp != NULL means called from squeue
13164  */
13165 void
13166 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
13167 {
13168 	int32_t		bytes_acked;
13169 	int32_t		gap;
13170 	mblk_t		*mp1;
13171 	uint_t		flags;
13172 	uint32_t	new_swnd = 0;
13173 	uchar_t		*iphdr;
13174 	uchar_t		*rptr;
13175 	int32_t		rgap;
13176 	uint32_t	seg_ack;
13177 	int		seg_len;
13178 	uint_t		ip_hdr_len;
13179 	uint32_t	seg_seq;
13180 	tcph_t		*tcph;
13181 	int		urp;
13182 	tcp_opt_t	tcpopt;
13183 	uint_t		ipvers;
13184 	ip6_pkt_t	ipp;
13185 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
13186 	uint32_t	cwnd;
13187 	uint32_t	add;
13188 	int		npkt;
13189 	int		mss;
13190 	conn_t		*connp = (conn_t *)arg;
13191 	squeue_t	*sqp = (squeue_t *)arg2;
13192 	tcp_t		*tcp = connp->conn_tcp;
13193 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13194 
13195 	/*
13196 	 * RST from fused tcp loopback peer should trigger an unfuse.
13197 	 */
13198 	if (tcp->tcp_fused) {
13199 		TCP_STAT(tcps, tcp_fusion_aborted);
13200 		tcp_unfuse(tcp);
13201 	}
13202 
13203 	iphdr = mp->b_rptr;
13204 	rptr = mp->b_rptr;
13205 	ASSERT(OK_32PTR(rptr));
13206 
13207 	/*
13208 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
13209 	 * processing here. For rest call tcp_find_pktinfo to fill up the
13210 	 * necessary information.
13211 	 */
13212 	if (IPCL_IS_TCP4(connp)) {
13213 		ipvers = IPV4_VERSION;
13214 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13215 	} else {
13216 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
13217 		    NULL, &ipp);
13218 		if (mp == NULL) {
13219 			TCP_STAT(tcps, tcp_rput_v6_error);
13220 			return;
13221 		}
13222 		iphdr = mp->b_rptr;
13223 		rptr = mp->b_rptr;
13224 	}
13225 	ASSERT(DB_TYPE(mp) == M_DATA);
13226 
13227 	tcph = (tcph_t *)&rptr[ip_hdr_len];
13228 	seg_seq = ABE32_TO_U32(tcph->th_seq);
13229 	seg_ack = ABE32_TO_U32(tcph->th_ack);
13230 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
13231 	seg_len = (int)(mp->b_wptr - rptr) -
13232 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
13233 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
13234 		do {
13235 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13236 			    (uintptr_t)INT_MAX);
13237 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
13238 		} while ((mp1 = mp1->b_cont) != NULL &&
13239 		    mp1->b_datap->db_type == M_DATA);
13240 	}
13241 
13242 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
13243 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
13244 		    seg_len, tcph);
13245 		return;
13246 	}
13247 
13248 	if (sqp != NULL) {
13249 		/*
13250 		 * This is the correct place to update tcp_last_recv_time. Note
13251 		 * that it is also updated for tcp structure that belongs to
13252 		 * global and listener queues which do not really need updating.
13253 		 * But that should not cause any harm.  And it is updated for
13254 		 * all kinds of incoming segments, not only for data segments.
13255 		 */
13256 		tcp->tcp_last_recv_time = lbolt;
13257 	}
13258 
13259 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13260 
13261 	BUMP_LOCAL(tcp->tcp_ibsegs);
13262 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13263 
13264 	if ((flags & TH_URG) && sqp != NULL) {
13265 		/*
13266 		 * TCP can't handle urgent pointers that arrive before
13267 		 * the connection has been accept()ed since it can't
13268 		 * buffer OOB data.  Discard segment if this happens.
13269 		 *
13270 		 * We can't just rely on a non-null tcp_listener to indicate
13271 		 * that the accept() has completed since unlinking of the
13272 		 * eager and completion of the accept are not atomic.
13273 		 * tcp_detached, when it is not set (B_FALSE) indicates
13274 		 * that the accept() has completed.
13275 		 *
13276 		 * Nor can it reassemble urgent pointers, so discard
13277 		 * if it's not the next segment expected.
13278 		 *
13279 		 * Otherwise, collapse chain into one mblk (discard if
13280 		 * that fails).  This makes sure the headers, retransmitted
13281 		 * data, and new data all are in the same mblk.
13282 		 */
13283 		ASSERT(mp != NULL);
13284 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13285 			freemsg(mp);
13286 			return;
13287 		}
13288 		/* Update pointers into message */
13289 		iphdr = rptr = mp->b_rptr;
13290 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13291 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13292 			/*
13293 			 * Since we can't handle any data with this urgent
13294 			 * pointer that is out of sequence, we expunge
13295 			 * the data.  This allows us to still register
13296 			 * the urgent mark and generate the M_PCSIG,
13297 			 * which we can do.
13298 			 */
13299 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13300 			seg_len = 0;
13301 		}
13302 	}
13303 
13304 	switch (tcp->tcp_state) {
13305 	case TCPS_SYN_SENT:
13306 		if (flags & TH_ACK) {
13307 			/*
13308 			 * Note that our stack cannot send data before a
13309 			 * connection is established, therefore the
13310 			 * following check is valid.  Otherwise, it has
13311 			 * to be changed.
13312 			 */
13313 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13314 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13315 				freemsg(mp);
13316 				if (flags & TH_RST)
13317 					return;
13318 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13319 				    tcp, seg_ack, 0, TH_RST);
13320 				return;
13321 			}
13322 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13323 		}
13324 		if (flags & TH_RST) {
13325 			freemsg(mp);
13326 			if (flags & TH_ACK)
13327 				(void) tcp_clean_death(tcp,
13328 				    ECONNREFUSED, 13);
13329 			return;
13330 		}
13331 		if (!(flags & TH_SYN)) {
13332 			freemsg(mp);
13333 			return;
13334 		}
13335 
13336 		/* Process all TCP options. */
13337 		tcp_process_options(tcp, tcph);
13338 		/*
13339 		 * The following changes our rwnd to be a multiple of the
13340 		 * MIN(peer MSS, our MSS) for performance reason.
13341 		 */
13342 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
13343 		    tcp->tcp_mss));
13344 
13345 		/* Is the other end ECN capable? */
13346 		if (tcp->tcp_ecn_ok) {
13347 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13348 				tcp->tcp_ecn_ok = B_FALSE;
13349 			}
13350 		}
13351 		/*
13352 		 * Clear ECN flags because it may interfere with later
13353 		 * processing.
13354 		 */
13355 		flags &= ~(TH_ECE|TH_CWR);
13356 
13357 		tcp->tcp_irs = seg_seq;
13358 		tcp->tcp_rack = seg_seq;
13359 		tcp->tcp_rnxt = seg_seq + 1;
13360 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13361 		if (!TCP_IS_DETACHED(tcp)) {
13362 			/* Allocate room for SACK options if needed. */
13363 			if (tcp->tcp_snd_sack_ok) {
13364 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13365 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13366 				    (tcp->tcp_loopback ? 0 :
13367 				    tcps->tcps_wroff_xtra));
13368 			} else {
13369 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13370 				    tcp->tcp_hdr_len +
13371 				    (tcp->tcp_loopback ? 0 :
13372 				    tcps->tcps_wroff_xtra));
13373 			}
13374 		}
13375 		if (flags & TH_ACK) {
13376 			/*
13377 			 * If we can't get the confirmation upstream, pretend
13378 			 * we didn't even see this one.
13379 			 *
13380 			 * XXX: how can we pretend we didn't see it if we
13381 			 * have updated rnxt et. al.
13382 			 *
13383 			 * For loopback we defer sending up the T_CONN_CON
13384 			 * until after some checks below.
13385 			 */
13386 			mp1 = NULL;
13387 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13388 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13389 				freemsg(mp);
13390 				return;
13391 			}
13392 			/* SYN was acked - making progress */
13393 			if (tcp->tcp_ipversion == IPV6_VERSION)
13394 				tcp->tcp_ip_forward_progress = B_TRUE;
13395 
13396 			/* One for the SYN */
13397 			tcp->tcp_suna = tcp->tcp_iss + 1;
13398 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13399 			tcp->tcp_state = TCPS_ESTABLISHED;
13400 
13401 			/*
13402 			 * If SYN was retransmitted, need to reset all
13403 			 * retransmission info.  This is because this
13404 			 * segment will be treated as a dup ACK.
13405 			 */
13406 			if (tcp->tcp_rexmit) {
13407 				tcp->tcp_rexmit = B_FALSE;
13408 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13409 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13410 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13411 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13412 				tcp->tcp_ms_we_have_waited = 0;
13413 
13414 				/*
13415 				 * Set tcp_cwnd back to 1 MSS, per
13416 				 * recommendation from
13417 				 * draft-floyd-incr-init-win-01.txt,
13418 				 * Increasing TCP's Initial Window.
13419 				 */
13420 				tcp->tcp_cwnd = tcp->tcp_mss;
13421 			}
13422 
13423 			tcp->tcp_swl1 = seg_seq;
13424 			tcp->tcp_swl2 = seg_ack;
13425 
13426 			new_swnd = BE16_TO_U16(tcph->th_win);
13427 			tcp->tcp_swnd = new_swnd;
13428 			if (new_swnd > tcp->tcp_max_swnd)
13429 				tcp->tcp_max_swnd = new_swnd;
13430 
13431 			/*
13432 			 * Always send the three-way handshake ack immediately
13433 			 * in order to make the connection complete as soon as
13434 			 * possible on the accepting host.
13435 			 */
13436 			flags |= TH_ACK_NEEDED;
13437 
13438 			/*
13439 			 * Special case for loopback.  At this point we have
13440 			 * received SYN-ACK from the remote endpoint.  In
13441 			 * order to ensure that both endpoints reach the
13442 			 * fused state prior to any data exchange, the final
13443 			 * ACK needs to be sent before we indicate T_CONN_CON
13444 			 * to the module upstream.
13445 			 */
13446 			if (tcp->tcp_loopback) {
13447 				mblk_t *ack_mp;
13448 
13449 				ASSERT(!tcp->tcp_unfusable);
13450 				ASSERT(mp1 != NULL);
13451 				/*
13452 				 * For loopback, we always get a pure SYN-ACK
13453 				 * and only need to send back the final ACK
13454 				 * with no data (this is because the other
13455 				 * tcp is ours and we don't do T/TCP).  This
13456 				 * final ACK triggers the passive side to
13457 				 * perform fusion in ESTABLISHED state.
13458 				 */
13459 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13460 					if (tcp->tcp_ack_tid != 0) {
13461 						(void) TCP_TIMER_CANCEL(tcp,
13462 						    tcp->tcp_ack_tid);
13463 						tcp->tcp_ack_tid = 0;
13464 					}
13465 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13466 					BUMP_LOCAL(tcp->tcp_obsegs);
13467 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13468 
13469 					/* Send up T_CONN_CON */
13470 					putnext(tcp->tcp_rq, mp1);
13471 
13472 					freemsg(mp);
13473 					return;
13474 				}
13475 				/*
13476 				 * Forget fusion; we need to handle more
13477 				 * complex cases below.  Send the deferred
13478 				 * T_CONN_CON message upstream and proceed
13479 				 * as usual.  Mark this tcp as not capable
13480 				 * of fusion.
13481 				 */
13482 				TCP_STAT(tcps, tcp_fusion_unfusable);
13483 				tcp->tcp_unfusable = B_TRUE;
13484 				putnext(tcp->tcp_rq, mp1);
13485 			}
13486 
13487 			/*
13488 			 * Check to see if there is data to be sent.  If
13489 			 * yes, set the transmit flag.  Then check to see
13490 			 * if received data processing needs to be done.
13491 			 * If not, go straight to xmit_check.  This short
13492 			 * cut is OK as we don't support T/TCP.
13493 			 */
13494 			if (tcp->tcp_unsent)
13495 				flags |= TH_XMIT_NEEDED;
13496 
13497 			if (seg_len == 0 && !(flags & TH_URG)) {
13498 				freemsg(mp);
13499 				goto xmit_check;
13500 			}
13501 
13502 			flags &= ~TH_SYN;
13503 			seg_seq++;
13504 			break;
13505 		}
13506 		tcp->tcp_state = TCPS_SYN_RCVD;
13507 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13508 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13509 		if (mp1) {
13510 			DB_CPID(mp1) = tcp->tcp_cpid;
13511 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13512 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13513 		}
13514 		freemsg(mp);
13515 		return;
13516 	case TCPS_SYN_RCVD:
13517 		if (flags & TH_ACK) {
13518 			/*
13519 			 * In this state, a SYN|ACK packet is either bogus
13520 			 * because the other side must be ACKing our SYN which
13521 			 * indicates it has seen the ACK for their SYN and
13522 			 * shouldn't retransmit it or we're crossing SYNs
13523 			 * on active open.
13524 			 */
13525 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13526 				freemsg(mp);
13527 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13528 				    tcp, seg_ack, 0, TH_RST);
13529 				return;
13530 			}
13531 			/*
13532 			 * NOTE: RFC 793 pg. 72 says this should be
13533 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13534 			 * but that would mean we have an ack that ignored
13535 			 * our SYN.
13536 			 */
13537 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13538 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13539 				freemsg(mp);
13540 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13541 				    tcp, seg_ack, 0, TH_RST);
13542 				return;
13543 			}
13544 		}
13545 		break;
13546 	case TCPS_LISTEN:
13547 		/*
13548 		 * Only a TLI listener can come through this path when a
13549 		 * acceptor is going back to be a listener and a packet
13550 		 * for the acceptor hits the classifier. For a socket
13551 		 * listener, this can never happen because a listener
13552 		 * can never accept connection on itself and hence a
13553 		 * socket acceptor can not go back to being a listener.
13554 		 */
13555 		ASSERT(!TCP_IS_SOCKET(tcp));
13556 		/*FALLTHRU*/
13557 	case TCPS_CLOSED:
13558 	case TCPS_BOUND: {
13559 		conn_t	*new_connp;
13560 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13561 
13562 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13563 		if (new_connp != NULL) {
13564 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13565 			return;
13566 		}
13567 		/* We failed to classify. For now just drop the packet */
13568 		freemsg(mp);
13569 		return;
13570 	}
13571 	case TCPS_IDLE:
13572 		/*
13573 		 * Handle the case where the tcp_clean_death() has happened
13574 		 * on a connection (application hasn't closed yet) but a packet
13575 		 * was already queued on squeue before tcp_clean_death()
13576 		 * was processed. Calling tcp_clean_death() twice on same
13577 		 * connection can result in weird behaviour.
13578 		 */
13579 		freemsg(mp);
13580 		return;
13581 	default:
13582 		break;
13583 	}
13584 
13585 	/*
13586 	 * Already on the correct queue/perimeter.
13587 	 * If this is a detached connection and not an eager
13588 	 * connection hanging off a listener then new data
13589 	 * (past the FIN) will cause a reset.
13590 	 * We do a special check here where it
13591 	 * is out of the main line, rather than check
13592 	 * if we are detached every time we see new
13593 	 * data down below.
13594 	 */
13595 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13596 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13597 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13598 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13599 
13600 		freemsg(mp);
13601 		/*
13602 		 * This could be an SSL closure alert. We're detached so just
13603 		 * acknowledge it this last time.
13604 		 */
13605 		if (tcp->tcp_kssl_ctx != NULL) {
13606 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13607 			tcp->tcp_kssl_ctx = NULL;
13608 
13609 			tcp->tcp_rnxt += seg_len;
13610 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13611 			flags |= TH_ACK_NEEDED;
13612 			goto ack_check;
13613 		}
13614 
13615 		tcp_xmit_ctl("new data when detached", tcp,
13616 		    tcp->tcp_snxt, 0, TH_RST);
13617 		(void) tcp_clean_death(tcp, EPROTO, 12);
13618 		return;
13619 	}
13620 
13621 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13622 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13623 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13624 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13625 
13626 	if (tcp->tcp_snd_ts_ok) {
13627 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13628 			/*
13629 			 * This segment is not acceptable.
13630 			 * Drop it and send back an ACK.
13631 			 */
13632 			freemsg(mp);
13633 			flags |= TH_ACK_NEEDED;
13634 			goto ack_check;
13635 		}
13636 	} else if (tcp->tcp_snd_sack_ok) {
13637 		ASSERT(tcp->tcp_sack_info != NULL);
13638 		tcpopt.tcp = tcp;
13639 		/*
13640 		 * SACK info in already updated in tcp_parse_options.  Ignore
13641 		 * all other TCP options...
13642 		 */
13643 		(void) tcp_parse_options(tcph, &tcpopt);
13644 	}
13645 try_again:;
13646 	mss = tcp->tcp_mss;
13647 	gap = seg_seq - tcp->tcp_rnxt;
13648 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13649 	/*
13650 	 * gap is the amount of sequence space between what we expect to see
13651 	 * and what we got for seg_seq.  A positive value for gap means
13652 	 * something got lost.  A negative value means we got some old stuff.
13653 	 */
13654 	if (gap < 0) {
13655 		/* Old stuff present.  Is the SYN in there? */
13656 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13657 		    (seg_len != 0)) {
13658 			flags &= ~TH_SYN;
13659 			seg_seq++;
13660 			urp--;
13661 			/* Recompute the gaps after noting the SYN. */
13662 			goto try_again;
13663 		}
13664 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13665 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13666 		    (seg_len > -gap ? -gap : seg_len));
13667 		/* Remove the old stuff from seg_len. */
13668 		seg_len += gap;
13669 		/*
13670 		 * Anything left?
13671 		 * Make sure to check for unack'd FIN when rest of data
13672 		 * has been previously ack'd.
13673 		 */
13674 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13675 			/*
13676 			 * Resets are only valid if they lie within our offered
13677 			 * window.  If the RST bit is set, we just ignore this
13678 			 * segment.
13679 			 */
13680 			if (flags & TH_RST) {
13681 				freemsg(mp);
13682 				return;
13683 			}
13684 
13685 			/*
13686 			 * The arriving of dup data packets indicate that we
13687 			 * may have postponed an ack for too long, or the other
13688 			 * side's RTT estimate is out of shape. Start acking
13689 			 * more often.
13690 			 */
13691 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13692 			    tcp->tcp_rack_cnt >= 1 &&
13693 			    tcp->tcp_rack_abs_max > 2) {
13694 				tcp->tcp_rack_abs_max--;
13695 			}
13696 			tcp->tcp_rack_cur_max = 1;
13697 
13698 			/*
13699 			 * This segment is "unacceptable".  None of its
13700 			 * sequence space lies within our advertized window.
13701 			 *
13702 			 * Adjust seg_len to the original value for tracing.
13703 			 */
13704 			seg_len -= gap;
13705 			if (tcp->tcp_debug) {
13706 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13707 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13708 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13709 				    "seg_len %d, rnxt %u, snxt %u, %s",
13710 				    gap, rgap, flags, seg_seq, seg_ack,
13711 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13712 				    tcp_display(tcp, NULL,
13713 				    DISP_ADDR_AND_PORT));
13714 			}
13715 
13716 			/*
13717 			 * Arrange to send an ACK in response to the
13718 			 * unacceptable segment per RFC 793 page 69. There
13719 			 * is only one small difference between ours and the
13720 			 * acceptability test in the RFC - we accept ACK-only
13721 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13722 			 * will be generated.
13723 			 *
13724 			 * Note that we have to ACK an ACK-only packet at least
13725 			 * for stacks that send 0-length keep-alives with
13726 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13727 			 * section 4.2.3.6. As long as we don't ever generate
13728 			 * an unacceptable packet in response to an incoming
13729 			 * packet that is unacceptable, it should not cause
13730 			 * "ACK wars".
13731 			 */
13732 			flags |=  TH_ACK_NEEDED;
13733 
13734 			/*
13735 			 * Continue processing this segment in order to use the
13736 			 * ACK information it contains, but skip all other
13737 			 * sequence-number processing.	Processing the ACK
13738 			 * information is necessary in order to
13739 			 * re-synchronize connections that may have lost
13740 			 * synchronization.
13741 			 *
13742 			 * We clear seg_len and flag fields related to
13743 			 * sequence number processing as they are not
13744 			 * to be trusted for an unacceptable segment.
13745 			 */
13746 			seg_len = 0;
13747 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13748 			goto process_ack;
13749 		}
13750 
13751 		/* Fix seg_seq, and chew the gap off the front. */
13752 		seg_seq = tcp->tcp_rnxt;
13753 		urp += gap;
13754 		do {
13755 			mblk_t	*mp2;
13756 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13757 			    (uintptr_t)UINT_MAX);
13758 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13759 			if (gap > 0) {
13760 				mp->b_rptr = mp->b_wptr - gap;
13761 				break;
13762 			}
13763 			mp2 = mp;
13764 			mp = mp->b_cont;
13765 			freeb(mp2);
13766 		} while (gap < 0);
13767 		/*
13768 		 * If the urgent data has already been acknowledged, we
13769 		 * should ignore TH_URG below
13770 		 */
13771 		if (urp < 0)
13772 			flags &= ~TH_URG;
13773 	}
13774 	/*
13775 	 * rgap is the amount of stuff received out of window.  A negative
13776 	 * value is the amount out of window.
13777 	 */
13778 	if (rgap < 0) {
13779 		mblk_t	*mp2;
13780 
13781 		if (tcp->tcp_rwnd == 0) {
13782 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13783 		} else {
13784 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13785 			UPDATE_MIB(&tcps->tcps_mib,
13786 			    tcpInDataPastWinBytes, -rgap);
13787 		}
13788 
13789 		/*
13790 		 * seg_len does not include the FIN, so if more than
13791 		 * just the FIN is out of window, we act like we don't
13792 		 * see it.  (If just the FIN is out of window, rgap
13793 		 * will be zero and we will go ahead and acknowledge
13794 		 * the FIN.)
13795 		 */
13796 		flags &= ~TH_FIN;
13797 
13798 		/* Fix seg_len and make sure there is something left. */
13799 		seg_len += rgap;
13800 		if (seg_len <= 0) {
13801 			/*
13802 			 * Resets are only valid if they lie within our offered
13803 			 * window.  If the RST bit is set, we just ignore this
13804 			 * segment.
13805 			 */
13806 			if (flags & TH_RST) {
13807 				freemsg(mp);
13808 				return;
13809 			}
13810 
13811 			/* Per RFC 793, we need to send back an ACK. */
13812 			flags |= TH_ACK_NEEDED;
13813 
13814 			/*
13815 			 * Send SIGURG as soon as possible i.e. even
13816 			 * if the TH_URG was delivered in a window probe
13817 			 * packet (which will be unacceptable).
13818 			 *
13819 			 * We generate a signal if none has been generated
13820 			 * for this connection or if this is a new urgent
13821 			 * byte. Also send a zero-length "unmarked" message
13822 			 * to inform SIOCATMARK that this is not the mark.
13823 			 *
13824 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13825 			 * is sent up. This plus the check for old data
13826 			 * (gap >= 0) handles the wraparound of the sequence
13827 			 * number space without having to always track the
13828 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13829 			 * this max in its rcv_up variable).
13830 			 *
13831 			 * This prevents duplicate SIGURGS due to a "late"
13832 			 * zero-window probe when the T_EXDATA_IND has already
13833 			 * been sent up.
13834 			 */
13835 			if ((flags & TH_URG) &&
13836 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13837 			    tcp->tcp_urp_last))) {
13838 				mp1 = allocb(0, BPRI_MED);
13839 				if (mp1 == NULL) {
13840 					freemsg(mp);
13841 					return;
13842 				}
13843 				if (!TCP_IS_DETACHED(tcp) &&
13844 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13845 				    SIGURG)) {
13846 					/* Try again on the rexmit. */
13847 					freemsg(mp1);
13848 					freemsg(mp);
13849 					return;
13850 				}
13851 				/*
13852 				 * If the next byte would be the mark
13853 				 * then mark with MARKNEXT else mark
13854 				 * with NOTMARKNEXT.
13855 				 */
13856 				if (gap == 0 && urp == 0)
13857 					mp1->b_flag |= MSGMARKNEXT;
13858 				else
13859 					mp1->b_flag |= MSGNOTMARKNEXT;
13860 				freemsg(tcp->tcp_urp_mark_mp);
13861 				tcp->tcp_urp_mark_mp = mp1;
13862 				flags |= TH_SEND_URP_MARK;
13863 				tcp->tcp_urp_last_valid = B_TRUE;
13864 				tcp->tcp_urp_last = urp + seg_seq;
13865 			}
13866 			/*
13867 			 * If this is a zero window probe, continue to
13868 			 * process the ACK part.  But we need to set seg_len
13869 			 * to 0 to avoid data processing.  Otherwise just
13870 			 * drop the segment and send back an ACK.
13871 			 */
13872 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13873 				flags &= ~(TH_SYN | TH_URG);
13874 				seg_len = 0;
13875 				goto process_ack;
13876 			} else {
13877 				freemsg(mp);
13878 				goto ack_check;
13879 			}
13880 		}
13881 		/* Pitch out of window stuff off the end. */
13882 		rgap = seg_len;
13883 		mp2 = mp;
13884 		do {
13885 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13886 			    (uintptr_t)INT_MAX);
13887 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13888 			if (rgap < 0) {
13889 				mp2->b_wptr += rgap;
13890 				if ((mp1 = mp2->b_cont) != NULL) {
13891 					mp2->b_cont = NULL;
13892 					freemsg(mp1);
13893 				}
13894 				break;
13895 			}
13896 		} while ((mp2 = mp2->b_cont) != NULL);
13897 	}
13898 ok:;
13899 	/*
13900 	 * TCP should check ECN info for segments inside the window only.
13901 	 * Therefore the check should be done here.
13902 	 */
13903 	if (tcp->tcp_ecn_ok) {
13904 		if (flags & TH_CWR) {
13905 			tcp->tcp_ecn_echo_on = B_FALSE;
13906 		}
13907 		/*
13908 		 * Note that both ECN_CE and CWR can be set in the
13909 		 * same segment.  In this case, we once again turn
13910 		 * on ECN_ECHO.
13911 		 */
13912 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13913 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13914 
13915 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13916 				tcp->tcp_ecn_echo_on = B_TRUE;
13917 			}
13918 		} else {
13919 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13920 
13921 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13922 			    htonl(IPH_ECN_CE << 20)) {
13923 				tcp->tcp_ecn_echo_on = B_TRUE;
13924 			}
13925 		}
13926 	}
13927 
13928 	/*
13929 	 * Check whether we can update tcp_ts_recent.  This test is
13930 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13931 	 * Extensions for High Performance: An Update", Internet Draft.
13932 	 */
13933 	if (tcp->tcp_snd_ts_ok &&
13934 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13935 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13936 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13937 		tcp->tcp_last_rcv_lbolt = lbolt64;
13938 	}
13939 
13940 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13941 		/*
13942 		 * FIN in an out of order segment.  We record this in
13943 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13944 		 * Clear the FIN so that any check on FIN flag will fail.
13945 		 * Remember that FIN also counts in the sequence number
13946 		 * space.  So we need to ack out of order FIN only segments.
13947 		 */
13948 		if (flags & TH_FIN) {
13949 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13950 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13951 			flags &= ~TH_FIN;
13952 			flags |= TH_ACK_NEEDED;
13953 		}
13954 		if (seg_len > 0) {
13955 			/* Fill in the SACK blk list. */
13956 			if (tcp->tcp_snd_sack_ok) {
13957 				ASSERT(tcp->tcp_sack_info != NULL);
13958 				tcp_sack_insert(tcp->tcp_sack_list,
13959 				    seg_seq, seg_seq + seg_len,
13960 				    &(tcp->tcp_num_sack_blk));
13961 			}
13962 
13963 			/*
13964 			 * Attempt reassembly and see if we have something
13965 			 * ready to go.
13966 			 */
13967 			mp = tcp_reass(tcp, mp, seg_seq);
13968 			/* Always ack out of order packets */
13969 			flags |= TH_ACK_NEEDED | TH_PUSH;
13970 			if (mp) {
13971 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13972 				    (uintptr_t)INT_MAX);
13973 				seg_len = mp->b_cont ? msgdsize(mp) :
13974 				    (int)(mp->b_wptr - mp->b_rptr);
13975 				seg_seq = tcp->tcp_rnxt;
13976 				/*
13977 				 * A gap is filled and the seq num and len
13978 				 * of the gap match that of a previously
13979 				 * received FIN, put the FIN flag back in.
13980 				 */
13981 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13982 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13983 					flags |= TH_FIN;
13984 					tcp->tcp_valid_bits &=
13985 					    ~TCP_OFO_FIN_VALID;
13986 				}
13987 			} else {
13988 				/*
13989 				 * Keep going even with NULL mp.
13990 				 * There may be a useful ACK or something else
13991 				 * we don't want to miss.
13992 				 *
13993 				 * But TCP should not perform fast retransmit
13994 				 * because of the ack number.  TCP uses
13995 				 * seg_len == 0 to determine if it is a pure
13996 				 * ACK.  And this is not a pure ACK.
13997 				 */
13998 				seg_len = 0;
13999 				ofo_seg = B_TRUE;
14000 			}
14001 		}
14002 	} else if (seg_len > 0) {
14003 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
14004 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
14005 		/*
14006 		 * If an out of order FIN was received before, and the seq
14007 		 * num and len of the new segment match that of the FIN,
14008 		 * put the FIN flag back in.
14009 		 */
14010 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
14011 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
14012 			flags |= TH_FIN;
14013 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
14014 		}
14015 	}
14016 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
14017 	if (flags & TH_RST) {
14018 		freemsg(mp);
14019 		switch (tcp->tcp_state) {
14020 		case TCPS_SYN_RCVD:
14021 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
14022 			break;
14023 		case TCPS_ESTABLISHED:
14024 		case TCPS_FIN_WAIT_1:
14025 		case TCPS_FIN_WAIT_2:
14026 		case TCPS_CLOSE_WAIT:
14027 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
14028 			break;
14029 		case TCPS_CLOSING:
14030 		case TCPS_LAST_ACK:
14031 			(void) tcp_clean_death(tcp, 0, 16);
14032 			break;
14033 		default:
14034 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14035 			(void) tcp_clean_death(tcp, ENXIO, 17);
14036 			break;
14037 		}
14038 		return;
14039 	}
14040 	if (flags & TH_SYN) {
14041 		/*
14042 		 * See RFC 793, Page 71
14043 		 *
14044 		 * The seq number must be in the window as it should
14045 		 * be "fixed" above.  If it is outside window, it should
14046 		 * be already rejected.  Note that we allow seg_seq to be
14047 		 * rnxt + rwnd because we want to accept 0 window probe.
14048 		 */
14049 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
14050 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
14051 		freemsg(mp);
14052 		/*
14053 		 * If the ACK flag is not set, just use our snxt as the
14054 		 * seq number of the RST segment.
14055 		 */
14056 		if (!(flags & TH_ACK)) {
14057 			seg_ack = tcp->tcp_snxt;
14058 		}
14059 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
14060 		    TH_RST|TH_ACK);
14061 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14062 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
14063 		return;
14064 	}
14065 	/*
14066 	 * urp could be -1 when the urp field in the packet is 0
14067 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
14068 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
14069 	 */
14070 	if (flags & TH_URG && urp >= 0) {
14071 		if (!tcp->tcp_urp_last_valid ||
14072 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
14073 			/*
14074 			 * If we haven't generated the signal yet for this
14075 			 * urgent pointer value, do it now.  Also, send up a
14076 			 * zero-length M_DATA indicating whether or not this is
14077 			 * the mark. The latter is not needed when a
14078 			 * T_EXDATA_IND is sent up. However, if there are
14079 			 * allocation failures this code relies on the sender
14080 			 * retransmitting and the socket code for determining
14081 			 * the mark should not block waiting for the peer to
14082 			 * transmit. Thus, for simplicity we always send up the
14083 			 * mark indication.
14084 			 */
14085 			mp1 = allocb(0, BPRI_MED);
14086 			if (mp1 == NULL) {
14087 				freemsg(mp);
14088 				return;
14089 			}
14090 			if (!TCP_IS_DETACHED(tcp) &&
14091 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
14092 				/* Try again on the rexmit. */
14093 				freemsg(mp1);
14094 				freemsg(mp);
14095 				return;
14096 			}
14097 			/*
14098 			 * Mark with NOTMARKNEXT for now.
14099 			 * The code below will change this to MARKNEXT
14100 			 * if we are at the mark.
14101 			 *
14102 			 * If there are allocation failures (e.g. in dupmsg
14103 			 * below) the next time tcp_rput_data sees the urgent
14104 			 * segment it will send up the MSG*MARKNEXT message.
14105 			 */
14106 			mp1->b_flag |= MSGNOTMARKNEXT;
14107 			freemsg(tcp->tcp_urp_mark_mp);
14108 			tcp->tcp_urp_mark_mp = mp1;
14109 			flags |= TH_SEND_URP_MARK;
14110 #ifdef DEBUG
14111 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14112 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
14113 			    "last %x, %s",
14114 			    seg_seq, urp, tcp->tcp_urp_last,
14115 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14116 #endif /* DEBUG */
14117 			tcp->tcp_urp_last_valid = B_TRUE;
14118 			tcp->tcp_urp_last = urp + seg_seq;
14119 		} else if (tcp->tcp_urp_mark_mp != NULL) {
14120 			/*
14121 			 * An allocation failure prevented the previous
14122 			 * tcp_rput_data from sending up the allocated
14123 			 * MSG*MARKNEXT message - send it up this time
14124 			 * around.
14125 			 */
14126 			flags |= TH_SEND_URP_MARK;
14127 		}
14128 
14129 		/*
14130 		 * If the urgent byte is in this segment, make sure that it is
14131 		 * all by itself.  This makes it much easier to deal with the
14132 		 * possibility of an allocation failure on the T_exdata_ind.
14133 		 * Note that seg_len is the number of bytes in the segment, and
14134 		 * urp is the offset into the segment of the urgent byte.
14135 		 * urp < seg_len means that the urgent byte is in this segment.
14136 		 */
14137 		if (urp < seg_len) {
14138 			if (seg_len != 1) {
14139 				uint32_t  tmp_rnxt;
14140 				/*
14141 				 * Break it up and feed it back in.
14142 				 * Re-attach the IP header.
14143 				 */
14144 				mp->b_rptr = iphdr;
14145 				if (urp > 0) {
14146 					/*
14147 					 * There is stuff before the urgent
14148 					 * byte.
14149 					 */
14150 					mp1 = dupmsg(mp);
14151 					if (!mp1) {
14152 						/*
14153 						 * Trim from urgent byte on.
14154 						 * The rest will come back.
14155 						 */
14156 						(void) adjmsg(mp,
14157 						    urp - seg_len);
14158 						tcp_rput_data(connp,
14159 						    mp, NULL);
14160 						return;
14161 					}
14162 					(void) adjmsg(mp1, urp - seg_len);
14163 					/* Feed this piece back in. */
14164 					tmp_rnxt = tcp->tcp_rnxt;
14165 					tcp_rput_data(connp, mp1, NULL);
14166 					/*
14167 					 * If the data passed back in was not
14168 					 * processed (ie: bad ACK) sending
14169 					 * the remainder back in will cause a
14170 					 * loop. In this case, drop the
14171 					 * packet and let the sender try
14172 					 * sending a good packet.
14173 					 */
14174 					if (tmp_rnxt == tcp->tcp_rnxt) {
14175 						freemsg(mp);
14176 						return;
14177 					}
14178 				}
14179 				if (urp != seg_len - 1) {
14180 					uint32_t  tmp_rnxt;
14181 					/*
14182 					 * There is stuff after the urgent
14183 					 * byte.
14184 					 */
14185 					mp1 = dupmsg(mp);
14186 					if (!mp1) {
14187 						/*
14188 						 * Trim everything beyond the
14189 						 * urgent byte.  The rest will
14190 						 * come back.
14191 						 */
14192 						(void) adjmsg(mp,
14193 						    urp + 1 - seg_len);
14194 						tcp_rput_data(connp,
14195 						    mp, NULL);
14196 						return;
14197 					}
14198 					(void) adjmsg(mp1, urp + 1 - seg_len);
14199 					tmp_rnxt = tcp->tcp_rnxt;
14200 					tcp_rput_data(connp, mp1, NULL);
14201 					/*
14202 					 * If the data passed back in was not
14203 					 * processed (ie: bad ACK) sending
14204 					 * the remainder back in will cause a
14205 					 * loop. In this case, drop the
14206 					 * packet and let the sender try
14207 					 * sending a good packet.
14208 					 */
14209 					if (tmp_rnxt == tcp->tcp_rnxt) {
14210 						freemsg(mp);
14211 						return;
14212 					}
14213 				}
14214 				tcp_rput_data(connp, mp, NULL);
14215 				return;
14216 			}
14217 			/*
14218 			 * This segment contains only the urgent byte.  We
14219 			 * have to allocate the T_exdata_ind, if we can.
14220 			 */
14221 			if (!tcp->tcp_urp_mp) {
14222 				struct T_exdata_ind *tei;
14223 				mp1 = allocb(sizeof (struct T_exdata_ind),
14224 				    BPRI_MED);
14225 				if (!mp1) {
14226 					/*
14227 					 * Sigh... It'll be back.
14228 					 * Generate any MSG*MARK message now.
14229 					 */
14230 					freemsg(mp);
14231 					seg_len = 0;
14232 					if (flags & TH_SEND_URP_MARK) {
14233 
14234 
14235 						ASSERT(tcp->tcp_urp_mark_mp);
14236 						tcp->tcp_urp_mark_mp->b_flag &=
14237 						    ~MSGNOTMARKNEXT;
14238 						tcp->tcp_urp_mark_mp->b_flag |=
14239 						    MSGMARKNEXT;
14240 					}
14241 					goto ack_check;
14242 				}
14243 				mp1->b_datap->db_type = M_PROTO;
14244 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14245 				tei->PRIM_type = T_EXDATA_IND;
14246 				tei->MORE_flag = 0;
14247 				mp1->b_wptr = (uchar_t *)&tei[1];
14248 				tcp->tcp_urp_mp = mp1;
14249 #ifdef DEBUG
14250 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14251 				    "tcp_rput: allocated exdata_ind %s",
14252 				    tcp_display(tcp, NULL,
14253 				    DISP_PORT_ONLY));
14254 #endif /* DEBUG */
14255 				/*
14256 				 * There is no need to send a separate MSG*MARK
14257 				 * message since the T_EXDATA_IND will be sent
14258 				 * now.
14259 				 */
14260 				flags &= ~TH_SEND_URP_MARK;
14261 				freemsg(tcp->tcp_urp_mark_mp);
14262 				tcp->tcp_urp_mark_mp = NULL;
14263 			}
14264 			/*
14265 			 * Now we are all set.  On the next putnext upstream,
14266 			 * tcp_urp_mp will be non-NULL and will get prepended
14267 			 * to what has to be this piece containing the urgent
14268 			 * byte.  If for any reason we abort this segment below,
14269 			 * if it comes back, we will have this ready, or it
14270 			 * will get blown off in close.
14271 			 */
14272 		} else if (urp == seg_len) {
14273 			/*
14274 			 * The urgent byte is the next byte after this sequence
14275 			 * number. If there is data it is marked with
14276 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14277 			 * since it is not needed. Otherwise, if the code
14278 			 * above just allocated a zero-length tcp_urp_mark_mp
14279 			 * message, that message is tagged with MSGMARKNEXT.
14280 			 * Sending up these MSGMARKNEXT messages makes
14281 			 * SIOCATMARK work correctly even though
14282 			 * the T_EXDATA_IND will not be sent up until the
14283 			 * urgent byte arrives.
14284 			 */
14285 			if (seg_len != 0) {
14286 				flags |= TH_MARKNEXT_NEEDED;
14287 				freemsg(tcp->tcp_urp_mark_mp);
14288 				tcp->tcp_urp_mark_mp = NULL;
14289 				flags &= ~TH_SEND_URP_MARK;
14290 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14291 				flags |= TH_SEND_URP_MARK;
14292 				tcp->tcp_urp_mark_mp->b_flag &=
14293 				    ~MSGNOTMARKNEXT;
14294 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14295 			}
14296 #ifdef DEBUG
14297 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14298 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14299 			    seg_len, flags,
14300 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14301 #endif /* DEBUG */
14302 		} else {
14303 			/* Data left until we hit mark */
14304 #ifdef DEBUG
14305 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14306 			    "tcp_rput: URP %d bytes left, %s",
14307 			    urp - seg_len, tcp_display(tcp, NULL,
14308 			    DISP_PORT_ONLY));
14309 #endif /* DEBUG */
14310 		}
14311 	}
14312 
14313 process_ack:
14314 	if (!(flags & TH_ACK)) {
14315 		freemsg(mp);
14316 		goto xmit_check;
14317 	}
14318 	}
14319 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14320 
14321 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14322 		tcp->tcp_ip_forward_progress = B_TRUE;
14323 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14324 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14325 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14326 			/* 3-way handshake complete - pass up the T_CONN_IND */
14327 			tcp_t	*listener = tcp->tcp_listener;
14328 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14329 
14330 			tcp->tcp_tconnind_started = B_TRUE;
14331 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14332 			/*
14333 			 * We are here means eager is fine but it can
14334 			 * get a TH_RST at any point between now and till
14335 			 * accept completes and disappear. We need to
14336 			 * ensure that reference to eager is valid after
14337 			 * we get out of eager's perimeter. So we do
14338 			 * an extra refhold.
14339 			 */
14340 			CONN_INC_REF(connp);
14341 
14342 			/*
14343 			 * The listener also exists because of the refhold
14344 			 * done in tcp_conn_request. Its possible that it
14345 			 * might have closed. We will check that once we
14346 			 * get inside listeners context.
14347 			 */
14348 			CONN_INC_REF(listener->tcp_connp);
14349 			if (listener->tcp_connp->conn_sqp ==
14350 			    connp->conn_sqp) {
14351 				/*
14352 				 * We optimize by not calling an SQUEUE_ENTER
14353 				 * on the listener since we know that the
14354 				 * listener and eager squeues are the same.
14355 				 * We are able to make this check safely only
14356 				 * because neither the eager nor the listener
14357 				 * can change its squeue. Only an active connect
14358 				 * can change its squeue
14359 				 */
14360 				tcp_send_conn_ind(listener->tcp_connp, mp,
14361 				    listener->tcp_connp->conn_sqp);
14362 				CONN_DEC_REF(listener->tcp_connp);
14363 			} else if (!tcp->tcp_loopback) {
14364 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14365 				    mp, tcp_send_conn_ind,
14366 				    listener->tcp_connp, SQ_FILL,
14367 				    SQTAG_TCP_CONN_IND);
14368 			} else {
14369 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14370 				    mp, tcp_send_conn_ind,
14371 				    listener->tcp_connp, SQ_PROCESS,
14372 				    SQTAG_TCP_CONN_IND);
14373 			}
14374 		}
14375 
14376 		if (tcp->tcp_active_open) {
14377 			/*
14378 			 * We are seeing the final ack in the three way
14379 			 * hand shake of a active open'ed connection
14380 			 * so we must send up a T_CONN_CON
14381 			 */
14382 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14383 				freemsg(mp);
14384 				return;
14385 			}
14386 			/*
14387 			 * Don't fuse the loopback endpoints for
14388 			 * simultaneous active opens.
14389 			 */
14390 			if (tcp->tcp_loopback) {
14391 				TCP_STAT(tcps, tcp_fusion_unfusable);
14392 				tcp->tcp_unfusable = B_TRUE;
14393 			}
14394 		}
14395 
14396 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14397 		bytes_acked--;
14398 		/* SYN was acked - making progress */
14399 		if (tcp->tcp_ipversion == IPV6_VERSION)
14400 			tcp->tcp_ip_forward_progress = B_TRUE;
14401 
14402 		/*
14403 		 * If SYN was retransmitted, need to reset all
14404 		 * retransmission info as this segment will be
14405 		 * treated as a dup ACK.
14406 		 */
14407 		if (tcp->tcp_rexmit) {
14408 			tcp->tcp_rexmit = B_FALSE;
14409 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14410 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14411 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14412 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14413 			tcp->tcp_ms_we_have_waited = 0;
14414 			tcp->tcp_cwnd = mss;
14415 		}
14416 
14417 		/*
14418 		 * We set the send window to zero here.
14419 		 * This is needed if there is data to be
14420 		 * processed already on the queue.
14421 		 * Later (at swnd_update label), the
14422 		 * "new_swnd > tcp_swnd" condition is satisfied
14423 		 * the XMIT_NEEDED flag is set in the current
14424 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14425 		 * called if there is already data on queue in
14426 		 * this state.
14427 		 */
14428 		tcp->tcp_swnd = 0;
14429 
14430 		if (new_swnd > tcp->tcp_max_swnd)
14431 			tcp->tcp_max_swnd = new_swnd;
14432 		tcp->tcp_swl1 = seg_seq;
14433 		tcp->tcp_swl2 = seg_ack;
14434 		tcp->tcp_state = TCPS_ESTABLISHED;
14435 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14436 
14437 		/* Fuse when both sides are in ESTABLISHED state */
14438 		if (tcp->tcp_loopback && do_tcp_fusion)
14439 			tcp_fuse(tcp, iphdr, tcph);
14440 
14441 	}
14442 	/* This code follows 4.4BSD-Lite2 mostly. */
14443 	if (bytes_acked < 0)
14444 		goto est;
14445 
14446 	/*
14447 	 * If TCP is ECN capable and the congestion experience bit is
14448 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14449 	 * done once per window (or more loosely, per RTT).
14450 	 */
14451 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14452 		tcp->tcp_cwr = B_FALSE;
14453 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14454 		if (!tcp->tcp_cwr) {
14455 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14456 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14457 			tcp->tcp_cwnd = npkt * mss;
14458 			/*
14459 			 * If the cwnd is 0, use the timer to clock out
14460 			 * new segments.  This is required by the ECN spec.
14461 			 */
14462 			if (npkt == 0) {
14463 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14464 				/*
14465 				 * This makes sure that when the ACK comes
14466 				 * back, we will increase tcp_cwnd by 1 MSS.
14467 				 */
14468 				tcp->tcp_cwnd_cnt = 0;
14469 			}
14470 			tcp->tcp_cwr = B_TRUE;
14471 			/*
14472 			 * This marks the end of the current window of in
14473 			 * flight data.  That is why we don't use
14474 			 * tcp_suna + tcp_swnd.  Only data in flight can
14475 			 * provide ECN info.
14476 			 */
14477 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14478 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14479 		}
14480 	}
14481 
14482 	mp1 = tcp->tcp_xmit_head;
14483 	if (bytes_acked == 0) {
14484 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14485 			int dupack_cnt;
14486 
14487 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14488 			/*
14489 			 * Fast retransmit.  When we have seen exactly three
14490 			 * identical ACKs while we have unacked data
14491 			 * outstanding we take it as a hint that our peer
14492 			 * dropped something.
14493 			 *
14494 			 * If TCP is retransmitting, don't do fast retransmit.
14495 			 */
14496 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14497 			    ! tcp->tcp_rexmit) {
14498 				/* Do Limited Transmit */
14499 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14500 				    tcps->tcps_dupack_fast_retransmit) {
14501 					/*
14502 					 * RFC 3042
14503 					 *
14504 					 * What we need to do is temporarily
14505 					 * increase tcp_cwnd so that new
14506 					 * data can be sent if it is allowed
14507 					 * by the receive window (tcp_rwnd).
14508 					 * tcp_wput_data() will take care of
14509 					 * the rest.
14510 					 *
14511 					 * If the connection is SACK capable,
14512 					 * only do limited xmit when there
14513 					 * is SACK info.
14514 					 *
14515 					 * Note how tcp_cwnd is incremented.
14516 					 * The first dup ACK will increase
14517 					 * it by 1 MSS.  The second dup ACK
14518 					 * will increase it by 2 MSS.  This
14519 					 * means that only 1 new segment will
14520 					 * be sent for each dup ACK.
14521 					 */
14522 					if (tcp->tcp_unsent > 0 &&
14523 					    (!tcp->tcp_snd_sack_ok ||
14524 					    (tcp->tcp_snd_sack_ok &&
14525 					    tcp->tcp_notsack_list != NULL))) {
14526 						tcp->tcp_cwnd += mss <<
14527 						    (tcp->tcp_dupack_cnt - 1);
14528 						flags |= TH_LIMIT_XMIT;
14529 					}
14530 				} else if (dupack_cnt ==
14531 				    tcps->tcps_dupack_fast_retransmit) {
14532 
14533 				/*
14534 				 * If we have reduced tcp_ssthresh
14535 				 * because of ECN, do not reduce it again
14536 				 * unless it is already one window of data
14537 				 * away.  After one window of data, tcp_cwr
14538 				 * should then be cleared.  Note that
14539 				 * for non ECN capable connection, tcp_cwr
14540 				 * should always be false.
14541 				 *
14542 				 * Adjust cwnd since the duplicate
14543 				 * ack indicates that a packet was
14544 				 * dropped (due to congestion.)
14545 				 */
14546 				if (!tcp->tcp_cwr) {
14547 					npkt = ((tcp->tcp_snxt -
14548 					    tcp->tcp_suna) >> 1) / mss;
14549 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14550 					    mss;
14551 					tcp->tcp_cwnd = (npkt +
14552 					    tcp->tcp_dupack_cnt) * mss;
14553 				}
14554 				if (tcp->tcp_ecn_ok) {
14555 					tcp->tcp_cwr = B_TRUE;
14556 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14557 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14558 				}
14559 
14560 				/*
14561 				 * We do Hoe's algorithm.  Refer to her
14562 				 * paper "Improving the Start-up Behavior
14563 				 * of a Congestion Control Scheme for TCP,"
14564 				 * appeared in SIGCOMM'96.
14565 				 *
14566 				 * Save highest seq no we have sent so far.
14567 				 * Be careful about the invisible FIN byte.
14568 				 */
14569 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14570 				    (tcp->tcp_unsent == 0)) {
14571 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14572 				} else {
14573 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14574 				}
14575 
14576 				/*
14577 				 * Do not allow bursty traffic during.
14578 				 * fast recovery.  Refer to Fall and Floyd's
14579 				 * paper "Simulation-based Comparisons of
14580 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14581 				 * This is a best current practise.
14582 				 */
14583 				tcp->tcp_snd_burst = TCP_CWND_SS;
14584 
14585 				/*
14586 				 * For SACK:
14587 				 * Calculate tcp_pipe, which is the
14588 				 * estimated number of bytes in
14589 				 * network.
14590 				 *
14591 				 * tcp_fack is the highest sack'ed seq num
14592 				 * TCP has received.
14593 				 *
14594 				 * tcp_pipe is explained in the above quoted
14595 				 * Fall and Floyd's paper.  tcp_fack is
14596 				 * explained in Mathis and Mahdavi's
14597 				 * "Forward Acknowledgment: Refining TCP
14598 				 * Congestion Control" in SIGCOMM '96.
14599 				 */
14600 				if (tcp->tcp_snd_sack_ok) {
14601 					ASSERT(tcp->tcp_sack_info != NULL);
14602 					if (tcp->tcp_notsack_list != NULL) {
14603 						tcp->tcp_pipe = tcp->tcp_snxt -
14604 						    tcp->tcp_fack;
14605 						tcp->tcp_sack_snxt = seg_ack;
14606 						flags |= TH_NEED_SACK_REXMIT;
14607 					} else {
14608 						/*
14609 						 * Always initialize tcp_pipe
14610 						 * even though we don't have
14611 						 * any SACK info.  If later
14612 						 * we get SACK info and
14613 						 * tcp_pipe is not initialized,
14614 						 * funny things will happen.
14615 						 */
14616 						tcp->tcp_pipe =
14617 						    tcp->tcp_cwnd_ssthresh;
14618 					}
14619 				} else {
14620 					flags |= TH_REXMIT_NEEDED;
14621 				} /* tcp_snd_sack_ok */
14622 
14623 				} else {
14624 					/*
14625 					 * Here we perform congestion
14626 					 * avoidance, but NOT slow start.
14627 					 * This is known as the Fast
14628 					 * Recovery Algorithm.
14629 					 */
14630 					if (tcp->tcp_snd_sack_ok &&
14631 					    tcp->tcp_notsack_list != NULL) {
14632 						flags |= TH_NEED_SACK_REXMIT;
14633 						tcp->tcp_pipe -= mss;
14634 						if (tcp->tcp_pipe < 0)
14635 							tcp->tcp_pipe = 0;
14636 					} else {
14637 					/*
14638 					 * We know that one more packet has
14639 					 * left the pipe thus we can update
14640 					 * cwnd.
14641 					 */
14642 					cwnd = tcp->tcp_cwnd + mss;
14643 					if (cwnd > tcp->tcp_cwnd_max)
14644 						cwnd = tcp->tcp_cwnd_max;
14645 					tcp->tcp_cwnd = cwnd;
14646 					if (tcp->tcp_unsent > 0)
14647 						flags |= TH_XMIT_NEEDED;
14648 					}
14649 				}
14650 			}
14651 		} else if (tcp->tcp_zero_win_probe) {
14652 			/*
14653 			 * If the window has opened, need to arrange
14654 			 * to send additional data.
14655 			 */
14656 			if (new_swnd != 0) {
14657 				/* tcp_suna != tcp_snxt */
14658 				/* Packet contains a window update */
14659 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14660 				tcp->tcp_zero_win_probe = 0;
14661 				tcp->tcp_timer_backoff = 0;
14662 				tcp->tcp_ms_we_have_waited = 0;
14663 
14664 				/*
14665 				 * Transmit starting with tcp_suna since
14666 				 * the one byte probe is not ack'ed.
14667 				 * If TCP has sent more than one identical
14668 				 * probe, tcp_rexmit will be set.  That means
14669 				 * tcp_ss_rexmit() will send out the one
14670 				 * byte along with new data.  Otherwise,
14671 				 * fake the retransmission.
14672 				 */
14673 				flags |= TH_XMIT_NEEDED;
14674 				if (!tcp->tcp_rexmit) {
14675 					tcp->tcp_rexmit = B_TRUE;
14676 					tcp->tcp_dupack_cnt = 0;
14677 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14678 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14679 				}
14680 			}
14681 		}
14682 		goto swnd_update;
14683 	}
14684 
14685 	/*
14686 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14687 	 * If the ACK value acks something that we have not yet sent, it might
14688 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14689 	 * other side.
14690 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14691 	 * state is handled above, so we can always just drop the segment and
14692 	 * send an ACK here.
14693 	 *
14694 	 * Should we send ACKs in response to ACK only segments?
14695 	 */
14696 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14697 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14698 		/* drop the received segment */
14699 		freemsg(mp);
14700 
14701 		/*
14702 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14703 		 * greater than 0, check if the number of such
14704 		 * bogus ACks is greater than that count.  If yes,
14705 		 * don't send back any ACK.  This prevents TCP from
14706 		 * getting into an ACK storm if somehow an attacker
14707 		 * successfully spoofs an acceptable segment to our
14708 		 * peer.
14709 		 */
14710 		if (tcp_drop_ack_unsent_cnt > 0 &&
14711 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14712 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14713 			return;
14714 		}
14715 		mp = tcp_ack_mp(tcp);
14716 		if (mp != NULL) {
14717 			BUMP_LOCAL(tcp->tcp_obsegs);
14718 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14719 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14720 		}
14721 		return;
14722 	}
14723 
14724 	/*
14725 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14726 	 * blocks that are covered by this ACK.
14727 	 */
14728 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14729 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14730 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14731 	}
14732 
14733 	/*
14734 	 * If we got an ACK after fast retransmit, check to see
14735 	 * if it is a partial ACK.  If it is not and the congestion
14736 	 * window was inflated to account for the other side's
14737 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14738 	 */
14739 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14740 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14741 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14742 			tcp->tcp_dupack_cnt = 0;
14743 			/*
14744 			 * Restore the orig tcp_cwnd_ssthresh after
14745 			 * fast retransmit phase.
14746 			 */
14747 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14748 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14749 			}
14750 			tcp->tcp_rexmit_max = seg_ack;
14751 			tcp->tcp_cwnd_cnt = 0;
14752 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14753 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14754 
14755 			/*
14756 			 * Remove all notsack info to avoid confusion with
14757 			 * the next fast retrasnmit/recovery phase.
14758 			 */
14759 			if (tcp->tcp_snd_sack_ok &&
14760 			    tcp->tcp_notsack_list != NULL) {
14761 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14762 			}
14763 		} else {
14764 			if (tcp->tcp_snd_sack_ok &&
14765 			    tcp->tcp_notsack_list != NULL) {
14766 				flags |= TH_NEED_SACK_REXMIT;
14767 				tcp->tcp_pipe -= mss;
14768 				if (tcp->tcp_pipe < 0)
14769 					tcp->tcp_pipe = 0;
14770 			} else {
14771 				/*
14772 				 * Hoe's algorithm:
14773 				 *
14774 				 * Retransmit the unack'ed segment and
14775 				 * restart fast recovery.  Note that we
14776 				 * need to scale back tcp_cwnd to the
14777 				 * original value when we started fast
14778 				 * recovery.  This is to prevent overly
14779 				 * aggressive behaviour in sending new
14780 				 * segments.
14781 				 */
14782 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14783 				    tcps->tcps_dupack_fast_retransmit * mss;
14784 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14785 				flags |= TH_REXMIT_NEEDED;
14786 			}
14787 		}
14788 	} else {
14789 		tcp->tcp_dupack_cnt = 0;
14790 		if (tcp->tcp_rexmit) {
14791 			/*
14792 			 * TCP is retranmitting.  If the ACK ack's all
14793 			 * outstanding data, update tcp_rexmit_max and
14794 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14795 			 * to the correct value.
14796 			 *
14797 			 * Note that SEQ_LEQ() is used.  This is to avoid
14798 			 * unnecessary fast retransmit caused by dup ACKs
14799 			 * received when TCP does slow start retransmission
14800 			 * after a time out.  During this phase, TCP may
14801 			 * send out segments which are already received.
14802 			 * This causes dup ACKs to be sent back.
14803 			 */
14804 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14805 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14806 					tcp->tcp_rexmit_nxt = seg_ack;
14807 				}
14808 				if (seg_ack != tcp->tcp_rexmit_max) {
14809 					flags |= TH_XMIT_NEEDED;
14810 				}
14811 			} else {
14812 				tcp->tcp_rexmit = B_FALSE;
14813 				tcp->tcp_xmit_zc_clean = B_FALSE;
14814 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14815 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14816 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14817 			}
14818 			tcp->tcp_ms_we_have_waited = 0;
14819 		}
14820 	}
14821 
14822 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14823 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14824 	tcp->tcp_suna = seg_ack;
14825 	if (tcp->tcp_zero_win_probe != 0) {
14826 		tcp->tcp_zero_win_probe = 0;
14827 		tcp->tcp_timer_backoff = 0;
14828 	}
14829 
14830 	/*
14831 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14832 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14833 	 * will not reach here.
14834 	 */
14835 	if (mp1 == NULL) {
14836 		goto fin_acked;
14837 	}
14838 
14839 	/*
14840 	 * Update the congestion window.
14841 	 *
14842 	 * If TCP is not ECN capable or TCP is ECN capable but the
14843 	 * congestion experience bit is not set, increase the tcp_cwnd as
14844 	 * usual.
14845 	 */
14846 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14847 		cwnd = tcp->tcp_cwnd;
14848 		add = mss;
14849 
14850 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14851 			/*
14852 			 * This is to prevent an increase of less than 1 MSS of
14853 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14854 			 * may send out tinygrams in order to preserve mblk
14855 			 * boundaries.
14856 			 *
14857 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14858 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14859 			 * increased by 1 MSS for every RTTs.
14860 			 */
14861 			if (tcp->tcp_cwnd_cnt <= 0) {
14862 				tcp->tcp_cwnd_cnt = cwnd + add;
14863 			} else {
14864 				tcp->tcp_cwnd_cnt -= add;
14865 				add = 0;
14866 			}
14867 		}
14868 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14869 	}
14870 
14871 	/* See if the latest urgent data has been acknowledged */
14872 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14873 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14874 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14875 
14876 	/* Can we update the RTT estimates? */
14877 	if (tcp->tcp_snd_ts_ok) {
14878 		/* Ignore zero timestamp echo-reply. */
14879 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14880 			tcp_set_rto(tcp, (int32_t)lbolt -
14881 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14882 		}
14883 
14884 		/* If needed, restart the timer. */
14885 		if (tcp->tcp_set_timer == 1) {
14886 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14887 			tcp->tcp_set_timer = 0;
14888 		}
14889 		/*
14890 		 * Update tcp_csuna in case the other side stops sending
14891 		 * us timestamps.
14892 		 */
14893 		tcp->tcp_csuna = tcp->tcp_snxt;
14894 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14895 		/*
14896 		 * An ACK sequence we haven't seen before, so get the RTT
14897 		 * and update the RTO. But first check if the timestamp is
14898 		 * valid to use.
14899 		 */
14900 		if ((mp1->b_next != NULL) &&
14901 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14902 			tcp_set_rto(tcp, (int32_t)lbolt -
14903 			    (int32_t)(intptr_t)mp1->b_prev);
14904 		else
14905 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14906 
14907 		/* Remeber the last sequence to be ACKed */
14908 		tcp->tcp_csuna = seg_ack;
14909 		if (tcp->tcp_set_timer == 1) {
14910 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14911 			tcp->tcp_set_timer = 0;
14912 		}
14913 	} else {
14914 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14915 	}
14916 
14917 	/* Eat acknowledged bytes off the xmit queue. */
14918 	for (;;) {
14919 		mblk_t	*mp2;
14920 		uchar_t	*wptr;
14921 
14922 		wptr = mp1->b_wptr;
14923 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14924 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14925 		if (bytes_acked < 0) {
14926 			mp1->b_rptr = wptr + bytes_acked;
14927 			/*
14928 			 * Set a new timestamp if all the bytes timed by the
14929 			 * old timestamp have been ack'ed.
14930 			 */
14931 			if (SEQ_GT(seg_ack,
14932 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14933 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14934 				mp1->b_next = NULL;
14935 			}
14936 			break;
14937 		}
14938 		mp1->b_next = NULL;
14939 		mp1->b_prev = NULL;
14940 		mp2 = mp1;
14941 		mp1 = mp1->b_cont;
14942 
14943 		/*
14944 		 * This notification is required for some zero-copy
14945 		 * clients to maintain a copy semantic. After the data
14946 		 * is ack'ed, client is safe to modify or reuse the buffer.
14947 		 */
14948 		if (tcp->tcp_snd_zcopy_aware &&
14949 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14950 			tcp_zcopy_notify(tcp);
14951 		freeb(mp2);
14952 		if (bytes_acked == 0) {
14953 			if (mp1 == NULL) {
14954 				/* Everything is ack'ed, clear the tail. */
14955 				tcp->tcp_xmit_tail = NULL;
14956 				/*
14957 				 * Cancel the timer unless we are still
14958 				 * waiting for an ACK for the FIN packet.
14959 				 */
14960 				if (tcp->tcp_timer_tid != 0 &&
14961 				    tcp->tcp_snxt == tcp->tcp_suna) {
14962 					(void) TCP_TIMER_CANCEL(tcp,
14963 					    tcp->tcp_timer_tid);
14964 					tcp->tcp_timer_tid = 0;
14965 				}
14966 				goto pre_swnd_update;
14967 			}
14968 			if (mp2 != tcp->tcp_xmit_tail)
14969 				break;
14970 			tcp->tcp_xmit_tail = mp1;
14971 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14972 			    (uintptr_t)INT_MAX);
14973 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14974 			    mp1->b_rptr);
14975 			break;
14976 		}
14977 		if (mp1 == NULL) {
14978 			/*
14979 			 * More was acked but there is nothing more
14980 			 * outstanding.  This means that the FIN was
14981 			 * just acked or that we're talking to a clown.
14982 			 */
14983 fin_acked:
14984 			ASSERT(tcp->tcp_fin_sent);
14985 			tcp->tcp_xmit_tail = NULL;
14986 			if (tcp->tcp_fin_sent) {
14987 				/* FIN was acked - making progress */
14988 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14989 				    !tcp->tcp_fin_acked)
14990 					tcp->tcp_ip_forward_progress = B_TRUE;
14991 				tcp->tcp_fin_acked = B_TRUE;
14992 				if (tcp->tcp_linger_tid != 0 &&
14993 				    TCP_TIMER_CANCEL(tcp,
14994 				    tcp->tcp_linger_tid) >= 0) {
14995 					tcp_stop_lingering(tcp);
14996 					freemsg(mp);
14997 					mp = NULL;
14998 				}
14999 			} else {
15000 				/*
15001 				 * We should never get here because
15002 				 * we have already checked that the
15003 				 * number of bytes ack'ed should be
15004 				 * smaller than or equal to what we
15005 				 * have sent so far (it is the
15006 				 * acceptability check of the ACK).
15007 				 * We can only get here if the send
15008 				 * queue is corrupted.
15009 				 *
15010 				 * Terminate the connection and
15011 				 * panic the system.  It is better
15012 				 * for us to panic instead of
15013 				 * continuing to avoid other disaster.
15014 				 */
15015 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
15016 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
15017 				panic("Memory corruption "
15018 				    "detected for connection %s.",
15019 				    tcp_display(tcp, NULL,
15020 				    DISP_ADDR_AND_PORT));
15021 				/*NOTREACHED*/
15022 			}
15023 			goto pre_swnd_update;
15024 		}
15025 		ASSERT(mp2 != tcp->tcp_xmit_tail);
15026 	}
15027 	if (tcp->tcp_unsent) {
15028 		flags |= TH_XMIT_NEEDED;
15029 	}
15030 pre_swnd_update:
15031 	tcp->tcp_xmit_head = mp1;
15032 swnd_update:
15033 	/*
15034 	 * The following check is different from most other implementations.
15035 	 * For bi-directional transfer, when segments are dropped, the
15036 	 * "normal" check will not accept a window update in those
15037 	 * retransmitted segemnts.  Failing to do that, TCP may send out
15038 	 * segments which are outside receiver's window.  As TCP accepts
15039 	 * the ack in those retransmitted segments, if the window update in
15040 	 * the same segment is not accepted, TCP will incorrectly calculates
15041 	 * that it can send more segments.  This can create a deadlock
15042 	 * with the receiver if its window becomes zero.
15043 	 */
15044 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
15045 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
15046 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
15047 		/*
15048 		 * The criteria for update is:
15049 		 *
15050 		 * 1. the segment acknowledges some data.  Or
15051 		 * 2. the segment is new, i.e. it has a higher seq num. Or
15052 		 * 3. the segment is not old and the advertised window is
15053 		 * larger than the previous advertised window.
15054 		 */
15055 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
15056 			flags |= TH_XMIT_NEEDED;
15057 		tcp->tcp_swnd = new_swnd;
15058 		if (new_swnd > tcp->tcp_max_swnd)
15059 			tcp->tcp_max_swnd = new_swnd;
15060 		tcp->tcp_swl1 = seg_seq;
15061 		tcp->tcp_swl2 = seg_ack;
15062 	}
15063 est:
15064 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
15065 
15066 		switch (tcp->tcp_state) {
15067 		case TCPS_FIN_WAIT_1:
15068 			if (tcp->tcp_fin_acked) {
15069 				tcp->tcp_state = TCPS_FIN_WAIT_2;
15070 				/*
15071 				 * We implement the non-standard BSD/SunOS
15072 				 * FIN_WAIT_2 flushing algorithm.
15073 				 * If there is no user attached to this
15074 				 * TCP endpoint, then this TCP struct
15075 				 * could hang around forever in FIN_WAIT_2
15076 				 * state if the peer forgets to send us
15077 				 * a FIN.  To prevent this, we wait only
15078 				 * 2*MSL (a convenient time value) for
15079 				 * the FIN to arrive.  If it doesn't show up,
15080 				 * we flush the TCP endpoint.  This algorithm,
15081 				 * though a violation of RFC-793, has worked
15082 				 * for over 10 years in BSD systems.
15083 				 * Note: SunOS 4.x waits 675 seconds before
15084 				 * flushing the FIN_WAIT_2 connection.
15085 				 */
15086 				TCP_TIMER_RESTART(tcp,
15087 				    tcps->tcps_fin_wait_2_flush_interval);
15088 			}
15089 			break;
15090 		case TCPS_FIN_WAIT_2:
15091 			break;	/* Shutdown hook? */
15092 		case TCPS_LAST_ACK:
15093 			freemsg(mp);
15094 			if (tcp->tcp_fin_acked) {
15095 				(void) tcp_clean_death(tcp, 0, 19);
15096 				return;
15097 			}
15098 			goto xmit_check;
15099 		case TCPS_CLOSING:
15100 			if (tcp->tcp_fin_acked) {
15101 				tcp->tcp_state = TCPS_TIME_WAIT;
15102 				/*
15103 				 * Unconditionally clear the exclusive binding
15104 				 * bit so this TIME-WAIT connection won't
15105 				 * interfere with new ones.
15106 				 */
15107 				tcp->tcp_exclbind = 0;
15108 				if (!TCP_IS_DETACHED(tcp)) {
15109 					TCP_TIMER_RESTART(tcp,
15110 					    tcps->tcps_time_wait_interval);
15111 				} else {
15112 					tcp_time_wait_append(tcp);
15113 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15114 				}
15115 			}
15116 			/*FALLTHRU*/
15117 		case TCPS_CLOSE_WAIT:
15118 			freemsg(mp);
15119 			goto xmit_check;
15120 		default:
15121 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
15122 			break;
15123 		}
15124 	}
15125 	if (flags & TH_FIN) {
15126 		/* Make sure we ack the fin */
15127 		flags |= TH_ACK_NEEDED;
15128 		if (!tcp->tcp_fin_rcvd) {
15129 			tcp->tcp_fin_rcvd = B_TRUE;
15130 			tcp->tcp_rnxt++;
15131 			tcph = tcp->tcp_tcph;
15132 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15133 
15134 			/*
15135 			 * Generate the ordrel_ind at the end unless we
15136 			 * are an eager guy.
15137 			 * In the eager case tcp_rsrv will do this when run
15138 			 * after tcp_accept is done.
15139 			 */
15140 			if (tcp->tcp_listener == NULL &&
15141 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
15142 				flags |= TH_ORDREL_NEEDED;
15143 			switch (tcp->tcp_state) {
15144 			case TCPS_SYN_RCVD:
15145 			case TCPS_ESTABLISHED:
15146 				tcp->tcp_state = TCPS_CLOSE_WAIT;
15147 				/* Keepalive? */
15148 				break;
15149 			case TCPS_FIN_WAIT_1:
15150 				if (!tcp->tcp_fin_acked) {
15151 					tcp->tcp_state = TCPS_CLOSING;
15152 					break;
15153 				}
15154 				/* FALLTHRU */
15155 			case TCPS_FIN_WAIT_2:
15156 				tcp->tcp_state = TCPS_TIME_WAIT;
15157 				/*
15158 				 * Unconditionally clear the exclusive binding
15159 				 * bit so this TIME-WAIT connection won't
15160 				 * interfere with new ones.
15161 				 */
15162 				tcp->tcp_exclbind = 0;
15163 				if (!TCP_IS_DETACHED(tcp)) {
15164 					TCP_TIMER_RESTART(tcp,
15165 					    tcps->tcps_time_wait_interval);
15166 				} else {
15167 					tcp_time_wait_append(tcp);
15168 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15169 				}
15170 				if (seg_len) {
15171 					/*
15172 					 * implies data piggybacked on FIN.
15173 					 * break to handle data.
15174 					 */
15175 					break;
15176 				}
15177 				freemsg(mp);
15178 				goto ack_check;
15179 			}
15180 		}
15181 	}
15182 	if (mp == NULL)
15183 		goto xmit_check;
15184 	if (seg_len == 0) {
15185 		freemsg(mp);
15186 		goto xmit_check;
15187 	}
15188 	if (mp->b_rptr == mp->b_wptr) {
15189 		/*
15190 		 * The header has been consumed, so we remove the
15191 		 * zero-length mblk here.
15192 		 */
15193 		mp1 = mp;
15194 		mp = mp->b_cont;
15195 		freeb(mp1);
15196 	}
15197 	tcph = tcp->tcp_tcph;
15198 	tcp->tcp_rack_cnt++;
15199 	{
15200 		uint32_t cur_max;
15201 
15202 		cur_max = tcp->tcp_rack_cur_max;
15203 		if (tcp->tcp_rack_cnt >= cur_max) {
15204 			/*
15205 			 * We have more unacked data than we should - send
15206 			 * an ACK now.
15207 			 */
15208 			flags |= TH_ACK_NEEDED;
15209 			cur_max++;
15210 			if (cur_max > tcp->tcp_rack_abs_max)
15211 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15212 			else
15213 				tcp->tcp_rack_cur_max = cur_max;
15214 		} else if (TCP_IS_DETACHED(tcp)) {
15215 			/* We don't have an ACK timer for detached TCP. */
15216 			flags |= TH_ACK_NEEDED;
15217 		} else if (seg_len < mss) {
15218 			/*
15219 			 * If we get a segment that is less than an mss, and we
15220 			 * already have unacknowledged data, and the amount
15221 			 * unacknowledged is not a multiple of mss, then we
15222 			 * better generate an ACK now.  Otherwise, this may be
15223 			 * the tail piece of a transaction, and we would rather
15224 			 * wait for the response.
15225 			 */
15226 			uint32_t udif;
15227 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15228 			    (uintptr_t)INT_MAX);
15229 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15230 			if (udif && (udif % mss))
15231 				flags |= TH_ACK_NEEDED;
15232 			else
15233 				flags |= TH_ACK_TIMER_NEEDED;
15234 		} else {
15235 			/* Start delayed ack timer */
15236 			flags |= TH_ACK_TIMER_NEEDED;
15237 		}
15238 	}
15239 	tcp->tcp_rnxt += seg_len;
15240 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15241 
15242 	/* Update SACK list */
15243 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15244 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15245 		    &(tcp->tcp_num_sack_blk));
15246 	}
15247 
15248 	if (tcp->tcp_urp_mp) {
15249 		tcp->tcp_urp_mp->b_cont = mp;
15250 		mp = tcp->tcp_urp_mp;
15251 		tcp->tcp_urp_mp = NULL;
15252 		/* Ready for a new signal. */
15253 		tcp->tcp_urp_last_valid = B_FALSE;
15254 #ifdef DEBUG
15255 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15256 		    "tcp_rput: sending exdata_ind %s",
15257 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15258 #endif /* DEBUG */
15259 	}
15260 
15261 	/*
15262 	 * Check for ancillary data changes compared to last segment.
15263 	 */
15264 	if (tcp->tcp_ipv6_recvancillary != 0) {
15265 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15266 		ASSERT(mp != NULL);
15267 	}
15268 
15269 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15270 		/*
15271 		 * Side queue inbound data until the accept happens.
15272 		 * tcp_accept/tcp_rput drains this when the accept happens.
15273 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15274 		 * T_EXDATA_IND) it is queued on b_next.
15275 		 * XXX Make urgent data use this. Requires:
15276 		 *	Removing tcp_listener check for TH_URG
15277 		 *	Making M_PCPROTO and MARK messages skip the eager case
15278 		 */
15279 
15280 		if (tcp->tcp_kssl_pending) {
15281 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15282 			    mblk_t *, mp);
15283 			tcp_kssl_input(tcp, mp);
15284 		} else {
15285 			tcp_rcv_enqueue(tcp, mp, seg_len);
15286 		}
15287 	} else {
15288 		sodirect_t	*sodp = tcp->tcp_sodirect;
15289 
15290 		/*
15291 		 * If an sodirect connection and an enabled sodirect_t then
15292 		 * sodp will be set to point to the tcp_t/sonode_t shared
15293 		 * sodirect_t and the sodirect_t's lock will be held.
15294 		 */
15295 		if (sodp != NULL) {
15296 			mutex_enter(sodp->sod_lockp);
15297 			if (!(sodp->sod_state & SOD_ENABLED) ||
15298 			    (tcp->tcp_kssl_ctx != NULL &&
15299 			    DB_TYPE(mp) == M_DATA)) {
15300 				mutex_exit(sodp->sod_lockp);
15301 				sodp = NULL;
15302 			}
15303 		}
15304 		if (mp->b_datap->db_type != M_DATA ||
15305 		    (flags & TH_MARKNEXT_NEEDED)) {
15306 			if (sodp != NULL) {
15307 				if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15308 					sodp->sod_uioa.uioa_state &= UIOA_CLR;
15309 					sodp->sod_uioa.uioa_state |= UIOA_FINI;
15310 				}
15311 				if (!SOD_QEMPTY(sodp) &&
15312 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15313 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15314 					/* sod_wakeup() did the mutex_exit() */
15315 				} else {
15316 					mutex_exit(sodp->sod_lockp);
15317 				}
15318 			} else if (tcp->tcp_rcv_list != NULL) {
15319 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15320 			}
15321 			ASSERT(tcp->tcp_rcv_list == NULL ||
15322 			    tcp->tcp_fused_sigurg);
15323 
15324 			if (flags & TH_MARKNEXT_NEEDED) {
15325 #ifdef DEBUG
15326 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15327 				    "tcp_rput: sending MSGMARKNEXT %s",
15328 				    tcp_display(tcp, NULL,
15329 				    DISP_PORT_ONLY));
15330 #endif /* DEBUG */
15331 				mp->b_flag |= MSGMARKNEXT;
15332 				flags &= ~TH_MARKNEXT_NEEDED;
15333 			}
15334 
15335 			/* Does this need SSL processing first? */
15336 			if ((tcp->tcp_kssl_ctx != NULL) &&
15337 			    (DB_TYPE(mp) == M_DATA)) {
15338 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15339 				    mblk_t *, mp);
15340 				tcp_kssl_input(tcp, mp);
15341 			} else {
15342 				putnext(tcp->tcp_rq, mp);
15343 				if (!canputnext(tcp->tcp_rq))
15344 					tcp->tcp_rwnd -= seg_len;
15345 			}
15346 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15347 		    (DB_TYPE(mp) == M_DATA)) {
15348 			/* Do SSL processing first */
15349 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2,
15350 			    mblk_t *, mp);
15351 			tcp_kssl_input(tcp, mp);
15352 		} else if (sodp != NULL) {
15353 			/*
15354 			 * Sodirect so all mblk_t's are queued on the
15355 			 * socket directly, check for wakeup of blocked
15356 			 * reader (if any), and last if flow-controled.
15357 			 */
15358 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15359 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15360 			    (flags & (TH_PUSH|TH_FIN))) {
15361 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15362 				/* sod_wakeup() did the mutex_exit() */
15363 			} else {
15364 				if (SOD_QFULL(sodp)) {
15365 					/* Q is full, need backenable */
15366 					SOD_QSETBE(sodp);
15367 				}
15368 				mutex_exit(sodp->sod_lockp);
15369 			}
15370 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15371 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
15372 			if (tcp->tcp_rcv_list != NULL) {
15373 				/*
15374 				 * Enqueue the new segment first and then
15375 				 * call tcp_rcv_drain() to send all data
15376 				 * up.  The other way to do this is to
15377 				 * send all queued data up and then call
15378 				 * putnext() to send the new segment up.
15379 				 * This way can remove the else part later
15380 				 * on.
15381 				 *
15382 				 * We don't this to avoid one more call to
15383 				 * canputnext() as tcp_rcv_drain() needs to
15384 				 * call canputnext().
15385 				 */
15386 				tcp_rcv_enqueue(tcp, mp, seg_len);
15387 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15388 			} else {
15389 				putnext(tcp->tcp_rq, mp);
15390 				if (!canputnext(tcp->tcp_rq))
15391 					tcp->tcp_rwnd -= seg_len;
15392 			}
15393 		} else {
15394 			/*
15395 			 * Enqueue all packets when processing an mblk
15396 			 * from the co queue and also enqueue normal packets.
15397 			 */
15398 			tcp_rcv_enqueue(tcp, mp, seg_len);
15399 		}
15400 		/*
15401 		 * Make sure the timer is running if we have data waiting
15402 		 * for a push bit. This provides resiliency against
15403 		 * implementations that do not correctly generate push bits.
15404 		 *
15405 		 * Note, for sodirect if Q isn't empty and there's not a
15406 		 * pending wakeup then we need a timer. Also note that sodp
15407 		 * is assumed to be still valid after exit()ing the sod_lockp
15408 		 * above and while the SOD state can change it can only change
15409 		 * such that the Q is empty now even though data was added
15410 		 * above.
15411 		 */
15412 		if (((sodp != NULL && !SOD_QEMPTY(sodp) &&
15413 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15414 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15415 		    tcp->tcp_push_tid == 0) {
15416 			/*
15417 			 * The connection may be closed at this point, so don't
15418 			 * do anything for a detached tcp.
15419 			 */
15420 			if (!TCP_IS_DETACHED(tcp))
15421 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15422 				    tcp_push_timer,
15423 				    MSEC_TO_TICK(
15424 				    tcps->tcps_push_timer_interval));
15425 		}
15426 	}
15427 
15428 xmit_check:
15429 	/* Is there anything left to do? */
15430 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15431 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15432 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15433 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15434 		goto done;
15435 
15436 	/* Any transmit work to do and a non-zero window? */
15437 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15438 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15439 		if (flags & TH_REXMIT_NEEDED) {
15440 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15441 
15442 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15443 			if (snd_size > mss)
15444 				snd_size = mss;
15445 			if (snd_size > tcp->tcp_swnd)
15446 				snd_size = tcp->tcp_swnd;
15447 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15448 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15449 			    B_TRUE);
15450 
15451 			if (mp1 != NULL) {
15452 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15453 				tcp->tcp_csuna = tcp->tcp_snxt;
15454 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15455 				UPDATE_MIB(&tcps->tcps_mib,
15456 				    tcpRetransBytes, snd_size);
15457 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15458 			}
15459 		}
15460 		if (flags & TH_NEED_SACK_REXMIT) {
15461 			tcp_sack_rxmit(tcp, &flags);
15462 		}
15463 		/*
15464 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15465 		 * out new segment.  Note that tcp_rexmit should not be
15466 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15467 		 */
15468 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15469 			if (!tcp->tcp_rexmit) {
15470 				tcp_wput_data(tcp, NULL, B_FALSE);
15471 			} else {
15472 				tcp_ss_rexmit(tcp);
15473 			}
15474 		}
15475 		/*
15476 		 * Adjust tcp_cwnd back to normal value after sending
15477 		 * new data segments.
15478 		 */
15479 		if (flags & TH_LIMIT_XMIT) {
15480 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15481 			/*
15482 			 * This will restart the timer.  Restarting the
15483 			 * timer is used to avoid a timeout before the
15484 			 * limited transmitted segment's ACK gets back.
15485 			 */
15486 			if (tcp->tcp_xmit_head != NULL)
15487 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15488 		}
15489 
15490 		/* Anything more to do? */
15491 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15492 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15493 			goto done;
15494 	}
15495 ack_check:
15496 	if (flags & TH_SEND_URP_MARK) {
15497 		ASSERT(tcp->tcp_urp_mark_mp);
15498 		/*
15499 		 * Send up any queued data and then send the mark message
15500 		 */
15501 		sodirect_t *sodp;
15502 
15503 		SOD_PTR_ENTER(tcp, sodp);
15504 
15505 		mp1 = tcp->tcp_urp_mark_mp;
15506 		tcp->tcp_urp_mark_mp = NULL;
15507 		if (sodp != NULL) {
15508 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15509 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15510 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15511 			}
15512 			ASSERT(tcp->tcp_rcv_list == NULL);
15513 
15514 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15515 			/* sod_wakeup() does the mutex_exit() */
15516 		} else if (tcp->tcp_rcv_list != NULL) {
15517 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15518 
15519 			ASSERT(tcp->tcp_rcv_list == NULL ||
15520 			    tcp->tcp_fused_sigurg);
15521 
15522 		}
15523 		putnext(tcp->tcp_rq, mp1);
15524 #ifdef DEBUG
15525 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15526 		    "tcp_rput: sending zero-length %s %s",
15527 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15528 		    "MSGNOTMARKNEXT"),
15529 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15530 #endif /* DEBUG */
15531 		flags &= ~TH_SEND_URP_MARK;
15532 	}
15533 	if (flags & TH_ACK_NEEDED) {
15534 		/*
15535 		 * Time to send an ack for some reason.
15536 		 */
15537 		mp1 = tcp_ack_mp(tcp);
15538 
15539 		if (mp1 != NULL) {
15540 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15541 			BUMP_LOCAL(tcp->tcp_obsegs);
15542 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15543 		}
15544 		if (tcp->tcp_ack_tid != 0) {
15545 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15546 			tcp->tcp_ack_tid = 0;
15547 		}
15548 	}
15549 	if (flags & TH_ACK_TIMER_NEEDED) {
15550 		/*
15551 		 * Arrange for deferred ACK or push wait timeout.
15552 		 * Start timer if it is not already running.
15553 		 */
15554 		if (tcp->tcp_ack_tid == 0) {
15555 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15556 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15557 			    (clock_t)tcps->tcps_local_dack_interval :
15558 			    (clock_t)tcps->tcps_deferred_ack_interval));
15559 		}
15560 	}
15561 	if (flags & TH_ORDREL_NEEDED) {
15562 		/*
15563 		 * Send up the ordrel_ind unless we are an eager guy.
15564 		 * In the eager case tcp_rsrv will do this when run
15565 		 * after tcp_accept is done.
15566 		 */
15567 		sodirect_t *sodp;
15568 
15569 		ASSERT(tcp->tcp_listener == NULL);
15570 
15571 		SOD_PTR_ENTER(tcp, sodp);
15572 		if (sodp != NULL) {
15573 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15574 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15575 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15576 			}
15577 			/* No more sodirect */
15578 			tcp->tcp_sodirect = NULL;
15579 			if (!SOD_QEMPTY(sodp)) {
15580 				/* Mblk(s) to process, notify */
15581 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15582 				/* sod_wakeup() does the mutex_exit() */
15583 			} else {
15584 				/* Nothing to process */
15585 				mutex_exit(sodp->sod_lockp);
15586 			}
15587 		} else if (tcp->tcp_rcv_list != NULL) {
15588 			/*
15589 			 * Push any mblk(s) enqueued from co processing.
15590 			 */
15591 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15592 
15593 			ASSERT(tcp->tcp_rcv_list == NULL ||
15594 			    tcp->tcp_fused_sigurg);
15595 		}
15596 
15597 		mp1 = tcp->tcp_ordrel_mp;
15598 		tcp->tcp_ordrel_mp = NULL;
15599 		tcp->tcp_ordrel_done = B_TRUE;
15600 		putnext(tcp->tcp_rq, mp1);
15601 	}
15602 done:
15603 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15604 }
15605 
15606 /*
15607  * This function does PAWS protection check. Returns B_TRUE if the
15608  * segment passes the PAWS test, else returns B_FALSE.
15609  */
15610 boolean_t
15611 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15612 {
15613 	uint8_t	flags;
15614 	int	options;
15615 	uint8_t *up;
15616 
15617 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15618 	/*
15619 	 * If timestamp option is aligned nicely, get values inline,
15620 	 * otherwise call general routine to parse.  Only do that
15621 	 * if timestamp is the only option.
15622 	 */
15623 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15624 	    TCPOPT_REAL_TS_LEN &&
15625 	    OK_32PTR((up = ((uint8_t *)tcph) +
15626 	    TCP_MIN_HEADER_LENGTH)) &&
15627 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15628 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15629 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15630 
15631 		options = TCP_OPT_TSTAMP_PRESENT;
15632 	} else {
15633 		if (tcp->tcp_snd_sack_ok) {
15634 			tcpoptp->tcp = tcp;
15635 		} else {
15636 			tcpoptp->tcp = NULL;
15637 		}
15638 		options = tcp_parse_options(tcph, tcpoptp);
15639 	}
15640 
15641 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15642 		/*
15643 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15644 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15645 		 */
15646 		if ((flags & TH_RST) == 0 &&
15647 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15648 		    tcp->tcp_ts_recent)) {
15649 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15650 			    PAWS_TIMEOUT)) {
15651 				/* This segment is not acceptable. */
15652 				return (B_FALSE);
15653 			} else {
15654 				/*
15655 				 * Connection has been idle for
15656 				 * too long.  Reset the timestamp
15657 				 * and assume the segment is valid.
15658 				 */
15659 				tcp->tcp_ts_recent =
15660 				    tcpoptp->tcp_opt_ts_val;
15661 			}
15662 		}
15663 	} else {
15664 		/*
15665 		 * If we don't get a timestamp on every packet, we
15666 		 * figure we can't really trust 'em, so we stop sending
15667 		 * and parsing them.
15668 		 */
15669 		tcp->tcp_snd_ts_ok = B_FALSE;
15670 
15671 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15672 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15673 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15674 		/*
15675 		 * Adjust the tcp_mss accordingly. We also need to
15676 		 * adjust tcp_cwnd here in accordance with the new mss.
15677 		 * But we avoid doing a slow start here so as to not
15678 		 * to lose on the transfer rate built up so far.
15679 		 */
15680 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15681 		if (tcp->tcp_snd_sack_ok) {
15682 			ASSERT(tcp->tcp_sack_info != NULL);
15683 			tcp->tcp_max_sack_blk = 4;
15684 		}
15685 	}
15686 	return (B_TRUE);
15687 }
15688 
15689 /*
15690  * Attach ancillary data to a received TCP segments for the
15691  * ancillary pieces requested by the application that are
15692  * different than they were in the previous data segment.
15693  *
15694  * Save the "current" values once memory allocation is ok so that
15695  * when memory allocation fails we can just wait for the next data segment.
15696  */
15697 static mblk_t *
15698 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15699 {
15700 	struct T_optdata_ind *todi;
15701 	int optlen;
15702 	uchar_t *optptr;
15703 	struct T_opthdr *toh;
15704 	uint_t addflag;	/* Which pieces to add */
15705 	mblk_t *mp1;
15706 
15707 	optlen = 0;
15708 	addflag = 0;
15709 	/* If app asked for pktinfo and the index has changed ... */
15710 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15711 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15712 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15713 		optlen += sizeof (struct T_opthdr) +
15714 		    sizeof (struct in6_pktinfo);
15715 		addflag |= TCP_IPV6_RECVPKTINFO;
15716 	}
15717 	/* If app asked for hoplimit and it has changed ... */
15718 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15719 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15720 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15721 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15722 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15723 	}
15724 	/* If app asked for tclass and it has changed ... */
15725 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15726 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15727 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15728 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15729 		addflag |= TCP_IPV6_RECVTCLASS;
15730 	}
15731 	/*
15732 	 * If app asked for hopbyhop headers and it has changed ...
15733 	 * For security labels, note that (1) security labels can't change on
15734 	 * a connected socket at all, (2) we're connected to at most one peer,
15735 	 * (3) if anything changes, then it must be some other extra option.
15736 	 */
15737 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15738 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15739 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15740 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15741 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15742 		    tcp->tcp_label_len;
15743 		addflag |= TCP_IPV6_RECVHOPOPTS;
15744 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15745 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15746 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15747 			return (mp);
15748 	}
15749 	/* If app asked for dst headers before routing headers ... */
15750 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15751 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15752 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15753 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15754 		optlen += sizeof (struct T_opthdr) +
15755 		    ipp->ipp_rtdstoptslen;
15756 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15757 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15758 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15759 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15760 			return (mp);
15761 	}
15762 	/* If app asked for routing headers and it has changed ... */
15763 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15764 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15765 	    (ipp->ipp_fields & IPPF_RTHDR),
15766 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15767 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15768 		addflag |= TCP_IPV6_RECVRTHDR;
15769 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15770 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15771 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15772 			return (mp);
15773 	}
15774 	/* If app asked for dest headers and it has changed ... */
15775 	if ((tcp->tcp_ipv6_recvancillary &
15776 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15777 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15778 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15779 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15780 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15781 		addflag |= TCP_IPV6_RECVDSTOPTS;
15782 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15783 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15784 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15785 			return (mp);
15786 	}
15787 
15788 	if (optlen == 0) {
15789 		/* Nothing to add */
15790 		return (mp);
15791 	}
15792 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15793 	if (mp1 == NULL) {
15794 		/*
15795 		 * Defer sending ancillary data until the next TCP segment
15796 		 * arrives.
15797 		 */
15798 		return (mp);
15799 	}
15800 	mp1->b_cont = mp;
15801 	mp = mp1;
15802 	mp->b_wptr += sizeof (*todi) + optlen;
15803 	mp->b_datap->db_type = M_PROTO;
15804 	todi = (struct T_optdata_ind *)mp->b_rptr;
15805 	todi->PRIM_type = T_OPTDATA_IND;
15806 	todi->DATA_flag = 1;	/* MORE data */
15807 	todi->OPT_length = optlen;
15808 	todi->OPT_offset = sizeof (*todi);
15809 	optptr = (uchar_t *)&todi[1];
15810 	/*
15811 	 * If app asked for pktinfo and the index has changed ...
15812 	 * Note that the local address never changes for the connection.
15813 	 */
15814 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15815 		struct in6_pktinfo *pkti;
15816 
15817 		toh = (struct T_opthdr *)optptr;
15818 		toh->level = IPPROTO_IPV6;
15819 		toh->name = IPV6_PKTINFO;
15820 		toh->len = sizeof (*toh) + sizeof (*pkti);
15821 		toh->status = 0;
15822 		optptr += sizeof (*toh);
15823 		pkti = (struct in6_pktinfo *)optptr;
15824 		if (tcp->tcp_ipversion == IPV6_VERSION)
15825 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15826 		else
15827 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15828 			    &pkti->ipi6_addr);
15829 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15830 		optptr += sizeof (*pkti);
15831 		ASSERT(OK_32PTR(optptr));
15832 		/* Save as "last" value */
15833 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15834 	}
15835 	/* If app asked for hoplimit and it has changed ... */
15836 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15837 		toh = (struct T_opthdr *)optptr;
15838 		toh->level = IPPROTO_IPV6;
15839 		toh->name = IPV6_HOPLIMIT;
15840 		toh->len = sizeof (*toh) + sizeof (uint_t);
15841 		toh->status = 0;
15842 		optptr += sizeof (*toh);
15843 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15844 		optptr += sizeof (uint_t);
15845 		ASSERT(OK_32PTR(optptr));
15846 		/* Save as "last" value */
15847 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15848 	}
15849 	/* If app asked for tclass and it has changed ... */
15850 	if (addflag & TCP_IPV6_RECVTCLASS) {
15851 		toh = (struct T_opthdr *)optptr;
15852 		toh->level = IPPROTO_IPV6;
15853 		toh->name = IPV6_TCLASS;
15854 		toh->len = sizeof (*toh) + sizeof (uint_t);
15855 		toh->status = 0;
15856 		optptr += sizeof (*toh);
15857 		*(uint_t *)optptr = ipp->ipp_tclass;
15858 		optptr += sizeof (uint_t);
15859 		ASSERT(OK_32PTR(optptr));
15860 		/* Save as "last" value */
15861 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15862 	}
15863 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15864 		toh = (struct T_opthdr *)optptr;
15865 		toh->level = IPPROTO_IPV6;
15866 		toh->name = IPV6_HOPOPTS;
15867 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15868 		    tcp->tcp_label_len;
15869 		toh->status = 0;
15870 		optptr += sizeof (*toh);
15871 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15872 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15873 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15874 		ASSERT(OK_32PTR(optptr));
15875 		/* Save as last value */
15876 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15877 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15878 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15879 	}
15880 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15881 		toh = (struct T_opthdr *)optptr;
15882 		toh->level = IPPROTO_IPV6;
15883 		toh->name = IPV6_RTHDRDSTOPTS;
15884 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15885 		toh->status = 0;
15886 		optptr += sizeof (*toh);
15887 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15888 		optptr += ipp->ipp_rtdstoptslen;
15889 		ASSERT(OK_32PTR(optptr));
15890 		/* Save as last value */
15891 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15892 		    &tcp->tcp_rtdstoptslen,
15893 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15894 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15895 	}
15896 	if (addflag & TCP_IPV6_RECVRTHDR) {
15897 		toh = (struct T_opthdr *)optptr;
15898 		toh->level = IPPROTO_IPV6;
15899 		toh->name = IPV6_RTHDR;
15900 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15901 		toh->status = 0;
15902 		optptr += sizeof (*toh);
15903 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15904 		optptr += ipp->ipp_rthdrlen;
15905 		ASSERT(OK_32PTR(optptr));
15906 		/* Save as last value */
15907 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15908 		    (ipp->ipp_fields & IPPF_RTHDR),
15909 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15910 	}
15911 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15912 		toh = (struct T_opthdr *)optptr;
15913 		toh->level = IPPROTO_IPV6;
15914 		toh->name = IPV6_DSTOPTS;
15915 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15916 		toh->status = 0;
15917 		optptr += sizeof (*toh);
15918 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15919 		optptr += ipp->ipp_dstoptslen;
15920 		ASSERT(OK_32PTR(optptr));
15921 		/* Save as last value */
15922 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15923 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15924 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15925 	}
15926 	ASSERT(optptr == mp->b_wptr);
15927 	return (mp);
15928 }
15929 
15930 /*
15931  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15932  * or a "bad" IRE detected by tcp_adapt_ire.
15933  * We can't tell if the failure was due to the laddr or the faddr
15934  * thus we clear out all addresses and ports.
15935  */
15936 static void
15937 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15938 {
15939 	queue_t	*q = tcp->tcp_rq;
15940 	tcph_t	*tcph;
15941 	struct T_error_ack *tea;
15942 	conn_t	*connp = tcp->tcp_connp;
15943 
15944 
15945 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15946 
15947 	if (mp->b_cont) {
15948 		freemsg(mp->b_cont);
15949 		mp->b_cont = NULL;
15950 	}
15951 	tea = (struct T_error_ack *)mp->b_rptr;
15952 	switch (tea->PRIM_type) {
15953 	case T_BIND_ACK:
15954 		/*
15955 		 * Need to unbind with classifier since we were just told that
15956 		 * our bind succeeded.
15957 		 */
15958 		tcp->tcp_hard_bound = B_FALSE;
15959 		tcp->tcp_hard_binding = B_FALSE;
15960 
15961 		ipcl_hash_remove(connp);
15962 		/* Reuse the mblk if possible */
15963 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15964 		    sizeof (*tea));
15965 		mp->b_rptr = mp->b_datap->db_base;
15966 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15967 		tea = (struct T_error_ack *)mp->b_rptr;
15968 		tea->PRIM_type = T_ERROR_ACK;
15969 		tea->TLI_error = TSYSERR;
15970 		tea->UNIX_error = error;
15971 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15972 			tea->ERROR_prim = T_CONN_REQ;
15973 		} else {
15974 			tea->ERROR_prim = O_T_BIND_REQ;
15975 		}
15976 		break;
15977 
15978 	case T_ERROR_ACK:
15979 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15980 			tea->ERROR_prim = T_CONN_REQ;
15981 		break;
15982 	default:
15983 		panic("tcp_bind_failed: unexpected TPI type");
15984 		/*NOTREACHED*/
15985 	}
15986 
15987 	tcp->tcp_state = TCPS_IDLE;
15988 	if (tcp->tcp_ipversion == IPV4_VERSION)
15989 		tcp->tcp_ipha->ipha_src = 0;
15990 	else
15991 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15992 	/*
15993 	 * Copy of the src addr. in tcp_t is needed since
15994 	 * the lookup funcs. can only look at tcp_t
15995 	 */
15996 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15997 
15998 	tcph = tcp->tcp_tcph;
15999 	tcph->th_lport[0] = 0;
16000 	tcph->th_lport[1] = 0;
16001 	tcp_bind_hash_remove(tcp);
16002 	bzero(&connp->u_port, sizeof (connp->u_port));
16003 	/* blow away saved option results if any */
16004 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
16005 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
16006 
16007 	conn_delete_ire(tcp->tcp_connp, NULL);
16008 	putnext(q, mp);
16009 }
16010 
16011 /*
16012  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
16013  * messages.
16014  */
16015 void
16016 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
16017 {
16018 	mblk_t	*mp1;
16019 	uchar_t	*rptr = mp->b_rptr;
16020 	queue_t	*q = tcp->tcp_rq;
16021 	struct T_error_ack *tea;
16022 	uint32_t mss;
16023 	mblk_t *syn_mp;
16024 	mblk_t *mdti;
16025 	mblk_t *lsoi;
16026 	int	retval;
16027 	mblk_t *ire_mp;
16028 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16029 
16030 	switch (mp->b_datap->db_type) {
16031 	case M_PROTO:
16032 	case M_PCPROTO:
16033 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
16034 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
16035 			break;
16036 		tea = (struct T_error_ack *)rptr;
16037 		switch (tea->PRIM_type) {
16038 		case T_BIND_ACK:
16039 			/*
16040 			 * Adapt Multidata information, if any.  The
16041 			 * following tcp_mdt_update routine will free
16042 			 * the message.
16043 			 */
16044 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
16045 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
16046 				    b_rptr)->mdt_capab, B_TRUE);
16047 				freemsg(mdti);
16048 			}
16049 
16050 			/*
16051 			 * Check to update LSO information with tcp, and
16052 			 * tcp_lso_update routine will free the message.
16053 			 */
16054 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
16055 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
16056 				    b_rptr)->lso_capab);
16057 				freemsg(lsoi);
16058 			}
16059 
16060 			/* Get the IRE, if we had requested for it */
16061 			ire_mp = tcp_ire_mp(mp);
16062 
16063 			if (tcp->tcp_hard_binding) {
16064 				tcp->tcp_hard_binding = B_FALSE;
16065 				tcp->tcp_hard_bound = B_TRUE;
16066 				CL_INET_CONNECT(tcp);
16067 			} else {
16068 				if (ire_mp != NULL)
16069 					freeb(ire_mp);
16070 				goto after_syn_sent;
16071 			}
16072 
16073 			retval = tcp_adapt_ire(tcp, ire_mp);
16074 			if (ire_mp != NULL)
16075 				freeb(ire_mp);
16076 			if (retval == 0) {
16077 				tcp_bind_failed(tcp, mp,
16078 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
16079 				    ENETUNREACH : EADDRNOTAVAIL));
16080 				return;
16081 			}
16082 			/*
16083 			 * Don't let an endpoint connect to itself.
16084 			 * Also checked in tcp_connect() but that
16085 			 * check can't handle the case when the
16086 			 * local IP address is INADDR_ANY.
16087 			 */
16088 			if (tcp->tcp_ipversion == IPV4_VERSION) {
16089 				if ((tcp->tcp_ipha->ipha_dst ==
16090 				    tcp->tcp_ipha->ipha_src) &&
16091 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16092 				    tcp->tcp_tcph->th_fport))) {
16093 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16094 					return;
16095 				}
16096 			} else {
16097 				if (IN6_ARE_ADDR_EQUAL(
16098 				    &tcp->tcp_ip6h->ip6_dst,
16099 				    &tcp->tcp_ip6h->ip6_src) &&
16100 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16101 				    tcp->tcp_tcph->th_fport))) {
16102 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16103 					return;
16104 				}
16105 			}
16106 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
16107 			/*
16108 			 * This should not be possible!  Just for
16109 			 * defensive coding...
16110 			 */
16111 			if (tcp->tcp_state != TCPS_SYN_SENT)
16112 				goto after_syn_sent;
16113 
16114 			if (is_system_labeled() &&
16115 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
16116 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
16117 				return;
16118 			}
16119 
16120 			ASSERT(q == tcp->tcp_rq);
16121 			/*
16122 			 * tcp_adapt_ire() does not adjust
16123 			 * for TCP/IP header length.
16124 			 */
16125 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
16126 
16127 			/*
16128 			 * Just make sure our rwnd is at
16129 			 * least tcp_recv_hiwat_mss * MSS
16130 			 * large, and round up to the nearest
16131 			 * MSS.
16132 			 *
16133 			 * We do the round up here because
16134 			 * we need to get the interface
16135 			 * MTU first before we can do the
16136 			 * round up.
16137 			 */
16138 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
16139 			    tcps->tcps_recv_hiwat_minmss * mss);
16140 			q->q_hiwat = tcp->tcp_rwnd;
16141 			tcp_set_ws_value(tcp);
16142 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
16143 			    tcp->tcp_tcph->th_win);
16144 			if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
16145 				tcp->tcp_snd_ws_ok = B_TRUE;
16146 
16147 			/*
16148 			 * Set tcp_snd_ts_ok to true
16149 			 * so that tcp_xmit_mp will
16150 			 * include the timestamp
16151 			 * option in the SYN segment.
16152 			 */
16153 			if (tcps->tcps_tstamp_always ||
16154 			    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
16155 				tcp->tcp_snd_ts_ok = B_TRUE;
16156 			}
16157 
16158 			/*
16159 			 * tcp_snd_sack_ok can be set in
16160 			 * tcp_adapt_ire() if the sack metric
16161 			 * is set.  So check it here also.
16162 			 */
16163 			if (tcps->tcps_sack_permitted == 2 ||
16164 			    tcp->tcp_snd_sack_ok) {
16165 				if (tcp->tcp_sack_info == NULL) {
16166 					tcp->tcp_sack_info =
16167 					    kmem_cache_alloc(
16168 					    tcp_sack_info_cache,
16169 					    KM_SLEEP);
16170 				}
16171 				tcp->tcp_snd_sack_ok = B_TRUE;
16172 			}
16173 
16174 			/*
16175 			 * Should we use ECN?  Note that the current
16176 			 * default value (SunOS 5.9) of tcp_ecn_permitted
16177 			 * is 1.  The reason for doing this is that there
16178 			 * are equipments out there that will drop ECN
16179 			 * enabled IP packets.  Setting it to 1 avoids
16180 			 * compatibility problems.
16181 			 */
16182 			if (tcps->tcps_ecn_permitted == 2)
16183 				tcp->tcp_ecn_ok = B_TRUE;
16184 
16185 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16186 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
16187 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
16188 			if (syn_mp) {
16189 				cred_t *cr;
16190 				pid_t pid;
16191 
16192 				/*
16193 				 * Obtain the credential from the
16194 				 * thread calling connect(); the credential
16195 				 * lives on in the second mblk which
16196 				 * originated from T_CONN_REQ and is echoed
16197 				 * with the T_BIND_ACK from ip.  If none
16198 				 * can be found, default to the creator
16199 				 * of the socket.
16200 				 */
16201 				if (mp->b_cont == NULL ||
16202 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
16203 					cr = tcp->tcp_cred;
16204 					pid = tcp->tcp_cpid;
16205 				} else {
16206 					pid = DB_CPID(mp->b_cont);
16207 				}
16208 				mblk_setcred(syn_mp, cr);
16209 				DB_CPID(syn_mp) = pid;
16210 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
16211 			}
16212 		after_syn_sent:
16213 			/*
16214 			 * A trailer mblk indicates a waiting client upstream.
16215 			 * We complete here the processing begun in
16216 			 * either tcp_bind() or tcp_connect() by passing
16217 			 * upstream the reply message they supplied.
16218 			 */
16219 			mp1 = mp;
16220 			mp = mp->b_cont;
16221 			freeb(mp1);
16222 			if (mp)
16223 				break;
16224 			return;
16225 		case T_ERROR_ACK:
16226 			if (tcp->tcp_debug) {
16227 				(void) strlog(TCP_MOD_ID, 0, 1,
16228 				    SL_TRACE|SL_ERROR,
16229 				    "tcp_rput_other: case T_ERROR_ACK, "
16230 				    "ERROR_prim == %d",
16231 				    tea->ERROR_prim);
16232 			}
16233 			switch (tea->ERROR_prim) {
16234 			case O_T_BIND_REQ:
16235 			case T_BIND_REQ:
16236 				tcp_bind_failed(tcp, mp,
16237 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
16238 				    ENETUNREACH : EADDRNOTAVAIL));
16239 				return;
16240 			case T_UNBIND_REQ:
16241 				tcp->tcp_hard_binding = B_FALSE;
16242 				tcp->tcp_hard_bound = B_FALSE;
16243 				if (mp->b_cont) {
16244 					freemsg(mp->b_cont);
16245 					mp->b_cont = NULL;
16246 				}
16247 				if (tcp->tcp_unbind_pending)
16248 					tcp->tcp_unbind_pending = 0;
16249 				else {
16250 					/* From tcp_ip_unbind() - free */
16251 					freemsg(mp);
16252 					return;
16253 				}
16254 				break;
16255 			case T_SVR4_OPTMGMT_REQ:
16256 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
16257 					/* T_OPTMGMT_REQ generated by TCP */
16258 					printf("T_SVR4_OPTMGMT_REQ failed "
16259 					    "%d/%d - dropped (cnt %d)\n",
16260 					    tea->TLI_error, tea->UNIX_error,
16261 					    tcp->tcp_drop_opt_ack_cnt);
16262 					freemsg(mp);
16263 					tcp->tcp_drop_opt_ack_cnt--;
16264 					return;
16265 				}
16266 				break;
16267 			}
16268 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
16269 			    tcp->tcp_drop_opt_ack_cnt > 0) {
16270 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
16271 				    "- dropped (cnt %d)\n",
16272 				    tea->TLI_error, tea->UNIX_error,
16273 				    tcp->tcp_drop_opt_ack_cnt);
16274 				freemsg(mp);
16275 				tcp->tcp_drop_opt_ack_cnt--;
16276 				return;
16277 			}
16278 			break;
16279 		case T_OPTMGMT_ACK:
16280 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
16281 				/* T_OPTMGMT_REQ generated by TCP */
16282 				freemsg(mp);
16283 				tcp->tcp_drop_opt_ack_cnt--;
16284 				return;
16285 			}
16286 			break;
16287 		default:
16288 			break;
16289 		}
16290 		break;
16291 	case M_FLUSH:
16292 		if (*rptr & FLUSHR)
16293 			flushq(q, FLUSHDATA);
16294 		break;
16295 	default:
16296 		/* M_CTL will be directly sent to tcp_icmp_error() */
16297 		ASSERT(DB_TYPE(mp) != M_CTL);
16298 		break;
16299 	}
16300 	/*
16301 	 * Make sure we set this bit before sending the ACK for
16302 	 * bind. Otherwise accept could possibly run and free
16303 	 * this tcp struct.
16304 	 */
16305 	putnext(q, mp);
16306 }
16307 
16308 /* ARGSUSED */
16309 static void
16310 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
16311 {
16312 	conn_t	*connp = (conn_t *)arg;
16313 	tcp_t	*tcp = connp->conn_tcp;
16314 	queue_t	*q = tcp->tcp_rq;
16315 	uint_t	thwin;
16316 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16317 	sodirect_t	*sodp;
16318 	boolean_t	fc;
16319 
16320 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
16321 	tcp->tcp_rsrv_mp = mp;
16322 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
16323 
16324 	TCP_STAT(tcps, tcp_rsrv_calls);
16325 
16326 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
16327 		return;
16328 	}
16329 
16330 	if (tcp->tcp_fused) {
16331 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16332 
16333 		ASSERT(tcp->tcp_fused);
16334 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
16335 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
16336 		ASSERT(!TCP_IS_DETACHED(tcp));
16337 		ASSERT(tcp->tcp_connp->conn_sqp ==
16338 		    peer_tcp->tcp_connp->conn_sqp);
16339 
16340 		/*
16341 		 * Normally we would not get backenabled in synchronous
16342 		 * streams mode, but in case this happens, we need to plug
16343 		 * synchronous streams during our drain to prevent a race
16344 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
16345 		 */
16346 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
16347 		if (tcp->tcp_rcv_list != NULL)
16348 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
16349 
16350 		if (peer_tcp > tcp) {
16351 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16352 			mutex_enter(&tcp->tcp_non_sq_lock);
16353 		} else {
16354 			mutex_enter(&tcp->tcp_non_sq_lock);
16355 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16356 		}
16357 
16358 		if (peer_tcp->tcp_flow_stopped &&
16359 		    (TCP_UNSENT_BYTES(peer_tcp) <=
16360 		    peer_tcp->tcp_xmit_lowater)) {
16361 			tcp_clrqfull(peer_tcp);
16362 		}
16363 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
16364 		mutex_exit(&tcp->tcp_non_sq_lock);
16365 
16366 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
16367 		TCP_STAT(tcps, tcp_fusion_backenabled);
16368 		return;
16369 	}
16370 
16371 	SOD_PTR_ENTER(tcp, sodp);
16372 	if (sodp != NULL) {
16373 		/* An sodirect connection */
16374 		if (SOD_QFULL(sodp)) {
16375 			/* Flow-controlled, need another back-enable */
16376 			fc = B_TRUE;
16377 			SOD_QSETBE(sodp);
16378 		} else {
16379 			/* Not flow-controlled */
16380 			fc = B_FALSE;
16381 		}
16382 		mutex_exit(sodp->sod_lockp);
16383 	} else if (canputnext(q)) {
16384 		/* STREAMS, not flow-controlled */
16385 		fc = B_FALSE;
16386 	} else {
16387 		/* STREAMS, flow-controlled */
16388 		fc = B_TRUE;
16389 	}
16390 	if (!fc) {
16391 		/* Not flow-controlled, open rwnd */
16392 		tcp->tcp_rwnd = q->q_hiwat;
16393 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16394 		    << tcp->tcp_rcv_ws;
16395 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16396 		/*
16397 		 * Send back a window update immediately if TCP is above
16398 		 * ESTABLISHED state and the increase of the rcv window
16399 		 * that the other side knows is at least 1 MSS after flow
16400 		 * control is lifted.
16401 		 */
16402 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16403 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16404 			tcp_xmit_ctl(NULL, tcp,
16405 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16406 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16407 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
16408 		}
16409 	}
16410 }
16411 
16412 /*
16413  * The read side service routine is called mostly when we get back-enabled as a
16414  * result of flow control relief.  Since we don't actually queue anything in
16415  * TCP, we have no data to send out of here.  What we do is clear the receive
16416  * window, and send out a window update.
16417  */
16418 static void
16419 tcp_rsrv(queue_t *q)
16420 {
16421 	conn_t		*connp = Q_TO_CONN(q);
16422 	tcp_t		*tcp = connp->conn_tcp;
16423 	mblk_t		*mp;
16424 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16425 
16426 	/* No code does a putq on the read side */
16427 	ASSERT(q->q_first == NULL);
16428 
16429 	/* Nothing to do for the default queue */
16430 	if (q == tcps->tcps_g_q) {
16431 		return;
16432 	}
16433 
16434 	/*
16435 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
16436 	 * been run.  So just return.
16437 	 */
16438 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
16439 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
16440 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
16441 		return;
16442 	}
16443 	tcp->tcp_rsrv_mp = NULL;
16444 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
16445 
16446 	CONN_INC_REF(connp);
16447 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16448 	    SQ_PROCESS, SQTAG_TCP_RSRV);
16449 }
16450 
16451 /*
16452  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16453  * We do not allow the receive window to shrink.  After setting rwnd,
16454  * set the flow control hiwat of the stream.
16455  *
16456  * This function is called in 2 cases:
16457  *
16458  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16459  *    connection (passive open) and in tcp_rput_data() for active connect.
16460  *    This is called after tcp_mss_set() when the desired MSS value is known.
16461  *    This makes sure that our window size is a mutiple of the other side's
16462  *    MSS.
16463  * 2) Handling SO_RCVBUF option.
16464  *
16465  * It is ASSUMED that the requested size is a multiple of the current MSS.
16466  *
16467  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16468  * user requests so.
16469  */
16470 static int
16471 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16472 {
16473 	uint32_t	mss = tcp->tcp_mss;
16474 	uint32_t	old_max_rwnd;
16475 	uint32_t	max_transmittable_rwnd;
16476 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16477 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16478 
16479 	if (tcp->tcp_fused) {
16480 		size_t sth_hiwat;
16481 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16482 
16483 		ASSERT(peer_tcp != NULL);
16484 		/*
16485 		 * Record the stream head's high water mark for
16486 		 * this endpoint; this is used for flow-control
16487 		 * purposes in tcp_fuse_output().
16488 		 */
16489 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16490 		if (!tcp_detached)
16491 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
16492 
16493 		/*
16494 		 * In the fusion case, the maxpsz stream head value of
16495 		 * our peer is set according to its send buffer size
16496 		 * and our receive buffer size; since the latter may
16497 		 * have changed we need to update the peer's maxpsz.
16498 		 */
16499 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16500 		return (rwnd);
16501 	}
16502 
16503 	if (tcp_detached)
16504 		old_max_rwnd = tcp->tcp_rwnd;
16505 	else
16506 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16507 
16508 	/*
16509 	 * Insist on a receive window that is at least
16510 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16511 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16512 	 * and delayed acknowledgement.
16513 	 */
16514 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16515 
16516 	/*
16517 	 * If window size info has already been exchanged, TCP should not
16518 	 * shrink the window.  Shrinking window is doable if done carefully.
16519 	 * We may add that support later.  But so far there is not a real
16520 	 * need to do that.
16521 	 */
16522 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16523 		/* MSS may have changed, do a round up again. */
16524 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16525 	}
16526 
16527 	/*
16528 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16529 	 * can be applied even before the window scale option is decided.
16530 	 */
16531 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16532 	if (rwnd > max_transmittable_rwnd) {
16533 		rwnd = max_transmittable_rwnd -
16534 		    (max_transmittable_rwnd % mss);
16535 		if (rwnd < mss)
16536 			rwnd = max_transmittable_rwnd;
16537 		/*
16538 		 * If we're over the limit we may have to back down tcp_rwnd.
16539 		 * The increment below won't work for us. So we set all three
16540 		 * here and the increment below will have no effect.
16541 		 */
16542 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16543 	}
16544 	if (tcp->tcp_localnet) {
16545 		tcp->tcp_rack_abs_max =
16546 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16547 	} else {
16548 		/*
16549 		 * For a remote host on a different subnet (through a router),
16550 		 * we ack every other packet to be conforming to RFC1122.
16551 		 * tcp_deferred_acks_max is default to 2.
16552 		 */
16553 		tcp->tcp_rack_abs_max =
16554 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16555 	}
16556 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16557 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16558 	else
16559 		tcp->tcp_rack_cur_max = 0;
16560 	/*
16561 	 * Increment the current rwnd by the amount the maximum grew (we
16562 	 * can not overwrite it since we might be in the middle of a
16563 	 * connection.)
16564 	 */
16565 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16566 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16567 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16568 		tcp->tcp_cwnd_max = rwnd;
16569 
16570 	if (tcp_detached)
16571 		return (rwnd);
16572 	/*
16573 	 * We set the maximum receive window into rq->q_hiwat.
16574 	 * This is not actually used for flow control.
16575 	 */
16576 	tcp->tcp_rq->q_hiwat = rwnd;
16577 	/*
16578 	 * Set the Stream head high water mark. This doesn't have to be
16579 	 * here, since we are simply using default values, but we would
16580 	 * prefer to choose these values algorithmically, with a likely
16581 	 * relationship to rwnd.
16582 	 */
16583 	(void) mi_set_sth_hiwat(tcp->tcp_rq,
16584 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16585 	return (rwnd);
16586 }
16587 
16588 /*
16589  * Return SNMP stuff in buffer in mpdata.
16590  */
16591 mblk_t *
16592 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16593 {
16594 	mblk_t			*mpdata;
16595 	mblk_t			*mp_conn_ctl = NULL;
16596 	mblk_t			*mp_conn_tail;
16597 	mblk_t			*mp_attr_ctl = NULL;
16598 	mblk_t			*mp_attr_tail;
16599 	mblk_t			*mp6_conn_ctl = NULL;
16600 	mblk_t			*mp6_conn_tail;
16601 	mblk_t			*mp6_attr_ctl = NULL;
16602 	mblk_t			*mp6_attr_tail;
16603 	struct opthdr		*optp;
16604 	mib2_tcpConnEntry_t	tce;
16605 	mib2_tcp6ConnEntry_t	tce6;
16606 	mib2_transportMLPEntry_t mlp;
16607 	connf_t			*connfp;
16608 	int			i;
16609 	boolean_t 		ispriv;
16610 	zoneid_t 		zoneid;
16611 	int			v4_conn_idx;
16612 	int			v6_conn_idx;
16613 	conn_t			*connp = Q_TO_CONN(q);
16614 	tcp_stack_t		*tcps;
16615 	ip_stack_t		*ipst;
16616 	mblk_t			*mp2ctl;
16617 
16618 	/*
16619 	 * make a copy of the original message
16620 	 */
16621 	mp2ctl = copymsg(mpctl);
16622 
16623 	if (mpctl == NULL ||
16624 	    (mpdata = mpctl->b_cont) == NULL ||
16625 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16626 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16627 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16628 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16629 		freemsg(mp_conn_ctl);
16630 		freemsg(mp_attr_ctl);
16631 		freemsg(mp6_conn_ctl);
16632 		freemsg(mp6_attr_ctl);
16633 		freemsg(mpctl);
16634 		freemsg(mp2ctl);
16635 		return (NULL);
16636 	}
16637 
16638 	ipst = connp->conn_netstack->netstack_ip;
16639 	tcps = connp->conn_netstack->netstack_tcp;
16640 
16641 	/* build table of connections -- need count in fixed part */
16642 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16643 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16644 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16645 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16646 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16647 
16648 	ispriv =
16649 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16650 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16651 
16652 	v4_conn_idx = v6_conn_idx = 0;
16653 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16654 
16655 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16656 		ipst = tcps->tcps_netstack->netstack_ip;
16657 
16658 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16659 
16660 		connp = NULL;
16661 
16662 		while ((connp =
16663 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16664 			tcp_t *tcp;
16665 			boolean_t needattr;
16666 
16667 			if (connp->conn_zoneid != zoneid)
16668 				continue;	/* not in this zone */
16669 
16670 			tcp = connp->conn_tcp;
16671 			UPDATE_MIB(&tcps->tcps_mib,
16672 			    tcpHCInSegs, tcp->tcp_ibsegs);
16673 			tcp->tcp_ibsegs = 0;
16674 			UPDATE_MIB(&tcps->tcps_mib,
16675 			    tcpHCOutSegs, tcp->tcp_obsegs);
16676 			tcp->tcp_obsegs = 0;
16677 
16678 			tce6.tcp6ConnState = tce.tcpConnState =
16679 			    tcp_snmp_state(tcp);
16680 			if (tce.tcpConnState == MIB2_TCP_established ||
16681 			    tce.tcpConnState == MIB2_TCP_closeWait)
16682 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16683 
16684 			needattr = B_FALSE;
16685 			bzero(&mlp, sizeof (mlp));
16686 			if (connp->conn_mlp_type != mlptSingle) {
16687 				if (connp->conn_mlp_type == mlptShared ||
16688 				    connp->conn_mlp_type == mlptBoth)
16689 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16690 				if (connp->conn_mlp_type == mlptPrivate ||
16691 				    connp->conn_mlp_type == mlptBoth)
16692 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16693 				needattr = B_TRUE;
16694 			}
16695 			if (connp->conn_peercred != NULL) {
16696 				ts_label_t *tsl;
16697 
16698 				tsl = crgetlabel(connp->conn_peercred);
16699 				mlp.tme_doi = label2doi(tsl);
16700 				mlp.tme_label = *label2bslabel(tsl);
16701 				needattr = B_TRUE;
16702 			}
16703 
16704 			/* Create a message to report on IPv6 entries */
16705 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16706 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16707 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16708 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16709 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16710 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16711 			/* Don't want just anybody seeing these... */
16712 			if (ispriv) {
16713 				tce6.tcp6ConnEntryInfo.ce_snxt =
16714 				    tcp->tcp_snxt;
16715 				tce6.tcp6ConnEntryInfo.ce_suna =
16716 				    tcp->tcp_suna;
16717 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16718 				    tcp->tcp_rnxt;
16719 				tce6.tcp6ConnEntryInfo.ce_rack =
16720 				    tcp->tcp_rack;
16721 			} else {
16722 				/*
16723 				 * Netstat, unfortunately, uses this to
16724 				 * get send/receive queue sizes.  How to fix?
16725 				 * Why not compute the difference only?
16726 				 */
16727 				tce6.tcp6ConnEntryInfo.ce_snxt =
16728 				    tcp->tcp_snxt - tcp->tcp_suna;
16729 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16730 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16731 				    tcp->tcp_rnxt - tcp->tcp_rack;
16732 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16733 			}
16734 
16735 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16736 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16737 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16738 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16739 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16740 
16741 			tce6.tcp6ConnCreationProcess =
16742 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16743 			    tcp->tcp_cpid;
16744 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16745 
16746 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16747 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16748 
16749 			mlp.tme_connidx = v6_conn_idx++;
16750 			if (needattr)
16751 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16752 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16753 			}
16754 			/*
16755 			 * Create an IPv4 table entry for IPv4 entries and also
16756 			 * for IPv6 entries which are bound to in6addr_any
16757 			 * but don't have IPV6_V6ONLY set.
16758 			 * (i.e. anything an IPv4 peer could connect to)
16759 			 */
16760 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16761 			    (tcp->tcp_state <= TCPS_LISTEN &&
16762 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16763 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16764 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16765 					tce.tcpConnRemAddress = INADDR_ANY;
16766 					tce.tcpConnLocalAddress = INADDR_ANY;
16767 				} else {
16768 					tce.tcpConnRemAddress =
16769 					    tcp->tcp_remote;
16770 					tce.tcpConnLocalAddress =
16771 					    tcp->tcp_ip_src;
16772 				}
16773 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16774 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16775 				/* Don't want just anybody seeing these... */
16776 				if (ispriv) {
16777 					tce.tcpConnEntryInfo.ce_snxt =
16778 					    tcp->tcp_snxt;
16779 					tce.tcpConnEntryInfo.ce_suna =
16780 					    tcp->tcp_suna;
16781 					tce.tcpConnEntryInfo.ce_rnxt =
16782 					    tcp->tcp_rnxt;
16783 					tce.tcpConnEntryInfo.ce_rack =
16784 					    tcp->tcp_rack;
16785 				} else {
16786 					/*
16787 					 * Netstat, unfortunately, uses this to
16788 					 * get send/receive queue sizes.  How
16789 					 * to fix?
16790 					 * Why not compute the difference only?
16791 					 */
16792 					tce.tcpConnEntryInfo.ce_snxt =
16793 					    tcp->tcp_snxt - tcp->tcp_suna;
16794 					tce.tcpConnEntryInfo.ce_suna = 0;
16795 					tce.tcpConnEntryInfo.ce_rnxt =
16796 					    tcp->tcp_rnxt - tcp->tcp_rack;
16797 					tce.tcpConnEntryInfo.ce_rack = 0;
16798 				}
16799 
16800 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16801 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16802 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16803 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16804 				tce.tcpConnEntryInfo.ce_state =
16805 				    tcp->tcp_state;
16806 
16807 				tce.tcpConnCreationProcess =
16808 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16809 				    tcp->tcp_cpid;
16810 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16811 
16812 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16813 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16814 
16815 				mlp.tme_connidx = v4_conn_idx++;
16816 				if (needattr)
16817 					(void) snmp_append_data2(
16818 					    mp_attr_ctl->b_cont,
16819 					    &mp_attr_tail, (char *)&mlp,
16820 					    sizeof (mlp));
16821 			}
16822 		}
16823 	}
16824 
16825 	/* fixed length structure for IPv4 and IPv6 counters */
16826 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16827 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16828 	    sizeof (mib2_tcp6ConnEntry_t));
16829 	/* synchronize 32- and 64-bit counters */
16830 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16831 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16832 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16833 	optp->level = MIB2_TCP;
16834 	optp->name = 0;
16835 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16836 	    sizeof (tcps->tcps_mib));
16837 	optp->len = msgdsize(mpdata);
16838 	qreply(q, mpctl);
16839 
16840 	/* table of connections... */
16841 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16842 	    sizeof (struct T_optmgmt_ack)];
16843 	optp->level = MIB2_TCP;
16844 	optp->name = MIB2_TCP_CONN;
16845 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16846 	qreply(q, mp_conn_ctl);
16847 
16848 	/* table of MLP attributes... */
16849 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16850 	    sizeof (struct T_optmgmt_ack)];
16851 	optp->level = MIB2_TCP;
16852 	optp->name = EXPER_XPORT_MLP;
16853 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16854 	if (optp->len == 0)
16855 		freemsg(mp_attr_ctl);
16856 	else
16857 		qreply(q, mp_attr_ctl);
16858 
16859 	/* table of IPv6 connections... */
16860 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16861 	    sizeof (struct T_optmgmt_ack)];
16862 	optp->level = MIB2_TCP6;
16863 	optp->name = MIB2_TCP6_CONN;
16864 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16865 	qreply(q, mp6_conn_ctl);
16866 
16867 	/* table of IPv6 MLP attributes... */
16868 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16869 	    sizeof (struct T_optmgmt_ack)];
16870 	optp->level = MIB2_TCP6;
16871 	optp->name = EXPER_XPORT_MLP;
16872 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16873 	if (optp->len == 0)
16874 		freemsg(mp6_attr_ctl);
16875 	else
16876 		qreply(q, mp6_attr_ctl);
16877 	return (mp2ctl);
16878 }
16879 
16880 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16881 /* ARGSUSED */
16882 int
16883 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16884 {
16885 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16886 
16887 	switch (level) {
16888 	case MIB2_TCP:
16889 		switch (name) {
16890 		case 13:
16891 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16892 				return (0);
16893 			/* TODO: delete entry defined by tce */
16894 			return (1);
16895 		default:
16896 			return (0);
16897 		}
16898 	default:
16899 		return (1);
16900 	}
16901 }
16902 
16903 /* Translate TCP state to MIB2 TCP state. */
16904 static int
16905 tcp_snmp_state(tcp_t *tcp)
16906 {
16907 	if (tcp == NULL)
16908 		return (0);
16909 
16910 	switch (tcp->tcp_state) {
16911 	case TCPS_CLOSED:
16912 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16913 	case TCPS_BOUND:
16914 		return (MIB2_TCP_closed);
16915 	case TCPS_LISTEN:
16916 		return (MIB2_TCP_listen);
16917 	case TCPS_SYN_SENT:
16918 		return (MIB2_TCP_synSent);
16919 	case TCPS_SYN_RCVD:
16920 		return (MIB2_TCP_synReceived);
16921 	case TCPS_ESTABLISHED:
16922 		return (MIB2_TCP_established);
16923 	case TCPS_CLOSE_WAIT:
16924 		return (MIB2_TCP_closeWait);
16925 	case TCPS_FIN_WAIT_1:
16926 		return (MIB2_TCP_finWait1);
16927 	case TCPS_CLOSING:
16928 		return (MIB2_TCP_closing);
16929 	case TCPS_LAST_ACK:
16930 		return (MIB2_TCP_lastAck);
16931 	case TCPS_FIN_WAIT_2:
16932 		return (MIB2_TCP_finWait2);
16933 	case TCPS_TIME_WAIT:
16934 		return (MIB2_TCP_timeWait);
16935 	default:
16936 		return (0);
16937 	}
16938 }
16939 
16940 static char tcp_report_header[] =
16941 	"TCP     " MI_COL_HDRPAD_STR
16942 	"zone dest            snxt     suna     "
16943 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16944 	"recent   [lport,fport] state";
16945 
16946 /*
16947  * TCP status report triggered via the Named Dispatch mechanism.
16948  */
16949 /* ARGSUSED */
16950 static void
16951 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16952     cred_t *cr)
16953 {
16954 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16955 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16956 	char cflag;
16957 	in6_addr_t	v6dst;
16958 	char buf[80];
16959 	uint_t print_len, buf_len;
16960 
16961 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16962 	if (buf_len <= 0)
16963 		return;
16964 
16965 	if (hashval >= 0)
16966 		(void) sprintf(hash, "%03d ", hashval);
16967 	else
16968 		hash[0] = '\0';
16969 
16970 	/*
16971 	 * Note that we use the remote address in the tcp_b  structure.
16972 	 * This means that it will print out the real destination address,
16973 	 * not the next hop's address if source routing is used.  This
16974 	 * avoid the confusion on the output because user may not
16975 	 * know that source routing is used for a connection.
16976 	 */
16977 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16978 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16979 	} else {
16980 		v6dst = tcp->tcp_remote_v6;
16981 	}
16982 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16983 	/*
16984 	 * the ispriv checks are so that normal users cannot determine
16985 	 * sequence number information using NDD.
16986 	 */
16987 
16988 	if (TCP_IS_DETACHED(tcp))
16989 		cflag = '*';
16990 	else
16991 		cflag = ' ';
16992 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16993 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16994 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16995 	    hash,
16996 	    (void *)tcp,
16997 	    tcp->tcp_connp->conn_zoneid,
16998 	    addrbuf,
16999 	    (ispriv) ? tcp->tcp_snxt : 0,
17000 	    (ispriv) ? tcp->tcp_suna : 0,
17001 	    tcp->tcp_swnd,
17002 	    (ispriv) ? tcp->tcp_rnxt : 0,
17003 	    (ispriv) ? tcp->tcp_rack : 0,
17004 	    tcp->tcp_rwnd,
17005 	    tcp->tcp_rto,
17006 	    tcp->tcp_mss,
17007 	    tcp->tcp_snd_ws_ok,
17008 	    tcp->tcp_snd_ws,
17009 	    tcp->tcp_rcv_ws,
17010 	    tcp->tcp_snd_ts_ok,
17011 	    tcp->tcp_ts_recent,
17012 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
17013 	if (print_len < buf_len) {
17014 		((mblk_t *)mp)->b_wptr += print_len;
17015 	} else {
17016 		((mblk_t *)mp)->b_wptr += buf_len;
17017 	}
17018 }
17019 
17020 /*
17021  * TCP status report (for listeners only) triggered via the Named Dispatch
17022  * mechanism.
17023  */
17024 /* ARGSUSED */
17025 static void
17026 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
17027 {
17028 	char addrbuf[INET6_ADDRSTRLEN];
17029 	in6_addr_t	v6dst;
17030 	uint_t print_len, buf_len;
17031 
17032 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
17033 	if (buf_len <= 0)
17034 		return;
17035 
17036 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17037 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
17038 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
17039 	} else {
17040 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
17041 		    addrbuf, sizeof (addrbuf));
17042 	}
17043 	print_len = snprintf((char *)mp->b_wptr, buf_len,
17044 	    "%03d "
17045 	    MI_COL_PTRFMT_STR
17046 	    "%d %s %05u %08u %d/%d/%d%c\n",
17047 	    hashval, (void *)tcp,
17048 	    tcp->tcp_connp->conn_zoneid,
17049 	    addrbuf,
17050 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
17051 	    tcp->tcp_conn_req_seqnum,
17052 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
17053 	    tcp->tcp_conn_req_max,
17054 	    tcp->tcp_syn_defense ? '*' : ' ');
17055 	if (print_len < buf_len) {
17056 		((mblk_t *)mp)->b_wptr += print_len;
17057 	} else {
17058 		((mblk_t *)mp)->b_wptr += buf_len;
17059 	}
17060 }
17061 
17062 /* TCP status report triggered via the Named Dispatch mechanism. */
17063 /* ARGSUSED */
17064 static int
17065 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17066 {
17067 	tcp_t	*tcp;
17068 	int	i;
17069 	conn_t	*connp;
17070 	connf_t	*connfp;
17071 	zoneid_t zoneid;
17072 	tcp_stack_t *tcps;
17073 	ip_stack_t *ipst;
17074 
17075 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17076 	tcps = Q_TO_TCP(q)->tcp_tcps;
17077 
17078 	/*
17079 	 * Because of the ndd constraint, at most we can have 64K buffer
17080 	 * to put in all TCP info.  So to be more efficient, just
17081 	 * allocate a 64K buffer here, assuming we need that large buffer.
17082 	 * This may be a problem as any user can read tcp_status.  Therefore
17083 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
17084 	 * This should be OK as normal users should not do this too often.
17085 	 */
17086 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17087 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17088 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17089 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17090 			return (0);
17091 		}
17092 	}
17093 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17094 		/* The following may work even if we cannot get a large buf. */
17095 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17096 		return (0);
17097 	}
17098 
17099 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
17100 
17101 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
17102 
17103 		ipst = tcps->tcps_netstack->netstack_ip;
17104 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
17105 
17106 		connp = NULL;
17107 
17108 		while ((connp =
17109 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17110 			tcp = connp->conn_tcp;
17111 			if (zoneid != GLOBAL_ZONEID &&
17112 			    zoneid != connp->conn_zoneid)
17113 				continue;
17114 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
17115 			    cr);
17116 		}
17117 
17118 	}
17119 
17120 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17121 	return (0);
17122 }
17123 
17124 /* TCP status report triggered via the Named Dispatch mechanism. */
17125 /* ARGSUSED */
17126 static int
17127 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17128 {
17129 	tf_t	*tbf;
17130 	tcp_t	*tcp;
17131 	int	i;
17132 	zoneid_t zoneid;
17133 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17134 
17135 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17136 
17137 	/* Refer to comments in tcp_status_report(). */
17138 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17139 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17140 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17141 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17142 			return (0);
17143 		}
17144 	}
17145 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17146 		/* The following may work even if we cannot get a large buf. */
17147 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17148 		return (0);
17149 	}
17150 
17151 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17152 
17153 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
17154 		tbf = &tcps->tcps_bind_fanout[i];
17155 		mutex_enter(&tbf->tf_lock);
17156 		for (tcp = tbf->tf_tcp; tcp != NULL;
17157 		    tcp = tcp->tcp_bind_hash) {
17158 			if (zoneid != GLOBAL_ZONEID &&
17159 			    zoneid != tcp->tcp_connp->conn_zoneid)
17160 				continue;
17161 			CONN_INC_REF(tcp->tcp_connp);
17162 			tcp_report_item(mp->b_cont, tcp, i,
17163 			    Q_TO_TCP(q), cr);
17164 			CONN_DEC_REF(tcp->tcp_connp);
17165 		}
17166 		mutex_exit(&tbf->tf_lock);
17167 	}
17168 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17169 	return (0);
17170 }
17171 
17172 /* TCP status report triggered via the Named Dispatch mechanism. */
17173 /* ARGSUSED */
17174 static int
17175 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17176 {
17177 	connf_t	*connfp;
17178 	conn_t	*connp;
17179 	tcp_t	*tcp;
17180 	int	i;
17181 	zoneid_t zoneid;
17182 	tcp_stack_t *tcps;
17183 	ip_stack_t	*ipst;
17184 
17185 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17186 	tcps = Q_TO_TCP(q)->tcp_tcps;
17187 
17188 	/* Refer to comments in tcp_status_report(). */
17189 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17190 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17191 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17192 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17193 			return (0);
17194 		}
17195 	}
17196 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17197 		/* The following may work even if we cannot get a large buf. */
17198 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17199 		return (0);
17200 	}
17201 
17202 	(void) mi_mpprintf(mp,
17203 	    "    TCP    " MI_COL_HDRPAD_STR
17204 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
17205 
17206 	ipst = tcps->tcps_netstack->netstack_ip;
17207 
17208 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
17209 		connfp = &ipst->ips_ipcl_bind_fanout[i];
17210 		connp = NULL;
17211 		while ((connp =
17212 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17213 			tcp = connp->conn_tcp;
17214 			if (zoneid != GLOBAL_ZONEID &&
17215 			    zoneid != connp->conn_zoneid)
17216 				continue;
17217 			tcp_report_listener(mp->b_cont, tcp, i);
17218 		}
17219 	}
17220 
17221 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17222 	return (0);
17223 }
17224 
17225 /* TCP status report triggered via the Named Dispatch mechanism. */
17226 /* ARGSUSED */
17227 static int
17228 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17229 {
17230 	connf_t	*connfp;
17231 	conn_t	*connp;
17232 	tcp_t	*tcp;
17233 	int	i;
17234 	zoneid_t zoneid;
17235 	tcp_stack_t *tcps;
17236 	ip_stack_t *ipst;
17237 
17238 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17239 	tcps = Q_TO_TCP(q)->tcp_tcps;
17240 	ipst = tcps->tcps_netstack->netstack_ip;
17241 
17242 	/* Refer to comments in tcp_status_report(). */
17243 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17244 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17245 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17246 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17247 			return (0);
17248 		}
17249 	}
17250 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17251 		/* The following may work even if we cannot get a large buf. */
17252 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17253 		return (0);
17254 	}
17255 
17256 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
17257 	    ipst->ips_ipcl_conn_fanout_size);
17258 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17259 
17260 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
17261 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
17262 		connp = NULL;
17263 		while ((connp =
17264 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17265 			tcp = connp->conn_tcp;
17266 			if (zoneid != GLOBAL_ZONEID &&
17267 			    zoneid != connp->conn_zoneid)
17268 				continue;
17269 			tcp_report_item(mp->b_cont, tcp, i,
17270 			    Q_TO_TCP(q), cr);
17271 		}
17272 	}
17273 
17274 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17275 	return (0);
17276 }
17277 
17278 /* TCP status report triggered via the Named Dispatch mechanism. */
17279 /* ARGSUSED */
17280 static int
17281 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17282 {
17283 	tf_t	*tf;
17284 	tcp_t	*tcp;
17285 	int	i;
17286 	zoneid_t zoneid;
17287 	tcp_stack_t	*tcps;
17288 
17289 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17290 	tcps = Q_TO_TCP(q)->tcp_tcps;
17291 
17292 	/* Refer to comments in tcp_status_report(). */
17293 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17294 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17295 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17296 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17297 			return (0);
17298 		}
17299 	}
17300 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17301 		/* The following may work even if we cannot get a large buf. */
17302 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17303 		return (0);
17304 	}
17305 
17306 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17307 
17308 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
17309 		tf = &tcps->tcps_acceptor_fanout[i];
17310 		mutex_enter(&tf->tf_lock);
17311 		for (tcp = tf->tf_tcp; tcp != NULL;
17312 		    tcp = tcp->tcp_acceptor_hash) {
17313 			if (zoneid != GLOBAL_ZONEID &&
17314 			    zoneid != tcp->tcp_connp->conn_zoneid)
17315 				continue;
17316 			tcp_report_item(mp->b_cont, tcp, i,
17317 			    Q_TO_TCP(q), cr);
17318 		}
17319 		mutex_exit(&tf->tf_lock);
17320 	}
17321 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17322 	return (0);
17323 }
17324 
17325 /*
17326  * tcp_timer is the timer service routine.  It handles the retransmission,
17327  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
17328  * from the state of the tcp instance what kind of action needs to be done
17329  * at the time it is called.
17330  */
17331 static void
17332 tcp_timer(void *arg)
17333 {
17334 	mblk_t		*mp;
17335 	clock_t		first_threshold;
17336 	clock_t		second_threshold;
17337 	clock_t		ms;
17338 	uint32_t	mss;
17339 	conn_t		*connp = (conn_t *)arg;
17340 	tcp_t		*tcp = connp->conn_tcp;
17341 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17342 
17343 	tcp->tcp_timer_tid = 0;
17344 
17345 	if (tcp->tcp_fused)
17346 		return;
17347 
17348 	first_threshold =  tcp->tcp_first_timer_threshold;
17349 	second_threshold = tcp->tcp_second_timer_threshold;
17350 	switch (tcp->tcp_state) {
17351 	case TCPS_IDLE:
17352 	case TCPS_BOUND:
17353 	case TCPS_LISTEN:
17354 		return;
17355 	case TCPS_SYN_RCVD: {
17356 		tcp_t	*listener = tcp->tcp_listener;
17357 
17358 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
17359 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
17360 			/* it's our first timeout */
17361 			tcp->tcp_syn_rcvd_timeout = 1;
17362 			mutex_enter(&listener->tcp_eager_lock);
17363 			listener->tcp_syn_rcvd_timeout++;
17364 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
17365 				/*
17366 				 * Make this eager available for drop if we
17367 				 * need to drop one to accomodate a new
17368 				 * incoming SYN request.
17369 				 */
17370 				MAKE_DROPPABLE(listener, tcp);
17371 			}
17372 			if (!listener->tcp_syn_defense &&
17373 			    (listener->tcp_syn_rcvd_timeout >
17374 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
17375 			    (tcps->tcps_conn_req_max_q0 > 200)) {
17376 				/* We may be under attack. Put on a defense. */
17377 				listener->tcp_syn_defense = B_TRUE;
17378 				cmn_err(CE_WARN, "High TCP connect timeout "
17379 				    "rate! System (port %d) may be under a "
17380 				    "SYN flood attack!",
17381 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
17382 
17383 				listener->tcp_ip_addr_cache = kmem_zalloc(
17384 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
17385 				    KM_NOSLEEP);
17386 			}
17387 			mutex_exit(&listener->tcp_eager_lock);
17388 		} else if (listener != NULL) {
17389 			mutex_enter(&listener->tcp_eager_lock);
17390 			tcp->tcp_syn_rcvd_timeout++;
17391 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17392 			    !tcp->tcp_closemp_used) {
17393 				/*
17394 				 * This is our second timeout. Put the tcp in
17395 				 * the list of droppable eagers to allow it to
17396 				 * be dropped, if needed. We don't check
17397 				 * whether tcp_dontdrop is set or not to
17398 				 * protect ourselve from a SYN attack where a
17399 				 * remote host can spoof itself as one of the
17400 				 * good IP source and continue to hold
17401 				 * resources too long.
17402 				 */
17403 				MAKE_DROPPABLE(listener, tcp);
17404 			}
17405 			mutex_exit(&listener->tcp_eager_lock);
17406 		}
17407 	}
17408 		/* FALLTHRU */
17409 	case TCPS_SYN_SENT:
17410 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17411 		second_threshold = tcp->tcp_second_ctimer_threshold;
17412 		break;
17413 	case TCPS_ESTABLISHED:
17414 	case TCPS_FIN_WAIT_1:
17415 	case TCPS_CLOSING:
17416 	case TCPS_CLOSE_WAIT:
17417 	case TCPS_LAST_ACK:
17418 		/* If we have data to rexmit */
17419 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17420 			clock_t	time_to_wait;
17421 
17422 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17423 			if (!tcp->tcp_xmit_head)
17424 				break;
17425 			time_to_wait = lbolt -
17426 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17427 			time_to_wait = tcp->tcp_rto -
17428 			    TICK_TO_MSEC(time_to_wait);
17429 			/*
17430 			 * If the timer fires too early, 1 clock tick earlier,
17431 			 * restart the timer.
17432 			 */
17433 			if (time_to_wait > msec_per_tick) {
17434 				TCP_STAT(tcps, tcp_timer_fire_early);
17435 				TCP_TIMER_RESTART(tcp, time_to_wait);
17436 				return;
17437 			}
17438 			/*
17439 			 * When we probe zero windows, we force the swnd open.
17440 			 * If our peer acks with a closed window swnd will be
17441 			 * set to zero by tcp_rput(). As long as we are
17442 			 * receiving acks tcp_rput will
17443 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17444 			 * first and second interval actions.  NOTE: the timer
17445 			 * interval is allowed to continue its exponential
17446 			 * backoff.
17447 			 */
17448 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17449 				if (tcp->tcp_debug) {
17450 					(void) strlog(TCP_MOD_ID, 0, 1,
17451 					    SL_TRACE, "tcp_timer: zero win");
17452 				}
17453 			} else {
17454 				/*
17455 				 * After retransmission, we need to do
17456 				 * slow start.  Set the ssthresh to one
17457 				 * half of current effective window and
17458 				 * cwnd to one MSS.  Also reset
17459 				 * tcp_cwnd_cnt.
17460 				 *
17461 				 * Note that if tcp_ssthresh is reduced because
17462 				 * of ECN, do not reduce it again unless it is
17463 				 * already one window of data away (tcp_cwr
17464 				 * should then be cleared) or this is a
17465 				 * timeout for a retransmitted segment.
17466 				 */
17467 				uint32_t npkt;
17468 
17469 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17470 					npkt = ((tcp->tcp_timer_backoff ?
17471 					    tcp->tcp_cwnd_ssthresh :
17472 					    tcp->tcp_snxt -
17473 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17474 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17475 					    tcp->tcp_mss;
17476 				}
17477 				tcp->tcp_cwnd = tcp->tcp_mss;
17478 				tcp->tcp_cwnd_cnt = 0;
17479 				if (tcp->tcp_ecn_ok) {
17480 					tcp->tcp_cwr = B_TRUE;
17481 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17482 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17483 				}
17484 			}
17485 			break;
17486 		}
17487 		/*
17488 		 * We have something to send yet we cannot send.  The
17489 		 * reason can be:
17490 		 *
17491 		 * 1. Zero send window: we need to do zero window probe.
17492 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17493 		 * segments.
17494 		 * 3. SWS avoidance: receiver may have shrunk window,
17495 		 * reset our knowledge.
17496 		 *
17497 		 * Note that condition 2 can happen with either 1 or
17498 		 * 3.  But 1 and 3 are exclusive.
17499 		 */
17500 		if (tcp->tcp_unsent != 0) {
17501 			if (tcp->tcp_cwnd == 0) {
17502 				/*
17503 				 * Set tcp_cwnd to 1 MSS so that a
17504 				 * new segment can be sent out.  We
17505 				 * are "clocking out" new data when
17506 				 * the network is really congested.
17507 				 */
17508 				ASSERT(tcp->tcp_ecn_ok);
17509 				tcp->tcp_cwnd = tcp->tcp_mss;
17510 			}
17511 			if (tcp->tcp_swnd == 0) {
17512 				/* Extend window for zero window probe */
17513 				tcp->tcp_swnd++;
17514 				tcp->tcp_zero_win_probe = B_TRUE;
17515 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17516 			} else {
17517 				/*
17518 				 * Handle timeout from sender SWS avoidance.
17519 				 * Reset our knowledge of the max send window
17520 				 * since the receiver might have reduced its
17521 				 * receive buffer.  Avoid setting tcp_max_swnd
17522 				 * to one since that will essentially disable
17523 				 * the SWS checks.
17524 				 *
17525 				 * Note that since we don't have a SWS
17526 				 * state variable, if the timeout is set
17527 				 * for ECN but not for SWS, this
17528 				 * code will also be executed.  This is
17529 				 * fine as tcp_max_swnd is updated
17530 				 * constantly and it will not affect
17531 				 * anything.
17532 				 */
17533 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17534 			}
17535 			tcp_wput_data(tcp, NULL, B_FALSE);
17536 			return;
17537 		}
17538 		/* Is there a FIN that needs to be to re retransmitted? */
17539 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17540 		    !tcp->tcp_fin_acked)
17541 			break;
17542 		/* Nothing to do, return without restarting timer. */
17543 		TCP_STAT(tcps, tcp_timer_fire_miss);
17544 		return;
17545 	case TCPS_FIN_WAIT_2:
17546 		/*
17547 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17548 		 * We waited some time for for peer's FIN, but it hasn't
17549 		 * arrived.  We flush the connection now to avoid
17550 		 * case where the peer has rebooted.
17551 		 */
17552 		if (TCP_IS_DETACHED(tcp)) {
17553 			(void) tcp_clean_death(tcp, 0, 23);
17554 		} else {
17555 			TCP_TIMER_RESTART(tcp,
17556 			    tcps->tcps_fin_wait_2_flush_interval);
17557 		}
17558 		return;
17559 	case TCPS_TIME_WAIT:
17560 		(void) tcp_clean_death(tcp, 0, 24);
17561 		return;
17562 	default:
17563 		if (tcp->tcp_debug) {
17564 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17565 			    "tcp_timer: strange state (%d) %s",
17566 			    tcp->tcp_state, tcp_display(tcp, NULL,
17567 			    DISP_PORT_ONLY));
17568 		}
17569 		return;
17570 	}
17571 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17572 		/*
17573 		 * For zero window probe, we need to send indefinitely,
17574 		 * unless we have not heard from the other side for some
17575 		 * time...
17576 		 */
17577 		if ((tcp->tcp_zero_win_probe == 0) ||
17578 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17579 		    second_threshold)) {
17580 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17581 			/*
17582 			 * If TCP is in SYN_RCVD state, send back a
17583 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17584 			 * should be zero in TCPS_SYN_RCVD state.
17585 			 */
17586 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17587 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17588 				    "in SYN_RCVD",
17589 				    tcp, tcp->tcp_snxt,
17590 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17591 			}
17592 			(void) tcp_clean_death(tcp,
17593 			    tcp->tcp_client_errno ?
17594 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17595 			return;
17596 		} else {
17597 			/*
17598 			 * Set tcp_ms_we_have_waited to second_threshold
17599 			 * so that in next timeout, we will do the above
17600 			 * check (lbolt - tcp_last_recv_time).  This is
17601 			 * also to avoid overflow.
17602 			 *
17603 			 * We don't need to decrement tcp_timer_backoff
17604 			 * to avoid overflow because it will be decremented
17605 			 * later if new timeout value is greater than
17606 			 * tcp_rexmit_interval_max.  In the case when
17607 			 * tcp_rexmit_interval_max is greater than
17608 			 * second_threshold, it means that we will wait
17609 			 * longer than second_threshold to send the next
17610 			 * window probe.
17611 			 */
17612 			tcp->tcp_ms_we_have_waited = second_threshold;
17613 		}
17614 	} else if (ms > first_threshold) {
17615 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17616 		    tcp->tcp_xmit_head != NULL) {
17617 			tcp->tcp_xmit_head =
17618 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17619 		}
17620 		/*
17621 		 * We have been retransmitting for too long...  The RTT
17622 		 * we calculated is probably incorrect.  Reinitialize it.
17623 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17624 		 * tcp_rtt_update so that we won't accidentally cache a
17625 		 * bad value.  But only do this if this is not a zero
17626 		 * window probe.
17627 		 */
17628 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17629 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17630 			    (tcp->tcp_rtt_sa >> 5);
17631 			tcp->tcp_rtt_sa = 0;
17632 			tcp_ip_notify(tcp);
17633 			tcp->tcp_rtt_update = 0;
17634 		}
17635 	}
17636 	tcp->tcp_timer_backoff++;
17637 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17638 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17639 	    tcps->tcps_rexmit_interval_min) {
17640 		/*
17641 		 * This means the original RTO is tcp_rexmit_interval_min.
17642 		 * So we will use tcp_rexmit_interval_min as the RTO value
17643 		 * and do the backoff.
17644 		 */
17645 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17646 	} else {
17647 		ms <<= tcp->tcp_timer_backoff;
17648 	}
17649 	if (ms > tcps->tcps_rexmit_interval_max) {
17650 		ms = tcps->tcps_rexmit_interval_max;
17651 		/*
17652 		 * ms is at max, decrement tcp_timer_backoff to avoid
17653 		 * overflow.
17654 		 */
17655 		tcp->tcp_timer_backoff--;
17656 	}
17657 	tcp->tcp_ms_we_have_waited += ms;
17658 	if (tcp->tcp_zero_win_probe == 0) {
17659 		tcp->tcp_rto = ms;
17660 	}
17661 	TCP_TIMER_RESTART(tcp, ms);
17662 	/*
17663 	 * This is after a timeout and tcp_rto is backed off.  Set
17664 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17665 	 * restart the timer with a correct value.
17666 	 */
17667 	tcp->tcp_set_timer = 1;
17668 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17669 	if (mss > tcp->tcp_mss)
17670 		mss = tcp->tcp_mss;
17671 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17672 		mss = tcp->tcp_swnd;
17673 
17674 	if ((mp = tcp->tcp_xmit_head) != NULL)
17675 		mp->b_prev = (mblk_t *)lbolt;
17676 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17677 	    B_TRUE);
17678 
17679 	/*
17680 	 * When slow start after retransmission begins, start with
17681 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17682 	 * start phase.  tcp_snd_burst controls how many segments
17683 	 * can be sent because of an ack.
17684 	 */
17685 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17686 	tcp->tcp_snd_burst = TCP_CWND_SS;
17687 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17688 	    (tcp->tcp_unsent == 0)) {
17689 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17690 	} else {
17691 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17692 	}
17693 	tcp->tcp_rexmit = B_TRUE;
17694 	tcp->tcp_dupack_cnt = 0;
17695 
17696 	/*
17697 	 * Remove all rexmit SACK blk to start from fresh.
17698 	 */
17699 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17700 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17701 		tcp->tcp_num_notsack_blk = 0;
17702 		tcp->tcp_cnt_notsack_list = 0;
17703 	}
17704 	if (mp == NULL) {
17705 		return;
17706 	}
17707 	/* Attach credentials to retransmitted initial SYNs. */
17708 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17709 		mblk_setcred(mp, tcp->tcp_cred);
17710 		DB_CPID(mp) = tcp->tcp_cpid;
17711 	}
17712 
17713 	tcp->tcp_csuna = tcp->tcp_snxt;
17714 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17715 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17716 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17717 
17718 }
17719 
17720 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17721 static void
17722 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17723 {
17724 	conn_t	*connp;
17725 
17726 	switch (tcp->tcp_state) {
17727 	case TCPS_BOUND:
17728 	case TCPS_LISTEN:
17729 		break;
17730 	default:
17731 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17732 		return;
17733 	}
17734 
17735 	/*
17736 	 * Need to clean up all the eagers since after the unbind, segments
17737 	 * will no longer be delivered to this listener stream.
17738 	 */
17739 	mutex_enter(&tcp->tcp_eager_lock);
17740 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17741 		tcp_eager_cleanup(tcp, 0);
17742 	}
17743 	mutex_exit(&tcp->tcp_eager_lock);
17744 
17745 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17746 		tcp->tcp_ipha->ipha_src = 0;
17747 	} else {
17748 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17749 	}
17750 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17751 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17752 	tcp_bind_hash_remove(tcp);
17753 	tcp->tcp_state = TCPS_IDLE;
17754 	tcp->tcp_mdt = B_FALSE;
17755 	/* Send M_FLUSH according to TPI */
17756 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17757 	connp = tcp->tcp_connp;
17758 	connp->conn_mdt_ok = B_FALSE;
17759 	ipcl_hash_remove(connp);
17760 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17761 	mp = mi_tpi_ok_ack_alloc(mp);
17762 	putnext(tcp->tcp_rq, mp);
17763 }
17764 
17765 /*
17766  * Don't let port fall into the privileged range.
17767  * Since the extra privileged ports can be arbitrary we also
17768  * ensure that we exclude those from consideration.
17769  * tcp_g_epriv_ports is not sorted thus we loop over it until
17770  * there are no changes.
17771  *
17772  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17773  * but instead the code relies on:
17774  * - the fact that the address of the array and its size never changes
17775  * - the atomic assignment of the elements of the array
17776  *
17777  * Returns 0 if there are no more ports available.
17778  *
17779  * TS note: skip multilevel ports.
17780  */
17781 static in_port_t
17782 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17783 {
17784 	int i;
17785 	boolean_t restart = B_FALSE;
17786 	tcp_stack_t *tcps = tcp->tcp_tcps;
17787 
17788 	if (random && tcp_random_anon_port != 0) {
17789 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17790 		    sizeof (in_port_t));
17791 		/*
17792 		 * Unless changed by a sys admin, the smallest anon port
17793 		 * is 32768 and the largest anon port is 65535.  It is
17794 		 * very likely (50%) for the random port to be smaller
17795 		 * than the smallest anon port.  When that happens,
17796 		 * add port % (anon port range) to the smallest anon
17797 		 * port to get the random port.  It should fall into the
17798 		 * valid anon port range.
17799 		 */
17800 		if (port < tcps->tcps_smallest_anon_port) {
17801 			port = tcps->tcps_smallest_anon_port +
17802 			    port % (tcps->tcps_largest_anon_port -
17803 			    tcps->tcps_smallest_anon_port);
17804 		}
17805 	}
17806 
17807 retry:
17808 	if (port < tcps->tcps_smallest_anon_port)
17809 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17810 
17811 	if (port > tcps->tcps_largest_anon_port) {
17812 		if (restart)
17813 			return (0);
17814 		restart = B_TRUE;
17815 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17816 	}
17817 
17818 	if (port < tcps->tcps_smallest_nonpriv_port)
17819 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17820 
17821 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17822 		if (port == tcps->tcps_g_epriv_ports[i]) {
17823 			port++;
17824 			/*
17825 			 * Make sure whether the port is in the
17826 			 * valid range.
17827 			 */
17828 			goto retry;
17829 		}
17830 	}
17831 	if (is_system_labeled() &&
17832 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17833 	    IPPROTO_TCP, B_TRUE)) != 0) {
17834 		port = i;
17835 		goto retry;
17836 	}
17837 	return (port);
17838 }
17839 
17840 /*
17841  * Return the next anonymous port in the privileged port range for
17842  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17843  * downwards.  This is the same behavior as documented in the userland
17844  * library call rresvport(3N).
17845  *
17846  * TS note: skip multilevel ports.
17847  */
17848 static in_port_t
17849 tcp_get_next_priv_port(const tcp_t *tcp)
17850 {
17851 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17852 	in_port_t nextport;
17853 	boolean_t restart = B_FALSE;
17854 	tcp_stack_t *tcps = tcp->tcp_tcps;
17855 retry:
17856 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17857 	    next_priv_port >= IPPORT_RESERVED) {
17858 		next_priv_port = IPPORT_RESERVED - 1;
17859 		if (restart)
17860 			return (0);
17861 		restart = B_TRUE;
17862 	}
17863 	if (is_system_labeled() &&
17864 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17865 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17866 		next_priv_port = nextport;
17867 		goto retry;
17868 	}
17869 	return (next_priv_port--);
17870 }
17871 
17872 /* The write side r/w procedure. */
17873 
17874 #if CCS_STATS
17875 struct {
17876 	struct {
17877 		int64_t count, bytes;
17878 	} tot, hit;
17879 } wrw_stats;
17880 #endif
17881 
17882 /*
17883  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17884  * messages.
17885  */
17886 /* ARGSUSED */
17887 static void
17888 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17889 {
17890 	conn_t	*connp = (conn_t *)arg;
17891 	tcp_t	*tcp = connp->conn_tcp;
17892 	queue_t	*q = tcp->tcp_wq;
17893 
17894 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17895 	/*
17896 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17897 	 * Once the close starts, streamhead and sockfs will not let any data
17898 	 * packets come down (close ensures that there are no threads using the
17899 	 * queue and no new threads will come down) but since qprocsoff()
17900 	 * hasn't happened yet, a M_FLUSH or some non data message might
17901 	 * get reflected back (in response to our own FLUSHRW) and get
17902 	 * processed after tcp_close() is done. The conn would still be valid
17903 	 * because a ref would have added but we need to check the state
17904 	 * before actually processing the packet.
17905 	 */
17906 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17907 		freemsg(mp);
17908 		return;
17909 	}
17910 
17911 	switch (DB_TYPE(mp)) {
17912 	case M_IOCDATA:
17913 		tcp_wput_iocdata(tcp, mp);
17914 		break;
17915 	case M_FLUSH:
17916 		tcp_wput_flush(tcp, mp);
17917 		break;
17918 	default:
17919 		CALL_IP_WPUT(connp, q, mp);
17920 		break;
17921 	}
17922 }
17923 
17924 /*
17925  * The TCP fast path write put procedure.
17926  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17927  */
17928 /* ARGSUSED */
17929 void
17930 tcp_output(void *arg, mblk_t *mp, void *arg2)
17931 {
17932 	int		len;
17933 	int		hdrlen;
17934 	int		plen;
17935 	mblk_t		*mp1;
17936 	uchar_t		*rptr;
17937 	uint32_t	snxt;
17938 	tcph_t		*tcph;
17939 	struct datab	*db;
17940 	uint32_t	suna;
17941 	uint32_t	mss;
17942 	ipaddr_t	*dst;
17943 	ipaddr_t	*src;
17944 	uint32_t	sum;
17945 	int		usable;
17946 	conn_t		*connp = (conn_t *)arg;
17947 	tcp_t		*tcp = connp->conn_tcp;
17948 	uint32_t	msize;
17949 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17950 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17951 
17952 	/*
17953 	 * Try and ASSERT the minimum possible references on the
17954 	 * conn early enough. Since we are executing on write side,
17955 	 * the connection is obviously not detached and that means
17956 	 * there is a ref each for TCP and IP. Since we are behind
17957 	 * the squeue, the minimum references needed are 3. If the
17958 	 * conn is in classifier hash list, there should be an
17959 	 * extra ref for that (we check both the possibilities).
17960 	 */
17961 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17962 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17963 
17964 	ASSERT(DB_TYPE(mp) == M_DATA);
17965 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17966 
17967 	mutex_enter(&tcp->tcp_non_sq_lock);
17968 	tcp->tcp_squeue_bytes -= msize;
17969 	mutex_exit(&tcp->tcp_non_sq_lock);
17970 
17971 	/* Check to see if this connection wants to be re-fused. */
17972 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17973 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17974 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17975 			    &tcp->tcp_saved_tcph);
17976 		} else {
17977 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17978 			    &tcp->tcp_saved_tcph);
17979 		}
17980 	}
17981 	/* Bypass tcp protocol for fused tcp loopback */
17982 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17983 		return;
17984 
17985 	mss = tcp->tcp_mss;
17986 	if (tcp->tcp_xmit_zc_clean)
17987 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17988 
17989 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17990 	len = (int)(mp->b_wptr - mp->b_rptr);
17991 
17992 	/*
17993 	 * Criteria for fast path:
17994 	 *
17995 	 *   1. no unsent data
17996 	 *   2. single mblk in request
17997 	 *   3. connection established
17998 	 *   4. data in mblk
17999 	 *   5. len <= mss
18000 	 *   6. no tcp_valid bits
18001 	 */
18002 	if ((tcp->tcp_unsent != 0) ||
18003 	    (tcp->tcp_cork) ||
18004 	    (mp->b_cont != NULL) ||
18005 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
18006 	    (len == 0) ||
18007 	    (len > mss) ||
18008 	    (tcp->tcp_valid_bits != 0)) {
18009 		tcp_wput_data(tcp, mp, B_FALSE);
18010 		return;
18011 	}
18012 
18013 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
18014 	ASSERT(tcp->tcp_fin_sent == 0);
18015 
18016 	/* queue new packet onto retransmission queue */
18017 	if (tcp->tcp_xmit_head == NULL) {
18018 		tcp->tcp_xmit_head = mp;
18019 	} else {
18020 		tcp->tcp_xmit_last->b_cont = mp;
18021 	}
18022 	tcp->tcp_xmit_last = mp;
18023 	tcp->tcp_xmit_tail = mp;
18024 
18025 	/* find out how much we can send */
18026 	/* BEGIN CSTYLED */
18027 	/*
18028 	 *    un-acked           usable
18029 	 *  |--------------|-----------------|
18030 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
18031 	 */
18032 	/* END CSTYLED */
18033 
18034 	/* start sending from tcp_snxt */
18035 	snxt = tcp->tcp_snxt;
18036 
18037 	/*
18038 	 * Check to see if this connection has been idled for some
18039 	 * time and no ACK is expected.  If it is, we need to slow
18040 	 * start again to get back the connection's "self-clock" as
18041 	 * described in VJ's paper.
18042 	 *
18043 	 * Refer to the comment in tcp_mss_set() for the calculation
18044 	 * of tcp_cwnd after idle.
18045 	 */
18046 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18047 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18048 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18049 	}
18050 
18051 	usable = tcp->tcp_swnd;		/* tcp window size */
18052 	if (usable > tcp->tcp_cwnd)
18053 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
18054 	usable -= snxt;		/* subtract stuff already sent */
18055 	suna = tcp->tcp_suna;
18056 	usable += suna;
18057 	/* usable can be < 0 if the congestion window is smaller */
18058 	if (len > usable) {
18059 		/* Can't send complete M_DATA in one shot */
18060 		goto slow;
18061 	}
18062 
18063 	mutex_enter(&tcp->tcp_non_sq_lock);
18064 	if (tcp->tcp_flow_stopped &&
18065 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18066 		tcp_clrqfull(tcp);
18067 	}
18068 	mutex_exit(&tcp->tcp_non_sq_lock);
18069 
18070 	/*
18071 	 * determine if anything to send (Nagle).
18072 	 *
18073 	 *   1. len < tcp_mss (i.e. small)
18074 	 *   2. unacknowledged data present
18075 	 *   3. len < nagle limit
18076 	 *   4. last packet sent < nagle limit (previous packet sent)
18077 	 */
18078 	if ((len < mss) && (snxt != suna) &&
18079 	    (len < (int)tcp->tcp_naglim) &&
18080 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
18081 		/*
18082 		 * This was the first unsent packet and normally
18083 		 * mss < xmit_hiwater so there is no need to worry
18084 		 * about flow control. The next packet will go
18085 		 * through the flow control check in tcp_wput_data().
18086 		 */
18087 		/* leftover work from above */
18088 		tcp->tcp_unsent = len;
18089 		tcp->tcp_xmit_tail_unsent = len;
18090 
18091 		return;
18092 	}
18093 
18094 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
18095 
18096 	if (snxt == suna) {
18097 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18098 	}
18099 
18100 	/* we have always sent something */
18101 	tcp->tcp_rack_cnt = 0;
18102 
18103 	tcp->tcp_snxt = snxt + len;
18104 	tcp->tcp_rack = tcp->tcp_rnxt;
18105 
18106 	if ((mp1 = dupb(mp)) == 0)
18107 		goto no_memory;
18108 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
18109 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
18110 
18111 	/* adjust tcp header information */
18112 	tcph = tcp->tcp_tcph;
18113 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
18114 
18115 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
18116 	sum = (sum >> 16) + (sum & 0xFFFF);
18117 	U16_TO_ABE16(sum, tcph->th_sum);
18118 
18119 	U32_TO_ABE32(snxt, tcph->th_seq);
18120 
18121 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
18122 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
18123 	BUMP_LOCAL(tcp->tcp_obsegs);
18124 
18125 	/* Update the latest receive window size in TCP header. */
18126 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18127 	    tcph->th_win);
18128 
18129 	tcp->tcp_last_sent_len = (ushort_t)len;
18130 
18131 	plen = len + tcp->tcp_hdr_len;
18132 
18133 	if (tcp->tcp_ipversion == IPV4_VERSION) {
18134 		tcp->tcp_ipha->ipha_length = htons(plen);
18135 	} else {
18136 		tcp->tcp_ip6h->ip6_plen = htons(plen -
18137 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
18138 	}
18139 
18140 	/* see if we need to allocate a mblk for the headers */
18141 	hdrlen = tcp->tcp_hdr_len;
18142 	rptr = mp1->b_rptr - hdrlen;
18143 	db = mp1->b_datap;
18144 	if ((db->db_ref != 2) || rptr < db->db_base ||
18145 	    (!OK_32PTR(rptr))) {
18146 		/* NOTE: we assume allocb returns an OK_32PTR */
18147 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
18148 		    tcps->tcps_wroff_xtra, BPRI_MED);
18149 		if (!mp) {
18150 			freemsg(mp1);
18151 			goto no_memory;
18152 		}
18153 		mp->b_cont = mp1;
18154 		mp1 = mp;
18155 		/* Leave room for Link Level header */
18156 		/* hdrlen = tcp->tcp_hdr_len; */
18157 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
18158 		mp1->b_wptr = &rptr[hdrlen];
18159 	}
18160 	mp1->b_rptr = rptr;
18161 
18162 	/* Fill in the timestamp option. */
18163 	if (tcp->tcp_snd_ts_ok) {
18164 		U32_TO_BE32((uint32_t)lbolt,
18165 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
18166 		U32_TO_BE32(tcp->tcp_ts_recent,
18167 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
18168 	} else {
18169 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18170 	}
18171 
18172 	/* copy header into outgoing packet */
18173 	dst = (ipaddr_t *)rptr;
18174 	src = (ipaddr_t *)tcp->tcp_iphc;
18175 	dst[0] = src[0];
18176 	dst[1] = src[1];
18177 	dst[2] = src[2];
18178 	dst[3] = src[3];
18179 	dst[4] = src[4];
18180 	dst[5] = src[5];
18181 	dst[6] = src[6];
18182 	dst[7] = src[7];
18183 	dst[8] = src[8];
18184 	dst[9] = src[9];
18185 	if (hdrlen -= 40) {
18186 		hdrlen >>= 2;
18187 		dst += 10;
18188 		src += 10;
18189 		do {
18190 			*dst++ = *src++;
18191 		} while (--hdrlen);
18192 	}
18193 
18194 	/*
18195 	 * Set the ECN info in the TCP header.  Note that this
18196 	 * is not the template header.
18197 	 */
18198 	if (tcp->tcp_ecn_ok) {
18199 		SET_ECT(tcp, rptr);
18200 
18201 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18202 		if (tcp->tcp_ecn_echo_on)
18203 			tcph->th_flags[0] |= TH_ECE;
18204 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18205 			tcph->th_flags[0] |= TH_CWR;
18206 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18207 		}
18208 	}
18209 
18210 	if (tcp->tcp_ip_forward_progress) {
18211 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
18212 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
18213 		tcp->tcp_ip_forward_progress = B_FALSE;
18214 	}
18215 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
18216 	return;
18217 
18218 	/*
18219 	 * If we ran out of memory, we pretend to have sent the packet
18220 	 * and that it was lost on the wire.
18221 	 */
18222 no_memory:
18223 	return;
18224 
18225 slow:
18226 	/* leftover work from above */
18227 	tcp->tcp_unsent = len;
18228 	tcp->tcp_xmit_tail_unsent = len;
18229 	tcp_wput_data(tcp, NULL, B_FALSE);
18230 }
18231 
18232 /*
18233  * The function called through squeue to get behind eager's perimeter to
18234  * finish the accept processing.
18235  */
18236 /* ARGSUSED */
18237 void
18238 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
18239 {
18240 	conn_t			*connp = (conn_t *)arg;
18241 	tcp_t			*tcp = connp->conn_tcp;
18242 	queue_t			*q = tcp->tcp_rq;
18243 	mblk_t			*mp1;
18244 	mblk_t			*stropt_mp = mp;
18245 	struct  stroptions	*stropt;
18246 	uint_t			thwin;
18247 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18248 
18249 	/*
18250 	 * Drop the eager's ref on the listener, that was placed when
18251 	 * this eager began life in tcp_conn_request.
18252 	 */
18253 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
18254 
18255 	tcp->tcp_detached = B_FALSE;
18256 
18257 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
18258 		/*
18259 		 * Someone blewoff the eager before we could finish
18260 		 * the accept.
18261 		 *
18262 		 * The only reason eager exists it because we put in
18263 		 * a ref on it when conn ind went up. We need to send
18264 		 * a disconnect indication up while the last reference
18265 		 * on the eager will be dropped by the squeue when we
18266 		 * return.
18267 		 */
18268 		ASSERT(tcp->tcp_listener == NULL);
18269 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
18270 			struct	T_discon_ind	*tdi;
18271 
18272 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
18273 			/*
18274 			 * Let us reuse the incoming mblk to avoid memory
18275 			 * allocation failure problems. We know that the
18276 			 * size of the incoming mblk i.e. stroptions is greater
18277 			 * than sizeof T_discon_ind. So the reallocb below
18278 			 * can't fail.
18279 			 */
18280 			freemsg(mp->b_cont);
18281 			mp->b_cont = NULL;
18282 			ASSERT(DB_REF(mp) == 1);
18283 			mp = reallocb(mp, sizeof (struct T_discon_ind),
18284 			    B_FALSE);
18285 			ASSERT(mp != NULL);
18286 			DB_TYPE(mp) = M_PROTO;
18287 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
18288 			tdi = (struct T_discon_ind *)mp->b_rptr;
18289 			if (tcp->tcp_issocket) {
18290 				tdi->DISCON_reason = ECONNREFUSED;
18291 				tdi->SEQ_number = 0;
18292 			} else {
18293 				tdi->DISCON_reason = ENOPROTOOPT;
18294 				tdi->SEQ_number =
18295 				    tcp->tcp_conn_req_seqnum;
18296 			}
18297 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
18298 			putnext(q, mp);
18299 		} else {
18300 			freemsg(mp);
18301 		}
18302 		if (tcp->tcp_hard_binding) {
18303 			tcp->tcp_hard_binding = B_FALSE;
18304 			tcp->tcp_hard_bound = B_TRUE;
18305 		}
18306 		return;
18307 	}
18308 
18309 	mp1 = stropt_mp->b_cont;
18310 	stropt_mp->b_cont = NULL;
18311 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
18312 	stropt = (struct stroptions *)stropt_mp->b_rptr;
18313 
18314 	while (mp1 != NULL) {
18315 		mp = mp1;
18316 		mp1 = mp1->b_cont;
18317 		mp->b_cont = NULL;
18318 		tcp->tcp_drop_opt_ack_cnt++;
18319 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
18320 	}
18321 	mp = NULL;
18322 
18323 	/*
18324 	 * For a loopback connection with tcp_direct_sockfs on, note that
18325 	 * we don't have to protect tcp_rcv_list yet because synchronous
18326 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
18327 	 * possibly race with us.
18328 	 */
18329 
18330 	/*
18331 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
18332 	 * properly.  This is the first time we know of the acceptor'
18333 	 * queue.  So we do it here.
18334 	 */
18335 	if (tcp->tcp_rcv_list == NULL) {
18336 		/*
18337 		 * Recv queue is empty, tcp_rwnd should not have changed.
18338 		 * That means it should be equal to the listener's tcp_rwnd.
18339 		 */
18340 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
18341 	} else {
18342 #ifdef DEBUG
18343 		uint_t cnt = 0;
18344 
18345 		mp1 = tcp->tcp_rcv_list;
18346 		while ((mp = mp1) != NULL) {
18347 			mp1 = mp->b_next;
18348 			cnt += msgdsize(mp);
18349 		}
18350 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
18351 #endif
18352 		/* There is some data, add them back to get the max. */
18353 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18354 	}
18355 	/*
18356 	 * This is the first time we run on the correct
18357 	 * queue after tcp_accept. So fix all the q parameters
18358 	 * here.
18359 	 */
18360 	stropt->so_flags = SO_HIWAT | SO_MAXBLK | SO_WROFF;
18361 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
18362 
18363 	/*
18364 	 * Record the stream head's high water mark for this endpoint;
18365 	 * this is used for flow-control purposes.
18366 	 */
18367 	stropt->so_hiwat = tcp->tcp_fused ?
18368 	    tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat) :
18369 	    MAX(q->q_hiwat, tcps->tcps_sth_rcv_hiwat);
18370 
18371 	/*
18372 	 * Determine what write offset value to use depending on SACK and
18373 	 * whether the endpoint is fused or not.
18374 	 */
18375 	if (tcp->tcp_fused) {
18376 		ASSERT(tcp->tcp_loopback);
18377 		ASSERT(tcp->tcp_loopback_peer != NULL);
18378 		/*
18379 		 * For fused tcp loopback, set the stream head's write
18380 		 * offset value to zero since we won't be needing any room
18381 		 * for TCP/IP headers.  This would also improve performance
18382 		 * since it would reduce the amount of work done by kmem.
18383 		 * Non-fused tcp loopback case is handled separately below.
18384 		 */
18385 		stropt->so_wroff = 0;
18386 		/*
18387 		 * Update the peer's transmit parameters according to
18388 		 * our recently calculated high water mark value.
18389 		 */
18390 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18391 	} else if (tcp->tcp_snd_sack_ok) {
18392 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18393 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18394 	} else {
18395 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18396 		    tcps->tcps_wroff_xtra);
18397 	}
18398 
18399 	/*
18400 	 * If this is endpoint is handling SSL, then reserve extra
18401 	 * offset and space at the end.
18402 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18403 	 * overriding the previous setting. The extra cost of signing and
18404 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18405 	 * instead of a single contiguous one by the stream head
18406 	 * largely outweighs the statistical reduction of ACKs, when
18407 	 * applicable. The peer will also save on decryption and verification
18408 	 * costs.
18409 	 */
18410 	if (tcp->tcp_kssl_ctx != NULL) {
18411 		stropt->so_wroff += SSL3_WROFFSET;
18412 
18413 		stropt->so_flags |= SO_TAIL;
18414 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
18415 
18416 		stropt->so_flags |= SO_COPYOPT;
18417 		stropt->so_copyopt = ZCVMUNSAFE;
18418 
18419 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
18420 	}
18421 
18422 	/* Send the options up */
18423 	putnext(q, stropt_mp);
18424 
18425 	/*
18426 	 * Pass up any data and/or a fin that has been received.
18427 	 *
18428 	 * Adjust receive window in case it had decreased
18429 	 * (because there is data <=> tcp_rcv_list != NULL)
18430 	 * while the connection was detached. Note that
18431 	 * in case the eager was flow-controlled, w/o this
18432 	 * code, the rwnd may never open up again!
18433 	 */
18434 	if (tcp->tcp_rcv_list != NULL) {
18435 		/* We drain directly in case of fused tcp loopback */
18436 		sodirect_t *sodp;
18437 
18438 		if (!tcp->tcp_fused && canputnext(q)) {
18439 			tcp->tcp_rwnd = q->q_hiwat;
18440 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
18441 			    << tcp->tcp_rcv_ws;
18442 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
18443 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18444 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
18445 				tcp_xmit_ctl(NULL,
18446 				    tcp, (tcp->tcp_swnd == 0) ?
18447 				    tcp->tcp_suna : tcp->tcp_snxt,
18448 				    tcp->tcp_rnxt, TH_ACK);
18449 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
18450 			}
18451 
18452 		}
18453 
18454 		SOD_PTR_ENTER(tcp, sodp);
18455 		if (sodp != NULL) {
18456 			/* Sodirect, move from rcv_list */
18457 			ASSERT(!tcp->tcp_fused);
18458 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18459 				tcp->tcp_rcv_list = mp->b_next;
18460 				mp->b_next = NULL;
18461 				(void) tcp_rcv_sod_enqueue(tcp, sodp, mp,
18462 				    msgdsize(mp));
18463 			}
18464 			tcp->tcp_rcv_last_head = NULL;
18465 			tcp->tcp_rcv_last_tail = NULL;
18466 			tcp->tcp_rcv_cnt = 0;
18467 			(void) tcp_rcv_sod_wakeup(tcp, sodp);
18468 			/* sod_wakeup() did the mutex_exit() */
18469 		} else {
18470 			/* Not sodirect, drain */
18471 			(void) tcp_rcv_drain(q, tcp);
18472 		}
18473 
18474 		/*
18475 		 * For fused tcp loopback, back-enable peer endpoint
18476 		 * if it's currently flow-controlled.
18477 		 */
18478 		if (tcp->tcp_fused) {
18479 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18480 
18481 			ASSERT(peer_tcp != NULL);
18482 			ASSERT(peer_tcp->tcp_fused);
18483 			/*
18484 			 * In order to change the peer's tcp_flow_stopped,
18485 			 * we need to take locks for both end points. The
18486 			 * highest address is taken first.
18487 			 */
18488 			if (peer_tcp > tcp) {
18489 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18490 				mutex_enter(&tcp->tcp_non_sq_lock);
18491 			} else {
18492 				mutex_enter(&tcp->tcp_non_sq_lock);
18493 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18494 			}
18495 			if (peer_tcp->tcp_flow_stopped) {
18496 				tcp_clrqfull(peer_tcp);
18497 				TCP_STAT(tcps, tcp_fusion_backenabled);
18498 			}
18499 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18500 			mutex_exit(&tcp->tcp_non_sq_lock);
18501 		}
18502 	}
18503 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18504 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18505 		mp = tcp->tcp_ordrel_mp;
18506 		tcp->tcp_ordrel_mp = NULL;
18507 		tcp->tcp_ordrel_done = B_TRUE;
18508 		putnext(q, mp);
18509 	}
18510 	if (tcp->tcp_hard_binding) {
18511 		tcp->tcp_hard_binding = B_FALSE;
18512 		tcp->tcp_hard_bound = B_TRUE;
18513 	}
18514 
18515 	/* We can enable synchronous streams now */
18516 	if (tcp->tcp_fused) {
18517 		tcp_fuse_syncstr_enable_pair(tcp);
18518 	}
18519 
18520 	if (tcp->tcp_ka_enabled) {
18521 		tcp->tcp_ka_last_intrvl = 0;
18522 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18523 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18524 	}
18525 
18526 	/*
18527 	 * At this point, eager is fully established and will
18528 	 * have the following references -
18529 	 *
18530 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18531 	 * 1 reference for the squeue which will be dropped by the squeue as
18532 	 *	soon as this function returns.
18533 	 * There will be 1 additonal reference for being in classifier
18534 	 *	hash list provided something bad hasn't happened.
18535 	 */
18536 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18537 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18538 }
18539 
18540 /*
18541  * The function called through squeue to get behind listener's perimeter to
18542  * send a deffered conn_ind.
18543  */
18544 /* ARGSUSED */
18545 void
18546 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18547 {
18548 	conn_t	*connp = (conn_t *)arg;
18549 	tcp_t *listener = connp->conn_tcp;
18550 
18551 	if (listener->tcp_state == TCPS_CLOSED ||
18552 	    TCP_IS_DETACHED(listener)) {
18553 		/*
18554 		 * If listener has closed, it would have caused a
18555 		 * a cleanup/blowoff to happen for the eager.
18556 		 */
18557 		tcp_t *tcp;
18558 		struct T_conn_ind	*conn_ind;
18559 
18560 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18561 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18562 		    conn_ind->OPT_length);
18563 		/*
18564 		 * We need to drop the ref on eager that was put
18565 		 * tcp_rput_data() before trying to send the conn_ind
18566 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18567 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18568 		 * listener is closed so we drop the ref.
18569 		 */
18570 		CONN_DEC_REF(tcp->tcp_connp);
18571 		freemsg(mp);
18572 		return;
18573 	}
18574 	putnext(listener->tcp_rq, mp);
18575 }
18576 
18577 
18578 /*
18579  * This is the STREAMS entry point for T_CONN_RES coming down on
18580  * Acceptor STREAM when  sockfs listener does accept processing.
18581  * Read the block comment on top of tcp_conn_request().
18582  */
18583 void
18584 tcp_wput_accept(queue_t *q, mblk_t *mp)
18585 {
18586 	queue_t *rq = RD(q);
18587 	struct T_conn_res *conn_res;
18588 	tcp_t *eager;
18589 	tcp_t *listener;
18590 	struct T_ok_ack *ok;
18591 	t_scalar_t PRIM_type;
18592 	mblk_t *opt_mp;
18593 	conn_t *econnp;
18594 
18595 	ASSERT(DB_TYPE(mp) == M_PROTO);
18596 
18597 	conn_res = (struct T_conn_res *)mp->b_rptr;
18598 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18599 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18600 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18601 		if (mp != NULL)
18602 			putnext(rq, mp);
18603 		return;
18604 	}
18605 	switch (conn_res->PRIM_type) {
18606 	case O_T_CONN_RES:
18607 	case T_CONN_RES:
18608 		/*
18609 		 * We pass up an err ack if allocb fails. This will
18610 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18611 		 * tcp_eager_blowoff to be called. sockfs will then call
18612 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18613 		 * we need to do the allocb up here because we have to
18614 		 * make sure rq->q_qinfo->qi_qclose still points to the
18615 		 * correct function (tcpclose_accept) in case allocb
18616 		 * fails.
18617 		 */
18618 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18619 		if (opt_mp == NULL) {
18620 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18621 			if (mp != NULL)
18622 				putnext(rq, mp);
18623 			return;
18624 		}
18625 
18626 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18627 		    &eager, conn_res->OPT_length);
18628 		PRIM_type = conn_res->PRIM_type;
18629 		mp->b_datap->db_type = M_PCPROTO;
18630 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18631 		ok = (struct T_ok_ack *)mp->b_rptr;
18632 		ok->PRIM_type = T_OK_ACK;
18633 		ok->CORRECT_prim = PRIM_type;
18634 		econnp = eager->tcp_connp;
18635 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18636 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18637 		eager->tcp_rq = rq;
18638 		eager->tcp_wq = q;
18639 		rq->q_ptr = econnp;
18640 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18641 		q->q_ptr = econnp;
18642 		q->q_qinfo = &tcp_winit;
18643 		listener = eager->tcp_listener;
18644 		eager->tcp_issocket = B_TRUE;
18645 
18646 		/*
18647 		 * TCP is _D_SODIRECT and sockfs is directly above so
18648 		 * save shared sodirect_t pointer (if any).
18649 		 *
18650 		 * If tcp_fused and sodirect enabled disable it.
18651 		 */
18652 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18653 		if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18654 			/* Fused, disable sodirect */
18655 			mutex_enter(eager->tcp_sodirect->sod_lockp);
18656 			SOD_DISABLE(eager->tcp_sodirect);
18657 			mutex_exit(eager->tcp_sodirect->sod_lockp);
18658 			eager->tcp_sodirect = NULL;
18659 		}
18660 
18661 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18662 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18663 		ASSERT(econnp->conn_netstack ==
18664 		    listener->tcp_connp->conn_netstack);
18665 		ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18666 
18667 		/* Put the ref for IP */
18668 		CONN_INC_REF(econnp);
18669 
18670 		/*
18671 		 * We should have minimum of 3 references on the conn
18672 		 * at this point. One each for TCP and IP and one for
18673 		 * the T_conn_ind that was sent up when the 3-way handshake
18674 		 * completed. In the normal case we would also have another
18675 		 * reference (making a total of 4) for the conn being in the
18676 		 * classifier hash list. However the eager could have received
18677 		 * an RST subsequently and tcp_closei_local could have removed
18678 		 * the eager from the classifier hash list, hence we can't
18679 		 * assert that reference.
18680 		 */
18681 		ASSERT(econnp->conn_ref >= 3);
18682 
18683 		/*
18684 		 * Send the new local address also up to sockfs. There
18685 		 * should already be enough space in the mp that came
18686 		 * down from soaccept().
18687 		 */
18688 		if (eager->tcp_family == AF_INET) {
18689 			sin_t *sin;
18690 
18691 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18692 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18693 			sin = (sin_t *)mp->b_wptr;
18694 			mp->b_wptr += sizeof (sin_t);
18695 			sin->sin_family = AF_INET;
18696 			sin->sin_port = eager->tcp_lport;
18697 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18698 		} else {
18699 			sin6_t *sin6;
18700 
18701 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18702 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18703 			sin6 = (sin6_t *)mp->b_wptr;
18704 			mp->b_wptr += sizeof (sin6_t);
18705 			sin6->sin6_family = AF_INET6;
18706 			sin6->sin6_port = eager->tcp_lport;
18707 			if (eager->tcp_ipversion == IPV4_VERSION) {
18708 				sin6->sin6_flowinfo = 0;
18709 				IN6_IPADDR_TO_V4MAPPED(
18710 				    eager->tcp_ipha->ipha_src,
18711 				    &sin6->sin6_addr);
18712 			} else {
18713 				ASSERT(eager->tcp_ip6h != NULL);
18714 				sin6->sin6_flowinfo =
18715 				    eager->tcp_ip6h->ip6_vcf &
18716 				    ~IPV6_VERS_AND_FLOW_MASK;
18717 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18718 			}
18719 			sin6->sin6_scope_id = 0;
18720 			sin6->__sin6_src_id = 0;
18721 		}
18722 
18723 		putnext(rq, mp);
18724 
18725 		opt_mp->b_datap->db_type = M_SETOPTS;
18726 		opt_mp->b_wptr += sizeof (struct stroptions);
18727 
18728 		/*
18729 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18730 		 * from listener to acceptor. The message is chained on the
18731 		 * bind_mp which tcp_rput_other will send down to IP.
18732 		 */
18733 		if (listener->tcp_bound_if != 0) {
18734 			/* allocate optmgmt req */
18735 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18736 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18737 			    sizeof (int));
18738 			if (mp != NULL)
18739 				linkb(opt_mp, mp);
18740 		}
18741 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18742 			uint_t on = 1;
18743 
18744 			/* allocate optmgmt req */
18745 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18746 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18747 			if (mp != NULL)
18748 				linkb(opt_mp, mp);
18749 		}
18750 
18751 
18752 		mutex_enter(&listener->tcp_eager_lock);
18753 
18754 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18755 
18756 			tcp_t *tail;
18757 			tcp_t *tcp;
18758 			mblk_t *mp1;
18759 
18760 			tcp = listener->tcp_eager_prev_q0;
18761 			/*
18762 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18763 			 * deferred T_conn_ind queue. We need to get to the head
18764 			 * of the queue in order to send up T_conn_ind the same
18765 			 * order as how the 3WHS is completed.
18766 			 */
18767 			while (tcp != listener) {
18768 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18769 				    !tcp->tcp_kssl_pending)
18770 					break;
18771 				else
18772 					tcp = tcp->tcp_eager_prev_q0;
18773 			}
18774 			/* None of the pending eagers can be sent up now */
18775 			if (tcp == listener)
18776 				goto no_more_eagers;
18777 
18778 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18779 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18780 			/* Move from q0 to q */
18781 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18782 			listener->tcp_conn_req_cnt_q0--;
18783 			listener->tcp_conn_req_cnt_q++;
18784 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18785 			    tcp->tcp_eager_prev_q0;
18786 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18787 			    tcp->tcp_eager_next_q0;
18788 			tcp->tcp_eager_prev_q0 = NULL;
18789 			tcp->tcp_eager_next_q0 = NULL;
18790 			tcp->tcp_conn_def_q0 = B_FALSE;
18791 
18792 			/* Make sure the tcp isn't in the list of droppables */
18793 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18794 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18795 
18796 			/*
18797 			 * Insert at end of the queue because sockfs sends
18798 			 * down T_CONN_RES in chronological order. Leaving
18799 			 * the older conn indications at front of the queue
18800 			 * helps reducing search time.
18801 			 */
18802 			tail = listener->tcp_eager_last_q;
18803 			if (tail != NULL) {
18804 				tail->tcp_eager_next_q = tcp;
18805 			} else {
18806 				listener->tcp_eager_next_q = tcp;
18807 			}
18808 			listener->tcp_eager_last_q = tcp;
18809 			tcp->tcp_eager_next_q = NULL;
18810 
18811 			/* Need to get inside the listener perimeter */
18812 			CONN_INC_REF(listener->tcp_connp);
18813 			SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
18814 			    tcp_send_pending, listener->tcp_connp,
18815 			    SQ_FILL, SQTAG_TCP_SEND_PENDING);
18816 		}
18817 no_more_eagers:
18818 		tcp_eager_unlink(eager);
18819 		mutex_exit(&listener->tcp_eager_lock);
18820 
18821 		/*
18822 		 * At this point, the eager is detached from the listener
18823 		 * but we still have an extra refs on eager (apart from the
18824 		 * usual tcp references). The ref was placed in tcp_rput_data
18825 		 * before sending the conn_ind in tcp_send_conn_ind.
18826 		 * The ref will be dropped in tcp_accept_finish(). As sockfs
18827 		 * has already established this tcp with it's own stream,
18828 		 * it's OK to set tcp_detached to B_FALSE.
18829 		 */
18830 		econnp->conn_tcp->tcp_detached = B_FALSE;
18831 		SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
18832 		    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
18833 		return;
18834 	default:
18835 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18836 		if (mp != NULL)
18837 			putnext(rq, mp);
18838 		return;
18839 	}
18840 }
18841 
18842 static int
18843 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18844 {
18845 	sin_t *sin = (sin_t *)sa;
18846 	sin6_t *sin6 = (sin6_t *)sa;
18847 
18848 	switch (tcp->tcp_family) {
18849 	case AF_INET:
18850 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18851 
18852 		if (*salenp < sizeof (sin_t))
18853 			return (EINVAL);
18854 
18855 		*sin = sin_null;
18856 		sin->sin_family = AF_INET;
18857 		sin->sin_port = tcp->tcp_lport;
18858 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18859 		break;
18860 
18861 	case AF_INET6:
18862 		if (*salenp < sizeof (sin6_t))
18863 			return (EINVAL);
18864 
18865 		*sin6 = sin6_null;
18866 		sin6->sin6_family = AF_INET6;
18867 		sin6->sin6_port = tcp->tcp_lport;
18868 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18869 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18870 			    &sin6->sin6_addr);
18871 		} else {
18872 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18873 		}
18874 		break;
18875 	}
18876 
18877 	return (0);
18878 }
18879 
18880 static int
18881 tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18882 {
18883 	sin_t *sin = (sin_t *)sa;
18884 	sin6_t *sin6 = (sin6_t *)sa;
18885 
18886 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18887 		return (ENOTCONN);
18888 
18889 	switch (tcp->tcp_family) {
18890 	case AF_INET:
18891 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18892 
18893 		if (*salenp < sizeof (sin_t))
18894 			return (EINVAL);
18895 
18896 		*sin = sin_null;
18897 		sin->sin_family = AF_INET;
18898 		sin->sin_port = tcp->tcp_fport;
18899 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18900 		    sin->sin_addr.s_addr);
18901 		break;
18902 
18903 	case AF_INET6:
18904 		if (*salenp < sizeof (sin6_t))
18905 			return (EINVAL);
18906 
18907 		*sin6 = sin6_null;
18908 		sin6->sin6_family = AF_INET6;
18909 		sin6->sin6_port = tcp->tcp_fport;
18910 		sin6->sin6_addr = tcp->tcp_remote_v6;
18911 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18912 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18913 			    ~IPV6_VERS_AND_FLOW_MASK;
18914 		}
18915 		break;
18916 	}
18917 
18918 	return (0);
18919 }
18920 
18921 /*
18922  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18923  */
18924 static void
18925 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18926 {
18927 	void	*data;
18928 	mblk_t	*datamp = mp->b_cont;
18929 	tcp_t	*tcp = Q_TO_TCP(q);
18930 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18931 
18932 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18933 		cmdp->cb_error = EPROTO;
18934 		qreply(q, mp);
18935 		return;
18936 	}
18937 
18938 	data = datamp->b_rptr;
18939 
18940 	switch (cmdp->cb_cmd) {
18941 	case TI_GETPEERNAME:
18942 		cmdp->cb_error = tcp_getpeername(tcp, data, &cmdp->cb_len);
18943 		break;
18944 	case TI_GETMYNAME:
18945 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
18946 		break;
18947 	default:
18948 		cmdp->cb_error = EINVAL;
18949 		break;
18950 	}
18951 
18952 	qreply(q, mp);
18953 }
18954 
18955 void
18956 tcp_wput(queue_t *q, mblk_t *mp)
18957 {
18958 	conn_t	*connp = Q_TO_CONN(q);
18959 	tcp_t	*tcp;
18960 	void (*output_proc)();
18961 	t_scalar_t type;
18962 	uchar_t *rptr;
18963 	struct iocblk	*iocp;
18964 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18965 
18966 	ASSERT(connp->conn_ref >= 2);
18967 
18968 	switch (DB_TYPE(mp)) {
18969 	case M_DATA:
18970 		tcp = connp->conn_tcp;
18971 		ASSERT(tcp != NULL);
18972 
18973 		mutex_enter(&tcp->tcp_non_sq_lock);
18974 		tcp->tcp_squeue_bytes += msgdsize(mp);
18975 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18976 			tcp_setqfull(tcp);
18977 		}
18978 		mutex_exit(&tcp->tcp_non_sq_lock);
18979 
18980 		CONN_INC_REF(connp);
18981 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18982 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18983 		return;
18984 
18985 	case M_CMD:
18986 		tcp_wput_cmdblk(q, mp);
18987 		return;
18988 
18989 	case M_PROTO:
18990 	case M_PCPROTO:
18991 		/*
18992 		 * if it is a snmp message, don't get behind the squeue
18993 		 */
18994 		tcp = connp->conn_tcp;
18995 		rptr = mp->b_rptr;
18996 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18997 			type = ((union T_primitives *)rptr)->type;
18998 		} else {
18999 			if (tcp->tcp_debug) {
19000 				(void) strlog(TCP_MOD_ID, 0, 1,
19001 				    SL_ERROR|SL_TRACE,
19002 				    "tcp_wput_proto, dropping one...");
19003 			}
19004 			freemsg(mp);
19005 			return;
19006 		}
19007 		if (type == T_SVR4_OPTMGMT_REQ) {
19008 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
19009 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
19010 			    cr)) {
19011 				/*
19012 				 * This was a SNMP request
19013 				 */
19014 				return;
19015 			} else {
19016 				output_proc = tcp_wput_proto;
19017 			}
19018 		} else {
19019 			output_proc = tcp_wput_proto;
19020 		}
19021 		break;
19022 	case M_IOCTL:
19023 		/*
19024 		 * Most ioctls can be processed right away without going via
19025 		 * squeues - process them right here. Those that do require
19026 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
19027 		 * are processed by tcp_wput_ioctl().
19028 		 */
19029 		iocp = (struct iocblk *)mp->b_rptr;
19030 		tcp = connp->conn_tcp;
19031 
19032 		switch (iocp->ioc_cmd) {
19033 		case TCP_IOC_ABORT_CONN:
19034 			tcp_ioctl_abort_conn(q, mp);
19035 			return;
19036 		case TI_GETPEERNAME:
19037 		case TI_GETMYNAME:
19038 			mi_copyin(q, mp, NULL,
19039 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
19040 			return;
19041 		case ND_SET:
19042 			/* nd_getset does the necessary checks */
19043 		case ND_GET:
19044 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
19045 				CALL_IP_WPUT(connp, q, mp);
19046 				return;
19047 			}
19048 			qreply(q, mp);
19049 			return;
19050 		case TCP_IOC_DEFAULT_Q:
19051 			/*
19052 			 * Wants to be the default wq. Check the credentials
19053 			 * first, the rest is executed via squeue.
19054 			 */
19055 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19056 				iocp->ioc_error = EPERM;
19057 				iocp->ioc_count = 0;
19058 				mp->b_datap->db_type = M_IOCACK;
19059 				qreply(q, mp);
19060 				return;
19061 			}
19062 			output_proc = tcp_wput_ioctl;
19063 			break;
19064 		default:
19065 			output_proc = tcp_wput_ioctl;
19066 			break;
19067 		}
19068 		break;
19069 	default:
19070 		output_proc = tcp_wput_nondata;
19071 		break;
19072 	}
19073 
19074 	CONN_INC_REF(connp);
19075 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
19076 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
19077 }
19078 
19079 /*
19080  * Initial STREAMS write side put() procedure for sockets. It tries to
19081  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
19082  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
19083  * are handled by tcp_wput() as usual.
19084  *
19085  * All further messages will also be handled by tcp_wput() because we cannot
19086  * be sure that the above short cut is safe later.
19087  */
19088 static void
19089 tcp_wput_sock(queue_t *wq, mblk_t *mp)
19090 {
19091 	conn_t			*connp = Q_TO_CONN(wq);
19092 	tcp_t			*tcp = connp->conn_tcp;
19093 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
19094 
19095 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
19096 	wq->q_qinfo = &tcp_winit;
19097 
19098 	ASSERT(IPCL_IS_TCP(connp));
19099 	ASSERT(TCP_IS_SOCKET(tcp));
19100 
19101 	if (DB_TYPE(mp) == M_PCPROTO &&
19102 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
19103 	    car->PRIM_type == T_CAPABILITY_REQ) {
19104 		tcp_capability_req(tcp, mp);
19105 		return;
19106 	}
19107 
19108 	tcp_wput(wq, mp);
19109 }
19110 
19111 static boolean_t
19112 tcp_zcopy_check(tcp_t *tcp)
19113 {
19114 	conn_t	*connp = tcp->tcp_connp;
19115 	ire_t	*ire;
19116 	boolean_t	zc_enabled = B_FALSE;
19117 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19118 
19119 	if (do_tcpzcopy == 2)
19120 		zc_enabled = B_TRUE;
19121 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
19122 	    IPCL_IS_CONNECTED(connp) &&
19123 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
19124 	    connp->conn_dontroute == 0 &&
19125 	    !connp->conn_nexthop_set &&
19126 	    connp->conn_outgoing_ill == NULL &&
19127 	    connp->conn_nofailover_ill == NULL &&
19128 	    do_tcpzcopy == 1) {
19129 		/*
19130 		 * the checks above  closely resemble the fast path checks
19131 		 * in tcp_send_data().
19132 		 */
19133 		mutex_enter(&connp->conn_lock);
19134 		ire = connp->conn_ire_cache;
19135 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19136 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19137 			IRE_REFHOLD(ire);
19138 			if (ire->ire_stq != NULL) {
19139 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
19140 
19141 				zc_enabled = ill && (ill->ill_capabilities &
19142 				    ILL_CAPAB_ZEROCOPY) &&
19143 				    (ill->ill_zerocopy_capab->
19144 				    ill_zerocopy_flags != 0);
19145 			}
19146 			IRE_REFRELE(ire);
19147 		}
19148 		mutex_exit(&connp->conn_lock);
19149 	}
19150 	tcp->tcp_snd_zcopy_on = zc_enabled;
19151 	if (!TCP_IS_DETACHED(tcp)) {
19152 		if (zc_enabled) {
19153 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
19154 			TCP_STAT(tcps, tcp_zcopy_on);
19155 		} else {
19156 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19157 			TCP_STAT(tcps, tcp_zcopy_off);
19158 		}
19159 	}
19160 	return (zc_enabled);
19161 }
19162 
19163 static mblk_t *
19164 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
19165 {
19166 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19167 
19168 	if (do_tcpzcopy == 2)
19169 		return (bp);
19170 	else if (tcp->tcp_snd_zcopy_on) {
19171 		tcp->tcp_snd_zcopy_on = B_FALSE;
19172 		if (!TCP_IS_DETACHED(tcp)) {
19173 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19174 			TCP_STAT(tcps, tcp_zcopy_disable);
19175 		}
19176 	}
19177 	return (tcp_zcopy_backoff(tcp, bp, 0));
19178 }
19179 
19180 /*
19181  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
19182  * the original desballoca'ed segmapped mblk.
19183  */
19184 static mblk_t *
19185 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
19186 {
19187 	mblk_t *head, *tail, *nbp;
19188 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19189 
19190 	if (IS_VMLOANED_MBLK(bp)) {
19191 		TCP_STAT(tcps, tcp_zcopy_backoff);
19192 		if ((head = copyb(bp)) == NULL) {
19193 			/* fail to backoff; leave it for the next backoff */
19194 			tcp->tcp_xmit_zc_clean = B_FALSE;
19195 			return (bp);
19196 		}
19197 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19198 			if (fix_xmitlist)
19199 				tcp_zcopy_notify(tcp);
19200 			else
19201 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19202 		}
19203 		nbp = bp->b_cont;
19204 		if (fix_xmitlist) {
19205 			head->b_prev = bp->b_prev;
19206 			head->b_next = bp->b_next;
19207 			if (tcp->tcp_xmit_tail == bp)
19208 				tcp->tcp_xmit_tail = head;
19209 		}
19210 		bp->b_next = NULL;
19211 		bp->b_prev = NULL;
19212 		freeb(bp);
19213 	} else {
19214 		head = bp;
19215 		nbp = bp->b_cont;
19216 	}
19217 	tail = head;
19218 	while (nbp) {
19219 		if (IS_VMLOANED_MBLK(nbp)) {
19220 			TCP_STAT(tcps, tcp_zcopy_backoff);
19221 			if ((tail->b_cont = copyb(nbp)) == NULL) {
19222 				tcp->tcp_xmit_zc_clean = B_FALSE;
19223 				tail->b_cont = nbp;
19224 				return (head);
19225 			}
19226 			tail = tail->b_cont;
19227 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19228 				if (fix_xmitlist)
19229 					tcp_zcopy_notify(tcp);
19230 				else
19231 					tail->b_datap->db_struioflag |=
19232 					    STRUIO_ZCNOTIFY;
19233 			}
19234 			bp = nbp;
19235 			nbp = nbp->b_cont;
19236 			if (fix_xmitlist) {
19237 				tail->b_prev = bp->b_prev;
19238 				tail->b_next = bp->b_next;
19239 				if (tcp->tcp_xmit_tail == bp)
19240 					tcp->tcp_xmit_tail = tail;
19241 			}
19242 			bp->b_next = NULL;
19243 			bp->b_prev = NULL;
19244 			freeb(bp);
19245 		} else {
19246 			tail->b_cont = nbp;
19247 			tail = nbp;
19248 			nbp = nbp->b_cont;
19249 		}
19250 	}
19251 	if (fix_xmitlist) {
19252 		tcp->tcp_xmit_last = tail;
19253 		tcp->tcp_xmit_zc_clean = B_TRUE;
19254 	}
19255 	return (head);
19256 }
19257 
19258 static void
19259 tcp_zcopy_notify(tcp_t *tcp)
19260 {
19261 	struct stdata	*stp;
19262 
19263 	if (tcp->tcp_detached)
19264 		return;
19265 	stp = STREAM(tcp->tcp_rq);
19266 	mutex_enter(&stp->sd_lock);
19267 	stp->sd_flag |= STZCNOTIFY;
19268 	cv_broadcast(&stp->sd_zcopy_wait);
19269 	mutex_exit(&stp->sd_lock);
19270 }
19271 
19272 static boolean_t
19273 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19274 {
19275 	ire_t	*ire;
19276 	conn_t	*connp = tcp->tcp_connp;
19277 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19278 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19279 
19280 	mutex_enter(&connp->conn_lock);
19281 	ire = connp->conn_ire_cache;
19282 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19283 
19284 	if ((ire != NULL) &&
19285 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19286 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19287 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19288 		IRE_REFHOLD(ire);
19289 		mutex_exit(&connp->conn_lock);
19290 	} else {
19291 		boolean_t cached = B_FALSE;
19292 		ts_label_t *tsl;
19293 
19294 		/* force a recheck later on */
19295 		tcp->tcp_ire_ill_check_done = B_FALSE;
19296 
19297 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19298 		connp->conn_ire_cache = NULL;
19299 		mutex_exit(&connp->conn_lock);
19300 
19301 		if (ire != NULL)
19302 			IRE_REFRELE_NOTR(ire);
19303 
19304 		tsl = crgetlabel(CONN_CRED(connp));
19305 		ire = (dst ?
19306 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19307 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19308 		    connp->conn_zoneid, tsl, ipst));
19309 
19310 		if (ire == NULL) {
19311 			TCP_STAT(tcps, tcp_ire_null);
19312 			return (B_FALSE);
19313 		}
19314 
19315 		IRE_REFHOLD_NOTR(ire);
19316 
19317 		mutex_enter(&connp->conn_lock);
19318 		if (CONN_CACHE_IRE(connp)) {
19319 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19320 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19321 				TCP_CHECK_IREINFO(tcp, ire);
19322 				connp->conn_ire_cache = ire;
19323 				cached = B_TRUE;
19324 			}
19325 			rw_exit(&ire->ire_bucket->irb_lock);
19326 		}
19327 		mutex_exit(&connp->conn_lock);
19328 
19329 		/*
19330 		 * We can continue to use the ire but since it was
19331 		 * not cached, we should drop the extra reference.
19332 		 */
19333 		if (!cached)
19334 			IRE_REFRELE_NOTR(ire);
19335 
19336 		/*
19337 		 * Rampart note: no need to select a new label here, since
19338 		 * labels are not allowed to change during the life of a TCP
19339 		 * connection.
19340 		 */
19341 	}
19342 
19343 	*irep = ire;
19344 
19345 	return (B_TRUE);
19346 }
19347 
19348 /*
19349  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19350  *
19351  * 0 = success;
19352  * 1 = failed to find ire and ill.
19353  */
19354 static boolean_t
19355 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19356 {
19357 	ipha_t		*ipha;
19358 	ipaddr_t	dst;
19359 	ire_t		*ire;
19360 	ill_t		*ill;
19361 	conn_t		*connp = tcp->tcp_connp;
19362 	mblk_t		*ire_fp_mp;
19363 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19364 
19365 	if (mp != NULL)
19366 		ipha = (ipha_t *)mp->b_rptr;
19367 	else
19368 		ipha = tcp->tcp_ipha;
19369 	dst = ipha->ipha_dst;
19370 
19371 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19372 		return (B_FALSE);
19373 
19374 	if ((ire->ire_flags & RTF_MULTIRT) ||
19375 	    (ire->ire_stq == NULL) ||
19376 	    (ire->ire_nce == NULL) ||
19377 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19378 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19379 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19380 		TCP_STAT(tcps, tcp_ip_ire_send);
19381 		IRE_REFRELE(ire);
19382 		return (B_FALSE);
19383 	}
19384 
19385 	ill = ire_to_ill(ire);
19386 	if (connp->conn_outgoing_ill != NULL) {
19387 		ill_t *conn_outgoing_ill = NULL;
19388 		/*
19389 		 * Choose a good ill in the group to send the packets on.
19390 		 */
19391 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
19392 		ill = ire_to_ill(ire);
19393 	}
19394 	ASSERT(ill != NULL);
19395 
19396 	if (!tcp->tcp_ire_ill_check_done) {
19397 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19398 		tcp->tcp_ire_ill_check_done = B_TRUE;
19399 	}
19400 
19401 	*irep = ire;
19402 	*illp = ill;
19403 
19404 	return (B_TRUE);
19405 }
19406 
19407 static void
19408 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19409 {
19410 	ipha_t		*ipha;
19411 	ipaddr_t	src;
19412 	ipaddr_t	dst;
19413 	uint32_t	cksum;
19414 	ire_t		*ire;
19415 	uint16_t	*up;
19416 	ill_t		*ill;
19417 	conn_t		*connp = tcp->tcp_connp;
19418 	uint32_t	hcksum_txflags = 0;
19419 	mblk_t		*ire_fp_mp;
19420 	uint_t		ire_fp_mp_len;
19421 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19422 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19423 
19424 	ASSERT(DB_TYPE(mp) == M_DATA);
19425 
19426 	if (DB_CRED(mp) == NULL)
19427 		mblk_setcred(mp, CONN_CRED(connp));
19428 
19429 	ipha = (ipha_t *)mp->b_rptr;
19430 	src = ipha->ipha_src;
19431 	dst = ipha->ipha_dst;
19432 
19433 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19434 
19435 	/*
19436 	 * Drop off fast path for IPv6 and also if options are present or
19437 	 * we need to resolve a TS label.
19438 	 */
19439 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19440 	    !IPCL_IS_CONNECTED(connp) ||
19441 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19442 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19443 	    !connp->conn_ulp_labeled ||
19444 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19445 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19446 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19447 		if (tcp->tcp_snd_zcopy_aware)
19448 			mp = tcp_zcopy_disable(tcp, mp);
19449 		TCP_STAT(tcps, tcp_ip_send);
19450 		CALL_IP_WPUT(connp, q, mp);
19451 		return;
19452 	}
19453 
19454 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19455 		if (tcp->tcp_snd_zcopy_aware)
19456 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19457 		CALL_IP_WPUT(connp, q, mp);
19458 		return;
19459 	}
19460 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19461 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19462 
19463 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19464 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19465 #ifndef _BIG_ENDIAN
19466 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19467 #endif
19468 
19469 	/*
19470 	 * Check to see if we need to re-enable LSO/MDT for this connection
19471 	 * because it was previously disabled due to changes in the ill;
19472 	 * note that by doing it here, this re-enabling only applies when
19473 	 * the packet is not dispatched through CALL_IP_WPUT().
19474 	 *
19475 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19476 	 * case, since that's how we ended up here.  For IPv6, we do the
19477 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19478 	 */
19479 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19480 		/*
19481 		 * Restore LSO for this connection, so that next time around
19482 		 * it is eligible to go through tcp_lsosend() path again.
19483 		 */
19484 		TCP_STAT(tcps, tcp_lso_enabled);
19485 		tcp->tcp_lso = B_TRUE;
19486 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19487 		    "interface %s\n", (void *)connp, ill->ill_name));
19488 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19489 		/*
19490 		 * Restore MDT for this connection, so that next time around
19491 		 * it is eligible to go through tcp_multisend() path again.
19492 		 */
19493 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19494 		tcp->tcp_mdt = B_TRUE;
19495 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19496 		    "interface %s\n", (void *)connp, ill->ill_name));
19497 	}
19498 
19499 	if (tcp->tcp_snd_zcopy_aware) {
19500 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19501 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19502 			mp = tcp_zcopy_disable(tcp, mp);
19503 		/*
19504 		 * we shouldn't need to reset ipha as the mp containing
19505 		 * ipha should never be a zero-copy mp.
19506 		 */
19507 	}
19508 
19509 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19510 		ASSERT(ill->ill_hcksum_capab != NULL);
19511 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19512 	}
19513 
19514 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19515 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19516 
19517 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19518 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19519 
19520 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19521 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19522 
19523 	/* Software checksum? */
19524 	if (DB_CKSUMFLAGS(mp) == 0) {
19525 		TCP_STAT(tcps, tcp_out_sw_cksum);
19526 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19527 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19528 	}
19529 
19530 	/* Calculate IP header checksum if hardware isn't capable */
19531 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19532 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19533 		    ((uint16_t *)ipha)[4]);
19534 	}
19535 
19536 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19537 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19538 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19539 
19540 	UPDATE_OB_PKT_COUNT(ire);
19541 	ire->ire_last_used_time = lbolt;
19542 
19543 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19544 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19545 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19546 	    ntohs(ipha->ipha_length));
19547 
19548 	DTRACE_PROBE4(ip4__physical__out__start,
19549 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
19550 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
19551 	    ipst->ips_ipv4firewall_physical_out,
19552 	    NULL, ill, ipha, mp, mp, 0, ipst);
19553 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19554 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
19555 
19556 	if (mp != NULL) {
19557 		if (ipst->ips_ipobs_enabled) {
19558 			zoneid_t szone;
19559 
19560 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
19561 			    ipst, ALL_ZONES);
19562 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
19563 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
19564 		}
19565 
19566 		ILL_SEND_TX(ill, ire, connp, mp, 0);
19567 	}
19568 
19569 	IRE_REFRELE(ire);
19570 }
19571 
19572 /*
19573  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19574  * if the receiver shrinks the window, i.e. moves the right window to the
19575  * left, the we should not send new data, but should retransmit normally the
19576  * old unacked data between suna and suna + swnd. We might has sent data
19577  * that is now outside the new window, pretend that we didn't send  it.
19578  */
19579 static void
19580 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19581 {
19582 	uint32_t	snxt = tcp->tcp_snxt;
19583 	mblk_t		*xmit_tail;
19584 	int32_t		offset;
19585 
19586 	ASSERT(shrunk_count > 0);
19587 
19588 	/* Pretend we didn't send the data outside the window */
19589 	snxt -= shrunk_count;
19590 
19591 	/* Get the mblk and the offset in it per the shrunk window */
19592 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19593 
19594 	ASSERT(xmit_tail != NULL);
19595 
19596 	/* Reset all the values per the now shrunk window */
19597 	tcp->tcp_snxt = snxt;
19598 	tcp->tcp_xmit_tail = xmit_tail;
19599 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19600 	    offset;
19601 	tcp->tcp_unsent += shrunk_count;
19602 
19603 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19604 		/*
19605 		 * Make sure the timer is running so that we will probe a zero
19606 		 * window.
19607 		 */
19608 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19609 }
19610 
19611 
19612 /*
19613  * The TCP normal data output path.
19614  * NOTE: the logic of the fast path is duplicated from this function.
19615  */
19616 static void
19617 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19618 {
19619 	int		len;
19620 	mblk_t		*local_time;
19621 	mblk_t		*mp1;
19622 	uint32_t	snxt;
19623 	int		tail_unsent;
19624 	int		tcpstate;
19625 	int		usable = 0;
19626 	mblk_t		*xmit_tail;
19627 	queue_t		*q = tcp->tcp_wq;
19628 	int32_t		mss;
19629 	int32_t		num_sack_blk = 0;
19630 	int32_t		tcp_hdr_len;
19631 	int32_t		tcp_tcp_hdr_len;
19632 	int		mdt_thres;
19633 	int		rc;
19634 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19635 	ip_stack_t	*ipst;
19636 
19637 	tcpstate = tcp->tcp_state;
19638 	if (mp == NULL) {
19639 		/*
19640 		 * tcp_wput_data() with NULL mp should only be called when
19641 		 * there is unsent data.
19642 		 */
19643 		ASSERT(tcp->tcp_unsent > 0);
19644 		/* Really tacky... but we need this for detached closes. */
19645 		len = tcp->tcp_unsent;
19646 		goto data_null;
19647 	}
19648 
19649 #if CCS_STATS
19650 	wrw_stats.tot.count++;
19651 	wrw_stats.tot.bytes += msgdsize(mp);
19652 #endif
19653 	ASSERT(mp->b_datap->db_type == M_DATA);
19654 	/*
19655 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19656 	 * or before a connection attempt has begun.
19657 	 */
19658 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19659 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19660 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19661 #ifdef DEBUG
19662 			cmn_err(CE_WARN,
19663 			    "tcp_wput_data: data after ordrel, %s",
19664 			    tcp_display(tcp, NULL,
19665 			    DISP_ADDR_AND_PORT));
19666 #else
19667 			if (tcp->tcp_debug) {
19668 				(void) strlog(TCP_MOD_ID, 0, 1,
19669 				    SL_TRACE|SL_ERROR,
19670 				    "tcp_wput_data: data after ordrel, %s\n",
19671 				    tcp_display(tcp, NULL,
19672 				    DISP_ADDR_AND_PORT));
19673 			}
19674 #endif /* DEBUG */
19675 		}
19676 		if (tcp->tcp_snd_zcopy_aware &&
19677 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19678 			tcp_zcopy_notify(tcp);
19679 		freemsg(mp);
19680 		mutex_enter(&tcp->tcp_non_sq_lock);
19681 		if (tcp->tcp_flow_stopped &&
19682 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19683 			tcp_clrqfull(tcp);
19684 		}
19685 		mutex_exit(&tcp->tcp_non_sq_lock);
19686 		return;
19687 	}
19688 
19689 	/* Strip empties */
19690 	for (;;) {
19691 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19692 		    (uintptr_t)INT_MAX);
19693 		len = (int)(mp->b_wptr - mp->b_rptr);
19694 		if (len > 0)
19695 			break;
19696 		mp1 = mp;
19697 		mp = mp->b_cont;
19698 		freeb(mp1);
19699 		if (!mp) {
19700 			return;
19701 		}
19702 	}
19703 
19704 	/* If we are the first on the list ... */
19705 	if (tcp->tcp_xmit_head == NULL) {
19706 		tcp->tcp_xmit_head = mp;
19707 		tcp->tcp_xmit_tail = mp;
19708 		tcp->tcp_xmit_tail_unsent = len;
19709 	} else {
19710 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19711 		struct datab *dp;
19712 
19713 		mp1 = tcp->tcp_xmit_last;
19714 		if (len < tcp_tx_pull_len &&
19715 		    (dp = mp1->b_datap)->db_ref == 1 &&
19716 		    dp->db_lim - mp1->b_wptr >= len) {
19717 			ASSERT(len > 0);
19718 			ASSERT(!mp1->b_cont);
19719 			if (len == 1) {
19720 				*mp1->b_wptr++ = *mp->b_rptr;
19721 			} else {
19722 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19723 				mp1->b_wptr += len;
19724 			}
19725 			if (mp1 == tcp->tcp_xmit_tail)
19726 				tcp->tcp_xmit_tail_unsent += len;
19727 			mp1->b_cont = mp->b_cont;
19728 			if (tcp->tcp_snd_zcopy_aware &&
19729 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19730 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19731 			freeb(mp);
19732 			mp = mp1;
19733 		} else {
19734 			tcp->tcp_xmit_last->b_cont = mp;
19735 		}
19736 		len += tcp->tcp_unsent;
19737 	}
19738 
19739 	/* Tack on however many more positive length mblks we have */
19740 	if ((mp1 = mp->b_cont) != NULL) {
19741 		do {
19742 			int tlen;
19743 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19744 			    (uintptr_t)INT_MAX);
19745 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19746 			if (tlen <= 0) {
19747 				mp->b_cont = mp1->b_cont;
19748 				freeb(mp1);
19749 			} else {
19750 				len += tlen;
19751 				mp = mp1;
19752 			}
19753 		} while ((mp1 = mp->b_cont) != NULL);
19754 	}
19755 	tcp->tcp_xmit_last = mp;
19756 	tcp->tcp_unsent = len;
19757 
19758 	if (urgent)
19759 		usable = 1;
19760 
19761 data_null:
19762 	snxt = tcp->tcp_snxt;
19763 	xmit_tail = tcp->tcp_xmit_tail;
19764 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19765 
19766 	/*
19767 	 * Note that tcp_mss has been adjusted to take into account the
19768 	 * timestamp option if applicable.  Because SACK options do not
19769 	 * appear in every TCP segments and they are of variable lengths,
19770 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19771 	 * the actual segment length when we need to send a segment which
19772 	 * includes SACK options.
19773 	 */
19774 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19775 		int32_t	opt_len;
19776 
19777 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19778 		    tcp->tcp_num_sack_blk);
19779 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19780 		    2 + TCPOPT_HEADER_LEN;
19781 		mss = tcp->tcp_mss - opt_len;
19782 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19783 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19784 	} else {
19785 		mss = tcp->tcp_mss;
19786 		tcp_hdr_len = tcp->tcp_hdr_len;
19787 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19788 	}
19789 
19790 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19791 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19792 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19793 	}
19794 	if (tcpstate == TCPS_SYN_RCVD) {
19795 		/*
19796 		 * The three-way connection establishment handshake is not
19797 		 * complete yet. We want to queue the data for transmission
19798 		 * after entering ESTABLISHED state (RFC793). A jump to
19799 		 * "done" label effectively leaves data on the queue.
19800 		 */
19801 		goto done;
19802 	} else {
19803 		int usable_r;
19804 
19805 		/*
19806 		 * In the special case when cwnd is zero, which can only
19807 		 * happen if the connection is ECN capable, return now.
19808 		 * New segments is sent using tcp_timer().  The timer
19809 		 * is set in tcp_rput_data().
19810 		 */
19811 		if (tcp->tcp_cwnd == 0) {
19812 			/*
19813 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19814 			 * finished.
19815 			 */
19816 			ASSERT(tcp->tcp_ecn_ok ||
19817 			    tcp->tcp_state < TCPS_ESTABLISHED);
19818 			return;
19819 		}
19820 
19821 		/* NOTE: trouble if xmitting while SYN not acked? */
19822 		usable_r = snxt - tcp->tcp_suna;
19823 		usable_r = tcp->tcp_swnd - usable_r;
19824 
19825 		/*
19826 		 * Check if the receiver has shrunk the window.  If
19827 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19828 		 * cannot be set as there is unsent data, so FIN cannot
19829 		 * be sent out.  Otherwise, we need to take into account
19830 		 * of FIN as it consumes an "invisible" sequence number.
19831 		 */
19832 		ASSERT(tcp->tcp_fin_sent == 0);
19833 		if (usable_r < 0) {
19834 			/*
19835 			 * The receiver has shrunk the window and we have sent
19836 			 * -usable_r date beyond the window, re-adjust.
19837 			 *
19838 			 * If TCP window scaling is enabled, there can be
19839 			 * round down error as the advertised receive window
19840 			 * is actually right shifted n bits.  This means that
19841 			 * the lower n bits info is wiped out.  It will look
19842 			 * like the window is shrunk.  Do a check here to
19843 			 * see if the shrunk amount is actually within the
19844 			 * error in window calculation.  If it is, just
19845 			 * return.  Note that this check is inside the
19846 			 * shrunk window check.  This makes sure that even
19847 			 * though tcp_process_shrunk_swnd() is not called,
19848 			 * we will stop further processing.
19849 			 */
19850 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19851 				tcp_process_shrunk_swnd(tcp, -usable_r);
19852 			}
19853 			return;
19854 		}
19855 
19856 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19857 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19858 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19859 
19860 		/* usable = MIN(usable, unsent) */
19861 		if (usable_r > len)
19862 			usable_r = len;
19863 
19864 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19865 		if (usable_r > 0) {
19866 			usable = usable_r;
19867 		} else {
19868 			/* Bypass all other unnecessary processing. */
19869 			goto done;
19870 		}
19871 	}
19872 
19873 	local_time = (mblk_t *)lbolt;
19874 
19875 	/*
19876 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19877 	 * BSD.  This is more in line with the true intent of Nagle.
19878 	 *
19879 	 * The conditions are:
19880 	 * 1. The amount of unsent data (or amount of data which can be
19881 	 *    sent, whichever is smaller) is less than Nagle limit.
19882 	 * 2. The last sent size is also less than Nagle limit.
19883 	 * 3. There is unack'ed data.
19884 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19885 	 *    Nagle algorithm.  This reduces the probability that urgent
19886 	 *    bytes get "merged" together.
19887 	 * 5. The app has not closed the connection.  This eliminates the
19888 	 *    wait time of the receiving side waiting for the last piece of
19889 	 *    (small) data.
19890 	 *
19891 	 * If all are satisified, exit without sending anything.  Note
19892 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19893 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19894 	 * 4095).
19895 	 */
19896 	if (usable < (int)tcp->tcp_naglim &&
19897 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19898 	    snxt != tcp->tcp_suna &&
19899 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19900 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19901 		goto done;
19902 	}
19903 
19904 	if (tcp->tcp_cork) {
19905 		/*
19906 		 * if the tcp->tcp_cork option is set, then we have to force
19907 		 * TCP not to send partial segment (smaller than MSS bytes).
19908 		 * We are calculating the usable now based on full mss and
19909 		 * will save the rest of remaining data for later.
19910 		 */
19911 		if (usable < mss)
19912 			goto done;
19913 		usable = (usable / mss) * mss;
19914 	}
19915 
19916 	/* Update the latest receive window size in TCP header. */
19917 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19918 	    tcp->tcp_tcph->th_win);
19919 
19920 	/*
19921 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19922 	 *
19923 	 * 1. Simple TCP/IP{v4,v6} (no options).
19924 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19925 	 * 3. If the TCP connection is in ESTABLISHED state.
19926 	 * 4. The TCP is not detached.
19927 	 *
19928 	 * If any of the above conditions have changed during the
19929 	 * connection, stop using LSO/MDT and restore the stream head
19930 	 * parameters accordingly.
19931 	 */
19932 	ipst = tcps->tcps_netstack->netstack_ip;
19933 
19934 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19935 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19936 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19937 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19938 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19939 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19940 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19941 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19942 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19943 		if (tcp->tcp_lso) {
19944 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19945 			tcp->tcp_lso = B_FALSE;
19946 		} else {
19947 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19948 			tcp->tcp_mdt = B_FALSE;
19949 		}
19950 
19951 		/* Anything other than detached is considered pathological */
19952 		if (!TCP_IS_DETACHED(tcp)) {
19953 			if (tcp->tcp_lso)
19954 				TCP_STAT(tcps, tcp_lso_disabled);
19955 			else
19956 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19957 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19958 		}
19959 	}
19960 
19961 	/* Use MDT if sendable amount is greater than the threshold */
19962 	if (tcp->tcp_mdt &&
19963 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19964 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19965 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19966 	    (tcp->tcp_valid_bits == 0 ||
19967 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19968 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19969 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19970 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19971 		    local_time, mdt_thres);
19972 	} else {
19973 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19974 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19975 		    local_time, INT_MAX);
19976 	}
19977 
19978 	/* Pretend that all we were trying to send really got sent */
19979 	if (rc < 0 && tail_unsent < 0) {
19980 		do {
19981 			xmit_tail = xmit_tail->b_cont;
19982 			xmit_tail->b_prev = local_time;
19983 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19984 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19985 			tail_unsent += (int)(xmit_tail->b_wptr -
19986 			    xmit_tail->b_rptr);
19987 		} while (tail_unsent < 0);
19988 	}
19989 done:;
19990 	tcp->tcp_xmit_tail = xmit_tail;
19991 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19992 	len = tcp->tcp_snxt - snxt;
19993 	if (len) {
19994 		/*
19995 		 * If new data was sent, need to update the notsack
19996 		 * list, which is, afterall, data blocks that have
19997 		 * not been sack'ed by the receiver.  New data is
19998 		 * not sack'ed.
19999 		 */
20000 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
20001 			/* len is a negative value. */
20002 			tcp->tcp_pipe -= len;
20003 			tcp_notsack_update(&(tcp->tcp_notsack_list),
20004 			    tcp->tcp_snxt, snxt,
20005 			    &(tcp->tcp_num_notsack_blk),
20006 			    &(tcp->tcp_cnt_notsack_list));
20007 		}
20008 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
20009 		tcp->tcp_rack = tcp->tcp_rnxt;
20010 		tcp->tcp_rack_cnt = 0;
20011 		if ((snxt + len) == tcp->tcp_suna) {
20012 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20013 		}
20014 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
20015 		/*
20016 		 * Didn't send anything. Make sure the timer is running
20017 		 * so that we will probe a zero window.
20018 		 */
20019 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20020 	}
20021 	/* Note that len is the amount we just sent but with a negative sign */
20022 	tcp->tcp_unsent += len;
20023 	mutex_enter(&tcp->tcp_non_sq_lock);
20024 	if (tcp->tcp_flow_stopped) {
20025 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
20026 			tcp_clrqfull(tcp);
20027 		}
20028 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
20029 		tcp_setqfull(tcp);
20030 	}
20031 	mutex_exit(&tcp->tcp_non_sq_lock);
20032 }
20033 
20034 /*
20035  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
20036  * outgoing TCP header with the template header, as well as other
20037  * options such as time-stamp, ECN and/or SACK.
20038  */
20039 static void
20040 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
20041 {
20042 	tcph_t *tcp_tmpl, *tcp_h;
20043 	uint32_t *dst, *src;
20044 	int hdrlen;
20045 
20046 	ASSERT(OK_32PTR(rptr));
20047 
20048 	/* Template header */
20049 	tcp_tmpl = tcp->tcp_tcph;
20050 
20051 	/* Header of outgoing packet */
20052 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20053 
20054 	/* dst and src are opaque 32-bit fields, used for copying */
20055 	dst = (uint32_t *)rptr;
20056 	src = (uint32_t *)tcp->tcp_iphc;
20057 	hdrlen = tcp->tcp_hdr_len;
20058 
20059 	/* Fill time-stamp option if needed */
20060 	if (tcp->tcp_snd_ts_ok) {
20061 		U32_TO_BE32((uint32_t)now,
20062 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
20063 		U32_TO_BE32(tcp->tcp_ts_recent,
20064 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
20065 	} else {
20066 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
20067 	}
20068 
20069 	/*
20070 	 * Copy the template header; is this really more efficient than
20071 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
20072 	 * but perhaps not for other scenarios.
20073 	 */
20074 	dst[0] = src[0];
20075 	dst[1] = src[1];
20076 	dst[2] = src[2];
20077 	dst[3] = src[3];
20078 	dst[4] = src[4];
20079 	dst[5] = src[5];
20080 	dst[6] = src[6];
20081 	dst[7] = src[7];
20082 	dst[8] = src[8];
20083 	dst[9] = src[9];
20084 	if (hdrlen -= 40) {
20085 		hdrlen >>= 2;
20086 		dst += 10;
20087 		src += 10;
20088 		do {
20089 			*dst++ = *src++;
20090 		} while (--hdrlen);
20091 	}
20092 
20093 	/*
20094 	 * Set the ECN info in the TCP header if it is not a zero
20095 	 * window probe.  Zero window probe is only sent in
20096 	 * tcp_wput_data() and tcp_timer().
20097 	 */
20098 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
20099 		SET_ECT(tcp, rptr);
20100 
20101 		if (tcp->tcp_ecn_echo_on)
20102 			tcp_h->th_flags[0] |= TH_ECE;
20103 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
20104 			tcp_h->th_flags[0] |= TH_CWR;
20105 			tcp->tcp_ecn_cwr_sent = B_TRUE;
20106 		}
20107 	}
20108 
20109 	/* Fill in SACK options */
20110 	if (num_sack_blk > 0) {
20111 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
20112 		sack_blk_t *tmp;
20113 		int32_t	i;
20114 
20115 		wptr[0] = TCPOPT_NOP;
20116 		wptr[1] = TCPOPT_NOP;
20117 		wptr[2] = TCPOPT_SACK;
20118 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
20119 		    sizeof (sack_blk_t);
20120 		wptr += TCPOPT_REAL_SACK_LEN;
20121 
20122 		tmp = tcp->tcp_sack_list;
20123 		for (i = 0; i < num_sack_blk; i++) {
20124 			U32_TO_BE32(tmp[i].begin, wptr);
20125 			wptr += sizeof (tcp_seq);
20126 			U32_TO_BE32(tmp[i].end, wptr);
20127 			wptr += sizeof (tcp_seq);
20128 		}
20129 		tcp_h->th_offset_and_rsrvd[0] +=
20130 		    ((num_sack_blk * 2 + 1) << 4);
20131 	}
20132 }
20133 
20134 /*
20135  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
20136  * the destination address and SAP attribute, and if necessary, the
20137  * hardware checksum offload attribute to a Multidata message.
20138  */
20139 static int
20140 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
20141     const uint32_t start, const uint32_t stuff, const uint32_t end,
20142     const uint32_t flags, tcp_stack_t *tcps)
20143 {
20144 	/* Add global destination address & SAP attribute */
20145 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
20146 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
20147 		    "destination address+SAP\n"));
20148 
20149 		if (dlmp != NULL)
20150 			TCP_STAT(tcps, tcp_mdt_allocfail);
20151 		return (-1);
20152 	}
20153 
20154 	/* Add global hwcksum attribute */
20155 	if (hwcksum &&
20156 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
20157 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
20158 		    "checksum attribute\n"));
20159 
20160 		TCP_STAT(tcps, tcp_mdt_allocfail);
20161 		return (-1);
20162 	}
20163 
20164 	return (0);
20165 }
20166 
20167 /*
20168  * Smaller and private version of pdescinfo_t used specifically for TCP,
20169  * which allows for only two payload spans per packet.
20170  */
20171 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
20172 
20173 /*
20174  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
20175  * scheme, and returns one the following:
20176  *
20177  * -1 = failed allocation.
20178  *  0 = success; burst count reached, or usable send window is too small,
20179  *      and that we'd rather wait until later before sending again.
20180  */
20181 static int
20182 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20183     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20184     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20185     const int mdt_thres)
20186 {
20187 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
20188 	multidata_t	*mmd;
20189 	uint_t		obsegs, obbytes, hdr_frag_sz;
20190 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
20191 	int		num_burst_seg, max_pld;
20192 	pdesc_t		*pkt;
20193 	tcp_pdescinfo_t	tcp_pkt_info;
20194 	pdescinfo_t	*pkt_info;
20195 	int		pbuf_idx, pbuf_idx_nxt;
20196 	int		seg_len, len, spill, af;
20197 	boolean_t	add_buffer, zcopy, clusterwide;
20198 	boolean_t	rconfirm = B_FALSE;
20199 	boolean_t	done = B_FALSE;
20200 	uint32_t	cksum;
20201 	uint32_t	hwcksum_flags;
20202 	ire_t		*ire = NULL;
20203 	ill_t		*ill;
20204 	ipha_t		*ipha;
20205 	ip6_t		*ip6h;
20206 	ipaddr_t	src, dst;
20207 	ill_zerocopy_capab_t *zc_cap = NULL;
20208 	uint16_t	*up;
20209 	int		err;
20210 	conn_t		*connp;
20211 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20212 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
20213 	int		usable_mmd, tail_unsent_mmd;
20214 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
20215 	mblk_t		*xmit_tail_mmd;
20216 
20217 #ifdef	_BIG_ENDIAN
20218 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20219 #else
20220 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20221 #endif
20222 
20223 #define	PREP_NEW_MULTIDATA() {			\
20224 	mmd = NULL;				\
20225 	md_mp = md_hbuf = NULL;			\
20226 	cur_hdr_off = 0;			\
20227 	max_pld = tcp->tcp_mdt_max_pld;		\
20228 	pbuf_idx = pbuf_idx_nxt = -1;		\
20229 	add_buffer = B_TRUE;			\
20230 	zcopy = B_FALSE;			\
20231 }
20232 
20233 #define	PREP_NEW_PBUF() {			\
20234 	md_pbuf = md_pbuf_nxt = NULL;		\
20235 	pbuf_idx = pbuf_idx_nxt = -1;		\
20236 	cur_pld_off = 0;			\
20237 	first_snxt = *snxt;			\
20238 	ASSERT(*tail_unsent > 0);		\
20239 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20240 }
20241 
20242 	ASSERT(mdt_thres >= mss);
20243 	ASSERT(*usable > 0 && *usable > mdt_thres);
20244 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20245 	ASSERT(!TCP_IS_DETACHED(tcp));
20246 	ASSERT(tcp->tcp_valid_bits == 0 ||
20247 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20248 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20249 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20250 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20251 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20252 
20253 	connp = tcp->tcp_connp;
20254 	ASSERT(connp != NULL);
20255 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20256 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20257 
20258 	usable_mmd = tail_unsent_mmd = 0;
20259 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20260 	xmit_tail_mmd = NULL;
20261 	/*
20262 	 * Note that tcp will only declare at most 2 payload spans per
20263 	 * packet, which is much lower than the maximum allowable number
20264 	 * of packet spans per Multidata.  For this reason, we use the
20265 	 * privately declared and smaller descriptor info structure, in
20266 	 * order to save some stack space.
20267 	 */
20268 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20269 
20270 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20271 	if (af == AF_INET) {
20272 		dst = tcp->tcp_ipha->ipha_dst;
20273 		src = tcp->tcp_ipha->ipha_src;
20274 		ASSERT(!CLASSD(dst));
20275 	}
20276 	ASSERT(af == AF_INET ||
20277 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20278 
20279 	obsegs = obbytes = 0;
20280 	num_burst_seg = tcp->tcp_snd_burst;
20281 	md_mp_head = NULL;
20282 	PREP_NEW_MULTIDATA();
20283 
20284 	/*
20285 	 * Before we go on further, make sure there is an IRE that we can
20286 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20287 	 * in proceeding any further, and we should just hand everything
20288 	 * off to the legacy path.
20289 	 */
20290 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20291 		goto legacy_send_no_md;
20292 
20293 	ASSERT(ire != NULL);
20294 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20295 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20296 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20297 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20298 	/*
20299 	 * If we do support loopback for MDT (which requires modifications
20300 	 * to the receiving paths), the following assertions should go away,
20301 	 * and we would be sending the Multidata to loopback conn later on.
20302 	 */
20303 	ASSERT(!IRE_IS_LOCAL(ire));
20304 	ASSERT(ire->ire_stq != NULL);
20305 
20306 	ill = ire_to_ill(ire);
20307 	ASSERT(ill != NULL);
20308 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20309 
20310 	if (!tcp->tcp_ire_ill_check_done) {
20311 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20312 		tcp->tcp_ire_ill_check_done = B_TRUE;
20313 	}
20314 
20315 	/*
20316 	 * If the underlying interface conditions have changed, or if the
20317 	 * new interface does not support MDT, go back to legacy path.
20318 	 */
20319 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20320 		/* don't go through this path anymore for this connection */
20321 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20322 		tcp->tcp_mdt = B_FALSE;
20323 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20324 		    "interface %s\n", (void *)connp, ill->ill_name));
20325 		/* IRE will be released prior to returning */
20326 		goto legacy_send_no_md;
20327 	}
20328 
20329 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20330 		zc_cap = ill->ill_zerocopy_capab;
20331 
20332 	/*
20333 	 * Check if we can take tcp fast-path. Note that "incomplete"
20334 	 * ire's (where the link-layer for next hop is not resolved
20335 	 * or where the fast-path header in nce_fp_mp is not available
20336 	 * yet) are sent down the legacy (slow) path.
20337 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20338 	 */
20339 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20340 		/* IRE will be released prior to returning */
20341 		goto legacy_send_no_md;
20342 	}
20343 
20344 	/* go to legacy path if interface doesn't support zerocopy */
20345 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20346 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20347 		/* IRE will be released prior to returning */
20348 		goto legacy_send_no_md;
20349 	}
20350 
20351 	/* does the interface support hardware checksum offload? */
20352 	hwcksum_flags = 0;
20353 	if (ILL_HCKSUM_CAPABLE(ill) &&
20354 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20355 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20356 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20357 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20358 		    HCKSUM_IPHDRCKSUM)
20359 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20360 
20361 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20362 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20363 			hwcksum_flags |= HCK_FULLCKSUM;
20364 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20365 		    HCKSUM_INET_PARTIAL)
20366 			hwcksum_flags |= HCK_PARTIALCKSUM;
20367 	}
20368 
20369 	/*
20370 	 * Each header fragment consists of the leading extra space,
20371 	 * followed by the TCP/IP header, and the trailing extra space.
20372 	 * We make sure that each header fragment begins on a 32-bit
20373 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20374 	 * aligned in tcp_mdt_update).
20375 	 */
20376 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20377 	    tcp->tcp_mdt_hdr_tail), 4);
20378 
20379 	/* are we starting from the beginning of data block? */
20380 	if (*tail_unsent == 0) {
20381 		*xmit_tail = (*xmit_tail)->b_cont;
20382 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20383 		*tail_unsent = (int)MBLKL(*xmit_tail);
20384 	}
20385 
20386 	/*
20387 	 * Here we create one or more Multidata messages, each made up of
20388 	 * one header buffer and up to N payload buffers.  This entire
20389 	 * operation is done within two loops:
20390 	 *
20391 	 * The outer loop mostly deals with creating the Multidata message,
20392 	 * as well as the header buffer that gets added to it.  It also
20393 	 * links the Multidata messages together such that all of them can
20394 	 * be sent down to the lower layer in a single putnext call; this
20395 	 * linking behavior depends on the tcp_mdt_chain tunable.
20396 	 *
20397 	 * The inner loop takes an existing Multidata message, and adds
20398 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20399 	 * packetizes those buffers by filling up the corresponding header
20400 	 * buffer fragments with the proper IP and TCP headers, and by
20401 	 * describing the layout of each packet in the packet descriptors
20402 	 * that get added to the Multidata.
20403 	 */
20404 	do {
20405 		/*
20406 		 * If usable send window is too small, or data blocks in
20407 		 * transmit list are smaller than our threshold (i.e. app
20408 		 * performs large writes followed by small ones), we hand
20409 		 * off the control over to the legacy path.  Note that we'll
20410 		 * get back the control once it encounters a large block.
20411 		 */
20412 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20413 		    (*xmit_tail)->b_cont != NULL &&
20414 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20415 			/* send down what we've got so far */
20416 			if (md_mp_head != NULL) {
20417 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20418 				    obsegs, obbytes, &rconfirm);
20419 			}
20420 			/*
20421 			 * Pass control over to tcp_send(), but tell it to
20422 			 * return to us once a large-size transmission is
20423 			 * possible.
20424 			 */
20425 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20426 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20427 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20428 			    tail_unsent, xmit_tail, local_time,
20429 			    mdt_thres)) <= 0) {
20430 				/* burst count reached, or alloc failed */
20431 				IRE_REFRELE(ire);
20432 				return (err);
20433 			}
20434 
20435 			/* tcp_send() may have sent everything, so check */
20436 			if (*usable <= 0) {
20437 				IRE_REFRELE(ire);
20438 				return (0);
20439 			}
20440 
20441 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20442 			/*
20443 			 * We may have delivered the Multidata, so make sure
20444 			 * to re-initialize before the next round.
20445 			 */
20446 			md_mp_head = NULL;
20447 			obsegs = obbytes = 0;
20448 			num_burst_seg = tcp->tcp_snd_burst;
20449 			PREP_NEW_MULTIDATA();
20450 
20451 			/* are we starting from the beginning of data block? */
20452 			if (*tail_unsent == 0) {
20453 				*xmit_tail = (*xmit_tail)->b_cont;
20454 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20455 				    (uintptr_t)INT_MAX);
20456 				*tail_unsent = (int)MBLKL(*xmit_tail);
20457 			}
20458 		}
20459 		/*
20460 		 * Record current values for parameters we may need to pass
20461 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20462 		 * each iteration of the outer loop (each multidata message
20463 		 * creation). If we have a failure in the inner loop, we send
20464 		 * any complete multidata messages we have before reverting
20465 		 * to using the traditional non-md path.
20466 		 */
20467 		snxt_mmd = *snxt;
20468 		usable_mmd = *usable;
20469 		xmit_tail_mmd = *xmit_tail;
20470 		tail_unsent_mmd = *tail_unsent;
20471 		obsegs_mmd = obsegs;
20472 		obbytes_mmd = obbytes;
20473 
20474 		/*
20475 		 * max_pld limits the number of mblks in tcp's transmit
20476 		 * queue that can be added to a Multidata message.  Once
20477 		 * this counter reaches zero, no more additional mblks
20478 		 * can be added to it.  What happens afterwards depends
20479 		 * on whether or not we are set to chain the Multidata
20480 		 * messages.  If we are to link them together, reset
20481 		 * max_pld to its original value (tcp_mdt_max_pld) and
20482 		 * prepare to create a new Multidata message which will
20483 		 * get linked to md_mp_head.  Else, leave it alone and
20484 		 * let the inner loop break on its own.
20485 		 */
20486 		if (tcp_mdt_chain && max_pld == 0)
20487 			PREP_NEW_MULTIDATA();
20488 
20489 		/* adding a payload buffer; re-initialize values */
20490 		if (add_buffer)
20491 			PREP_NEW_PBUF();
20492 
20493 		/*
20494 		 * If we don't have a Multidata, either because we just
20495 		 * (re)entered this outer loop, or after we branched off
20496 		 * to tcp_send above, setup the Multidata and header
20497 		 * buffer to be used.
20498 		 */
20499 		if (md_mp == NULL) {
20500 			int md_hbuflen;
20501 			uint32_t start, stuff;
20502 
20503 			/*
20504 			 * Calculate Multidata header buffer size large enough
20505 			 * to hold all of the headers that can possibly be
20506 			 * sent at this moment.  We'd rather over-estimate
20507 			 * the size than running out of space; this is okay
20508 			 * since this buffer is small anyway.
20509 			 */
20510 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20511 
20512 			/*
20513 			 * Start and stuff offset for partial hardware
20514 			 * checksum offload; these are currently for IPv4.
20515 			 * For full checksum offload, they are set to zero.
20516 			 */
20517 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20518 				if (af == AF_INET) {
20519 					start = IP_SIMPLE_HDR_LENGTH;
20520 					stuff = IP_SIMPLE_HDR_LENGTH +
20521 					    TCP_CHECKSUM_OFFSET;
20522 				} else {
20523 					start = IPV6_HDR_LEN;
20524 					stuff = IPV6_HDR_LEN +
20525 					    TCP_CHECKSUM_OFFSET;
20526 				}
20527 			} else {
20528 				start = stuff = 0;
20529 			}
20530 
20531 			/*
20532 			 * Create the header buffer, Multidata, as well as
20533 			 * any necessary attributes (destination address,
20534 			 * SAP and hardware checksum offload) that should
20535 			 * be associated with the Multidata message.
20536 			 */
20537 			ASSERT(cur_hdr_off == 0);
20538 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20539 			    ((md_hbuf->b_wptr += md_hbuflen),
20540 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20541 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20542 			    /* fastpath mblk */
20543 			    ire->ire_nce->nce_res_mp,
20544 			    /* hardware checksum enabled */
20545 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20546 			    /* hardware checksum offsets */
20547 			    start, stuff, 0,
20548 			    /* hardware checksum flag */
20549 			    hwcksum_flags, tcps) != 0)) {
20550 legacy_send:
20551 				/*
20552 				 * We arrive here from a failure within the
20553 				 * inner (packetizer) loop or we fail one of
20554 				 * the conditionals above. We restore the
20555 				 * previously checkpointed values for:
20556 				 *    xmit_tail
20557 				 *    usable
20558 				 *    tail_unsent
20559 				 *    snxt
20560 				 *    obbytes
20561 				 *    obsegs
20562 				 * We should then be able to dispatch any
20563 				 * complete multidata before reverting to the
20564 				 * traditional path with consistent parameters
20565 				 * (the inner loop updates these as it
20566 				 * iterates).
20567 				 */
20568 				*xmit_tail = xmit_tail_mmd;
20569 				*usable = usable_mmd;
20570 				*tail_unsent = tail_unsent_mmd;
20571 				*snxt = snxt_mmd;
20572 				obbytes = obbytes_mmd;
20573 				obsegs = obsegs_mmd;
20574 				if (md_mp != NULL) {
20575 					/* Unlink message from the chain */
20576 					if (md_mp_head != NULL) {
20577 						err = (intptr_t)rmvb(md_mp_head,
20578 						    md_mp);
20579 						/*
20580 						 * We can't assert that rmvb
20581 						 * did not return -1, since we
20582 						 * may get here before linkb
20583 						 * happens.  We do, however,
20584 						 * check if we just removed the
20585 						 * only element in the list.
20586 						 */
20587 						if (err == 0)
20588 							md_mp_head = NULL;
20589 					}
20590 					/* md_hbuf gets freed automatically */
20591 					TCP_STAT(tcps, tcp_mdt_discarded);
20592 					freeb(md_mp);
20593 				} else {
20594 					/* Either allocb or mmd_alloc failed */
20595 					TCP_STAT(tcps, tcp_mdt_allocfail);
20596 					if (md_hbuf != NULL)
20597 						freeb(md_hbuf);
20598 				}
20599 
20600 				/* send down what we've got so far */
20601 				if (md_mp_head != NULL) {
20602 					tcp_multisend_data(tcp, ire, ill,
20603 					    md_mp_head, obsegs, obbytes,
20604 					    &rconfirm);
20605 				}
20606 legacy_send_no_md:
20607 				if (ire != NULL)
20608 					IRE_REFRELE(ire);
20609 				/*
20610 				 * Too bad; let the legacy path handle this.
20611 				 * We specify INT_MAX for the threshold, since
20612 				 * we gave up with the Multidata processings
20613 				 * and let the old path have it all.
20614 				 */
20615 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20616 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20617 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20618 				    snxt, tail_unsent, xmit_tail, local_time,
20619 				    INT_MAX));
20620 			}
20621 
20622 			/* link to any existing ones, if applicable */
20623 			TCP_STAT(tcps, tcp_mdt_allocd);
20624 			if (md_mp_head == NULL) {
20625 				md_mp_head = md_mp;
20626 			} else if (tcp_mdt_chain) {
20627 				TCP_STAT(tcps, tcp_mdt_linked);
20628 				linkb(md_mp_head, md_mp);
20629 			}
20630 		}
20631 
20632 		ASSERT(md_mp_head != NULL);
20633 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20634 		ASSERT(md_mp != NULL && mmd != NULL);
20635 		ASSERT(md_hbuf != NULL);
20636 
20637 		/*
20638 		 * Packetize the transmittable portion of the data block;
20639 		 * each data block is essentially added to the Multidata
20640 		 * as a payload buffer.  We also deal with adding more
20641 		 * than one payload buffers, which happens when the remaining
20642 		 * packetized portion of the current payload buffer is less
20643 		 * than MSS, while the next data block in transmit queue
20644 		 * has enough data to make up for one.  This "spillover"
20645 		 * case essentially creates a split-packet, where portions
20646 		 * of the packet's payload fragments may span across two
20647 		 * virtually discontiguous address blocks.
20648 		 */
20649 		seg_len = mss;
20650 		do {
20651 			len = seg_len;
20652 
20653 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20654 			ipha = NULL;
20655 			ip6h = NULL;
20656 
20657 			ASSERT(len > 0);
20658 			ASSERT(max_pld >= 0);
20659 			ASSERT(!add_buffer || cur_pld_off == 0);
20660 
20661 			/*
20662 			 * First time around for this payload buffer; note
20663 			 * in the case of a spillover, the following has
20664 			 * been done prior to adding the split-packet
20665 			 * descriptor to Multidata, and we don't want to
20666 			 * repeat the process.
20667 			 */
20668 			if (add_buffer) {
20669 				ASSERT(mmd != NULL);
20670 				ASSERT(md_pbuf == NULL);
20671 				ASSERT(md_pbuf_nxt == NULL);
20672 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20673 
20674 				/*
20675 				 * Have we reached the limit?  We'd get to
20676 				 * this case when we're not chaining the
20677 				 * Multidata messages together, and since
20678 				 * we're done, terminate this loop.
20679 				 */
20680 				if (max_pld == 0)
20681 					break; /* done */
20682 
20683 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20684 					TCP_STAT(tcps, tcp_mdt_allocfail);
20685 					goto legacy_send; /* out_of_mem */
20686 				}
20687 
20688 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20689 				    zc_cap != NULL) {
20690 					if (!ip_md_zcopy_attr(mmd, NULL,
20691 					    zc_cap->ill_zerocopy_flags)) {
20692 						freeb(md_pbuf);
20693 						TCP_STAT(tcps,
20694 						    tcp_mdt_allocfail);
20695 						/* out_of_mem */
20696 						goto legacy_send;
20697 					}
20698 					zcopy = B_TRUE;
20699 				}
20700 
20701 				md_pbuf->b_rptr += base_pld_off;
20702 
20703 				/*
20704 				 * Add a payload buffer to the Multidata; this
20705 				 * operation must not fail, or otherwise our
20706 				 * logic in this routine is broken.  There
20707 				 * is no memory allocation done by the
20708 				 * routine, so any returned failure simply
20709 				 * tells us that we've done something wrong.
20710 				 *
20711 				 * A failure tells us that either we're adding
20712 				 * the same payload buffer more than once, or
20713 				 * we're trying to add more buffers than
20714 				 * allowed (max_pld calculation is wrong).
20715 				 * None of the above cases should happen, and
20716 				 * we panic because either there's horrible
20717 				 * heap corruption, and/or programming mistake.
20718 				 */
20719 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20720 				if (pbuf_idx < 0) {
20721 					cmn_err(CE_PANIC, "tcp_multisend: "
20722 					    "payload buffer logic error "
20723 					    "detected for tcp %p mmd %p "
20724 					    "pbuf %p (%d)\n",
20725 					    (void *)tcp, (void *)mmd,
20726 					    (void *)md_pbuf, pbuf_idx);
20727 				}
20728 
20729 				ASSERT(max_pld > 0);
20730 				--max_pld;
20731 				add_buffer = B_FALSE;
20732 			}
20733 
20734 			ASSERT(md_mp_head != NULL);
20735 			ASSERT(md_pbuf != NULL);
20736 			ASSERT(md_pbuf_nxt == NULL);
20737 			ASSERT(pbuf_idx != -1);
20738 			ASSERT(pbuf_idx_nxt == -1);
20739 			ASSERT(*usable > 0);
20740 
20741 			/*
20742 			 * We spillover to the next payload buffer only
20743 			 * if all of the following is true:
20744 			 *
20745 			 *   1. There is not enough data on the current
20746 			 *	payload buffer to make up `len',
20747 			 *   2. We are allowed to send `len',
20748 			 *   3. The next payload buffer length is large
20749 			 *	enough to accomodate `spill'.
20750 			 */
20751 			if ((spill = len - *tail_unsent) > 0 &&
20752 			    *usable >= len &&
20753 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20754 			    max_pld > 0) {
20755 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20756 				if (md_pbuf_nxt == NULL) {
20757 					TCP_STAT(tcps, tcp_mdt_allocfail);
20758 					goto legacy_send; /* out_of_mem */
20759 				}
20760 
20761 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20762 				    zc_cap != NULL) {
20763 					if (!ip_md_zcopy_attr(mmd, NULL,
20764 					    zc_cap->ill_zerocopy_flags)) {
20765 						freeb(md_pbuf_nxt);
20766 						TCP_STAT(tcps,
20767 						    tcp_mdt_allocfail);
20768 						/* out_of_mem */
20769 						goto legacy_send;
20770 					}
20771 					zcopy = B_TRUE;
20772 				}
20773 
20774 				/*
20775 				 * See comments above on the first call to
20776 				 * mmd_addpldbuf for explanation on the panic.
20777 				 */
20778 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20779 				if (pbuf_idx_nxt < 0) {
20780 					panic("tcp_multisend: "
20781 					    "next payload buffer logic error "
20782 					    "detected for tcp %p mmd %p "
20783 					    "pbuf %p (%d)\n",
20784 					    (void *)tcp, (void *)mmd,
20785 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20786 				}
20787 
20788 				ASSERT(max_pld > 0);
20789 				--max_pld;
20790 			} else if (spill > 0) {
20791 				/*
20792 				 * If there's a spillover, but the following
20793 				 * xmit_tail couldn't give us enough octets
20794 				 * to reach "len", then stop the current
20795 				 * Multidata creation and let the legacy
20796 				 * tcp_send() path take over.  We don't want
20797 				 * to send the tiny segment as part of this
20798 				 * Multidata for performance reasons; instead,
20799 				 * we let the legacy path deal with grouping
20800 				 * it with the subsequent small mblks.
20801 				 */
20802 				if (*usable >= len &&
20803 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20804 					max_pld = 0;
20805 					break;	/* done */
20806 				}
20807 
20808 				/*
20809 				 * We can't spillover, and we are near
20810 				 * the end of the current payload buffer,
20811 				 * so send what's left.
20812 				 */
20813 				ASSERT(*tail_unsent > 0);
20814 				len = *tail_unsent;
20815 			}
20816 
20817 			/* tail_unsent is negated if there is a spillover */
20818 			*tail_unsent -= len;
20819 			*usable -= len;
20820 			ASSERT(*usable >= 0);
20821 
20822 			if (*usable < mss)
20823 				seg_len = *usable;
20824 			/*
20825 			 * Sender SWS avoidance; see comments in tcp_send();
20826 			 * everything else is the same, except that we only
20827 			 * do this here if there is no more data to be sent
20828 			 * following the current xmit_tail.  We don't check
20829 			 * for 1-byte urgent data because we shouldn't get
20830 			 * here if TCP_URG_VALID is set.
20831 			 */
20832 			if (*usable > 0 && *usable < mss &&
20833 			    ((md_pbuf_nxt == NULL &&
20834 			    (*xmit_tail)->b_cont == NULL) ||
20835 			    (md_pbuf_nxt != NULL &&
20836 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20837 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20838 			    (tcp->tcp_unsent -
20839 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20840 			    !tcp->tcp_zero_win_probe) {
20841 				if ((*snxt + len) == tcp->tcp_snxt &&
20842 				    (*snxt + len) == tcp->tcp_suna) {
20843 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20844 				}
20845 				done = B_TRUE;
20846 			}
20847 
20848 			/*
20849 			 * Prime pump for IP's checksumming on our behalf;
20850 			 * include the adjustment for a source route if any.
20851 			 * Do this only for software/partial hardware checksum
20852 			 * offload, as this field gets zeroed out later for
20853 			 * the full hardware checksum offload case.
20854 			 */
20855 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20856 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20857 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20858 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20859 			}
20860 
20861 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20862 			*snxt += len;
20863 
20864 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20865 			/*
20866 			 * We set the PUSH bit only if TCP has no more buffered
20867 			 * data to be transmitted (or if sender SWS avoidance
20868 			 * takes place), as opposed to setting it for every
20869 			 * last packet in the burst.
20870 			 */
20871 			if (done ||
20872 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20873 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20874 
20875 			/*
20876 			 * Set FIN bit if this is our last segment; snxt
20877 			 * already includes its length, and it will not
20878 			 * be adjusted after this point.
20879 			 */
20880 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20881 			    *snxt == tcp->tcp_fss) {
20882 				if (!tcp->tcp_fin_acked) {
20883 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20884 					BUMP_MIB(&tcps->tcps_mib,
20885 					    tcpOutControl);
20886 				}
20887 				if (!tcp->tcp_fin_sent) {
20888 					tcp->tcp_fin_sent = B_TRUE;
20889 					/*
20890 					 * tcp state must be ESTABLISHED
20891 					 * in order for us to get here in
20892 					 * the first place.
20893 					 */
20894 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20895 
20896 					/*
20897 					 * Upon returning from this routine,
20898 					 * tcp_wput_data() will set tcp_snxt
20899 					 * to be equal to snxt + tcp_fin_sent.
20900 					 * This is essentially the same as
20901 					 * setting it to tcp_fss + 1.
20902 					 */
20903 				}
20904 			}
20905 
20906 			tcp->tcp_last_sent_len = (ushort_t)len;
20907 
20908 			len += tcp_hdr_len;
20909 			if (tcp->tcp_ipversion == IPV4_VERSION)
20910 				tcp->tcp_ipha->ipha_length = htons(len);
20911 			else
20912 				tcp->tcp_ip6h->ip6_plen = htons(len -
20913 				    ((char *)&tcp->tcp_ip6h[1] -
20914 				    tcp->tcp_iphc));
20915 
20916 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20917 
20918 			/* setup header fragment */
20919 			PDESC_HDR_ADD(pkt_info,
20920 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20921 			    tcp->tcp_mdt_hdr_head,		/* head room */
20922 			    tcp_hdr_len,			/* len */
20923 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20924 
20925 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20926 			    hdr_frag_sz);
20927 			ASSERT(MBLKIN(md_hbuf,
20928 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20929 			    PDESC_HDRSIZE(pkt_info)));
20930 
20931 			/* setup first payload fragment */
20932 			PDESC_PLD_INIT(pkt_info);
20933 			PDESC_PLD_SPAN_ADD(pkt_info,
20934 			    pbuf_idx,				/* index */
20935 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20936 			    tcp->tcp_last_sent_len);		/* len */
20937 
20938 			/* create a split-packet in case of a spillover */
20939 			if (md_pbuf_nxt != NULL) {
20940 				ASSERT(spill > 0);
20941 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20942 				ASSERT(!add_buffer);
20943 
20944 				md_pbuf = md_pbuf_nxt;
20945 				md_pbuf_nxt = NULL;
20946 				pbuf_idx = pbuf_idx_nxt;
20947 				pbuf_idx_nxt = -1;
20948 				cur_pld_off = spill;
20949 
20950 				/* trim out first payload fragment */
20951 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20952 
20953 				/* setup second payload fragment */
20954 				PDESC_PLD_SPAN_ADD(pkt_info,
20955 				    pbuf_idx,			/* index */
20956 				    md_pbuf->b_rptr,		/* start */
20957 				    spill);			/* len */
20958 
20959 				if ((*xmit_tail)->b_next == NULL) {
20960 					/*
20961 					 * Store the lbolt used for RTT
20962 					 * estimation. We can only record one
20963 					 * timestamp per mblk so we do it when
20964 					 * we reach the end of the payload
20965 					 * buffer.  Also we only take a new
20966 					 * timestamp sample when the previous
20967 					 * timed data from the same mblk has
20968 					 * been ack'ed.
20969 					 */
20970 					(*xmit_tail)->b_prev = local_time;
20971 					(*xmit_tail)->b_next =
20972 					    (mblk_t *)(uintptr_t)first_snxt;
20973 				}
20974 
20975 				first_snxt = *snxt - spill;
20976 
20977 				/*
20978 				 * Advance xmit_tail; usable could be 0 by
20979 				 * the time we got here, but we made sure
20980 				 * above that we would only spillover to
20981 				 * the next data block if usable includes
20982 				 * the spilled-over amount prior to the
20983 				 * subtraction.  Therefore, we are sure
20984 				 * that xmit_tail->b_cont can't be NULL.
20985 				 */
20986 				ASSERT((*xmit_tail)->b_cont != NULL);
20987 				*xmit_tail = (*xmit_tail)->b_cont;
20988 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20989 				    (uintptr_t)INT_MAX);
20990 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20991 			} else {
20992 				cur_pld_off += tcp->tcp_last_sent_len;
20993 			}
20994 
20995 			/*
20996 			 * Fill in the header using the template header, and
20997 			 * add options such as time-stamp, ECN and/or SACK,
20998 			 * as needed.
20999 			 */
21000 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
21001 			    (clock_t)local_time, num_sack_blk);
21002 
21003 			/* take care of some IP header businesses */
21004 			if (af == AF_INET) {
21005 				ipha = (ipha_t *)pkt_info->hdr_rptr;
21006 
21007 				ASSERT(OK_32PTR((uchar_t *)ipha));
21008 				ASSERT(PDESC_HDRL(pkt_info) >=
21009 				    IP_SIMPLE_HDR_LENGTH);
21010 				ASSERT(ipha->ipha_version_and_hdr_length ==
21011 				    IP_SIMPLE_HDR_VERSION);
21012 
21013 				/*
21014 				 * Assign ident value for current packet; see
21015 				 * related comments in ip_wput_ire() about the
21016 				 * contract private interface with clustering
21017 				 * group.
21018 				 */
21019 				clusterwide = B_FALSE;
21020 				if (cl_inet_ipident != NULL) {
21021 					ASSERT(cl_inet_isclusterwide != NULL);
21022 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
21023 					    AF_INET,
21024 					    (uint8_t *)(uintptr_t)src)) {
21025 						ipha->ipha_ident =
21026 						    (*cl_inet_ipident)
21027 						    (IPPROTO_IP, AF_INET,
21028 						    (uint8_t *)(uintptr_t)src,
21029 						    (uint8_t *)(uintptr_t)dst);
21030 						clusterwide = B_TRUE;
21031 					}
21032 				}
21033 
21034 				if (!clusterwide) {
21035 					ipha->ipha_ident = (uint16_t)
21036 					    atomic_add_32_nv(
21037 						&ire->ire_ident, 1);
21038 				}
21039 #ifndef _BIG_ENDIAN
21040 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
21041 				    (ipha->ipha_ident >> 8);
21042 #endif
21043 			} else {
21044 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
21045 
21046 				ASSERT(OK_32PTR((uchar_t *)ip6h));
21047 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
21048 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
21049 				ASSERT(PDESC_HDRL(pkt_info) >=
21050 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
21051 				    TCP_CHECKSUM_SIZE));
21052 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21053 
21054 				if (tcp->tcp_ip_forward_progress) {
21055 					rconfirm = B_TRUE;
21056 					tcp->tcp_ip_forward_progress = B_FALSE;
21057 				}
21058 			}
21059 
21060 			/* at least one payload span, and at most two */
21061 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
21062 
21063 			/* add the packet descriptor to Multidata */
21064 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
21065 			    KM_NOSLEEP)) == NULL) {
21066 				/*
21067 				 * Any failure other than ENOMEM indicates
21068 				 * that we have passed in invalid pkt_info
21069 				 * or parameters to mmd_addpdesc, which must
21070 				 * not happen.
21071 				 *
21072 				 * EINVAL is a result of failure on boundary
21073 				 * checks against the pkt_info contents.  It
21074 				 * should not happen, and we panic because
21075 				 * either there's horrible heap corruption,
21076 				 * and/or programming mistake.
21077 				 */
21078 				if (err != ENOMEM) {
21079 					cmn_err(CE_PANIC, "tcp_multisend: "
21080 					    "pdesc logic error detected for "
21081 					    "tcp %p mmd %p pinfo %p (%d)\n",
21082 					    (void *)tcp, (void *)mmd,
21083 					    (void *)pkt_info, err);
21084 				}
21085 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
21086 				goto legacy_send; /* out_of_mem */
21087 			}
21088 			ASSERT(pkt != NULL);
21089 
21090 			/* calculate IP header and TCP checksums */
21091 			if (af == AF_INET) {
21092 				/* calculate pseudo-header checksum */
21093 				cksum = (dst >> 16) + (dst & 0xFFFF) +
21094 				    (src >> 16) + (src & 0xFFFF);
21095 
21096 				/* offset for TCP header checksum */
21097 				up = IPH_TCPH_CHECKSUMP(ipha,
21098 				    IP_SIMPLE_HDR_LENGTH);
21099 			} else {
21100 				up = (uint16_t *)&ip6h->ip6_src;
21101 
21102 				/* calculate pseudo-header checksum */
21103 				cksum = up[0] + up[1] + up[2] + up[3] +
21104 				    up[4] + up[5] + up[6] + up[7] +
21105 				    up[8] + up[9] + up[10] + up[11] +
21106 				    up[12] + up[13] + up[14] + up[15];
21107 
21108 				/* Fold the initial sum */
21109 				cksum = (cksum & 0xffff) + (cksum >> 16);
21110 
21111 				up = (uint16_t *)(((uchar_t *)ip6h) +
21112 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
21113 			}
21114 
21115 			if (hwcksum_flags & HCK_FULLCKSUM) {
21116 				/* clear checksum field for hardware */
21117 				*up = 0;
21118 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
21119 				uint32_t sum;
21120 
21121 				/* pseudo-header checksumming */
21122 				sum = *up + cksum + IP_TCP_CSUM_COMP;
21123 				sum = (sum & 0xFFFF) + (sum >> 16);
21124 				*up = (sum & 0xFFFF) + (sum >> 16);
21125 			} else {
21126 				/* software checksumming */
21127 				TCP_STAT(tcps, tcp_out_sw_cksum);
21128 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
21129 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
21130 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
21131 				    cksum + IP_TCP_CSUM_COMP);
21132 				if (*up == 0)
21133 					*up = 0xFFFF;
21134 			}
21135 
21136 			/* IPv4 header checksum */
21137 			if (af == AF_INET) {
21138 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
21139 					ipha->ipha_hdr_checksum = 0;
21140 				} else {
21141 					IP_HDR_CKSUM(ipha, cksum,
21142 					    ((uint32_t *)ipha)[0],
21143 					    ((uint16_t *)ipha)[4]);
21144 				}
21145 			}
21146 
21147 			if (af == AF_INET &&
21148 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
21149 			    af == AF_INET6 &&
21150 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
21151 				mblk_t	*mp, *mp1;
21152 				uchar_t	*hdr_rptr, *hdr_wptr;
21153 				uchar_t	*pld_rptr, *pld_wptr;
21154 
21155 				/*
21156 				 * We reconstruct a pseudo packet for the hooks
21157 				 * framework using mmd_transform_link().
21158 				 * If it is a split packet we pullup the
21159 				 * payload. FW_HOOKS expects a pkt comprising
21160 				 * of two mblks: a header and the payload.
21161 				 */
21162 				if ((mp = mmd_transform_link(pkt)) == NULL) {
21163 					TCP_STAT(tcps, tcp_mdt_allocfail);
21164 					goto legacy_send;
21165 				}
21166 
21167 				if (pkt_info->pld_cnt > 1) {
21168 					/* split payload, more than one pld */
21169 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
21170 					    NULL) {
21171 						freemsg(mp);
21172 						TCP_STAT(tcps,
21173 						    tcp_mdt_allocfail);
21174 						goto legacy_send;
21175 					}
21176 					freemsg(mp->b_cont);
21177 					mp->b_cont = mp1;
21178 				} else {
21179 					mp1 = mp->b_cont;
21180 				}
21181 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
21182 
21183 				/*
21184 				 * Remember the message offsets. This is so we
21185 				 * can detect changes when we return from the
21186 				 * FW_HOOKS callbacks.
21187 				 */
21188 				hdr_rptr = mp->b_rptr;
21189 				hdr_wptr = mp->b_wptr;
21190 				pld_rptr = mp->b_cont->b_rptr;
21191 				pld_wptr = mp->b_cont->b_wptr;
21192 
21193 				if (af == AF_INET) {
21194 					DTRACE_PROBE4(
21195 					    ip4__physical__out__start,
21196 					    ill_t *, NULL,
21197 					    ill_t *, ill,
21198 					    ipha_t *, ipha,
21199 					    mblk_t *, mp);
21200 					FW_HOOKS(
21201 					    ipst->ips_ip4_physical_out_event,
21202 					    ipst->ips_ipv4firewall_physical_out,
21203 					    NULL, ill, ipha, mp, mp, 0, ipst);
21204 					DTRACE_PROBE1(
21205 					    ip4__physical__out__end,
21206 					    mblk_t *, mp);
21207 				} else {
21208 					DTRACE_PROBE4(
21209 					    ip6__physical__out_start,
21210 					    ill_t *, NULL,
21211 					    ill_t *, ill,
21212 					    ip6_t *, ip6h,
21213 					    mblk_t *, mp);
21214 					FW_HOOKS6(
21215 					    ipst->ips_ip6_physical_out_event,
21216 					    ipst->ips_ipv6firewall_physical_out,
21217 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21218 					DTRACE_PROBE1(
21219 					    ip6__physical__out__end,
21220 					    mblk_t *, mp);
21221 				}
21222 
21223 				if (mp == NULL ||
21224 				    (mp1 = mp->b_cont) == NULL ||
21225 				    mp->b_rptr != hdr_rptr ||
21226 				    mp->b_wptr != hdr_wptr ||
21227 				    mp1->b_rptr != pld_rptr ||
21228 				    mp1->b_wptr != pld_wptr ||
21229 				    mp1->b_cont != NULL) {
21230 					/*
21231 					 * We abandon multidata processing and
21232 					 * return to the normal path, either
21233 					 * when a packet is blocked, or when
21234 					 * the boundaries of header buffer or
21235 					 * payload buffer have been changed by
21236 					 * FW_HOOKS[6].
21237 					 */
21238 					if (mp != NULL)
21239 						freemsg(mp);
21240 					goto legacy_send;
21241 				}
21242 				/* Finished with the pseudo packet */
21243 				freemsg(mp);
21244 			}
21245 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21246 			    ill, ipha, ip6h);
21247 			/* advance header offset */
21248 			cur_hdr_off += hdr_frag_sz;
21249 
21250 			obbytes += tcp->tcp_last_sent_len;
21251 			++obsegs;
21252 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21253 		    *tail_unsent > 0);
21254 
21255 		if ((*xmit_tail)->b_next == NULL) {
21256 			/*
21257 			 * Store the lbolt used for RTT estimation. We can only
21258 			 * record one timestamp per mblk so we do it when we
21259 			 * reach the end of the payload buffer. Also we only
21260 			 * take a new timestamp sample when the previous timed
21261 			 * data from the same mblk has been ack'ed.
21262 			 */
21263 			(*xmit_tail)->b_prev = local_time;
21264 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21265 		}
21266 
21267 		ASSERT(*tail_unsent >= 0);
21268 		if (*tail_unsent > 0) {
21269 			/*
21270 			 * We got here because we broke out of the above
21271 			 * loop due to of one of the following cases:
21272 			 *
21273 			 *   1. len < adjusted MSS (i.e. small),
21274 			 *   2. Sender SWS avoidance,
21275 			 *   3. max_pld is zero.
21276 			 *
21277 			 * We are done for this Multidata, so trim our
21278 			 * last payload buffer (if any) accordingly.
21279 			 */
21280 			if (md_pbuf != NULL)
21281 				md_pbuf->b_wptr -= *tail_unsent;
21282 		} else if (*usable > 0) {
21283 			*xmit_tail = (*xmit_tail)->b_cont;
21284 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21285 			    (uintptr_t)INT_MAX);
21286 			*tail_unsent = (int)MBLKL(*xmit_tail);
21287 			add_buffer = B_TRUE;
21288 		}
21289 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21290 	    (tcp_mdt_chain || max_pld > 0));
21291 
21292 	if (md_mp_head != NULL) {
21293 		/* send everything down */
21294 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21295 		    &rconfirm);
21296 	}
21297 
21298 #undef PREP_NEW_MULTIDATA
21299 #undef PREP_NEW_PBUF
21300 #undef IPVER
21301 
21302 	IRE_REFRELE(ire);
21303 	return (0);
21304 }
21305 
21306 /*
21307  * A wrapper function for sending one or more Multidata messages down to
21308  * the module below ip; this routine does not release the reference of the
21309  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21310  */
21311 static void
21312 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21313     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21314 {
21315 	uint64_t delta;
21316 	nce_t *nce;
21317 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21318 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21319 
21320 	ASSERT(ire != NULL && ill != NULL);
21321 	ASSERT(ire->ire_stq != NULL);
21322 	ASSERT(md_mp_head != NULL);
21323 	ASSERT(rconfirm != NULL);
21324 
21325 	/* adjust MIBs and IRE timestamp */
21326 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21327 	tcp->tcp_obsegs += obsegs;
21328 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21329 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21330 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21331 
21332 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21333 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21334 	} else {
21335 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21336 	}
21337 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21338 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21339 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21340 
21341 	ire->ire_ob_pkt_count += obsegs;
21342 	if (ire->ire_ipif != NULL)
21343 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21344 	ire->ire_last_used_time = lbolt;
21345 
21346 	if (ipst->ips_ipobs_enabled) {
21347 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21348 		pdesc_t *dl_pkt;
21349 		pdescinfo_t pinfo;
21350 		mblk_t *nmp;
21351 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21352 
21353 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21354 		    (dl_pkt != NULL);
21355 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21356 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21357 				continue;
21358 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21359 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21360 			freemsg(nmp);
21361 		}
21362 	}
21363 
21364 	/* send it down */
21365 	putnext(ire->ire_stq, md_mp_head);
21366 
21367 	/* we're done for TCP/IPv4 */
21368 	if (tcp->tcp_ipversion == IPV4_VERSION)
21369 		return;
21370 
21371 	nce = ire->ire_nce;
21372 
21373 	ASSERT(nce != NULL);
21374 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21375 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21376 
21377 	/* reachability confirmation? */
21378 	if (*rconfirm) {
21379 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21380 		if (nce->nce_state != ND_REACHABLE) {
21381 			mutex_enter(&nce->nce_lock);
21382 			nce->nce_state = ND_REACHABLE;
21383 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21384 			mutex_exit(&nce->nce_lock);
21385 			(void) untimeout(nce->nce_timeout_id);
21386 			if (ip_debug > 2) {
21387 				/* ip1dbg */
21388 				pr_addr_dbg("tcp_multisend_data: state "
21389 				    "for %s changed to REACHABLE\n",
21390 				    AF_INET6, &ire->ire_addr_v6);
21391 			}
21392 		}
21393 		/* reset transport reachability confirmation */
21394 		*rconfirm = B_FALSE;
21395 	}
21396 
21397 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21398 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21399 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21400 
21401 	if (delta > (uint64_t)ill->ill_reachable_time) {
21402 		mutex_enter(&nce->nce_lock);
21403 		switch (nce->nce_state) {
21404 		case ND_REACHABLE:
21405 		case ND_STALE:
21406 			/*
21407 			 * ND_REACHABLE is identical to ND_STALE in this
21408 			 * specific case. If reachable time has expired for
21409 			 * this neighbor (delta is greater than reachable
21410 			 * time), conceptually, the neighbor cache is no
21411 			 * longer in REACHABLE state, but already in STALE
21412 			 * state.  So the correct transition here is to
21413 			 * ND_DELAY.
21414 			 */
21415 			nce->nce_state = ND_DELAY;
21416 			mutex_exit(&nce->nce_lock);
21417 			NDP_RESTART_TIMER(nce,
21418 			    ipst->ips_delay_first_probe_time);
21419 			if (ip_debug > 3) {
21420 				/* ip2dbg */
21421 				pr_addr_dbg("tcp_multisend_data: state "
21422 				    "for %s changed to DELAY\n",
21423 				    AF_INET6, &ire->ire_addr_v6);
21424 			}
21425 			break;
21426 		case ND_DELAY:
21427 		case ND_PROBE:
21428 			mutex_exit(&nce->nce_lock);
21429 			/* Timers have already started */
21430 			break;
21431 		case ND_UNREACHABLE:
21432 			/*
21433 			 * ndp timer has detected that this nce is
21434 			 * unreachable and initiated deleting this nce
21435 			 * and all its associated IREs. This is a race
21436 			 * where we found the ire before it was deleted
21437 			 * and have just sent out a packet using this
21438 			 * unreachable nce.
21439 			 */
21440 			mutex_exit(&nce->nce_lock);
21441 			break;
21442 		default:
21443 			ASSERT(0);
21444 		}
21445 	}
21446 }
21447 
21448 /*
21449  * Derived from tcp_send_data().
21450  */
21451 static void
21452 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21453     int num_lso_seg)
21454 {
21455 	ipha_t		*ipha;
21456 	mblk_t		*ire_fp_mp;
21457 	uint_t		ire_fp_mp_len;
21458 	uint32_t	hcksum_txflags = 0;
21459 	ipaddr_t	src;
21460 	ipaddr_t	dst;
21461 	uint32_t	cksum;
21462 	uint16_t	*up;
21463 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21464 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21465 
21466 	ASSERT(DB_TYPE(mp) == M_DATA);
21467 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21468 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21469 	ASSERT(tcp->tcp_connp != NULL);
21470 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21471 
21472 	ipha = (ipha_t *)mp->b_rptr;
21473 	src = ipha->ipha_src;
21474 	dst = ipha->ipha_dst;
21475 
21476 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21477 
21478 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21479 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21480 	    num_lso_seg);
21481 #ifndef _BIG_ENDIAN
21482 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21483 #endif
21484 	if (tcp->tcp_snd_zcopy_aware) {
21485 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21486 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21487 			mp = tcp_zcopy_disable(tcp, mp);
21488 	}
21489 
21490 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21491 		ASSERT(ill->ill_hcksum_capab != NULL);
21492 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21493 	}
21494 
21495 	/*
21496 	 * Since the TCP checksum should be recalculated by h/w, we can just
21497 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21498 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21499 	 * The partial pseudo-header excludes TCP length, that was calculated
21500 	 * in tcp_send(), so to zero *up before further processing.
21501 	 */
21502 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21503 
21504 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21505 	*up = 0;
21506 
21507 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21508 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21509 
21510 	/*
21511 	 * Append LSO flags and mss to the mp.
21512 	 */
21513 	lso_info_set(mp, mss, HW_LSO);
21514 
21515 	ipha->ipha_fragment_offset_and_flags |=
21516 	    (uint32_t)htons(ire->ire_frag_flag);
21517 
21518 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21519 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21520 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21521 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21522 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21523 
21524 	UPDATE_OB_PKT_COUNT(ire);
21525 	ire->ire_last_used_time = lbolt;
21526 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21527 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21528 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21529 	    ntohs(ipha->ipha_length));
21530 
21531 	DTRACE_PROBE4(ip4__physical__out__start,
21532 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
21533 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
21534 	    ipst->ips_ipv4firewall_physical_out, NULL,
21535 	    ill, ipha, mp, mp, 0, ipst);
21536 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21537 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
21538 
21539 	if (mp != NULL) {
21540 		if (ipst->ips_ipobs_enabled) {
21541 			zoneid_t szone;
21542 
21543 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
21544 			    ipst, ALL_ZONES);
21545 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21546 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
21547 		}
21548 
21549 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0);
21550 	}
21551 }
21552 
21553 /*
21554  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21555  * scheme, and returns one of the following:
21556  *
21557  * -1 = failed allocation.
21558  *  0 = success; burst count reached, or usable send window is too small,
21559  *      and that we'd rather wait until later before sending again.
21560  *  1 = success; we are called from tcp_multisend(), and both usable send
21561  *      window and tail_unsent are greater than the MDT threshold, and thus
21562  *      Multidata Transmit should be used instead.
21563  */
21564 static int
21565 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21566     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21567     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21568     const int mdt_thres)
21569 {
21570 	int num_burst_seg = tcp->tcp_snd_burst;
21571 	ire_t		*ire = NULL;
21572 	ill_t		*ill = NULL;
21573 	mblk_t		*ire_fp_mp = NULL;
21574 	uint_t		ire_fp_mp_len = 0;
21575 	int		num_lso_seg = 1;
21576 	uint_t		lso_usable;
21577 	boolean_t	do_lso_send = B_FALSE;
21578 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21579 
21580 	/*
21581 	 * Check LSO capability before any further work. And the similar check
21582 	 * need to be done in for(;;) loop.
21583 	 * LSO will be deployed when therer is more than one mss of available
21584 	 * data and a burst transmission is allowed.
21585 	 */
21586 	if (tcp->tcp_lso &&
21587 	    (tcp->tcp_valid_bits == 0 ||
21588 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21589 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21590 		/*
21591 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21592 		 */
21593 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21594 			/*
21595 			 * Enable LSO with this transmission.
21596 			 * Since IRE has been hold in
21597 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21598 			 * should be called before return.
21599 			 */
21600 			do_lso_send = B_TRUE;
21601 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21602 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21603 			/* Round up to multiple of 4 */
21604 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21605 		} else {
21606 			do_lso_send = B_FALSE;
21607 			ill = NULL;
21608 		}
21609 	}
21610 
21611 	for (;;) {
21612 		struct datab	*db;
21613 		tcph_t		*tcph;
21614 		uint32_t	sum;
21615 		mblk_t		*mp, *mp1;
21616 		uchar_t		*rptr;
21617 		int		len;
21618 
21619 		/*
21620 		 * If we're called by tcp_multisend(), and the amount of
21621 		 * sendable data as well as the size of current xmit_tail
21622 		 * is beyond the MDT threshold, return to the caller and
21623 		 * let the large data transmit be done using MDT.
21624 		 */
21625 		if (*usable > 0 && *usable > mdt_thres &&
21626 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21627 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21628 			ASSERT(tcp->tcp_mdt);
21629 			return (1);	/* success; do large send */
21630 		}
21631 
21632 		if (num_burst_seg == 0)
21633 			break;		/* success; burst count reached */
21634 
21635 		/*
21636 		 * Calculate the maximum payload length we can send in *one*
21637 		 * time.
21638 		 */
21639 		if (do_lso_send) {
21640 			/*
21641 			 * Check whether need to do LSO any more.
21642 			 */
21643 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21644 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21645 				lso_usable = MIN(lso_usable,
21646 				    num_burst_seg * mss);
21647 
21648 				num_lso_seg = lso_usable / mss;
21649 				if (lso_usable % mss) {
21650 					num_lso_seg++;
21651 					tcp->tcp_last_sent_len = (ushort_t)
21652 					    (lso_usable % mss);
21653 				} else {
21654 					tcp->tcp_last_sent_len = (ushort_t)mss;
21655 				}
21656 			} else {
21657 				do_lso_send = B_FALSE;
21658 				num_lso_seg = 1;
21659 				lso_usable = mss;
21660 			}
21661 		}
21662 
21663 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21664 
21665 		/*
21666 		 * Adjust num_burst_seg here.
21667 		 */
21668 		num_burst_seg -= num_lso_seg;
21669 
21670 		len = mss;
21671 		if (len > *usable) {
21672 			ASSERT(do_lso_send == B_FALSE);
21673 
21674 			len = *usable;
21675 			if (len <= 0) {
21676 				/* Terminate the loop */
21677 				break;	/* success; too small */
21678 			}
21679 			/*
21680 			 * Sender silly-window avoidance.
21681 			 * Ignore this if we are going to send a
21682 			 * zero window probe out.
21683 			 *
21684 			 * TODO: force data into microscopic window?
21685 			 *	==> (!pushed || (unsent > usable))
21686 			 */
21687 			if (len < (tcp->tcp_max_swnd >> 1) &&
21688 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21689 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21690 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21691 				/*
21692 				 * If the retransmit timer is not running
21693 				 * we start it so that we will retransmit
21694 				 * in the case when the the receiver has
21695 				 * decremented the window.
21696 				 */
21697 				if (*snxt == tcp->tcp_snxt &&
21698 				    *snxt == tcp->tcp_suna) {
21699 					/*
21700 					 * We are not supposed to send
21701 					 * anything.  So let's wait a little
21702 					 * bit longer before breaking SWS
21703 					 * avoidance.
21704 					 *
21705 					 * What should the value be?
21706 					 * Suggestion: MAX(init rexmit time,
21707 					 * tcp->tcp_rto)
21708 					 */
21709 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21710 				}
21711 				break;	/* success; too small */
21712 			}
21713 		}
21714 
21715 		tcph = tcp->tcp_tcph;
21716 
21717 		/*
21718 		 * The reason to adjust len here is that we need to set flags
21719 		 * and calculate checksum.
21720 		 */
21721 		if (do_lso_send)
21722 			len = lso_usable;
21723 
21724 		*usable -= len; /* Approximate - can be adjusted later */
21725 		if (*usable > 0)
21726 			tcph->th_flags[0] = TH_ACK;
21727 		else
21728 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21729 
21730 		/*
21731 		 * Prime pump for IP's checksumming on our behalf
21732 		 * Include the adjustment for a source route if any.
21733 		 */
21734 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21735 		sum = (sum >> 16) + (sum & 0xFFFF);
21736 		U16_TO_ABE16(sum, tcph->th_sum);
21737 
21738 		U32_TO_ABE32(*snxt, tcph->th_seq);
21739 
21740 		/*
21741 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21742 		 * set.  For the case when TCP_FSS_VALID is the only valid
21743 		 * bit (normal active close), branch off only when we think
21744 		 * that the FIN flag needs to be set.  Note for this case,
21745 		 * that (snxt + len) may not reflect the actual seg_len,
21746 		 * as len may be further reduced in tcp_xmit_mp().  If len
21747 		 * gets modified, we will end up here again.
21748 		 */
21749 		if (tcp->tcp_valid_bits != 0 &&
21750 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21751 		    ((*snxt + len) == tcp->tcp_fss))) {
21752 			uchar_t		*prev_rptr;
21753 			uint32_t	prev_snxt = tcp->tcp_snxt;
21754 
21755 			if (*tail_unsent == 0) {
21756 				ASSERT((*xmit_tail)->b_cont != NULL);
21757 				*xmit_tail = (*xmit_tail)->b_cont;
21758 				prev_rptr = (*xmit_tail)->b_rptr;
21759 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21760 				    (*xmit_tail)->b_rptr);
21761 			} else {
21762 				prev_rptr = (*xmit_tail)->b_rptr;
21763 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21764 				    *tail_unsent;
21765 			}
21766 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21767 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21768 			/* Restore tcp_snxt so we get amount sent right. */
21769 			tcp->tcp_snxt = prev_snxt;
21770 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21771 				/*
21772 				 * If the previous timestamp is still in use,
21773 				 * don't stomp on it.
21774 				 */
21775 				if ((*xmit_tail)->b_next == NULL) {
21776 					(*xmit_tail)->b_prev = local_time;
21777 					(*xmit_tail)->b_next =
21778 					    (mblk_t *)(uintptr_t)(*snxt);
21779 				}
21780 			} else
21781 				(*xmit_tail)->b_rptr = prev_rptr;
21782 
21783 			if (mp == NULL) {
21784 				if (ire != NULL)
21785 					IRE_REFRELE(ire);
21786 				return (-1);
21787 			}
21788 			mp1 = mp->b_cont;
21789 
21790 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21791 				tcp->tcp_last_sent_len = (ushort_t)len;
21792 			while (mp1->b_cont) {
21793 				*xmit_tail = (*xmit_tail)->b_cont;
21794 				(*xmit_tail)->b_prev = local_time;
21795 				(*xmit_tail)->b_next =
21796 				    (mblk_t *)(uintptr_t)(*snxt);
21797 				mp1 = mp1->b_cont;
21798 			}
21799 			*snxt += len;
21800 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21801 			BUMP_LOCAL(tcp->tcp_obsegs);
21802 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21803 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21804 			tcp_send_data(tcp, q, mp);
21805 			continue;
21806 		}
21807 
21808 		*snxt += len;	/* Adjust later if we don't send all of len */
21809 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21810 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21811 
21812 		if (*tail_unsent) {
21813 			/* Are the bytes above us in flight? */
21814 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21815 			if (rptr != (*xmit_tail)->b_rptr) {
21816 				*tail_unsent -= len;
21817 				if (len <= mss) /* LSO is unusable */
21818 					tcp->tcp_last_sent_len = (ushort_t)len;
21819 				len += tcp_hdr_len;
21820 				if (tcp->tcp_ipversion == IPV4_VERSION)
21821 					tcp->tcp_ipha->ipha_length = htons(len);
21822 				else
21823 					tcp->tcp_ip6h->ip6_plen =
21824 					    htons(len -
21825 					    ((char *)&tcp->tcp_ip6h[1] -
21826 					    tcp->tcp_iphc));
21827 				mp = dupb(*xmit_tail);
21828 				if (mp == NULL) {
21829 					if (ire != NULL)
21830 						IRE_REFRELE(ire);
21831 					return (-1);	/* out_of_mem */
21832 				}
21833 				mp->b_rptr = rptr;
21834 				/*
21835 				 * If the old timestamp is no longer in use,
21836 				 * sample a new timestamp now.
21837 				 */
21838 				if ((*xmit_tail)->b_next == NULL) {
21839 					(*xmit_tail)->b_prev = local_time;
21840 					(*xmit_tail)->b_next =
21841 					    (mblk_t *)(uintptr_t)(*snxt-len);
21842 				}
21843 				goto must_alloc;
21844 			}
21845 		} else {
21846 			*xmit_tail = (*xmit_tail)->b_cont;
21847 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21848 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21849 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21850 			    (*xmit_tail)->b_rptr);
21851 		}
21852 
21853 		(*xmit_tail)->b_prev = local_time;
21854 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21855 
21856 		*tail_unsent -= len;
21857 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21858 			tcp->tcp_last_sent_len = (ushort_t)len;
21859 
21860 		len += tcp_hdr_len;
21861 		if (tcp->tcp_ipversion == IPV4_VERSION)
21862 			tcp->tcp_ipha->ipha_length = htons(len);
21863 		else
21864 			tcp->tcp_ip6h->ip6_plen = htons(len -
21865 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21866 
21867 		mp = dupb(*xmit_tail);
21868 		if (mp == NULL) {
21869 			if (ire != NULL)
21870 				IRE_REFRELE(ire);
21871 			return (-1);	/* out_of_mem */
21872 		}
21873 
21874 		len = tcp_hdr_len;
21875 		/*
21876 		 * There are four reasons to allocate a new hdr mblk:
21877 		 *  1) The bytes above us are in use by another packet
21878 		 *  2) We don't have good alignment
21879 		 *  3) The mblk is being shared
21880 		 *  4) We don't have enough room for a header
21881 		 */
21882 		rptr = mp->b_rptr - len;
21883 		if (!OK_32PTR(rptr) ||
21884 		    ((db = mp->b_datap), db->db_ref != 2) ||
21885 		    rptr < db->db_base + ire_fp_mp_len) {
21886 			/* NOTE: we assume allocb returns an OK_32PTR */
21887 
21888 		must_alloc:;
21889 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21890 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21891 			if (mp1 == NULL) {
21892 				freemsg(mp);
21893 				if (ire != NULL)
21894 					IRE_REFRELE(ire);
21895 				return (-1);	/* out_of_mem */
21896 			}
21897 			mp1->b_cont = mp;
21898 			mp = mp1;
21899 			/* Leave room for Link Level header */
21900 			len = tcp_hdr_len;
21901 			rptr =
21902 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21903 			mp->b_wptr = &rptr[len];
21904 		}
21905 
21906 		/*
21907 		 * Fill in the header using the template header, and add
21908 		 * options such as time-stamp, ECN and/or SACK, as needed.
21909 		 */
21910 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21911 
21912 		mp->b_rptr = rptr;
21913 
21914 		if (*tail_unsent) {
21915 			int spill = *tail_unsent;
21916 
21917 			mp1 = mp->b_cont;
21918 			if (mp1 == NULL)
21919 				mp1 = mp;
21920 
21921 			/*
21922 			 * If we're a little short, tack on more mblks until
21923 			 * there is no more spillover.
21924 			 */
21925 			while (spill < 0) {
21926 				mblk_t *nmp;
21927 				int nmpsz;
21928 
21929 				nmp = (*xmit_tail)->b_cont;
21930 				nmpsz = MBLKL(nmp);
21931 
21932 				/*
21933 				 * Excess data in mblk; can we split it?
21934 				 * If MDT is enabled for the connection,
21935 				 * keep on splitting as this is a transient
21936 				 * send path.
21937 				 */
21938 				if (!do_lso_send && !tcp->tcp_mdt &&
21939 				    (spill + nmpsz > 0)) {
21940 					/*
21941 					 * Don't split if stream head was
21942 					 * told to break up larger writes
21943 					 * into smaller ones.
21944 					 */
21945 					if (tcp->tcp_maxpsz > 0)
21946 						break;
21947 
21948 					/*
21949 					 * Next mblk is less than SMSS/2
21950 					 * rounded up to nearest 64-byte;
21951 					 * let it get sent as part of the
21952 					 * next segment.
21953 					 */
21954 					if (tcp->tcp_localnet &&
21955 					    !tcp->tcp_cork &&
21956 					    (nmpsz < roundup((mss >> 1), 64)))
21957 						break;
21958 				}
21959 
21960 				*xmit_tail = nmp;
21961 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21962 				/* Stash for rtt use later */
21963 				(*xmit_tail)->b_prev = local_time;
21964 				(*xmit_tail)->b_next =
21965 				    (mblk_t *)(uintptr_t)(*snxt - len);
21966 				mp1->b_cont = dupb(*xmit_tail);
21967 				mp1 = mp1->b_cont;
21968 
21969 				spill += nmpsz;
21970 				if (mp1 == NULL) {
21971 					*tail_unsent = spill;
21972 					freemsg(mp);
21973 					if (ire != NULL)
21974 						IRE_REFRELE(ire);
21975 					return (-1);	/* out_of_mem */
21976 				}
21977 			}
21978 
21979 			/* Trim back any surplus on the last mblk */
21980 			if (spill >= 0) {
21981 				mp1->b_wptr -= spill;
21982 				*tail_unsent = spill;
21983 			} else {
21984 				/*
21985 				 * We did not send everything we could in
21986 				 * order to remain within the b_cont limit.
21987 				 */
21988 				*usable -= spill;
21989 				*snxt += spill;
21990 				tcp->tcp_last_sent_len += spill;
21991 				UPDATE_MIB(&tcps->tcps_mib,
21992 				    tcpOutDataBytes, spill);
21993 				/*
21994 				 * Adjust the checksum
21995 				 */
21996 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21997 				sum += spill;
21998 				sum = (sum >> 16) + (sum & 0xFFFF);
21999 				U16_TO_ABE16(sum, tcph->th_sum);
22000 				if (tcp->tcp_ipversion == IPV4_VERSION) {
22001 					sum = ntohs(
22002 					    ((ipha_t *)rptr)->ipha_length) +
22003 					    spill;
22004 					((ipha_t *)rptr)->ipha_length =
22005 					    htons(sum);
22006 				} else {
22007 					sum = ntohs(
22008 					    ((ip6_t *)rptr)->ip6_plen) +
22009 					    spill;
22010 					((ip6_t *)rptr)->ip6_plen =
22011 					    htons(sum);
22012 				}
22013 				*tail_unsent = 0;
22014 			}
22015 		}
22016 		if (tcp->tcp_ip_forward_progress) {
22017 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22018 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
22019 			tcp->tcp_ip_forward_progress = B_FALSE;
22020 		}
22021 
22022 		if (do_lso_send) {
22023 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
22024 			    num_lso_seg);
22025 			tcp->tcp_obsegs += num_lso_seg;
22026 
22027 			TCP_STAT(tcps, tcp_lso_times);
22028 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
22029 		} else {
22030 			tcp_send_data(tcp, q, mp);
22031 			BUMP_LOCAL(tcp->tcp_obsegs);
22032 		}
22033 	}
22034 
22035 	if (ire != NULL)
22036 		IRE_REFRELE(ire);
22037 	return (0);
22038 }
22039 
22040 /* Unlink and return any mblk that looks like it contains a MDT info */
22041 static mblk_t *
22042 tcp_mdt_info_mp(mblk_t *mp)
22043 {
22044 	mblk_t	*prev_mp;
22045 
22046 	for (;;) {
22047 		prev_mp = mp;
22048 		/* no more to process? */
22049 		if ((mp = mp->b_cont) == NULL)
22050 			break;
22051 
22052 		switch (DB_TYPE(mp)) {
22053 		case M_CTL:
22054 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
22055 				continue;
22056 			ASSERT(prev_mp != NULL);
22057 			prev_mp->b_cont = mp->b_cont;
22058 			mp->b_cont = NULL;
22059 			return (mp);
22060 		default:
22061 			break;
22062 		}
22063 	}
22064 	return (mp);
22065 }
22066 
22067 /* MDT info update routine, called when IP notifies us about MDT */
22068 static void
22069 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
22070 {
22071 	boolean_t prev_state;
22072 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22073 
22074 	/*
22075 	 * IP is telling us to abort MDT on this connection?  We know
22076 	 * this because the capability is only turned off when IP
22077 	 * encounters some pathological cases, e.g. link-layer change
22078 	 * where the new driver doesn't support MDT, or in situation
22079 	 * where MDT usage on the link-layer has been switched off.
22080 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
22081 	 * if the link-layer doesn't support MDT, and if it does, it
22082 	 * will indicate that the feature is to be turned on.
22083 	 */
22084 	prev_state = tcp->tcp_mdt;
22085 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
22086 	if (!tcp->tcp_mdt && !first) {
22087 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
22088 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
22089 		    (void *)tcp->tcp_connp));
22090 	}
22091 
22092 	/*
22093 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
22094 	 * so disable MDT otherwise.  The checks are done here
22095 	 * and in tcp_wput_data().
22096 	 */
22097 	if (tcp->tcp_mdt &&
22098 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22099 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22100 	    (tcp->tcp_ipversion == IPV6_VERSION &&
22101 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
22102 		tcp->tcp_mdt = B_FALSE;
22103 
22104 	if (tcp->tcp_mdt) {
22105 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
22106 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
22107 			    "version (%d), expected version is %d",
22108 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
22109 			tcp->tcp_mdt = B_FALSE;
22110 			return;
22111 		}
22112 
22113 		/*
22114 		 * We need the driver to be able to handle at least three
22115 		 * spans per packet in order for tcp MDT to be utilized.
22116 		 * The first is for the header portion, while the rest are
22117 		 * needed to handle a packet that straddles across two
22118 		 * virtually non-contiguous buffers; a typical tcp packet
22119 		 * therefore consists of only two spans.  Note that we take
22120 		 * a zero as "don't care".
22121 		 */
22122 		if (mdt_capab->ill_mdt_span_limit > 0 &&
22123 		    mdt_capab->ill_mdt_span_limit < 3) {
22124 			tcp->tcp_mdt = B_FALSE;
22125 			return;
22126 		}
22127 
22128 		/* a zero means driver wants default value */
22129 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
22130 		    tcps->tcps_mdt_max_pbufs);
22131 		if (tcp->tcp_mdt_max_pld == 0)
22132 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
22133 
22134 		/* ensure 32-bit alignment */
22135 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
22136 		    mdt_capab->ill_mdt_hdr_head), 4);
22137 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
22138 		    mdt_capab->ill_mdt_hdr_tail), 4);
22139 
22140 		if (!first && !prev_state) {
22141 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
22142 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
22143 			    (void *)tcp->tcp_connp));
22144 		}
22145 	}
22146 }
22147 
22148 /* Unlink and return any mblk that looks like it contains a LSO info */
22149 static mblk_t *
22150 tcp_lso_info_mp(mblk_t *mp)
22151 {
22152 	mblk_t	*prev_mp;
22153 
22154 	for (;;) {
22155 		prev_mp = mp;
22156 		/* no more to process? */
22157 		if ((mp = mp->b_cont) == NULL)
22158 			break;
22159 
22160 		switch (DB_TYPE(mp)) {
22161 		case M_CTL:
22162 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
22163 				continue;
22164 			ASSERT(prev_mp != NULL);
22165 			prev_mp->b_cont = mp->b_cont;
22166 			mp->b_cont = NULL;
22167 			return (mp);
22168 		default:
22169 			break;
22170 		}
22171 	}
22172 
22173 	return (mp);
22174 }
22175 
22176 /* LSO info update routine, called when IP notifies us about LSO */
22177 static void
22178 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
22179 {
22180 	tcp_stack_t *tcps = tcp->tcp_tcps;
22181 
22182 	/*
22183 	 * IP is telling us to abort LSO on this connection?  We know
22184 	 * this because the capability is only turned off when IP
22185 	 * encounters some pathological cases, e.g. link-layer change
22186 	 * where the new NIC/driver doesn't support LSO, or in situation
22187 	 * where LSO usage on the link-layer has been switched off.
22188 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
22189 	 * if the link-layer doesn't support LSO, and if it does, it
22190 	 * will indicate that the feature is to be turned on.
22191 	 */
22192 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
22193 	TCP_STAT(tcps, tcp_lso_enabled);
22194 
22195 	/*
22196 	 * We currently only support LSO on simple TCP/IPv4,
22197 	 * so disable LSO otherwise.  The checks are done here
22198 	 * and in tcp_wput_data().
22199 	 */
22200 	if (tcp->tcp_lso &&
22201 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22202 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22203 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
22204 		tcp->tcp_lso = B_FALSE;
22205 		TCP_STAT(tcps, tcp_lso_disabled);
22206 	} else {
22207 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
22208 		    lso_capab->ill_lso_max);
22209 	}
22210 }
22211 
22212 static void
22213 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22214 {
22215 	conn_t *connp = tcp->tcp_connp;
22216 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22217 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22218 
22219 	ASSERT(ire != NULL);
22220 
22221 	/*
22222 	 * We may be in the fastpath here, and although we essentially do
22223 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22224 	 * we try to keep things as brief as possible.  After all, these
22225 	 * are only best-effort checks, and we do more thorough ones prior
22226 	 * to calling tcp_send()/tcp_multisend().
22227 	 */
22228 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22229 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22230 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22231 	    !(ire->ire_flags & RTF_MULTIRT) &&
22232 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22233 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22234 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22235 			/* Cache the result */
22236 			connp->conn_lso_ok = B_TRUE;
22237 
22238 			ASSERT(ill->ill_lso_capab != NULL);
22239 			if (!ill->ill_lso_capab->ill_lso_on) {
22240 				ill->ill_lso_capab->ill_lso_on = 1;
22241 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22242 				    "LSO for interface %s\n", (void *)connp,
22243 				    ill->ill_name));
22244 			}
22245 			tcp_lso_update(tcp, ill->ill_lso_capab);
22246 		} else if (ipst->ips_ip_multidata_outbound &&
22247 		    ILL_MDT_CAPABLE(ill)) {
22248 			/* Cache the result */
22249 			connp->conn_mdt_ok = B_TRUE;
22250 
22251 			ASSERT(ill->ill_mdt_capab != NULL);
22252 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22253 				ill->ill_mdt_capab->ill_mdt_on = 1;
22254 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22255 				    "MDT for interface %s\n", (void *)connp,
22256 				    ill->ill_name));
22257 			}
22258 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22259 		}
22260 	}
22261 
22262 	/*
22263 	 * The goal is to reduce the number of generated tcp segments by
22264 	 * setting the maxpsz multiplier to 0; this will have an affect on
22265 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22266 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22267 	 * of outbound segments and incoming ACKs, thus allowing for better
22268 	 * network and system performance.  In contrast the legacy behavior
22269 	 * may result in sending less than SMSS size, because the last mblk
22270 	 * for some packets may have more data than needed to make up SMSS,
22271 	 * and the legacy code refused to "split" it.
22272 	 *
22273 	 * We apply the new behavior on following situations:
22274 	 *
22275 	 *   1) Loopback connections,
22276 	 *   2) Connections in which the remote peer is not on local subnet,
22277 	 *   3) Local subnet connections over the bge interface (see below).
22278 	 *
22279 	 * Ideally, we would like this behavior to apply for interfaces other
22280 	 * than bge.  However, doing so would negatively impact drivers which
22281 	 * perform dynamic mapping and unmapping of DMA resources, which are
22282 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22283 	 * packet will be generated by tcp).  The bge driver does not suffer
22284 	 * from this, as it copies the mblks into pre-mapped buffers, and
22285 	 * therefore does not require more I/O resources than before.
22286 	 *
22287 	 * Otherwise, this behavior is present on all network interfaces when
22288 	 * the destination endpoint is non-local, since reducing the number
22289 	 * of packets in general is good for the network.
22290 	 *
22291 	 * TODO We need to remove this hard-coded conditional for bge once
22292 	 *	a better "self-tuning" mechanism, or a way to comprehend
22293 	 *	the driver transmit strategy is devised.  Until the solution
22294 	 *	is found and well understood, we live with this hack.
22295 	 */
22296 	if (!tcp_static_maxpsz &&
22297 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22298 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22299 		/* override the default value */
22300 		tcp->tcp_maxpsz = 0;
22301 
22302 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22303 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22304 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22305 	}
22306 
22307 	/* set the stream head parameters accordingly */
22308 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22309 }
22310 
22311 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22312 static void
22313 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22314 {
22315 	uchar_t	fval = *mp->b_rptr;
22316 	mblk_t	*tail;
22317 	queue_t	*q = tcp->tcp_wq;
22318 
22319 	/* TODO: How should flush interact with urgent data? */
22320 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22321 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22322 		/*
22323 		 * Flush only data that has not yet been put on the wire.  If
22324 		 * we flush data that we have already transmitted, life, as we
22325 		 * know it, may come to an end.
22326 		 */
22327 		tail = tcp->tcp_xmit_tail;
22328 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22329 		tcp->tcp_xmit_tail_unsent = 0;
22330 		tcp->tcp_unsent = 0;
22331 		if (tail->b_wptr != tail->b_rptr)
22332 			tail = tail->b_cont;
22333 		if (tail) {
22334 			mblk_t **excess = &tcp->tcp_xmit_head;
22335 			for (;;) {
22336 				mblk_t *mp1 = *excess;
22337 				if (mp1 == tail)
22338 					break;
22339 				tcp->tcp_xmit_tail = mp1;
22340 				tcp->tcp_xmit_last = mp1;
22341 				excess = &mp1->b_cont;
22342 			}
22343 			*excess = NULL;
22344 			tcp_close_mpp(&tail);
22345 			if (tcp->tcp_snd_zcopy_aware)
22346 				tcp_zcopy_notify(tcp);
22347 		}
22348 		/*
22349 		 * We have no unsent data, so unsent must be less than
22350 		 * tcp_xmit_lowater, so re-enable flow.
22351 		 */
22352 		mutex_enter(&tcp->tcp_non_sq_lock);
22353 		if (tcp->tcp_flow_stopped) {
22354 			tcp_clrqfull(tcp);
22355 		}
22356 		mutex_exit(&tcp->tcp_non_sq_lock);
22357 	}
22358 	/*
22359 	 * TODO: you can't just flush these, you have to increase rwnd for one
22360 	 * thing.  For another, how should urgent data interact?
22361 	 */
22362 	if (fval & FLUSHR) {
22363 		*mp->b_rptr = fval & ~FLUSHW;
22364 		/* XXX */
22365 		qreply(q, mp);
22366 		return;
22367 	}
22368 	freemsg(mp);
22369 }
22370 
22371 /*
22372  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22373  * messages.
22374  */
22375 static void
22376 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22377 {
22378 	mblk_t	*mp1;
22379 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22380 	STRUCT_HANDLE(strbuf, sb);
22381 	queue_t *q = tcp->tcp_wq;
22382 	int	error;
22383 	uint_t	addrlen;
22384 
22385 	/* Make sure it is one of ours. */
22386 	switch (iocp->ioc_cmd) {
22387 	case TI_GETMYNAME:
22388 	case TI_GETPEERNAME:
22389 		break;
22390 	default:
22391 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22392 		return;
22393 	}
22394 	switch (mi_copy_state(q, mp, &mp1)) {
22395 	case -1:
22396 		return;
22397 	case MI_COPY_CASE(MI_COPY_IN, 1):
22398 		break;
22399 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22400 		/* Copy out the strbuf. */
22401 		mi_copyout(q, mp);
22402 		return;
22403 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22404 		/* All done. */
22405 		mi_copy_done(q, mp, 0);
22406 		return;
22407 	default:
22408 		mi_copy_done(q, mp, EPROTO);
22409 		return;
22410 	}
22411 	/* Check alignment of the strbuf */
22412 	if (!OK_32PTR(mp1->b_rptr)) {
22413 		mi_copy_done(q, mp, EINVAL);
22414 		return;
22415 	}
22416 
22417 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22418 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22419 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22420 		mi_copy_done(q, mp, EINVAL);
22421 		return;
22422 	}
22423 
22424 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22425 	if (mp1 == NULL)
22426 		return;
22427 
22428 	switch (iocp->ioc_cmd) {
22429 	case TI_GETMYNAME:
22430 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22431 		break;
22432 	case TI_GETPEERNAME:
22433 		error = tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22434 		break;
22435 	}
22436 
22437 	if (error != 0) {
22438 		mi_copy_done(q, mp, error);
22439 	} else {
22440 		mp1->b_wptr += addrlen;
22441 		STRUCT_FSET(sb, len, addrlen);
22442 
22443 		/* Copy out the address */
22444 		mi_copyout(q, mp);
22445 	}
22446 }
22447 
22448 /*
22449  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22450  * messages.
22451  */
22452 /* ARGSUSED */
22453 static void
22454 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22455 {
22456 	conn_t 	*connp = (conn_t *)arg;
22457 	tcp_t	*tcp = connp->conn_tcp;
22458 	queue_t	*q = tcp->tcp_wq;
22459 	struct iocblk	*iocp;
22460 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22461 
22462 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22463 	/*
22464 	 * Try and ASSERT the minimum possible references on the
22465 	 * conn early enough. Since we are executing on write side,
22466 	 * the connection is obviously not detached and that means
22467 	 * there is a ref each for TCP and IP. Since we are behind
22468 	 * the squeue, the minimum references needed are 3. If the
22469 	 * conn is in classifier hash list, there should be an
22470 	 * extra ref for that (we check both the possibilities).
22471 	 */
22472 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22473 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22474 
22475 	iocp = (struct iocblk *)mp->b_rptr;
22476 	switch (iocp->ioc_cmd) {
22477 	case TCP_IOC_DEFAULT_Q:
22478 		/* Wants to be the default wq. */
22479 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22480 			iocp->ioc_error = EPERM;
22481 			iocp->ioc_count = 0;
22482 			mp->b_datap->db_type = M_IOCACK;
22483 			qreply(q, mp);
22484 			return;
22485 		}
22486 		tcp_def_q_set(tcp, mp);
22487 		return;
22488 	case _SIOCSOCKFALLBACK:
22489 		/*
22490 		 * Either sockmod is about to be popped and the socket
22491 		 * would now be treated as a plain stream, or a module
22492 		 * is about to be pushed so we could no longer use read-
22493 		 * side synchronous streams for fused loopback tcp.
22494 		 * Drain any queued data and disable direct sockfs
22495 		 * interface from now on.
22496 		 */
22497 		if (!tcp->tcp_issocket) {
22498 			DB_TYPE(mp) = M_IOCNAK;
22499 			iocp->ioc_error = EINVAL;
22500 		} else {
22501 #ifdef	_ILP32
22502 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
22503 #else
22504 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22505 #endif
22506 			/*
22507 			 * Insert this socket into the acceptor hash.
22508 			 * We might need it for T_CONN_RES message
22509 			 */
22510 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22511 
22512 			if (tcp->tcp_fused) {
22513 				/*
22514 				 * This is a fused loopback tcp; disable
22515 				 * read-side synchronous streams interface
22516 				 * and drain any queued data.  It is okay
22517 				 * to do this for non-synchronous streams
22518 				 * fused tcp as well.
22519 				 */
22520 				tcp_fuse_disable_pair(tcp, B_FALSE);
22521 			}
22522 			tcp->tcp_issocket = B_FALSE;
22523 			tcp->tcp_sodirect = NULL;
22524 			TCP_STAT(tcps, tcp_sock_fallback);
22525 
22526 			DB_TYPE(mp) = M_IOCACK;
22527 			iocp->ioc_error = 0;
22528 		}
22529 		iocp->ioc_count = 0;
22530 		iocp->ioc_rval = 0;
22531 		qreply(q, mp);
22532 		return;
22533 	}
22534 	CALL_IP_WPUT(connp, q, mp);
22535 }
22536 
22537 /*
22538  * This routine is called by tcp_wput() to handle all TPI requests.
22539  */
22540 /* ARGSUSED */
22541 static void
22542 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22543 {
22544 	conn_t 	*connp = (conn_t *)arg;
22545 	tcp_t	*tcp = connp->conn_tcp;
22546 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22547 	uchar_t *rptr;
22548 	t_scalar_t type;
22549 	int len;
22550 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22551 
22552 	/*
22553 	 * Try and ASSERT the minimum possible references on the
22554 	 * conn early enough. Since we are executing on write side,
22555 	 * the connection is obviously not detached and that means
22556 	 * there is a ref each for TCP and IP. Since we are behind
22557 	 * the squeue, the minimum references needed are 3. If the
22558 	 * conn is in classifier hash list, there should be an
22559 	 * extra ref for that (we check both the possibilities).
22560 	 */
22561 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22562 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22563 
22564 	rptr = mp->b_rptr;
22565 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22566 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22567 		type = ((union T_primitives *)rptr)->type;
22568 		if (type == T_EXDATA_REQ) {
22569 			uint32_t msize = msgdsize(mp->b_cont);
22570 
22571 			len = msize - 1;
22572 			if (len < 0) {
22573 				freemsg(mp);
22574 				return;
22575 			}
22576 			/*
22577 			 * Try to force urgent data out on the wire.
22578 			 * Even if we have unsent data this will
22579 			 * at least send the urgent flag.
22580 			 * XXX does not handle more flag correctly.
22581 			 */
22582 			len += tcp->tcp_unsent;
22583 			len += tcp->tcp_snxt;
22584 			tcp->tcp_urg = len;
22585 			tcp->tcp_valid_bits |= TCP_URG_VALID;
22586 
22587 			/* Bypass tcp protocol for fused tcp loopback */
22588 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
22589 				return;
22590 		} else if (type != T_DATA_REQ) {
22591 			goto non_urgent_data;
22592 		}
22593 		/* TODO: options, flags, ... from user */
22594 		/* Set length to zero for reclamation below */
22595 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22596 		freeb(mp);
22597 		return;
22598 	} else {
22599 		if (tcp->tcp_debug) {
22600 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22601 			    "tcp_wput_proto, dropping one...");
22602 		}
22603 		freemsg(mp);
22604 		return;
22605 	}
22606 
22607 non_urgent_data:
22608 
22609 	switch ((int)tprim->type) {
22610 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22611 		/*
22612 		 * save the kssl_ent_t from the next block, and convert this
22613 		 * back to a normal bind_req.
22614 		 */
22615 		if (mp->b_cont != NULL) {
22616 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22617 
22618 			if (tcp->tcp_kssl_ent != NULL) {
22619 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22620 				    KSSL_NO_PROXY);
22621 				tcp->tcp_kssl_ent = NULL;
22622 			}
22623 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22624 			    sizeof (kssl_ent_t));
22625 			kssl_hold_ent(tcp->tcp_kssl_ent);
22626 			freemsg(mp->b_cont);
22627 			mp->b_cont = NULL;
22628 		}
22629 		tprim->type = T_BIND_REQ;
22630 
22631 	/* FALLTHROUGH */
22632 	case O_T_BIND_REQ:	/* bind request */
22633 	case T_BIND_REQ:	/* new semantics bind request */
22634 		tcp_bind(tcp, mp);
22635 		break;
22636 	case T_UNBIND_REQ:	/* unbind request */
22637 		tcp_unbind(tcp, mp);
22638 		break;
22639 	case O_T_CONN_RES:	/* old connection response XXX */
22640 	case T_CONN_RES:	/* connection response */
22641 		tcp_accept(tcp, mp);
22642 		break;
22643 	case T_CONN_REQ:	/* connection request */
22644 		tcp_connect(tcp, mp);
22645 		break;
22646 	case T_DISCON_REQ:	/* disconnect request */
22647 		tcp_disconnect(tcp, mp);
22648 		break;
22649 	case T_CAPABILITY_REQ:
22650 		tcp_capability_req(tcp, mp);	/* capability request */
22651 		break;
22652 	case T_INFO_REQ:	/* information request */
22653 		tcp_info_req(tcp, mp);
22654 		break;
22655 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22656 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22657 		    &tcp_opt_obj, B_TRUE);
22658 		break;
22659 	case T_OPTMGMT_REQ:
22660 		/*
22661 		 * Note:  no support for snmpcom_req() through new
22662 		 * T_OPTMGMT_REQ. See comments in ip.c
22663 		 */
22664 		/* Only IP is allowed to return meaningful value */
22665 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22666 		    B_TRUE);
22667 		break;
22668 
22669 	case T_UNITDATA_REQ:	/* unitdata request */
22670 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22671 		break;
22672 	case T_ORDREL_REQ:	/* orderly release req */
22673 		freemsg(mp);
22674 
22675 		if (tcp->tcp_fused)
22676 			tcp_unfuse(tcp);
22677 
22678 		if (tcp_xmit_end(tcp) != 0) {
22679 			/*
22680 			 * We were crossing FINs and got a reset from
22681 			 * the other side. Just ignore it.
22682 			 */
22683 			if (tcp->tcp_debug) {
22684 				(void) strlog(TCP_MOD_ID, 0, 1,
22685 				    SL_ERROR|SL_TRACE,
22686 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22687 				    "state %s",
22688 				    tcp_display(tcp, NULL,
22689 				    DISP_ADDR_AND_PORT));
22690 			}
22691 		}
22692 		break;
22693 	case T_ADDR_REQ:
22694 		tcp_addr_req(tcp, mp);
22695 		break;
22696 	default:
22697 		if (tcp->tcp_debug) {
22698 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22699 			    "tcp_wput_proto, bogus TPI msg, type %d",
22700 			    tprim->type);
22701 		}
22702 		/*
22703 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22704 		 * to recover.
22705 		 */
22706 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22707 		break;
22708 	}
22709 }
22710 
22711 /*
22712  * The TCP write service routine should never be called...
22713  */
22714 /* ARGSUSED */
22715 static void
22716 tcp_wsrv(queue_t *q)
22717 {
22718 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22719 
22720 	TCP_STAT(tcps, tcp_wsrv_called);
22721 }
22722 
22723 /* Non overlapping byte exchanger */
22724 static void
22725 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22726 {
22727 	uchar_t	uch;
22728 
22729 	while (len-- > 0) {
22730 		uch = a[len];
22731 		a[len] = b[len];
22732 		b[len] = uch;
22733 	}
22734 }
22735 
22736 /*
22737  * Send out a control packet on the tcp connection specified.  This routine
22738  * is typically called where we need a simple ACK or RST generated.
22739  */
22740 static void
22741 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22742 {
22743 	uchar_t		*rptr;
22744 	tcph_t		*tcph;
22745 	ipha_t		*ipha = NULL;
22746 	ip6_t		*ip6h = NULL;
22747 	uint32_t	sum;
22748 	int		tcp_hdr_len;
22749 	int		tcp_ip_hdr_len;
22750 	mblk_t		*mp;
22751 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22752 
22753 	/*
22754 	 * Save sum for use in source route later.
22755 	 */
22756 	ASSERT(tcp != NULL);
22757 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22758 	tcp_hdr_len = tcp->tcp_hdr_len;
22759 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22760 
22761 	/* If a text string is passed in with the request, pass it to strlog. */
22762 	if (str != NULL && tcp->tcp_debug) {
22763 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22764 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22765 		    str, seq, ack, ctl);
22766 	}
22767 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22768 	    BPRI_MED);
22769 	if (mp == NULL) {
22770 		return;
22771 	}
22772 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22773 	mp->b_rptr = rptr;
22774 	mp->b_wptr = &rptr[tcp_hdr_len];
22775 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22776 
22777 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22778 		ipha = (ipha_t *)rptr;
22779 		ipha->ipha_length = htons(tcp_hdr_len);
22780 	} else {
22781 		ip6h = (ip6_t *)rptr;
22782 		ASSERT(tcp != NULL);
22783 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22784 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22785 	}
22786 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22787 	tcph->th_flags[0] = (uint8_t)ctl;
22788 	if (ctl & TH_RST) {
22789 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22790 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22791 		/*
22792 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22793 		 */
22794 		if (tcp->tcp_snd_ts_ok &&
22795 		    tcp->tcp_state > TCPS_SYN_SENT) {
22796 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22797 			*(mp->b_wptr) = TCPOPT_EOL;
22798 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22799 				ipha->ipha_length = htons(tcp_hdr_len -
22800 				    TCPOPT_REAL_TS_LEN);
22801 			} else {
22802 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22803 				    TCPOPT_REAL_TS_LEN);
22804 			}
22805 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22806 			sum -= TCPOPT_REAL_TS_LEN;
22807 		}
22808 	}
22809 	if (ctl & TH_ACK) {
22810 		if (tcp->tcp_snd_ts_ok) {
22811 			U32_TO_BE32(lbolt,
22812 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22813 			U32_TO_BE32(tcp->tcp_ts_recent,
22814 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22815 		}
22816 
22817 		/* Update the latest receive window size in TCP header. */
22818 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22819 		    tcph->th_win);
22820 		tcp->tcp_rack = ack;
22821 		tcp->tcp_rack_cnt = 0;
22822 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22823 	}
22824 	BUMP_LOCAL(tcp->tcp_obsegs);
22825 	U32_TO_BE32(seq, tcph->th_seq);
22826 	U32_TO_BE32(ack, tcph->th_ack);
22827 	/*
22828 	 * Include the adjustment for a source route if any.
22829 	 */
22830 	sum = (sum >> 16) + (sum & 0xFFFF);
22831 	U16_TO_BE16(sum, tcph->th_sum);
22832 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22833 }
22834 
22835 /*
22836  * If this routine returns B_TRUE, TCP can generate a RST in response
22837  * to a segment.  If it returns B_FALSE, TCP should not respond.
22838  */
22839 static boolean_t
22840 tcp_send_rst_chk(tcp_stack_t *tcps)
22841 {
22842 	clock_t	now;
22843 
22844 	/*
22845 	 * TCP needs to protect itself from generating too many RSTs.
22846 	 * This can be a DoS attack by sending us random segments
22847 	 * soliciting RSTs.
22848 	 *
22849 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22850 	 * in each 1 second interval.  In this way, TCP still generate
22851 	 * RSTs in normal cases but when under attack, the impact is
22852 	 * limited.
22853 	 */
22854 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22855 		now = lbolt;
22856 		/* lbolt can wrap around. */
22857 		if ((tcps->tcps_last_rst_intrvl > now) ||
22858 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22859 		    1*SECONDS)) {
22860 			tcps->tcps_last_rst_intrvl = now;
22861 			tcps->tcps_rst_cnt = 1;
22862 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22863 			return (B_FALSE);
22864 		}
22865 	}
22866 	return (B_TRUE);
22867 }
22868 
22869 /*
22870  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22871  */
22872 static void
22873 tcp_ip_ire_mark_advice(tcp_t *tcp)
22874 {
22875 	mblk_t *mp;
22876 	ipic_t *ipic;
22877 
22878 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22879 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22880 		    &ipic);
22881 	} else {
22882 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22883 		    &ipic);
22884 	}
22885 	if (mp == NULL)
22886 		return;
22887 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22888 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22889 }
22890 
22891 /*
22892  * Return an IP advice ioctl mblk and set ipic to be the pointer
22893  * to the advice structure.
22894  */
22895 static mblk_t *
22896 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22897 {
22898 	struct iocblk *ioc;
22899 	mblk_t *mp, *mp1;
22900 
22901 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22902 	if (mp == NULL)
22903 		return (NULL);
22904 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22905 	*ipic = (ipic_t *)mp->b_rptr;
22906 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22907 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22908 
22909 	bcopy(addr, *ipic + 1, addr_len);
22910 
22911 	(*ipic)->ipic_addr_length = addr_len;
22912 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22913 
22914 	mp1 = mkiocb(IP_IOCTL);
22915 	if (mp1 == NULL) {
22916 		freemsg(mp);
22917 		return (NULL);
22918 	}
22919 	mp1->b_cont = mp;
22920 	ioc = (struct iocblk *)mp1->b_rptr;
22921 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22922 
22923 	return (mp1);
22924 }
22925 
22926 /*
22927  * Generate a reset based on an inbound packet, connp is set by caller
22928  * when RST is in response to an unexpected inbound packet for which
22929  * there is active tcp state in the system.
22930  *
22931  * IPSEC NOTE : Try to send the reply with the same protection as it came
22932  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22933  * the packet will go out at the same level of protection as it came in by
22934  * converting the IPSEC_IN to IPSEC_OUT.
22935  */
22936 static void
22937 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22938     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22939     tcp_stack_t *tcps, conn_t *connp)
22940 {
22941 	ipha_t		*ipha = NULL;
22942 	ip6_t		*ip6h = NULL;
22943 	ushort_t	len;
22944 	tcph_t		*tcph;
22945 	int		i;
22946 	mblk_t		*ipsec_mp;
22947 	boolean_t	mctl_present;
22948 	ipic_t		*ipic;
22949 	ipaddr_t	v4addr;
22950 	in6_addr_t	v6addr;
22951 	int		addr_len;
22952 	void		*addr;
22953 	queue_t		*q = tcps->tcps_g_q;
22954 	tcp_t		*tcp;
22955 	cred_t		*cr;
22956 	mblk_t		*nmp;
22957 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22958 
22959 	if (tcps->tcps_g_q == NULL) {
22960 		/*
22961 		 * For non-zero stackids the default queue isn't created
22962 		 * until the first open, thus there can be a need to send
22963 		 * a reset before then. But we can't do that, hence we just
22964 		 * drop the packet. Later during boot, when the default queue
22965 		 * has been setup, a retransmitted packet from the peer
22966 		 * will result in a reset.
22967 		 */
22968 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22969 		    GLOBAL_NETSTACKID);
22970 		freemsg(mp);
22971 		return;
22972 	}
22973 
22974 	if (connp != NULL)
22975 		tcp = connp->conn_tcp;
22976 	else
22977 		tcp = Q_TO_TCP(q);
22978 
22979 	if (!tcp_send_rst_chk(tcps)) {
22980 		tcps->tcps_rst_unsent++;
22981 		freemsg(mp);
22982 		return;
22983 	}
22984 
22985 	if (mp->b_datap->db_type == M_CTL) {
22986 		ipsec_mp = mp;
22987 		mp = mp->b_cont;
22988 		mctl_present = B_TRUE;
22989 	} else {
22990 		ipsec_mp = mp;
22991 		mctl_present = B_FALSE;
22992 	}
22993 
22994 	if (str && q && tcps->tcps_dbg) {
22995 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22996 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22997 		    "flags 0x%x",
22998 		    str, seq, ack, ctl);
22999 	}
23000 	if (mp->b_datap->db_ref != 1) {
23001 		mblk_t *mp1 = copyb(mp);
23002 		freemsg(mp);
23003 		mp = mp1;
23004 		if (!mp) {
23005 			if (mctl_present)
23006 				freeb(ipsec_mp);
23007 			return;
23008 		} else {
23009 			if (mctl_present) {
23010 				ipsec_mp->b_cont = mp;
23011 			} else {
23012 				ipsec_mp = mp;
23013 			}
23014 		}
23015 	} else if (mp->b_cont) {
23016 		freemsg(mp->b_cont);
23017 		mp->b_cont = NULL;
23018 	}
23019 	/*
23020 	 * We skip reversing source route here.
23021 	 * (for now we replace all IP options with EOL)
23022 	 */
23023 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23024 		ipha = (ipha_t *)mp->b_rptr;
23025 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
23026 			mp->b_rptr[i] = IPOPT_EOL;
23027 		/*
23028 		 * Make sure that src address isn't flagrantly invalid.
23029 		 * Not all broadcast address checking for the src address
23030 		 * is possible, since we don't know the netmask of the src
23031 		 * addr.  No check for destination address is done, since
23032 		 * IP will not pass up a packet with a broadcast dest
23033 		 * address to TCP.  Similar checks are done below for IPv6.
23034 		 */
23035 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
23036 		    CLASSD(ipha->ipha_src)) {
23037 			freemsg(ipsec_mp);
23038 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
23039 			return;
23040 		}
23041 	} else {
23042 		ip6h = (ip6_t *)mp->b_rptr;
23043 
23044 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
23045 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
23046 			freemsg(ipsec_mp);
23047 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
23048 			return;
23049 		}
23050 
23051 		/* Remove any extension headers assuming partial overlay */
23052 		if (ip_hdr_len > IPV6_HDR_LEN) {
23053 			uint8_t *to;
23054 
23055 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
23056 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
23057 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
23058 			ip_hdr_len = IPV6_HDR_LEN;
23059 			ip6h = (ip6_t *)mp->b_rptr;
23060 			ip6h->ip6_nxt = IPPROTO_TCP;
23061 		}
23062 	}
23063 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
23064 	if (tcph->th_flags[0] & TH_RST) {
23065 		freemsg(ipsec_mp);
23066 		return;
23067 	}
23068 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
23069 	len = ip_hdr_len + sizeof (tcph_t);
23070 	mp->b_wptr = &mp->b_rptr[len];
23071 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23072 		ipha->ipha_length = htons(len);
23073 		/* Swap addresses */
23074 		v4addr = ipha->ipha_src;
23075 		ipha->ipha_src = ipha->ipha_dst;
23076 		ipha->ipha_dst = v4addr;
23077 		ipha->ipha_ident = 0;
23078 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
23079 		addr_len = IP_ADDR_LEN;
23080 		addr = &v4addr;
23081 	} else {
23082 		/* No ip6i_t in this case */
23083 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
23084 		/* Swap addresses */
23085 		v6addr = ip6h->ip6_src;
23086 		ip6h->ip6_src = ip6h->ip6_dst;
23087 		ip6h->ip6_dst = v6addr;
23088 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
23089 		addr_len = IPV6_ADDR_LEN;
23090 		addr = &v6addr;
23091 	}
23092 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
23093 	U32_TO_BE32(ack, tcph->th_ack);
23094 	U32_TO_BE32(seq, tcph->th_seq);
23095 	U16_TO_BE16(0, tcph->th_win);
23096 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
23097 	tcph->th_flags[0] = (uint8_t)ctl;
23098 	if (ctl & TH_RST) {
23099 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
23100 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23101 	}
23102 
23103 	/* IP trusts us to set up labels when required. */
23104 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
23105 	    crgetlabel(cr) != NULL) {
23106 		int err;
23107 
23108 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
23109 			err = tsol_check_label(cr, &mp,
23110 			    tcp->tcp_connp->conn_mac_exempt,
23111 			    tcps->tcps_netstack->netstack_ip);
23112 		else
23113 			err = tsol_check_label_v6(cr, &mp,
23114 			    tcp->tcp_connp->conn_mac_exempt,
23115 			    tcps->tcps_netstack->netstack_ip);
23116 		if (mctl_present)
23117 			ipsec_mp->b_cont = mp;
23118 		else
23119 			ipsec_mp = mp;
23120 		if (err != 0) {
23121 			freemsg(ipsec_mp);
23122 			return;
23123 		}
23124 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23125 			ipha = (ipha_t *)mp->b_rptr;
23126 		} else {
23127 			ip6h = (ip6_t *)mp->b_rptr;
23128 		}
23129 	}
23130 
23131 	if (mctl_present) {
23132 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23133 
23134 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23135 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
23136 			return;
23137 		}
23138 	}
23139 	if (zoneid == ALL_ZONES)
23140 		zoneid = GLOBAL_ZONEID;
23141 
23142 	/* Add the zoneid so ip_output routes it properly */
23143 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
23144 		freemsg(ipsec_mp);
23145 		return;
23146 	}
23147 	ipsec_mp = nmp;
23148 
23149 	/*
23150 	 * NOTE:  one might consider tracing a TCP packet here, but
23151 	 * this function has no active TCP state and no tcp structure
23152 	 * that has a trace buffer.  If we traced here, we would have
23153 	 * to keep a local trace buffer in tcp_record_trace().
23154 	 *
23155 	 * TSol note: The mblk that contains the incoming packet was
23156 	 * reused by tcp_xmit_listener_reset, so it already contains
23157 	 * the right credentials and we don't need to call mblk_setcred.
23158 	 * Also the conn's cred is not right since it is associated
23159 	 * with tcps_g_q.
23160 	 */
23161 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
23162 
23163 	/*
23164 	 * Tell IP to mark the IRE used for this destination temporary.
23165 	 * This way, we can limit our exposure to DoS attack because IP
23166 	 * creates an IRE for each destination.  If there are too many,
23167 	 * the time to do any routing lookup will be extremely long.  And
23168 	 * the lookup can be in interrupt context.
23169 	 *
23170 	 * Note that in normal circumstances, this marking should not
23171 	 * affect anything.  It would be nice if only 1 message is
23172 	 * needed to inform IP that the IRE created for this RST should
23173 	 * not be added to the cache table.  But there is currently
23174 	 * not such communication mechanism between TCP and IP.  So
23175 	 * the best we can do now is to send the advice ioctl to IP
23176 	 * to mark the IRE temporary.
23177 	 */
23178 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
23179 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
23180 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23181 	}
23182 }
23183 
23184 /*
23185  * Initiate closedown sequence on an active connection.  (May be called as
23186  * writer.)  Return value zero for OK return, non-zero for error return.
23187  */
23188 static int
23189 tcp_xmit_end(tcp_t *tcp)
23190 {
23191 	ipic_t	*ipic;
23192 	mblk_t	*mp;
23193 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23194 
23195 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
23196 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
23197 		/*
23198 		 * Invalid state, only states TCPS_SYN_RCVD,
23199 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
23200 		 */
23201 		return (-1);
23202 	}
23203 
23204 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
23205 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
23206 	/*
23207 	 * If there is nothing more unsent, send the FIN now.
23208 	 * Otherwise, it will go out with the last segment.
23209 	 */
23210 	if (tcp->tcp_unsent == 0) {
23211 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
23212 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
23213 
23214 		if (mp) {
23215 			tcp_send_data(tcp, tcp->tcp_wq, mp);
23216 		} else {
23217 			/*
23218 			 * Couldn't allocate msg.  Pretend we got it out.
23219 			 * Wait for rexmit timeout.
23220 			 */
23221 			tcp->tcp_snxt = tcp->tcp_fss + 1;
23222 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23223 		}
23224 
23225 		/*
23226 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23227 		 * changed.
23228 		 */
23229 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23230 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23231 		}
23232 	} else {
23233 		/*
23234 		 * If tcp->tcp_cork is set, then the data will not get sent,
23235 		 * so we have to check that and unset it first.
23236 		 */
23237 		if (tcp->tcp_cork)
23238 			tcp->tcp_cork = B_FALSE;
23239 		tcp_wput_data(tcp, NULL, B_FALSE);
23240 	}
23241 
23242 	/*
23243 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23244 	 * is 0, don't update the cache.
23245 	 */
23246 	if (tcps->tcps_rtt_updates == 0 ||
23247 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23248 		return (0);
23249 
23250 	/*
23251 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23252 	 * different from the destination.
23253 	 */
23254 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23255 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23256 			return (0);
23257 		}
23258 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23259 		    &ipic);
23260 	} else {
23261 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23262 		    &tcp->tcp_ip6h->ip6_dst))) {
23263 			return (0);
23264 		}
23265 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23266 		    &ipic);
23267 	}
23268 
23269 	/* Record route attributes in the IRE for use by future connections. */
23270 	if (mp == NULL)
23271 		return (0);
23272 
23273 	/*
23274 	 * We do not have a good algorithm to update ssthresh at this time.
23275 	 * So don't do any update.
23276 	 */
23277 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23278 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23279 
23280 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23281 	return (0);
23282 }
23283 
23284 /*
23285  * Generate a "no listener here" RST in response to an "unknown" segment.
23286  * connp is set by caller when RST is in response to an unexpected
23287  * inbound packet for which there is active tcp state in the system.
23288  * Note that we are reusing the incoming mp to construct the outgoing RST.
23289  */
23290 void
23291 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23292     tcp_stack_t *tcps, conn_t *connp)
23293 {
23294 	uchar_t		*rptr;
23295 	uint32_t	seg_len;
23296 	tcph_t		*tcph;
23297 	uint32_t	seg_seq;
23298 	uint32_t	seg_ack;
23299 	uint_t		flags;
23300 	mblk_t		*ipsec_mp;
23301 	ipha_t 		*ipha;
23302 	ip6_t 		*ip6h;
23303 	boolean_t	mctl_present = B_FALSE;
23304 	boolean_t	check = B_TRUE;
23305 	boolean_t	policy_present;
23306 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23307 
23308 	TCP_STAT(tcps, tcp_no_listener);
23309 
23310 	ipsec_mp = mp;
23311 
23312 	if (mp->b_datap->db_type == M_CTL) {
23313 		ipsec_in_t *ii;
23314 
23315 		mctl_present = B_TRUE;
23316 		mp = mp->b_cont;
23317 
23318 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23319 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23320 		if (ii->ipsec_in_dont_check) {
23321 			check = B_FALSE;
23322 			if (!ii->ipsec_in_secure) {
23323 				freeb(ipsec_mp);
23324 				mctl_present = B_FALSE;
23325 				ipsec_mp = mp;
23326 			}
23327 		}
23328 	}
23329 
23330 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23331 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23332 		ipha = (ipha_t *)mp->b_rptr;
23333 		ip6h = NULL;
23334 	} else {
23335 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23336 		ipha = NULL;
23337 		ip6h = (ip6_t *)mp->b_rptr;
23338 	}
23339 
23340 	if (check && policy_present) {
23341 		/*
23342 		 * The conn_t parameter is NULL because we already know
23343 		 * nobody's home.
23344 		 */
23345 		ipsec_mp = ipsec_check_global_policy(
23346 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23347 		    tcps->tcps_netstack);
23348 		if (ipsec_mp == NULL)
23349 			return;
23350 	}
23351 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23352 		DTRACE_PROBE2(
23353 		    tx__ip__log__error__nolistener__tcp,
23354 		    char *, "Could not reply with RST to mp(1)",
23355 		    mblk_t *, mp);
23356 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23357 		freemsg(ipsec_mp);
23358 		return;
23359 	}
23360 
23361 	rptr = mp->b_rptr;
23362 
23363 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23364 	seg_seq = BE32_TO_U32(tcph->th_seq);
23365 	seg_ack = BE32_TO_U32(tcph->th_ack);
23366 	flags = tcph->th_flags[0];
23367 
23368 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23369 	if (flags & TH_RST) {
23370 		freemsg(ipsec_mp);
23371 	} else if (flags & TH_ACK) {
23372 		tcp_xmit_early_reset("no tcp, reset",
23373 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23374 		    connp);
23375 	} else {
23376 		if (flags & TH_SYN) {
23377 			seg_len++;
23378 		} else {
23379 			/*
23380 			 * Here we violate the RFC.  Note that a normal
23381 			 * TCP will never send a segment without the ACK
23382 			 * flag, except for RST or SYN segment.  This
23383 			 * segment is neither.  Just drop it on the
23384 			 * floor.
23385 			 */
23386 			freemsg(ipsec_mp);
23387 			tcps->tcps_rst_unsent++;
23388 			return;
23389 		}
23390 
23391 		tcp_xmit_early_reset("no tcp, reset/ack",
23392 		    ipsec_mp, 0, seg_seq + seg_len,
23393 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23394 	}
23395 }
23396 
23397 /*
23398  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23399  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23400  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23401  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23402  * otherwise it will dup partial mblks.)
23403  * Otherwise, an appropriate ACK packet will be generated.  This
23404  * routine is not usually called to send new data for the first time.  It
23405  * is mostly called out of the timer for retransmits, and to generate ACKs.
23406  *
23407  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23408  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23409  * of the original mblk chain will be returned in *offset and *end_mp.
23410  */
23411 mblk_t *
23412 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23413     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23414     boolean_t rexmit)
23415 {
23416 	int	data_length;
23417 	int32_t	off = 0;
23418 	uint_t	flags;
23419 	mblk_t	*mp1;
23420 	mblk_t	*mp2;
23421 	uchar_t	*rptr;
23422 	tcph_t	*tcph;
23423 	int32_t	num_sack_blk = 0;
23424 	int32_t	sack_opt_len = 0;
23425 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23426 
23427 	/* Allocate for our maximum TCP header + link-level */
23428 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23429 	    tcps->tcps_wroff_xtra, BPRI_MED);
23430 	if (!mp1)
23431 		return (NULL);
23432 	data_length = 0;
23433 
23434 	/*
23435 	 * Note that tcp_mss has been adjusted to take into account the
23436 	 * timestamp option if applicable.  Because SACK options do not
23437 	 * appear in every TCP segments and they are of variable lengths,
23438 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23439 	 * the actual segment length when we need to send a segment which
23440 	 * includes SACK options.
23441 	 */
23442 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23443 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23444 		    tcp->tcp_num_sack_blk);
23445 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23446 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23447 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23448 			max_to_send -= sack_opt_len;
23449 	}
23450 
23451 	if (offset != NULL) {
23452 		off = *offset;
23453 		/* We use offset as an indicator that end_mp is not NULL. */
23454 		*end_mp = NULL;
23455 	}
23456 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23457 		/* This could be faster with cooperation from downstream */
23458 		if (mp2 != mp1 && !sendall &&
23459 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23460 		    max_to_send)
23461 			/*
23462 			 * Don't send the next mblk since the whole mblk
23463 			 * does not fit.
23464 			 */
23465 			break;
23466 		mp2->b_cont = dupb(mp);
23467 		mp2 = mp2->b_cont;
23468 		if (!mp2) {
23469 			freemsg(mp1);
23470 			return (NULL);
23471 		}
23472 		mp2->b_rptr += off;
23473 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23474 		    (uintptr_t)INT_MAX);
23475 
23476 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23477 		if (data_length > max_to_send) {
23478 			mp2->b_wptr -= data_length - max_to_send;
23479 			data_length = max_to_send;
23480 			off = mp2->b_wptr - mp->b_rptr;
23481 			break;
23482 		} else {
23483 			off = 0;
23484 		}
23485 	}
23486 	if (offset != NULL) {
23487 		*offset = off;
23488 		*end_mp = mp;
23489 	}
23490 	if (seg_len != NULL) {
23491 		*seg_len = data_length;
23492 	}
23493 
23494 	/* Update the latest receive window size in TCP header. */
23495 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23496 	    tcp->tcp_tcph->th_win);
23497 
23498 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23499 	mp1->b_rptr = rptr;
23500 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23501 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23502 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23503 	U32_TO_ABE32(seq, tcph->th_seq);
23504 
23505 	/*
23506 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23507 	 * that this function was called from tcp_wput_data. Thus, when called
23508 	 * to retransmit data the setting of the PUSH bit may appear some
23509 	 * what random in that it might get set when it should not. This
23510 	 * should not pose any performance issues.
23511 	 */
23512 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23513 	    tcp->tcp_unsent == data_length)) {
23514 		flags = TH_ACK | TH_PUSH;
23515 	} else {
23516 		flags = TH_ACK;
23517 	}
23518 
23519 	if (tcp->tcp_ecn_ok) {
23520 		if (tcp->tcp_ecn_echo_on)
23521 			flags |= TH_ECE;
23522 
23523 		/*
23524 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23525 		 * There is no TCP flow control for non-data segments, and
23526 		 * only data segment is transmitted reliably.
23527 		 */
23528 		if (data_length > 0 && !rexmit) {
23529 			SET_ECT(tcp, rptr);
23530 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23531 				flags |= TH_CWR;
23532 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23533 			}
23534 		}
23535 	}
23536 
23537 	if (tcp->tcp_valid_bits) {
23538 		uint32_t u1;
23539 
23540 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23541 		    seq == tcp->tcp_iss) {
23542 			uchar_t	*wptr;
23543 
23544 			/*
23545 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23546 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23547 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23548 			 * our SYN is not ack'ed but the app closes this
23549 			 * TCP connection.
23550 			 */
23551 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23552 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23553 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23554 
23555 			/*
23556 			 * Tack on the MSS option.  It is always needed
23557 			 * for both active and passive open.
23558 			 *
23559 			 * MSS option value should be interface MTU - MIN
23560 			 * TCP/IP header according to RFC 793 as it means
23561 			 * the maximum segment size TCP can receive.  But
23562 			 * to get around some broken middle boxes/end hosts
23563 			 * out there, we allow the option value to be the
23564 			 * same as the MSS option size on the peer side.
23565 			 * In this way, the other side will not send
23566 			 * anything larger than they can receive.
23567 			 *
23568 			 * Note that for SYN_SENT state, the ndd param
23569 			 * tcp_use_smss_as_mss_opt has no effect as we
23570 			 * don't know the peer's MSS option value. So
23571 			 * the only case we need to take care of is in
23572 			 * SYN_RCVD state, which is done later.
23573 			 */
23574 			wptr = mp1->b_wptr;
23575 			wptr[0] = TCPOPT_MAXSEG;
23576 			wptr[1] = TCPOPT_MAXSEG_LEN;
23577 			wptr += 2;
23578 			u1 = tcp->tcp_if_mtu -
23579 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23580 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23581 			    TCP_MIN_HEADER_LENGTH;
23582 			U16_TO_BE16(u1, wptr);
23583 			mp1->b_wptr = wptr + 2;
23584 			/* Update the offset to cover the additional word */
23585 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23586 
23587 			/*
23588 			 * Note that the following way of filling in
23589 			 * TCP options are not optimal.  Some NOPs can
23590 			 * be saved.  But there is no need at this time
23591 			 * to optimize it.  When it is needed, we will
23592 			 * do it.
23593 			 */
23594 			switch (tcp->tcp_state) {
23595 			case TCPS_SYN_SENT:
23596 				flags = TH_SYN;
23597 
23598 				if (tcp->tcp_snd_ts_ok) {
23599 					uint32_t llbolt = (uint32_t)lbolt;
23600 
23601 					wptr = mp1->b_wptr;
23602 					wptr[0] = TCPOPT_NOP;
23603 					wptr[1] = TCPOPT_NOP;
23604 					wptr[2] = TCPOPT_TSTAMP;
23605 					wptr[3] = TCPOPT_TSTAMP_LEN;
23606 					wptr += 4;
23607 					U32_TO_BE32(llbolt, wptr);
23608 					wptr += 4;
23609 					ASSERT(tcp->tcp_ts_recent == 0);
23610 					U32_TO_BE32(0L, wptr);
23611 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23612 					tcph->th_offset_and_rsrvd[0] +=
23613 					    (3 << 4);
23614 				}
23615 
23616 				/*
23617 				 * Set up all the bits to tell other side
23618 				 * we are ECN capable.
23619 				 */
23620 				if (tcp->tcp_ecn_ok) {
23621 					flags |= (TH_ECE | TH_CWR);
23622 				}
23623 				break;
23624 			case TCPS_SYN_RCVD:
23625 				flags |= TH_SYN;
23626 
23627 				/*
23628 				 * Reset the MSS option value to be SMSS
23629 				 * We should probably add back the bytes
23630 				 * for timestamp option and IPsec.  We
23631 				 * don't do that as this is a workaround
23632 				 * for broken middle boxes/end hosts, it
23633 				 * is better for us to be more cautious.
23634 				 * They may not take these things into
23635 				 * account in their SMSS calculation.  Thus
23636 				 * the peer's calculated SMSS may be smaller
23637 				 * than what it can be.  This should be OK.
23638 				 */
23639 				if (tcps->tcps_use_smss_as_mss_opt) {
23640 					u1 = tcp->tcp_mss;
23641 					U16_TO_BE16(u1, wptr);
23642 				}
23643 
23644 				/*
23645 				 * If the other side is ECN capable, reply
23646 				 * that we are also ECN capable.
23647 				 */
23648 				if (tcp->tcp_ecn_ok)
23649 					flags |= TH_ECE;
23650 				break;
23651 			default:
23652 				/*
23653 				 * The above ASSERT() makes sure that this
23654 				 * must be FIN-WAIT-1 state.  Our SYN has
23655 				 * not been ack'ed so retransmit it.
23656 				 */
23657 				flags |= TH_SYN;
23658 				break;
23659 			}
23660 
23661 			if (tcp->tcp_snd_ws_ok) {
23662 				wptr = mp1->b_wptr;
23663 				wptr[0] =  TCPOPT_NOP;
23664 				wptr[1] =  TCPOPT_WSCALE;
23665 				wptr[2] =  TCPOPT_WS_LEN;
23666 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23667 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23668 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23669 			}
23670 
23671 			if (tcp->tcp_snd_sack_ok) {
23672 				wptr = mp1->b_wptr;
23673 				wptr[0] = TCPOPT_NOP;
23674 				wptr[1] = TCPOPT_NOP;
23675 				wptr[2] = TCPOPT_SACK_PERMITTED;
23676 				wptr[3] = TCPOPT_SACK_OK_LEN;
23677 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23678 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23679 			}
23680 
23681 			/* allocb() of adequate mblk assures space */
23682 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23683 			    (uintptr_t)INT_MAX);
23684 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23685 			/*
23686 			 * Get IP set to checksum on our behalf
23687 			 * Include the adjustment for a source route if any.
23688 			 */
23689 			u1 += tcp->tcp_sum;
23690 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23691 			U16_TO_BE16(u1, tcph->th_sum);
23692 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23693 		}
23694 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23695 		    (seq + data_length) == tcp->tcp_fss) {
23696 			if (!tcp->tcp_fin_acked) {
23697 				flags |= TH_FIN;
23698 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23699 			}
23700 			if (!tcp->tcp_fin_sent) {
23701 				tcp->tcp_fin_sent = B_TRUE;
23702 				switch (tcp->tcp_state) {
23703 				case TCPS_SYN_RCVD:
23704 				case TCPS_ESTABLISHED:
23705 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23706 					break;
23707 				case TCPS_CLOSE_WAIT:
23708 					tcp->tcp_state = TCPS_LAST_ACK;
23709 					break;
23710 				}
23711 				if (tcp->tcp_suna == tcp->tcp_snxt)
23712 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23713 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23714 			}
23715 		}
23716 		/*
23717 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23718 		 * is smaller than seq, u1 will become a very huge value.
23719 		 * So the comparison will fail.  Also note that tcp_urp
23720 		 * should be positive, see RFC 793 page 17.
23721 		 */
23722 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23723 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23724 		    u1 < (uint32_t)(64 * 1024)) {
23725 			flags |= TH_URG;
23726 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23727 			U32_TO_ABE16(u1, tcph->th_urp);
23728 		}
23729 	}
23730 	tcph->th_flags[0] = (uchar_t)flags;
23731 	tcp->tcp_rack = tcp->tcp_rnxt;
23732 	tcp->tcp_rack_cnt = 0;
23733 
23734 	if (tcp->tcp_snd_ts_ok) {
23735 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23736 			uint32_t llbolt = (uint32_t)lbolt;
23737 
23738 			U32_TO_BE32(llbolt,
23739 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23740 			U32_TO_BE32(tcp->tcp_ts_recent,
23741 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23742 		}
23743 	}
23744 
23745 	if (num_sack_blk > 0) {
23746 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23747 		sack_blk_t *tmp;
23748 		int32_t	i;
23749 
23750 		wptr[0] = TCPOPT_NOP;
23751 		wptr[1] = TCPOPT_NOP;
23752 		wptr[2] = TCPOPT_SACK;
23753 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23754 		    sizeof (sack_blk_t);
23755 		wptr += TCPOPT_REAL_SACK_LEN;
23756 
23757 		tmp = tcp->tcp_sack_list;
23758 		for (i = 0; i < num_sack_blk; i++) {
23759 			U32_TO_BE32(tmp[i].begin, wptr);
23760 			wptr += sizeof (tcp_seq);
23761 			U32_TO_BE32(tmp[i].end, wptr);
23762 			wptr += sizeof (tcp_seq);
23763 		}
23764 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23765 	}
23766 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23767 	data_length += (int)(mp1->b_wptr - rptr);
23768 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23769 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23770 	} else {
23771 		ip6_t *ip6 = (ip6_t *)(rptr +
23772 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23773 		    sizeof (ip6i_t) : 0));
23774 
23775 		ip6->ip6_plen = htons(data_length -
23776 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23777 	}
23778 
23779 	/*
23780 	 * Prime pump for IP
23781 	 * Include the adjustment for a source route if any.
23782 	 */
23783 	data_length -= tcp->tcp_ip_hdr_len;
23784 	data_length += tcp->tcp_sum;
23785 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23786 	U16_TO_ABE16(data_length, tcph->th_sum);
23787 	if (tcp->tcp_ip_forward_progress) {
23788 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23789 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23790 		tcp->tcp_ip_forward_progress = B_FALSE;
23791 	}
23792 	return (mp1);
23793 }
23794 
23795 /* This function handles the push timeout. */
23796 void
23797 tcp_push_timer(void *arg)
23798 {
23799 	conn_t	*connp = (conn_t *)arg;
23800 	tcp_t *tcp = connp->conn_tcp;
23801 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23802 	uint_t		flags;
23803 	sodirect_t	*sodp;
23804 
23805 	TCP_DBGSTAT(tcps, tcp_push_timer_cnt);
23806 
23807 	ASSERT(tcp->tcp_listener == NULL);
23808 
23809 	/*
23810 	 * We need to plug synchronous streams during our drain to prevent
23811 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23812 	 */
23813 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23814 	tcp->tcp_push_tid = 0;
23815 
23816 	SOD_PTR_ENTER(tcp, sodp);
23817 	if (sodp != NULL) {
23818 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23819 		/* sod_wakeup() does the mutex_exit() */
23820 	} else if (tcp->tcp_rcv_list != NULL) {
23821 		flags = tcp_rcv_drain(tcp->tcp_rq, tcp);
23822 	}
23823 	if (flags == TH_ACK_NEEDED)
23824 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23825 
23826 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23827 }
23828 
23829 /*
23830  * This function handles delayed ACK timeout.
23831  */
23832 static void
23833 tcp_ack_timer(void *arg)
23834 {
23835 	conn_t	*connp = (conn_t *)arg;
23836 	tcp_t *tcp = connp->conn_tcp;
23837 	mblk_t *mp;
23838 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23839 
23840 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23841 
23842 	tcp->tcp_ack_tid = 0;
23843 
23844 	if (tcp->tcp_fused)
23845 		return;
23846 
23847 	/*
23848 	 * Do not send ACK if there is no outstanding unack'ed data.
23849 	 */
23850 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23851 		return;
23852 	}
23853 
23854 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23855 		/*
23856 		 * Make sure we don't allow deferred ACKs to result in
23857 		 * timer-based ACKing.  If we have held off an ACK
23858 		 * when there was more than an mss here, and the timer
23859 		 * goes off, we have to worry about the possibility
23860 		 * that the sender isn't doing slow-start, or is out
23861 		 * of step with us for some other reason.  We fall
23862 		 * permanently back in the direction of
23863 		 * ACK-every-other-packet as suggested in RFC 1122.
23864 		 */
23865 		if (tcp->tcp_rack_abs_max > 2)
23866 			tcp->tcp_rack_abs_max--;
23867 		tcp->tcp_rack_cur_max = 2;
23868 	}
23869 	mp = tcp_ack_mp(tcp);
23870 
23871 	if (mp != NULL) {
23872 		BUMP_LOCAL(tcp->tcp_obsegs);
23873 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23874 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23875 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23876 	}
23877 }
23878 
23879 
23880 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23881 static mblk_t *
23882 tcp_ack_mp(tcp_t *tcp)
23883 {
23884 	uint32_t	seq_no;
23885 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23886 
23887 	/*
23888 	 * There are a few cases to be considered while setting the sequence no.
23889 	 * Essentially, we can come here while processing an unacceptable pkt
23890 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23891 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23892 	 * If we are here for a zero window probe, stick with suna. In all
23893 	 * other cases, we check if suna + swnd encompasses snxt and set
23894 	 * the sequence number to snxt, if so. If snxt falls outside the
23895 	 * window (the receiver probably shrunk its window), we will go with
23896 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23897 	 * receiver.
23898 	 */
23899 	if (tcp->tcp_zero_win_probe) {
23900 		seq_no = tcp->tcp_suna;
23901 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23902 		ASSERT(tcp->tcp_swnd == 0);
23903 		seq_no = tcp->tcp_snxt;
23904 	} else {
23905 		seq_no = SEQ_GT(tcp->tcp_snxt,
23906 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23907 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23908 	}
23909 
23910 	if (tcp->tcp_valid_bits) {
23911 		/*
23912 		 * For the complex case where we have to send some
23913 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23914 		 */
23915 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23916 		    NULL, B_FALSE));
23917 	} else {
23918 		/* Generate a simple ACK */
23919 		int	data_length;
23920 		uchar_t	*rptr;
23921 		tcph_t	*tcph;
23922 		mblk_t	*mp1;
23923 		int32_t	tcp_hdr_len;
23924 		int32_t	tcp_tcp_hdr_len;
23925 		int32_t	num_sack_blk = 0;
23926 		int32_t sack_opt_len;
23927 
23928 		/*
23929 		 * Allocate space for TCP + IP headers
23930 		 * and link-level header
23931 		 */
23932 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23933 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23934 			    tcp->tcp_num_sack_blk);
23935 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23936 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23937 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23938 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23939 		} else {
23940 			tcp_hdr_len = tcp->tcp_hdr_len;
23941 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23942 		}
23943 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23944 		if (!mp1)
23945 			return (NULL);
23946 
23947 		/* Update the latest receive window size in TCP header. */
23948 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23949 		    tcp->tcp_tcph->th_win);
23950 		/* copy in prototype TCP + IP header */
23951 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23952 		mp1->b_rptr = rptr;
23953 		mp1->b_wptr = rptr + tcp_hdr_len;
23954 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23955 
23956 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23957 
23958 		/* Set the TCP sequence number. */
23959 		U32_TO_ABE32(seq_no, tcph->th_seq);
23960 
23961 		/* Set up the TCP flag field. */
23962 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23963 		if (tcp->tcp_ecn_echo_on)
23964 			tcph->th_flags[0] |= TH_ECE;
23965 
23966 		tcp->tcp_rack = tcp->tcp_rnxt;
23967 		tcp->tcp_rack_cnt = 0;
23968 
23969 		/* fill in timestamp option if in use */
23970 		if (tcp->tcp_snd_ts_ok) {
23971 			uint32_t llbolt = (uint32_t)lbolt;
23972 
23973 			U32_TO_BE32(llbolt,
23974 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23975 			U32_TO_BE32(tcp->tcp_ts_recent,
23976 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23977 		}
23978 
23979 		/* Fill in SACK options */
23980 		if (num_sack_blk > 0) {
23981 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23982 			sack_blk_t *tmp;
23983 			int32_t	i;
23984 
23985 			wptr[0] = TCPOPT_NOP;
23986 			wptr[1] = TCPOPT_NOP;
23987 			wptr[2] = TCPOPT_SACK;
23988 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23989 			    sizeof (sack_blk_t);
23990 			wptr += TCPOPT_REAL_SACK_LEN;
23991 
23992 			tmp = tcp->tcp_sack_list;
23993 			for (i = 0; i < num_sack_blk; i++) {
23994 				U32_TO_BE32(tmp[i].begin, wptr);
23995 				wptr += sizeof (tcp_seq);
23996 				U32_TO_BE32(tmp[i].end, wptr);
23997 				wptr += sizeof (tcp_seq);
23998 			}
23999 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
24000 			    << 4);
24001 		}
24002 
24003 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24004 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
24005 		} else {
24006 			/* Check for ip6i_t header in sticky hdrs */
24007 			ip6_t *ip6 = (ip6_t *)(rptr +
24008 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
24009 			    sizeof (ip6i_t) : 0));
24010 
24011 			ip6->ip6_plen = htons(tcp_hdr_len -
24012 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
24013 		}
24014 
24015 		/*
24016 		 * Prime pump for checksum calculation in IP.  Include the
24017 		 * adjustment for a source route if any.
24018 		 */
24019 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
24020 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
24021 		U16_TO_ABE16(data_length, tcph->th_sum);
24022 
24023 		if (tcp->tcp_ip_forward_progress) {
24024 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
24025 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
24026 			tcp->tcp_ip_forward_progress = B_FALSE;
24027 		}
24028 		return (mp1);
24029 	}
24030 }
24031 
24032 /*
24033  * Hash list insertion routine for tcp_t structures.
24034  * Inserts entries with the ones bound to a specific IP address first
24035  * followed by those bound to INADDR_ANY.
24036  */
24037 static void
24038 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
24039 {
24040 	tcp_t	**tcpp;
24041 	tcp_t	*tcpnext;
24042 
24043 	if (tcp->tcp_ptpbhn != NULL) {
24044 		ASSERT(!caller_holds_lock);
24045 		tcp_bind_hash_remove(tcp);
24046 	}
24047 	tcpp = &tbf->tf_tcp;
24048 	if (!caller_holds_lock) {
24049 		mutex_enter(&tbf->tf_lock);
24050 	} else {
24051 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
24052 	}
24053 	tcpnext = tcpp[0];
24054 	if (tcpnext) {
24055 		/*
24056 		 * If the new tcp bound to the INADDR_ANY address
24057 		 * and the first one in the list is not bound to
24058 		 * INADDR_ANY we skip all entries until we find the
24059 		 * first one bound to INADDR_ANY.
24060 		 * This makes sure that applications binding to a
24061 		 * specific address get preference over those binding to
24062 		 * INADDR_ANY.
24063 		 */
24064 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
24065 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
24066 			while ((tcpnext = tcpp[0]) != NULL &&
24067 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
24068 				tcpp = &(tcpnext->tcp_bind_hash);
24069 			if (tcpnext)
24070 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24071 		} else
24072 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24073 	}
24074 	tcp->tcp_bind_hash = tcpnext;
24075 	tcp->tcp_ptpbhn = tcpp;
24076 	tcpp[0] = tcp;
24077 	if (!caller_holds_lock)
24078 		mutex_exit(&tbf->tf_lock);
24079 }
24080 
24081 /*
24082  * Hash list removal routine for tcp_t structures.
24083  */
24084 static void
24085 tcp_bind_hash_remove(tcp_t *tcp)
24086 {
24087 	tcp_t	*tcpnext;
24088 	kmutex_t *lockp;
24089 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24090 
24091 	if (tcp->tcp_ptpbhn == NULL)
24092 		return;
24093 
24094 	/*
24095 	 * Extract the lock pointer in case there are concurrent
24096 	 * hash_remove's for this instance.
24097 	 */
24098 	ASSERT(tcp->tcp_lport != 0);
24099 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
24100 
24101 	ASSERT(lockp != NULL);
24102 	mutex_enter(lockp);
24103 	if (tcp->tcp_ptpbhn) {
24104 		tcpnext = tcp->tcp_bind_hash;
24105 		if (tcpnext) {
24106 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24107 			tcp->tcp_bind_hash = NULL;
24108 		}
24109 		*tcp->tcp_ptpbhn = tcpnext;
24110 		tcp->tcp_ptpbhn = NULL;
24111 	}
24112 	mutex_exit(lockp);
24113 }
24114 
24115 
24116 /*
24117  * Hash list lookup routine for tcp_t structures.
24118  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24119  */
24120 static tcp_t *
24121 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24122 {
24123 	tf_t	*tf;
24124 	tcp_t	*tcp;
24125 
24126 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24127 	mutex_enter(&tf->tf_lock);
24128 	for (tcp = tf->tf_tcp; tcp != NULL;
24129 	    tcp = tcp->tcp_acceptor_hash) {
24130 		if (tcp->tcp_acceptor_id == id) {
24131 			CONN_INC_REF(tcp->tcp_connp);
24132 			mutex_exit(&tf->tf_lock);
24133 			return (tcp);
24134 		}
24135 	}
24136 	mutex_exit(&tf->tf_lock);
24137 	return (NULL);
24138 }
24139 
24140 
24141 /*
24142  * Hash list insertion routine for tcp_t structures.
24143  */
24144 void
24145 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24146 {
24147 	tf_t	*tf;
24148 	tcp_t	**tcpp;
24149 	tcp_t	*tcpnext;
24150 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24151 
24152 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24153 
24154 	if (tcp->tcp_ptpahn != NULL)
24155 		tcp_acceptor_hash_remove(tcp);
24156 	tcpp = &tf->tf_tcp;
24157 	mutex_enter(&tf->tf_lock);
24158 	tcpnext = tcpp[0];
24159 	if (tcpnext)
24160 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24161 	tcp->tcp_acceptor_hash = tcpnext;
24162 	tcp->tcp_ptpahn = tcpp;
24163 	tcpp[0] = tcp;
24164 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24165 	mutex_exit(&tf->tf_lock);
24166 }
24167 
24168 /*
24169  * Hash list removal routine for tcp_t structures.
24170  */
24171 static void
24172 tcp_acceptor_hash_remove(tcp_t *tcp)
24173 {
24174 	tcp_t	*tcpnext;
24175 	kmutex_t *lockp;
24176 
24177 	/*
24178 	 * Extract the lock pointer in case there are concurrent
24179 	 * hash_remove's for this instance.
24180 	 */
24181 	lockp = tcp->tcp_acceptor_lockp;
24182 
24183 	if (tcp->tcp_ptpahn == NULL)
24184 		return;
24185 
24186 	ASSERT(lockp != NULL);
24187 	mutex_enter(lockp);
24188 	if (tcp->tcp_ptpahn) {
24189 		tcpnext = tcp->tcp_acceptor_hash;
24190 		if (tcpnext) {
24191 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24192 			tcp->tcp_acceptor_hash = NULL;
24193 		}
24194 		*tcp->tcp_ptpahn = tcpnext;
24195 		tcp->tcp_ptpahn = NULL;
24196 	}
24197 	mutex_exit(lockp);
24198 	tcp->tcp_acceptor_lockp = NULL;
24199 }
24200 
24201 /* Data for fast netmask macro used by tcp_hsp_lookup */
24202 
24203 static ipaddr_t netmasks[] = {
24204 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24205 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24206 };
24207 
24208 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24209 
24210 /*
24211  * XXX This routine should go away and instead we should use the metrics
24212  * associated with the routes to determine the default sndspace and rcvspace.
24213  */
24214 static tcp_hsp_t *
24215 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24216 {
24217 	tcp_hsp_t *hsp = NULL;
24218 
24219 	/* Quick check without acquiring the lock. */
24220 	if (tcps->tcps_hsp_hash == NULL)
24221 		return (NULL);
24222 
24223 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24224 
24225 	/* This routine finds the best-matching HSP for address addr. */
24226 
24227 	if (tcps->tcps_hsp_hash) {
24228 		int i;
24229 		ipaddr_t srchaddr;
24230 		tcp_hsp_t *hsp_net;
24231 
24232 		/* We do three passes: host, network, and subnet. */
24233 
24234 		srchaddr = addr;
24235 
24236 		for (i = 1; i <= 3; i++) {
24237 			/* Look for exact match on srchaddr */
24238 
24239 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24240 			while (hsp) {
24241 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24242 				    hsp->tcp_hsp_addr == srchaddr)
24243 					break;
24244 				hsp = hsp->tcp_hsp_next;
24245 			}
24246 			ASSERT(hsp == NULL ||
24247 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24248 
24249 			/*
24250 			 * If this is the first pass:
24251 			 *   If we found a match, great, return it.
24252 			 *   If not, search for the network on the second pass.
24253 			 */
24254 
24255 			if (i == 1)
24256 				if (hsp)
24257 					break;
24258 				else
24259 				{
24260 					srchaddr = addr & netmask(addr);
24261 					continue;
24262 				}
24263 
24264 			/*
24265 			 * If this is the second pass:
24266 			 *   If we found a match, but there's a subnet mask,
24267 			 *    save the match but try again using the subnet
24268 			 *    mask on the third pass.
24269 			 *   Otherwise, return whatever we found.
24270 			 */
24271 
24272 			if (i == 2) {
24273 				if (hsp && hsp->tcp_hsp_subnet) {
24274 					hsp_net = hsp;
24275 					srchaddr = addr & hsp->tcp_hsp_subnet;
24276 					continue;
24277 				} else {
24278 					break;
24279 				}
24280 			}
24281 
24282 			/*
24283 			 * This must be the third pass.  If we didn't find
24284 			 * anything, return the saved network HSP instead.
24285 			 */
24286 
24287 			if (!hsp)
24288 				hsp = hsp_net;
24289 		}
24290 	}
24291 
24292 	rw_exit(&tcps->tcps_hsp_lock);
24293 	return (hsp);
24294 }
24295 
24296 /*
24297  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24298  * match lookup.
24299  */
24300 static tcp_hsp_t *
24301 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24302 {
24303 	tcp_hsp_t *hsp = NULL;
24304 
24305 	/* Quick check without acquiring the lock. */
24306 	if (tcps->tcps_hsp_hash == NULL)
24307 		return (NULL);
24308 
24309 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24310 
24311 	/* This routine finds the best-matching HSP for address addr. */
24312 
24313 	if (tcps->tcps_hsp_hash) {
24314 		int i;
24315 		in6_addr_t v6srchaddr;
24316 		tcp_hsp_t *hsp_net;
24317 
24318 		/* We do three passes: host, network, and subnet. */
24319 
24320 		v6srchaddr = *v6addr;
24321 
24322 		for (i = 1; i <= 3; i++) {
24323 			/* Look for exact match on srchaddr */
24324 
24325 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24326 			    V4_PART_OF_V6(v6srchaddr))];
24327 			while (hsp) {
24328 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24329 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24330 				    &v6srchaddr))
24331 					break;
24332 				hsp = hsp->tcp_hsp_next;
24333 			}
24334 
24335 			/*
24336 			 * If this is the first pass:
24337 			 *   If we found a match, great, return it.
24338 			 *   If not, search for the network on the second pass.
24339 			 */
24340 
24341 			if (i == 1)
24342 				if (hsp)
24343 					break;
24344 				else {
24345 					/* Assume a 64 bit mask */
24346 					v6srchaddr.s6_addr32[0] =
24347 					    v6addr->s6_addr32[0];
24348 					v6srchaddr.s6_addr32[1] =
24349 					    v6addr->s6_addr32[1];
24350 					v6srchaddr.s6_addr32[2] = 0;
24351 					v6srchaddr.s6_addr32[3] = 0;
24352 					continue;
24353 				}
24354 
24355 			/*
24356 			 * If this is the second pass:
24357 			 *   If we found a match, but there's a subnet mask,
24358 			 *    save the match but try again using the subnet
24359 			 *    mask on the third pass.
24360 			 *   Otherwise, return whatever we found.
24361 			 */
24362 
24363 			if (i == 2) {
24364 				ASSERT(hsp == NULL ||
24365 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24366 				if (hsp &&
24367 				    !IN6_IS_ADDR_UNSPECIFIED(
24368 				    &hsp->tcp_hsp_subnet_v6)) {
24369 					hsp_net = hsp;
24370 					V6_MASK_COPY(*v6addr,
24371 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24372 					continue;
24373 				} else {
24374 					break;
24375 				}
24376 			}
24377 
24378 			/*
24379 			 * This must be the third pass.  If we didn't find
24380 			 * anything, return the saved network HSP instead.
24381 			 */
24382 
24383 			if (!hsp)
24384 				hsp = hsp_net;
24385 		}
24386 	}
24387 
24388 	rw_exit(&tcps->tcps_hsp_lock);
24389 	return (hsp);
24390 }
24391 
24392 /*
24393  * Type three generator adapted from the random() function in 4.4 BSD:
24394  */
24395 
24396 /*
24397  * Copyright (c) 1983, 1993
24398  *	The Regents of the University of California.  All rights reserved.
24399  *
24400  * Redistribution and use in source and binary forms, with or without
24401  * modification, are permitted provided that the following conditions
24402  * are met:
24403  * 1. Redistributions of source code must retain the above copyright
24404  *    notice, this list of conditions and the following disclaimer.
24405  * 2. Redistributions in binary form must reproduce the above copyright
24406  *    notice, this list of conditions and the following disclaimer in the
24407  *    documentation and/or other materials provided with the distribution.
24408  * 3. All advertising materials mentioning features or use of this software
24409  *    must display the following acknowledgement:
24410  *	This product includes software developed by the University of
24411  *	California, Berkeley and its contributors.
24412  * 4. Neither the name of the University nor the names of its contributors
24413  *    may be used to endorse or promote products derived from this software
24414  *    without specific prior written permission.
24415  *
24416  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24417  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24418  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24419  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24420  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24421  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24422  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24423  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24424  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24425  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24426  * SUCH DAMAGE.
24427  */
24428 
24429 /* Type 3 -- x**31 + x**3 + 1 */
24430 #define	DEG_3		31
24431 #define	SEP_3		3
24432 
24433 
24434 /* Protected by tcp_random_lock */
24435 static int tcp_randtbl[DEG_3 + 1];
24436 
24437 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24438 static int *tcp_random_rptr = &tcp_randtbl[1];
24439 
24440 static int *tcp_random_state = &tcp_randtbl[1];
24441 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24442 
24443 kmutex_t tcp_random_lock;
24444 
24445 void
24446 tcp_random_init(void)
24447 {
24448 	int i;
24449 	hrtime_t hrt;
24450 	time_t wallclock;
24451 	uint64_t result;
24452 
24453 	/*
24454 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24455 	 * a longlong, which may contain resolution down to nanoseconds.
24456 	 * The current time will either be a 32-bit or a 64-bit quantity.
24457 	 * XOR the two together in a 64-bit result variable.
24458 	 * Convert the result to a 32-bit value by multiplying the high-order
24459 	 * 32-bits by the low-order 32-bits.
24460 	 */
24461 
24462 	hrt = gethrtime();
24463 	(void) drv_getparm(TIME, &wallclock);
24464 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24465 	mutex_enter(&tcp_random_lock);
24466 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24467 	    (result & 0xffffffff);
24468 
24469 	for (i = 1; i < DEG_3; i++)
24470 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24471 		    + 12345;
24472 	tcp_random_fptr = &tcp_random_state[SEP_3];
24473 	tcp_random_rptr = &tcp_random_state[0];
24474 	mutex_exit(&tcp_random_lock);
24475 	for (i = 0; i < 10 * DEG_3; i++)
24476 		(void) tcp_random();
24477 }
24478 
24479 /*
24480  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24481  * This range is selected to be approximately centered on TCP_ISS / 2,
24482  * and easy to compute. We get this value by generating a 32-bit random
24483  * number, selecting out the high-order 17 bits, and then adding one so
24484  * that we never return zero.
24485  */
24486 int
24487 tcp_random(void)
24488 {
24489 	int i;
24490 
24491 	mutex_enter(&tcp_random_lock);
24492 	*tcp_random_fptr += *tcp_random_rptr;
24493 
24494 	/*
24495 	 * The high-order bits are more random than the low-order bits,
24496 	 * so we select out the high-order 17 bits and add one so that
24497 	 * we never return zero.
24498 	 */
24499 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24500 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24501 		tcp_random_fptr = tcp_random_state;
24502 		++tcp_random_rptr;
24503 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24504 		tcp_random_rptr = tcp_random_state;
24505 
24506 	mutex_exit(&tcp_random_lock);
24507 	return (i);
24508 }
24509 
24510 /*
24511  * XXX This will go away when TPI is extended to send
24512  * info reqs to sockfs/timod .....
24513  * Given a queue, set the max packet size for the write
24514  * side of the queue below stream head.  This value is
24515  * cached on the stream head.
24516  * Returns 1 on success, 0 otherwise.
24517  */
24518 static int
24519 setmaxps(queue_t *q, int maxpsz)
24520 {
24521 	struct stdata	*stp;
24522 	queue_t		*wq;
24523 	stp = STREAM(q);
24524 
24525 	/*
24526 	 * At this point change of a queue parameter is not allowed
24527 	 * when a multiplexor is sitting on top.
24528 	 */
24529 	if (stp->sd_flag & STPLEX)
24530 		return (0);
24531 
24532 	claimstr(stp->sd_wrq);
24533 	wq = stp->sd_wrq->q_next;
24534 	ASSERT(wq != NULL);
24535 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
24536 	releasestr(stp->sd_wrq);
24537 	return (1);
24538 }
24539 
24540 static int
24541 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24542     int *t_errorp, int *sys_errorp)
24543 {
24544 	int error;
24545 	int is_absreq_failure;
24546 	t_scalar_t *opt_lenp;
24547 	t_scalar_t opt_offset;
24548 	int prim_type;
24549 	struct T_conn_req *tcreqp;
24550 	struct T_conn_res *tcresp;
24551 	cred_t *cr;
24552 
24553 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24554 
24555 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24556 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24557 	    prim_type == T_CONN_RES);
24558 
24559 	switch (prim_type) {
24560 	case T_CONN_REQ:
24561 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24562 		opt_offset = tcreqp->OPT_offset;
24563 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24564 		break;
24565 	case O_T_CONN_RES:
24566 	case T_CONN_RES:
24567 		tcresp = (struct T_conn_res *)mp->b_rptr;
24568 		opt_offset = tcresp->OPT_offset;
24569 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24570 		break;
24571 	}
24572 
24573 	*t_errorp = 0;
24574 	*sys_errorp = 0;
24575 	*do_disconnectp = 0;
24576 
24577 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24578 	    opt_offset, cr, &tcp_opt_obj,
24579 	    NULL, &is_absreq_failure);
24580 
24581 	switch (error) {
24582 	case  0:		/* no error */
24583 		ASSERT(is_absreq_failure == 0);
24584 		return (0);
24585 	case ENOPROTOOPT:
24586 		*t_errorp = TBADOPT;
24587 		break;
24588 	case EACCES:
24589 		*t_errorp = TACCES;
24590 		break;
24591 	default:
24592 		*t_errorp = TSYSERR; *sys_errorp = error;
24593 		break;
24594 	}
24595 	if (is_absreq_failure != 0) {
24596 		/*
24597 		 * The connection request should get the local ack
24598 		 * T_OK_ACK and then a T_DISCON_IND.
24599 		 */
24600 		*do_disconnectp = 1;
24601 	}
24602 	return (-1);
24603 }
24604 
24605 /*
24606  * Split this function out so that if the secret changes, I'm okay.
24607  *
24608  * Initialize the tcp_iss_cookie and tcp_iss_key.
24609  */
24610 
24611 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24612 
24613 static void
24614 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24615 {
24616 	struct {
24617 		int32_t current_time;
24618 		uint32_t randnum;
24619 		uint16_t pad;
24620 		uint8_t ether[6];
24621 		uint8_t passwd[PASSWD_SIZE];
24622 	} tcp_iss_cookie;
24623 	time_t t;
24624 
24625 	/*
24626 	 * Start with the current absolute time.
24627 	 */
24628 	(void) drv_getparm(TIME, &t);
24629 	tcp_iss_cookie.current_time = t;
24630 
24631 	/*
24632 	 * XXX - Need a more random number per RFC 1750, not this crap.
24633 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24634 	 */
24635 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24636 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24637 
24638 	/*
24639 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24640 	 * as a good template.
24641 	 */
24642 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24643 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24644 
24645 	/*
24646 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24647 	 */
24648 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24649 
24650 	/*
24651 	 * See 4010593 if this section becomes a problem again,
24652 	 * but the local ethernet address is useful here.
24653 	 */
24654 	(void) localetheraddr(NULL,
24655 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24656 
24657 	/*
24658 	 * Hash 'em all together.  The MD5Final is called per-connection.
24659 	 */
24660 	mutex_enter(&tcps->tcps_iss_key_lock);
24661 	MD5Init(&tcps->tcps_iss_key);
24662 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24663 	    sizeof (tcp_iss_cookie));
24664 	mutex_exit(&tcps->tcps_iss_key_lock);
24665 }
24666 
24667 /*
24668  * Set the RFC 1948 pass phrase
24669  */
24670 /* ARGSUSED */
24671 static int
24672 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24673     cred_t *cr)
24674 {
24675 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24676 
24677 	/*
24678 	 * Basically, value contains a new pass phrase.  Pass it along!
24679 	 */
24680 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24681 	return (0);
24682 }
24683 
24684 /* ARGSUSED */
24685 static int
24686 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24687 {
24688 	bzero(buf, sizeof (tcp_sack_info_t));
24689 	return (0);
24690 }
24691 
24692 /* ARGSUSED */
24693 static int
24694 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24695 {
24696 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24697 	return (0);
24698 }
24699 
24700 /*
24701  * Make sure we wait until the default queue is setup, yet allow
24702  * tcp_g_q_create() to open a TCP stream.
24703  * We need to allow tcp_g_q_create() do do an open
24704  * of tcp, hence we compare curhread.
24705  * All others have to wait until the tcps_g_q has been
24706  * setup.
24707  */
24708 void
24709 tcp_g_q_setup(tcp_stack_t *tcps)
24710 {
24711 	mutex_enter(&tcps->tcps_g_q_lock);
24712 	if (tcps->tcps_g_q != NULL) {
24713 		mutex_exit(&tcps->tcps_g_q_lock);
24714 		return;
24715 	}
24716 	if (tcps->tcps_g_q_creator == NULL) {
24717 		/* This thread will set it up */
24718 		tcps->tcps_g_q_creator = curthread;
24719 		mutex_exit(&tcps->tcps_g_q_lock);
24720 		tcp_g_q_create(tcps);
24721 		mutex_enter(&tcps->tcps_g_q_lock);
24722 		ASSERT(tcps->tcps_g_q_creator == curthread);
24723 		tcps->tcps_g_q_creator = NULL;
24724 		cv_signal(&tcps->tcps_g_q_cv);
24725 		ASSERT(tcps->tcps_g_q != NULL);
24726 		mutex_exit(&tcps->tcps_g_q_lock);
24727 		return;
24728 	}
24729 	/* Everybody but the creator has to wait */
24730 	if (tcps->tcps_g_q_creator != curthread) {
24731 		while (tcps->tcps_g_q == NULL)
24732 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24733 	}
24734 	mutex_exit(&tcps->tcps_g_q_lock);
24735 }
24736 
24737 #define	IP	"ip"
24738 
24739 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24740 
24741 /*
24742  * Create a default tcp queue here instead of in strplumb
24743  */
24744 void
24745 tcp_g_q_create(tcp_stack_t *tcps)
24746 {
24747 	int error;
24748 	ldi_handle_t	lh = NULL;
24749 	ldi_ident_t	li = NULL;
24750 	int		rval;
24751 	cred_t		*cr;
24752 	major_t IP_MAJ;
24753 
24754 #ifdef NS_DEBUG
24755 	(void) printf("tcp_g_q_create()\n");
24756 #endif
24757 
24758 	IP_MAJ = ddi_name_to_major(IP);
24759 
24760 	ASSERT(tcps->tcps_g_q_creator == curthread);
24761 
24762 	error = ldi_ident_from_major(IP_MAJ, &li);
24763 	if (error) {
24764 #ifdef DEBUG
24765 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24766 		    error);
24767 #endif
24768 		return;
24769 	}
24770 
24771 	cr = zone_get_kcred(netstackid_to_zoneid(
24772 	    tcps->tcps_netstack->netstack_stackid));
24773 	ASSERT(cr != NULL);
24774 	/*
24775 	 * We set the tcp default queue to IPv6 because IPv4 falls
24776 	 * back to IPv6 when it can't find a client, but
24777 	 * IPv6 does not fall back to IPv4.
24778 	 */
24779 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24780 	if (error) {
24781 #ifdef DEBUG
24782 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24783 		    error);
24784 #endif
24785 		goto out;
24786 	}
24787 
24788 	/*
24789 	 * This ioctl causes the tcp framework to cache a pointer to
24790 	 * this stream, so we don't want to close the stream after
24791 	 * this operation.
24792 	 * Use the kernel credentials that are for the zone we're in.
24793 	 */
24794 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24795 	    (intptr_t)0, FKIOCTL, cr, &rval);
24796 	if (error) {
24797 #ifdef DEBUG
24798 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24799 		    "error %d\n", error);
24800 #endif
24801 		goto out;
24802 	}
24803 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24804 	lh = NULL;
24805 out:
24806 	/* Close layered handles */
24807 	if (li)
24808 		ldi_ident_release(li);
24809 	/* Keep cred around until _inactive needs it */
24810 	tcps->tcps_g_q_cr = cr;
24811 }
24812 
24813 /*
24814  * We keep tcp_g_q set until all other tcp_t's in the zone
24815  * has gone away, and then when tcp_g_q_inactive() is called
24816  * we clear it.
24817  */
24818 void
24819 tcp_g_q_destroy(tcp_stack_t *tcps)
24820 {
24821 #ifdef NS_DEBUG
24822 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24823 	    tcps->tcps_netstack->netstack_stackid);
24824 #endif
24825 
24826 	if (tcps->tcps_g_q == NULL) {
24827 		return;	/* Nothing to cleanup */
24828 	}
24829 	/*
24830 	 * Drop reference corresponding to the default queue.
24831 	 * This reference was added from tcp_open when the default queue
24832 	 * was created, hence we compensate for this extra drop in
24833 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24834 	 * the default queue was the last one to be open, in which
24835 	 * case, then tcp_g_q_inactive will be
24836 	 * called as a result of the refrele.
24837 	 */
24838 	TCPS_REFRELE(tcps);
24839 }
24840 
24841 /*
24842  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24843  * Run by tcp_q_q_inactive using a taskq.
24844  */
24845 static void
24846 tcp_g_q_close(void *arg)
24847 {
24848 	tcp_stack_t *tcps = arg;
24849 	int error;
24850 	ldi_handle_t	lh = NULL;
24851 	ldi_ident_t	li = NULL;
24852 	cred_t		*cr;
24853 	major_t IP_MAJ;
24854 
24855 	IP_MAJ = ddi_name_to_major(IP);
24856 
24857 #ifdef NS_DEBUG
24858 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24859 	    tcps->tcps_netstack->netstack_stackid,
24860 	    tcps->tcps_netstack->netstack_refcnt);
24861 #endif
24862 	lh = tcps->tcps_g_q_lh;
24863 	if (lh == NULL)
24864 		return;	/* Nothing to cleanup */
24865 
24866 	ASSERT(tcps->tcps_refcnt == 1);
24867 	ASSERT(tcps->tcps_g_q != NULL);
24868 
24869 	error = ldi_ident_from_major(IP_MAJ, &li);
24870 	if (error) {
24871 #ifdef DEBUG
24872 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24873 		    error);
24874 #endif
24875 		return;
24876 	}
24877 
24878 	cr = tcps->tcps_g_q_cr;
24879 	tcps->tcps_g_q_cr = NULL;
24880 	ASSERT(cr != NULL);
24881 
24882 	/*
24883 	 * Make sure we can break the recursion when tcp_close decrements
24884 	 * the reference count causing g_q_inactive to be called again.
24885 	 */
24886 	tcps->tcps_g_q_lh = NULL;
24887 
24888 	/* close the default queue */
24889 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24890 	/*
24891 	 * At this point in time tcps and the rest of netstack_t might
24892 	 * have been deleted.
24893 	 */
24894 	tcps = NULL;
24895 
24896 	/* Close layered handles */
24897 	ldi_ident_release(li);
24898 	crfree(cr);
24899 }
24900 
24901 /*
24902  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24903  *
24904  * Have to ensure that the ldi routines are not used by an
24905  * interrupt thread by using a taskq.
24906  */
24907 void
24908 tcp_g_q_inactive(tcp_stack_t *tcps)
24909 {
24910 	if (tcps->tcps_g_q_lh == NULL)
24911 		return;	/* Nothing to cleanup */
24912 
24913 	ASSERT(tcps->tcps_refcnt == 0);
24914 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24915 
24916 	if (servicing_interrupt()) {
24917 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24918 		    (void *) tcps, TQ_SLEEP);
24919 	} else {
24920 		tcp_g_q_close(tcps);
24921 	}
24922 }
24923 
24924 /*
24925  * Called by IP when IP is loaded into the kernel
24926  */
24927 void
24928 tcp_ddi_g_init(void)
24929 {
24930 	tcp_timercache = kmem_cache_create("tcp_timercache",
24931 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24932 	    NULL, NULL, NULL, NULL, NULL, 0);
24933 
24934 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24935 	    sizeof (tcp_sack_info_t), 0,
24936 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24937 
24938 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24939 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24940 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24941 
24942 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24943 
24944 	/* Initialize the random number generator */
24945 	tcp_random_init();
24946 
24947 	/* A single callback independently of how many netstacks we have */
24948 	ip_squeue_init(tcp_squeue_add);
24949 
24950 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24951 
24952 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24953 	    TASKQ_PREPOPULATE);
24954 
24955 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24956 
24957 	/*
24958 	 * We want to be informed each time a stack is created or
24959 	 * destroyed in the kernel, so we can maintain the
24960 	 * set of tcp_stack_t's.
24961 	 */
24962 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24963 	    tcp_stack_fini);
24964 }
24965 
24966 
24967 /*
24968  * Initialize the TCP stack instance.
24969  */
24970 static void *
24971 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24972 {
24973 	tcp_stack_t	*tcps;
24974 	tcpparam_t	*pa;
24975 	int		i;
24976 
24977 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24978 	tcps->tcps_netstack = ns;
24979 
24980 	/* Initialize locks */
24981 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24982 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24983 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24984 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24985 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24986 
24987 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24988 	tcps->tcps_g_epriv_ports[0] = 2049;
24989 	tcps->tcps_g_epriv_ports[1] = 4045;
24990 	tcps->tcps_min_anonpriv_port = 512;
24991 
24992 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24993 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24994 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24995 	    TCP_FANOUT_SIZE, KM_SLEEP);
24996 
24997 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24998 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24999 		    MUTEX_DEFAULT, NULL);
25000 	}
25001 
25002 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25003 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
25004 		    MUTEX_DEFAULT, NULL);
25005 	}
25006 
25007 	/* TCP's IPsec code calls the packet dropper. */
25008 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
25009 
25010 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
25011 	tcps->tcps_params = pa;
25012 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25013 
25014 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
25015 	    A_CNT(lcl_tcp_param_arr), tcps);
25016 
25017 	/*
25018 	 * Note: To really walk the device tree you need the devinfo
25019 	 * pointer to your device which is only available after probe/attach.
25020 	 * The following is safe only because it uses ddi_root_node()
25021 	 */
25022 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
25023 	    tcp_opt_obj.odb_opt_arr_cnt);
25024 
25025 	/*
25026 	 * Initialize RFC 1948 secret values.  This will probably be reset once
25027 	 * by the boot scripts.
25028 	 *
25029 	 * Use NULL name, as the name is caught by the new lockstats.
25030 	 *
25031 	 * Initialize with some random, non-guessable string, like the global
25032 	 * T_INFO_ACK.
25033 	 */
25034 
25035 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
25036 	    sizeof (tcp_g_t_info_ack), tcps);
25037 
25038 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
25039 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
25040 
25041 	return (tcps);
25042 }
25043 
25044 /*
25045  * Called when the IP module is about to be unloaded.
25046  */
25047 void
25048 tcp_ddi_g_destroy(void)
25049 {
25050 	tcp_g_kstat_fini(tcp_g_kstat);
25051 	tcp_g_kstat = NULL;
25052 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25053 
25054 	mutex_destroy(&tcp_random_lock);
25055 
25056 	kmem_cache_destroy(tcp_timercache);
25057 	kmem_cache_destroy(tcp_sack_info_cache);
25058 	kmem_cache_destroy(tcp_iphc_cache);
25059 
25060 	netstack_unregister(NS_TCP);
25061 	taskq_destroy(tcp_taskq);
25062 }
25063 
25064 /*
25065  * Shut down the TCP stack instance.
25066  */
25067 /* ARGSUSED */
25068 static void
25069 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25070 {
25071 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25072 
25073 	tcp_g_q_destroy(tcps);
25074 }
25075 
25076 /*
25077  * Free the TCP stack instance.
25078  */
25079 static void
25080 tcp_stack_fini(netstackid_t stackid, void *arg)
25081 {
25082 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25083 	int i;
25084 
25085 	nd_free(&tcps->tcps_g_nd);
25086 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25087 	tcps->tcps_params = NULL;
25088 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25089 	tcps->tcps_wroff_xtra_param = NULL;
25090 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25091 	tcps->tcps_mdt_head_param = NULL;
25092 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25093 	tcps->tcps_mdt_tail_param = NULL;
25094 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25095 	tcps->tcps_mdt_max_pbufs_param = NULL;
25096 
25097 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25098 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25099 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25100 	}
25101 
25102 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25103 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25104 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25105 	}
25106 
25107 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25108 	tcps->tcps_bind_fanout = NULL;
25109 
25110 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25111 	tcps->tcps_acceptor_fanout = NULL;
25112 
25113 	mutex_destroy(&tcps->tcps_iss_key_lock);
25114 	rw_destroy(&tcps->tcps_hsp_lock);
25115 	mutex_destroy(&tcps->tcps_g_q_lock);
25116 	cv_destroy(&tcps->tcps_g_q_cv);
25117 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25118 
25119 	ip_drop_unregister(&tcps->tcps_dropper);
25120 
25121 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25122 	tcps->tcps_kstat = NULL;
25123 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25124 
25125 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25126 	tcps->tcps_mibkp = NULL;
25127 
25128 	kmem_free(tcps, sizeof (*tcps));
25129 }
25130 
25131 /*
25132  * Generate ISS, taking into account NDD changes may happen halfway through.
25133  * (If the iss is not zero, set it.)
25134  */
25135 
25136 static void
25137 tcp_iss_init(tcp_t *tcp)
25138 {
25139 	MD5_CTX context;
25140 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25141 	uint32_t answer[4];
25142 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25143 
25144 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25145 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25146 	switch (tcps->tcps_strong_iss) {
25147 	case 2:
25148 		mutex_enter(&tcps->tcps_iss_key_lock);
25149 		context = tcps->tcps_iss_key;
25150 		mutex_exit(&tcps->tcps_iss_key_lock);
25151 		arg.ports = tcp->tcp_ports;
25152 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25153 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25154 			    &arg.src);
25155 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25156 			    &arg.dst);
25157 		} else {
25158 			arg.src = tcp->tcp_ip6h->ip6_src;
25159 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25160 		}
25161 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25162 		MD5Final((uchar_t *)answer, &context);
25163 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25164 		/*
25165 		 * Now that we've hashed into a unique per-connection sequence
25166 		 * space, add a random increment per strong_iss == 1.  So I
25167 		 * guess we'll have to...
25168 		 */
25169 		/* FALLTHRU */
25170 	case 1:
25171 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25172 		break;
25173 	default:
25174 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25175 		break;
25176 	}
25177 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25178 	tcp->tcp_fss = tcp->tcp_iss - 1;
25179 	tcp->tcp_suna = tcp->tcp_iss;
25180 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25181 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25182 	tcp->tcp_csuna = tcp->tcp_snxt;
25183 }
25184 
25185 /*
25186  * Exported routine for extracting active tcp connection status.
25187  *
25188  * This is used by the Solaris Cluster Networking software to
25189  * gather a list of connections that need to be forwarded to
25190  * specific nodes in the cluster when configuration changes occur.
25191  *
25192  * The callback is invoked for each tcp_t structure. Returning
25193  * non-zero from the callback routine terminates the search.
25194  */
25195 int
25196 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25197     void *arg)
25198 {
25199 	netstack_handle_t nh;
25200 	netstack_t *ns;
25201 	int ret = 0;
25202 
25203 	netstack_next_init(&nh);
25204 	while ((ns = netstack_next(&nh)) != NULL) {
25205 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25206 		    ns->netstack_tcp);
25207 		netstack_rele(ns);
25208 	}
25209 	netstack_next_fini(&nh);
25210 	return (ret);
25211 }
25212 
25213 static int
25214 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25215     tcp_stack_t *tcps)
25216 {
25217 	tcp_t *tcp;
25218 	cl_tcp_info_t	cl_tcpi;
25219 	connf_t	*connfp;
25220 	conn_t	*connp;
25221 	int	i;
25222 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25223 
25224 	ASSERT(callback != NULL);
25225 
25226 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25227 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25228 		connp = NULL;
25229 
25230 		while ((connp =
25231 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25232 
25233 			tcp = connp->conn_tcp;
25234 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25235 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25236 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25237 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25238 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25239 			/*
25240 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25241 			 * addresses. They are copied implicitly below as
25242 			 * mapped addresses.
25243 			 */
25244 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25245 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25246 				cl_tcpi.cl_tcpi_faddr =
25247 				    tcp->tcp_ipha->ipha_dst;
25248 			} else {
25249 				cl_tcpi.cl_tcpi_faddr_v6 =
25250 				    tcp->tcp_ip6h->ip6_dst;
25251 			}
25252 
25253 			/*
25254 			 * If the callback returns non-zero
25255 			 * we terminate the traversal.
25256 			 */
25257 			if ((*callback)(&cl_tcpi, arg) != 0) {
25258 				CONN_DEC_REF(tcp->tcp_connp);
25259 				return (1);
25260 			}
25261 		}
25262 	}
25263 
25264 	return (0);
25265 }
25266 
25267 /*
25268  * Macros used for accessing the different types of sockaddr
25269  * structures inside a tcp_ioc_abort_conn_t.
25270  */
25271 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25272 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25273 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25274 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25275 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25276 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25277 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25278 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25279 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25280 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25281 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25282 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25283 
25284 /*
25285  * Return the correct error code to mimic the behavior
25286  * of a connection reset.
25287  */
25288 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25289 		switch ((state)) {		\
25290 		case TCPS_SYN_SENT:		\
25291 		case TCPS_SYN_RCVD:		\
25292 			(err) = ECONNREFUSED;	\
25293 			break;			\
25294 		case TCPS_ESTABLISHED:		\
25295 		case TCPS_FIN_WAIT_1:		\
25296 		case TCPS_FIN_WAIT_2:		\
25297 		case TCPS_CLOSE_WAIT:		\
25298 			(err) = ECONNRESET;	\
25299 			break;			\
25300 		case TCPS_CLOSING:		\
25301 		case TCPS_LAST_ACK:		\
25302 		case TCPS_TIME_WAIT:		\
25303 			(err) = 0;		\
25304 			break;			\
25305 		default:			\
25306 			(err) = ENXIO;		\
25307 		}				\
25308 	}
25309 
25310 /*
25311  * Check if a tcp structure matches the info in acp.
25312  */
25313 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25314 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25315 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25316 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25317 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25318 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25319 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25320 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25321 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25322 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25323 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25324 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25325 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25326 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25327 	&(tcp)->tcp_ip_src_v6)) &&				\
25328 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25329 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25330 	&(tcp)->tcp_remote_v6)) &&				\
25331 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25332 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25333 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25334 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25335 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25336 	(acp)->ac_end >= (tcp)->tcp_state))
25337 
25338 #define	TCP_AC_MATCH(acp, tcp)					\
25339 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25340 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25341 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25342 
25343 /*
25344  * Build a message containing a tcp_ioc_abort_conn_t structure
25345  * which is filled in with information from acp and tp.
25346  */
25347 static mblk_t *
25348 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25349 {
25350 	mblk_t *mp;
25351 	tcp_ioc_abort_conn_t *tacp;
25352 
25353 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25354 	if (mp == NULL)
25355 		return (NULL);
25356 
25357 	mp->b_datap->db_type = M_CTL;
25358 
25359 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25360 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25361 	    sizeof (uint32_t));
25362 
25363 	tacp->ac_start = acp->ac_start;
25364 	tacp->ac_end = acp->ac_end;
25365 	tacp->ac_zoneid = acp->ac_zoneid;
25366 
25367 	if (acp->ac_local.ss_family == AF_INET) {
25368 		tacp->ac_local.ss_family = AF_INET;
25369 		tacp->ac_remote.ss_family = AF_INET;
25370 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25371 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25372 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25373 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25374 	} else {
25375 		tacp->ac_local.ss_family = AF_INET6;
25376 		tacp->ac_remote.ss_family = AF_INET6;
25377 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25378 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25379 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25380 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25381 	}
25382 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25383 	return (mp);
25384 }
25385 
25386 /*
25387  * Print a tcp_ioc_abort_conn_t structure.
25388  */
25389 static void
25390 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25391 {
25392 	char lbuf[128];
25393 	char rbuf[128];
25394 	sa_family_t af;
25395 	in_port_t lport, rport;
25396 	ushort_t logflags;
25397 
25398 	af = acp->ac_local.ss_family;
25399 
25400 	if (af == AF_INET) {
25401 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25402 		    lbuf, 128);
25403 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25404 		    rbuf, 128);
25405 		lport = ntohs(TCP_AC_V4LPORT(acp));
25406 		rport = ntohs(TCP_AC_V4RPORT(acp));
25407 	} else {
25408 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25409 		    lbuf, 128);
25410 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25411 		    rbuf, 128);
25412 		lport = ntohs(TCP_AC_V6LPORT(acp));
25413 		rport = ntohs(TCP_AC_V6RPORT(acp));
25414 	}
25415 
25416 	logflags = SL_TRACE | SL_NOTE;
25417 	/*
25418 	 * Don't print this message to the console if the operation was done
25419 	 * to a non-global zone.
25420 	 */
25421 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25422 		logflags |= SL_CONSOLE;
25423 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25424 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25425 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25426 	    acp->ac_start, acp->ac_end);
25427 }
25428 
25429 /*
25430  * Called inside tcp_rput when a message built using
25431  * tcp_ioctl_abort_build_msg is put into a queue.
25432  * Note that when we get here there is no wildcard in acp any more.
25433  */
25434 static void
25435 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25436 {
25437 	tcp_ioc_abort_conn_t *acp;
25438 
25439 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25440 	if (tcp->tcp_state <= acp->ac_end) {
25441 		/*
25442 		 * If we get here, we are already on the correct
25443 		 * squeue. This ioctl follows the following path
25444 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25445 		 * ->tcp_ioctl_abort->squeue_enter (if on a
25446 		 * different squeue)
25447 		 */
25448 		int errcode;
25449 
25450 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25451 		(void) tcp_clean_death(tcp, errcode, 26);
25452 	}
25453 	freemsg(mp);
25454 }
25455 
25456 /*
25457  * Abort all matching connections on a hash chain.
25458  */
25459 static int
25460 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25461     boolean_t exact, tcp_stack_t *tcps)
25462 {
25463 	int nmatch, err = 0;
25464 	tcp_t *tcp;
25465 	MBLKP mp, last, listhead = NULL;
25466 	conn_t	*tconnp;
25467 	connf_t	*connfp;
25468 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25469 
25470 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25471 
25472 startover:
25473 	nmatch = 0;
25474 
25475 	mutex_enter(&connfp->connf_lock);
25476 	for (tconnp = connfp->connf_head; tconnp != NULL;
25477 	    tconnp = tconnp->conn_next) {
25478 		tcp = tconnp->conn_tcp;
25479 		if (TCP_AC_MATCH(acp, tcp)) {
25480 			CONN_INC_REF(tcp->tcp_connp);
25481 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25482 			if (mp == NULL) {
25483 				err = ENOMEM;
25484 				CONN_DEC_REF(tcp->tcp_connp);
25485 				break;
25486 			}
25487 			mp->b_prev = (mblk_t *)tcp;
25488 
25489 			if (listhead == NULL) {
25490 				listhead = mp;
25491 				last = mp;
25492 			} else {
25493 				last->b_next = mp;
25494 				last = mp;
25495 			}
25496 			nmatch++;
25497 			if (exact)
25498 				break;
25499 		}
25500 
25501 		/* Avoid holding lock for too long. */
25502 		if (nmatch >= 500)
25503 			break;
25504 	}
25505 	mutex_exit(&connfp->connf_lock);
25506 
25507 	/* Pass mp into the correct tcp */
25508 	while ((mp = listhead) != NULL) {
25509 		listhead = listhead->b_next;
25510 		tcp = (tcp_t *)mp->b_prev;
25511 		mp->b_next = mp->b_prev = NULL;
25512 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
25513 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
25514 	}
25515 
25516 	*count += nmatch;
25517 	if (nmatch >= 500 && err == 0)
25518 		goto startover;
25519 	return (err);
25520 }
25521 
25522 /*
25523  * Abort all connections that matches the attributes specified in acp.
25524  */
25525 static int
25526 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25527 {
25528 	sa_family_t af;
25529 	uint32_t  ports;
25530 	uint16_t *pports;
25531 	int err = 0, count = 0;
25532 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25533 	int index = -1;
25534 	ushort_t logflags;
25535 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25536 
25537 	af = acp->ac_local.ss_family;
25538 
25539 	if (af == AF_INET) {
25540 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25541 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25542 			pports = (uint16_t *)&ports;
25543 			pports[1] = TCP_AC_V4LPORT(acp);
25544 			pports[0] = TCP_AC_V4RPORT(acp);
25545 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25546 		}
25547 	} else {
25548 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25549 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25550 			pports = (uint16_t *)&ports;
25551 			pports[1] = TCP_AC_V6LPORT(acp);
25552 			pports[0] = TCP_AC_V6RPORT(acp);
25553 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25554 		}
25555 	}
25556 
25557 	/*
25558 	 * For cases where remote addr, local port, and remote port are non-
25559 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25560 	 */
25561 	if (index != -1) {
25562 		err = tcp_ioctl_abort_bucket(acp, index,
25563 		    &count, exact, tcps);
25564 	} else {
25565 		/*
25566 		 * loop through all entries for wildcard case
25567 		 */
25568 		for (index = 0;
25569 		    index < ipst->ips_ipcl_conn_fanout_size;
25570 		    index++) {
25571 			err = tcp_ioctl_abort_bucket(acp, index,
25572 			    &count, exact, tcps);
25573 			if (err != 0)
25574 				break;
25575 		}
25576 	}
25577 
25578 	logflags = SL_TRACE | SL_NOTE;
25579 	/*
25580 	 * Don't print this message to the console if the operation was done
25581 	 * to a non-global zone.
25582 	 */
25583 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25584 		logflags |= SL_CONSOLE;
25585 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25586 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25587 	if (err == 0 && count == 0)
25588 		err = ENOENT;
25589 	return (err);
25590 }
25591 
25592 /*
25593  * Process the TCP_IOC_ABORT_CONN ioctl request.
25594  */
25595 static void
25596 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25597 {
25598 	int	err;
25599 	IOCP    iocp;
25600 	MBLKP   mp1;
25601 	sa_family_t laf, raf;
25602 	tcp_ioc_abort_conn_t *acp;
25603 	zone_t		*zptr;
25604 	conn_t		*connp = Q_TO_CONN(q);
25605 	zoneid_t	zoneid = connp->conn_zoneid;
25606 	tcp_t		*tcp = connp->conn_tcp;
25607 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25608 
25609 	iocp = (IOCP)mp->b_rptr;
25610 
25611 	if ((mp1 = mp->b_cont) == NULL ||
25612 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25613 		err = EINVAL;
25614 		goto out;
25615 	}
25616 
25617 	/* check permissions */
25618 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25619 		err = EPERM;
25620 		goto out;
25621 	}
25622 
25623 	if (mp1->b_cont != NULL) {
25624 		freemsg(mp1->b_cont);
25625 		mp1->b_cont = NULL;
25626 	}
25627 
25628 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25629 	laf = acp->ac_local.ss_family;
25630 	raf = acp->ac_remote.ss_family;
25631 
25632 	/* check that a zone with the supplied zoneid exists */
25633 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25634 		zptr = zone_find_by_id(zoneid);
25635 		if (zptr != NULL) {
25636 			zone_rele(zptr);
25637 		} else {
25638 			err = EINVAL;
25639 			goto out;
25640 		}
25641 	}
25642 
25643 	/*
25644 	 * For exclusive stacks we set the zoneid to zero
25645 	 * to make TCP operate as if in the global zone.
25646 	 */
25647 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25648 		acp->ac_zoneid = GLOBAL_ZONEID;
25649 
25650 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25651 	    acp->ac_start > acp->ac_end || laf != raf ||
25652 	    (laf != AF_INET && laf != AF_INET6)) {
25653 		err = EINVAL;
25654 		goto out;
25655 	}
25656 
25657 	tcp_ioctl_abort_dump(acp);
25658 	err = tcp_ioctl_abort(acp, tcps);
25659 
25660 out:
25661 	if (mp1 != NULL) {
25662 		freemsg(mp1);
25663 		mp->b_cont = NULL;
25664 	}
25665 
25666 	if (err != 0)
25667 		miocnak(q, mp, 0, err);
25668 	else
25669 		miocack(q, mp, 0, 0);
25670 }
25671 
25672 /*
25673  * tcp_time_wait_processing() handles processing of incoming packets when
25674  * the tcp is in the TIME_WAIT state.
25675  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25676  * on the time wait list.
25677  */
25678 void
25679 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25680     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25681 {
25682 	int32_t		bytes_acked;
25683 	int32_t		gap;
25684 	int32_t		rgap;
25685 	tcp_opt_t	tcpopt;
25686 	uint_t		flags;
25687 	uint32_t	new_swnd = 0;
25688 	conn_t		*connp;
25689 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25690 
25691 	BUMP_LOCAL(tcp->tcp_ibsegs);
25692 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25693 
25694 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25695 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25696 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25697 	if (tcp->tcp_snd_ts_ok) {
25698 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25699 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25700 			    tcp->tcp_rnxt, TH_ACK);
25701 			goto done;
25702 		}
25703 	}
25704 	gap = seg_seq - tcp->tcp_rnxt;
25705 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25706 	if (gap < 0) {
25707 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25708 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25709 		    (seg_len > -gap ? -gap : seg_len));
25710 		seg_len += gap;
25711 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25712 			if (flags & TH_RST) {
25713 				goto done;
25714 			}
25715 			if ((flags & TH_FIN) && seg_len == -1) {
25716 				/*
25717 				 * When TCP receives a duplicate FIN in
25718 				 * TIME_WAIT state, restart the 2 MSL timer.
25719 				 * See page 73 in RFC 793. Make sure this TCP
25720 				 * is already on the TIME_WAIT list. If not,
25721 				 * just restart the timer.
25722 				 */
25723 				if (TCP_IS_DETACHED(tcp)) {
25724 					if (tcp_time_wait_remove(tcp, NULL) ==
25725 					    B_TRUE) {
25726 						tcp_time_wait_append(tcp);
25727 						TCP_DBGSTAT(tcps,
25728 						    tcp_rput_time_wait);
25729 					}
25730 				} else {
25731 					ASSERT(tcp != NULL);
25732 					TCP_TIMER_RESTART(tcp,
25733 					    tcps->tcps_time_wait_interval);
25734 				}
25735 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25736 				    tcp->tcp_rnxt, TH_ACK);
25737 				goto done;
25738 			}
25739 			flags |=  TH_ACK_NEEDED;
25740 			seg_len = 0;
25741 			goto process_ack;
25742 		}
25743 
25744 		/* Fix seg_seq, and chew the gap off the front. */
25745 		seg_seq = tcp->tcp_rnxt;
25746 	}
25747 
25748 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25749 		/*
25750 		 * Make sure that when we accept the connection, pick
25751 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25752 		 * old connection.
25753 		 *
25754 		 * The next ISS generated is equal to tcp_iss_incr_extra
25755 		 * + ISS_INCR/2 + other components depending on the
25756 		 * value of tcp_strong_iss.  We pre-calculate the new
25757 		 * ISS here and compare with tcp_snxt to determine if
25758 		 * we need to make adjustment to tcp_iss_incr_extra.
25759 		 *
25760 		 * The above calculation is ugly and is a
25761 		 * waste of CPU cycles...
25762 		 */
25763 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25764 		int32_t adj;
25765 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25766 
25767 		switch (tcps->tcps_strong_iss) {
25768 		case 2: {
25769 			/* Add time and MD5 components. */
25770 			uint32_t answer[4];
25771 			struct {
25772 				uint32_t ports;
25773 				in6_addr_t src;
25774 				in6_addr_t dst;
25775 			} arg;
25776 			MD5_CTX context;
25777 
25778 			mutex_enter(&tcps->tcps_iss_key_lock);
25779 			context = tcps->tcps_iss_key;
25780 			mutex_exit(&tcps->tcps_iss_key_lock);
25781 			arg.ports = tcp->tcp_ports;
25782 			/* We use MAPPED addresses in tcp_iss_init */
25783 			arg.src = tcp->tcp_ip_src_v6;
25784 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25785 				IN6_IPADDR_TO_V4MAPPED(
25786 				    tcp->tcp_ipha->ipha_dst,
25787 				    &arg.dst);
25788 			} else {
25789 				arg.dst =
25790 				    tcp->tcp_ip6h->ip6_dst;
25791 			}
25792 			MD5Update(&context, (uchar_t *)&arg,
25793 			    sizeof (arg));
25794 			MD5Final((uchar_t *)answer, &context);
25795 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25796 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25797 			break;
25798 		}
25799 		case 1:
25800 			/* Add time component and min random (i.e. 1). */
25801 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25802 			break;
25803 		default:
25804 			/* Add only time component. */
25805 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25806 			break;
25807 		}
25808 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25809 			/*
25810 			 * New ISS not guaranteed to be ISS_INCR/2
25811 			 * ahead of the current tcp_snxt, so add the
25812 			 * difference to tcp_iss_incr_extra.
25813 			 */
25814 			tcps->tcps_iss_incr_extra += adj;
25815 		}
25816 		/*
25817 		 * If tcp_clean_death() can not perform the task now,
25818 		 * drop the SYN packet and let the other side re-xmit.
25819 		 * Otherwise pass the SYN packet back in, since the
25820 		 * old tcp state has been cleaned up or freed.
25821 		 */
25822 		if (tcp_clean_death(tcp, 0, 27) == -1)
25823 			goto done;
25824 		/*
25825 		 * We will come back to tcp_rput_data
25826 		 * on the global queue. Packets destined
25827 		 * for the global queue will be checked
25828 		 * with global policy. But the policy for
25829 		 * this packet has already been checked as
25830 		 * this was destined for the detached
25831 		 * connection. We need to bypass policy
25832 		 * check this time by attaching a dummy
25833 		 * ipsec_in with ipsec_in_dont_check set.
25834 		 */
25835 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25836 		if (connp != NULL) {
25837 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25838 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25839 			return;
25840 		}
25841 		goto done;
25842 	}
25843 
25844 	/*
25845 	 * rgap is the amount of stuff received out of window.  A negative
25846 	 * value is the amount out of window.
25847 	 */
25848 	if (rgap < 0) {
25849 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25850 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25851 		/* Fix seg_len and make sure there is something left. */
25852 		seg_len += rgap;
25853 		if (seg_len <= 0) {
25854 			if (flags & TH_RST) {
25855 				goto done;
25856 			}
25857 			flags |=  TH_ACK_NEEDED;
25858 			seg_len = 0;
25859 			goto process_ack;
25860 		}
25861 	}
25862 	/*
25863 	 * Check whether we can update tcp_ts_recent.  This test is
25864 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25865 	 * Extensions for High Performance: An Update", Internet Draft.
25866 	 */
25867 	if (tcp->tcp_snd_ts_ok &&
25868 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25869 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25870 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25871 		tcp->tcp_last_rcv_lbolt = lbolt64;
25872 	}
25873 
25874 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25875 		/* Always ack out of order packets */
25876 		flags |= TH_ACK_NEEDED;
25877 		seg_len = 0;
25878 	} else if (seg_len > 0) {
25879 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25880 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25881 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25882 	}
25883 	if (flags & TH_RST) {
25884 		(void) tcp_clean_death(tcp, 0, 28);
25885 		goto done;
25886 	}
25887 	if (flags & TH_SYN) {
25888 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25889 		    TH_RST|TH_ACK);
25890 		/*
25891 		 * Do not delete the TCP structure if it is in
25892 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25893 		 */
25894 		goto done;
25895 	}
25896 process_ack:
25897 	if (flags & TH_ACK) {
25898 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25899 		if (bytes_acked <= 0) {
25900 			if (bytes_acked == 0 && seg_len == 0 &&
25901 			    new_swnd == tcp->tcp_swnd)
25902 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25903 		} else {
25904 			/* Acks something not sent */
25905 			flags |= TH_ACK_NEEDED;
25906 		}
25907 	}
25908 	if (flags & TH_ACK_NEEDED) {
25909 		/*
25910 		 * Time to send an ack for some reason.
25911 		 */
25912 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25913 		    tcp->tcp_rnxt, TH_ACK);
25914 	}
25915 done:
25916 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25917 		DB_CKSUMSTART(mp) = 0;
25918 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25919 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25920 	}
25921 	freemsg(mp);
25922 }
25923 
25924 /*
25925  * Allocate a T_SVR4_OPTMGMT_REQ.
25926  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
25927  * that tcp_rput_other can drop the acks.
25928  */
25929 static mblk_t *
25930 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
25931 {
25932 	mblk_t *mp;
25933 	struct T_optmgmt_req *tor;
25934 	struct opthdr *oh;
25935 	uint_t size;
25936 	char *optptr;
25937 
25938 	size = sizeof (*tor) + sizeof (*oh) + optlen;
25939 	mp = allocb(size, BPRI_MED);
25940 	if (mp == NULL)
25941 		return (NULL);
25942 
25943 	mp->b_wptr += size;
25944 	mp->b_datap->db_type = M_PROTO;
25945 	tor = (struct T_optmgmt_req *)mp->b_rptr;
25946 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
25947 	tor->MGMT_flags = T_NEGOTIATE;
25948 	tor->OPT_length = sizeof (*oh) + optlen;
25949 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
25950 
25951 	oh = (struct opthdr *)&tor[1];
25952 	oh->level = level;
25953 	oh->name = cmd;
25954 	oh->len = optlen;
25955 	if (optlen != 0) {
25956 		optptr = (char *)&oh[1];
25957 		bcopy(opt, optptr, optlen);
25958 	}
25959 	return (mp);
25960 }
25961 
25962 /*
25963  * TCP Timers Implementation.
25964  */
25965 timeout_id_t
25966 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25967 {
25968 	mblk_t *mp;
25969 	tcp_timer_t *tcpt;
25970 	tcp_t *tcp = connp->conn_tcp;
25971 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25972 
25973 	ASSERT(connp->conn_sqp != NULL);
25974 
25975 	TCP_DBGSTAT(tcps, tcp_timeout_calls);
25976 
25977 	if (tcp->tcp_timercache == NULL) {
25978 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25979 	} else {
25980 		TCP_DBGSTAT(tcps, tcp_timeout_cached_alloc);
25981 		mp = tcp->tcp_timercache;
25982 		tcp->tcp_timercache = mp->b_next;
25983 		mp->b_next = NULL;
25984 		ASSERT(mp->b_wptr == NULL);
25985 	}
25986 
25987 	CONN_INC_REF(connp);
25988 	tcpt = (tcp_timer_t *)mp->b_rptr;
25989 	tcpt->connp = connp;
25990 	tcpt->tcpt_proc = f;
25991 	/*
25992 	 * TCP timers are normal timeouts. Plus, they do not require more than
25993 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25994 	 * rounding up the expiration to the next resolution boundary, we can
25995 	 * batch timers in the callout subsystem to make TCP timers more
25996 	 * efficient. The roundup also protects short timers from expiring too
25997 	 * early before they have a chance to be cancelled.
25998 	 */
25999 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
26000 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
26001 
26002 	return ((timeout_id_t)mp);
26003 }
26004 
26005 static void
26006 tcp_timer_callback(void *arg)
26007 {
26008 	mblk_t *mp = (mblk_t *)arg;
26009 	tcp_timer_t *tcpt;
26010 	conn_t	*connp;
26011 
26012 	tcpt = (tcp_timer_t *)mp->b_rptr;
26013 	connp = tcpt->connp;
26014 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
26015 	    SQ_FILL, SQTAG_TCP_TIMER);
26016 }
26017 
26018 static void
26019 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
26020 {
26021 	tcp_timer_t *tcpt;
26022 	conn_t *connp = (conn_t *)arg;
26023 	tcp_t *tcp = connp->conn_tcp;
26024 
26025 	tcpt = (tcp_timer_t *)mp->b_rptr;
26026 	ASSERT(connp == tcpt->connp);
26027 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
26028 
26029 	/*
26030 	 * If the TCP has reached the closed state, don't proceed any
26031 	 * further. This TCP logically does not exist on the system.
26032 	 * tcpt_proc could for example access queues, that have already
26033 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
26034 	 */
26035 	if (tcp->tcp_state != TCPS_CLOSED) {
26036 		(*tcpt->tcpt_proc)(connp);
26037 	} else {
26038 		tcp->tcp_timer_tid = 0;
26039 	}
26040 	tcp_timer_free(connp->conn_tcp, mp);
26041 }
26042 
26043 /*
26044  * There is potential race with untimeout and the handler firing at the same
26045  * time. The mblock may be freed by the handler while we are trying to use
26046  * it. But since both should execute on the same squeue, this race should not
26047  * occur.
26048  */
26049 clock_t
26050 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
26051 {
26052 	mblk_t	*mp = (mblk_t *)id;
26053 	tcp_timer_t *tcpt;
26054 	clock_t delta;
26055 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26056 
26057 	TCP_DBGSTAT(tcps, tcp_timeout_cancel_reqs);
26058 
26059 	if (mp == NULL)
26060 		return (-1);
26061 
26062 	tcpt = (tcp_timer_t *)mp->b_rptr;
26063 	ASSERT(tcpt->connp == connp);
26064 
26065 	delta = untimeout_default(tcpt->tcpt_tid, 0);
26066 
26067 	if (delta >= 0) {
26068 		TCP_DBGSTAT(tcps, tcp_timeout_canceled);
26069 		tcp_timer_free(connp->conn_tcp, mp);
26070 		CONN_DEC_REF(connp);
26071 	}
26072 
26073 	return (delta);
26074 }
26075 
26076 /*
26077  * Allocate space for the timer event. The allocation looks like mblk, but it is
26078  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26079  *
26080  * Dealing with failures: If we can't allocate from the timer cache we try
26081  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26082  * points to b_rptr.
26083  * If we can't allocate anything using allocb_tryhard(), we perform a last
26084  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26085  * save the actual allocation size in b_datap.
26086  */
26087 mblk_t *
26088 tcp_timermp_alloc(int kmflags)
26089 {
26090 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26091 	    kmflags & ~KM_PANIC);
26092 
26093 	if (mp != NULL) {
26094 		mp->b_next = mp->b_prev = NULL;
26095 		mp->b_rptr = (uchar_t *)(&mp[1]);
26096 		mp->b_wptr = NULL;
26097 		mp->b_datap = NULL;
26098 		mp->b_queue = NULL;
26099 		mp->b_cont = NULL;
26100 	} else if (kmflags & KM_PANIC) {
26101 		/*
26102 		 * Failed to allocate memory for the timer. Try allocating from
26103 		 * dblock caches.
26104 		 */
26105 		/* ipclassifier calls this from a constructor - hence no tcps */
26106 		TCP_G_STAT(tcp_timermp_allocfail);
26107 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26108 		if (mp == NULL) {
26109 			size_t size = 0;
26110 			/*
26111 			 * Memory is really low. Try tryhard allocation.
26112 			 *
26113 			 * ipclassifier calls this from a constructor -
26114 			 * hence no tcps
26115 			 */
26116 			TCP_G_STAT(tcp_timermp_allocdblfail);
26117 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26118 			    sizeof (tcp_timer_t), &size, kmflags);
26119 			mp->b_rptr = (uchar_t *)(&mp[1]);
26120 			mp->b_next = mp->b_prev = NULL;
26121 			mp->b_wptr = (uchar_t *)-1;
26122 			mp->b_datap = (dblk_t *)size;
26123 			mp->b_queue = NULL;
26124 			mp->b_cont = NULL;
26125 		}
26126 		ASSERT(mp->b_wptr != NULL);
26127 	}
26128 	/* ipclassifier calls this from a constructor - hence no tcps */
26129 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26130 
26131 	return (mp);
26132 }
26133 
26134 /*
26135  * Free per-tcp timer cache.
26136  * It can only contain entries from tcp_timercache.
26137  */
26138 void
26139 tcp_timermp_free(tcp_t *tcp)
26140 {
26141 	mblk_t *mp;
26142 
26143 	while ((mp = tcp->tcp_timercache) != NULL) {
26144 		ASSERT(mp->b_wptr == NULL);
26145 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26146 		kmem_cache_free(tcp_timercache, mp);
26147 	}
26148 }
26149 
26150 /*
26151  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26152  * events there already (currently at most two events are cached).
26153  * If the event is not allocated from the timer cache, free it right away.
26154  */
26155 static void
26156 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26157 {
26158 	mblk_t *mp1 = tcp->tcp_timercache;
26159 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26160 
26161 	if (mp->b_wptr != NULL) {
26162 		/*
26163 		 * This allocation is not from a timer cache, free it right
26164 		 * away.
26165 		 */
26166 		if (mp->b_wptr != (uchar_t *)-1)
26167 			freeb(mp);
26168 		else
26169 			kmem_free(mp, (size_t)mp->b_datap);
26170 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26171 		/* Cache this timer block for future allocations */
26172 		mp->b_rptr = (uchar_t *)(&mp[1]);
26173 		mp->b_next = mp1;
26174 		tcp->tcp_timercache = mp;
26175 	} else {
26176 		kmem_cache_free(tcp_timercache, mp);
26177 		TCP_DBGSTAT(tcps, tcp_timermp_freed);
26178 	}
26179 }
26180 
26181 /*
26182  * End of TCP Timers implementation.
26183  */
26184 
26185 /*
26186  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26187  * on the specified backing STREAMS q. Note, the caller may make the
26188  * decision to call based on the tcp_t.tcp_flow_stopped value which
26189  * when check outside the q's lock is only an advisory check ...
26190  */
26191 
26192 void
26193 tcp_setqfull(tcp_t *tcp)
26194 {
26195 	queue_t *q = tcp->tcp_wq;
26196 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26197 
26198 	if (!(q->q_flag & QFULL)) {
26199 		mutex_enter(QLOCK(q));
26200 		if (!(q->q_flag & QFULL)) {
26201 			/* still need to set QFULL */
26202 			q->q_flag |= QFULL;
26203 			tcp->tcp_flow_stopped = B_TRUE;
26204 			mutex_exit(QLOCK(q));
26205 			TCP_STAT(tcps, tcp_flwctl_on);
26206 		} else {
26207 			mutex_exit(QLOCK(q));
26208 		}
26209 	}
26210 }
26211 
26212 void
26213 tcp_clrqfull(tcp_t *tcp)
26214 {
26215 	queue_t *q = tcp->tcp_wq;
26216 
26217 	if (q->q_flag & QFULL) {
26218 		mutex_enter(QLOCK(q));
26219 		if (q->q_flag & QFULL) {
26220 			q->q_flag &= ~QFULL;
26221 			tcp->tcp_flow_stopped = B_FALSE;
26222 			mutex_exit(QLOCK(q));
26223 			if (q->q_flag & QWANTW)
26224 				qbackenable(q, 0);
26225 		} else {
26226 			mutex_exit(QLOCK(q));
26227 		}
26228 	}
26229 }
26230 
26231 
26232 /*
26233  * kstats related to squeues i.e. not per IP instance
26234  */
26235 static void *
26236 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26237 {
26238 	kstat_t *ksp;
26239 
26240 	tcp_g_stat_t template = {
26241 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26242 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26243 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26244 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26245 	};
26246 
26247 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26248 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26249 	    KSTAT_FLAG_VIRTUAL);
26250 
26251 	if (ksp == NULL)
26252 		return (NULL);
26253 
26254 	bcopy(&template, tcp_g_statp, sizeof (template));
26255 	ksp->ks_data = (void *)tcp_g_statp;
26256 
26257 	kstat_install(ksp);
26258 	return (ksp);
26259 }
26260 
26261 static void
26262 tcp_g_kstat_fini(kstat_t *ksp)
26263 {
26264 	if (ksp != NULL) {
26265 		kstat_delete(ksp);
26266 	}
26267 }
26268 
26269 
26270 static void *
26271 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26272 {
26273 	kstat_t *ksp;
26274 
26275 	tcp_stat_t template = {
26276 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26277 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26278 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26279 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26280 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26281 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26282 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26283 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26284 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26285 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26286 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26287 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26288 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26289 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26290 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26291 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26292 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26293 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26294 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26295 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26296 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26297 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26298 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26299 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26300 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26301 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26302 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26303 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26304 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26305 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26306 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26307 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26308 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26309 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26310 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26311 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26312 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26313 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26314 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26315 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26316 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26317 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26318 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26319 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26320 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26321 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26322 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26323 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26324 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26325 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26326 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26327 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26328 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26329 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26330 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26331 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26332 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26333 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26334 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26335 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26336 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26337 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26338 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26339 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26340 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26341 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26342 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26343 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26344 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26345 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26346 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26347 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26348 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26349 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26350 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26351 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26352 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26353 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26354 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26355 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26356 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26357 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26358 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26359 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26360 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26361 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26362 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26363 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26364 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26365 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26366 	};
26367 
26368 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26369 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26370 	    KSTAT_FLAG_VIRTUAL, stackid);
26371 
26372 	if (ksp == NULL)
26373 		return (NULL);
26374 
26375 	bcopy(&template, tcps_statisticsp, sizeof (template));
26376 	ksp->ks_data = (void *)tcps_statisticsp;
26377 	ksp->ks_private = (void *)(uintptr_t)stackid;
26378 
26379 	kstat_install(ksp);
26380 	return (ksp);
26381 }
26382 
26383 static void
26384 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26385 {
26386 	if (ksp != NULL) {
26387 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26388 		kstat_delete_netstack(ksp, stackid);
26389 	}
26390 }
26391 
26392 /*
26393  * TCP Kstats implementation
26394  */
26395 static void *
26396 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26397 {
26398 	kstat_t	*ksp;
26399 
26400 	tcp_named_kstat_t template = {
26401 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26402 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26403 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26404 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26405 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26406 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26407 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26408 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26409 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26410 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26411 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26412 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26413 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26414 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26415 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26416 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26417 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26418 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26419 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26420 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26421 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26422 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26423 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26424 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26425 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26426 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26427 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26428 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26429 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26430 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26431 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26432 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26433 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26434 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26435 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26436 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26437 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26438 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26439 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26440 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26441 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26442 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26443 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26444 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26445 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26446 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26447 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26448 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26449 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26450 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26451 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26452 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26453 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26454 	};
26455 
26456 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26457 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26458 
26459 	if (ksp == NULL)
26460 		return (NULL);
26461 
26462 	template.rtoAlgorithm.value.ui32 = 4;
26463 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26464 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26465 	template.maxConn.value.i32 = -1;
26466 
26467 	bcopy(&template, ksp->ks_data, sizeof (template));
26468 	ksp->ks_update = tcp_kstat_update;
26469 	ksp->ks_private = (void *)(uintptr_t)stackid;
26470 
26471 	kstat_install(ksp);
26472 	return (ksp);
26473 }
26474 
26475 static void
26476 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26477 {
26478 	if (ksp != NULL) {
26479 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26480 		kstat_delete_netstack(ksp, stackid);
26481 	}
26482 }
26483 
26484 static int
26485 tcp_kstat_update(kstat_t *kp, int rw)
26486 {
26487 	tcp_named_kstat_t *tcpkp;
26488 	tcp_t		*tcp;
26489 	connf_t		*connfp;
26490 	conn_t		*connp;
26491 	int 		i;
26492 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26493 	netstack_t	*ns;
26494 	tcp_stack_t	*tcps;
26495 	ip_stack_t	*ipst;
26496 
26497 	if ((kp == NULL) || (kp->ks_data == NULL))
26498 		return (EIO);
26499 
26500 	if (rw == KSTAT_WRITE)
26501 		return (EACCES);
26502 
26503 	ns = netstack_find_by_stackid(stackid);
26504 	if (ns == NULL)
26505 		return (-1);
26506 	tcps = ns->netstack_tcp;
26507 	if (tcps == NULL) {
26508 		netstack_rele(ns);
26509 		return (-1);
26510 	}
26511 
26512 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26513 
26514 	tcpkp->currEstab.value.ui32 = 0;
26515 
26516 	ipst = ns->netstack_ip;
26517 
26518 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26519 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26520 		connp = NULL;
26521 		while ((connp =
26522 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26523 			tcp = connp->conn_tcp;
26524 			switch (tcp_snmp_state(tcp)) {
26525 			case MIB2_TCP_established:
26526 			case MIB2_TCP_closeWait:
26527 				tcpkp->currEstab.value.ui32++;
26528 				break;
26529 			}
26530 		}
26531 	}
26532 
26533 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26534 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26535 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26536 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26537 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26538 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26539 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26540 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26541 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26542 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26543 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26544 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26545 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26546 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26547 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26548 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26549 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26550 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26551 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26552 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26553 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26554 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26555 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26556 	tcpkp->inDataInorderSegs.value.ui32 =
26557 	    tcps->tcps_mib.tcpInDataInorderSegs;
26558 	tcpkp->inDataInorderBytes.value.ui32 =
26559 	    tcps->tcps_mib.tcpInDataInorderBytes;
26560 	tcpkp->inDataUnorderSegs.value.ui32 =
26561 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26562 	tcpkp->inDataUnorderBytes.value.ui32 =
26563 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26564 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26565 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26566 	tcpkp->inDataPartDupSegs.value.ui32 =
26567 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26568 	tcpkp->inDataPartDupBytes.value.ui32 =
26569 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26570 	tcpkp->inDataPastWinSegs.value.ui32 =
26571 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26572 	tcpkp->inDataPastWinBytes.value.ui32 =
26573 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26574 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26575 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26576 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26577 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26578 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26579 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26580 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26581 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26582 	tcpkp->timKeepaliveProbe.value.ui32 =
26583 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26584 	tcpkp->timKeepaliveDrop.value.ui32 =
26585 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26586 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26587 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26588 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26589 	tcpkp->outSackRetransSegs.value.ui32 =
26590 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26591 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26592 
26593 	netstack_rele(ns);
26594 	return (0);
26595 }
26596 
26597 void
26598 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26599 {
26600 	uint16_t	hdr_len;
26601 	ipha_t		*ipha;
26602 	uint8_t		*nexthdrp;
26603 	tcph_t		*tcph;
26604 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26605 
26606 	/* Already has an eager */
26607 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26608 		TCP_STAT(tcps, tcp_reinput_syn);
26609 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26610 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
26611 		return;
26612 	}
26613 
26614 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26615 	case IPV4_VERSION:
26616 		ipha = (ipha_t *)mp->b_rptr;
26617 		hdr_len = IPH_HDR_LENGTH(ipha);
26618 		break;
26619 	case IPV6_VERSION:
26620 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26621 		    &hdr_len, &nexthdrp)) {
26622 			CONN_DEC_REF(connp);
26623 			freemsg(mp);
26624 			return;
26625 		}
26626 		break;
26627 	}
26628 
26629 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26630 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26631 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26632 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26633 	}
26634 
26635 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26636 	    SQ_FILL, SQTAG_TCP_REINPUT);
26637 }
26638 
26639 static int
26640 tcp_squeue_switch(int val)
26641 {
26642 	int rval = SQ_FILL;
26643 
26644 	switch (val) {
26645 	case 1:
26646 		rval = SQ_NODRAIN;
26647 		break;
26648 	case 2:
26649 		rval = SQ_PROCESS;
26650 		break;
26651 	default:
26652 		break;
26653 	}
26654 	return (rval);
26655 }
26656 
26657 /*
26658  * This is called once for each squeue - globally for all stack
26659  * instances.
26660  */
26661 static void
26662 tcp_squeue_add(squeue_t *sqp)
26663 {
26664 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26665 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26666 
26667 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26668 	tcp_time_wait->tcp_time_wait_tid =
26669 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26670 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26671 	    CALLOUT_FLAG_ROUNDUP);
26672 	if (tcp_free_list_max_cnt == 0) {
26673 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26674 		    max_ncpus : boot_max_ncpus);
26675 
26676 		/*
26677 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26678 		 */
26679 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26680 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26681 	}
26682 	tcp_time_wait->tcp_free_list_cnt = 0;
26683 }
26684