xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 67ce1dada345581246cd990d73516418f321a793)
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 <netinet/in.h>
68 #include <netinet/tcp.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <net/if.h>
72 #include <net/route.h>
73 #include <inet/ipsec_impl.h>
74 
75 #include <inet/common.h>
76 #include <inet/ip.h>
77 #include <inet/ip_impl.h>
78 #include <inet/ip6.h>
79 #include <inet/ip_ndp.h>
80 #include <inet/mi.h>
81 #include <inet/mib2.h>
82 #include <inet/nd.h>
83 #include <inet/optcom.h>
84 #include <inet/snmpcom.h>
85 #include <inet/kstatcom.h>
86 #include <inet/tcp.h>
87 #include <inet/tcp_impl.h>
88 #include <net/pfkeyv2.h>
89 #include <inet/ipsec_info.h>
90 #include <inet/ipdrop.h>
91 
92 #include <inet/ipclassifier.h>
93 #include <inet/ip_ire.h>
94 #include <inet/ip_ftable.h>
95 #include <inet/ip_if.h>
96 #include <inet/ipp_common.h>
97 #include <inet/ip_netinfo.h>
98 #include <sys/squeue.h>
99 #include <inet/kssl/ksslapi.h>
100 #include <sys/tsol/label.h>
101 #include <sys/tsol/tnet.h>
102 #include <rpc/pmap_prot.h>
103 
104 /*
105  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
106  *
107  * (Read the detailed design doc in PSARC case directory)
108  *
109  * The entire tcp state is contained in tcp_t and conn_t structure
110  * which are allocated in tandem using ipcl_conn_create() and passing
111  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
112  * the references on the tcp_t. The tcp_t structure is never compressed
113  * and packets always land on the correct TCP perimeter from the time
114  * eager is created till the time tcp_t dies (as such the old mentat
115  * TCP global queue is not used for detached state and no IPSEC checking
116  * is required). The global queue is still allocated to send out resets
117  * for connection which have no listeners and IP directly calls
118  * tcp_xmit_listeners_reset() which does any policy check.
119  *
120  * Protection and Synchronisation mechanism:
121  *
122  * The tcp data structure does not use any kind of lock for protecting
123  * its state but instead uses 'squeues' for mutual exclusion from various
124  * read and write side threads. To access a tcp member, the thread should
125  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
126  * squeue_fill). Since the squeues allow a direct function call, caller
127  * can pass any tcp function having prototype of edesc_t as argument
128  * (different from traditional STREAMs model where packets come in only
129  * designated entry points). The list of functions that can be directly
130  * called via squeue are listed before the usual function prototype.
131  *
132  * Referencing:
133  *
134  * TCP is MT-Hot and we use a reference based scheme to make sure that the
135  * tcp structure doesn't disappear when its needed. When the application
136  * creates an outgoing connection or accepts an incoming connection, we
137  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
138  * The IP reference is just a symbolic reference since ip_tcpclose()
139  * looks at tcp structure after tcp_close_output() returns which could
140  * have dropped the last TCP reference. So as long as the connection is
141  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
142  * conn_t. The classifier puts its own reference when the connection is
143  * inserted in listen or connected hash. Anytime a thread needs to enter
144  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
145  * on write side or by doing a classify on read side and then puts a
146  * reference on the conn before doing squeue_enter/tryenter/fill. For
147  * read side, the classifier itself puts the reference under fanout lock
148  * to make sure that tcp can't disappear before it gets processed. The
149  * squeue will drop this reference automatically so the called function
150  * doesn't have to do a DEC_REF.
151  *
152  * Opening a new connection:
153  *
154  * The outgoing connection open is pretty simple. tcp_open() does the
155  * work in creating the conn/tcp structure and initializing it. The
156  * squeue assignment is done based on the CPU the application
157  * is running on. So for outbound connections, processing is always done
158  * on application CPU which might be different from the incoming CPU
159  * being interrupted by the NIC. An optimal way would be to figure out
160  * the NIC <-> CPU binding at listen time, and assign the outgoing
161  * connection to the squeue attached to the CPU that will be interrupted
162  * for incoming packets (we know the NIC based on the bind IP address).
163  * This might seem like a problem if more data is going out but the
164  * fact is that in most cases the transmit is ACK driven transmit where
165  * the outgoing data normally sits on TCP's xmit queue waiting to be
166  * transmitted.
167  *
168  * Accepting a connection:
169  *
170  * This is a more interesting case because of various races involved in
171  * establishing a eager in its own perimeter. Read the meta comment on
172  * top of tcp_conn_request(). But briefly, the squeue is picked by
173  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
174  *
175  * Closing a connection:
176  *
177  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
178  * via squeue to do the close and mark the tcp as detached if the connection
179  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
180  * reference but tcp_close() drop IP's reference always. So if tcp was
181  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
182  * and 1 because it is in classifier's connected hash. This is the condition
183  * we use to determine that its OK to clean up the tcp outside of squeue
184  * when time wait expires (check the ref under fanout and conn_lock and
185  * if it is 2, remove it from fanout hash and kill it).
186  *
187  * Although close just drops the necessary references and marks the
188  * tcp_detached state, tcp_close needs to know the tcp_detached has been
189  * set (under squeue) before letting the STREAM go away (because a
190  * inbound packet might attempt to go up the STREAM while the close
191  * has happened and tcp_detached is not set). So a special lock and
192  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
193  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
194  * tcp_detached.
195  *
196  * Special provisions and fast paths:
197  *
198  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
199  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
200  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
201  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
202  * check to send packets directly to tcp_rput_data via squeue. Everyone
203  * else comes through tcp_input() on the read side.
204  *
205  * We also make special provisions for sockfs by marking tcp_issocket
206  * whenever we have only sockfs on top of TCP. This allows us to skip
207  * putting the tcp in acceptor hash since a sockfs listener can never
208  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
209  * since eager has already been allocated and the accept now happens
210  * on acceptor STREAM. There is a big blob of comment on top of
211  * tcp_conn_request explaining the new accept. When socket is POP'd,
212  * sockfs sends us an ioctl to mark the fact and we go back to old
213  * behaviour. Once tcp_issocket is unset, its never set for the
214  * life of that connection.
215  *
216  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
217  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
218  * directly to the socket (sodirect) and start an asynchronous copyout
219  * to a user-land receive-side buffer (uioa) when a blocking socket read
220  * (e.g. read, recv, ...) is pending.
221  *
222  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
223  * NULL so points to an sodirect_t and if marked enabled then we enqueue
224  * all mblk_t's directly to the socket.
225  *
226  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
227  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
228  * copyout will be started directly to the user-land uio buffer. Also, as we
229  * have a pending read, TCP's push logic can take into account the number of
230  * bytes to be received and only awake the blocked read()er when the uioa_t
231  * byte count has been satisfied.
232  *
233  * IPsec notes :
234  *
235  * Since a packet is always executed on the correct TCP perimeter
236  * all IPsec processing is defered to IP including checking new
237  * connections and setting IPSEC policies for new connection. The
238  * only exception is tcp_xmit_listeners_reset() which is called
239  * directly from IP and needs to policy check to see if TH_RST
240  * can be sent out.
241  *
242  * PFHooks notes :
243  *
244  * For mdt case, one meta buffer contains multiple packets. Mblks for every
245  * packet are assembled and passed to the hooks. When packets are blocked,
246  * or boundary of any packet is changed, the mdt processing is stopped, and
247  * packets of the meta buffer are send to the IP path one by one.
248  */
249 
250 /*
251  * Values for squeue switch:
252  * 1: squeue_enter_nodrain
253  * 2: squeue_enter
254  * 3: squeue_fill
255  */
256 int tcp_squeue_close = 2;	/* Setable in /etc/system */
257 int tcp_squeue_wput = 2;
258 
259 squeue_func_t tcp_squeue_close_proc;
260 squeue_func_t tcp_squeue_wput_proc;
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 	timeout_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 	timeout_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 squeue_func_t 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 
1634 	tcp_bind_hash_remove(tcp);
1635 
1636 	/* Cleanup that which needs the netstack first */
1637 	tcp_ipsec_cleanup(tcp);
1638 
1639 	tcp_free(tcp);
1640 
1641 	/* Release any SSL context */
1642 	if (tcp->tcp_kssl_ent != NULL) {
1643 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1644 		tcp->tcp_kssl_ent = NULL;
1645 	}
1646 
1647 	if (tcp->tcp_kssl_ctx != NULL) {
1648 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1649 		tcp->tcp_kssl_ctx = NULL;
1650 	}
1651 	tcp->tcp_kssl_pending = B_FALSE;
1652 
1653 	conn_delete_ire(connp, NULL);
1654 
1655 	/*
1656 	 * Since we will bzero the entire structure, we need to
1657 	 * remove it and reinsert it in global hash list. We
1658 	 * know the walkers can't get to this conn because we
1659 	 * had set CONDEMNED flag earlier and checked reference
1660 	 * under conn_lock so walker won't pick it and when we
1661 	 * go the ipcl_globalhash_remove() below, no walker
1662 	 * can get to it.
1663 	 */
1664 	ipcl_globalhash_remove(connp);
1665 
1666 	/*
1667 	 * Now it is safe to decrement the reference counts.
1668 	 * This might be the last reference on the netstack and TCPS
1669 	 * in which case it will cause the tcp_g_q_close and
1670 	 * the freeing of the IP Instance.
1671 	 */
1672 	connp->conn_netstack = NULL;
1673 	netstack_rele(ns);
1674 	ASSERT(tcps != NULL);
1675 	tcp->tcp_tcps = NULL;
1676 	TCPS_REFRELE(tcps);
1677 
1678 	/* Save some state */
1679 	mp = tcp->tcp_timercache;
1680 
1681 	tcp_sack_info = tcp->tcp_sack_info;
1682 	tcp_iphc = tcp->tcp_iphc;
1683 	tcp_iphc_len = tcp->tcp_iphc_len;
1684 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1685 
1686 	if (connp->conn_cred != NULL) {
1687 		crfree(connp->conn_cred);
1688 		connp->conn_cred = NULL;
1689 	}
1690 	if (connp->conn_peercred != NULL) {
1691 		crfree(connp->conn_peercred);
1692 		connp->conn_peercred = NULL;
1693 	}
1694 	ipcl_conn_cleanup(connp);
1695 	connp->conn_flags = IPCL_TCPCONN;
1696 	bzero(tcp, sizeof (tcp_t));
1697 
1698 	/* restore the state */
1699 	tcp->tcp_timercache = mp;
1700 
1701 	tcp->tcp_sack_info = tcp_sack_info;
1702 	tcp->tcp_iphc = tcp_iphc;
1703 	tcp->tcp_iphc_len = tcp_iphc_len;
1704 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1705 
1706 	tcp->tcp_connp = connp;
1707 
1708 	ASSERT(connp->conn_tcp == tcp);
1709 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1710 	connp->conn_state_flags = CONN_INCIPIENT;
1711 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1712 	ASSERT(connp->conn_ref == 1);
1713 }
1714 
1715 /*
1716  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1717  * is done forwards from the head.
1718  * This walks all stack instances since
1719  * tcp_time_wait remains global across all stacks.
1720  */
1721 /* ARGSUSED */
1722 void
1723 tcp_time_wait_collector(void *arg)
1724 {
1725 	tcp_t *tcp;
1726 	clock_t now;
1727 	mblk_t *mp;
1728 	conn_t *connp;
1729 	kmutex_t *lock;
1730 	boolean_t removed;
1731 
1732 	squeue_t *sqp = (squeue_t *)arg;
1733 	tcp_squeue_priv_t *tcp_time_wait =
1734 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1735 
1736 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1737 	tcp_time_wait->tcp_time_wait_tid = 0;
1738 
1739 	if (tcp_time_wait->tcp_free_list != NULL &&
1740 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1741 		TCP_G_STAT(tcp_freelist_cleanup);
1742 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1743 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1744 			tcp->tcp_time_wait_next = NULL;
1745 			tcp_time_wait->tcp_free_list_cnt--;
1746 			ASSERT(tcp->tcp_tcps == NULL);
1747 			CONN_DEC_REF(tcp->tcp_connp);
1748 		}
1749 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1750 	}
1751 
1752 	/*
1753 	 * In order to reap time waits reliably, we should use a
1754 	 * source of time that is not adjustable by the user -- hence
1755 	 * the call to ddi_get_lbolt().
1756 	 */
1757 	now = ddi_get_lbolt();
1758 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1759 		/*
1760 		 * Compare times using modular arithmetic, since
1761 		 * lbolt can wrapover.
1762 		 */
1763 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1764 			break;
1765 		}
1766 
1767 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1768 		ASSERT(removed);
1769 
1770 		connp = tcp->tcp_connp;
1771 		ASSERT(connp->conn_fanout != NULL);
1772 		lock = &connp->conn_fanout->connf_lock;
1773 		/*
1774 		 * This is essentially a TW reclaim fast path optimization for
1775 		 * performance where the timewait collector checks under the
1776 		 * fanout lock (so that no one else can get access to the
1777 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1778 		 * the classifier hash list. If ref count is indeed 2, we can
1779 		 * just remove the conn under the fanout lock and avoid
1780 		 * cleaning up the conn under the squeue, provided that
1781 		 * clustering callbacks are not enabled. If clustering is
1782 		 * enabled, we need to make the clustering callback before
1783 		 * setting the CONDEMNED flag and after dropping all locks and
1784 		 * so we forego this optimization and fall back to the slow
1785 		 * path. Also please see the comments in tcp_closei_local
1786 		 * regarding the refcnt logic.
1787 		 *
1788 		 * Since we are holding the tcp_time_wait_lock, its better
1789 		 * not to block on the fanout_lock because other connections
1790 		 * can't add themselves to time_wait list. So we do a
1791 		 * tryenter instead of mutex_enter.
1792 		 */
1793 		if (mutex_tryenter(lock)) {
1794 			mutex_enter(&connp->conn_lock);
1795 			if ((connp->conn_ref == 2) &&
1796 			    (cl_inet_disconnect == NULL)) {
1797 				ipcl_hash_remove_locked(connp,
1798 				    connp->conn_fanout);
1799 				/*
1800 				 * Set the CONDEMNED flag now itself so that
1801 				 * the refcnt cannot increase due to any
1802 				 * walker. But we have still not cleaned up
1803 				 * conn_ire_cache. This is still ok since
1804 				 * we are going to clean it up in tcp_cleanup
1805 				 * immediately and any interface unplumb
1806 				 * thread will wait till the ire is blown away
1807 				 */
1808 				connp->conn_state_flags |= CONN_CONDEMNED;
1809 				mutex_exit(lock);
1810 				mutex_exit(&connp->conn_lock);
1811 				if (tcp_time_wait->tcp_free_list_cnt <
1812 				    tcp_free_list_max_cnt) {
1813 					/* Add to head of tcp_free_list */
1814 					mutex_exit(
1815 					    &tcp_time_wait->tcp_time_wait_lock);
1816 					tcp_cleanup(tcp);
1817 					ASSERT(connp->conn_latch == NULL);
1818 					ASSERT(connp->conn_policy == NULL);
1819 					ASSERT(tcp->tcp_tcps == NULL);
1820 					ASSERT(connp->conn_netstack == NULL);
1821 
1822 					mutex_enter(
1823 					    &tcp_time_wait->tcp_time_wait_lock);
1824 					tcp->tcp_time_wait_next =
1825 					    tcp_time_wait->tcp_free_list;
1826 					tcp_time_wait->tcp_free_list = tcp;
1827 					tcp_time_wait->tcp_free_list_cnt++;
1828 					continue;
1829 				} else {
1830 					/* Do not add to tcp_free_list */
1831 					mutex_exit(
1832 					    &tcp_time_wait->tcp_time_wait_lock);
1833 					tcp_bind_hash_remove(tcp);
1834 					conn_delete_ire(tcp->tcp_connp, NULL);
1835 					tcp_ipsec_cleanup(tcp);
1836 					CONN_DEC_REF(tcp->tcp_connp);
1837 				}
1838 			} else {
1839 				CONN_INC_REF_LOCKED(connp);
1840 				mutex_exit(lock);
1841 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1842 				mutex_exit(&connp->conn_lock);
1843 				/*
1844 				 * We can reuse the closemp here since conn has
1845 				 * detached (otherwise we wouldn't even be in
1846 				 * time_wait list). tcp_closemp_used can safely
1847 				 * be changed without taking a lock as no other
1848 				 * thread can concurrently access it at this
1849 				 * point in the connection lifecycle.
1850 				 */
1851 
1852 				if (tcp->tcp_closemp.b_prev == NULL)
1853 					tcp->tcp_closemp_used = B_TRUE;
1854 				else
1855 					cmn_err(CE_PANIC,
1856 					    "tcp_timewait_collector: "
1857 					    "concurrent use of tcp_closemp: "
1858 					    "connp %p tcp %p\n", (void *)connp,
1859 					    (void *)tcp);
1860 
1861 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1862 				mp = &tcp->tcp_closemp;
1863 				squeue_fill(connp->conn_sqp, mp,
1864 				    tcp_timewait_output, connp,
1865 				    SQTAG_TCP_TIMEWAIT);
1866 			}
1867 		} else {
1868 			mutex_enter(&connp->conn_lock);
1869 			CONN_INC_REF_LOCKED(connp);
1870 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1871 			mutex_exit(&connp->conn_lock);
1872 			/*
1873 			 * We can reuse the closemp here since conn has
1874 			 * detached (otherwise we wouldn't even be in
1875 			 * time_wait list). tcp_closemp_used can safely
1876 			 * be changed without taking a lock as no other
1877 			 * thread can concurrently access it at this
1878 			 * point in the connection lifecycle.
1879 			 */
1880 
1881 			if (tcp->tcp_closemp.b_prev == NULL)
1882 				tcp->tcp_closemp_used = B_TRUE;
1883 			else
1884 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1885 				    "concurrent use of tcp_closemp: "
1886 				    "connp %p tcp %p\n", (void *)connp,
1887 				    (void *)tcp);
1888 
1889 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1890 			mp = &tcp->tcp_closemp;
1891 			squeue_fill(connp->conn_sqp, mp,
1892 			    tcp_timewait_output, connp, 0);
1893 		}
1894 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1895 	}
1896 
1897 	if (tcp_time_wait->tcp_free_list != NULL)
1898 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1899 
1900 	tcp_time_wait->tcp_time_wait_tid =
1901 	    timeout(tcp_time_wait_collector, sqp, TCP_TIME_WAIT_DELAY);
1902 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1903 }
1904 /*
1905  * Reply to a clients T_CONN_RES TPI message. This function
1906  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1907  * on the acceptor STREAM and processed in tcp_wput_accept().
1908  * Read the block comment on top of tcp_conn_request().
1909  */
1910 static void
1911 tcp_accept(tcp_t *listener, mblk_t *mp)
1912 {
1913 	tcp_t	*acceptor;
1914 	tcp_t	*eager;
1915 	tcp_t   *tcp;
1916 	struct T_conn_res	*tcr;
1917 	t_uscalar_t	acceptor_id;
1918 	t_scalar_t	seqnum;
1919 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1920 	mblk_t	*ok_mp;
1921 	mblk_t	*mp1;
1922 	tcp_stack_t	*tcps = listener->tcp_tcps;
1923 
1924 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1925 		tcp_err_ack(listener, mp, TPROTO, 0);
1926 		return;
1927 	}
1928 	tcr = (struct T_conn_res *)mp->b_rptr;
1929 
1930 	/*
1931 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1932 	 * read side queue of the streams device underneath us i.e. the
1933 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1934 	 * look it up in the queue_hash.  Under LP64 it sends down the
1935 	 * minor_t of the accepting endpoint.
1936 	 *
1937 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1938 	 * fanout hash lock is held.
1939 	 * This prevents any thread from entering the acceptor queue from
1940 	 * below (since it has not been hard bound yet i.e. any inbound
1941 	 * packets will arrive on the listener or default tcp queue and
1942 	 * go through tcp_lookup).
1943 	 * The CONN_INC_REF will prevent the acceptor from closing.
1944 	 *
1945 	 * XXX It is still possible for a tli application to send down data
1946 	 * on the accepting stream while another thread calls t_accept.
1947 	 * This should not be a problem for well-behaved applications since
1948 	 * the T_OK_ACK is sent after the queue swapping is completed.
1949 	 *
1950 	 * If the accepting fd is the same as the listening fd, avoid
1951 	 * queue hash lookup since that will return an eager listener in a
1952 	 * already established state.
1953 	 */
1954 	acceptor_id = tcr->ACCEPTOR_id;
1955 	mutex_enter(&listener->tcp_eager_lock);
1956 	if (listener->tcp_acceptor_id == acceptor_id) {
1957 		eager = listener->tcp_eager_next_q;
1958 		/* only count how many T_CONN_INDs so don't count q0 */
1959 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1960 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1961 			mutex_exit(&listener->tcp_eager_lock);
1962 			tcp_err_ack(listener, mp, TBADF, 0);
1963 			return;
1964 		}
1965 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1966 			/* Throw away all the eagers on q0. */
1967 			tcp_eager_cleanup(listener, 1);
1968 		}
1969 		if (listener->tcp_syn_defense) {
1970 			listener->tcp_syn_defense = B_FALSE;
1971 			if (listener->tcp_ip_addr_cache != NULL) {
1972 				kmem_free(listener->tcp_ip_addr_cache,
1973 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1974 				listener->tcp_ip_addr_cache = NULL;
1975 			}
1976 		}
1977 		/*
1978 		 * Transfer tcp_conn_req_max to the eager so that when
1979 		 * a disconnect occurs we can revert the endpoint to the
1980 		 * listen state.
1981 		 */
1982 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1983 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1984 		/*
1985 		 * Get a reference on the acceptor just like the
1986 		 * tcp_acceptor_hash_lookup below.
1987 		 */
1988 		acceptor = listener;
1989 		CONN_INC_REF(acceptor->tcp_connp);
1990 	} else {
1991 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1992 		if (acceptor == NULL) {
1993 			if (listener->tcp_debug) {
1994 				(void) strlog(TCP_MOD_ID, 0, 1,
1995 				    SL_ERROR|SL_TRACE,
1996 				    "tcp_accept: did not find acceptor 0x%x\n",
1997 				    acceptor_id);
1998 			}
1999 			mutex_exit(&listener->tcp_eager_lock);
2000 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2001 			return;
2002 		}
2003 		/*
2004 		 * Verify acceptor state. The acceptable states for an acceptor
2005 		 * include TCPS_IDLE and TCPS_BOUND.
2006 		 */
2007 		switch (acceptor->tcp_state) {
2008 		case TCPS_IDLE:
2009 			/* FALLTHRU */
2010 		case TCPS_BOUND:
2011 			break;
2012 		default:
2013 			CONN_DEC_REF(acceptor->tcp_connp);
2014 			mutex_exit(&listener->tcp_eager_lock);
2015 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2016 			return;
2017 		}
2018 	}
2019 
2020 	/* The listener must be in TCPS_LISTEN */
2021 	if (listener->tcp_state != TCPS_LISTEN) {
2022 		CONN_DEC_REF(acceptor->tcp_connp);
2023 		mutex_exit(&listener->tcp_eager_lock);
2024 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2025 		return;
2026 	}
2027 
2028 	/*
2029 	 * Rendezvous with an eager connection request packet hanging off
2030 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2031 	 * tcp structure when the connection packet arrived in
2032 	 * tcp_conn_request().
2033 	 */
2034 	seqnum = tcr->SEQ_number;
2035 	eager = listener;
2036 	do {
2037 		eager = eager->tcp_eager_next_q;
2038 		if (eager == NULL) {
2039 			CONN_DEC_REF(acceptor->tcp_connp);
2040 			mutex_exit(&listener->tcp_eager_lock);
2041 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2042 			return;
2043 		}
2044 	} while (eager->tcp_conn_req_seqnum != seqnum);
2045 	mutex_exit(&listener->tcp_eager_lock);
2046 
2047 	/*
2048 	 * At this point, both acceptor and listener have 2 ref
2049 	 * that they begin with. Acceptor has one additional ref
2050 	 * we placed in lookup while listener has 3 additional
2051 	 * ref for being behind the squeue (tcp_accept() is
2052 	 * done on listener's squeue); being in classifier hash;
2053 	 * and eager's ref on listener.
2054 	 */
2055 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2056 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2057 
2058 	/*
2059 	 * The eager at this point is set in its own squeue and
2060 	 * could easily have been killed (tcp_accept_finish will
2061 	 * deal with that) because of a TH_RST so we can only
2062 	 * ASSERT for a single ref.
2063 	 */
2064 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2065 
2066 	/* Pre allocate the stroptions mblk also */
2067 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2068 	if (opt_mp == NULL) {
2069 		CONN_DEC_REF(acceptor->tcp_connp);
2070 		CONN_DEC_REF(eager->tcp_connp);
2071 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2072 		return;
2073 	}
2074 	DB_TYPE(opt_mp) = M_SETOPTS;
2075 	opt_mp->b_wptr += sizeof (struct stroptions);
2076 
2077 	/*
2078 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2079 	 * from listener to acceptor. The message is chained on opt_mp
2080 	 * which will be sent onto eager's squeue.
2081 	 */
2082 	if (listener->tcp_bound_if != 0) {
2083 		/* allocate optmgmt req */
2084 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2085 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2086 		    sizeof (int));
2087 		if (mp1 != NULL)
2088 			linkb(opt_mp, mp1);
2089 	}
2090 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2091 		uint_t on = 1;
2092 
2093 		/* allocate optmgmt req */
2094 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2095 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2096 		if (mp1 != NULL)
2097 			linkb(opt_mp, mp1);
2098 	}
2099 
2100 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2101 	if ((mp1 = copymsg(mp)) == NULL) {
2102 		CONN_DEC_REF(acceptor->tcp_connp);
2103 		CONN_DEC_REF(eager->tcp_connp);
2104 		freemsg(opt_mp);
2105 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2106 		return;
2107 	}
2108 
2109 	tcr = (struct T_conn_res *)mp1->b_rptr;
2110 
2111 	/*
2112 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2113 	 * which allocates a larger mblk and appends the new
2114 	 * local address to the ok_ack.  The address is copied by
2115 	 * soaccept() for getsockname().
2116 	 */
2117 	{
2118 		int extra;
2119 
2120 		extra = (eager->tcp_family == AF_INET) ?
2121 		    sizeof (sin_t) : sizeof (sin6_t);
2122 
2123 		/*
2124 		 * Try to re-use mp, if possible.  Otherwise, allocate
2125 		 * an mblk and return it as ok_mp.  In any case, mp
2126 		 * is no longer usable upon return.
2127 		 */
2128 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2129 			CONN_DEC_REF(acceptor->tcp_connp);
2130 			CONN_DEC_REF(eager->tcp_connp);
2131 			freemsg(opt_mp);
2132 			/* Original mp has been freed by now, so use mp1 */
2133 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2134 			return;
2135 		}
2136 
2137 		mp = NULL;	/* We should never use mp after this point */
2138 
2139 		switch (extra) {
2140 		case sizeof (sin_t): {
2141 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2142 
2143 				ok_mp->b_wptr += extra;
2144 				sin->sin_family = AF_INET;
2145 				sin->sin_port = eager->tcp_lport;
2146 				sin->sin_addr.s_addr =
2147 				    eager->tcp_ipha->ipha_src;
2148 				break;
2149 			}
2150 		case sizeof (sin6_t): {
2151 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2152 
2153 				ok_mp->b_wptr += extra;
2154 				sin6->sin6_family = AF_INET6;
2155 				sin6->sin6_port = eager->tcp_lport;
2156 				if (eager->tcp_ipversion == IPV4_VERSION) {
2157 					sin6->sin6_flowinfo = 0;
2158 					IN6_IPADDR_TO_V4MAPPED(
2159 					    eager->tcp_ipha->ipha_src,
2160 					    &sin6->sin6_addr);
2161 				} else {
2162 					ASSERT(eager->tcp_ip6h != NULL);
2163 					sin6->sin6_flowinfo =
2164 					    eager->tcp_ip6h->ip6_vcf &
2165 					    ~IPV6_VERS_AND_FLOW_MASK;
2166 					sin6->sin6_addr =
2167 					    eager->tcp_ip6h->ip6_src;
2168 				}
2169 				sin6->sin6_scope_id = 0;
2170 				sin6->__sin6_src_id = 0;
2171 				break;
2172 			}
2173 		default:
2174 			break;
2175 		}
2176 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2177 	}
2178 
2179 	/*
2180 	 * If there are no options we know that the T_CONN_RES will
2181 	 * succeed. However, we can't send the T_OK_ACK upstream until
2182 	 * the tcp_accept_swap is done since it would be dangerous to
2183 	 * let the application start using the new fd prior to the swap.
2184 	 */
2185 	tcp_accept_swap(listener, acceptor, eager);
2186 
2187 	/*
2188 	 * tcp_accept_swap unlinks eager from listener but does not drop
2189 	 * the eager's reference on the listener.
2190 	 */
2191 	ASSERT(eager->tcp_listener == NULL);
2192 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2193 
2194 	/*
2195 	 * The eager is now associated with its own queue. Insert in
2196 	 * the hash so that the connection can be reused for a future
2197 	 * T_CONN_RES.
2198 	 */
2199 	tcp_acceptor_hash_insert(acceptor_id, eager);
2200 
2201 	/*
2202 	 * We now do the processing of options with T_CONN_RES.
2203 	 * We delay till now since we wanted to have queue to pass to
2204 	 * option processing routines that points back to the right
2205 	 * instance structure which does not happen until after
2206 	 * tcp_accept_swap().
2207 	 *
2208 	 * Note:
2209 	 * The sanity of the logic here assumes that whatever options
2210 	 * are appropriate to inherit from listner=>eager are done
2211 	 * before this point, and whatever were to be overridden (or not)
2212 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2213 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2214 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2215 	 * This may not be true at this point in time but can be fixed
2216 	 * independently. This option processing code starts with
2217 	 * the instantiated acceptor instance and the final queue at
2218 	 * this point.
2219 	 */
2220 
2221 	if (tcr->OPT_length != 0) {
2222 		/* Options to process */
2223 		int t_error = 0;
2224 		int sys_error = 0;
2225 		int do_disconnect = 0;
2226 
2227 		if (tcp_conprim_opt_process(eager, mp1,
2228 		    &do_disconnect, &t_error, &sys_error) < 0) {
2229 			eager->tcp_accept_error = 1;
2230 			if (do_disconnect) {
2231 				/*
2232 				 * An option failed which does not allow
2233 				 * connection to be accepted.
2234 				 *
2235 				 * We allow T_CONN_RES to succeed and
2236 				 * put a T_DISCON_IND on the eager queue.
2237 				 */
2238 				ASSERT(t_error == 0 && sys_error == 0);
2239 				eager->tcp_send_discon_ind = 1;
2240 			} else {
2241 				ASSERT(t_error != 0);
2242 				freemsg(ok_mp);
2243 				/*
2244 				 * Original mp was either freed or set
2245 				 * to ok_mp above, so use mp1 instead.
2246 				 */
2247 				tcp_err_ack(listener, mp1, t_error, sys_error);
2248 				goto finish;
2249 			}
2250 		}
2251 		/*
2252 		 * Most likely success in setting options (except if
2253 		 * eager->tcp_send_discon_ind set).
2254 		 * mp1 option buffer represented by OPT_length/offset
2255 		 * potentially modified and contains results of setting
2256 		 * options at this point
2257 		 */
2258 	}
2259 
2260 	/* We no longer need mp1, since all options processing has passed */
2261 	freemsg(mp1);
2262 
2263 	putnext(listener->tcp_rq, ok_mp);
2264 
2265 	mutex_enter(&listener->tcp_eager_lock);
2266 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2267 		tcp_t	*tail;
2268 		mblk_t	*conn_ind;
2269 
2270 		/*
2271 		 * This path should not be executed if listener and
2272 		 * acceptor streams are the same.
2273 		 */
2274 		ASSERT(listener != acceptor);
2275 
2276 		tcp = listener->tcp_eager_prev_q0;
2277 		/*
2278 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2279 		 * deferred T_conn_ind queue. We need to get to the head of
2280 		 * the queue in order to send up T_conn_ind the same order as
2281 		 * how the 3WHS is completed.
2282 		 */
2283 		while (tcp != listener) {
2284 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2285 				break;
2286 			else
2287 				tcp = tcp->tcp_eager_prev_q0;
2288 		}
2289 		ASSERT(tcp != listener);
2290 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2291 		ASSERT(conn_ind != NULL);
2292 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2293 
2294 		/* Move from q0 to q */
2295 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2296 		listener->tcp_conn_req_cnt_q0--;
2297 		listener->tcp_conn_req_cnt_q++;
2298 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2299 		    tcp->tcp_eager_prev_q0;
2300 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2301 		    tcp->tcp_eager_next_q0;
2302 		tcp->tcp_eager_prev_q0 = NULL;
2303 		tcp->tcp_eager_next_q0 = NULL;
2304 		tcp->tcp_conn_def_q0 = B_FALSE;
2305 
2306 		/* Make sure the tcp isn't in the list of droppables */
2307 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2308 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2309 
2310 		/*
2311 		 * Insert at end of the queue because sockfs sends
2312 		 * down T_CONN_RES in chronological order. Leaving
2313 		 * the older conn indications at front of the queue
2314 		 * helps reducing search time.
2315 		 */
2316 		tail = listener->tcp_eager_last_q;
2317 		if (tail != NULL)
2318 			tail->tcp_eager_next_q = tcp;
2319 		else
2320 			listener->tcp_eager_next_q = tcp;
2321 		listener->tcp_eager_last_q = tcp;
2322 		tcp->tcp_eager_next_q = NULL;
2323 		mutex_exit(&listener->tcp_eager_lock);
2324 		putnext(tcp->tcp_rq, conn_ind);
2325 	} else {
2326 		mutex_exit(&listener->tcp_eager_lock);
2327 	}
2328 
2329 	/*
2330 	 * Done with the acceptor - free it
2331 	 *
2332 	 * Note: from this point on, no access to listener should be made
2333 	 * as listener can be equal to acceptor.
2334 	 */
2335 finish:
2336 	ASSERT(acceptor->tcp_detached);
2337 	ASSERT(tcps->tcps_g_q != NULL);
2338 	acceptor->tcp_rq = tcps->tcps_g_q;
2339 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2340 	(void) tcp_clean_death(acceptor, 0, 2);
2341 	CONN_DEC_REF(acceptor->tcp_connp);
2342 
2343 	/*
2344 	 * In case we already received a FIN we have to make tcp_rput send
2345 	 * the ordrel_ind. This will also send up a window update if the window
2346 	 * has opened up.
2347 	 *
2348 	 * In the normal case of a successful connection acceptance
2349 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2350 	 * indication that this was just accepted. This tells tcp_rput to
2351 	 * pass up any data queued in tcp_rcv_list.
2352 	 *
2353 	 * In the fringe case where options sent with T_CONN_RES failed and
2354 	 * we required, we would be indicating a T_DISCON_IND to blow
2355 	 * away this connection.
2356 	 */
2357 
2358 	/*
2359 	 * XXX: we currently have a problem if XTI application closes the
2360 	 * acceptor stream in between. This problem exists in on10-gate also
2361 	 * and is well know but nothing can be done short of major rewrite
2362 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2363 	 * eager same squeue as listener (we can distinguish non socket
2364 	 * listeners at the time of handling a SYN in tcp_conn_request)
2365 	 * and do most of the work that tcp_accept_finish does here itself
2366 	 * and then get behind the acceptor squeue to access the acceptor
2367 	 * queue.
2368 	 */
2369 	/*
2370 	 * We already have a ref on tcp so no need to do one before squeue_fill
2371 	 */
2372 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2373 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2374 }
2375 
2376 /*
2377  * Swap information between the eager and acceptor for a TLI/XTI client.
2378  * The sockfs accept is done on the acceptor stream and control goes
2379  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2380  * called. In either case, both the eager and listener are in their own
2381  * perimeter (squeue) and the code has to deal with potential race.
2382  *
2383  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2384  */
2385 static void
2386 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2387 {
2388 	conn_t	*econnp, *aconnp;
2389 
2390 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2391 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2392 	ASSERT(!eager->tcp_hard_bound);
2393 	ASSERT(!TCP_IS_SOCKET(acceptor));
2394 	ASSERT(!TCP_IS_SOCKET(eager));
2395 	ASSERT(!TCP_IS_SOCKET(listener));
2396 
2397 	acceptor->tcp_detached = B_TRUE;
2398 	/*
2399 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2400 	 * the acceptor id.
2401 	 */
2402 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2403 
2404 	/* remove eager from listen list... */
2405 	mutex_enter(&listener->tcp_eager_lock);
2406 	tcp_eager_unlink(eager);
2407 	ASSERT(eager->tcp_eager_next_q == NULL &&
2408 	    eager->tcp_eager_last_q == NULL);
2409 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2410 	    eager->tcp_eager_prev_q0 == NULL);
2411 	mutex_exit(&listener->tcp_eager_lock);
2412 	eager->tcp_rq = acceptor->tcp_rq;
2413 	eager->tcp_wq = acceptor->tcp_wq;
2414 
2415 	econnp = eager->tcp_connp;
2416 	aconnp = acceptor->tcp_connp;
2417 
2418 	eager->tcp_rq->q_ptr = econnp;
2419 	eager->tcp_wq->q_ptr = econnp;
2420 
2421 	/*
2422 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2423 	 * which might be a different squeue from our peer TCP instance.
2424 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2425 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2426 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2427 	 * above reach global visibility prior to the clearing of tcp_detached.
2428 	 */
2429 	membar_producer();
2430 	eager->tcp_detached = B_FALSE;
2431 
2432 	ASSERT(eager->tcp_ack_tid == 0);
2433 
2434 	econnp->conn_dev = aconnp->conn_dev;
2435 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2436 	ASSERT(econnp->conn_minor_arena != NULL);
2437 	if (eager->tcp_cred != NULL)
2438 		crfree(eager->tcp_cred);
2439 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2440 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2441 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2442 
2443 	aconnp->conn_cred = NULL;
2444 
2445 	econnp->conn_zoneid = aconnp->conn_zoneid;
2446 	econnp->conn_allzones = aconnp->conn_allzones;
2447 
2448 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2449 	aconnp->conn_mac_exempt = B_FALSE;
2450 
2451 	ASSERT(aconnp->conn_peercred == NULL);
2452 
2453 	/* Do the IPC initialization */
2454 	CONN_INC_REF(econnp);
2455 
2456 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2457 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2458 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2459 
2460 	/* Done with old IPC. Drop its ref on its connp */
2461 	CONN_DEC_REF(aconnp);
2462 }
2463 
2464 
2465 /*
2466  * Adapt to the information, such as rtt and rtt_sd, provided from the
2467  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2468  *
2469  * Checks for multicast and broadcast destination address.
2470  * Returns zero on failure; non-zero if ok.
2471  *
2472  * Note that the MSS calculation here is based on the info given in
2473  * the IRE.  We do not do any calculation based on TCP options.  They
2474  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2475  * knows which options to use.
2476  *
2477  * Note on how TCP gets its parameters for a connection.
2478  *
2479  * When a tcp_t structure is allocated, it gets all the default parameters.
2480  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2481  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2482  * default.
2483  *
2484  * An incoming SYN with a multicast or broadcast destination address, is dropped
2485  * in 1 of 2 places.
2486  *
2487  * 1. If the packet was received over the wire it is dropped in
2488  * ip_rput_process_broadcast()
2489  *
2490  * 2. If the packet was received through internal IP loopback, i.e. the packet
2491  * was generated and received on the same machine, it is dropped in
2492  * ip_wput_local()
2493  *
2494  * An incoming SYN with a multicast or broadcast source address is always
2495  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2496  * reject an attempt to connect to a broadcast or multicast (destination)
2497  * address.
2498  */
2499 static int
2500 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2501 {
2502 	tcp_hsp_t	*hsp;
2503 	ire_t		*ire;
2504 	ire_t		*sire = NULL;
2505 	iulp_t		*ire_uinfo = NULL;
2506 	uint32_t	mss_max;
2507 	uint32_t	mss;
2508 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2509 	conn_t		*connp = tcp->tcp_connp;
2510 	boolean_t	ire_cacheable = B_FALSE;
2511 	zoneid_t	zoneid = connp->conn_zoneid;
2512 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2513 	    MATCH_IRE_SECATTR;
2514 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2515 	ill_t		*ill = NULL;
2516 	boolean_t	incoming = (ire_mp == NULL);
2517 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2518 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2519 
2520 	ASSERT(connp->conn_ire_cache == NULL);
2521 
2522 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2523 
2524 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2525 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2526 			return (0);
2527 		}
2528 		/*
2529 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2530 		 * for the destination with the nexthop as gateway.
2531 		 * ire_ctable_lookup() is used because this particular
2532 		 * ire, if it exists, will be marked private.
2533 		 * If that is not available, use the interface ire
2534 		 * for the nexthop.
2535 		 *
2536 		 * TSol: tcp_update_label will detect label mismatches based
2537 		 * only on the destination's label, but that would not
2538 		 * detect label mismatches based on the security attributes
2539 		 * of routes or next hop gateway. Hence we need to pass the
2540 		 * label to ire_ftable_lookup below in order to locate the
2541 		 * right prefix (and/or) ire cache. Similarly we also need
2542 		 * pass the label to the ire_cache_lookup below to locate
2543 		 * the right ire that also matches on the label.
2544 		 */
2545 		if (tcp->tcp_connp->conn_nexthop_set) {
2546 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2547 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2548 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2549 			    ipst);
2550 			if (ire == NULL) {
2551 				ire = ire_ftable_lookup(
2552 				    tcp->tcp_connp->conn_nexthop_v4,
2553 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2554 				    tsl, match_flags, ipst);
2555 				if (ire == NULL)
2556 					return (0);
2557 			} else {
2558 				ire_uinfo = &ire->ire_uinfo;
2559 			}
2560 		} else {
2561 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2562 			    zoneid, tsl, ipst);
2563 			if (ire != NULL) {
2564 				ire_cacheable = B_TRUE;
2565 				ire_uinfo = (ire_mp != NULL) ?
2566 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2567 				    &ire->ire_uinfo;
2568 
2569 			} else {
2570 				if (ire_mp == NULL) {
2571 					ire = ire_ftable_lookup(
2572 					    tcp->tcp_connp->conn_rem,
2573 					    0, 0, 0, NULL, &sire, zoneid, 0,
2574 					    tsl, (MATCH_IRE_RECURSIVE |
2575 					    MATCH_IRE_DEFAULT), ipst);
2576 					if (ire == NULL)
2577 						return (0);
2578 					ire_uinfo = (sire != NULL) ?
2579 					    &sire->ire_uinfo :
2580 					    &ire->ire_uinfo;
2581 				} else {
2582 					ire = (ire_t *)ire_mp->b_rptr;
2583 					ire_uinfo =
2584 					    &((ire_t *)
2585 					    ire_mp->b_rptr)->ire_uinfo;
2586 				}
2587 			}
2588 		}
2589 		ASSERT(ire != NULL);
2590 
2591 		if ((ire->ire_src_addr == INADDR_ANY) ||
2592 		    (ire->ire_type & IRE_BROADCAST)) {
2593 			/*
2594 			 * ire->ire_mp is non null when ire_mp passed in is used
2595 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2596 			 */
2597 			if (ire->ire_mp == NULL)
2598 				ire_refrele(ire);
2599 			if (sire != NULL)
2600 				ire_refrele(sire);
2601 			return (0);
2602 		}
2603 
2604 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2605 			ipaddr_t src_addr;
2606 
2607 			/*
2608 			 * ip_bind_connected() has stored the correct source
2609 			 * address in conn_src.
2610 			 */
2611 			src_addr = tcp->tcp_connp->conn_src;
2612 			tcp->tcp_ipha->ipha_src = src_addr;
2613 			/*
2614 			 * Copy of the src addr. in tcp_t is needed
2615 			 * for the lookup funcs.
2616 			 */
2617 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2618 		}
2619 		/*
2620 		 * Set the fragment bit so that IP will tell us if the MTU
2621 		 * should change. IP tells us the latest setting of
2622 		 * ip_path_mtu_discovery through ire_frag_flag.
2623 		 */
2624 		if (ipst->ips_ip_path_mtu_discovery) {
2625 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2626 			    htons(IPH_DF);
2627 		}
2628 		/*
2629 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2630 		 * for IP_NEXTHOP. No cache ire has been found for the
2631 		 * destination and we are working with the nexthop's
2632 		 * interface ire. Since we need to forward all packets
2633 		 * to the nexthop first, we "blindly" set tcp_localnet
2634 		 * to false, eventhough the destination may also be
2635 		 * onlink.
2636 		 */
2637 		if (ire_uinfo == NULL)
2638 			tcp->tcp_localnet = 0;
2639 		else
2640 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2641 	} else {
2642 		/*
2643 		 * For incoming connection ire_mp = NULL
2644 		 * For outgoing connection ire_mp != NULL
2645 		 * Technically we should check conn_incoming_ill
2646 		 * when ire_mp is NULL and conn_outgoing_ill when
2647 		 * ire_mp is non-NULL. But this is performance
2648 		 * critical path and for IPV*_BOUND_IF, outgoing
2649 		 * and incoming ill are always set to the same value.
2650 		 */
2651 		ill_t	*dst_ill = NULL;
2652 		ipif_t  *dst_ipif = NULL;
2653 
2654 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2655 
2656 		if (connp->conn_outgoing_ill != NULL) {
2657 			/* Outgoing or incoming path */
2658 			int   err;
2659 
2660 			dst_ill = conn_get_held_ill(connp,
2661 			    &connp->conn_outgoing_ill, &err);
2662 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2663 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2664 				return (0);
2665 			}
2666 			match_flags |= MATCH_IRE_ILL;
2667 			dst_ipif = dst_ill->ill_ipif;
2668 		}
2669 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2670 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2671 
2672 		if (ire != NULL) {
2673 			ire_cacheable = B_TRUE;
2674 			ire_uinfo = (ire_mp != NULL) ?
2675 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2676 			    &ire->ire_uinfo;
2677 		} else {
2678 			if (ire_mp == NULL) {
2679 				ire = ire_ftable_lookup_v6(
2680 				    &tcp->tcp_connp->conn_remv6,
2681 				    0, 0, 0, dst_ipif, &sire, zoneid,
2682 				    0, tsl, match_flags, ipst);
2683 				if (ire == NULL) {
2684 					if (dst_ill != NULL)
2685 						ill_refrele(dst_ill);
2686 					return (0);
2687 				}
2688 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2689 				    &ire->ire_uinfo;
2690 			} else {
2691 				ire = (ire_t *)ire_mp->b_rptr;
2692 				ire_uinfo =
2693 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2694 			}
2695 		}
2696 		if (dst_ill != NULL)
2697 			ill_refrele(dst_ill);
2698 
2699 		ASSERT(ire != NULL);
2700 		ASSERT(ire_uinfo != NULL);
2701 
2702 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2703 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2704 			/*
2705 			 * ire->ire_mp is non null when ire_mp passed in is used
2706 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2707 			 */
2708 			if (ire->ire_mp == NULL)
2709 				ire_refrele(ire);
2710 			if (sire != NULL)
2711 				ire_refrele(sire);
2712 			return (0);
2713 		}
2714 
2715 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2716 			in6_addr_t	src_addr;
2717 
2718 			/*
2719 			 * ip_bind_connected_v6() has stored the correct source
2720 			 * address per IPv6 addr. selection policy in
2721 			 * conn_src_v6.
2722 			 */
2723 			src_addr = tcp->tcp_connp->conn_srcv6;
2724 
2725 			tcp->tcp_ip6h->ip6_src = src_addr;
2726 			/*
2727 			 * Copy of the src addr. in tcp_t is needed
2728 			 * for the lookup funcs.
2729 			 */
2730 			tcp->tcp_ip_src_v6 = src_addr;
2731 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2732 			    &connp->conn_srcv6));
2733 		}
2734 		tcp->tcp_localnet =
2735 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2736 	}
2737 
2738 	/*
2739 	 * This allows applications to fail quickly when connections are made
2740 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2741 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2742 	 */
2743 	if ((ire->ire_flags & RTF_REJECT) &&
2744 	    (ire->ire_flags & RTF_PRIVATE))
2745 		goto error;
2746 
2747 	/*
2748 	 * Make use of the cached rtt and rtt_sd values to calculate the
2749 	 * initial RTO.  Note that they are already initialized in
2750 	 * tcp_init_values().
2751 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2752 	 * IP_NEXTHOP, but instead are using the interface ire for the
2753 	 * nexthop, then we do not use the ire_uinfo from that ire to
2754 	 * do any initializations.
2755 	 */
2756 	if (ire_uinfo != NULL) {
2757 		if (ire_uinfo->iulp_rtt != 0) {
2758 			clock_t	rto;
2759 
2760 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2761 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2762 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2763 			    tcps->tcps_rexmit_interval_extra +
2764 			    (tcp->tcp_rtt_sa >> 5);
2765 
2766 			if (rto > tcps->tcps_rexmit_interval_max) {
2767 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2768 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2769 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2770 			} else {
2771 				tcp->tcp_rto = rto;
2772 			}
2773 		}
2774 		if (ire_uinfo->iulp_ssthresh != 0)
2775 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2776 		else
2777 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2778 		if (ire_uinfo->iulp_spipe > 0) {
2779 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2780 			    tcps->tcps_max_buf);
2781 			if (tcps->tcps_snd_lowat_fraction != 0)
2782 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2783 				    tcps->tcps_snd_lowat_fraction;
2784 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2785 		}
2786 		/*
2787 		 * Note that up till now, acceptor always inherits receive
2788 		 * window from the listener.  But if there is a metrics
2789 		 * associated with a host, we should use that instead of
2790 		 * inheriting it from listener. Thus we need to pass this
2791 		 * info back to the caller.
2792 		 */
2793 		if (ire_uinfo->iulp_rpipe > 0) {
2794 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2795 			    tcps->tcps_max_buf);
2796 		}
2797 
2798 		if (ire_uinfo->iulp_rtomax > 0) {
2799 			tcp->tcp_second_timer_threshold =
2800 			    ire_uinfo->iulp_rtomax;
2801 		}
2802 
2803 		/*
2804 		 * Use the metric option settings, iulp_tstamp_ok and
2805 		 * iulp_wscale_ok, only for active open. What this means
2806 		 * is that if the other side uses timestamp or window
2807 		 * scale option, TCP will also use those options. That
2808 		 * is for passive open.  If the application sets a
2809 		 * large window, window scale is enabled regardless of
2810 		 * the value in iulp_wscale_ok.  This is the behavior
2811 		 * since 2.6.  So we keep it.
2812 		 * The only case left in passive open processing is the
2813 		 * check for SACK.
2814 		 * For ECN, it should probably be like SACK.  But the
2815 		 * current value is binary, so we treat it like the other
2816 		 * cases.  The metric only controls active open.For passive
2817 		 * open, the ndd param, tcp_ecn_permitted, controls the
2818 		 * behavior.
2819 		 */
2820 		if (!tcp_detached) {
2821 			/*
2822 			 * The if check means that the following can only
2823 			 * be turned on by the metrics only IRE, but not off.
2824 			 */
2825 			if (ire_uinfo->iulp_tstamp_ok)
2826 				tcp->tcp_snd_ts_ok = B_TRUE;
2827 			if (ire_uinfo->iulp_wscale_ok)
2828 				tcp->tcp_snd_ws_ok = B_TRUE;
2829 			if (ire_uinfo->iulp_sack == 2)
2830 				tcp->tcp_snd_sack_ok = B_TRUE;
2831 			if (ire_uinfo->iulp_ecn_ok)
2832 				tcp->tcp_ecn_ok = B_TRUE;
2833 		} else {
2834 			/*
2835 			 * Passive open.
2836 			 *
2837 			 * As above, the if check means that SACK can only be
2838 			 * turned on by the metric only IRE.
2839 			 */
2840 			if (ire_uinfo->iulp_sack > 0) {
2841 				tcp->tcp_snd_sack_ok = B_TRUE;
2842 			}
2843 		}
2844 	}
2845 
2846 
2847 	/*
2848 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2849 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2850 	 * length of all those options exceeds 28 bytes.  But because
2851 	 * of the tcp_mss_min check below, we may not have a problem if
2852 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2853 	 * the negative problem still exists.  And the check defeats PMTUd.
2854 	 * In fact, if PMTUd finds that the MSS should be smaller than
2855 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2856 	 * value.
2857 	 *
2858 	 * We do not deal with that now.  All those problems related to
2859 	 * PMTUd will be fixed later.
2860 	 */
2861 	ASSERT(ire->ire_max_frag != 0);
2862 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2863 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2864 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2865 			mss = MIN(mss, IPV6_MIN_MTU);
2866 		}
2867 	}
2868 
2869 	/* Sanity check for MSS value. */
2870 	if (tcp->tcp_ipversion == IPV4_VERSION)
2871 		mss_max = tcps->tcps_mss_max_ipv4;
2872 	else
2873 		mss_max = tcps->tcps_mss_max_ipv6;
2874 
2875 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2876 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2877 		/*
2878 		 * After receiving an ICMPv6 "packet too big" message with a
2879 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2880 		 * will insert a 8-byte fragment header in every packet; we
2881 		 * reduce the MSS by that amount here.
2882 		 */
2883 		mss -= sizeof (ip6_frag_t);
2884 	}
2885 
2886 	if (tcp->tcp_ipsec_overhead == 0)
2887 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2888 
2889 	mss -= tcp->tcp_ipsec_overhead;
2890 
2891 	if (mss < tcps->tcps_mss_min)
2892 		mss = tcps->tcps_mss_min;
2893 	if (mss > mss_max)
2894 		mss = mss_max;
2895 
2896 	/* Note that this is the maximum MSS, excluding all options. */
2897 	tcp->tcp_mss = mss;
2898 
2899 	/*
2900 	 * Initialize the ISS here now that we have the full connection ID.
2901 	 * The RFC 1948 method of initial sequence number generation requires
2902 	 * knowledge of the full connection ID before setting the ISS.
2903 	 */
2904 
2905 	tcp_iss_init(tcp);
2906 
2907 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2908 		tcp->tcp_loopback = B_TRUE;
2909 
2910 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2911 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2912 	} else {
2913 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2914 	}
2915 
2916 	if (hsp != NULL) {
2917 		/* Only modify if we're going to make them bigger */
2918 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2919 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2920 			if (tcps->tcps_snd_lowat_fraction != 0)
2921 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2922 				    tcps->tcps_snd_lowat_fraction;
2923 		}
2924 
2925 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2926 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2927 		}
2928 
2929 		/* Copy timestamp flag only for active open */
2930 		if (!tcp_detached)
2931 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2932 	}
2933 
2934 	if (sire != NULL)
2935 		IRE_REFRELE(sire);
2936 
2937 	/*
2938 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2939 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2940 	 */
2941 	if (tcp->tcp_loopback ||
2942 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2943 		/*
2944 		 * For incoming, see if this tcp may be MDT-capable.  For
2945 		 * outgoing, this process has been taken care of through
2946 		 * tcp_rput_other.
2947 		 */
2948 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2949 		tcp->tcp_ire_ill_check_done = B_TRUE;
2950 	}
2951 
2952 	mutex_enter(&connp->conn_lock);
2953 	/*
2954 	 * Make sure that conn is not marked incipient
2955 	 * for incoming connections. A blind
2956 	 * removal of incipient flag is cheaper than
2957 	 * check and removal.
2958 	 */
2959 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2960 
2961 	/*
2962 	 * Must not cache forwarding table routes
2963 	 * or recache an IRE after the conn_t has
2964 	 * had conn_ire_cache cleared and is flagged
2965 	 * unusable, (see the CONN_CACHE_IRE() macro).
2966 	 */
2967 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2968 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2969 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2970 			connp->conn_ire_cache = ire;
2971 			IRE_UNTRACE_REF(ire);
2972 			rw_exit(&ire->ire_bucket->irb_lock);
2973 			mutex_exit(&connp->conn_lock);
2974 			return (1);
2975 		}
2976 		rw_exit(&ire->ire_bucket->irb_lock);
2977 	}
2978 	mutex_exit(&connp->conn_lock);
2979 
2980 	if (ire->ire_mp == NULL)
2981 		ire_refrele(ire);
2982 	return (1);
2983 
2984 error:
2985 	if (ire->ire_mp == NULL)
2986 		ire_refrele(ire);
2987 	if (sire != NULL)
2988 		ire_refrele(sire);
2989 	return (0);
2990 }
2991 
2992 /*
2993  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
2994  * O_T_BIND_REQ/T_BIND_REQ message.
2995  */
2996 static void
2997 tcp_bind(tcp_t *tcp, mblk_t *mp)
2998 {
2999 	sin_t	*sin;
3000 	sin6_t	*sin6;
3001 	mblk_t	*mp1;
3002 	in_port_t requested_port;
3003 	in_port_t allocated_port;
3004 	struct T_bind_req *tbr;
3005 	boolean_t	bind_to_req_port_only;
3006 	boolean_t	backlog_update = B_FALSE;
3007 	boolean_t	user_specified;
3008 	in6_addr_t	v6addr;
3009 	ipaddr_t	v4addr;
3010 	uint_t	origipversion;
3011 	int	err;
3012 	queue_t *q = tcp->tcp_wq;
3013 	conn_t	*connp = tcp->tcp_connp;
3014 	mlp_type_t addrtype, mlptype;
3015 	zone_t	*zone;
3016 	cred_t	*cr;
3017 	in_port_t mlp_port;
3018 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3019 
3020 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3021 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3022 		if (tcp->tcp_debug) {
3023 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3024 			    "tcp_bind: bad req, len %u",
3025 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3026 		}
3027 		tcp_err_ack(tcp, mp, TPROTO, 0);
3028 		return;
3029 	}
3030 	/* Make sure the largest address fits */
3031 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3032 	if (mp1 == NULL) {
3033 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3034 		return;
3035 	}
3036 	mp = mp1;
3037 	tbr = (struct T_bind_req *)mp->b_rptr;
3038 	if (tcp->tcp_state >= TCPS_BOUND) {
3039 		if ((tcp->tcp_state == TCPS_BOUND ||
3040 		    tcp->tcp_state == TCPS_LISTEN) &&
3041 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3042 		    tbr->CONIND_number > 0) {
3043 			/*
3044 			 * Handle listen() increasing CONIND_number.
3045 			 * This is more "liberal" then what the TPI spec
3046 			 * requires but is needed to avoid a t_unbind
3047 			 * when handling listen() since the port number
3048 			 * might be "stolen" between the unbind and bind.
3049 			 */
3050 			backlog_update = B_TRUE;
3051 			goto do_bind;
3052 		}
3053 		if (tcp->tcp_debug) {
3054 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3055 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3056 		}
3057 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3058 		return;
3059 	}
3060 	origipversion = tcp->tcp_ipversion;
3061 
3062 	switch (tbr->ADDR_length) {
3063 	case 0:			/* request for a generic port */
3064 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3065 		if (tcp->tcp_family == AF_INET) {
3066 			tbr->ADDR_length = sizeof (sin_t);
3067 			sin = (sin_t *)&tbr[1];
3068 			*sin = sin_null;
3069 			sin->sin_family = AF_INET;
3070 			mp->b_wptr = (uchar_t *)&sin[1];
3071 			tcp->tcp_ipversion = IPV4_VERSION;
3072 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3073 		} else {
3074 			ASSERT(tcp->tcp_family == AF_INET6);
3075 			tbr->ADDR_length = sizeof (sin6_t);
3076 			sin6 = (sin6_t *)&tbr[1];
3077 			*sin6 = sin6_null;
3078 			sin6->sin6_family = AF_INET6;
3079 			mp->b_wptr = (uchar_t *)&sin6[1];
3080 			tcp->tcp_ipversion = IPV6_VERSION;
3081 			V6_SET_ZERO(v6addr);
3082 		}
3083 		requested_port = 0;
3084 		break;
3085 
3086 	case sizeof (sin_t):	/* Complete IPv4 address */
3087 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3088 		    sizeof (sin_t));
3089 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3090 			if (tcp->tcp_debug) {
3091 				(void) strlog(TCP_MOD_ID, 0, 1,
3092 				    SL_ERROR|SL_TRACE,
3093 				    "tcp_bind: bad address parameter, "
3094 				    "offset %d, len %d",
3095 				    tbr->ADDR_offset, tbr->ADDR_length);
3096 			}
3097 			tcp_err_ack(tcp, mp, TPROTO, 0);
3098 			return;
3099 		}
3100 		/*
3101 		 * With sockets sockfs will accept bogus sin_family in
3102 		 * bind() and replace it with the family used in the socket
3103 		 * call.
3104 		 */
3105 		if (sin->sin_family != AF_INET ||
3106 		    tcp->tcp_family != AF_INET) {
3107 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3108 			return;
3109 		}
3110 		requested_port = ntohs(sin->sin_port);
3111 		tcp->tcp_ipversion = IPV4_VERSION;
3112 		v4addr = sin->sin_addr.s_addr;
3113 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3114 		break;
3115 
3116 	case sizeof (sin6_t): /* Complete IPv6 address */
3117 		sin6 = (sin6_t *)mi_offset_param(mp,
3118 		    tbr->ADDR_offset, sizeof (sin6_t));
3119 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3120 			if (tcp->tcp_debug) {
3121 				(void) strlog(TCP_MOD_ID, 0, 1,
3122 				    SL_ERROR|SL_TRACE,
3123 				    "tcp_bind: bad IPv6 address parameter, "
3124 				    "offset %d, len %d", tbr->ADDR_offset,
3125 				    tbr->ADDR_length);
3126 			}
3127 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3128 			return;
3129 		}
3130 		if (sin6->sin6_family != AF_INET6 ||
3131 		    tcp->tcp_family != AF_INET6) {
3132 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3133 			return;
3134 		}
3135 		requested_port = ntohs(sin6->sin6_port);
3136 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3137 		    IPV4_VERSION : IPV6_VERSION;
3138 		v6addr = sin6->sin6_addr;
3139 		break;
3140 
3141 	default:
3142 		if (tcp->tcp_debug) {
3143 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3144 			    "tcp_bind: bad address length, %d",
3145 			    tbr->ADDR_length);
3146 		}
3147 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3148 		return;
3149 	}
3150 	tcp->tcp_bound_source_v6 = v6addr;
3151 
3152 	/* Check for change in ipversion */
3153 	if (origipversion != tcp->tcp_ipversion) {
3154 		ASSERT(tcp->tcp_family == AF_INET6);
3155 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3156 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3157 		if (err) {
3158 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3159 			return;
3160 		}
3161 	}
3162 
3163 	/*
3164 	 * Initialize family specific fields. Copy of the src addr.
3165 	 * in tcp_t is needed for the lookup funcs.
3166 	 */
3167 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3168 		tcp->tcp_ip6h->ip6_src = v6addr;
3169 	} else {
3170 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3171 	}
3172 	tcp->tcp_ip_src_v6 = v6addr;
3173 
3174 	/*
3175 	 * For O_T_BIND_REQ:
3176 	 * Verify that the target port/addr is available, or choose
3177 	 * another.
3178 	 * For  T_BIND_REQ:
3179 	 * Verify that the target port/addr is available or fail.
3180 	 * In both cases when it succeeds the tcp is inserted in the
3181 	 * bind hash table. This ensures that the operation is atomic
3182 	 * under the lock on the hash bucket.
3183 	 */
3184 	bind_to_req_port_only = requested_port != 0 &&
3185 	    tbr->PRIM_type != O_T_BIND_REQ;
3186 	/*
3187 	 * Get a valid port (within the anonymous range and should not
3188 	 * be a privileged one) to use if the user has not given a port.
3189 	 * If multiple threads are here, they may all start with
3190 	 * with the same initial port. But, it should be fine as long as
3191 	 * tcp_bindi will ensure that no two threads will be assigned
3192 	 * the same port.
3193 	 *
3194 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3195 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3196 	 * unless TCP_ANONPRIVBIND option is set.
3197 	 */
3198 	mlptype = mlptSingle;
3199 	mlp_port = requested_port;
3200 	if (requested_port == 0) {
3201 		requested_port = tcp->tcp_anon_priv_bind ?
3202 		    tcp_get_next_priv_port(tcp) :
3203 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
3204 		    tcp, B_TRUE);
3205 		if (requested_port == 0) {
3206 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3207 			return;
3208 		}
3209 		user_specified = B_FALSE;
3210 
3211 		/*
3212 		 * If the user went through one of the RPC interfaces to create
3213 		 * this socket and RPC is MLP in this zone, then give him an
3214 		 * anonymous MLP.
3215 		 */
3216 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3217 		if (connp->conn_anon_mlp && is_system_labeled()) {
3218 			zone = crgetzone(cr);
3219 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3220 			    IPV6_VERSION, &v6addr,
3221 			    tcps->tcps_netstack->netstack_ip);
3222 			if (addrtype == mlptSingle) {
3223 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3224 				return;
3225 			}
3226 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3227 			    PMAPPORT, addrtype);
3228 			mlp_port = PMAPPORT;
3229 		}
3230 	} else {
3231 		int i;
3232 		boolean_t priv = B_FALSE;
3233 
3234 		/*
3235 		 * If the requested_port is in the well-known privileged range,
3236 		 * verify that the stream was opened by a privileged user.
3237 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3238 		 * but instead the code relies on:
3239 		 * - the fact that the address of the array and its size never
3240 		 *   changes
3241 		 * - the atomic assignment of the elements of the array
3242 		 */
3243 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3244 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
3245 			priv = B_TRUE;
3246 		} else {
3247 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
3248 				if (requested_port ==
3249 				    tcps->tcps_g_epriv_ports[i]) {
3250 					priv = B_TRUE;
3251 					break;
3252 				}
3253 			}
3254 		}
3255 		if (priv) {
3256 			if (secpolicy_net_privaddr(cr, requested_port,
3257 			    IPPROTO_TCP) != 0) {
3258 				if (tcp->tcp_debug) {
3259 					(void) strlog(TCP_MOD_ID, 0, 1,
3260 					    SL_ERROR|SL_TRACE,
3261 					    "tcp_bind: no priv for port %d",
3262 					    requested_port);
3263 				}
3264 				tcp_err_ack(tcp, mp, TACCES, 0);
3265 				return;
3266 			}
3267 		}
3268 		user_specified = B_TRUE;
3269 
3270 		if (is_system_labeled()) {
3271 			zone = crgetzone(cr);
3272 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3273 			    IPV6_VERSION, &v6addr,
3274 			    tcps->tcps_netstack->netstack_ip);
3275 			if (addrtype == mlptSingle) {
3276 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3277 				return;
3278 			}
3279 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3280 			    requested_port, addrtype);
3281 		}
3282 	}
3283 
3284 	if (mlptype != mlptSingle) {
3285 		if (secpolicy_net_bindmlp(cr) != 0) {
3286 			if (tcp->tcp_debug) {
3287 				(void) strlog(TCP_MOD_ID, 0, 1,
3288 				    SL_ERROR|SL_TRACE,
3289 				    "tcp_bind: no priv for multilevel port %d",
3290 				    requested_port);
3291 			}
3292 			tcp_err_ack(tcp, mp, TACCES, 0);
3293 			return;
3294 		}
3295 
3296 		/*
3297 		 * If we're specifically binding a shared IP address and the
3298 		 * port is MLP on shared addresses, then check to see if this
3299 		 * zone actually owns the MLP.  Reject if not.
3300 		 */
3301 		if (mlptype == mlptShared && addrtype == mlptShared) {
3302 			/*
3303 			 * No need to handle exclusive-stack zones since
3304 			 * ALL_ZONES only applies to the shared stack.
3305 			 */
3306 			zoneid_t mlpzone;
3307 
3308 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3309 			    htons(mlp_port));
3310 			if (connp->conn_zoneid != mlpzone) {
3311 				if (tcp->tcp_debug) {
3312 					(void) strlog(TCP_MOD_ID, 0, 1,
3313 					    SL_ERROR|SL_TRACE,
3314 					    "tcp_bind: attempt to bind port "
3315 					    "%d on shared addr in zone %d "
3316 					    "(should be %d)",
3317 					    mlp_port, connp->conn_zoneid,
3318 					    mlpzone);
3319 				}
3320 				tcp_err_ack(tcp, mp, TACCES, 0);
3321 				return;
3322 			}
3323 		}
3324 
3325 		if (!user_specified) {
3326 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3327 			    requested_port, B_TRUE);
3328 			if (err != 0) {
3329 				if (tcp->tcp_debug) {
3330 					(void) strlog(TCP_MOD_ID, 0, 1,
3331 					    SL_ERROR|SL_TRACE,
3332 					    "tcp_bind: cannot establish anon "
3333 					    "MLP for port %d",
3334 					    requested_port);
3335 				}
3336 				tcp_err_ack(tcp, mp, TSYSERR, err);
3337 				return;
3338 			}
3339 			connp->conn_anon_port = B_TRUE;
3340 		}
3341 		connp->conn_mlp_type = mlptype;
3342 	}
3343 
3344 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3345 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3346 
3347 	if (allocated_port == 0) {
3348 		connp->conn_mlp_type = mlptSingle;
3349 		if (connp->conn_anon_port) {
3350 			connp->conn_anon_port = B_FALSE;
3351 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3352 			    requested_port, B_FALSE);
3353 		}
3354 		if (bind_to_req_port_only) {
3355 			if (tcp->tcp_debug) {
3356 				(void) strlog(TCP_MOD_ID, 0, 1,
3357 				    SL_ERROR|SL_TRACE,
3358 				    "tcp_bind: requested addr busy");
3359 			}
3360 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3361 		} else {
3362 			/* If we are out of ports, fail the bind. */
3363 			if (tcp->tcp_debug) {
3364 				(void) strlog(TCP_MOD_ID, 0, 1,
3365 				    SL_ERROR|SL_TRACE,
3366 				    "tcp_bind: out of ports?");
3367 			}
3368 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3369 		}
3370 		return;
3371 	}
3372 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3373 do_bind:
3374 	if (!backlog_update) {
3375 		if (tcp->tcp_family == AF_INET)
3376 			sin->sin_port = htons(allocated_port);
3377 		else
3378 			sin6->sin6_port = htons(allocated_port);
3379 	}
3380 	if (tcp->tcp_family == AF_INET) {
3381 		if (tbr->CONIND_number != 0) {
3382 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3383 			    sizeof (sin_t));
3384 		} else {
3385 			/* Just verify the local IP address */
3386 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3387 		}
3388 	} else {
3389 		if (tbr->CONIND_number != 0) {
3390 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3391 			    sizeof (sin6_t));
3392 		} else {
3393 			/* Just verify the local IP address */
3394 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3395 			    IPV6_ADDR_LEN);
3396 		}
3397 	}
3398 	if (mp1 == NULL) {
3399 		if (connp->conn_anon_port) {
3400 			connp->conn_anon_port = B_FALSE;
3401 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3402 			    requested_port, B_FALSE);
3403 		}
3404 		connp->conn_mlp_type = mlptSingle;
3405 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3406 		return;
3407 	}
3408 
3409 	tbr->PRIM_type = T_BIND_ACK;
3410 	mp->b_datap->db_type = M_PCPROTO;
3411 
3412 	/* Chain in the reply mp for tcp_rput() */
3413 	mp1->b_cont = mp;
3414 	mp = mp1;
3415 
3416 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3417 	if (tcp->tcp_conn_req_max) {
3418 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
3419 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
3420 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
3421 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
3422 		/*
3423 		 * If this is a listener, do not reset the eager list
3424 		 * and other stuffs.  Note that we don't check if the
3425 		 * existing eager list meets the new tcp_conn_req_max
3426 		 * requirement.
3427 		 */
3428 		if (tcp->tcp_state != TCPS_LISTEN) {
3429 			tcp->tcp_state = TCPS_LISTEN;
3430 			/* Initialize the chain. Don't need the eager_lock */
3431 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3432 			tcp->tcp_eager_next_drop_q0 = tcp;
3433 			tcp->tcp_eager_prev_drop_q0 = tcp;
3434 			tcp->tcp_second_ctimer_threshold =
3435 			    tcps->tcps_ip_abort_linterval;
3436 		}
3437 	}
3438 
3439 	/*
3440 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3441 	 * processing continues in tcp_rput_other().
3442 	 *
3443 	 * We need to make sure that the conn_recv is set to a non-null
3444 	 * value before we insert the conn into the classifier table.
3445 	 * This is to avoid a race with an incoming packet which does an
3446 	 * ipcl_classify().
3447 	 */
3448 	connp->conn_recv = tcp_conn_request;
3449 	if (tcp->tcp_family == AF_INET6) {
3450 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3451 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3452 	} else {
3453 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3454 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3455 	}
3456 	/*
3457 	 * If the bind cannot complete immediately
3458 	 * IP will arrange to call tcp_rput_other
3459 	 * when the bind completes.
3460 	 */
3461 	if (mp != NULL) {
3462 		tcp_rput_other(tcp, mp);
3463 	} else {
3464 		/*
3465 		 * Bind will be resumed later. Need to ensure
3466 		 * that conn doesn't disappear when that happens.
3467 		 * This will be decremented in ip_resume_tcp_bind().
3468 		 */
3469 		CONN_INC_REF(tcp->tcp_connp);
3470 	}
3471 }
3472 
3473 
3474 /*
3475  * If the "bind_to_req_port_only" parameter is set, if the requested port
3476  * number is available, return it, If not return 0
3477  *
3478  * If "bind_to_req_port_only" parameter is not set and
3479  * If the requested port number is available, return it.  If not, return
3480  * the first anonymous port we happen across.  If no anonymous ports are
3481  * available, return 0. addr is the requested local address, if any.
3482  *
3483  * In either case, when succeeding update the tcp_t to record the port number
3484  * and insert it in the bind hash table.
3485  *
3486  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3487  * without setting SO_REUSEADDR. This is needed so that they
3488  * can be viewed as two independent transport protocols.
3489  */
3490 static in_port_t
3491 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3492     int reuseaddr, boolean_t quick_connect,
3493     boolean_t bind_to_req_port_only, boolean_t user_specified)
3494 {
3495 	/* number of times we have run around the loop */
3496 	int count = 0;
3497 	/* maximum number of times to run around the loop */
3498 	int loopmax;
3499 	conn_t *connp = tcp->tcp_connp;
3500 	zoneid_t zoneid = connp->conn_zoneid;
3501 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3502 
3503 	/*
3504 	 * Lookup for free addresses is done in a loop and "loopmax"
3505 	 * influences how long we spin in the loop
3506 	 */
3507 	if (bind_to_req_port_only) {
3508 		/*
3509 		 * If the requested port is busy, don't bother to look
3510 		 * for a new one. Setting loop maximum count to 1 has
3511 		 * that effect.
3512 		 */
3513 		loopmax = 1;
3514 	} else {
3515 		/*
3516 		 * If the requested port is busy, look for a free one
3517 		 * in the anonymous port range.
3518 		 * Set loopmax appropriately so that one does not look
3519 		 * forever in the case all of the anonymous ports are in use.
3520 		 */
3521 		if (tcp->tcp_anon_priv_bind) {
3522 			/*
3523 			 * loopmax =
3524 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3525 			 */
3526 			loopmax = IPPORT_RESERVED -
3527 			    tcps->tcps_min_anonpriv_port;
3528 		} else {
3529 			loopmax = (tcps->tcps_largest_anon_port -
3530 			    tcps->tcps_smallest_anon_port + 1);
3531 		}
3532 	}
3533 	do {
3534 		uint16_t	lport;
3535 		tf_t		*tbf;
3536 		tcp_t		*ltcp;
3537 		conn_t		*lconnp;
3538 
3539 		lport = htons(port);
3540 
3541 		/*
3542 		 * Ensure that the tcp_t is not currently in the bind hash.
3543 		 * Hold the lock on the hash bucket to ensure that
3544 		 * the duplicate check plus the insertion is an atomic
3545 		 * operation.
3546 		 *
3547 		 * This function does an inline lookup on the bind hash list
3548 		 * Make sure that we access only members of tcp_t
3549 		 * and that we don't look at tcp_tcp, since we are not
3550 		 * doing a CONN_INC_REF.
3551 		 */
3552 		tcp_bind_hash_remove(tcp);
3553 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3554 		mutex_enter(&tbf->tf_lock);
3555 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3556 		    ltcp = ltcp->tcp_bind_hash) {
3557 			boolean_t not_socket;
3558 			boolean_t exclbind;
3559 
3560 			if (lport != ltcp->tcp_lport)
3561 				continue;
3562 
3563 			lconnp = ltcp->tcp_connp;
3564 
3565 			/*
3566 			 * On a labeled system, we must treat bindings to ports
3567 			 * on shared IP addresses by sockets with MAC exemption
3568 			 * privilege as being in all zones, as there's
3569 			 * otherwise no way to identify the right receiver.
3570 			 */
3571 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3572 			    IPCL_ZONE_MATCH(connp,
3573 			    ltcp->tcp_connp->conn_zoneid)) &&
3574 			    !lconnp->conn_mac_exempt &&
3575 			    !connp->conn_mac_exempt)
3576 				continue;
3577 
3578 			/*
3579 			 * If TCP_EXCLBIND is set for either the bound or
3580 			 * binding endpoint, the semantics of bind
3581 			 * is changed according to the following.
3582 			 *
3583 			 * spec = specified address (v4 or v6)
3584 			 * unspec = unspecified address (v4 or v6)
3585 			 * A = specified addresses are different for endpoints
3586 			 *
3587 			 * bound	bind to		allowed
3588 			 * -------------------------------------
3589 			 * unspec	unspec		no
3590 			 * unspec	spec		no
3591 			 * spec		unspec		no
3592 			 * spec		spec		yes if A
3593 			 *
3594 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3595 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3596 			 *
3597 			 * Note:
3598 			 *
3599 			 * 1. Because of TLI semantics, an endpoint can go
3600 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3601 			 * TCPS_BOUND, depending on whether it is originally
3602 			 * a listener or not.  That is why we need to check
3603 			 * for states greater than or equal to TCPS_BOUND
3604 			 * here.
3605 			 *
3606 			 * 2. Ideally, we should only check for state equals
3607 			 * to TCPS_LISTEN. And the following check should be
3608 			 * added.
3609 			 *
3610 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3611 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3612 			 *		...
3613 			 * }
3614 			 *
3615 			 * The semantics will be changed to this.  If the
3616 			 * endpoint on the list is in state not equal to
3617 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3618 			 * set, let the bind succeed.
3619 			 *
3620 			 * Because of (1), we cannot do that for TLI
3621 			 * endpoints.  But we can do that for socket endpoints.
3622 			 * If in future, we can change this going back
3623 			 * semantics, we can use the above check for TLI also.
3624 			 */
3625 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3626 			    TCP_IS_SOCKET(tcp));
3627 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3628 
3629 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3630 			    (exclbind && (not_socket ||
3631 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3632 				if (V6_OR_V4_INADDR_ANY(
3633 				    ltcp->tcp_bound_source_v6) ||
3634 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3635 				    IN6_ARE_ADDR_EQUAL(laddr,
3636 				    &ltcp->tcp_bound_source_v6)) {
3637 					break;
3638 				}
3639 				continue;
3640 			}
3641 
3642 			/*
3643 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3644 			 * have disjoint port number spaces, if *_EXCLBIND
3645 			 * is not set and only if the application binds to a
3646 			 * specific port. We use the same autoassigned port
3647 			 * number space for IPv4 and IPv6 sockets.
3648 			 */
3649 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3650 			    bind_to_req_port_only)
3651 				continue;
3652 
3653 			/*
3654 			 * Ideally, we should make sure that the source
3655 			 * address, remote address, and remote port in the
3656 			 * four tuple for this tcp-connection is unique.
3657 			 * However, trying to find out the local source
3658 			 * address would require too much code duplication
3659 			 * with IP, since IP needs needs to have that code
3660 			 * to support userland TCP implementations.
3661 			 */
3662 			if (quick_connect &&
3663 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3664 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3665 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3666 			    &ltcp->tcp_remote_v6)))
3667 				continue;
3668 
3669 			if (!reuseaddr) {
3670 				/*
3671 				 * No socket option SO_REUSEADDR.
3672 				 * If existing port is bound to
3673 				 * a non-wildcard IP address
3674 				 * and the requesting stream is
3675 				 * bound to a distinct
3676 				 * different IP addresses
3677 				 * (non-wildcard, also), keep
3678 				 * going.
3679 				 */
3680 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3681 				    !V6_OR_V4_INADDR_ANY(
3682 				    ltcp->tcp_bound_source_v6) &&
3683 				    !IN6_ARE_ADDR_EQUAL(laddr,
3684 				    &ltcp->tcp_bound_source_v6))
3685 					continue;
3686 				if (ltcp->tcp_state >= TCPS_BOUND) {
3687 					/*
3688 					 * This port is being used and
3689 					 * its state is >= TCPS_BOUND,
3690 					 * so we can't bind to it.
3691 					 */
3692 					break;
3693 				}
3694 			} else {
3695 				/*
3696 				 * socket option SO_REUSEADDR is set on the
3697 				 * binding tcp_t.
3698 				 *
3699 				 * If two streams are bound to
3700 				 * same IP address or both addr
3701 				 * and bound source are wildcards
3702 				 * (INADDR_ANY), we want to stop
3703 				 * searching.
3704 				 * We have found a match of IP source
3705 				 * address and source port, which is
3706 				 * refused regardless of the
3707 				 * SO_REUSEADDR setting, so we break.
3708 				 */
3709 				if (IN6_ARE_ADDR_EQUAL(laddr,
3710 				    &ltcp->tcp_bound_source_v6) &&
3711 				    (ltcp->tcp_state == TCPS_LISTEN ||
3712 				    ltcp->tcp_state == TCPS_BOUND))
3713 					break;
3714 			}
3715 		}
3716 		if (ltcp != NULL) {
3717 			/* The port number is busy */
3718 			mutex_exit(&tbf->tf_lock);
3719 		} else {
3720 			/*
3721 			 * This port is ours. Insert in fanout and mark as
3722 			 * bound to prevent others from getting the port
3723 			 * number.
3724 			 */
3725 			tcp->tcp_state = TCPS_BOUND;
3726 			tcp->tcp_lport = htons(port);
3727 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3728 
3729 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3730 			    tcp->tcp_lport)] == tbf);
3731 			tcp_bind_hash_insert(tbf, tcp, 1);
3732 
3733 			mutex_exit(&tbf->tf_lock);
3734 
3735 			/*
3736 			 * We don't want tcp_next_port_to_try to "inherit"
3737 			 * a port number supplied by the user in a bind.
3738 			 */
3739 			if (user_specified)
3740 				return (port);
3741 
3742 			/*
3743 			 * This is the only place where tcp_next_port_to_try
3744 			 * is updated. After the update, it may or may not
3745 			 * be in the valid range.
3746 			 */
3747 			if (!tcp->tcp_anon_priv_bind)
3748 				tcps->tcps_next_port_to_try = port + 1;
3749 			return (port);
3750 		}
3751 
3752 		if (tcp->tcp_anon_priv_bind) {
3753 			port = tcp_get_next_priv_port(tcp);
3754 		} else {
3755 			if (count == 0 && user_specified) {
3756 				/*
3757 				 * We may have to return an anonymous port. So
3758 				 * get one to start with.
3759 				 */
3760 				port =
3761 				    tcp_update_next_port(
3762 				    tcps->tcps_next_port_to_try,
3763 				    tcp, B_TRUE);
3764 				user_specified = B_FALSE;
3765 			} else {
3766 				port = tcp_update_next_port(port + 1, tcp,
3767 				    B_FALSE);
3768 			}
3769 		}
3770 		if (port == 0)
3771 			break;
3772 
3773 		/*
3774 		 * Don't let this loop run forever in the case where
3775 		 * all of the anonymous ports are in use.
3776 		 */
3777 	} while (++count < loopmax);
3778 	return (0);
3779 }
3780 
3781 /*
3782  * tcp_clean_death / tcp_close_detached must not be called more than once
3783  * on a tcp. Thus every function that potentially calls tcp_clean_death
3784  * must check for the tcp state before calling tcp_clean_death.
3785  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3786  * tcp_timer_handler, all check for the tcp state.
3787  */
3788 /* ARGSUSED */
3789 void
3790 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3791 {
3792 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3793 
3794 	freemsg(mp);
3795 	if (tcp->tcp_state > TCPS_BOUND)
3796 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3797 		    ETIMEDOUT, 5);
3798 }
3799 
3800 /*
3801  * We are dying for some reason.  Try to do it gracefully.  (May be called
3802  * as writer.)
3803  *
3804  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3805  * done by a service procedure).
3806  * TBD - Should the return value distinguish between the tcp_t being
3807  * freed and it being reinitialized?
3808  */
3809 static int
3810 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3811 {
3812 	mblk_t	*mp;
3813 	queue_t	*q;
3814 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3815 	sodirect_t	*sodp;
3816 
3817 	TCP_CLD_STAT(tag);
3818 
3819 #if TCP_TAG_CLEAN_DEATH
3820 	tcp->tcp_cleandeathtag = tag;
3821 #endif
3822 
3823 	if (tcp->tcp_fused)
3824 		tcp_unfuse(tcp);
3825 
3826 	if (tcp->tcp_linger_tid != 0 &&
3827 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3828 		tcp_stop_lingering(tcp);
3829 	}
3830 
3831 	ASSERT(tcp != NULL);
3832 	ASSERT((tcp->tcp_family == AF_INET &&
3833 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3834 	    (tcp->tcp_family == AF_INET6 &&
3835 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3836 	    tcp->tcp_ipversion == IPV6_VERSION)));
3837 
3838 	if (TCP_IS_DETACHED(tcp)) {
3839 		if (tcp->tcp_hard_binding) {
3840 			/*
3841 			 * Its an eager that we are dealing with. We close the
3842 			 * eager but in case a conn_ind has already gone to the
3843 			 * listener, let tcp_accept_finish() send a discon_ind
3844 			 * to the listener and drop the last reference. If the
3845 			 * listener doesn't even know about the eager i.e. the
3846 			 * conn_ind hasn't gone up, blow away the eager and drop
3847 			 * the last reference as well. If the conn_ind has gone
3848 			 * up, state should be BOUND. tcp_accept_finish
3849 			 * will figure out that the connection has received a
3850 			 * RST and will send a DISCON_IND to the application.
3851 			 */
3852 			tcp_closei_local(tcp);
3853 			if (!tcp->tcp_tconnind_started) {
3854 				CONN_DEC_REF(tcp->tcp_connp);
3855 			} else {
3856 				tcp->tcp_state = TCPS_BOUND;
3857 			}
3858 		} else {
3859 			tcp_close_detached(tcp);
3860 		}
3861 		return (0);
3862 	}
3863 
3864 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3865 
3866 	/*
3867 	 * If T_ORDREL_IND has not been sent yet (done when service routine
3868 	 * is run) postpone cleaning up the endpoint until service routine
3869 	 * has sent up the T_ORDREL_IND. Avoid clearing out an existing
3870 	 * client_errno since tcp_close uses the client_errno field.
3871 	 */
3872 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
3873 		if (err != 0)
3874 			tcp->tcp_client_errno = err;
3875 
3876 		tcp->tcp_deferred_clean_death = B_TRUE;
3877 		return (-1);
3878 	}
3879 
3880 	/* If sodirect, not anymore */
3881 	SOD_PTR_ENTER(tcp, sodp);
3882 	if (sodp != NULL) {
3883 		tcp->tcp_sodirect = NULL;
3884 		mutex_exit(sodp->sod_lockp);
3885 	}
3886 
3887 	q = tcp->tcp_rq;
3888 
3889 	/* Trash all inbound data */
3890 	flushq(q, FLUSHALL);
3891 
3892 	/*
3893 	 * If we are at least part way open and there is error
3894 	 * (err==0 implies no error)
3895 	 * notify our client by a T_DISCON_IND.
3896 	 */
3897 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3898 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3899 		    !TCP_IS_SOCKET(tcp)) {
3900 			/*
3901 			 * Send M_FLUSH according to TPI. Because sockets will
3902 			 * (and must) ignore FLUSHR we do that only for TPI
3903 			 * endpoints and sockets in STREAMS mode.
3904 			 */
3905 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3906 		}
3907 		if (tcp->tcp_debug) {
3908 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3909 			    "tcp_clean_death: discon err %d", err);
3910 		}
3911 		mp = mi_tpi_discon_ind(NULL, err, 0);
3912 		if (mp != NULL) {
3913 			putnext(q, mp);
3914 		} else {
3915 			if (tcp->tcp_debug) {
3916 				(void) strlog(TCP_MOD_ID, 0, 1,
3917 				    SL_ERROR|SL_TRACE,
3918 				    "tcp_clean_death, sending M_ERROR");
3919 			}
3920 			(void) putnextctl1(q, M_ERROR, EPROTO);
3921 		}
3922 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3923 			/* SYN_SENT or SYN_RCVD */
3924 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3925 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3926 			/* ESTABLISHED or CLOSE_WAIT */
3927 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3928 		}
3929 	}
3930 
3931 	tcp_reinit(tcp);
3932 	return (-1);
3933 }
3934 
3935 /*
3936  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3937  * to expire, stop the wait and finish the close.
3938  */
3939 static void
3940 tcp_stop_lingering(tcp_t *tcp)
3941 {
3942 	clock_t	delta = 0;
3943 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3944 
3945 	tcp->tcp_linger_tid = 0;
3946 	if (tcp->tcp_state > TCPS_LISTEN) {
3947 		tcp_acceptor_hash_remove(tcp);
3948 		mutex_enter(&tcp->tcp_non_sq_lock);
3949 		if (tcp->tcp_flow_stopped) {
3950 			tcp_clrqfull(tcp);
3951 		}
3952 		mutex_exit(&tcp->tcp_non_sq_lock);
3953 
3954 		if (tcp->tcp_timer_tid != 0) {
3955 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3956 			tcp->tcp_timer_tid = 0;
3957 		}
3958 		/*
3959 		 * Need to cancel those timers which will not be used when
3960 		 * TCP is detached.  This has to be done before the tcp_wq
3961 		 * is set to the global queue.
3962 		 */
3963 		tcp_timers_stop(tcp);
3964 
3965 
3966 		tcp->tcp_detached = B_TRUE;
3967 		ASSERT(tcps->tcps_g_q != NULL);
3968 		tcp->tcp_rq = tcps->tcps_g_q;
3969 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3970 
3971 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3972 			tcp_time_wait_append(tcp);
3973 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3974 			goto finish;
3975 		}
3976 
3977 		/*
3978 		 * If delta is zero the timer event wasn't executed and was
3979 		 * successfully canceled. In this case we need to restart it
3980 		 * with the minimal delta possible.
3981 		 */
3982 		if (delta >= 0) {
3983 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3984 			    delta ? delta : 1);
3985 		}
3986 	} else {
3987 		tcp_closei_local(tcp);
3988 		CONN_DEC_REF(tcp->tcp_connp);
3989 	}
3990 finish:
3991 	/* Signal closing thread that it can complete close */
3992 	mutex_enter(&tcp->tcp_closelock);
3993 	tcp->tcp_detached = B_TRUE;
3994 	ASSERT(tcps->tcps_g_q != NULL);
3995 	tcp->tcp_rq = tcps->tcps_g_q;
3996 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3997 	tcp->tcp_closed = 1;
3998 	cv_signal(&tcp->tcp_closecv);
3999 	mutex_exit(&tcp->tcp_closelock);
4000 }
4001 
4002 /*
4003  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
4004  * expires.
4005  */
4006 static void
4007 tcp_close_linger_timeout(void *arg)
4008 {
4009 	conn_t	*connp = (conn_t *)arg;
4010 	tcp_t 	*tcp = connp->conn_tcp;
4011 
4012 	tcp->tcp_client_errno = ETIMEDOUT;
4013 	tcp_stop_lingering(tcp);
4014 }
4015 
4016 static int
4017 tcp_close(queue_t *q, int flags)
4018 {
4019 	conn_t		*connp = Q_TO_CONN(q);
4020 	tcp_t		*tcp = connp->conn_tcp;
4021 	mblk_t 		*mp = &tcp->tcp_closemp;
4022 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4023 	mblk_t		*bp;
4024 
4025 	ASSERT(WR(q)->q_next == NULL);
4026 	ASSERT(connp->conn_ref >= 2);
4027 
4028 	/*
4029 	 * We are being closed as /dev/tcp or /dev/tcp6.
4030 	 *
4031 	 * Mark the conn as closing. ill_pending_mp_add will not
4032 	 * add any mp to the pending mp list, after this conn has
4033 	 * started closing. Same for sq_pending_mp_add
4034 	 */
4035 	mutex_enter(&connp->conn_lock);
4036 	connp->conn_state_flags |= CONN_CLOSING;
4037 	if (connp->conn_oper_pending_ill != NULL)
4038 		conn_ioctl_cleanup_reqd = B_TRUE;
4039 	CONN_INC_REF_LOCKED(connp);
4040 	mutex_exit(&connp->conn_lock);
4041 	tcp->tcp_closeflags = (uint8_t)flags;
4042 	ASSERT(connp->conn_ref >= 3);
4043 
4044 	/*
4045 	 * tcp_closemp_used is used below without any protection of a lock
4046 	 * as we don't expect any one else to use it concurrently at this
4047 	 * point otherwise it would be a major defect.
4048 	 */
4049 
4050 	if (mp->b_prev == NULL)
4051 		tcp->tcp_closemp_used = B_TRUE;
4052 	else
4053 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
4054 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
4055 
4056 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
4057 
4058 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4059 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4060 
4061 	mutex_enter(&tcp->tcp_closelock);
4062 	while (!tcp->tcp_closed) {
4063 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
4064 			/*
4065 			 * The cv_wait_sig() was interrupted. We now do the
4066 			 * following:
4067 			 *
4068 			 * 1) If the endpoint was lingering, we allow this
4069 			 * to be interrupted by cancelling the linger timeout
4070 			 * and closing normally.
4071 			 *
4072 			 * 2) Revert to calling cv_wait()
4073 			 *
4074 			 * We revert to using cv_wait() to avoid an
4075 			 * infinite loop which can occur if the calling
4076 			 * thread is higher priority than the squeue worker
4077 			 * thread and is bound to the same cpu.
4078 			 */
4079 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
4080 				mutex_exit(&tcp->tcp_closelock);
4081 				/* Entering squeue, bump ref count. */
4082 				CONN_INC_REF(connp);
4083 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
4084 				squeue_enter(connp->conn_sqp, bp,
4085 				    tcp_linger_interrupted, connp,
4086 				    SQTAG_IP_TCP_CLOSE);
4087 				mutex_enter(&tcp->tcp_closelock);
4088 			}
4089 			break;
4090 		}
4091 	}
4092 	while (!tcp->tcp_closed)
4093 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
4094 	mutex_exit(&tcp->tcp_closelock);
4095 
4096 	/*
4097 	 * In the case of listener streams that have eagers in the q or q0
4098 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4099 	 * tcp_wq of the eagers point to our queues. By waiting for the
4100 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4101 	 * up their queue pointers and also dropped their references to us.
4102 	 */
4103 	if (tcp->tcp_wait_for_eagers) {
4104 		mutex_enter(&connp->conn_lock);
4105 		while (connp->conn_ref != 1) {
4106 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4107 		}
4108 		mutex_exit(&connp->conn_lock);
4109 	}
4110 	/*
4111 	 * ioctl cleanup. The mp is queued in the
4112 	 * ill_pending_mp or in the sq_pending_mp.
4113 	 */
4114 	if (conn_ioctl_cleanup_reqd)
4115 		conn_ioctl_cleanup(connp);
4116 
4117 	qprocsoff(q);
4118 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4119 
4120 	tcp->tcp_cpid = -1;
4121 
4122 	/*
4123 	 * Drop IP's reference on the conn. This is the last reference
4124 	 * on the connp if the state was less than established. If the
4125 	 * connection has gone into timewait state, then we will have
4126 	 * one ref for the TCP and one more ref (total of two) for the
4127 	 * classifier connected hash list (a timewait connections stays
4128 	 * in connected hash till closed).
4129 	 *
4130 	 * We can't assert the references because there might be other
4131 	 * transient reference places because of some walkers or queued
4132 	 * packets in squeue for the timewait state.
4133 	 */
4134 	CONN_DEC_REF(connp);
4135 	q->q_ptr = WR(q)->q_ptr = NULL;
4136 	return (0);
4137 }
4138 
4139 static int
4140 tcpclose_accept(queue_t *q)
4141 {
4142 	vmem_t	*minor_arena;
4143 	dev_t	conn_dev;
4144 
4145 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4146 
4147 	/*
4148 	 * We had opened an acceptor STREAM for sockfs which is
4149 	 * now being closed due to some error.
4150 	 */
4151 	qprocsoff(q);
4152 
4153 	minor_arena = (vmem_t *)WR(q)->q_ptr;
4154 	conn_dev = (dev_t)RD(q)->q_ptr;
4155 	ASSERT(minor_arena != NULL);
4156 	ASSERT(conn_dev != 0);
4157 	inet_minor_free(minor_arena, conn_dev);
4158 	q->q_ptr = WR(q)->q_ptr = NULL;
4159 	return (0);
4160 }
4161 
4162 /*
4163  * Called by tcp_close() routine via squeue when lingering is
4164  * interrupted by a signal.
4165  */
4166 
4167 /* ARGSUSED */
4168 static void
4169 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4170 {
4171 	conn_t	*connp = (conn_t *)arg;
4172 	tcp_t	*tcp = connp->conn_tcp;
4173 
4174 	freeb(mp);
4175 	if (tcp->tcp_linger_tid != 0 &&
4176 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4177 		tcp_stop_lingering(tcp);
4178 		tcp->tcp_client_errno = EINTR;
4179 	}
4180 }
4181 
4182 /*
4183  * Called by streams close routine via squeues when our client blows off her
4184  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4185  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4186  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4187  * acked.
4188  *
4189  * NOTE: tcp_close potentially returns error when lingering.
4190  * However, the stream head currently does not pass these errors
4191  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4192  * errors to the application (from tsleep()) and not errors
4193  * like ECONNRESET caused by receiving a reset packet.
4194  */
4195 
4196 /* ARGSUSED */
4197 static void
4198 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4199 {
4200 	char	*msg;
4201 	conn_t	*connp = (conn_t *)arg;
4202 	tcp_t	*tcp = connp->conn_tcp;
4203 	clock_t	delta = 0;
4204 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4205 
4206 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4207 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4208 
4209 	/* Cancel any pending timeout */
4210 	if (tcp->tcp_ordrelid != 0) {
4211 		if (tcp->tcp_timeout) {
4212 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ordrelid);
4213 		}
4214 		tcp->tcp_ordrelid = 0;
4215 		tcp->tcp_timeout = B_FALSE;
4216 	}
4217 
4218 	mutex_enter(&tcp->tcp_eager_lock);
4219 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4220 		/* Cleanup for listener */
4221 		tcp_eager_cleanup(tcp, 0);
4222 		tcp->tcp_wait_for_eagers = 1;
4223 	}
4224 	mutex_exit(&tcp->tcp_eager_lock);
4225 
4226 	connp->conn_mdt_ok = B_FALSE;
4227 	tcp->tcp_mdt = B_FALSE;
4228 
4229 	connp->conn_lso_ok = B_FALSE;
4230 	tcp->tcp_lso = B_FALSE;
4231 
4232 	msg = NULL;
4233 	switch (tcp->tcp_state) {
4234 	case TCPS_CLOSED:
4235 	case TCPS_IDLE:
4236 	case TCPS_BOUND:
4237 	case TCPS_LISTEN:
4238 		break;
4239 	case TCPS_SYN_SENT:
4240 		msg = "tcp_close, during connect";
4241 		break;
4242 	case TCPS_SYN_RCVD:
4243 		/*
4244 		 * Close during the connect 3-way handshake
4245 		 * but here there may or may not be pending data
4246 		 * already on queue. Process almost same as in
4247 		 * the ESTABLISHED state.
4248 		 */
4249 		/* FALLTHRU */
4250 	default:
4251 		if (tcp->tcp_sodirect != NULL) {
4252 			/* Ok, no more sodirect */
4253 			tcp->tcp_sodirect = NULL;
4254 		}
4255 
4256 		if (tcp->tcp_fused)
4257 			tcp_unfuse(tcp);
4258 
4259 		/*
4260 		 * If SO_LINGER has set a zero linger time, abort the
4261 		 * connection with a reset.
4262 		 */
4263 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4264 			msg = "tcp_close, zero lingertime";
4265 			break;
4266 		}
4267 
4268 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4269 		/*
4270 		 * Abort connection if there is unread data queued.
4271 		 */
4272 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4273 			msg = "tcp_close, unread data";
4274 			break;
4275 		}
4276 		/*
4277 		 * tcp_hard_bound is now cleared thus all packets go through
4278 		 * tcp_lookup. This fact is used by tcp_detach below.
4279 		 *
4280 		 * We have done a qwait() above which could have possibly
4281 		 * drained more messages in turn causing transition to a
4282 		 * different state. Check whether we have to do the rest
4283 		 * of the processing or not.
4284 		 */
4285 		if (tcp->tcp_state <= TCPS_LISTEN)
4286 			break;
4287 
4288 		/*
4289 		 * Transmit the FIN before detaching the tcp_t.
4290 		 * After tcp_detach returns this queue/perimeter
4291 		 * no longer owns the tcp_t thus others can modify it.
4292 		 */
4293 		(void) tcp_xmit_end(tcp);
4294 
4295 		/*
4296 		 * If lingering on close then wait until the fin is acked,
4297 		 * the SO_LINGER time passes, or a reset is sent/received.
4298 		 */
4299 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4300 		    !(tcp->tcp_fin_acked) &&
4301 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4302 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4303 				tcp->tcp_client_errno = EWOULDBLOCK;
4304 			} else if (tcp->tcp_client_errno == 0) {
4305 
4306 				ASSERT(tcp->tcp_linger_tid == 0);
4307 
4308 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4309 				    tcp_close_linger_timeout,
4310 				    tcp->tcp_lingertime * hz);
4311 
4312 				/* tcp_close_linger_timeout will finish close */
4313 				if (tcp->tcp_linger_tid == 0)
4314 					tcp->tcp_client_errno = ENOSR;
4315 				else
4316 					return;
4317 			}
4318 
4319 			/*
4320 			 * Check if we need to detach or just close
4321 			 * the instance.
4322 			 */
4323 			if (tcp->tcp_state <= TCPS_LISTEN)
4324 				break;
4325 		}
4326 
4327 		/*
4328 		 * Make sure that no other thread will access the tcp_rq of
4329 		 * this instance (through lookups etc.) as tcp_rq will go
4330 		 * away shortly.
4331 		 */
4332 		tcp_acceptor_hash_remove(tcp);
4333 
4334 		mutex_enter(&tcp->tcp_non_sq_lock);
4335 		if (tcp->tcp_flow_stopped) {
4336 			tcp_clrqfull(tcp);
4337 		}
4338 		mutex_exit(&tcp->tcp_non_sq_lock);
4339 
4340 		if (tcp->tcp_timer_tid != 0) {
4341 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4342 			tcp->tcp_timer_tid = 0;
4343 		}
4344 		/*
4345 		 * Need to cancel those timers which will not be used when
4346 		 * TCP is detached.  This has to be done before the tcp_wq
4347 		 * is set to the global queue.
4348 		 */
4349 		tcp_timers_stop(tcp);
4350 
4351 		tcp->tcp_detached = B_TRUE;
4352 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4353 			tcp_time_wait_append(tcp);
4354 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4355 			ASSERT(connp->conn_ref >= 3);
4356 			goto finish;
4357 		}
4358 
4359 		/*
4360 		 * If delta is zero the timer event wasn't executed and was
4361 		 * successfully canceled. In this case we need to restart it
4362 		 * with the minimal delta possible.
4363 		 */
4364 		if (delta >= 0)
4365 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4366 			    delta ? delta : 1);
4367 
4368 		ASSERT(connp->conn_ref >= 3);
4369 		goto finish;
4370 	}
4371 
4372 	/* Detach did not complete. Still need to remove q from stream. */
4373 	if (msg) {
4374 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4375 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4376 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4377 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4378 		    tcp->tcp_state == TCPS_SYN_RCVD)
4379 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4380 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4381 	}
4382 
4383 	tcp_closei_local(tcp);
4384 	CONN_DEC_REF(connp);
4385 	ASSERT(connp->conn_ref >= 2);
4386 
4387 finish:
4388 	/*
4389 	 * Although packets are always processed on the correct
4390 	 * tcp's perimeter and access is serialized via squeue's,
4391 	 * IP still needs a queue when sending packets in time_wait
4392 	 * state so use WR(tcps_g_q) till ip_output() can be
4393 	 * changed to deal with just connp. For read side, we
4394 	 * could have set tcp_rq to NULL but there are some cases
4395 	 * in tcp_rput_data() from early days of this code which
4396 	 * do a putnext without checking if tcp is closed. Those
4397 	 * need to be identified before both tcp_rq and tcp_wq
4398 	 * can be set to NULL and tcps_g_q can disappear forever.
4399 	 */
4400 	mutex_enter(&tcp->tcp_closelock);
4401 	/*
4402 	 * Don't change the queues in the case of a listener that has
4403 	 * eagers in its q or q0. It could surprise the eagers.
4404 	 * Instead wait for the eagers outside the squeue.
4405 	 */
4406 	if (!tcp->tcp_wait_for_eagers) {
4407 		tcp->tcp_detached = B_TRUE;
4408 		/*
4409 		 * When default queue is closing we set tcps_g_q to NULL
4410 		 * after the close is done.
4411 		 */
4412 		ASSERT(tcps->tcps_g_q != NULL);
4413 		tcp->tcp_rq = tcps->tcps_g_q;
4414 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4415 	}
4416 
4417 	/* Signal tcp_close() to finish closing. */
4418 	tcp->tcp_closed = 1;
4419 	cv_signal(&tcp->tcp_closecv);
4420 	mutex_exit(&tcp->tcp_closelock);
4421 }
4422 
4423 
4424 /*
4425  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4426  * Some stream heads get upset if they see these later on as anything but NULL.
4427  */
4428 static void
4429 tcp_close_mpp(mblk_t **mpp)
4430 {
4431 	mblk_t	*mp;
4432 
4433 	if ((mp = *mpp) != NULL) {
4434 		do {
4435 			mp->b_next = NULL;
4436 			mp->b_prev = NULL;
4437 		} while ((mp = mp->b_cont) != NULL);
4438 
4439 		mp = *mpp;
4440 		*mpp = NULL;
4441 		freemsg(mp);
4442 	}
4443 }
4444 
4445 /* Do detached close. */
4446 static void
4447 tcp_close_detached(tcp_t *tcp)
4448 {
4449 	if (tcp->tcp_fused)
4450 		tcp_unfuse(tcp);
4451 
4452 	/*
4453 	 * Clustering code serializes TCP disconnect callbacks and
4454 	 * cluster tcp list walks by blocking a TCP disconnect callback
4455 	 * if a cluster tcp list walk is in progress. This ensures
4456 	 * accurate accounting of TCPs in the cluster code even though
4457 	 * the TCP list walk itself is not atomic.
4458 	 */
4459 	tcp_closei_local(tcp);
4460 	CONN_DEC_REF(tcp->tcp_connp);
4461 }
4462 
4463 /*
4464  * Stop all TCP timers, and free the timer mblks if requested.
4465  */
4466 void
4467 tcp_timers_stop(tcp_t *tcp)
4468 {
4469 	if (tcp->tcp_timer_tid != 0) {
4470 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4471 		tcp->tcp_timer_tid = 0;
4472 	}
4473 	if (tcp->tcp_ka_tid != 0) {
4474 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4475 		tcp->tcp_ka_tid = 0;
4476 	}
4477 	if (tcp->tcp_ack_tid != 0) {
4478 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4479 		tcp->tcp_ack_tid = 0;
4480 	}
4481 	if (tcp->tcp_push_tid != 0) {
4482 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4483 		tcp->tcp_push_tid = 0;
4484 	}
4485 }
4486 
4487 /*
4488  * The tcp_t is going away. Remove it from all lists and set it
4489  * to TCPS_CLOSED. The freeing up of memory is deferred until
4490  * tcp_inactive. This is needed since a thread in tcp_rput might have
4491  * done a CONN_INC_REF on this structure before it was removed from the
4492  * hashes.
4493  */
4494 static void
4495 tcp_closei_local(tcp_t *tcp)
4496 {
4497 	ire_t 	*ire;
4498 	conn_t	*connp = tcp->tcp_connp;
4499 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4500 
4501 	if (!TCP_IS_SOCKET(tcp))
4502 		tcp_acceptor_hash_remove(tcp);
4503 
4504 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4505 	tcp->tcp_ibsegs = 0;
4506 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4507 	tcp->tcp_obsegs = 0;
4508 
4509 	/*
4510 	 * If we are an eager connection hanging off a listener that
4511 	 * hasn't formally accepted the connection yet, get off his
4512 	 * list and blow off any data that we have accumulated.
4513 	 */
4514 	if (tcp->tcp_listener != NULL) {
4515 		tcp_t	*listener = tcp->tcp_listener;
4516 		mutex_enter(&listener->tcp_eager_lock);
4517 		/*
4518 		 * tcp_tconnind_started == B_TRUE means that the
4519 		 * conn_ind has already gone to listener. At
4520 		 * this point, eager will be closed but we
4521 		 * leave it in listeners eager list so that
4522 		 * if listener decides to close without doing
4523 		 * accept, we can clean this up. In tcp_wput_accept
4524 		 * we take care of the case of accept on closed
4525 		 * eager.
4526 		 */
4527 		if (!tcp->tcp_tconnind_started) {
4528 			tcp_eager_unlink(tcp);
4529 			mutex_exit(&listener->tcp_eager_lock);
4530 			/*
4531 			 * We don't want to have any pointers to the
4532 			 * listener queue, after we have released our
4533 			 * reference on the listener
4534 			 */
4535 			ASSERT(tcps->tcps_g_q != NULL);
4536 			tcp->tcp_rq = tcps->tcps_g_q;
4537 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4538 			CONN_DEC_REF(listener->tcp_connp);
4539 		} else {
4540 			mutex_exit(&listener->tcp_eager_lock);
4541 		}
4542 	}
4543 
4544 	/* Stop all the timers */
4545 	tcp_timers_stop(tcp);
4546 
4547 	if (tcp->tcp_state == TCPS_LISTEN) {
4548 		if (tcp->tcp_ip_addr_cache) {
4549 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4550 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4551 			tcp->tcp_ip_addr_cache = NULL;
4552 		}
4553 	}
4554 	mutex_enter(&tcp->tcp_non_sq_lock);
4555 	if (tcp->tcp_flow_stopped)
4556 		tcp_clrqfull(tcp);
4557 	mutex_exit(&tcp->tcp_non_sq_lock);
4558 
4559 	tcp_bind_hash_remove(tcp);
4560 	/*
4561 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4562 	 * is trying to remove this tcp from the time wait list, we will
4563 	 * block in tcp_time_wait_remove while trying to acquire the
4564 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4565 	 * requires the ipcl_hash_remove to be ordered after the
4566 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4567 	 */
4568 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4569 		(void) tcp_time_wait_remove(tcp, NULL);
4570 	CL_INET_DISCONNECT(tcp);
4571 	ipcl_hash_remove(connp);
4572 
4573 	/*
4574 	 * Delete the cached ire in conn_ire_cache and also mark
4575 	 * the conn as CONDEMNED
4576 	 */
4577 	mutex_enter(&connp->conn_lock);
4578 	connp->conn_state_flags |= CONN_CONDEMNED;
4579 	ire = connp->conn_ire_cache;
4580 	connp->conn_ire_cache = NULL;
4581 	mutex_exit(&connp->conn_lock);
4582 	if (ire != NULL)
4583 		IRE_REFRELE_NOTR(ire);
4584 
4585 	/* Need to cleanup any pending ioctls */
4586 	ASSERT(tcp->tcp_time_wait_next == NULL);
4587 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4588 	ASSERT(tcp->tcp_time_wait_expire == 0);
4589 	tcp->tcp_state = TCPS_CLOSED;
4590 
4591 	/* Release any SSL context */
4592 	if (tcp->tcp_kssl_ent != NULL) {
4593 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4594 		tcp->tcp_kssl_ent = NULL;
4595 	}
4596 	if (tcp->tcp_kssl_ctx != NULL) {
4597 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4598 		tcp->tcp_kssl_ctx = NULL;
4599 	}
4600 	tcp->tcp_kssl_pending = B_FALSE;
4601 
4602 	tcp_ipsec_cleanup(tcp);
4603 }
4604 
4605 /*
4606  * tcp is dying (called from ipcl_conn_destroy and error cases).
4607  * Free the tcp_t in either case.
4608  */
4609 void
4610 tcp_free(tcp_t *tcp)
4611 {
4612 	mblk_t	*mp;
4613 	ip6_pkt_t	*ipp;
4614 
4615 	ASSERT(tcp != NULL);
4616 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4617 
4618 	tcp->tcp_rq = NULL;
4619 	tcp->tcp_wq = NULL;
4620 
4621 	tcp_close_mpp(&tcp->tcp_xmit_head);
4622 	tcp_close_mpp(&tcp->tcp_reass_head);
4623 	if (tcp->tcp_rcv_list != NULL) {
4624 		/* Free b_next chain */
4625 		tcp_close_mpp(&tcp->tcp_rcv_list);
4626 	}
4627 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4628 		freemsg(mp);
4629 	}
4630 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4631 		freemsg(mp);
4632 	}
4633 
4634 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4635 		freeb(tcp->tcp_fused_sigurg_mp);
4636 		tcp->tcp_fused_sigurg_mp = NULL;
4637 	}
4638 
4639 	if (tcp->tcp_sack_info != NULL) {
4640 		if (tcp->tcp_notsack_list != NULL) {
4641 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4642 		}
4643 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4644 	}
4645 
4646 	if (tcp->tcp_hopopts != NULL) {
4647 		mi_free(tcp->tcp_hopopts);
4648 		tcp->tcp_hopopts = NULL;
4649 		tcp->tcp_hopoptslen = 0;
4650 	}
4651 	ASSERT(tcp->tcp_hopoptslen == 0);
4652 	if (tcp->tcp_dstopts != NULL) {
4653 		mi_free(tcp->tcp_dstopts);
4654 		tcp->tcp_dstopts = NULL;
4655 		tcp->tcp_dstoptslen = 0;
4656 	}
4657 	ASSERT(tcp->tcp_dstoptslen == 0);
4658 	if (tcp->tcp_rtdstopts != NULL) {
4659 		mi_free(tcp->tcp_rtdstopts);
4660 		tcp->tcp_rtdstopts = NULL;
4661 		tcp->tcp_rtdstoptslen = 0;
4662 	}
4663 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4664 	if (tcp->tcp_rthdr != NULL) {
4665 		mi_free(tcp->tcp_rthdr);
4666 		tcp->tcp_rthdr = NULL;
4667 		tcp->tcp_rthdrlen = 0;
4668 	}
4669 	ASSERT(tcp->tcp_rthdrlen == 0);
4670 
4671 	ipp = &tcp->tcp_sticky_ipp;
4672 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4673 	    IPPF_RTHDR))
4674 		ip6_pkt_free(ipp);
4675 
4676 	/*
4677 	 * Free memory associated with the tcp/ip header template.
4678 	 */
4679 
4680 	if (tcp->tcp_iphc != NULL)
4681 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4682 
4683 	/*
4684 	 * Following is really a blowing away a union.
4685 	 * It happens to have exactly two members of identical size
4686 	 * the following code is enough.
4687 	 */
4688 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4689 }
4690 
4691 
4692 /*
4693  * Put a connection confirmation message upstream built from the
4694  * address information within 'iph' and 'tcph'.  Report our success or failure.
4695  */
4696 static boolean_t
4697 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4698     mblk_t **defermp)
4699 {
4700 	sin_t	sin;
4701 	sin6_t	sin6;
4702 	mblk_t	*mp;
4703 	char	*optp = NULL;
4704 	int	optlen = 0;
4705 	cred_t	*cr;
4706 
4707 	if (defermp != NULL)
4708 		*defermp = NULL;
4709 
4710 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4711 		/*
4712 		 * Return in T_CONN_CON results of option negotiation through
4713 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4714 		 * negotiation, then what is received from remote end needs
4715 		 * to be taken into account but there is no such thing (yet?)
4716 		 * in our TCP/IP.
4717 		 * Note: We do not use mi_offset_param() here as
4718 		 * tcp_opts_conn_req contents do not directly come from
4719 		 * an application and are either generated in kernel or
4720 		 * from user input that was already verified.
4721 		 */
4722 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4723 		optp = (char *)(mp->b_rptr +
4724 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4725 		optlen = (int)
4726 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4727 	}
4728 
4729 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4730 		ipha_t *ipha = (ipha_t *)iphdr;
4731 
4732 		/* packet is IPv4 */
4733 		if (tcp->tcp_family == AF_INET) {
4734 			sin = sin_null;
4735 			sin.sin_addr.s_addr = ipha->ipha_src;
4736 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4737 			sin.sin_family = AF_INET;
4738 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4739 			    (int)sizeof (sin_t), optp, optlen);
4740 		} else {
4741 			sin6 = sin6_null;
4742 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4743 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4744 			sin6.sin6_family = AF_INET6;
4745 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4746 			    (int)sizeof (sin6_t), optp, optlen);
4747 
4748 		}
4749 	} else {
4750 		ip6_t	*ip6h = (ip6_t *)iphdr;
4751 
4752 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4753 		ASSERT(tcp->tcp_family == AF_INET6);
4754 		sin6 = sin6_null;
4755 		sin6.sin6_addr = ip6h->ip6_src;
4756 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4757 		sin6.sin6_family = AF_INET6;
4758 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4759 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4760 		    (int)sizeof (sin6_t), optp, optlen);
4761 	}
4762 
4763 	if (!mp)
4764 		return (B_FALSE);
4765 
4766 	if ((cr = DB_CRED(idmp)) != NULL) {
4767 		mblk_setcred(mp, cr);
4768 		DB_CPID(mp) = DB_CPID(idmp);
4769 	}
4770 
4771 	if (defermp == NULL)
4772 		putnext(tcp->tcp_rq, mp);
4773 	else
4774 		*defermp = mp;
4775 
4776 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4777 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4778 	return (B_TRUE);
4779 }
4780 
4781 /*
4782  * Defense for the SYN attack -
4783  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4784  *    one from the list of droppable eagers. This list is a subset of q0.
4785  *    see comments before the definition of MAKE_DROPPABLE().
4786  * 2. Don't drop a SYN request before its first timeout. This gives every
4787  *    request at least til the first timeout to complete its 3-way handshake.
4788  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4789  *    requests currently on the queue that has timed out. This will be used
4790  *    as an indicator of whether an attack is under way, so that appropriate
4791  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4792  *    either when eager goes into ESTABLISHED, or gets freed up.)
4793  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4794  *    # of timeout drops back to <= q0len/32 => SYN alert off
4795  */
4796 static boolean_t
4797 tcp_drop_q0(tcp_t *tcp)
4798 {
4799 	tcp_t	*eager;
4800 	mblk_t	*mp;
4801 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4802 
4803 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4804 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4805 
4806 	/* Pick oldest eager from the list of droppable eagers */
4807 	eager = tcp->tcp_eager_prev_drop_q0;
4808 
4809 	/* If list is empty. return B_FALSE */
4810 	if (eager == tcp) {
4811 		return (B_FALSE);
4812 	}
4813 
4814 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4815 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4816 		return (B_FALSE);
4817 
4818 	/*
4819 	 * Take this eager out from the list of droppable eagers since we are
4820 	 * going to drop it.
4821 	 */
4822 	MAKE_UNDROPPABLE(eager);
4823 
4824 	if (tcp->tcp_debug) {
4825 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4826 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4827 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4828 		    tcp->tcp_conn_req_cnt_q0,
4829 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4830 	}
4831 
4832 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4833 
4834 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4835 	CONN_INC_REF(eager->tcp_connp);
4836 
4837 	/* Mark the IRE created for this SYN request temporary */
4838 	tcp_ip_ire_mark_advice(eager);
4839 	squeue_fill(eager->tcp_connp->conn_sqp, mp,
4840 	    tcp_clean_death_wrapper, eager->tcp_connp, SQTAG_TCP_DROP_Q0);
4841 
4842 	return (B_TRUE);
4843 }
4844 
4845 int
4846 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4847     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4848 {
4849 	tcp_t 		*ltcp = lconnp->conn_tcp;
4850 	tcp_t		*tcp = connp->conn_tcp;
4851 	mblk_t		*tpi_mp;
4852 	ipha_t		*ipha;
4853 	ip6_t		*ip6h;
4854 	sin6_t 		sin6;
4855 	in6_addr_t 	v6dst;
4856 	int		err;
4857 	int		ifindex = 0;
4858 	cred_t		*cr;
4859 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4860 
4861 	if (ipvers == IPV4_VERSION) {
4862 		ipha = (ipha_t *)mp->b_rptr;
4863 
4864 		connp->conn_send = ip_output;
4865 		connp->conn_recv = tcp_input;
4866 
4867 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4868 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4869 
4870 		sin6 = sin6_null;
4871 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4872 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4873 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4874 		sin6.sin6_family = AF_INET6;
4875 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4876 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4877 		if (tcp->tcp_recvdstaddr) {
4878 			sin6_t	sin6d;
4879 
4880 			sin6d = sin6_null;
4881 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4882 			    &sin6d.sin6_addr);
4883 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4884 			sin6d.sin6_family = AF_INET;
4885 			tpi_mp = mi_tpi_extconn_ind(NULL,
4886 			    (char *)&sin6d, sizeof (sin6_t),
4887 			    (char *)&tcp,
4888 			    (t_scalar_t)sizeof (intptr_t),
4889 			    (char *)&sin6d, sizeof (sin6_t),
4890 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4891 		} else {
4892 			tpi_mp = mi_tpi_conn_ind(NULL,
4893 			    (char *)&sin6, sizeof (sin6_t),
4894 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4895 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4896 		}
4897 	} else {
4898 		ip6h = (ip6_t *)mp->b_rptr;
4899 
4900 		connp->conn_send = ip_output_v6;
4901 		connp->conn_recv = tcp_input;
4902 
4903 		connp->conn_srcv6 = ip6h->ip6_dst;
4904 		connp->conn_remv6 = ip6h->ip6_src;
4905 
4906 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4907 		ifindex = (int)DB_CKSUMSTUFF(mp);
4908 		DB_CKSUMSTUFF(mp) = 0;
4909 
4910 		sin6 = sin6_null;
4911 		sin6.sin6_addr = ip6h->ip6_src;
4912 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4913 		sin6.sin6_family = AF_INET6;
4914 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4915 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4916 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4917 
4918 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4919 			/* Pass up the scope_id of remote addr */
4920 			sin6.sin6_scope_id = ifindex;
4921 		} else {
4922 			sin6.sin6_scope_id = 0;
4923 		}
4924 		if (tcp->tcp_recvdstaddr) {
4925 			sin6_t	sin6d;
4926 
4927 			sin6d = sin6_null;
4928 			sin6.sin6_addr = ip6h->ip6_dst;
4929 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4930 			sin6d.sin6_family = AF_INET;
4931 			tpi_mp = mi_tpi_extconn_ind(NULL,
4932 			    (char *)&sin6d, sizeof (sin6_t),
4933 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4934 			    (char *)&sin6d, sizeof (sin6_t),
4935 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4936 		} else {
4937 			tpi_mp = mi_tpi_conn_ind(NULL,
4938 			    (char *)&sin6, sizeof (sin6_t),
4939 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4940 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4941 		}
4942 	}
4943 
4944 	if (tpi_mp == NULL)
4945 		return (ENOMEM);
4946 
4947 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4948 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4949 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4950 	connp->conn_fully_bound = B_FALSE;
4951 
4952 	/* Inherit information from the "parent" */
4953 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4954 	tcp->tcp_family = ltcp->tcp_family;
4955 	tcp->tcp_wq = ltcp->tcp_wq;
4956 	tcp->tcp_rq = ltcp->tcp_rq;
4957 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4958 	tcp->tcp_detached = B_TRUE;
4959 	if ((err = tcp_init_values(tcp)) != 0) {
4960 		freemsg(tpi_mp);
4961 		return (err);
4962 	}
4963 
4964 	if (ipvers == IPV4_VERSION) {
4965 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4966 			freemsg(tpi_mp);
4967 			return (err);
4968 		}
4969 		ASSERT(tcp->tcp_ipha != NULL);
4970 	} else {
4971 		/* ifindex must be already set */
4972 		ASSERT(ifindex != 0);
4973 
4974 		if (ltcp->tcp_bound_if != 0) {
4975 			/*
4976 			 * Set newtcp's bound_if equal to
4977 			 * listener's value. If ifindex is
4978 			 * not the same as ltcp->tcp_bound_if,
4979 			 * it must be a packet for the ipmp group
4980 			 * of interfaces
4981 			 */
4982 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4983 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4984 			tcp->tcp_bound_if = ifindex;
4985 		}
4986 
4987 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4988 		tcp->tcp_recvifindex = 0;
4989 		tcp->tcp_recvhops = 0xffffffffU;
4990 		ASSERT(tcp->tcp_ip6h != NULL);
4991 	}
4992 
4993 	tcp->tcp_lport = ltcp->tcp_lport;
4994 
4995 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4996 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4997 			/*
4998 			 * Listener had options of some sort; eager inherits.
4999 			 * Free up the eager template and allocate one
5000 			 * of the right size.
5001 			 */
5002 			if (tcp->tcp_hdr_grown) {
5003 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
5004 			} else {
5005 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
5006 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
5007 			}
5008 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
5009 			    KM_NOSLEEP);
5010 			if (tcp->tcp_iphc == NULL) {
5011 				tcp->tcp_iphc_len = 0;
5012 				freemsg(tpi_mp);
5013 				return (ENOMEM);
5014 			}
5015 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
5016 			tcp->tcp_hdr_grown = B_TRUE;
5017 		}
5018 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5019 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5020 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5021 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
5022 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
5023 
5024 		/*
5025 		 * Copy the IP+TCP header template from listener to eager
5026 		 */
5027 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5028 		if (tcp->tcp_ipversion == IPV6_VERSION) {
5029 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
5030 			    IPPROTO_RAW) {
5031 				tcp->tcp_ip6h =
5032 				    (ip6_t *)(tcp->tcp_iphc +
5033 				    sizeof (ip6i_t));
5034 			} else {
5035 				tcp->tcp_ip6h =
5036 				    (ip6_t *)(tcp->tcp_iphc);
5037 			}
5038 			tcp->tcp_ipha = NULL;
5039 		} else {
5040 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5041 			tcp->tcp_ip6h = NULL;
5042 		}
5043 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5044 		    tcp->tcp_ip_hdr_len);
5045 	} else {
5046 		/*
5047 		 * only valid case when ipversion of listener and
5048 		 * eager differ is when listener is IPv6 and
5049 		 * eager is IPv4.
5050 		 * Eager header template has been initialized to the
5051 		 * maximum v4 header sizes, which includes space for
5052 		 * TCP and IP options.
5053 		 */
5054 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5055 		    (tcp->tcp_ipversion == IPV4_VERSION));
5056 		ASSERT(tcp->tcp_iphc_len >=
5057 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5058 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5059 		/* copy IP header fields individually */
5060 		tcp->tcp_ipha->ipha_ttl =
5061 		    ltcp->tcp_ip6h->ip6_hops;
5062 		bcopy(ltcp->tcp_tcph->th_lport,
5063 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5064 	}
5065 
5066 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5067 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5068 	    sizeof (in_port_t));
5069 
5070 	if (ltcp->tcp_lport == 0) {
5071 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5072 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5073 		    sizeof (in_port_t));
5074 	}
5075 
5076 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5077 		ASSERT(ipha != NULL);
5078 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5079 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5080 
5081 		/* Source routing option copyover (reverse it) */
5082 		if (tcps->tcps_rev_src_routes)
5083 			tcp_opt_reverse(tcp, ipha);
5084 	} else {
5085 		ASSERT(ip6h != NULL);
5086 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5087 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5088 	}
5089 
5090 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5091 	ASSERT(!tcp->tcp_tconnind_started);
5092 	/*
5093 	 * If the SYN contains a credential, it's a loopback packet; attach
5094 	 * the credential to the TPI message.
5095 	 */
5096 	if ((cr = DB_CRED(idmp)) != NULL) {
5097 		mblk_setcred(tpi_mp, cr);
5098 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5099 	}
5100 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5101 
5102 	/* Inherit the listener's SSL protection state */
5103 
5104 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5105 		kssl_hold_ent(tcp->tcp_kssl_ent);
5106 		tcp->tcp_kssl_pending = B_TRUE;
5107 	}
5108 
5109 	return (0);
5110 }
5111 
5112 
5113 int
5114 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5115     tcph_t *tcph, mblk_t *idmp)
5116 {
5117 	tcp_t 		*ltcp = lconnp->conn_tcp;
5118 	tcp_t		*tcp = connp->conn_tcp;
5119 	sin_t		sin;
5120 	mblk_t		*tpi_mp = NULL;
5121 	int		err;
5122 	cred_t		*cr;
5123 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5124 
5125 	sin = sin_null;
5126 	sin.sin_addr.s_addr = ipha->ipha_src;
5127 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5128 	sin.sin_family = AF_INET;
5129 	if (ltcp->tcp_recvdstaddr) {
5130 		sin_t	sind;
5131 
5132 		sind = sin_null;
5133 		sind.sin_addr.s_addr = ipha->ipha_dst;
5134 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5135 		sind.sin_family = AF_INET;
5136 		tpi_mp = mi_tpi_extconn_ind(NULL,
5137 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5138 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5139 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5140 	} else {
5141 		tpi_mp = mi_tpi_conn_ind(NULL,
5142 		    (char *)&sin, sizeof (sin_t),
5143 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5144 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5145 	}
5146 
5147 	if (tpi_mp == NULL) {
5148 		return (ENOMEM);
5149 	}
5150 
5151 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5152 	connp->conn_send = ip_output;
5153 	connp->conn_recv = tcp_input;
5154 	connp->conn_fully_bound = B_FALSE;
5155 
5156 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5157 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5158 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5159 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5160 
5161 	/* Inherit information from the "parent" */
5162 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5163 	tcp->tcp_family = ltcp->tcp_family;
5164 	tcp->tcp_wq = ltcp->tcp_wq;
5165 	tcp->tcp_rq = ltcp->tcp_rq;
5166 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
5167 	tcp->tcp_detached = B_TRUE;
5168 	if ((err = tcp_init_values(tcp)) != 0) {
5169 		freemsg(tpi_mp);
5170 		return (err);
5171 	}
5172 
5173 	/*
5174 	 * Let's make sure that eager tcp template has enough space to
5175 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5176 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5177 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5178 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5179 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5180 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5181 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5182 	 */
5183 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5184 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5185 
5186 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5187 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5188 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5189 	tcp->tcp_ttl = ltcp->tcp_ttl;
5190 	tcp->tcp_tos = ltcp->tcp_tos;
5191 
5192 	/* Copy the IP+TCP header template from listener to eager */
5193 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5194 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5195 	tcp->tcp_ip6h = NULL;
5196 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5197 	    tcp->tcp_ip_hdr_len);
5198 
5199 	/* Initialize the IP addresses and Ports */
5200 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5201 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5202 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5203 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5204 
5205 	/* Source routing option copyover (reverse it) */
5206 	if (tcps->tcps_rev_src_routes)
5207 		tcp_opt_reverse(tcp, ipha);
5208 
5209 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5210 	ASSERT(!tcp->tcp_tconnind_started);
5211 
5212 	/*
5213 	 * If the SYN contains a credential, it's a loopback packet; attach
5214 	 * the credential to the TPI message.
5215 	 */
5216 	if ((cr = DB_CRED(idmp)) != NULL) {
5217 		mblk_setcred(tpi_mp, cr);
5218 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5219 	}
5220 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5221 
5222 	/* Inherit the listener's SSL protection state */
5223 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5224 		kssl_hold_ent(tcp->tcp_kssl_ent);
5225 		tcp->tcp_kssl_pending = B_TRUE;
5226 	}
5227 
5228 	return (0);
5229 }
5230 
5231 /*
5232  * sets up conn for ipsec.
5233  * if the first mblk is M_CTL it is consumed and mpp is updated.
5234  * in case of error mpp is freed.
5235  */
5236 conn_t *
5237 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5238 {
5239 	conn_t 		*connp = tcp->tcp_connp;
5240 	conn_t 		*econnp;
5241 	squeue_t 	*new_sqp;
5242 	mblk_t 		*first_mp = *mpp;
5243 	mblk_t		*mp = *mpp;
5244 	boolean_t	mctl_present = B_FALSE;
5245 	uint_t		ipvers;
5246 
5247 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
5248 	if (econnp == NULL) {
5249 		freemsg(first_mp);
5250 		return (NULL);
5251 	}
5252 	if (DB_TYPE(mp) == M_CTL) {
5253 		if (mp->b_cont == NULL ||
5254 		    mp->b_cont->b_datap->db_type != M_DATA) {
5255 			freemsg(first_mp);
5256 			return (NULL);
5257 		}
5258 		mp = mp->b_cont;
5259 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5260 			freemsg(first_mp);
5261 			return (NULL);
5262 		}
5263 
5264 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5265 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5266 		mctl_present = B_TRUE;
5267 	} else {
5268 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5269 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5270 	}
5271 
5272 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5273 	DB_CKSUMSTART(mp) = 0;
5274 
5275 	ASSERT(OK_32PTR(mp->b_rptr));
5276 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5277 	if (ipvers == IPV4_VERSION) {
5278 		uint16_t  	*up;
5279 		uint32_t	ports;
5280 		ipha_t		*ipha;
5281 
5282 		ipha = (ipha_t *)mp->b_rptr;
5283 		up = (uint16_t *)((uchar_t *)ipha +
5284 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5285 		ports = *(uint32_t *)up;
5286 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5287 		    ipha->ipha_dst, ipha->ipha_src, ports);
5288 	} else {
5289 		uint16_t  	*up;
5290 		uint32_t	ports;
5291 		uint16_t	ip_hdr_len;
5292 		uint8_t		*nexthdrp;
5293 		ip6_t 		*ip6h;
5294 		tcph_t		*tcph;
5295 
5296 		ip6h = (ip6_t *)mp->b_rptr;
5297 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5298 			ip_hdr_len = IPV6_HDR_LEN;
5299 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5300 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5301 			CONN_DEC_REF(econnp);
5302 			freemsg(first_mp);
5303 			return (NULL);
5304 		}
5305 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5306 		up = (uint16_t *)tcph->th_lport;
5307 		ports = *(uint32_t *)up;
5308 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5309 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5310 	}
5311 
5312 	/*
5313 	 * The caller already ensured that there is a sqp present.
5314 	 */
5315 	econnp->conn_sqp = new_sqp;
5316 
5317 	if (connp->conn_policy != NULL) {
5318 		ipsec_in_t *ii;
5319 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5320 		ASSERT(ii->ipsec_in_policy == NULL);
5321 		IPPH_REFHOLD(connp->conn_policy);
5322 		ii->ipsec_in_policy = connp->conn_policy;
5323 
5324 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5325 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5326 			CONN_DEC_REF(econnp);
5327 			freemsg(first_mp);
5328 			return (NULL);
5329 		}
5330 	}
5331 
5332 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5333 		CONN_DEC_REF(econnp);
5334 		freemsg(first_mp);
5335 		return (NULL);
5336 	}
5337 
5338 	/*
5339 	 * If we know we have some policy, pass the "IPSEC"
5340 	 * options size TCP uses this adjust the MSS.
5341 	 */
5342 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5343 	if (mctl_present) {
5344 		freeb(first_mp);
5345 		*mpp = mp;
5346 	}
5347 
5348 	return (econnp);
5349 }
5350 
5351 /*
5352  * tcp_get_conn/tcp_free_conn
5353  *
5354  * tcp_get_conn is used to get a clean tcp connection structure.
5355  * It tries to reuse the connections put on the freelist by the
5356  * time_wait_collector failing which it goes to kmem_cache. This
5357  * way has two benefits compared to just allocating from and
5358  * freeing to kmem_cache.
5359  * 1) The time_wait_collector can free (which includes the cleanup)
5360  * outside the squeue. So when the interrupt comes, we have a clean
5361  * connection sitting in the freelist. Obviously, this buys us
5362  * performance.
5363  *
5364  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5365  * has multiple disadvantages - tying up the squeue during alloc, and the
5366  * fact that IPSec policy initialization has to happen here which
5367  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5368  * But allocating the conn/tcp in IP land is also not the best since
5369  * we can't check the 'q' and 'q0' which are protected by squeue and
5370  * blindly allocate memory which might have to be freed here if we are
5371  * not allowed to accept the connection. By using the freelist and
5372  * putting the conn/tcp back in freelist, we don't pay a penalty for
5373  * allocating memory without checking 'q/q0' and freeing it if we can't
5374  * accept the connection.
5375  *
5376  * Care should be taken to put the conn back in the same squeue's freelist
5377  * from which it was allocated. Best results are obtained if conn is
5378  * allocated from listener's squeue and freed to the same. Time wait
5379  * collector will free up the freelist is the connection ends up sitting
5380  * there for too long.
5381  */
5382 void *
5383 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5384 {
5385 	tcp_t			*tcp = NULL;
5386 	conn_t			*connp = NULL;
5387 	squeue_t		*sqp = (squeue_t *)arg;
5388 	tcp_squeue_priv_t 	*tcp_time_wait;
5389 	netstack_t		*ns;
5390 
5391 	tcp_time_wait =
5392 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5393 
5394 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5395 	tcp = tcp_time_wait->tcp_free_list;
5396 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5397 	if (tcp != NULL) {
5398 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5399 		tcp_time_wait->tcp_free_list_cnt--;
5400 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5401 		tcp->tcp_time_wait_next = NULL;
5402 		connp = tcp->tcp_connp;
5403 		connp->conn_flags |= IPCL_REUSED;
5404 
5405 		ASSERT(tcp->tcp_tcps == NULL);
5406 		ASSERT(connp->conn_netstack == NULL);
5407 		ns = tcps->tcps_netstack;
5408 		netstack_hold(ns);
5409 		connp->conn_netstack = ns;
5410 		tcp->tcp_tcps = tcps;
5411 		TCPS_REFHOLD(tcps);
5412 		ipcl_globalhash_insert(connp);
5413 		return ((void *)connp);
5414 	}
5415 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5416 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5417 	    tcps->tcps_netstack)) == NULL)
5418 		return (NULL);
5419 	tcp = connp->conn_tcp;
5420 	tcp->tcp_tcps = tcps;
5421 	TCPS_REFHOLD(tcps);
5422 	return ((void *)connp);
5423 }
5424 
5425 /*
5426  * Update the cached label for the given tcp_t.  This should be called once per
5427  * connection, and before any packets are sent or tcp_process_options is
5428  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5429  */
5430 static boolean_t
5431 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5432 {
5433 	conn_t *connp = tcp->tcp_connp;
5434 
5435 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5436 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5437 		int added;
5438 
5439 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5440 		    connp->conn_mac_exempt,
5441 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5442 			return (B_FALSE);
5443 
5444 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5445 		if (added == -1)
5446 			return (B_FALSE);
5447 		tcp->tcp_hdr_len += added;
5448 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5449 		tcp->tcp_ip_hdr_len += added;
5450 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5451 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5452 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5453 			    tcp->tcp_hdr_len);
5454 			if (added == -1)
5455 				return (B_FALSE);
5456 			tcp->tcp_hdr_len += added;
5457 			tcp->tcp_tcph = (tcph_t *)
5458 			    ((uchar_t *)tcp->tcp_tcph + added);
5459 			tcp->tcp_ip_hdr_len += added;
5460 		}
5461 	} else {
5462 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5463 
5464 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5465 		    connp->conn_mac_exempt,
5466 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5467 			return (B_FALSE);
5468 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5469 		    &tcp->tcp_label_len, optbuf) != 0)
5470 			return (B_FALSE);
5471 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5472 			return (B_FALSE);
5473 	}
5474 
5475 	connp->conn_ulp_labeled = 1;
5476 
5477 	return (B_TRUE);
5478 }
5479 
5480 /* BEGIN CSTYLED */
5481 /*
5482  *
5483  * The sockfs ACCEPT path:
5484  * =======================
5485  *
5486  * The eager is now established in its own perimeter as soon as SYN is
5487  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5488  * completes the accept processing on the acceptor STREAM. The sending
5489  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5490  * listener but a TLI/XTI listener completes the accept processing
5491  * on the listener perimeter.
5492  *
5493  * Common control flow for 3 way handshake:
5494  * ----------------------------------------
5495  *
5496  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5497  *					-> tcp_conn_request()
5498  *
5499  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5500  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5501  *
5502  * Sockfs ACCEPT Path:
5503  * -------------------
5504  *
5505  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5506  * as STREAM entry point)
5507  *
5508  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5509  *
5510  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5511  * association (we are not behind eager's squeue but sockfs is protecting us
5512  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5513  * is changed to point at tcp_wput().
5514  *
5515  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5516  * listener (done on listener's perimeter).
5517  *
5518  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5519  * accept.
5520  *
5521  * TLI/XTI client ACCEPT path:
5522  * ---------------------------
5523  *
5524  * soaccept() sends T_CONN_RES on the listener STREAM.
5525  *
5526  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5527  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5528  *
5529  * Locks:
5530  * ======
5531  *
5532  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5533  * and listeners->tcp_eager_next_q.
5534  *
5535  * Referencing:
5536  * ============
5537  *
5538  * 1) We start out in tcp_conn_request by eager placing a ref on
5539  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5540  *
5541  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5542  * doing so we place a ref on the eager. This ref is finally dropped at the
5543  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5544  * reference is dropped by the squeue framework.
5545  *
5546  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5547  *
5548  * The reference must be released by the same entity that added the reference
5549  * In the above scheme, the eager is the entity that adds and releases the
5550  * references. Note that tcp_accept_finish executes in the squeue of the eager
5551  * (albeit after it is attached to the acceptor stream). Though 1. executes
5552  * in the listener's squeue, the eager is nascent at this point and the
5553  * reference can be considered to have been added on behalf of the eager.
5554  *
5555  * Eager getting a Reset or listener closing:
5556  * ==========================================
5557  *
5558  * Once the listener and eager are linked, the listener never does the unlink.
5559  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5560  * a message on all eager perimeter. The eager then does the unlink, clears
5561  * any pointers to the listener's queue and drops the reference to the
5562  * listener. The listener waits in tcp_close outside the squeue until its
5563  * refcount has dropped to 1. This ensures that the listener has waited for
5564  * all eagers to clear their association with the listener.
5565  *
5566  * Similarly, if eager decides to go away, it can unlink itself and close.
5567  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5568  * the reference to eager is still valid because of the extra ref we put
5569  * in tcp_send_conn_ind.
5570  *
5571  * Listener can always locate the eager under the protection
5572  * of the listener->tcp_eager_lock, and then do a refhold
5573  * on the eager during the accept processing.
5574  *
5575  * The acceptor stream accesses the eager in the accept processing
5576  * based on the ref placed on eager before sending T_conn_ind.
5577  * The only entity that can negate this refhold is a listener close
5578  * which is mutually exclusive with an active acceptor stream.
5579  *
5580  * Eager's reference on the listener
5581  * ===================================
5582  *
5583  * If the accept happens (even on a closed eager) the eager drops its
5584  * reference on the listener at the start of tcp_accept_finish. If the
5585  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5586  * the reference is dropped in tcp_closei_local. If the listener closes,
5587  * the reference is dropped in tcp_eager_kill. In all cases the reference
5588  * is dropped while executing in the eager's context (squeue).
5589  */
5590 /* END CSTYLED */
5591 
5592 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5593 
5594 /*
5595  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5596  * tcp_rput_data will not see any SYN packets.
5597  */
5598 /* ARGSUSED */
5599 void
5600 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5601 {
5602 	tcph_t		*tcph;
5603 	uint32_t	seg_seq;
5604 	tcp_t		*eager;
5605 	uint_t		ipvers;
5606 	ipha_t		*ipha;
5607 	ip6_t		*ip6h;
5608 	int		err;
5609 	conn_t		*econnp = NULL;
5610 	squeue_t	*new_sqp;
5611 	mblk_t		*mp1;
5612 	uint_t 		ip_hdr_len;
5613 	conn_t		*connp = (conn_t *)arg;
5614 	tcp_t		*tcp = connp->conn_tcp;
5615 	cred_t		*credp;
5616 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5617 	ip_stack_t	*ipst;
5618 
5619 	if (tcp->tcp_state != TCPS_LISTEN)
5620 		goto error2;
5621 
5622 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5623 
5624 	mutex_enter(&tcp->tcp_eager_lock);
5625 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5626 		mutex_exit(&tcp->tcp_eager_lock);
5627 		TCP_STAT(tcps, tcp_listendrop);
5628 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5629 		if (tcp->tcp_debug) {
5630 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5631 			    "tcp_conn_request: listen backlog (max=%d) "
5632 			    "overflow (%d pending) on %s",
5633 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5634 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5635 		}
5636 		goto error2;
5637 	}
5638 
5639 	if (tcp->tcp_conn_req_cnt_q0 >=
5640 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5641 		/*
5642 		 * Q0 is full. Drop a pending half-open req from the queue
5643 		 * to make room for the new SYN req. Also mark the time we
5644 		 * drop a SYN.
5645 		 *
5646 		 * A more aggressive defense against SYN attack will
5647 		 * be to set the "tcp_syn_defense" flag now.
5648 		 */
5649 		TCP_STAT(tcps, tcp_listendropq0);
5650 		tcp->tcp_last_rcv_lbolt = lbolt64;
5651 		if (!tcp_drop_q0(tcp)) {
5652 			mutex_exit(&tcp->tcp_eager_lock);
5653 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5654 			if (tcp->tcp_debug) {
5655 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5656 				    "tcp_conn_request: listen half-open queue "
5657 				    "(max=%d) full (%d pending) on %s",
5658 				    tcps->tcps_conn_req_max_q0,
5659 				    tcp->tcp_conn_req_cnt_q0,
5660 				    tcp_display(tcp, NULL,
5661 				    DISP_PORT_ONLY));
5662 			}
5663 			goto error2;
5664 		}
5665 	}
5666 	mutex_exit(&tcp->tcp_eager_lock);
5667 
5668 	/*
5669 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5670 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5671 	 * link local address.  If IPSec is enabled, db_struioflag has
5672 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5673 	 * otherwise an error case if neither of them is set.
5674 	 */
5675 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5676 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5677 		DB_CKSUMSTART(mp) = 0;
5678 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5679 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5680 		if (econnp == NULL)
5681 			goto error2;
5682 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5683 		econnp->conn_sqp = new_sqp;
5684 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5685 		/*
5686 		 * mp is updated in tcp_get_ipsec_conn().
5687 		 */
5688 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5689 		if (econnp == NULL) {
5690 			/*
5691 			 * mp freed by tcp_get_ipsec_conn.
5692 			 */
5693 			return;
5694 		}
5695 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5696 	} else {
5697 		goto error2;
5698 	}
5699 
5700 	ASSERT(DB_TYPE(mp) == M_DATA);
5701 
5702 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5703 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5704 	ASSERT(OK_32PTR(mp->b_rptr));
5705 	if (ipvers == IPV4_VERSION) {
5706 		ipha = (ipha_t *)mp->b_rptr;
5707 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5708 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5709 	} else {
5710 		ip6h = (ip6_t *)mp->b_rptr;
5711 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5712 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5713 	}
5714 
5715 	if (tcp->tcp_family == AF_INET) {
5716 		ASSERT(ipvers == IPV4_VERSION);
5717 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5718 	} else {
5719 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5720 	}
5721 
5722 	if (err)
5723 		goto error3;
5724 
5725 	eager = econnp->conn_tcp;
5726 
5727 	/* Inherit various TCP parameters from the listener */
5728 	eager->tcp_naglim = tcp->tcp_naglim;
5729 	eager->tcp_first_timer_threshold =
5730 	    tcp->tcp_first_timer_threshold;
5731 	eager->tcp_second_timer_threshold =
5732 	    tcp->tcp_second_timer_threshold;
5733 
5734 	eager->tcp_first_ctimer_threshold =
5735 	    tcp->tcp_first_ctimer_threshold;
5736 	eager->tcp_second_ctimer_threshold =
5737 	    tcp->tcp_second_ctimer_threshold;
5738 
5739 	/*
5740 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5741 	 * If it does not, the eager's receive window will be set to the
5742 	 * listener's receive window later in this function.
5743 	 */
5744 	eager->tcp_rwnd = 0;
5745 
5746 	/*
5747 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5748 	 * calling tcp_process_options() where tcp_mss_set() is called
5749 	 * to set the initial cwnd.
5750 	 */
5751 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5752 
5753 	/*
5754 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5755 	 * zone id before the accept is completed in tcp_wput_accept().
5756 	 */
5757 	econnp->conn_zoneid = connp->conn_zoneid;
5758 	econnp->conn_allzones = connp->conn_allzones;
5759 
5760 	/* Copy nexthop information from listener to eager */
5761 	if (connp->conn_nexthop_set) {
5762 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5763 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5764 	}
5765 
5766 	/*
5767 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5768 	 * eager is accepted
5769 	 */
5770 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5771 	crhold(credp);
5772 
5773 	/*
5774 	 * If the caller has the process-wide flag set, then default to MAC
5775 	 * exempt mode.  This allows read-down to unlabeled hosts.
5776 	 */
5777 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5778 		econnp->conn_mac_exempt = B_TRUE;
5779 
5780 	if (is_system_labeled()) {
5781 		cred_t *cr;
5782 
5783 		if (connp->conn_mlp_type != mlptSingle) {
5784 			cr = econnp->conn_peercred = DB_CRED(mp);
5785 			if (cr != NULL)
5786 				crhold(cr);
5787 			else
5788 				cr = econnp->conn_cred;
5789 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5790 			    econnp, cred_t *, cr)
5791 		} else {
5792 			cr = econnp->conn_cred;
5793 			DTRACE_PROBE2(syn_accept, conn_t *,
5794 			    econnp, cred_t *, cr)
5795 		}
5796 
5797 		if (!tcp_update_label(eager, cr)) {
5798 			DTRACE_PROBE3(
5799 			    tx__ip__log__error__connrequest__tcp,
5800 			    char *, "eager connp(1) label on SYN mp(2) failed",
5801 			    conn_t *, econnp, mblk_t *, mp);
5802 			goto error3;
5803 		}
5804 	}
5805 
5806 	eager->tcp_hard_binding = B_TRUE;
5807 
5808 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5809 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5810 
5811 	CL_INET_CONNECT(eager);
5812 
5813 	/*
5814 	 * No need to check for multicast destination since ip will only pass
5815 	 * up multicasts to those that have expressed interest
5816 	 * TODO: what about rejecting broadcasts?
5817 	 * Also check that source is not a multicast or broadcast address.
5818 	 */
5819 	eager->tcp_state = TCPS_SYN_RCVD;
5820 
5821 
5822 	/*
5823 	 * There should be no ire in the mp as we are being called after
5824 	 * receiving the SYN.
5825 	 */
5826 	ASSERT(tcp_ire_mp(mp) == NULL);
5827 
5828 	/*
5829 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5830 	 */
5831 
5832 	if (tcp_adapt_ire(eager, NULL) == 0) {
5833 		/* Undo the bind_hash_insert */
5834 		tcp_bind_hash_remove(eager);
5835 		goto error3;
5836 	}
5837 
5838 	/* Process all TCP options. */
5839 	tcp_process_options(eager, tcph);
5840 
5841 	/* Is the other end ECN capable? */
5842 	if (tcps->tcps_ecn_permitted >= 1 &&
5843 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5844 		eager->tcp_ecn_ok = B_TRUE;
5845 	}
5846 
5847 	/*
5848 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5849 	 * window size changed via SO_RCVBUF option.  First round up the
5850 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5851 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5852 	 * setting.
5853 	 *
5854 	 * Note if there is a rpipe metric associated with the remote host,
5855 	 * we should not inherit receive window size from listener.
5856 	 */
5857 	eager->tcp_rwnd = MSS_ROUNDUP(
5858 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5859 	    eager->tcp_rwnd), eager->tcp_mss);
5860 	if (eager->tcp_snd_ws_ok)
5861 		tcp_set_ws_value(eager);
5862 	/*
5863 	 * Note that this is the only place tcp_rwnd_set() is called for
5864 	 * accepting a connection.  We need to call it here instead of
5865 	 * after the 3-way handshake because we need to tell the other
5866 	 * side our rwnd in the SYN-ACK segment.
5867 	 */
5868 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5869 
5870 	/*
5871 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5872 	 * via soaccept()->soinheritoptions() which essentially applies
5873 	 * all the listener options to the new STREAM. The options that we
5874 	 * need to take care of are:
5875 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5876 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5877 	 * SO_SNDBUF, SO_RCVBUF.
5878 	 *
5879 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5880 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5881 	 *		tcp_maxpsz_set() gets called later from
5882 	 *		tcp_accept_finish(), the option takes effect.
5883 	 *
5884 	 */
5885 	/* Set the TCP options */
5886 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5887 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5888 	eager->tcp_oobinline = tcp->tcp_oobinline;
5889 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5890 	eager->tcp_broadcast = tcp->tcp_broadcast;
5891 	eager->tcp_useloopback = tcp->tcp_useloopback;
5892 	eager->tcp_dontroute = tcp->tcp_dontroute;
5893 	eager->tcp_linger = tcp->tcp_linger;
5894 	eager->tcp_lingertime = tcp->tcp_lingertime;
5895 	if (tcp->tcp_ka_enabled)
5896 		eager->tcp_ka_enabled = 1;
5897 
5898 	/* Set the IP options */
5899 	econnp->conn_broadcast = connp->conn_broadcast;
5900 	econnp->conn_loopback = connp->conn_loopback;
5901 	econnp->conn_dontroute = connp->conn_dontroute;
5902 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5903 
5904 	/* Put a ref on the listener for the eager. */
5905 	CONN_INC_REF(connp);
5906 	mutex_enter(&tcp->tcp_eager_lock);
5907 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5908 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5909 	tcp->tcp_eager_next_q0 = eager;
5910 	eager->tcp_eager_prev_q0 = tcp;
5911 
5912 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5913 	eager->tcp_listener = tcp;
5914 	eager->tcp_saved_listener = tcp;
5915 
5916 	/*
5917 	 * Tag this detached tcp vector for later retrieval
5918 	 * by our listener client in tcp_accept().
5919 	 */
5920 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5921 	tcp->tcp_conn_req_cnt_q0++;
5922 	if (++tcp->tcp_conn_req_seqnum == -1) {
5923 		/*
5924 		 * -1 is "special" and defined in TPI as something
5925 		 * that should never be used in T_CONN_IND
5926 		 */
5927 		++tcp->tcp_conn_req_seqnum;
5928 	}
5929 	mutex_exit(&tcp->tcp_eager_lock);
5930 
5931 	if (tcp->tcp_syn_defense) {
5932 		/* Don't drop the SYN that comes from a good IP source */
5933 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5934 		if (addr_cache != NULL && eager->tcp_remote ==
5935 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5936 			eager->tcp_dontdrop = B_TRUE;
5937 		}
5938 	}
5939 
5940 	/*
5941 	 * We need to insert the eager in its own perimeter but as soon
5942 	 * as we do that, we expose the eager to the classifier and
5943 	 * should not touch any field outside the eager's perimeter.
5944 	 * So do all the work necessary before inserting the eager
5945 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5946 	 * will succeed but undo everything if it fails.
5947 	 */
5948 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5949 	eager->tcp_irs = seg_seq;
5950 	eager->tcp_rack = seg_seq;
5951 	eager->tcp_rnxt = seg_seq + 1;
5952 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5953 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5954 	eager->tcp_state = TCPS_SYN_RCVD;
5955 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5956 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5957 	if (mp1 == NULL) {
5958 		/*
5959 		 * Increment the ref count as we are going to
5960 		 * enqueueing an mp in squeue
5961 		 */
5962 		CONN_INC_REF(econnp);
5963 		goto error;
5964 	}
5965 	DB_CPID(mp1) = tcp->tcp_cpid;
5966 	eager->tcp_cpid = tcp->tcp_cpid;
5967 	eager->tcp_open_time = lbolt64;
5968 
5969 	/*
5970 	 * We need to start the rto timer. In normal case, we start
5971 	 * the timer after sending the packet on the wire (or at
5972 	 * least believing that packet was sent by waiting for
5973 	 * CALL_IP_WPUT() to return). Since this is the first packet
5974 	 * being sent on the wire for the eager, our initial tcp_rto
5975 	 * is at least tcp_rexmit_interval_min which is a fairly
5976 	 * large value to allow the algorithm to adjust slowly to large
5977 	 * fluctuations of RTT during first few transmissions.
5978 	 *
5979 	 * Starting the timer first and then sending the packet in this
5980 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5981 	 * is of the order of several 100ms and starting the timer
5982 	 * first and then sending the packet will result in difference
5983 	 * of few micro seconds.
5984 	 *
5985 	 * Without this optimization, we are forced to hold the fanout
5986 	 * lock across the ipcl_bind_insert() and sending the packet
5987 	 * so that we don't race against an incoming packet (maybe RST)
5988 	 * for this eager.
5989 	 *
5990 	 * It is necessary to acquire an extra reference on the eager
5991 	 * at this point and hold it until after tcp_send_data() to
5992 	 * ensure against an eager close race.
5993 	 */
5994 
5995 	CONN_INC_REF(eager->tcp_connp);
5996 
5997 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5998 
5999 	/*
6000 	 * Insert the eager in its own perimeter now. We are ready to deal
6001 	 * with any packets on eager.
6002 	 */
6003 	if (eager->tcp_ipversion == IPV4_VERSION) {
6004 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
6005 			goto error;
6006 		}
6007 	} else {
6008 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
6009 			goto error;
6010 		}
6011 	}
6012 
6013 	/* mark conn as fully-bound */
6014 	econnp->conn_fully_bound = B_TRUE;
6015 
6016 	/* Send the SYN-ACK */
6017 	tcp_send_data(eager, eager->tcp_wq, mp1);
6018 	CONN_DEC_REF(eager->tcp_connp);
6019 	freemsg(mp);
6020 
6021 	return;
6022 error:
6023 	freemsg(mp1);
6024 	eager->tcp_closemp_used = B_TRUE;
6025 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6026 	squeue_fill(econnp->conn_sqp, &eager->tcp_closemp, tcp_eager_kill,
6027 	    econnp, SQTAG_TCP_CONN_REQ_2);
6028 
6029 	/*
6030 	 * If a connection already exists, send the mp to that connections so
6031 	 * that it can be appropriately dealt with.
6032 	 */
6033 	ipst = tcps->tcps_netstack->netstack_ip;
6034 
6035 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
6036 		if (!IPCL_IS_CONNECTED(econnp)) {
6037 			/*
6038 			 * Something bad happened. ipcl_conn_insert()
6039 			 * failed because a connection already existed
6040 			 * in connected hash but we can't find it
6041 			 * anymore (someone blew it away). Just
6042 			 * free this message and hopefully remote
6043 			 * will retransmit at which time the SYN can be
6044 			 * treated as a new connection or dealth with
6045 			 * a TH_RST if a connection already exists.
6046 			 */
6047 			CONN_DEC_REF(econnp);
6048 			freemsg(mp);
6049 		} else {
6050 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6051 			    econnp, SQTAG_TCP_CONN_REQ_1);
6052 		}
6053 	} else {
6054 		/* Nobody wants this packet */
6055 		freemsg(mp);
6056 	}
6057 	return;
6058 error3:
6059 	CONN_DEC_REF(econnp);
6060 error2:
6061 	freemsg(mp);
6062 }
6063 
6064 /*
6065  * In an ideal case of vertical partition in NUMA architecture, its
6066  * beneficial to have the listener and all the incoming connections
6067  * tied to the same squeue. The other constraint is that incoming
6068  * connections should be tied to the squeue attached to interrupted
6069  * CPU for obvious locality reason so this leaves the listener to
6070  * be tied to the same squeue. Our only problem is that when listener
6071  * is binding, the CPU that will get interrupted by the NIC whose
6072  * IP address the listener is binding to is not even known. So
6073  * the code below allows us to change that binding at the time the
6074  * CPU is interrupted by virtue of incoming connection's squeue.
6075  *
6076  * This is usefull only in case of a listener bound to a specific IP
6077  * address. For other kind of listeners, they get bound the
6078  * very first time and there is no attempt to rebind them.
6079  */
6080 void
6081 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6082 {
6083 	conn_t		*connp = (conn_t *)arg;
6084 	squeue_t	*sqp = (squeue_t *)arg2;
6085 	squeue_t	*new_sqp;
6086 	uint32_t	conn_flags;
6087 
6088 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6089 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
6090 	} else {
6091 		goto done;
6092 	}
6093 
6094 	if (connp->conn_fanout == NULL)
6095 		goto done;
6096 
6097 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6098 		mutex_enter(&connp->conn_fanout->connf_lock);
6099 		mutex_enter(&connp->conn_lock);
6100 		/*
6101 		 * No one from read or write side can access us now
6102 		 * except for already queued packets on this squeue.
6103 		 * But since we haven't changed the squeue yet, they
6104 		 * can't execute. If they are processed after we have
6105 		 * changed the squeue, they are sent back to the
6106 		 * correct squeue down below.
6107 		 * But a listner close can race with processing of
6108 		 * incoming SYN. If incoming SYN processing changes
6109 		 * the squeue then the listener close which is waiting
6110 		 * to enter the squeue would operate on the wrong
6111 		 * squeue. Hence we don't change the squeue here unless
6112 		 * the refcount is exactly the minimum refcount. The
6113 		 * minimum refcount of 4 is counted as - 1 each for
6114 		 * TCP and IP, 1 for being in the classifier hash, and
6115 		 * 1 for the mblk being processed.
6116 		 */
6117 
6118 		if (connp->conn_ref != 4 ||
6119 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
6120 			mutex_exit(&connp->conn_lock);
6121 			mutex_exit(&connp->conn_fanout->connf_lock);
6122 			goto done;
6123 		}
6124 		if (connp->conn_sqp != new_sqp) {
6125 			while (connp->conn_sqp != new_sqp)
6126 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6127 		}
6128 
6129 		do {
6130 			conn_flags = connp->conn_flags;
6131 			conn_flags |= IPCL_FULLY_BOUND;
6132 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6133 			    conn_flags);
6134 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6135 
6136 		mutex_exit(&connp->conn_fanout->connf_lock);
6137 		mutex_exit(&connp->conn_lock);
6138 	}
6139 
6140 done:
6141 	if (connp->conn_sqp != sqp) {
6142 		CONN_INC_REF(connp);
6143 		squeue_fill(connp->conn_sqp, mp,
6144 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6145 	} else {
6146 		tcp_conn_request(connp, mp, sqp);
6147 	}
6148 }
6149 
6150 /*
6151  * Successful connect request processing begins when our client passes
6152  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6153  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6154  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6155  *   upstream <- tcp_rput()                <- IP
6156  * After various error checks are completed, tcp_connect() lays
6157  * the target address and port into the composite header template,
6158  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6159  * request followed by an IRE request, and passes the three mblk message
6160  * down to IP looking like this:
6161  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6162  * Processing continues in tcp_rput() when we receive the following message:
6163  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6164  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6165  * to fire off the connection request, and then passes the T_OK_ACK mblk
6166  * upstream that we filled in below.  There are, of course, numerous
6167  * error conditions along the way which truncate the processing described
6168  * above.
6169  */
6170 static void
6171 tcp_connect(tcp_t *tcp, mblk_t *mp)
6172 {
6173 	sin_t		*sin;
6174 	sin6_t		*sin6;
6175 	queue_t		*q = tcp->tcp_wq;
6176 	struct T_conn_req	*tcr;
6177 	ipaddr_t	*dstaddrp;
6178 	in_port_t	dstport;
6179 	uint_t		srcid;
6180 
6181 	tcr = (struct T_conn_req *)mp->b_rptr;
6182 
6183 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6184 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6185 		tcp_err_ack(tcp, mp, TPROTO, 0);
6186 		return;
6187 	}
6188 
6189 	/*
6190 	 * Determine packet type based on type of address passed in
6191 	 * the request should contain an IPv4 or IPv6 address.
6192 	 * Make sure that address family matches the type of
6193 	 * family of the the address passed down
6194 	 */
6195 	switch (tcr->DEST_length) {
6196 	default:
6197 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6198 		return;
6199 
6200 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6201 		/*
6202 		 * XXX: The check for valid DEST_length was not there
6203 		 * in earlier releases and some buggy
6204 		 * TLI apps (e.g Sybase) got away with not feeding
6205 		 * in sin_zero part of address.
6206 		 * We allow that bug to keep those buggy apps humming.
6207 		 * Test suites require the check on DEST_length.
6208 		 * We construct a new mblk with valid DEST_length
6209 		 * free the original so the rest of the code does
6210 		 * not have to keep track of this special shorter
6211 		 * length address case.
6212 		 */
6213 		mblk_t *nmp;
6214 		struct T_conn_req *ntcr;
6215 		sin_t *nsin;
6216 
6217 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6218 		    tcr->OPT_length, BPRI_HI);
6219 		if (nmp == NULL) {
6220 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6221 			return;
6222 		}
6223 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6224 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6225 		ntcr->PRIM_type = T_CONN_REQ;
6226 		ntcr->DEST_length = sizeof (sin_t);
6227 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6228 
6229 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6230 		*nsin = sin_null;
6231 		/* Get pointer to shorter address to copy from original mp */
6232 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6233 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6234 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6235 			freemsg(nmp);
6236 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6237 			return;
6238 		}
6239 		nsin->sin_family = sin->sin_family;
6240 		nsin->sin_port = sin->sin_port;
6241 		nsin->sin_addr = sin->sin_addr;
6242 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6243 		nmp->b_wptr = (uchar_t *)&nsin[1];
6244 		if (tcr->OPT_length != 0) {
6245 			ntcr->OPT_length = tcr->OPT_length;
6246 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6247 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6248 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6249 			    tcr->OPT_length);
6250 			nmp->b_wptr += tcr->OPT_length;
6251 		}
6252 		freemsg(mp);	/* original mp freed */
6253 		mp = nmp;	/* re-initialize original variables */
6254 		tcr = ntcr;
6255 	}
6256 	/* FALLTHRU */
6257 
6258 	case sizeof (sin_t):
6259 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6260 		    sizeof (sin_t));
6261 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6262 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6263 			return;
6264 		}
6265 		if (tcp->tcp_family != AF_INET ||
6266 		    sin->sin_family != AF_INET) {
6267 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6268 			return;
6269 		}
6270 		if (sin->sin_port == 0) {
6271 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6272 			return;
6273 		}
6274 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6275 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6276 			return;
6277 		}
6278 
6279 		break;
6280 
6281 	case sizeof (sin6_t):
6282 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6283 		    sizeof (sin6_t));
6284 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6285 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6286 			return;
6287 		}
6288 		if (tcp->tcp_family != AF_INET6 ||
6289 		    sin6->sin6_family != AF_INET6) {
6290 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6291 			return;
6292 		}
6293 		if (sin6->sin6_port == 0) {
6294 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6295 			return;
6296 		}
6297 		break;
6298 	}
6299 	/*
6300 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6301 	 * should key on their sequence number and cut them loose.
6302 	 */
6303 
6304 	/*
6305 	 * If options passed in, feed it for verification and handling
6306 	 */
6307 	if (tcr->OPT_length != 0) {
6308 		mblk_t	*ok_mp;
6309 		mblk_t	*discon_mp;
6310 		mblk_t  *conn_opts_mp;
6311 		int t_error, sys_error, do_disconnect;
6312 
6313 		conn_opts_mp = NULL;
6314 
6315 		if (tcp_conprim_opt_process(tcp, mp,
6316 		    &do_disconnect, &t_error, &sys_error) < 0) {
6317 			if (do_disconnect) {
6318 				ASSERT(t_error == 0 && sys_error == 0);
6319 				discon_mp = mi_tpi_discon_ind(NULL,
6320 				    ECONNREFUSED, 0);
6321 				if (!discon_mp) {
6322 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6323 					    TSYSERR, ENOMEM);
6324 					return;
6325 				}
6326 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6327 				if (!ok_mp) {
6328 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6329 					    TSYSERR, ENOMEM);
6330 					return;
6331 				}
6332 				qreply(q, ok_mp);
6333 				qreply(q, discon_mp); /* no flush! */
6334 			} else {
6335 				ASSERT(t_error != 0);
6336 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6337 				    sys_error);
6338 			}
6339 			return;
6340 		}
6341 		/*
6342 		 * Success in setting options, the mp option buffer represented
6343 		 * by OPT_length/offset has been potentially modified and
6344 		 * contains results of option processing. We copy it in
6345 		 * another mp to save it for potentially influencing returning
6346 		 * it in T_CONN_CONN.
6347 		 */
6348 		if (tcr->OPT_length != 0) { /* there are resulting options */
6349 			conn_opts_mp = copyb(mp);
6350 			if (!conn_opts_mp) {
6351 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6352 				    TSYSERR, ENOMEM);
6353 				return;
6354 			}
6355 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6356 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6357 			/*
6358 			 * Note:
6359 			 * These resulting option negotiation can include any
6360 			 * end-to-end negotiation options but there no such
6361 			 * thing (yet?) in our TCP/IP.
6362 			 */
6363 		}
6364 	}
6365 
6366 	/*
6367 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6368 	 * make sure that the template IP header in the tcp structure is an
6369 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6370 	 * need to this before we call tcp_bindi() so that the port lookup
6371 	 * code will look for ports in the correct port space (IPv4 and
6372 	 * IPv6 have separate port spaces).
6373 	 */
6374 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6375 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6376 		int err = 0;
6377 
6378 		err = tcp_header_init_ipv4(tcp);
6379 		if (err != 0) {
6380 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6381 			goto connect_failed;
6382 		}
6383 		if (tcp->tcp_lport != 0)
6384 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6385 	}
6386 
6387 	if (tcp->tcp_issocket) {
6388 		/*
6389 		 * TCP is _D_SODIRECT and sockfs is directly above so save
6390 		 * the shared sonode sodirect_t pointer (if any) to enable
6391 		 * TCP sodirect.
6392 		 */
6393 		tcp->tcp_sodirect = SOD_QTOSODP(tcp->tcp_rq);
6394 	}
6395 
6396 	switch (tcp->tcp_state) {
6397 	case TCPS_IDLE:
6398 		/*
6399 		 * We support quick connect, refer to comments in
6400 		 * tcp_connect_*()
6401 		 */
6402 		/* FALLTHRU */
6403 	case TCPS_BOUND:
6404 	case TCPS_LISTEN:
6405 		if (tcp->tcp_family == AF_INET6) {
6406 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6407 				tcp_connect_ipv6(tcp, mp,
6408 				    &sin6->sin6_addr,
6409 				    sin6->sin6_port, sin6->sin6_flowinfo,
6410 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6411 				return;
6412 			}
6413 			/*
6414 			 * Destination adress is mapped IPv6 address.
6415 			 * Source bound address should be unspecified or
6416 			 * IPv6 mapped address as well.
6417 			 */
6418 			if (!IN6_IS_ADDR_UNSPECIFIED(
6419 			    &tcp->tcp_bound_source_v6) &&
6420 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6421 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6422 				    EADDRNOTAVAIL);
6423 				break;
6424 			}
6425 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6426 			dstport = sin6->sin6_port;
6427 			srcid = sin6->__sin6_src_id;
6428 		} else {
6429 			dstaddrp = &sin->sin_addr.s_addr;
6430 			dstport = sin->sin_port;
6431 			srcid = 0;
6432 		}
6433 
6434 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6435 		return;
6436 	default:
6437 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6438 		break;
6439 	}
6440 	/*
6441 	 * Note: Code below is the "failure" case
6442 	 */
6443 	/* return error ack and blow away saved option results if any */
6444 connect_failed:
6445 	if (mp != NULL)
6446 		putnext(tcp->tcp_rq, mp);
6447 	else {
6448 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6449 		    TSYSERR, ENOMEM);
6450 	}
6451 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6452 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6453 }
6454 
6455 /*
6456  * Handle connect to IPv4 destinations, including connections for AF_INET6
6457  * sockets connecting to IPv4 mapped IPv6 destinations.
6458  */
6459 static void
6460 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6461     uint_t srcid)
6462 {
6463 	tcph_t	*tcph;
6464 	mblk_t	*mp1;
6465 	ipaddr_t dstaddr = *dstaddrp;
6466 	int32_t	oldstate;
6467 	uint16_t lport;
6468 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6469 
6470 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6471 
6472 	/* Check for attempt to connect to INADDR_ANY */
6473 	if (dstaddr == INADDR_ANY)  {
6474 		/*
6475 		 * SunOS 4.x and 4.3 BSD allow an application
6476 		 * to connect a TCP socket to INADDR_ANY.
6477 		 * When they do this, the kernel picks the
6478 		 * address of one interface and uses it
6479 		 * instead.  The kernel usually ends up
6480 		 * picking the address of the loopback
6481 		 * interface.  This is an undocumented feature.
6482 		 * However, we provide the same thing here
6483 		 * in order to have source and binary
6484 		 * compatibility with SunOS 4.x.
6485 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6486 		 * generate the T_CONN_CON.
6487 		 */
6488 		dstaddr = htonl(INADDR_LOOPBACK);
6489 		*dstaddrp = dstaddr;
6490 	}
6491 
6492 	/* Handle __sin6_src_id if socket not bound to an IP address */
6493 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6494 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6495 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6496 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6497 		    tcp->tcp_ipha->ipha_src);
6498 	}
6499 
6500 	/*
6501 	 * Don't let an endpoint connect to itself.  Note that
6502 	 * the test here does not catch the case where the
6503 	 * source IP addr was left unspecified by the user. In
6504 	 * this case, the source addr is set in tcp_adapt_ire()
6505 	 * using the reply to the T_BIND message that we send
6506 	 * down to IP here and the check is repeated in tcp_rput_other.
6507 	 */
6508 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6509 	    dstport == tcp->tcp_lport) {
6510 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6511 		goto failed;
6512 	}
6513 
6514 	tcp->tcp_ipha->ipha_dst = dstaddr;
6515 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6516 
6517 	/*
6518 	 * Massage a source route if any putting the first hop
6519 	 * in iph_dst. Compute a starting value for the checksum which
6520 	 * takes into account that the original iph_dst should be
6521 	 * included in the checksum but that ip will include the
6522 	 * first hop in the source route in the tcp checksum.
6523 	 */
6524 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6525 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6526 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6527 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6528 	if ((int)tcp->tcp_sum < 0)
6529 		tcp->tcp_sum--;
6530 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6531 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6532 	    (tcp->tcp_sum >> 16));
6533 	tcph = tcp->tcp_tcph;
6534 	*(uint16_t *)tcph->th_fport = dstport;
6535 	tcp->tcp_fport = dstport;
6536 
6537 	oldstate = tcp->tcp_state;
6538 	/*
6539 	 * At this point the remote destination address and remote port fields
6540 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6541 	 * have to see which state tcp was in so we can take apropriate action.
6542 	 */
6543 	if (oldstate == TCPS_IDLE) {
6544 		/*
6545 		 * We support a quick connect capability here, allowing
6546 		 * clients to transition directly from IDLE to SYN_SENT
6547 		 * tcp_bindi will pick an unused port, insert the connection
6548 		 * in the bind hash and transition to BOUND state.
6549 		 */
6550 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6551 		    tcp, B_TRUE);
6552 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6553 		    B_FALSE, B_FALSE);
6554 		if (lport == 0) {
6555 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6556 			goto failed;
6557 		}
6558 	}
6559 	tcp->tcp_state = TCPS_SYN_SENT;
6560 
6561 	/*
6562 	 * TODO: allow data with connect requests
6563 	 * by unlinking M_DATA trailers here and
6564 	 * linking them in behind the T_OK_ACK mblk.
6565 	 * The tcp_rput() bind ack handler would then
6566 	 * feed them to tcp_wput_data() rather than call
6567 	 * tcp_timer().
6568 	 */
6569 	mp = mi_tpi_ok_ack_alloc(mp);
6570 	if (!mp) {
6571 		tcp->tcp_state = oldstate;
6572 		goto failed;
6573 	}
6574 	if (tcp->tcp_family == AF_INET) {
6575 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6576 		    sizeof (ipa_conn_t));
6577 	} else {
6578 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6579 		    sizeof (ipa6_conn_t));
6580 	}
6581 	if (mp1) {
6582 		/*
6583 		 * We need to make sure that the conn_recv is set to a non-null
6584 		 * value before we insert the conn_t into the classifier table.
6585 		 * This is to avoid a race with an incoming packet which does
6586 		 * an ipcl_classify().
6587 		 */
6588 		tcp->tcp_connp->conn_recv = tcp_input;
6589 
6590 		/* Hang onto the T_OK_ACK for later. */
6591 		linkb(mp1, mp);
6592 		mblk_setcred(mp1, tcp->tcp_cred);
6593 		if (tcp->tcp_family == AF_INET)
6594 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6595 		else {
6596 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6597 			    &tcp->tcp_sticky_ipp);
6598 		}
6599 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6600 		tcp->tcp_active_open = 1;
6601 		/*
6602 		 * If the bind cannot complete immediately
6603 		 * IP will arrange to call tcp_rput_other
6604 		 * when the bind completes.
6605 		 */
6606 		if (mp1 != NULL)
6607 			tcp_rput_other(tcp, mp1);
6608 		return;
6609 	}
6610 	/* Error case */
6611 	tcp->tcp_state = oldstate;
6612 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6613 
6614 failed:
6615 	/* return error ack and blow away saved option results if any */
6616 	if (mp != NULL)
6617 		putnext(tcp->tcp_rq, mp);
6618 	else {
6619 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6620 		    TSYSERR, ENOMEM);
6621 	}
6622 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6623 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6624 
6625 }
6626 
6627 /*
6628  * Handle connect to IPv6 destinations.
6629  */
6630 static void
6631 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6632     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6633 {
6634 	tcph_t	*tcph;
6635 	mblk_t	*mp1;
6636 	ip6_rthdr_t *rth;
6637 	int32_t  oldstate;
6638 	uint16_t lport;
6639 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6640 
6641 	ASSERT(tcp->tcp_family == AF_INET6);
6642 
6643 	/*
6644 	 * If we're here, it means that the destination address is a native
6645 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6646 	 * reason why it might not be IPv6 is if the socket was bound to an
6647 	 * IPv4-mapped IPv6 address.
6648 	 */
6649 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6650 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6651 		goto failed;
6652 	}
6653 
6654 	/*
6655 	 * Interpret a zero destination to mean loopback.
6656 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6657 	 * generate the T_CONN_CON.
6658 	 */
6659 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6660 		*dstaddrp = ipv6_loopback;
6661 	}
6662 
6663 	/* Handle __sin6_src_id if socket not bound to an IP address */
6664 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6665 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6666 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6667 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6668 	}
6669 
6670 	/*
6671 	 * Take care of the scope_id now and add ip6i_t
6672 	 * if ip6i_t is not already allocated through TCP
6673 	 * sticky options. At this point tcp_ip6h does not
6674 	 * have dst info, thus use dstaddrp.
6675 	 */
6676 	if (scope_id != 0 &&
6677 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6678 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6679 		ip6i_t  *ip6i;
6680 
6681 		ipp->ipp_ifindex = scope_id;
6682 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6683 
6684 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6685 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6686 			/* Already allocated */
6687 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6688 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6689 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6690 		} else {
6691 			int reterr;
6692 
6693 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6694 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6695 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6696 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6697 			if (reterr != 0)
6698 				goto failed;
6699 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6700 		}
6701 	}
6702 
6703 	/*
6704 	 * Don't let an endpoint connect to itself.  Note that
6705 	 * the test here does not catch the case where the
6706 	 * source IP addr was left unspecified by the user. In
6707 	 * this case, the source addr is set in tcp_adapt_ire()
6708 	 * using the reply to the T_BIND message that we send
6709 	 * down to IP here and the check is repeated in tcp_rput_other.
6710 	 */
6711 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6712 	    (dstport == tcp->tcp_lport)) {
6713 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6714 		goto failed;
6715 	}
6716 
6717 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6718 	tcp->tcp_remote_v6 = *dstaddrp;
6719 	tcp->tcp_ip6h->ip6_vcf =
6720 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6721 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6722 
6723 
6724 	/*
6725 	 * Massage a routing header (if present) putting the first hop
6726 	 * in ip6_dst. Compute a starting value for the checksum which
6727 	 * takes into account that the original ip6_dst should be
6728 	 * included in the checksum but that ip will include the
6729 	 * first hop in the source route in the tcp checksum.
6730 	 */
6731 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6732 	if (rth != NULL) {
6733 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6734 		    tcps->tcps_netstack);
6735 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6736 		    (tcp->tcp_sum >> 16));
6737 	} else {
6738 		tcp->tcp_sum = 0;
6739 	}
6740 
6741 	tcph = tcp->tcp_tcph;
6742 	*(uint16_t *)tcph->th_fport = dstport;
6743 	tcp->tcp_fport = dstport;
6744 
6745 	oldstate = tcp->tcp_state;
6746 	/*
6747 	 * At this point the remote destination address and remote port fields
6748 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6749 	 * have to see which state tcp was in so we can take apropriate action.
6750 	 */
6751 	if (oldstate == TCPS_IDLE) {
6752 		/*
6753 		 * We support a quick connect capability here, allowing
6754 		 * clients to transition directly from IDLE to SYN_SENT
6755 		 * tcp_bindi will pick an unused port, insert the connection
6756 		 * in the bind hash and transition to BOUND state.
6757 		 */
6758 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6759 		    tcp, B_TRUE);
6760 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6761 		    B_FALSE, B_FALSE);
6762 		if (lport == 0) {
6763 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6764 			goto failed;
6765 		}
6766 	}
6767 	tcp->tcp_state = TCPS_SYN_SENT;
6768 	/*
6769 	 * TODO: allow data with connect requests
6770 	 * by unlinking M_DATA trailers here and
6771 	 * linking them in behind the T_OK_ACK mblk.
6772 	 * The tcp_rput() bind ack handler would then
6773 	 * feed them to tcp_wput_data() rather than call
6774 	 * tcp_timer().
6775 	 */
6776 	mp = mi_tpi_ok_ack_alloc(mp);
6777 	if (!mp) {
6778 		tcp->tcp_state = oldstate;
6779 		goto failed;
6780 	}
6781 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6782 	if (mp1) {
6783 		/*
6784 		 * We need to make sure that the conn_recv is set to a non-null
6785 		 * value before we insert the conn_t into the classifier table.
6786 		 * This is to avoid a race with an incoming packet which does
6787 		 * an ipcl_classify().
6788 		 */
6789 		tcp->tcp_connp->conn_recv = tcp_input;
6790 
6791 		/* Hang onto the T_OK_ACK for later. */
6792 		linkb(mp1, mp);
6793 		mblk_setcred(mp1, tcp->tcp_cred);
6794 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6795 		    &tcp->tcp_sticky_ipp);
6796 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6797 		tcp->tcp_active_open = 1;
6798 		/* ip_bind_v6() may return ACK or ERROR */
6799 		if (mp1 != NULL)
6800 			tcp_rput_other(tcp, mp1);
6801 		return;
6802 	}
6803 	/* Error case */
6804 	tcp->tcp_state = oldstate;
6805 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6806 
6807 failed:
6808 	/* return error ack and blow away saved option results if any */
6809 	if (mp != NULL)
6810 		putnext(tcp->tcp_rq, mp);
6811 	else {
6812 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6813 		    TSYSERR, ENOMEM);
6814 	}
6815 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6816 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6817 }
6818 
6819 /*
6820  * We need a stream q for detached closing tcp connections
6821  * to use.  Our client hereby indicates that this q is the
6822  * one to use.
6823  */
6824 static void
6825 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6826 {
6827 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6828 	queue_t	*q = tcp->tcp_wq;
6829 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6830 
6831 #ifdef NS_DEBUG
6832 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6833 	    tcps->tcps_netstack->netstack_stackid);
6834 #endif
6835 	mp->b_datap->db_type = M_IOCACK;
6836 	iocp->ioc_count = 0;
6837 	mutex_enter(&tcps->tcps_g_q_lock);
6838 	if (tcps->tcps_g_q != NULL) {
6839 		mutex_exit(&tcps->tcps_g_q_lock);
6840 		iocp->ioc_error = EALREADY;
6841 	} else {
6842 		mblk_t *mp1;
6843 
6844 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6845 		if (mp1 == NULL) {
6846 			mutex_exit(&tcps->tcps_g_q_lock);
6847 			iocp->ioc_error = ENOMEM;
6848 		} else {
6849 			tcps->tcps_g_q = tcp->tcp_rq;
6850 			mutex_exit(&tcps->tcps_g_q_lock);
6851 			iocp->ioc_error = 0;
6852 			iocp->ioc_rval = 0;
6853 			/*
6854 			 * We are passing tcp_sticky_ipp as NULL
6855 			 * as it is not useful for tcp_default queue
6856 			 *
6857 			 * Set conn_recv just in case.
6858 			 */
6859 			tcp->tcp_connp->conn_recv = tcp_conn_request;
6860 
6861 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6862 			if (mp1 != NULL)
6863 				tcp_rput_other(tcp, mp1);
6864 		}
6865 	}
6866 	qreply(q, mp);
6867 }
6868 
6869 /*
6870  * Our client hereby directs us to reject the connection request
6871  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6872  * of sending the appropriate RST, not an ICMP error.
6873  */
6874 static void
6875 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6876 {
6877 	tcp_t	*ltcp = NULL;
6878 	t_scalar_t seqnum;
6879 	conn_t	*connp;
6880 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6881 
6882 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6883 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6884 		tcp_err_ack(tcp, mp, TPROTO, 0);
6885 		return;
6886 	}
6887 
6888 	/*
6889 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6890 	 * when the stream is in BOUND state. Do not send a reset,
6891 	 * since the destination IP address is not valid, and it can
6892 	 * be the initialized value of all zeros (broadcast address).
6893 	 *
6894 	 * If TCP has sent down a bind request to IP and has not
6895 	 * received the reply, reject the request.  Otherwise, TCP
6896 	 * will be confused.
6897 	 */
6898 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6899 		if (tcp->tcp_debug) {
6900 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6901 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6902 		}
6903 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6904 		return;
6905 	}
6906 
6907 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6908 
6909 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6910 
6911 		/*
6912 		 * According to TPI, for non-listeners, ignore seqnum
6913 		 * and disconnect.
6914 		 * Following interpretation of -1 seqnum is historical
6915 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6916 		 * a valid seqnum should not be -1).
6917 		 *
6918 		 *	-1 means disconnect everything
6919 		 *	regardless even on a listener.
6920 		 */
6921 
6922 		int old_state = tcp->tcp_state;
6923 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6924 
6925 		/*
6926 		 * The connection can't be on the tcp_time_wait_head list
6927 		 * since it is not detached.
6928 		 */
6929 		ASSERT(tcp->tcp_time_wait_next == NULL);
6930 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6931 		ASSERT(tcp->tcp_time_wait_expire == 0);
6932 		ltcp = NULL;
6933 		/*
6934 		 * If it used to be a listener, check to make sure no one else
6935 		 * has taken the port before switching back to LISTEN state.
6936 		 */
6937 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6938 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6939 			    tcp->tcp_ipha->ipha_src,
6940 			    tcp->tcp_connp->conn_zoneid, ipst);
6941 			if (connp != NULL)
6942 				ltcp = connp->conn_tcp;
6943 		} else {
6944 			/* Allow tcp_bound_if listeners? */
6945 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6946 			    &tcp->tcp_ip6h->ip6_src, 0,
6947 			    tcp->tcp_connp->conn_zoneid, ipst);
6948 			if (connp != NULL)
6949 				ltcp = connp->conn_tcp;
6950 		}
6951 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6952 			tcp->tcp_state = TCPS_LISTEN;
6953 		} else if (old_state > TCPS_BOUND) {
6954 			tcp->tcp_conn_req_max = 0;
6955 			tcp->tcp_state = TCPS_BOUND;
6956 		}
6957 		if (ltcp != NULL)
6958 			CONN_DEC_REF(ltcp->tcp_connp);
6959 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6960 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6961 		} else if (old_state == TCPS_ESTABLISHED ||
6962 		    old_state == TCPS_CLOSE_WAIT) {
6963 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6964 		}
6965 
6966 		if (tcp->tcp_fused)
6967 			tcp_unfuse(tcp);
6968 
6969 		mutex_enter(&tcp->tcp_eager_lock);
6970 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6971 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6972 			tcp_eager_cleanup(tcp, 0);
6973 		}
6974 		mutex_exit(&tcp->tcp_eager_lock);
6975 
6976 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6977 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6978 
6979 		tcp_reinit(tcp);
6980 
6981 		if (old_state >= TCPS_ESTABLISHED) {
6982 			/* Send M_FLUSH according to TPI */
6983 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6984 		}
6985 		mp = mi_tpi_ok_ack_alloc(mp);
6986 		if (mp)
6987 			putnext(tcp->tcp_rq, mp);
6988 		return;
6989 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6990 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
6991 		return;
6992 	}
6993 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6994 		/* Send M_FLUSH according to TPI */
6995 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6996 	}
6997 	mp = mi_tpi_ok_ack_alloc(mp);
6998 	if (mp)
6999 		putnext(tcp->tcp_rq, mp);
7000 }
7001 
7002 /*
7003  * Diagnostic routine used to return a string associated with the tcp state.
7004  * Note that if the caller does not supply a buffer, it will use an internal
7005  * static string.  This means that if multiple threads call this function at
7006  * the same time, output can be corrupted...  Note also that this function
7007  * does not check the size of the supplied buffer.  The caller has to make
7008  * sure that it is big enough.
7009  */
7010 static char *
7011 tcp_display(tcp_t *tcp, char *sup_buf, char format)
7012 {
7013 	char		buf1[30];
7014 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
7015 	char		*buf;
7016 	char		*cp;
7017 	in6_addr_t	local, remote;
7018 	char		local_addrbuf[INET6_ADDRSTRLEN];
7019 	char		remote_addrbuf[INET6_ADDRSTRLEN];
7020 
7021 	if (sup_buf != NULL)
7022 		buf = sup_buf;
7023 	else
7024 		buf = priv_buf;
7025 
7026 	if (tcp == NULL)
7027 		return ("NULL_TCP");
7028 	switch (tcp->tcp_state) {
7029 	case TCPS_CLOSED:
7030 		cp = "TCP_CLOSED";
7031 		break;
7032 	case TCPS_IDLE:
7033 		cp = "TCP_IDLE";
7034 		break;
7035 	case TCPS_BOUND:
7036 		cp = "TCP_BOUND";
7037 		break;
7038 	case TCPS_LISTEN:
7039 		cp = "TCP_LISTEN";
7040 		break;
7041 	case TCPS_SYN_SENT:
7042 		cp = "TCP_SYN_SENT";
7043 		break;
7044 	case TCPS_SYN_RCVD:
7045 		cp = "TCP_SYN_RCVD";
7046 		break;
7047 	case TCPS_ESTABLISHED:
7048 		cp = "TCP_ESTABLISHED";
7049 		break;
7050 	case TCPS_CLOSE_WAIT:
7051 		cp = "TCP_CLOSE_WAIT";
7052 		break;
7053 	case TCPS_FIN_WAIT_1:
7054 		cp = "TCP_FIN_WAIT_1";
7055 		break;
7056 	case TCPS_CLOSING:
7057 		cp = "TCP_CLOSING";
7058 		break;
7059 	case TCPS_LAST_ACK:
7060 		cp = "TCP_LAST_ACK";
7061 		break;
7062 	case TCPS_FIN_WAIT_2:
7063 		cp = "TCP_FIN_WAIT_2";
7064 		break;
7065 	case TCPS_TIME_WAIT:
7066 		cp = "TCP_TIME_WAIT";
7067 		break;
7068 	default:
7069 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7070 		cp = buf1;
7071 		break;
7072 	}
7073 	switch (format) {
7074 	case DISP_ADDR_AND_PORT:
7075 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7076 			/*
7077 			 * Note that we use the remote address in the tcp_b
7078 			 * structure.  This means that it will print out
7079 			 * the real destination address, not the next hop's
7080 			 * address if source routing is used.
7081 			 */
7082 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7083 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7084 
7085 		} else {
7086 			local = tcp->tcp_ip_src_v6;
7087 			remote = tcp->tcp_remote_v6;
7088 		}
7089 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7090 		    sizeof (local_addrbuf));
7091 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7092 		    sizeof (remote_addrbuf));
7093 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7094 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7095 		    ntohs(tcp->tcp_fport), cp);
7096 		break;
7097 	case DISP_PORT_ONLY:
7098 	default:
7099 		(void) mi_sprintf(buf, "[%u, %u] %s",
7100 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7101 		break;
7102 	}
7103 
7104 	return (buf);
7105 }
7106 
7107 /*
7108  * Called via squeue to get on to eager's perimeter. It sends a
7109  * TH_RST if eager is in the fanout table. The listener wants the
7110  * eager to disappear either by means of tcp_eager_blowoff() or
7111  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
7112  * called (via squeue) if the eager cannot be inserted in the
7113  * fanout table in tcp_conn_request().
7114  */
7115 /* ARGSUSED */
7116 void
7117 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7118 {
7119 	conn_t	*econnp = (conn_t *)arg;
7120 	tcp_t	*eager = econnp->conn_tcp;
7121 	tcp_t	*listener = eager->tcp_listener;
7122 	tcp_stack_t	*tcps = eager->tcp_tcps;
7123 
7124 	/*
7125 	 * We could be called because listener is closing. Since
7126 	 * the eager is using listener's queue's, its not safe.
7127 	 * Better use the default queue just to send the TH_RST
7128 	 * out.
7129 	 */
7130 	ASSERT(tcps->tcps_g_q != NULL);
7131 	eager->tcp_rq = tcps->tcps_g_q;
7132 	eager->tcp_wq = WR(tcps->tcps_g_q);
7133 
7134 	/*
7135 	 * An eager's conn_fanout will be NULL if it's a duplicate
7136 	 * for an existing 4-tuples in the conn fanout table.
7137 	 * We don't want to send an RST out in such case.
7138 	 */
7139 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
7140 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7141 		    eager, eager->tcp_snxt, 0, TH_RST);
7142 	}
7143 
7144 	/* We are here because listener wants this eager gone */
7145 	if (listener != NULL) {
7146 		mutex_enter(&listener->tcp_eager_lock);
7147 		tcp_eager_unlink(eager);
7148 		if (eager->tcp_tconnind_started) {
7149 			/*
7150 			 * The eager has sent a conn_ind up to the
7151 			 * listener but listener decides to close
7152 			 * instead. We need to drop the extra ref
7153 			 * placed on eager in tcp_rput_data() before
7154 			 * sending the conn_ind to listener.
7155 			 */
7156 			CONN_DEC_REF(econnp);
7157 		}
7158 		mutex_exit(&listener->tcp_eager_lock);
7159 		CONN_DEC_REF(listener->tcp_connp);
7160 	}
7161 
7162 	if (eager->tcp_state > TCPS_BOUND)
7163 		tcp_close_detached(eager);
7164 }
7165 
7166 /*
7167  * Reset any eager connection hanging off this listener marked
7168  * with 'seqnum' and then reclaim it's resources.
7169  */
7170 static boolean_t
7171 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7172 {
7173 	tcp_t	*eager;
7174 	mblk_t 	*mp;
7175 	tcp_stack_t	*tcps = listener->tcp_tcps;
7176 
7177 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
7178 	eager = listener;
7179 	mutex_enter(&listener->tcp_eager_lock);
7180 	do {
7181 		eager = eager->tcp_eager_next_q;
7182 		if (eager == NULL) {
7183 			mutex_exit(&listener->tcp_eager_lock);
7184 			return (B_FALSE);
7185 		}
7186 	} while (eager->tcp_conn_req_seqnum != seqnum);
7187 
7188 	if (eager->tcp_closemp_used) {
7189 		mutex_exit(&listener->tcp_eager_lock);
7190 		return (B_TRUE);
7191 	}
7192 	eager->tcp_closemp_used = B_TRUE;
7193 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7194 	CONN_INC_REF(eager->tcp_connp);
7195 	mutex_exit(&listener->tcp_eager_lock);
7196 	mp = &eager->tcp_closemp;
7197 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7198 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7199 	return (B_TRUE);
7200 }
7201 
7202 /*
7203  * Reset any eager connection hanging off this listener
7204  * and then reclaim it's resources.
7205  */
7206 static void
7207 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7208 {
7209 	tcp_t	*eager;
7210 	mblk_t	*mp;
7211 	tcp_stack_t	*tcps = listener->tcp_tcps;
7212 
7213 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7214 
7215 	if (!q0_only) {
7216 		/* First cleanup q */
7217 		TCP_STAT(tcps, tcp_eager_blowoff_q);
7218 		eager = listener->tcp_eager_next_q;
7219 		while (eager != NULL) {
7220 			if (!eager->tcp_closemp_used) {
7221 				eager->tcp_closemp_used = B_TRUE;
7222 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7223 				CONN_INC_REF(eager->tcp_connp);
7224 				mp = &eager->tcp_closemp;
7225 				squeue_fill(eager->tcp_connp->conn_sqp, mp,
7226 				    tcp_eager_kill, eager->tcp_connp,
7227 				    SQTAG_TCP_EAGER_CLEANUP);
7228 			}
7229 			eager = eager->tcp_eager_next_q;
7230 		}
7231 	}
7232 	/* Then cleanup q0 */
7233 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
7234 	eager = listener->tcp_eager_next_q0;
7235 	while (eager != listener) {
7236 		if (!eager->tcp_closemp_used) {
7237 			eager->tcp_closemp_used = B_TRUE;
7238 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7239 			CONN_INC_REF(eager->tcp_connp);
7240 			mp = &eager->tcp_closemp;
7241 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7242 			    tcp_eager_kill, eager->tcp_connp,
7243 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
7244 		}
7245 		eager = eager->tcp_eager_next_q0;
7246 	}
7247 }
7248 
7249 /*
7250  * If we are an eager connection hanging off a listener that hasn't
7251  * formally accepted the connection yet, get off his list and blow off
7252  * any data that we have accumulated.
7253  */
7254 static void
7255 tcp_eager_unlink(tcp_t *tcp)
7256 {
7257 	tcp_t	*listener = tcp->tcp_listener;
7258 
7259 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7260 	ASSERT(listener != NULL);
7261 	if (tcp->tcp_eager_next_q0 != NULL) {
7262 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7263 
7264 		/* Remove the eager tcp from q0 */
7265 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7266 		    tcp->tcp_eager_prev_q0;
7267 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7268 		    tcp->tcp_eager_next_q0;
7269 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7270 		listener->tcp_conn_req_cnt_q0--;
7271 
7272 		tcp->tcp_eager_next_q0 = NULL;
7273 		tcp->tcp_eager_prev_q0 = NULL;
7274 
7275 		/*
7276 		 * Take the eager out, if it is in the list of droppable
7277 		 * eagers.
7278 		 */
7279 		MAKE_UNDROPPABLE(tcp);
7280 
7281 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7282 			/* we have timed out before */
7283 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7284 			listener->tcp_syn_rcvd_timeout--;
7285 		}
7286 	} else {
7287 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7288 		tcp_t	*prev = NULL;
7289 
7290 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7291 			if (tcpp[0] == tcp) {
7292 				if (listener->tcp_eager_last_q == tcp) {
7293 					/*
7294 					 * If we are unlinking the last
7295 					 * element on the list, adjust
7296 					 * tail pointer. Set tail pointer
7297 					 * to nil when list is empty.
7298 					 */
7299 					ASSERT(tcp->tcp_eager_next_q == NULL);
7300 					if (listener->tcp_eager_last_q ==
7301 					    listener->tcp_eager_next_q) {
7302 						listener->tcp_eager_last_q =
7303 						    NULL;
7304 					} else {
7305 						/*
7306 						 * We won't get here if there
7307 						 * is only one eager in the
7308 						 * list.
7309 						 */
7310 						ASSERT(prev != NULL);
7311 						listener->tcp_eager_last_q =
7312 						    prev;
7313 					}
7314 				}
7315 				tcpp[0] = tcp->tcp_eager_next_q;
7316 				tcp->tcp_eager_next_q = NULL;
7317 				tcp->tcp_eager_last_q = NULL;
7318 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7319 				listener->tcp_conn_req_cnt_q--;
7320 				break;
7321 			}
7322 			prev = tcpp[0];
7323 		}
7324 	}
7325 	tcp->tcp_listener = NULL;
7326 }
7327 
7328 /* Shorthand to generate and send TPI error acks to our client */
7329 static void
7330 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7331 {
7332 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7333 		putnext(tcp->tcp_rq, mp);
7334 }
7335 
7336 /* Shorthand to generate and send TPI error acks to our client */
7337 static void
7338 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7339     int t_error, int sys_error)
7340 {
7341 	struct T_error_ack	*teackp;
7342 
7343 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7344 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7345 		teackp = (struct T_error_ack *)mp->b_rptr;
7346 		teackp->ERROR_prim = primitive;
7347 		teackp->TLI_error = t_error;
7348 		teackp->UNIX_error = sys_error;
7349 		putnext(tcp->tcp_rq, mp);
7350 	}
7351 }
7352 
7353 /*
7354  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7355  * but instead the code relies on:
7356  * - the fact that the address of the array and its size never changes
7357  * - the atomic assignment of the elements of the array
7358  */
7359 /* ARGSUSED */
7360 static int
7361 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7362 {
7363 	int i;
7364 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7365 
7366 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7367 		if (tcps->tcps_g_epriv_ports[i] != 0)
7368 			(void) mi_mpprintf(mp, "%d ",
7369 			    tcps->tcps_g_epriv_ports[i]);
7370 	}
7371 	return (0);
7372 }
7373 
7374 /*
7375  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7376  * threads from changing it at the same time.
7377  */
7378 /* ARGSUSED */
7379 static int
7380 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7381     cred_t *cr)
7382 {
7383 	long	new_value;
7384 	int	i;
7385 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7386 
7387 	/*
7388 	 * Fail the request if the new value does not lie within the
7389 	 * port number limits.
7390 	 */
7391 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7392 	    new_value <= 0 || new_value >= 65536) {
7393 		return (EINVAL);
7394 	}
7395 
7396 	mutex_enter(&tcps->tcps_epriv_port_lock);
7397 	/* Check if the value is already in the list */
7398 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7399 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7400 			mutex_exit(&tcps->tcps_epriv_port_lock);
7401 			return (EEXIST);
7402 		}
7403 	}
7404 	/* Find an empty slot */
7405 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7406 		if (tcps->tcps_g_epriv_ports[i] == 0)
7407 			break;
7408 	}
7409 	if (i == tcps->tcps_g_num_epriv_ports) {
7410 		mutex_exit(&tcps->tcps_epriv_port_lock);
7411 		return (EOVERFLOW);
7412 	}
7413 	/* Set the new value */
7414 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7415 	mutex_exit(&tcps->tcps_epriv_port_lock);
7416 	return (0);
7417 }
7418 
7419 /*
7420  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7421  * threads from changing it at the same time.
7422  */
7423 /* ARGSUSED */
7424 static int
7425 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7426     cred_t *cr)
7427 {
7428 	long	new_value;
7429 	int	i;
7430 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7431 
7432 	/*
7433 	 * Fail the request if the new value does not lie within the
7434 	 * port number limits.
7435 	 */
7436 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7437 	    new_value >= 65536) {
7438 		return (EINVAL);
7439 	}
7440 
7441 	mutex_enter(&tcps->tcps_epriv_port_lock);
7442 	/* Check that the value is already in the list */
7443 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7444 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7445 			break;
7446 	}
7447 	if (i == tcps->tcps_g_num_epriv_ports) {
7448 		mutex_exit(&tcps->tcps_epriv_port_lock);
7449 		return (ESRCH);
7450 	}
7451 	/* Clear the value */
7452 	tcps->tcps_g_epriv_ports[i] = 0;
7453 	mutex_exit(&tcps->tcps_epriv_port_lock);
7454 	return (0);
7455 }
7456 
7457 /* Return the TPI/TLI equivalent of our current tcp_state */
7458 static int
7459 tcp_tpistate(tcp_t *tcp)
7460 {
7461 	switch (tcp->tcp_state) {
7462 	case TCPS_IDLE:
7463 		return (TS_UNBND);
7464 	case TCPS_LISTEN:
7465 		/*
7466 		 * Return whether there are outstanding T_CONN_IND waiting
7467 		 * for the matching T_CONN_RES. Therefore don't count q0.
7468 		 */
7469 		if (tcp->tcp_conn_req_cnt_q > 0)
7470 			return (TS_WRES_CIND);
7471 		else
7472 			return (TS_IDLE);
7473 	case TCPS_BOUND:
7474 		return (TS_IDLE);
7475 	case TCPS_SYN_SENT:
7476 		return (TS_WCON_CREQ);
7477 	case TCPS_SYN_RCVD:
7478 		/*
7479 		 * Note: assumption: this has to the active open SYN_RCVD.
7480 		 * The passive instance is detached in SYN_RCVD stage of
7481 		 * incoming connection processing so we cannot get request
7482 		 * for T_info_ack on it.
7483 		 */
7484 		return (TS_WACK_CRES);
7485 	case TCPS_ESTABLISHED:
7486 		return (TS_DATA_XFER);
7487 	case TCPS_CLOSE_WAIT:
7488 		return (TS_WREQ_ORDREL);
7489 	case TCPS_FIN_WAIT_1:
7490 		return (TS_WIND_ORDREL);
7491 	case TCPS_FIN_WAIT_2:
7492 		return (TS_WIND_ORDREL);
7493 
7494 	case TCPS_CLOSING:
7495 	case TCPS_LAST_ACK:
7496 	case TCPS_TIME_WAIT:
7497 	case TCPS_CLOSED:
7498 		/*
7499 		 * Following TS_WACK_DREQ7 is a rendition of "not
7500 		 * yet TS_IDLE" TPI state. There is no best match to any
7501 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7502 		 * choose a value chosen that will map to TLI/XTI level
7503 		 * state of TSTATECHNG (state is process of changing) which
7504 		 * captures what this dummy state represents.
7505 		 */
7506 		return (TS_WACK_DREQ7);
7507 	default:
7508 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7509 		    tcp->tcp_state, tcp_display(tcp, NULL,
7510 		    DISP_PORT_ONLY));
7511 		return (TS_UNBND);
7512 	}
7513 }
7514 
7515 static void
7516 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7517 {
7518 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7519 
7520 	if (tcp->tcp_family == AF_INET6)
7521 		*tia = tcp_g_t_info_ack_v6;
7522 	else
7523 		*tia = tcp_g_t_info_ack;
7524 	tia->CURRENT_state = tcp_tpistate(tcp);
7525 	tia->OPT_size = tcp_max_optsize;
7526 	if (tcp->tcp_mss == 0) {
7527 		/* Not yet set - tcp_open does not set mss */
7528 		if (tcp->tcp_ipversion == IPV4_VERSION)
7529 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7530 		else
7531 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7532 	} else {
7533 		tia->TIDU_size = tcp->tcp_mss;
7534 	}
7535 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7536 }
7537 
7538 /*
7539  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7540  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7541  * tcp_g_t_info_ack.  The current state of the stream is copied from
7542  * tcp_state.
7543  */
7544 static void
7545 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7546 {
7547 	t_uscalar_t		cap_bits1;
7548 	struct T_capability_ack	*tcap;
7549 
7550 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7551 		freemsg(mp);
7552 		return;
7553 	}
7554 
7555 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7556 
7557 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7558 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7559 	if (mp == NULL)
7560 		return;
7561 
7562 	tcap = (struct T_capability_ack *)mp->b_rptr;
7563 	tcap->CAP_bits1 = 0;
7564 
7565 	if (cap_bits1 & TC1_INFO) {
7566 		tcp_copy_info(&tcap->INFO_ack, tcp);
7567 		tcap->CAP_bits1 |= TC1_INFO;
7568 	}
7569 
7570 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7571 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7572 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7573 	}
7574 
7575 	putnext(tcp->tcp_rq, mp);
7576 }
7577 
7578 /*
7579  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7580  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7581  * The current state of the stream is copied from tcp_state.
7582  */
7583 static void
7584 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7585 {
7586 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7587 	    T_INFO_ACK);
7588 	if (!mp) {
7589 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7590 		return;
7591 	}
7592 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7593 	putnext(tcp->tcp_rq, mp);
7594 }
7595 
7596 /* Respond to the TPI addr request */
7597 static void
7598 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7599 {
7600 	sin_t	*sin;
7601 	mblk_t	*ackmp;
7602 	struct T_addr_ack *taa;
7603 
7604 	/* Make it large enough for worst case */
7605 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7606 	    2 * sizeof (sin6_t), 1);
7607 	if (ackmp == NULL) {
7608 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7609 		return;
7610 	}
7611 
7612 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7613 		tcp_addr_req_ipv6(tcp, ackmp);
7614 		return;
7615 	}
7616 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7617 
7618 	bzero(taa, sizeof (struct T_addr_ack));
7619 	ackmp->b_wptr = (uchar_t *)&taa[1];
7620 
7621 	taa->PRIM_type = T_ADDR_ACK;
7622 	ackmp->b_datap->db_type = M_PCPROTO;
7623 
7624 	/*
7625 	 * Note: Following code assumes 32 bit alignment of basic
7626 	 * data structures like sin_t and struct T_addr_ack.
7627 	 */
7628 	if (tcp->tcp_state >= TCPS_BOUND) {
7629 		/*
7630 		 * Fill in local address
7631 		 */
7632 		taa->LOCADDR_length = sizeof (sin_t);
7633 		taa->LOCADDR_offset = sizeof (*taa);
7634 
7635 		sin = (sin_t *)&taa[1];
7636 
7637 		/* Fill zeroes and then intialize non-zero fields */
7638 		*sin = sin_null;
7639 
7640 		sin->sin_family = AF_INET;
7641 
7642 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7643 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7644 
7645 		ackmp->b_wptr = (uchar_t *)&sin[1];
7646 
7647 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7648 			/*
7649 			 * Fill in Remote address
7650 			 */
7651 			taa->REMADDR_length = sizeof (sin_t);
7652 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7653 			    taa->LOCADDR_length);
7654 
7655 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7656 			*sin = sin_null;
7657 			sin->sin_family = AF_INET;
7658 			sin->sin_addr.s_addr = tcp->tcp_remote;
7659 			sin->sin_port = tcp->tcp_fport;
7660 
7661 			ackmp->b_wptr = (uchar_t *)&sin[1];
7662 		}
7663 	}
7664 	putnext(tcp->tcp_rq, ackmp);
7665 }
7666 
7667 /* Assumes that tcp_addr_req gets enough space and alignment */
7668 static void
7669 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7670 {
7671 	sin6_t	*sin6;
7672 	struct T_addr_ack *taa;
7673 
7674 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7675 	ASSERT(OK_32PTR(ackmp->b_rptr));
7676 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7677 	    2 * sizeof (sin6_t));
7678 
7679 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7680 
7681 	bzero(taa, sizeof (struct T_addr_ack));
7682 	ackmp->b_wptr = (uchar_t *)&taa[1];
7683 
7684 	taa->PRIM_type = T_ADDR_ACK;
7685 	ackmp->b_datap->db_type = M_PCPROTO;
7686 
7687 	/*
7688 	 * Note: Following code assumes 32 bit alignment of basic
7689 	 * data structures like sin6_t and struct T_addr_ack.
7690 	 */
7691 	if (tcp->tcp_state >= TCPS_BOUND) {
7692 		/*
7693 		 * Fill in local address
7694 		 */
7695 		taa->LOCADDR_length = sizeof (sin6_t);
7696 		taa->LOCADDR_offset = sizeof (*taa);
7697 
7698 		sin6 = (sin6_t *)&taa[1];
7699 		*sin6 = sin6_null;
7700 
7701 		sin6->sin6_family = AF_INET6;
7702 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7703 		sin6->sin6_port = tcp->tcp_lport;
7704 
7705 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7706 
7707 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7708 			/*
7709 			 * Fill in Remote address
7710 			 */
7711 			taa->REMADDR_length = sizeof (sin6_t);
7712 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7713 			    taa->LOCADDR_length);
7714 
7715 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7716 			*sin6 = sin6_null;
7717 			sin6->sin6_family = AF_INET6;
7718 			sin6->sin6_flowinfo =
7719 			    tcp->tcp_ip6h->ip6_vcf &
7720 			    ~IPV6_VERS_AND_FLOW_MASK;
7721 			sin6->sin6_addr = tcp->tcp_remote_v6;
7722 			sin6->sin6_port = tcp->tcp_fport;
7723 
7724 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7725 		}
7726 	}
7727 	putnext(tcp->tcp_rq, ackmp);
7728 }
7729 
7730 /*
7731  * Handle reinitialization of a tcp structure.
7732  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7733  */
7734 static void
7735 tcp_reinit(tcp_t *tcp)
7736 {
7737 	mblk_t	*mp;
7738 	int 	err;
7739 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7740 
7741 	TCP_STAT(tcps, tcp_reinit_calls);
7742 
7743 	/* tcp_reinit should never be called for detached tcp_t's */
7744 	ASSERT(tcp->tcp_listener == NULL);
7745 	ASSERT((tcp->tcp_family == AF_INET &&
7746 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7747 	    (tcp->tcp_family == AF_INET6 &&
7748 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7749 	    tcp->tcp_ipversion == IPV6_VERSION)));
7750 
7751 	/* Cancel outstanding timers */
7752 	tcp_timers_stop(tcp);
7753 
7754 	/*
7755 	 * Reset everything in the state vector, after updating global
7756 	 * MIB data from instance counters.
7757 	 */
7758 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7759 	tcp->tcp_ibsegs = 0;
7760 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7761 	tcp->tcp_obsegs = 0;
7762 
7763 	tcp_close_mpp(&tcp->tcp_xmit_head);
7764 	if (tcp->tcp_snd_zcopy_aware)
7765 		tcp_zcopy_notify(tcp);
7766 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7767 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7768 	mutex_enter(&tcp->tcp_non_sq_lock);
7769 	if (tcp->tcp_flow_stopped &&
7770 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7771 		tcp_clrqfull(tcp);
7772 	}
7773 	mutex_exit(&tcp->tcp_non_sq_lock);
7774 	tcp_close_mpp(&tcp->tcp_reass_head);
7775 	tcp->tcp_reass_tail = NULL;
7776 	if (tcp->tcp_rcv_list != NULL) {
7777 		/* Free b_next chain */
7778 		tcp_close_mpp(&tcp->tcp_rcv_list);
7779 		tcp->tcp_rcv_last_head = NULL;
7780 		tcp->tcp_rcv_last_tail = NULL;
7781 		tcp->tcp_rcv_cnt = 0;
7782 	}
7783 	tcp->tcp_rcv_last_tail = NULL;
7784 
7785 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7786 		freemsg(mp);
7787 		tcp->tcp_urp_mp = NULL;
7788 	}
7789 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7790 		freemsg(mp);
7791 		tcp->tcp_urp_mark_mp = NULL;
7792 	}
7793 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7794 		freeb(tcp->tcp_fused_sigurg_mp);
7795 		tcp->tcp_fused_sigurg_mp = NULL;
7796 	}
7797 
7798 	/*
7799 	 * Following is a union with two members which are
7800 	 * identical types and size so the following cleanup
7801 	 * is enough.
7802 	 */
7803 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7804 
7805 	CL_INET_DISCONNECT(tcp);
7806 
7807 	/*
7808 	 * The connection can't be on the tcp_time_wait_head list
7809 	 * since it is not detached.
7810 	 */
7811 	ASSERT(tcp->tcp_time_wait_next == NULL);
7812 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7813 	ASSERT(tcp->tcp_time_wait_expire == 0);
7814 
7815 	if (tcp->tcp_kssl_pending) {
7816 		tcp->tcp_kssl_pending = B_FALSE;
7817 
7818 		/* Don't reset if the initialized by bind. */
7819 		if (tcp->tcp_kssl_ent != NULL) {
7820 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7821 			    KSSL_NO_PROXY);
7822 		}
7823 	}
7824 	if (tcp->tcp_kssl_ctx != NULL) {
7825 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7826 		tcp->tcp_kssl_ctx = NULL;
7827 	}
7828 
7829 	/*
7830 	 * Reset/preserve other values
7831 	 */
7832 	tcp_reinit_values(tcp);
7833 	ipcl_hash_remove(tcp->tcp_connp);
7834 	conn_delete_ire(tcp->tcp_connp, NULL);
7835 	tcp_ipsec_cleanup(tcp);
7836 
7837 	if (tcp->tcp_conn_req_max != 0) {
7838 		/*
7839 		 * This is the case when a TLI program uses the same
7840 		 * transport end point to accept a connection.  This
7841 		 * makes the TCP both a listener and acceptor.  When
7842 		 * this connection is closed, we need to set the state
7843 		 * back to TCPS_LISTEN.  Make sure that the eager list
7844 		 * is reinitialized.
7845 		 *
7846 		 * Note that this stream is still bound to the four
7847 		 * tuples of the previous connection in IP.  If a new
7848 		 * SYN with different foreign address comes in, IP will
7849 		 * not find it and will send it to the global queue.  In
7850 		 * the global queue, TCP will do a tcp_lookup_listener()
7851 		 * to find this stream.  This works because this stream
7852 		 * is only removed from connected hash.
7853 		 *
7854 		 */
7855 		tcp->tcp_state = TCPS_LISTEN;
7856 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7857 		tcp->tcp_eager_next_drop_q0 = tcp;
7858 		tcp->tcp_eager_prev_drop_q0 = tcp;
7859 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7860 		if (tcp->tcp_family == AF_INET6) {
7861 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7862 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7863 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7864 		} else {
7865 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7866 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7867 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7868 		}
7869 	} else {
7870 		tcp->tcp_state = TCPS_BOUND;
7871 	}
7872 
7873 	/*
7874 	 * Initialize to default values
7875 	 * Can't fail since enough header template space already allocated
7876 	 * at open().
7877 	 */
7878 	err = tcp_init_values(tcp);
7879 	ASSERT(err == 0);
7880 	/* Restore state in tcp_tcph */
7881 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7882 	if (tcp->tcp_ipversion == IPV4_VERSION)
7883 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7884 	else
7885 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7886 	/*
7887 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7888 	 * since the lookup funcs can only lookup on tcp_t
7889 	 */
7890 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7891 
7892 	ASSERT(tcp->tcp_ptpbhn != NULL);
7893 	tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7894 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7895 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7896 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7897 }
7898 
7899 /*
7900  * Force values to zero that need be zero.
7901  * Do not touch values asociated with the BOUND or LISTEN state
7902  * since the connection will end up in that state after the reinit.
7903  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7904  * structure!
7905  */
7906 static void
7907 tcp_reinit_values(tcp)
7908 	tcp_t *tcp;
7909 {
7910 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7911 
7912 #ifndef	lint
7913 #define	DONTCARE(x)
7914 #define	PRESERVE(x)
7915 #else
7916 #define	DONTCARE(x)	((x) = (x))
7917 #define	PRESERVE(x)	((x) = (x))
7918 #endif	/* lint */
7919 
7920 	PRESERVE(tcp->tcp_bind_hash);
7921 	PRESERVE(tcp->tcp_ptpbhn);
7922 	PRESERVE(tcp->tcp_acceptor_hash);
7923 	PRESERVE(tcp->tcp_ptpahn);
7924 
7925 	/* Should be ASSERT NULL on these with new code! */
7926 	ASSERT(tcp->tcp_time_wait_next == NULL);
7927 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7928 	ASSERT(tcp->tcp_time_wait_expire == 0);
7929 	PRESERVE(tcp->tcp_state);
7930 	PRESERVE(tcp->tcp_rq);
7931 	PRESERVE(tcp->tcp_wq);
7932 
7933 	ASSERT(tcp->tcp_xmit_head == NULL);
7934 	ASSERT(tcp->tcp_xmit_last == NULL);
7935 	ASSERT(tcp->tcp_unsent == 0);
7936 	ASSERT(tcp->tcp_xmit_tail == NULL);
7937 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7938 
7939 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7940 	tcp->tcp_suna = 0;			/* Displayed in mib */
7941 	tcp->tcp_swnd = 0;
7942 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7943 
7944 	ASSERT(tcp->tcp_ibsegs == 0);
7945 	ASSERT(tcp->tcp_obsegs == 0);
7946 
7947 	if (tcp->tcp_iphc != NULL) {
7948 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7949 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7950 	}
7951 
7952 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7953 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7954 	DONTCARE(tcp->tcp_ipha);
7955 	DONTCARE(tcp->tcp_ip6h);
7956 	DONTCARE(tcp->tcp_ip_hdr_len);
7957 	DONTCARE(tcp->tcp_tcph);
7958 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7959 	tcp->tcp_valid_bits = 0;
7960 
7961 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7962 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7963 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7964 	tcp->tcp_last_rcv_lbolt = 0;
7965 
7966 	tcp->tcp_init_cwnd = 0;
7967 
7968 	tcp->tcp_urp_last_valid = 0;
7969 	tcp->tcp_hard_binding = 0;
7970 	tcp->tcp_hard_bound = 0;
7971 	PRESERVE(tcp->tcp_cred);
7972 	PRESERVE(tcp->tcp_cpid);
7973 	PRESERVE(tcp->tcp_open_time);
7974 	PRESERVE(tcp->tcp_exclbind);
7975 
7976 	tcp->tcp_fin_acked = 0;
7977 	tcp->tcp_fin_rcvd = 0;
7978 	tcp->tcp_fin_sent = 0;
7979 	tcp->tcp_ordrel_done = 0;
7980 
7981 	tcp->tcp_debug = 0;
7982 	tcp->tcp_dontroute = 0;
7983 	tcp->tcp_broadcast = 0;
7984 
7985 	tcp->tcp_useloopback = 0;
7986 	tcp->tcp_reuseaddr = 0;
7987 	tcp->tcp_oobinline = 0;
7988 	tcp->tcp_dgram_errind = 0;
7989 
7990 	tcp->tcp_detached = 0;
7991 	tcp->tcp_bind_pending = 0;
7992 	tcp->tcp_unbind_pending = 0;
7993 	tcp->tcp_deferred_clean_death = 0;
7994 
7995 	tcp->tcp_snd_ws_ok = B_FALSE;
7996 	tcp->tcp_snd_ts_ok = B_FALSE;
7997 	tcp->tcp_linger = 0;
7998 	tcp->tcp_ka_enabled = 0;
7999 	tcp->tcp_zero_win_probe = 0;
8000 
8001 	tcp->tcp_loopback = 0;
8002 	tcp->tcp_localnet = 0;
8003 	tcp->tcp_syn_defense = 0;
8004 	tcp->tcp_set_timer = 0;
8005 
8006 	tcp->tcp_active_open = 0;
8007 	ASSERT(tcp->tcp_timeout == B_FALSE);
8008 	tcp->tcp_rexmit = B_FALSE;
8009 	tcp->tcp_xmit_zc_clean = B_FALSE;
8010 
8011 	tcp->tcp_snd_sack_ok = B_FALSE;
8012 	PRESERVE(tcp->tcp_recvdstaddr);
8013 	tcp->tcp_hwcksum = B_FALSE;
8014 
8015 	tcp->tcp_ire_ill_check_done = B_FALSE;
8016 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
8017 
8018 	tcp->tcp_mdt = B_FALSE;
8019 	tcp->tcp_mdt_hdr_head = 0;
8020 	tcp->tcp_mdt_hdr_tail = 0;
8021 
8022 	tcp->tcp_conn_def_q0 = 0;
8023 	tcp->tcp_ip_forward_progress = B_FALSE;
8024 	tcp->tcp_anon_priv_bind = 0;
8025 	tcp->tcp_ecn_ok = B_FALSE;
8026 
8027 	tcp->tcp_cwr = B_FALSE;
8028 	tcp->tcp_ecn_echo_on = B_FALSE;
8029 
8030 	if (tcp->tcp_sack_info != NULL) {
8031 		if (tcp->tcp_notsack_list != NULL) {
8032 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
8033 		}
8034 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
8035 		tcp->tcp_sack_info = NULL;
8036 	}
8037 
8038 	tcp->tcp_rcv_ws = 0;
8039 	tcp->tcp_snd_ws = 0;
8040 	tcp->tcp_ts_recent = 0;
8041 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
8042 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
8043 	tcp->tcp_if_mtu = 0;
8044 
8045 	ASSERT(tcp->tcp_reass_head == NULL);
8046 	ASSERT(tcp->tcp_reass_tail == NULL);
8047 
8048 	tcp->tcp_cwnd_cnt = 0;
8049 
8050 	ASSERT(tcp->tcp_rcv_list == NULL);
8051 	ASSERT(tcp->tcp_rcv_last_head == NULL);
8052 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
8053 	ASSERT(tcp->tcp_rcv_cnt == 0);
8054 
8055 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8056 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8057 	tcp->tcp_csuna = 0;
8058 
8059 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8060 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8061 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8062 	tcp->tcp_rtt_update = 0;
8063 
8064 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8065 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8066 
8067 	tcp->tcp_rack = 0;			/* Displayed in mib */
8068 	tcp->tcp_rack_cnt = 0;
8069 	tcp->tcp_rack_cur_max = 0;
8070 	tcp->tcp_rack_abs_max = 0;
8071 
8072 	tcp->tcp_max_swnd = 0;
8073 
8074 	ASSERT(tcp->tcp_listener == NULL);
8075 
8076 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8077 
8078 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8079 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8080 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8081 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8082 
8083 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8084 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8085 	PRESERVE(tcp->tcp_conn_req_max);
8086 	PRESERVE(tcp->tcp_conn_req_seqnum);
8087 
8088 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8089 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8090 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8091 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8092 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8093 
8094 	tcp->tcp_lingertime = 0;
8095 
8096 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8097 	ASSERT(tcp->tcp_urp_mp == NULL);
8098 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8099 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8100 
8101 	ASSERT(tcp->tcp_eager_next_q == NULL);
8102 	ASSERT(tcp->tcp_eager_last_q == NULL);
8103 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8104 	    tcp->tcp_eager_prev_q0 == NULL) ||
8105 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8106 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8107 
8108 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
8109 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
8110 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
8111 
8112 	tcp->tcp_client_errno = 0;
8113 
8114 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8115 
8116 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8117 
8118 	PRESERVE(tcp->tcp_bound_source_v6);
8119 	tcp->tcp_last_sent_len = 0;
8120 	tcp->tcp_dupack_cnt = 0;
8121 
8122 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8123 	PRESERVE(tcp->tcp_lport);
8124 
8125 	PRESERVE(tcp->tcp_acceptor_lockp);
8126 
8127 	ASSERT(tcp->tcp_ordrelid == 0);
8128 	PRESERVE(tcp->tcp_acceptor_id);
8129 	DONTCARE(tcp->tcp_ipsec_overhead);
8130 
8131 	PRESERVE(tcp->tcp_family);
8132 	if (tcp->tcp_family == AF_INET6) {
8133 		tcp->tcp_ipversion = IPV6_VERSION;
8134 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
8135 	} else {
8136 		tcp->tcp_ipversion = IPV4_VERSION;
8137 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
8138 	}
8139 
8140 	tcp->tcp_bound_if = 0;
8141 	tcp->tcp_ipv6_recvancillary = 0;
8142 	tcp->tcp_recvifindex = 0;
8143 	tcp->tcp_recvhops = 0;
8144 	tcp->tcp_closed = 0;
8145 	tcp->tcp_cleandeathtag = 0;
8146 	if (tcp->tcp_hopopts != NULL) {
8147 		mi_free(tcp->tcp_hopopts);
8148 		tcp->tcp_hopopts = NULL;
8149 		tcp->tcp_hopoptslen = 0;
8150 	}
8151 	ASSERT(tcp->tcp_hopoptslen == 0);
8152 	if (tcp->tcp_dstopts != NULL) {
8153 		mi_free(tcp->tcp_dstopts);
8154 		tcp->tcp_dstopts = NULL;
8155 		tcp->tcp_dstoptslen = 0;
8156 	}
8157 	ASSERT(tcp->tcp_dstoptslen == 0);
8158 	if (tcp->tcp_rtdstopts != NULL) {
8159 		mi_free(tcp->tcp_rtdstopts);
8160 		tcp->tcp_rtdstopts = NULL;
8161 		tcp->tcp_rtdstoptslen = 0;
8162 	}
8163 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8164 	if (tcp->tcp_rthdr != NULL) {
8165 		mi_free(tcp->tcp_rthdr);
8166 		tcp->tcp_rthdr = NULL;
8167 		tcp->tcp_rthdrlen = 0;
8168 	}
8169 	ASSERT(tcp->tcp_rthdrlen == 0);
8170 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8171 
8172 	/* Reset fusion-related fields */
8173 	tcp->tcp_fused = B_FALSE;
8174 	tcp->tcp_unfusable = B_FALSE;
8175 	tcp->tcp_fused_sigurg = B_FALSE;
8176 	tcp->tcp_direct_sockfs = B_FALSE;
8177 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8178 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8179 	tcp->tcp_loopback_peer = NULL;
8180 	tcp->tcp_fuse_rcv_hiwater = 0;
8181 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8182 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8183 
8184 	tcp->tcp_lso = B_FALSE;
8185 
8186 	tcp->tcp_in_ack_unsent = 0;
8187 	tcp->tcp_cork = B_FALSE;
8188 	tcp->tcp_tconnind_started = B_FALSE;
8189 
8190 	PRESERVE(tcp->tcp_squeue_bytes);
8191 
8192 	ASSERT(tcp->tcp_kssl_ctx == NULL);
8193 	ASSERT(!tcp->tcp_kssl_pending);
8194 	PRESERVE(tcp->tcp_kssl_ent);
8195 
8196 	/* Sodirect */
8197 	tcp->tcp_sodirect = NULL;
8198 
8199 	tcp->tcp_closemp_used = B_FALSE;
8200 
8201 #ifdef DEBUG
8202 	DONTCARE(tcp->tcmp_stk[0]);
8203 #endif
8204 
8205 
8206 #undef	DONTCARE
8207 #undef	PRESERVE
8208 }
8209 
8210 /*
8211  * Allocate necessary resources and initialize state vector.
8212  * Guaranteed not to fail so that when an error is returned,
8213  * the caller doesn't need to do any additional cleanup.
8214  */
8215 int
8216 tcp_init(tcp_t *tcp, queue_t *q)
8217 {
8218 	int	err;
8219 
8220 	tcp->tcp_rq = q;
8221 	tcp->tcp_wq = WR(q);
8222 	tcp->tcp_state = TCPS_IDLE;
8223 	if ((err = tcp_init_values(tcp)) != 0)
8224 		tcp_timers_stop(tcp);
8225 	return (err);
8226 }
8227 
8228 static int
8229 tcp_init_values(tcp_t *tcp)
8230 {
8231 	int	err;
8232 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8233 
8234 	ASSERT((tcp->tcp_family == AF_INET &&
8235 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8236 	    (tcp->tcp_family == AF_INET6 &&
8237 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8238 	    tcp->tcp_ipversion == IPV6_VERSION)));
8239 
8240 	/*
8241 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8242 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8243 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8244 	 * during first few transmissions of a connection as seen in slow
8245 	 * links.
8246 	 */
8247 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
8248 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
8249 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8250 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8251 	    tcps->tcps_conn_grace_period;
8252 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
8253 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
8254 	tcp->tcp_timer_backoff = 0;
8255 	tcp->tcp_ms_we_have_waited = 0;
8256 	tcp->tcp_last_recv_time = lbolt;
8257 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
8258 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8259 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8260 
8261 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
8262 
8263 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
8264 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
8265 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
8266 	/*
8267 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8268 	 * passive open.
8269 	 */
8270 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
8271 
8272 	tcp->tcp_naglim = tcps->tcps_naglim_def;
8273 
8274 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8275 
8276 	tcp->tcp_mdt_hdr_head = 0;
8277 	tcp->tcp_mdt_hdr_tail = 0;
8278 
8279 	/* Reset fusion-related fields */
8280 	tcp->tcp_fused = B_FALSE;
8281 	tcp->tcp_unfusable = B_FALSE;
8282 	tcp->tcp_fused_sigurg = B_FALSE;
8283 	tcp->tcp_direct_sockfs = B_FALSE;
8284 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8285 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8286 	tcp->tcp_loopback_peer = NULL;
8287 	tcp->tcp_fuse_rcv_hiwater = 0;
8288 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8289 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8290 
8291 	/* Sodirect */
8292 	tcp->tcp_sodirect = NULL;
8293 
8294 	/* Initialize the header template */
8295 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8296 		err = tcp_header_init_ipv4(tcp);
8297 	} else {
8298 		err = tcp_header_init_ipv6(tcp);
8299 	}
8300 	if (err)
8301 		return (err);
8302 
8303 	/*
8304 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8305 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8306 	 */
8307 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8308 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8309 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8310 
8311 	tcp->tcp_cork = B_FALSE;
8312 	/*
8313 	 * Init the tcp_debug option.  This value determines whether TCP
8314 	 * calls strlog() to print out debug messages.  Doing this
8315 	 * initialization here means that this value is not inherited thru
8316 	 * tcp_reinit().
8317 	 */
8318 	tcp->tcp_debug = tcps->tcps_dbg;
8319 
8320 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8321 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8322 
8323 	return (0);
8324 }
8325 
8326 /*
8327  * Initialize the IPv4 header. Loses any record of any IP options.
8328  */
8329 static int
8330 tcp_header_init_ipv4(tcp_t *tcp)
8331 {
8332 	tcph_t		*tcph;
8333 	uint32_t	sum;
8334 	conn_t		*connp;
8335 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8336 
8337 	/*
8338 	 * This is a simple initialization. If there's
8339 	 * already a template, it should never be too small,
8340 	 * so reuse it.  Otherwise, allocate space for the new one.
8341 	 */
8342 	if (tcp->tcp_iphc == NULL) {
8343 		ASSERT(tcp->tcp_iphc_len == 0);
8344 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8345 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8346 		if (tcp->tcp_iphc == NULL) {
8347 			tcp->tcp_iphc_len = 0;
8348 			return (ENOMEM);
8349 		}
8350 	}
8351 
8352 	/* options are gone; may need a new label */
8353 	connp = tcp->tcp_connp;
8354 	connp->conn_mlp_type = mlptSingle;
8355 	connp->conn_ulp_labeled = !is_system_labeled();
8356 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8357 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8358 	tcp->tcp_ip6h = NULL;
8359 	tcp->tcp_ipversion = IPV4_VERSION;
8360 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8361 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8362 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8363 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8364 	tcp->tcp_ipha->ipha_version_and_hdr_length
8365 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8366 	tcp->tcp_ipha->ipha_ident = 0;
8367 
8368 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8369 	tcp->tcp_tos = 0;
8370 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8371 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8372 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8373 
8374 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8375 	tcp->tcp_tcph = tcph;
8376 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8377 	/*
8378 	 * IP wants our header length in the checksum field to
8379 	 * allow it to perform a single pseudo-header+checksum
8380 	 * calculation on behalf of TCP.
8381 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8382 	 */
8383 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8384 	sum = (sum >> 16) + (sum & 0xFFFF);
8385 	U16_TO_ABE16(sum, tcph->th_sum);
8386 	return (0);
8387 }
8388 
8389 /*
8390  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8391  */
8392 static int
8393 tcp_header_init_ipv6(tcp_t *tcp)
8394 {
8395 	tcph_t	*tcph;
8396 	uint32_t	sum;
8397 	conn_t	*connp;
8398 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8399 
8400 	/*
8401 	 * This is a simple initialization. If there's
8402 	 * already a template, it should never be too small,
8403 	 * so reuse it. Otherwise, allocate space for the new one.
8404 	 * Ensure that there is enough space to "downgrade" the tcp_t
8405 	 * to an IPv4 tcp_t. This requires having space for a full load
8406 	 * of IPv4 options, as well as a full load of TCP options
8407 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8408 	 * than a v6 header and a TCP header with a full load of TCP options
8409 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8410 	 * We want to avoid reallocation in the "downgraded" case when
8411 	 * processing outbound IPv4 options.
8412 	 */
8413 	if (tcp->tcp_iphc == NULL) {
8414 		ASSERT(tcp->tcp_iphc_len == 0);
8415 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8416 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8417 		if (tcp->tcp_iphc == NULL) {
8418 			tcp->tcp_iphc_len = 0;
8419 			return (ENOMEM);
8420 		}
8421 	}
8422 
8423 	/* options are gone; may need a new label */
8424 	connp = tcp->tcp_connp;
8425 	connp->conn_mlp_type = mlptSingle;
8426 	connp->conn_ulp_labeled = !is_system_labeled();
8427 
8428 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8429 	tcp->tcp_ipversion = IPV6_VERSION;
8430 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8431 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8432 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8433 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8434 	tcp->tcp_ipha = NULL;
8435 
8436 	/* Initialize the header template */
8437 
8438 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8439 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8440 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8441 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8442 
8443 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8444 	tcp->tcp_tcph = tcph;
8445 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8446 	/*
8447 	 * IP wants our header length in the checksum field to
8448 	 * allow it to perform a single psuedo-header+checksum
8449 	 * calculation on behalf of TCP.
8450 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8451 	 */
8452 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8453 	sum = (sum >> 16) + (sum & 0xFFFF);
8454 	U16_TO_ABE16(sum, tcph->th_sum);
8455 	return (0);
8456 }
8457 
8458 /* At minimum we need 8 bytes in the TCP header for the lookup */
8459 #define	ICMP_MIN_TCP_HDR	8
8460 
8461 /*
8462  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8463  * passed up by IP. The message is always received on the correct tcp_t.
8464  * Assumes that IP has pulled up everything up to and including the ICMP header.
8465  */
8466 void
8467 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8468 {
8469 	icmph_t *icmph;
8470 	ipha_t	*ipha;
8471 	int	iph_hdr_length;
8472 	tcph_t	*tcph;
8473 	boolean_t ipsec_mctl = B_FALSE;
8474 	boolean_t secure;
8475 	mblk_t *first_mp = mp;
8476 	uint32_t new_mss;
8477 	uint32_t ratio;
8478 	size_t mp_size = MBLKL(mp);
8479 	uint32_t seg_seq;
8480 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8481 
8482 	/* Assume IP provides aligned packets - otherwise toss */
8483 	if (!OK_32PTR(mp->b_rptr)) {
8484 		freemsg(mp);
8485 		return;
8486 	}
8487 
8488 	/*
8489 	 * Since ICMP errors are normal data marked with M_CTL when sent
8490 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8491 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8492 	 */
8493 	if ((mp_size == sizeof (ipsec_info_t)) &&
8494 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8495 		ASSERT(mp->b_cont != NULL);
8496 		mp = mp->b_cont;
8497 		/* IP should have done this */
8498 		ASSERT(OK_32PTR(mp->b_rptr));
8499 		mp_size = MBLKL(mp);
8500 		ipsec_mctl = B_TRUE;
8501 	}
8502 
8503 	/*
8504 	 * Verify that we have a complete outer IP header. If not, drop it.
8505 	 */
8506 	if (mp_size < sizeof (ipha_t)) {
8507 noticmpv4:
8508 		freemsg(first_mp);
8509 		return;
8510 	}
8511 
8512 	ipha = (ipha_t *)mp->b_rptr;
8513 	/*
8514 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8515 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8516 	 */
8517 	switch (IPH_HDR_VERSION(ipha)) {
8518 	case IPV6_VERSION:
8519 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8520 		return;
8521 	case IPV4_VERSION:
8522 		break;
8523 	default:
8524 		goto noticmpv4;
8525 	}
8526 
8527 	/* Skip past the outer IP and ICMP headers */
8528 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8529 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8530 	/*
8531 	 * If we don't have the correct outer IP header length or if the ULP
8532 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8533 	 * send it upstream.
8534 	 */
8535 	if (iph_hdr_length < sizeof (ipha_t) ||
8536 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8537 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8538 		goto noticmpv4;
8539 	}
8540 	ipha = (ipha_t *)&icmph[1];
8541 
8542 	/* Skip past the inner IP and find the ULP header */
8543 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8544 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8545 	/*
8546 	 * If we don't have the correct inner IP header length or if the ULP
8547 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8548 	 * bytes of TCP header, drop it.
8549 	 */
8550 	if (iph_hdr_length < sizeof (ipha_t) ||
8551 	    ipha->ipha_protocol != IPPROTO_TCP ||
8552 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8553 		goto noticmpv4;
8554 	}
8555 
8556 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8557 		if (ipsec_mctl) {
8558 			secure = ipsec_in_is_secure(first_mp);
8559 		} else {
8560 			secure = B_FALSE;
8561 		}
8562 		if (secure) {
8563 			/*
8564 			 * If we are willing to accept this in clear
8565 			 * we don't have to verify policy.
8566 			 */
8567 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8568 				if (!tcp_check_policy(tcp, first_mp,
8569 				    ipha, NULL, secure, ipsec_mctl)) {
8570 					/*
8571 					 * tcp_check_policy called
8572 					 * ip_drop_packet() on failure.
8573 					 */
8574 					return;
8575 				}
8576 			}
8577 		}
8578 	} else if (ipsec_mctl) {
8579 		/*
8580 		 * This is a hard_bound connection. IP has already
8581 		 * verified policy. We don't have to do it again.
8582 		 */
8583 		freeb(first_mp);
8584 		first_mp = mp;
8585 		ipsec_mctl = B_FALSE;
8586 	}
8587 
8588 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8589 	/*
8590 	 * TCP SHOULD check that the TCP sequence number contained in
8591 	 * payload of the ICMP error message is within the range
8592 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8593 	 */
8594 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8595 		/*
8596 		 * If the ICMP message is bogus, should we kill the
8597 		 * connection, or should we just drop the bogus ICMP
8598 		 * message? It would probably make more sense to just
8599 		 * drop the message so that if this one managed to get
8600 		 * in, the real connection should not suffer.
8601 		 */
8602 		goto noticmpv4;
8603 	}
8604 
8605 	switch (icmph->icmph_type) {
8606 	case ICMP_DEST_UNREACHABLE:
8607 		switch (icmph->icmph_code) {
8608 		case ICMP_FRAGMENTATION_NEEDED:
8609 			/*
8610 			 * Reduce the MSS based on the new MTU.  This will
8611 			 * eliminate any fragmentation locally.
8612 			 * N.B.  There may well be some funny side-effects on
8613 			 * the local send policy and the remote receive policy.
8614 			 * Pending further research, we provide
8615 			 * tcp_ignore_path_mtu just in case this proves
8616 			 * disastrous somewhere.
8617 			 *
8618 			 * After updating the MSS, retransmit part of the
8619 			 * dropped segment using the new mss by calling
8620 			 * tcp_wput_data().  Need to adjust all those
8621 			 * params to make sure tcp_wput_data() work properly.
8622 			 */
8623 			if (tcps->tcps_ignore_path_mtu)
8624 				break;
8625 
8626 			/*
8627 			 * Decrease the MSS by time stamp options
8628 			 * IP options and IPSEC options. tcp_hdr_len
8629 			 * includes time stamp option and IP option
8630 			 * length.
8631 			 */
8632 
8633 			new_mss = ntohs(icmph->icmph_du_mtu) -
8634 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8635 
8636 			/*
8637 			 * Only update the MSS if the new one is
8638 			 * smaller than the previous one.  This is
8639 			 * to avoid problems when getting multiple
8640 			 * ICMP errors for the same MTU.
8641 			 */
8642 			if (new_mss >= tcp->tcp_mss)
8643 				break;
8644 
8645 			/*
8646 			 * Stop doing PMTU if new_mss is less than 68
8647 			 * or less than tcp_mss_min.
8648 			 * The value 68 comes from rfc 1191.
8649 			 */
8650 			if (new_mss < MAX(68, tcps->tcps_mss_min))
8651 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8652 				    0;
8653 
8654 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8655 			ASSERT(ratio >= 1);
8656 			tcp_mss_set(tcp, new_mss, B_TRUE);
8657 
8658 			/*
8659 			 * Make sure we have something to
8660 			 * send.
8661 			 */
8662 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8663 			    (tcp->tcp_xmit_head != NULL)) {
8664 				/*
8665 				 * Shrink tcp_cwnd in
8666 				 * proportion to the old MSS/new MSS.
8667 				 */
8668 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8669 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8670 				    (tcp->tcp_unsent == 0)) {
8671 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8672 				} else {
8673 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8674 				}
8675 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8676 				tcp->tcp_rexmit = B_TRUE;
8677 				tcp->tcp_dupack_cnt = 0;
8678 				tcp->tcp_snd_burst = TCP_CWND_SS;
8679 				tcp_ss_rexmit(tcp);
8680 			}
8681 			break;
8682 		case ICMP_PORT_UNREACHABLE:
8683 		case ICMP_PROTOCOL_UNREACHABLE:
8684 			switch (tcp->tcp_state) {
8685 			case TCPS_SYN_SENT:
8686 			case TCPS_SYN_RCVD:
8687 				/*
8688 				 * ICMP can snipe away incipient
8689 				 * TCP connections as long as
8690 				 * seq number is same as initial
8691 				 * send seq number.
8692 				 */
8693 				if (seg_seq == tcp->tcp_iss) {
8694 					(void) tcp_clean_death(tcp,
8695 					    ECONNREFUSED, 6);
8696 				}
8697 				break;
8698 			}
8699 			break;
8700 		case ICMP_HOST_UNREACHABLE:
8701 		case ICMP_NET_UNREACHABLE:
8702 			/* Record the error in case we finally time out. */
8703 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8704 				tcp->tcp_client_errno = EHOSTUNREACH;
8705 			else
8706 				tcp->tcp_client_errno = ENETUNREACH;
8707 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8708 				if (tcp->tcp_listener != NULL &&
8709 				    tcp->tcp_listener->tcp_syn_defense) {
8710 					/*
8711 					 * Ditch the half-open connection if we
8712 					 * suspect a SYN attack is under way.
8713 					 */
8714 					tcp_ip_ire_mark_advice(tcp);
8715 					(void) tcp_clean_death(tcp,
8716 					    tcp->tcp_client_errno, 7);
8717 				}
8718 			}
8719 			break;
8720 		default:
8721 			break;
8722 		}
8723 		break;
8724 	case ICMP_SOURCE_QUENCH: {
8725 		/*
8726 		 * use a global boolean to control
8727 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8728 		 * The default is false.
8729 		 */
8730 		if (tcp_icmp_source_quench) {
8731 			/*
8732 			 * Reduce the sending rate as if we got a
8733 			 * retransmit timeout
8734 			 */
8735 			uint32_t npkt;
8736 
8737 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8738 			    tcp->tcp_mss;
8739 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8740 			tcp->tcp_cwnd = tcp->tcp_mss;
8741 			tcp->tcp_cwnd_cnt = 0;
8742 		}
8743 		break;
8744 	}
8745 	}
8746 	freemsg(first_mp);
8747 }
8748 
8749 /*
8750  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8751  * error messages passed up by IP.
8752  * Assumes that IP has pulled up all the extension headers as well
8753  * as the ICMPv6 header.
8754  */
8755 static void
8756 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8757 {
8758 	icmp6_t *icmp6;
8759 	ip6_t	*ip6h;
8760 	uint16_t	iph_hdr_length;
8761 	tcpha_t	*tcpha;
8762 	uint8_t	*nexthdrp;
8763 	uint32_t new_mss;
8764 	uint32_t ratio;
8765 	boolean_t secure;
8766 	mblk_t *first_mp = mp;
8767 	size_t mp_size;
8768 	uint32_t seg_seq;
8769 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8770 
8771 	/*
8772 	 * The caller has determined if this is an IPSEC_IN packet and
8773 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8774 	 */
8775 	if (ipsec_mctl)
8776 		mp = mp->b_cont;
8777 
8778 	mp_size = MBLKL(mp);
8779 
8780 	/*
8781 	 * Verify that we have a complete IP header. If not, send it upstream.
8782 	 */
8783 	if (mp_size < sizeof (ip6_t)) {
8784 noticmpv6:
8785 		freemsg(first_mp);
8786 		return;
8787 	}
8788 
8789 	/*
8790 	 * Verify this is an ICMPV6 packet, else send it upstream.
8791 	 */
8792 	ip6h = (ip6_t *)mp->b_rptr;
8793 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8794 		iph_hdr_length = IPV6_HDR_LEN;
8795 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8796 	    &nexthdrp) ||
8797 	    *nexthdrp != IPPROTO_ICMPV6) {
8798 		goto noticmpv6;
8799 	}
8800 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8801 	ip6h = (ip6_t *)&icmp6[1];
8802 	/*
8803 	 * Verify if we have a complete ICMP and inner IP header.
8804 	 */
8805 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8806 		goto noticmpv6;
8807 
8808 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8809 		goto noticmpv6;
8810 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8811 	/*
8812 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8813 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8814 	 * packet.
8815 	 */
8816 	if ((*nexthdrp != IPPROTO_TCP) ||
8817 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8818 		goto noticmpv6;
8819 	}
8820 
8821 	/*
8822 	 * ICMP errors come on the right queue or come on
8823 	 * listener/global queue for detached connections and
8824 	 * get switched to the right queue. If it comes on the
8825 	 * right queue, policy check has already been done by IP
8826 	 * and thus free the first_mp without verifying the policy.
8827 	 * If it has come for a non-hard bound connection, we need
8828 	 * to verify policy as IP may not have done it.
8829 	 */
8830 	if (!tcp->tcp_hard_bound) {
8831 		if (ipsec_mctl) {
8832 			secure = ipsec_in_is_secure(first_mp);
8833 		} else {
8834 			secure = B_FALSE;
8835 		}
8836 		if (secure) {
8837 			/*
8838 			 * If we are willing to accept this in clear
8839 			 * we don't have to verify policy.
8840 			 */
8841 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8842 				if (!tcp_check_policy(tcp, first_mp,
8843 				    NULL, ip6h, secure, ipsec_mctl)) {
8844 					/*
8845 					 * tcp_check_policy called
8846 					 * ip_drop_packet() on failure.
8847 					 */
8848 					return;
8849 				}
8850 			}
8851 		}
8852 	} else if (ipsec_mctl) {
8853 		/*
8854 		 * This is a hard_bound connection. IP has already
8855 		 * verified policy. We don't have to do it again.
8856 		 */
8857 		freeb(first_mp);
8858 		first_mp = mp;
8859 		ipsec_mctl = B_FALSE;
8860 	}
8861 
8862 	seg_seq = ntohl(tcpha->tha_seq);
8863 	/*
8864 	 * TCP SHOULD check that the TCP sequence number contained in
8865 	 * payload of the ICMP error message is within the range
8866 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8867 	 */
8868 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8869 		/*
8870 		 * If the ICMP message is bogus, should we kill the
8871 		 * connection, or should we just drop the bogus ICMP
8872 		 * message? It would probably make more sense to just
8873 		 * drop the message so that if this one managed to get
8874 		 * in, the real connection should not suffer.
8875 		 */
8876 		goto noticmpv6;
8877 	}
8878 
8879 	switch (icmp6->icmp6_type) {
8880 	case ICMP6_PACKET_TOO_BIG:
8881 		/*
8882 		 * Reduce the MSS based on the new MTU.  This will
8883 		 * eliminate any fragmentation locally.
8884 		 * N.B.  There may well be some funny side-effects on
8885 		 * the local send policy and the remote receive policy.
8886 		 * Pending further research, we provide
8887 		 * tcp_ignore_path_mtu just in case this proves
8888 		 * disastrous somewhere.
8889 		 *
8890 		 * After updating the MSS, retransmit part of the
8891 		 * dropped segment using the new mss by calling
8892 		 * tcp_wput_data().  Need to adjust all those
8893 		 * params to make sure tcp_wput_data() work properly.
8894 		 */
8895 		if (tcps->tcps_ignore_path_mtu)
8896 			break;
8897 
8898 		/*
8899 		 * Decrease the MSS by time stamp options
8900 		 * IP options and IPSEC options. tcp_hdr_len
8901 		 * includes time stamp option and IP option
8902 		 * length.
8903 		 */
8904 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8905 		    tcp->tcp_ipsec_overhead;
8906 
8907 		/*
8908 		 * Only update the MSS if the new one is
8909 		 * smaller than the previous one.  This is
8910 		 * to avoid problems when getting multiple
8911 		 * ICMP errors for the same MTU.
8912 		 */
8913 		if (new_mss >= tcp->tcp_mss)
8914 			break;
8915 
8916 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8917 		ASSERT(ratio >= 1);
8918 		tcp_mss_set(tcp, new_mss, B_TRUE);
8919 
8920 		/*
8921 		 * Make sure we have something to
8922 		 * send.
8923 		 */
8924 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8925 		    (tcp->tcp_xmit_head != NULL)) {
8926 			/*
8927 			 * Shrink tcp_cwnd in
8928 			 * proportion to the old MSS/new MSS.
8929 			 */
8930 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8931 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8932 			    (tcp->tcp_unsent == 0)) {
8933 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8934 			} else {
8935 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8936 			}
8937 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8938 			tcp->tcp_rexmit = B_TRUE;
8939 			tcp->tcp_dupack_cnt = 0;
8940 			tcp->tcp_snd_burst = TCP_CWND_SS;
8941 			tcp_ss_rexmit(tcp);
8942 		}
8943 		break;
8944 
8945 	case ICMP6_DST_UNREACH:
8946 		switch (icmp6->icmp6_code) {
8947 		case ICMP6_DST_UNREACH_NOPORT:
8948 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8949 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8950 			    (seg_seq == tcp->tcp_iss)) {
8951 				(void) tcp_clean_death(tcp,
8952 				    ECONNREFUSED, 8);
8953 			}
8954 			break;
8955 
8956 		case ICMP6_DST_UNREACH_ADMIN:
8957 		case ICMP6_DST_UNREACH_NOROUTE:
8958 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8959 		case ICMP6_DST_UNREACH_ADDR:
8960 			/* Record the error in case we finally time out. */
8961 			tcp->tcp_client_errno = EHOSTUNREACH;
8962 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8963 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8964 			    (seg_seq == tcp->tcp_iss)) {
8965 				if (tcp->tcp_listener != NULL &&
8966 				    tcp->tcp_listener->tcp_syn_defense) {
8967 					/*
8968 					 * Ditch the half-open connection if we
8969 					 * suspect a SYN attack is under way.
8970 					 */
8971 					tcp_ip_ire_mark_advice(tcp);
8972 					(void) tcp_clean_death(tcp,
8973 					    tcp->tcp_client_errno, 9);
8974 				}
8975 			}
8976 
8977 
8978 			break;
8979 		default:
8980 			break;
8981 		}
8982 		break;
8983 
8984 	case ICMP6_PARAM_PROB:
8985 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8986 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8987 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8988 		    (uchar_t *)nexthdrp) {
8989 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8990 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8991 				(void) tcp_clean_death(tcp,
8992 				    ECONNREFUSED, 10);
8993 			}
8994 			break;
8995 		}
8996 		break;
8997 
8998 	case ICMP6_TIME_EXCEEDED:
8999 	default:
9000 		break;
9001 	}
9002 	freemsg(first_mp);
9003 }
9004 
9005 /*
9006  * IP recognizes seven kinds of bind requests:
9007  *
9008  * - A zero-length address binds only to the protocol number.
9009  *
9010  * - A 4-byte address is treated as a request to
9011  * validate that the address is a valid local IPv4
9012  * address, appropriate for an application to bind to.
9013  * IP does the verification, but does not make any note
9014  * of the address at this time.
9015  *
9016  * - A 16-byte address contains is treated as a request
9017  * to validate a local IPv6 address, as the 4-byte
9018  * address case above.
9019  *
9020  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
9021  * use it for the inbound fanout of packets.
9022  *
9023  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
9024  * use it for the inbound fanout of packets.
9025  *
9026  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
9027  * information consisting of local and remote addresses
9028  * and ports.  In this case, the addresses are both
9029  * validated as appropriate for this operation, and, if
9030  * so, the information is retained for use in the
9031  * inbound fanout.
9032  *
9033  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
9034  * fanout information, like the 12-byte case above.
9035  *
9036  * IP will also fill in the IRE request mblk with information
9037  * regarding our peer.  In all cases, we notify IP of our protocol
9038  * type by appending a single protocol byte to the bind request.
9039  */
9040 static mblk_t *
9041 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
9042 {
9043 	char	*cp;
9044 	mblk_t	*mp;
9045 	struct T_bind_req *tbr;
9046 	ipa_conn_t	*ac;
9047 	ipa6_conn_t	*ac6;
9048 	sin_t		*sin;
9049 	sin6_t		*sin6;
9050 
9051 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9052 	ASSERT((tcp->tcp_family == AF_INET &&
9053 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9054 	    (tcp->tcp_family == AF_INET6 &&
9055 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9056 	    tcp->tcp_ipversion == IPV6_VERSION)));
9057 
9058 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9059 	if (!mp)
9060 		return (mp);
9061 	mp->b_datap->db_type = M_PROTO;
9062 	tbr = (struct T_bind_req *)mp->b_rptr;
9063 	tbr->PRIM_type = bind_prim;
9064 	tbr->ADDR_offset = sizeof (*tbr);
9065 	tbr->CONIND_number = 0;
9066 	tbr->ADDR_length = addr_length;
9067 	cp = (char *)&tbr[1];
9068 	switch (addr_length) {
9069 	case sizeof (ipa_conn_t):
9070 		ASSERT(tcp->tcp_family == AF_INET);
9071 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9072 
9073 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9074 		if (mp->b_cont == NULL) {
9075 			freemsg(mp);
9076 			return (NULL);
9077 		}
9078 		mp->b_cont->b_wptr += sizeof (ire_t);
9079 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9080 
9081 		/* cp known to be 32 bit aligned */
9082 		ac = (ipa_conn_t *)cp;
9083 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9084 		ac->ac_faddr = tcp->tcp_remote;
9085 		ac->ac_fport = tcp->tcp_fport;
9086 		ac->ac_lport = tcp->tcp_lport;
9087 		tcp->tcp_hard_binding = 1;
9088 		break;
9089 
9090 	case sizeof (ipa6_conn_t):
9091 		ASSERT(tcp->tcp_family == AF_INET6);
9092 
9093 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9094 		if (mp->b_cont == NULL) {
9095 			freemsg(mp);
9096 			return (NULL);
9097 		}
9098 		mp->b_cont->b_wptr += sizeof (ire_t);
9099 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9100 
9101 		/* cp known to be 32 bit aligned */
9102 		ac6 = (ipa6_conn_t *)cp;
9103 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9104 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9105 			    &ac6->ac6_laddr);
9106 		} else {
9107 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9108 		}
9109 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9110 		ac6->ac6_fport = tcp->tcp_fport;
9111 		ac6->ac6_lport = tcp->tcp_lport;
9112 		tcp->tcp_hard_binding = 1;
9113 		break;
9114 
9115 	case sizeof (sin_t):
9116 		/*
9117 		 * NOTE: IPV6_ADDR_LEN also has same size.
9118 		 * Use family to discriminate.
9119 		 */
9120 		if (tcp->tcp_family == AF_INET) {
9121 			sin = (sin_t *)cp;
9122 
9123 			*sin = sin_null;
9124 			sin->sin_family = AF_INET;
9125 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9126 			sin->sin_port = tcp->tcp_lport;
9127 			break;
9128 		} else {
9129 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9130 		}
9131 		break;
9132 
9133 	case sizeof (sin6_t):
9134 		ASSERT(tcp->tcp_family == AF_INET6);
9135 		sin6 = (sin6_t *)cp;
9136 
9137 		*sin6 = sin6_null;
9138 		sin6->sin6_family = AF_INET6;
9139 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9140 		sin6->sin6_port = tcp->tcp_lport;
9141 		break;
9142 
9143 	case IP_ADDR_LEN:
9144 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9145 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9146 		break;
9147 
9148 	}
9149 	/* Add protocol number to end */
9150 	cp[addr_length] = (char)IPPROTO_TCP;
9151 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9152 	return (mp);
9153 }
9154 
9155 /*
9156  * Notify IP that we are having trouble with this connection.  IP should
9157  * blow the IRE away and start over.
9158  */
9159 static void
9160 tcp_ip_notify(tcp_t *tcp)
9161 {
9162 	struct iocblk	*iocp;
9163 	ipid_t	*ipid;
9164 	mblk_t	*mp;
9165 
9166 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9167 	if (tcp->tcp_ipversion == IPV6_VERSION)
9168 		return;
9169 
9170 	mp = mkiocb(IP_IOCTL);
9171 	if (mp == NULL)
9172 		return;
9173 
9174 	iocp = (struct iocblk *)mp->b_rptr;
9175 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9176 
9177 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9178 	if (!mp->b_cont) {
9179 		freeb(mp);
9180 		return;
9181 	}
9182 
9183 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9184 	mp->b_cont->b_wptr += iocp->ioc_count;
9185 	bzero(ipid, sizeof (*ipid));
9186 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9187 	ipid->ipid_ire_type = IRE_CACHE;
9188 	ipid->ipid_addr_offset = sizeof (ipid_t);
9189 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9190 	/*
9191 	 * Note: in the case of source routing we want to blow away the
9192 	 * route to the first source route hop.
9193 	 */
9194 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9195 	    sizeof (tcp->tcp_ipha->ipha_dst));
9196 
9197 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9198 }
9199 
9200 /* Unlink and return any mblk that looks like it contains an ire */
9201 static mblk_t *
9202 tcp_ire_mp(mblk_t *mp)
9203 {
9204 	mblk_t	*prev_mp;
9205 
9206 	for (;;) {
9207 		prev_mp = mp;
9208 		mp = mp->b_cont;
9209 		if (mp == NULL)
9210 			break;
9211 		switch (DB_TYPE(mp)) {
9212 		case IRE_DB_TYPE:
9213 		case IRE_DB_REQ_TYPE:
9214 			if (prev_mp != NULL)
9215 				prev_mp->b_cont = mp->b_cont;
9216 			mp->b_cont = NULL;
9217 			return (mp);
9218 		default:
9219 			break;
9220 		}
9221 	}
9222 	return (mp);
9223 }
9224 
9225 /*
9226  * Timer callback routine for keepalive probe.  We do a fake resend of
9227  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9228  * check to see if we have heard anything from the other end for the last
9229  * RTO period.  If we have, set the timer to expire for another
9230  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9231  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9232  * the timeout if we have not heard from the other side.  If for more than
9233  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9234  * kill the connection unless the keepalive abort threshold is 0.  In
9235  * that case, we will probe "forever."
9236  */
9237 static void
9238 tcp_keepalive_killer(void *arg)
9239 {
9240 	mblk_t	*mp;
9241 	conn_t	*connp = (conn_t *)arg;
9242 	tcp_t  	*tcp = connp->conn_tcp;
9243 	int32_t	firetime;
9244 	int32_t	idletime;
9245 	int32_t	ka_intrvl;
9246 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9247 
9248 	tcp->tcp_ka_tid = 0;
9249 
9250 	if (tcp->tcp_fused)
9251 		return;
9252 
9253 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
9254 	ka_intrvl = tcp->tcp_ka_interval;
9255 
9256 	/*
9257 	 * Keepalive probe should only be sent if the application has not
9258 	 * done a close on the connection.
9259 	 */
9260 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9261 		return;
9262 	}
9263 	/* Timer fired too early, restart it. */
9264 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9265 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9266 		    MSEC_TO_TICK(ka_intrvl));
9267 		return;
9268 	}
9269 
9270 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9271 	/*
9272 	 * If we have not heard from the other side for a long
9273 	 * time, kill the connection unless the keepalive abort
9274 	 * threshold is 0.  In that case, we will probe "forever."
9275 	 */
9276 	if (tcp->tcp_ka_abort_thres != 0 &&
9277 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9278 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
9279 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9280 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9281 		return;
9282 	}
9283 
9284 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9285 	    idletime >= ka_intrvl) {
9286 		/* Fake resend of last ACKed byte. */
9287 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9288 
9289 		if (mp1 != NULL) {
9290 			*mp1->b_wptr++ = '\0';
9291 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9292 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9293 			freeb(mp1);
9294 			/*
9295 			 * if allocation failed, fall through to start the
9296 			 * timer back.
9297 			 */
9298 			if (mp != NULL) {
9299 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9300 				BUMP_MIB(&tcps->tcps_mib,
9301 				    tcpTimKeepaliveProbe);
9302 				if (tcp->tcp_ka_last_intrvl != 0) {
9303 					int max;
9304 					/*
9305 					 * We should probe again at least
9306 					 * in ka_intrvl, but not more than
9307 					 * tcp_rexmit_interval_max.
9308 					 */
9309 					max = tcps->tcps_rexmit_interval_max;
9310 					firetime = MIN(ka_intrvl - 1,
9311 					    tcp->tcp_ka_last_intrvl << 1);
9312 					if (firetime > max)
9313 						firetime = max;
9314 				} else {
9315 					firetime = tcp->tcp_rto;
9316 				}
9317 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9318 				    tcp_keepalive_killer,
9319 				    MSEC_TO_TICK(firetime));
9320 				tcp->tcp_ka_last_intrvl = firetime;
9321 				return;
9322 			}
9323 		}
9324 	} else {
9325 		tcp->tcp_ka_last_intrvl = 0;
9326 	}
9327 
9328 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9329 	if ((firetime = ka_intrvl - idletime) < 0) {
9330 		firetime = ka_intrvl;
9331 	}
9332 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9333 	    MSEC_TO_TICK(firetime));
9334 }
9335 
9336 int
9337 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9338 {
9339 	queue_t	*q = tcp->tcp_rq;
9340 	int32_t	mss = tcp->tcp_mss;
9341 	int	maxpsz;
9342 
9343 	if (TCP_IS_DETACHED(tcp))
9344 		return (mss);
9345 
9346 	if (tcp->tcp_fused) {
9347 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9348 		mss = INFPSZ;
9349 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
9350 		/*
9351 		 * Set the sd_qn_maxpsz according to the socket send buffer
9352 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9353 		 * instruct the stream head to copyin user data into contiguous
9354 		 * kernel-allocated buffers without breaking it up into smaller
9355 		 * chunks.  We round up the buffer size to the nearest SMSS.
9356 		 */
9357 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9358 		if (tcp->tcp_kssl_ctx == NULL)
9359 			mss = INFPSZ;
9360 		else
9361 			mss = SSL3_MAX_RECORD_LEN;
9362 	} else {
9363 		/*
9364 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9365 		 * (and a multiple of the mss).  This instructs the stream
9366 		 * head to break down larger than SMSS writes into SMSS-
9367 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9368 		 */
9369 		maxpsz = tcp->tcp_maxpsz * mss;
9370 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9371 			maxpsz = tcp->tcp_xmit_hiwater/2;
9372 			/* Round up to nearest mss */
9373 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9374 		}
9375 	}
9376 	(void) setmaxps(q, maxpsz);
9377 	tcp->tcp_wq->q_maxpsz = maxpsz;
9378 
9379 	if (set_maxblk)
9380 		(void) mi_set_sth_maxblk(q, mss);
9381 
9382 	return (mss);
9383 }
9384 
9385 /*
9386  * Extract option values from a tcp header.  We put any found values into the
9387  * tcpopt struct and return a bitmask saying which options were found.
9388  */
9389 static int
9390 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9391 {
9392 	uchar_t		*endp;
9393 	int		len;
9394 	uint32_t	mss;
9395 	uchar_t		*up = (uchar_t *)tcph;
9396 	int		found = 0;
9397 	int32_t		sack_len;
9398 	tcp_seq		sack_begin, sack_end;
9399 	tcp_t		*tcp;
9400 
9401 	endp = up + TCP_HDR_LENGTH(tcph);
9402 	up += TCP_MIN_HEADER_LENGTH;
9403 	while (up < endp) {
9404 		len = endp - up;
9405 		switch (*up) {
9406 		case TCPOPT_EOL:
9407 			break;
9408 
9409 		case TCPOPT_NOP:
9410 			up++;
9411 			continue;
9412 
9413 		case TCPOPT_MAXSEG:
9414 			if (len < TCPOPT_MAXSEG_LEN ||
9415 			    up[1] != TCPOPT_MAXSEG_LEN)
9416 				break;
9417 
9418 			mss = BE16_TO_U16(up+2);
9419 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9420 			tcpopt->tcp_opt_mss = mss;
9421 			found |= TCP_OPT_MSS_PRESENT;
9422 
9423 			up += TCPOPT_MAXSEG_LEN;
9424 			continue;
9425 
9426 		case TCPOPT_WSCALE:
9427 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9428 				break;
9429 
9430 			if (up[2] > TCP_MAX_WINSHIFT)
9431 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9432 			else
9433 				tcpopt->tcp_opt_wscale = up[2];
9434 			found |= TCP_OPT_WSCALE_PRESENT;
9435 
9436 			up += TCPOPT_WS_LEN;
9437 			continue;
9438 
9439 		case TCPOPT_SACK_PERMITTED:
9440 			if (len < TCPOPT_SACK_OK_LEN ||
9441 			    up[1] != TCPOPT_SACK_OK_LEN)
9442 				break;
9443 			found |= TCP_OPT_SACK_OK_PRESENT;
9444 			up += TCPOPT_SACK_OK_LEN;
9445 			continue;
9446 
9447 		case TCPOPT_SACK:
9448 			if (len <= 2 || up[1] <= 2 || len < up[1])
9449 				break;
9450 
9451 			/* If TCP is not interested in SACK blks... */
9452 			if ((tcp = tcpopt->tcp) == NULL) {
9453 				up += up[1];
9454 				continue;
9455 			}
9456 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9457 			up += TCPOPT_HEADER_LEN;
9458 
9459 			/*
9460 			 * If the list is empty, allocate one and assume
9461 			 * nothing is sack'ed.
9462 			 */
9463 			ASSERT(tcp->tcp_sack_info != NULL);
9464 			if (tcp->tcp_notsack_list == NULL) {
9465 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9466 				    tcp->tcp_suna, tcp->tcp_snxt,
9467 				    &(tcp->tcp_num_notsack_blk),
9468 				    &(tcp->tcp_cnt_notsack_list));
9469 
9470 				/*
9471 				 * Make sure tcp_notsack_list is not NULL.
9472 				 * This happens when kmem_alloc(KM_NOSLEEP)
9473 				 * returns NULL.
9474 				 */
9475 				if (tcp->tcp_notsack_list == NULL) {
9476 					up += sack_len;
9477 					continue;
9478 				}
9479 				tcp->tcp_fack = tcp->tcp_suna;
9480 			}
9481 
9482 			while (sack_len > 0) {
9483 				if (up + 8 > endp) {
9484 					up = endp;
9485 					break;
9486 				}
9487 				sack_begin = BE32_TO_U32(up);
9488 				up += 4;
9489 				sack_end = BE32_TO_U32(up);
9490 				up += 4;
9491 				sack_len -= 8;
9492 				/*
9493 				 * Bounds checking.  Make sure the SACK
9494 				 * info is within tcp_suna and tcp_snxt.
9495 				 * If this SACK blk is out of bound, ignore
9496 				 * it but continue to parse the following
9497 				 * blks.
9498 				 */
9499 				if (SEQ_LEQ(sack_end, sack_begin) ||
9500 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9501 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9502 					continue;
9503 				}
9504 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9505 				    sack_begin, sack_end,
9506 				    &(tcp->tcp_num_notsack_blk),
9507 				    &(tcp->tcp_cnt_notsack_list));
9508 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9509 					tcp->tcp_fack = sack_end;
9510 				}
9511 			}
9512 			found |= TCP_OPT_SACK_PRESENT;
9513 			continue;
9514 
9515 		case TCPOPT_TSTAMP:
9516 			if (len < TCPOPT_TSTAMP_LEN ||
9517 			    up[1] != TCPOPT_TSTAMP_LEN)
9518 				break;
9519 
9520 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9521 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9522 
9523 			found |= TCP_OPT_TSTAMP_PRESENT;
9524 
9525 			up += TCPOPT_TSTAMP_LEN;
9526 			continue;
9527 
9528 		default:
9529 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9530 				break;
9531 			up += up[1];
9532 			continue;
9533 		}
9534 		break;
9535 	}
9536 	return (found);
9537 }
9538 
9539 /*
9540  * Set the mss associated with a particular tcp based on its current value,
9541  * and a new one passed in. Observe minimums and maximums, and reset
9542  * other state variables that we want to view as multiples of mss.
9543  *
9544  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9545  * highwater marks etc. need to be initialized or adjusted.
9546  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9547  *    packet arrives.
9548  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9549  *    ICMP6_PACKET_TOO_BIG arrives.
9550  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9551  *    to increase the MSS to use the extra bytes available.
9552  *
9553  * Callers except tcp_paws_check() ensure that they only reduce mss.
9554  */
9555 static void
9556 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9557 {
9558 	uint32_t	mss_max;
9559 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9560 
9561 	if (tcp->tcp_ipversion == IPV4_VERSION)
9562 		mss_max = tcps->tcps_mss_max_ipv4;
9563 	else
9564 		mss_max = tcps->tcps_mss_max_ipv6;
9565 
9566 	if (mss < tcps->tcps_mss_min)
9567 		mss = tcps->tcps_mss_min;
9568 	if (mss > mss_max)
9569 		mss = mss_max;
9570 	/*
9571 	 * Unless naglim has been set by our client to
9572 	 * a non-mss value, force naglim to track mss.
9573 	 * This can help to aggregate small writes.
9574 	 */
9575 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9576 		tcp->tcp_naglim = mss;
9577 	/*
9578 	 * TCP should be able to buffer at least 4 MSS data for obvious
9579 	 * performance reason.
9580 	 */
9581 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9582 		tcp->tcp_xmit_hiwater = mss << 2;
9583 
9584 	if (do_ss) {
9585 		/*
9586 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9587 		 * changing due to a reduction in MTU, presumably as a
9588 		 * result of a new path component, reset cwnd to its
9589 		 * "initial" value, as a multiple of the new mss.
9590 		 */
9591 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9592 	} else {
9593 		/*
9594 		 * Called by tcp_paws_check(), the mss increased
9595 		 * marginally to allow use of space previously taken
9596 		 * by the timestamp option. It would be inappropriate
9597 		 * to apply slow start or tcp_init_cwnd values to
9598 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9599 		 */
9600 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9601 		tcp->tcp_cwnd_cnt = 0;
9602 	}
9603 	tcp->tcp_mss = mss;
9604 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9605 }
9606 
9607 /* For /dev/tcp aka AF_INET open */
9608 static int
9609 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9610 {
9611 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9612 }
9613 
9614 /* For /dev/tcp6 aka AF_INET6 open */
9615 static int
9616 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9617 {
9618 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9619 }
9620 
9621 static int
9622 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9623     boolean_t isv6)
9624 {
9625 	tcp_t		*tcp = NULL;
9626 	conn_t		*connp;
9627 	int		err;
9628 	vmem_t		*minor_arena = NULL;
9629 	dev_t		conn_dev;
9630 	zoneid_t	zoneid;
9631 	tcp_stack_t	*tcps = NULL;
9632 
9633 	if (q->q_ptr != NULL)
9634 		return (0);
9635 
9636 	if (sflag == MODOPEN)
9637 		return (EINVAL);
9638 
9639 	if (!(flag & SO_ACCEPTOR)) {
9640 		/*
9641 		 * Special case for install: miniroot needs to be able to
9642 		 * access files via NFS as though it were always in the
9643 		 * global zone.
9644 		 */
9645 		if (credp == kcred && nfs_global_client_only != 0) {
9646 			zoneid = GLOBAL_ZONEID;
9647 			tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9648 			    netstack_tcp;
9649 			ASSERT(tcps != NULL);
9650 		} else {
9651 			netstack_t *ns;
9652 
9653 			ns = netstack_find_by_cred(credp);
9654 			ASSERT(ns != NULL);
9655 			tcps = ns->netstack_tcp;
9656 			ASSERT(tcps != NULL);
9657 
9658 			/*
9659 			 * For exclusive stacks we set the zoneid to zero
9660 			 * to make TCP operate as if in the global zone.
9661 			 */
9662 			if (tcps->tcps_netstack->netstack_stackid !=
9663 			    GLOBAL_NETSTACKID)
9664 				zoneid = GLOBAL_ZONEID;
9665 			else
9666 				zoneid = crgetzoneid(credp);
9667 		}
9668 		/*
9669 		 * For stackid zero this is done from strplumb.c, but
9670 		 * non-zero stackids are handled here.
9671 		 */
9672 		if (tcps->tcps_g_q == NULL &&
9673 		    tcps->tcps_netstack->netstack_stackid !=
9674 		    GLOBAL_NETSTACKID) {
9675 			tcp_g_q_setup(tcps);
9676 		}
9677 	}
9678 
9679 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9680 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9681 		minor_arena = ip_minor_arena_la;
9682 	} else {
9683 		/*
9684 		 * Either minor numbers in the large arena were exhausted
9685 		 * or a non socket application is doing the open.
9686 		 * Try to allocate from the small arena.
9687 		 */
9688 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9689 			if (tcps != NULL)
9690 				netstack_rele(tcps->tcps_netstack);
9691 			return (EBUSY);
9692 		}
9693 		minor_arena = ip_minor_arena_sa;
9694 	}
9695 	ASSERT(minor_arena != NULL);
9696 
9697 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9698 
9699 	if (flag & SO_ACCEPTOR) {
9700 		/* No netstack_find_by_cred, hence no netstack_rele needed */
9701 		ASSERT(tcps == NULL);
9702 		q->q_qinfo = &tcp_acceptor_rinit;
9703 		/*
9704 		 * the conn_dev and minor_arena will be subsequently used by
9705 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9706 		 * minor device number for this connection from the q_ptr.
9707 		 */
9708 		RD(q)->q_ptr = (void *)conn_dev;
9709 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9710 		WR(q)->q_ptr = (void *)minor_arena;
9711 		qprocson(q);
9712 		return (0);
9713 	}
9714 
9715 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9716 	/*
9717 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9718 	 * so we drop it by one.
9719 	 */
9720 	netstack_rele(tcps->tcps_netstack);
9721 	if (connp == NULL) {
9722 		inet_minor_free(minor_arena, conn_dev);
9723 		q->q_ptr = NULL;
9724 		return (ENOSR);
9725 	}
9726 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9727 	tcp = connp->conn_tcp;
9728 
9729 	q->q_ptr = WR(q)->q_ptr = connp;
9730 	if (isv6) {
9731 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9732 		connp->conn_send = ip_output_v6;
9733 		connp->conn_af_isv6 = B_TRUE;
9734 		connp->conn_pkt_isv6 = B_TRUE;
9735 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9736 		tcp->tcp_ipversion = IPV6_VERSION;
9737 		tcp->tcp_family = AF_INET6;
9738 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9739 	} else {
9740 		connp->conn_flags |= IPCL_TCP4;
9741 		connp->conn_send = ip_output;
9742 		connp->conn_af_isv6 = B_FALSE;
9743 		connp->conn_pkt_isv6 = B_FALSE;
9744 		tcp->tcp_ipversion = IPV4_VERSION;
9745 		tcp->tcp_family = AF_INET;
9746 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9747 	}
9748 
9749 	/*
9750 	 * TCP keeps a copy of cred for cache locality reasons but
9751 	 * we put a reference only once. If connp->conn_cred
9752 	 * becomes invalid, tcp_cred should also be set to NULL.
9753 	 */
9754 	tcp->tcp_cred = connp->conn_cred = credp;
9755 	crhold(connp->conn_cred);
9756 	tcp->tcp_cpid = curproc->p_pid;
9757 	tcp->tcp_open_time = lbolt64;
9758 	connp->conn_zoneid = zoneid;
9759 	connp->conn_mlp_type = mlptSingle;
9760 	connp->conn_ulp_labeled = !is_system_labeled();
9761 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9762 	ASSERT(tcp->tcp_tcps == tcps);
9763 
9764 	/*
9765 	 * If the caller has the process-wide flag set, then default to MAC
9766 	 * exempt mode.  This allows read-down to unlabeled hosts.
9767 	 */
9768 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9769 		connp->conn_mac_exempt = B_TRUE;
9770 
9771 	connp->conn_dev = conn_dev;
9772 	connp->conn_minor_arena = minor_arena;
9773 
9774 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9775 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9776 
9777 	if (flag & SO_SOCKSTR) {
9778 		/*
9779 		 * No need to insert a socket in tcp acceptor hash.
9780 		 * If it was a socket acceptor stream, we dealt with
9781 		 * it above. A socket listener can never accept a
9782 		 * connection and doesn't need acceptor_id.
9783 		 */
9784 		connp->conn_flags |= IPCL_SOCKET;
9785 		tcp->tcp_issocket = 1;
9786 		WR(q)->q_qinfo = &tcp_sock_winit;
9787 	} else {
9788 #ifdef	_ILP32
9789 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9790 #else
9791 		tcp->tcp_acceptor_id = conn_dev;
9792 #endif	/* _ILP32 */
9793 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9794 	}
9795 
9796 	err = tcp_init(tcp, q);
9797 	if (err != 0) {
9798 		inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
9799 		tcp_acceptor_hash_remove(tcp);
9800 		CONN_DEC_REF(connp);
9801 		q->q_ptr = WR(q)->q_ptr = NULL;
9802 		return (err);
9803 	}
9804 
9805 	RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9806 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9807 
9808 	/* Non-zero default values */
9809 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9810 	/*
9811 	 * Put the ref for TCP. Ref for IP was already put
9812 	 * by ipcl_conn_create. Also Make the conn_t globally
9813 	 * visible to walkers
9814 	 */
9815 	mutex_enter(&connp->conn_lock);
9816 	CONN_INC_REF_LOCKED(connp);
9817 	ASSERT(connp->conn_ref == 2);
9818 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9819 	mutex_exit(&connp->conn_lock);
9820 
9821 	qprocson(q);
9822 	return (0);
9823 }
9824 
9825 /*
9826  * Some TCP options can be "set" by requesting them in the option
9827  * buffer. This is needed for XTI feature test though we do not
9828  * allow it in general. We interpret that this mechanism is more
9829  * applicable to OSI protocols and need not be allowed in general.
9830  * This routine filters out options for which it is not allowed (most)
9831  * and lets through those (few) for which it is. [ The XTI interface
9832  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9833  * ever implemented will have to be allowed here ].
9834  */
9835 static boolean_t
9836 tcp_allow_connopt_set(int level, int name)
9837 {
9838 
9839 	switch (level) {
9840 	case IPPROTO_TCP:
9841 		switch (name) {
9842 		case TCP_NODELAY:
9843 			return (B_TRUE);
9844 		default:
9845 			return (B_FALSE);
9846 		}
9847 		/*NOTREACHED*/
9848 	default:
9849 		return (B_FALSE);
9850 	}
9851 	/*NOTREACHED*/
9852 }
9853 
9854 /*
9855  * This routine gets default values of certain options whose default
9856  * values are maintained by protocol specific code
9857  */
9858 /* ARGSUSED */
9859 int
9860 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9861 {
9862 	int32_t	*i1 = (int32_t *)ptr;
9863 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9864 
9865 	switch (level) {
9866 	case IPPROTO_TCP:
9867 		switch (name) {
9868 		case TCP_NOTIFY_THRESHOLD:
9869 			*i1 = tcps->tcps_ip_notify_interval;
9870 			break;
9871 		case TCP_ABORT_THRESHOLD:
9872 			*i1 = tcps->tcps_ip_abort_interval;
9873 			break;
9874 		case TCP_CONN_NOTIFY_THRESHOLD:
9875 			*i1 = tcps->tcps_ip_notify_cinterval;
9876 			break;
9877 		case TCP_CONN_ABORT_THRESHOLD:
9878 			*i1 = tcps->tcps_ip_abort_cinterval;
9879 			break;
9880 		default:
9881 			return (-1);
9882 		}
9883 		break;
9884 	case IPPROTO_IP:
9885 		switch (name) {
9886 		case IP_TTL:
9887 			*i1 = tcps->tcps_ipv4_ttl;
9888 			break;
9889 		default:
9890 			return (-1);
9891 		}
9892 		break;
9893 	case IPPROTO_IPV6:
9894 		switch (name) {
9895 		case IPV6_UNICAST_HOPS:
9896 			*i1 = tcps->tcps_ipv6_hoplimit;
9897 			break;
9898 		default:
9899 			return (-1);
9900 		}
9901 		break;
9902 	default:
9903 		return (-1);
9904 	}
9905 	return (sizeof (int));
9906 }
9907 
9908 
9909 /*
9910  * TCP routine to get the values of options.
9911  */
9912 int
9913 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9914 {
9915 	int		*i1 = (int *)ptr;
9916 	conn_t		*connp = Q_TO_CONN(q);
9917 	tcp_t		*tcp = connp->conn_tcp;
9918 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9919 
9920 	switch (level) {
9921 	case SOL_SOCKET:
9922 		switch (name) {
9923 		case SO_LINGER:	{
9924 			struct linger *lgr = (struct linger *)ptr;
9925 
9926 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9927 			lgr->l_linger = tcp->tcp_lingertime;
9928 			}
9929 			return (sizeof (struct linger));
9930 		case SO_DEBUG:
9931 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9932 			break;
9933 		case SO_KEEPALIVE:
9934 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9935 			break;
9936 		case SO_DONTROUTE:
9937 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9938 			break;
9939 		case SO_USELOOPBACK:
9940 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9941 			break;
9942 		case SO_BROADCAST:
9943 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9944 			break;
9945 		case SO_REUSEADDR:
9946 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9947 			break;
9948 		case SO_OOBINLINE:
9949 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9950 			break;
9951 		case SO_DGRAM_ERRIND:
9952 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9953 			break;
9954 		case SO_TYPE:
9955 			*i1 = SOCK_STREAM;
9956 			break;
9957 		case SO_SNDBUF:
9958 			*i1 = tcp->tcp_xmit_hiwater;
9959 			break;
9960 		case SO_RCVBUF:
9961 			*i1 = RD(q)->q_hiwat;
9962 			break;
9963 		case SO_SND_COPYAVOID:
9964 			*i1 = tcp->tcp_snd_zcopy_on ?
9965 			    SO_SND_COPYAVOID : 0;
9966 			break;
9967 		case SO_ALLZONES:
9968 			*i1 = connp->conn_allzones ? 1 : 0;
9969 			break;
9970 		case SO_ANON_MLP:
9971 			*i1 = connp->conn_anon_mlp;
9972 			break;
9973 		case SO_MAC_EXEMPT:
9974 			*i1 = connp->conn_mac_exempt;
9975 			break;
9976 		case SO_EXCLBIND:
9977 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9978 			break;
9979 		case SO_PROTOTYPE:
9980 			*i1 = IPPROTO_TCP;
9981 			break;
9982 		case SO_DOMAIN:
9983 			*i1 = tcp->tcp_family;
9984 			break;
9985 		default:
9986 			return (-1);
9987 		}
9988 		break;
9989 	case IPPROTO_TCP:
9990 		switch (name) {
9991 		case TCP_NODELAY:
9992 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9993 			break;
9994 		case TCP_MAXSEG:
9995 			*i1 = tcp->tcp_mss;
9996 			break;
9997 		case TCP_NOTIFY_THRESHOLD:
9998 			*i1 = (int)tcp->tcp_first_timer_threshold;
9999 			break;
10000 		case TCP_ABORT_THRESHOLD:
10001 			*i1 = tcp->tcp_second_timer_threshold;
10002 			break;
10003 		case TCP_CONN_NOTIFY_THRESHOLD:
10004 			*i1 = tcp->tcp_first_ctimer_threshold;
10005 			break;
10006 		case TCP_CONN_ABORT_THRESHOLD:
10007 			*i1 = tcp->tcp_second_ctimer_threshold;
10008 			break;
10009 		case TCP_RECVDSTADDR:
10010 			*i1 = tcp->tcp_recvdstaddr;
10011 			break;
10012 		case TCP_ANONPRIVBIND:
10013 			*i1 = tcp->tcp_anon_priv_bind;
10014 			break;
10015 		case TCP_EXCLBIND:
10016 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
10017 			break;
10018 		case TCP_INIT_CWND:
10019 			*i1 = tcp->tcp_init_cwnd;
10020 			break;
10021 		case TCP_KEEPALIVE_THRESHOLD:
10022 			*i1 = tcp->tcp_ka_interval;
10023 			break;
10024 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10025 			*i1 = tcp->tcp_ka_abort_thres;
10026 			break;
10027 		case TCP_CORK:
10028 			*i1 = tcp->tcp_cork;
10029 			break;
10030 		default:
10031 			return (-1);
10032 		}
10033 		break;
10034 	case IPPROTO_IP:
10035 		if (tcp->tcp_family != AF_INET)
10036 			return (-1);
10037 		switch (name) {
10038 		case IP_OPTIONS:
10039 		case T_IP_OPTIONS: {
10040 			/*
10041 			 * This is compatible with BSD in that in only return
10042 			 * the reverse source route with the final destination
10043 			 * as the last entry. The first 4 bytes of the option
10044 			 * will contain the final destination.
10045 			 */
10046 			int	opt_len;
10047 
10048 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
10049 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
10050 			ASSERT(opt_len >= 0);
10051 			/* Caller ensures enough space */
10052 			if (opt_len > 0) {
10053 				/*
10054 				 * TODO: Do we have to handle getsockopt on an
10055 				 * initiator as well?
10056 				 */
10057 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
10058 			}
10059 			return (0);
10060 			}
10061 		case IP_TOS:
10062 		case T_IP_TOS:
10063 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10064 			break;
10065 		case IP_TTL:
10066 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10067 			break;
10068 		case IP_NEXTHOP:
10069 			/* Handled at IP level */
10070 			return (-EINVAL);
10071 		default:
10072 			return (-1);
10073 		}
10074 		break;
10075 	case IPPROTO_IPV6:
10076 		/*
10077 		 * IPPROTO_IPV6 options are only supported for sockets
10078 		 * that are using IPv6 on the wire.
10079 		 */
10080 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10081 			return (-1);
10082 		}
10083 		switch (name) {
10084 		case IPV6_UNICAST_HOPS:
10085 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10086 			break;	/* goto sizeof (int) option return */
10087 		case IPV6_BOUND_IF:
10088 			/* Zero if not set */
10089 			*i1 = tcp->tcp_bound_if;
10090 			break;	/* goto sizeof (int) option return */
10091 		case IPV6_RECVPKTINFO:
10092 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10093 				*i1 = 1;
10094 			else
10095 				*i1 = 0;
10096 			break;	/* goto sizeof (int) option return */
10097 		case IPV6_RECVTCLASS:
10098 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10099 				*i1 = 1;
10100 			else
10101 				*i1 = 0;
10102 			break;	/* goto sizeof (int) option return */
10103 		case IPV6_RECVHOPLIMIT:
10104 			if (tcp->tcp_ipv6_recvancillary &
10105 			    TCP_IPV6_RECVHOPLIMIT)
10106 				*i1 = 1;
10107 			else
10108 				*i1 = 0;
10109 			break;	/* goto sizeof (int) option return */
10110 		case IPV6_RECVHOPOPTS:
10111 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10112 				*i1 = 1;
10113 			else
10114 				*i1 = 0;
10115 			break;	/* goto sizeof (int) option return */
10116 		case IPV6_RECVDSTOPTS:
10117 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10118 				*i1 = 1;
10119 			else
10120 				*i1 = 0;
10121 			break;	/* goto sizeof (int) option return */
10122 		case _OLD_IPV6_RECVDSTOPTS:
10123 			if (tcp->tcp_ipv6_recvancillary &
10124 			    TCP_OLD_IPV6_RECVDSTOPTS)
10125 				*i1 = 1;
10126 			else
10127 				*i1 = 0;
10128 			break;	/* goto sizeof (int) option return */
10129 		case IPV6_RECVRTHDR:
10130 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10131 				*i1 = 1;
10132 			else
10133 				*i1 = 0;
10134 			break;	/* goto sizeof (int) option return */
10135 		case IPV6_RECVRTHDRDSTOPTS:
10136 			if (tcp->tcp_ipv6_recvancillary &
10137 			    TCP_IPV6_RECVRTDSTOPTS)
10138 				*i1 = 1;
10139 			else
10140 				*i1 = 0;
10141 			break;	/* goto sizeof (int) option return */
10142 		case IPV6_PKTINFO: {
10143 			/* XXX assumes that caller has room for max size! */
10144 			struct in6_pktinfo *pkti;
10145 
10146 			pkti = (struct in6_pktinfo *)ptr;
10147 			if (ipp->ipp_fields & IPPF_IFINDEX)
10148 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10149 			else
10150 				pkti->ipi6_ifindex = 0;
10151 			if (ipp->ipp_fields & IPPF_ADDR)
10152 				pkti->ipi6_addr = ipp->ipp_addr;
10153 			else
10154 				pkti->ipi6_addr = ipv6_all_zeros;
10155 			return (sizeof (struct in6_pktinfo));
10156 		}
10157 		case IPV6_TCLASS:
10158 			if (ipp->ipp_fields & IPPF_TCLASS)
10159 				*i1 = ipp->ipp_tclass;
10160 			else
10161 				*i1 = IPV6_FLOW_TCLASS(
10162 				    IPV6_DEFAULT_VERS_AND_FLOW);
10163 			break;	/* goto sizeof (int) option return */
10164 		case IPV6_NEXTHOP: {
10165 			sin6_t *sin6 = (sin6_t *)ptr;
10166 
10167 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10168 				return (0);
10169 			*sin6 = sin6_null;
10170 			sin6->sin6_family = AF_INET6;
10171 			sin6->sin6_addr = ipp->ipp_nexthop;
10172 			return (sizeof (sin6_t));
10173 		}
10174 		case IPV6_HOPOPTS:
10175 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10176 				return (0);
10177 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
10178 				return (0);
10179 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
10180 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
10181 			if (tcp->tcp_label_len > 0) {
10182 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
10183 				ptr[1] = (ipp->ipp_hopoptslen -
10184 				    tcp->tcp_label_len + 7) / 8 - 1;
10185 			}
10186 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
10187 		case IPV6_RTHDRDSTOPTS:
10188 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10189 				return (0);
10190 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10191 			return (ipp->ipp_rtdstoptslen);
10192 		case IPV6_RTHDR:
10193 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10194 				return (0);
10195 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10196 			return (ipp->ipp_rthdrlen);
10197 		case IPV6_DSTOPTS:
10198 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10199 				return (0);
10200 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10201 			return (ipp->ipp_dstoptslen);
10202 		case IPV6_SRC_PREFERENCES:
10203 			return (ip6_get_src_preferences(connp,
10204 			    (uint32_t *)ptr));
10205 		case IPV6_PATHMTU: {
10206 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10207 
10208 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10209 				return (-1);
10210 
10211 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10212 			    connp->conn_fport, mtuinfo,
10213 			    connp->conn_netstack));
10214 		}
10215 		default:
10216 			return (-1);
10217 		}
10218 		break;
10219 	default:
10220 		return (-1);
10221 	}
10222 	return (sizeof (int));
10223 }
10224 
10225 /*
10226  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10227  * Parameters are assumed to be verified by the caller.
10228  */
10229 /* ARGSUSED */
10230 int
10231 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10232     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10233     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10234 {
10235 	conn_t	*connp = Q_TO_CONN(q);
10236 	tcp_t	*tcp = connp->conn_tcp;
10237 	int	*i1 = (int *)invalp;
10238 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10239 	boolean_t checkonly;
10240 	int	reterr;
10241 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
10242 
10243 	switch (optset_context) {
10244 	case SETFN_OPTCOM_CHECKONLY:
10245 		checkonly = B_TRUE;
10246 		/*
10247 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10248 		 * inlen != 0 implies value supplied and
10249 		 * 	we have to "pretend" to set it.
10250 		 * inlen == 0 implies that there is no
10251 		 * 	value part in T_CHECK request and just validation
10252 		 * done elsewhere should be enough, we just return here.
10253 		 */
10254 		if (inlen == 0) {
10255 			*outlenp = 0;
10256 			return (0);
10257 		}
10258 		break;
10259 	case SETFN_OPTCOM_NEGOTIATE:
10260 		checkonly = B_FALSE;
10261 		break;
10262 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10263 	case SETFN_CONN_NEGOTIATE:
10264 		checkonly = B_FALSE;
10265 		/*
10266 		 * Negotiating local and "association-related" options
10267 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10268 		 * primitives is allowed by XTI, but we choose
10269 		 * to not implement this style negotiation for Internet
10270 		 * protocols (We interpret it is a must for OSI world but
10271 		 * optional for Internet protocols) for all options.
10272 		 * [ Will do only for the few options that enable test
10273 		 * suites that our XTI implementation of this feature
10274 		 * works for transports that do allow it ]
10275 		 */
10276 		if (!tcp_allow_connopt_set(level, name)) {
10277 			*outlenp = 0;
10278 			return (EINVAL);
10279 		}
10280 		break;
10281 	default:
10282 		/*
10283 		 * We should never get here
10284 		 */
10285 		*outlenp = 0;
10286 		return (EINVAL);
10287 	}
10288 
10289 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10290 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10291 
10292 	/*
10293 	 * For TCP, we should have no ancillary data sent down
10294 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10295 	 * has to be zero.
10296 	 */
10297 	ASSERT(thisdg_attrs == NULL);
10298 
10299 	/*
10300 	 * For fixed length options, no sanity check
10301 	 * of passed in length is done. It is assumed *_optcom_req()
10302 	 * routines do the right thing.
10303 	 */
10304 
10305 	switch (level) {
10306 	case SOL_SOCKET:
10307 		switch (name) {
10308 		case SO_LINGER: {
10309 			struct linger *lgr = (struct linger *)invalp;
10310 
10311 			if (!checkonly) {
10312 				if (lgr->l_onoff) {
10313 					tcp->tcp_linger = 1;
10314 					tcp->tcp_lingertime = lgr->l_linger;
10315 				} else {
10316 					tcp->tcp_linger = 0;
10317 					tcp->tcp_lingertime = 0;
10318 				}
10319 				/* struct copy */
10320 				*(struct linger *)outvalp = *lgr;
10321 			} else {
10322 				if (!lgr->l_onoff) {
10323 					((struct linger *)
10324 					    outvalp)->l_onoff = 0;
10325 					((struct linger *)
10326 					    outvalp)->l_linger = 0;
10327 				} else {
10328 					/* struct copy */
10329 					*(struct linger *)outvalp = *lgr;
10330 				}
10331 			}
10332 			*outlenp = sizeof (struct linger);
10333 			return (0);
10334 		}
10335 		case SO_DEBUG:
10336 			if (!checkonly)
10337 				tcp->tcp_debug = onoff;
10338 			break;
10339 		case SO_KEEPALIVE:
10340 			if (checkonly) {
10341 				/* T_CHECK case */
10342 				break;
10343 			}
10344 
10345 			if (!onoff) {
10346 				if (tcp->tcp_ka_enabled) {
10347 					if (tcp->tcp_ka_tid != 0) {
10348 						(void) TCP_TIMER_CANCEL(tcp,
10349 						    tcp->tcp_ka_tid);
10350 						tcp->tcp_ka_tid = 0;
10351 					}
10352 					tcp->tcp_ka_enabled = 0;
10353 				}
10354 				break;
10355 			}
10356 			if (!tcp->tcp_ka_enabled) {
10357 				/* Crank up the keepalive timer */
10358 				tcp->tcp_ka_last_intrvl = 0;
10359 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10360 				    tcp_keepalive_killer,
10361 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10362 				tcp->tcp_ka_enabled = 1;
10363 			}
10364 			break;
10365 		case SO_DONTROUTE:
10366 			/*
10367 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10368 			 * only of interest to IP.  We track them here only so
10369 			 * that we can report their current value.
10370 			 */
10371 			if (!checkonly) {
10372 				tcp->tcp_dontroute = onoff;
10373 				tcp->tcp_connp->conn_dontroute = onoff;
10374 			}
10375 			break;
10376 		case SO_USELOOPBACK:
10377 			if (!checkonly) {
10378 				tcp->tcp_useloopback = onoff;
10379 				tcp->tcp_connp->conn_loopback = onoff;
10380 			}
10381 			break;
10382 		case SO_BROADCAST:
10383 			if (!checkonly) {
10384 				tcp->tcp_broadcast = onoff;
10385 				tcp->tcp_connp->conn_broadcast = onoff;
10386 			}
10387 			break;
10388 		case SO_REUSEADDR:
10389 			if (!checkonly) {
10390 				tcp->tcp_reuseaddr = onoff;
10391 				tcp->tcp_connp->conn_reuseaddr = onoff;
10392 			}
10393 			break;
10394 		case SO_OOBINLINE:
10395 			if (!checkonly)
10396 				tcp->tcp_oobinline = onoff;
10397 			break;
10398 		case SO_DGRAM_ERRIND:
10399 			if (!checkonly)
10400 				tcp->tcp_dgram_errind = onoff;
10401 			break;
10402 		case SO_SNDBUF: {
10403 			if (*i1 > tcps->tcps_max_buf) {
10404 				*outlenp = 0;
10405 				return (ENOBUFS);
10406 			}
10407 			if (checkonly)
10408 				break;
10409 
10410 			tcp->tcp_xmit_hiwater = *i1;
10411 			if (tcps->tcps_snd_lowat_fraction != 0)
10412 				tcp->tcp_xmit_lowater =
10413 				    tcp->tcp_xmit_hiwater /
10414 				    tcps->tcps_snd_lowat_fraction;
10415 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10416 			/*
10417 			 * If we are flow-controlled, recheck the condition.
10418 			 * There are apps that increase SO_SNDBUF size when
10419 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10420 			 * control condition to be lifted right away.
10421 			 */
10422 			mutex_enter(&tcp->tcp_non_sq_lock);
10423 			if (tcp->tcp_flow_stopped &&
10424 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10425 				tcp_clrqfull(tcp);
10426 			}
10427 			mutex_exit(&tcp->tcp_non_sq_lock);
10428 			break;
10429 		}
10430 		case SO_RCVBUF:
10431 			if (*i1 > tcps->tcps_max_buf) {
10432 				*outlenp = 0;
10433 				return (ENOBUFS);
10434 			}
10435 			/* Silently ignore zero */
10436 			if (!checkonly && *i1 != 0) {
10437 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10438 				(void) tcp_rwnd_set(tcp, *i1);
10439 			}
10440 			/*
10441 			 * XXX should we return the rwnd here
10442 			 * and tcp_opt_get ?
10443 			 */
10444 			break;
10445 		case SO_SND_COPYAVOID:
10446 			if (!checkonly) {
10447 				/* we only allow enable at most once for now */
10448 				if (tcp->tcp_loopback ||
10449 				    (tcp->tcp_kssl_ctx != NULL) ||
10450 				    (!tcp->tcp_snd_zcopy_aware &&
10451 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10452 					*outlenp = 0;
10453 					return (EOPNOTSUPP);
10454 				}
10455 				tcp->tcp_snd_zcopy_aware = 1;
10456 			}
10457 			break;
10458 		case SO_ALLZONES:
10459 			/* Pass option along to IP level for handling */
10460 			return (-EINVAL);
10461 		case SO_ANON_MLP:
10462 			/* Pass option along to IP level for handling */
10463 			return (-EINVAL);
10464 		case SO_MAC_EXEMPT:
10465 			/* Pass option along to IP level for handling */
10466 			return (-EINVAL);
10467 		case SO_EXCLBIND:
10468 			if (!checkonly)
10469 				tcp->tcp_exclbind = onoff;
10470 			break;
10471 		default:
10472 			*outlenp = 0;
10473 			return (EINVAL);
10474 		}
10475 		break;
10476 	case IPPROTO_TCP:
10477 		switch (name) {
10478 		case TCP_NODELAY:
10479 			if (!checkonly)
10480 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10481 			break;
10482 		case TCP_NOTIFY_THRESHOLD:
10483 			if (!checkonly)
10484 				tcp->tcp_first_timer_threshold = *i1;
10485 			break;
10486 		case TCP_ABORT_THRESHOLD:
10487 			if (!checkonly)
10488 				tcp->tcp_second_timer_threshold = *i1;
10489 			break;
10490 		case TCP_CONN_NOTIFY_THRESHOLD:
10491 			if (!checkonly)
10492 				tcp->tcp_first_ctimer_threshold = *i1;
10493 			break;
10494 		case TCP_CONN_ABORT_THRESHOLD:
10495 			if (!checkonly)
10496 				tcp->tcp_second_ctimer_threshold = *i1;
10497 			break;
10498 		case TCP_RECVDSTADDR:
10499 			if (tcp->tcp_state > TCPS_LISTEN)
10500 				return (EOPNOTSUPP);
10501 			if (!checkonly)
10502 				tcp->tcp_recvdstaddr = onoff;
10503 			break;
10504 		case TCP_ANONPRIVBIND:
10505 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10506 			    IPPROTO_TCP)) != 0) {
10507 				*outlenp = 0;
10508 				return (reterr);
10509 			}
10510 			if (!checkonly) {
10511 				tcp->tcp_anon_priv_bind = onoff;
10512 			}
10513 			break;
10514 		case TCP_EXCLBIND:
10515 			if (!checkonly)
10516 				tcp->tcp_exclbind = onoff;
10517 			break;	/* goto sizeof (int) option return */
10518 		case TCP_INIT_CWND: {
10519 			uint32_t init_cwnd = *((uint32_t *)invalp);
10520 
10521 			if (checkonly)
10522 				break;
10523 
10524 			/*
10525 			 * Only allow socket with network configuration
10526 			 * privilege to set the initial cwnd to be larger
10527 			 * than allowed by RFC 3390.
10528 			 */
10529 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10530 				tcp->tcp_init_cwnd = init_cwnd;
10531 				break;
10532 			}
10533 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10534 				*outlenp = 0;
10535 				return (reterr);
10536 			}
10537 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10538 				*outlenp = 0;
10539 				return (EINVAL);
10540 			}
10541 			tcp->tcp_init_cwnd = init_cwnd;
10542 			break;
10543 		}
10544 		case TCP_KEEPALIVE_THRESHOLD:
10545 			if (checkonly)
10546 				break;
10547 
10548 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10549 			    *i1 > tcps->tcps_keepalive_interval_high) {
10550 				*outlenp = 0;
10551 				return (EINVAL);
10552 			}
10553 			if (*i1 != tcp->tcp_ka_interval) {
10554 				tcp->tcp_ka_interval = *i1;
10555 				/*
10556 				 * Check if we need to restart the
10557 				 * keepalive timer.
10558 				 */
10559 				if (tcp->tcp_ka_tid != 0) {
10560 					ASSERT(tcp->tcp_ka_enabled);
10561 					(void) TCP_TIMER_CANCEL(tcp,
10562 					    tcp->tcp_ka_tid);
10563 					tcp->tcp_ka_last_intrvl = 0;
10564 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10565 					    tcp_keepalive_killer,
10566 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10567 				}
10568 			}
10569 			break;
10570 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10571 			if (!checkonly) {
10572 				if (*i1 <
10573 				    tcps->tcps_keepalive_abort_interval_low ||
10574 				    *i1 >
10575 				    tcps->tcps_keepalive_abort_interval_high) {
10576 					*outlenp = 0;
10577 					return (EINVAL);
10578 				}
10579 				tcp->tcp_ka_abort_thres = *i1;
10580 			}
10581 			break;
10582 		case TCP_CORK:
10583 			if (!checkonly) {
10584 				/*
10585 				 * if tcp->tcp_cork was set and is now
10586 				 * being unset, we have to make sure that
10587 				 * the remaining data gets sent out. Also
10588 				 * unset tcp->tcp_cork so that tcp_wput_data()
10589 				 * can send data even if it is less than mss
10590 				 */
10591 				if (tcp->tcp_cork && onoff == 0 &&
10592 				    tcp->tcp_unsent > 0) {
10593 					tcp->tcp_cork = B_FALSE;
10594 					tcp_wput_data(tcp, NULL, B_FALSE);
10595 				}
10596 				tcp->tcp_cork = onoff;
10597 			}
10598 			break;
10599 		default:
10600 			*outlenp = 0;
10601 			return (EINVAL);
10602 		}
10603 		break;
10604 	case IPPROTO_IP:
10605 		if (tcp->tcp_family != AF_INET) {
10606 			*outlenp = 0;
10607 			return (ENOPROTOOPT);
10608 		}
10609 		switch (name) {
10610 		case IP_OPTIONS:
10611 		case T_IP_OPTIONS:
10612 			reterr = tcp_opt_set_header(tcp, checkonly,
10613 			    invalp, inlen);
10614 			if (reterr) {
10615 				*outlenp = 0;
10616 				return (reterr);
10617 			}
10618 			/* OK return - copy input buffer into output buffer */
10619 			if (invalp != outvalp) {
10620 				/* don't trust bcopy for identical src/dst */
10621 				bcopy(invalp, outvalp, inlen);
10622 			}
10623 			*outlenp = inlen;
10624 			return (0);
10625 		case IP_TOS:
10626 		case T_IP_TOS:
10627 			if (!checkonly) {
10628 				tcp->tcp_ipha->ipha_type_of_service =
10629 				    (uchar_t)*i1;
10630 				tcp->tcp_tos = (uchar_t)*i1;
10631 			}
10632 			break;
10633 		case IP_TTL:
10634 			if (!checkonly) {
10635 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10636 				tcp->tcp_ttl = (uchar_t)*i1;
10637 			}
10638 			break;
10639 		case IP_BOUND_IF:
10640 		case IP_NEXTHOP:
10641 			/* Handled at the IP level */
10642 			return (-EINVAL);
10643 		case IP_SEC_OPT:
10644 			/*
10645 			 * We should not allow policy setting after
10646 			 * we start listening for connections.
10647 			 */
10648 			if (tcp->tcp_state == TCPS_LISTEN) {
10649 				return (EINVAL);
10650 			} else {
10651 				/* Handled at the IP level */
10652 				return (-EINVAL);
10653 			}
10654 		default:
10655 			*outlenp = 0;
10656 			return (EINVAL);
10657 		}
10658 		break;
10659 	case IPPROTO_IPV6: {
10660 		ip6_pkt_t		*ipp;
10661 
10662 		/*
10663 		 * IPPROTO_IPV6 options are only supported for sockets
10664 		 * that are using IPv6 on the wire.
10665 		 */
10666 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10667 			*outlenp = 0;
10668 			return (ENOPROTOOPT);
10669 		}
10670 		/*
10671 		 * Only sticky options; no ancillary data
10672 		 */
10673 		ASSERT(thisdg_attrs == NULL);
10674 		ipp = &tcp->tcp_sticky_ipp;
10675 
10676 		switch (name) {
10677 		case IPV6_UNICAST_HOPS:
10678 			/* -1 means use default */
10679 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10680 				*outlenp = 0;
10681 				return (EINVAL);
10682 			}
10683 			if (!checkonly) {
10684 				if (*i1 == -1) {
10685 					tcp->tcp_ip6h->ip6_hops =
10686 					    ipp->ipp_unicast_hops =
10687 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10688 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10689 					/* Pass modified value to IP. */
10690 					*i1 = tcp->tcp_ip6h->ip6_hops;
10691 				} else {
10692 					tcp->tcp_ip6h->ip6_hops =
10693 					    ipp->ipp_unicast_hops =
10694 					    (uint8_t)*i1;
10695 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10696 				}
10697 				reterr = tcp_build_hdrs(q, tcp);
10698 				if (reterr != 0)
10699 					return (reterr);
10700 			}
10701 			break;
10702 		case IPV6_BOUND_IF:
10703 			if (!checkonly) {
10704 				int error = 0;
10705 
10706 				tcp->tcp_bound_if = *i1;
10707 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10708 				    B_TRUE, checkonly, level, name, mblk);
10709 				if (error != 0) {
10710 					*outlenp = 0;
10711 					return (error);
10712 				}
10713 			}
10714 			break;
10715 		/*
10716 		 * Set boolean switches for ancillary data delivery
10717 		 */
10718 		case IPV6_RECVPKTINFO:
10719 			if (!checkonly) {
10720 				if (onoff)
10721 					tcp->tcp_ipv6_recvancillary |=
10722 					    TCP_IPV6_RECVPKTINFO;
10723 				else
10724 					tcp->tcp_ipv6_recvancillary &=
10725 					    ~TCP_IPV6_RECVPKTINFO;
10726 				/* Force it to be sent up with the next msg */
10727 				tcp->tcp_recvifindex = 0;
10728 			}
10729 			break;
10730 		case IPV6_RECVTCLASS:
10731 			if (!checkonly) {
10732 				if (onoff)
10733 					tcp->tcp_ipv6_recvancillary |=
10734 					    TCP_IPV6_RECVTCLASS;
10735 				else
10736 					tcp->tcp_ipv6_recvancillary &=
10737 					    ~TCP_IPV6_RECVTCLASS;
10738 			}
10739 			break;
10740 		case IPV6_RECVHOPLIMIT:
10741 			if (!checkonly) {
10742 				if (onoff)
10743 					tcp->tcp_ipv6_recvancillary |=
10744 					    TCP_IPV6_RECVHOPLIMIT;
10745 				else
10746 					tcp->tcp_ipv6_recvancillary &=
10747 					    ~TCP_IPV6_RECVHOPLIMIT;
10748 				/* Force it to be sent up with the next msg */
10749 				tcp->tcp_recvhops = 0xffffffffU;
10750 			}
10751 			break;
10752 		case IPV6_RECVHOPOPTS:
10753 			if (!checkonly) {
10754 				if (onoff)
10755 					tcp->tcp_ipv6_recvancillary |=
10756 					    TCP_IPV6_RECVHOPOPTS;
10757 				else
10758 					tcp->tcp_ipv6_recvancillary &=
10759 					    ~TCP_IPV6_RECVHOPOPTS;
10760 			}
10761 			break;
10762 		case IPV6_RECVDSTOPTS:
10763 			if (!checkonly) {
10764 				if (onoff)
10765 					tcp->tcp_ipv6_recvancillary |=
10766 					    TCP_IPV6_RECVDSTOPTS;
10767 				else
10768 					tcp->tcp_ipv6_recvancillary &=
10769 					    ~TCP_IPV6_RECVDSTOPTS;
10770 			}
10771 			break;
10772 		case _OLD_IPV6_RECVDSTOPTS:
10773 			if (!checkonly) {
10774 				if (onoff)
10775 					tcp->tcp_ipv6_recvancillary |=
10776 					    TCP_OLD_IPV6_RECVDSTOPTS;
10777 				else
10778 					tcp->tcp_ipv6_recvancillary &=
10779 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10780 			}
10781 			break;
10782 		case IPV6_RECVRTHDR:
10783 			if (!checkonly) {
10784 				if (onoff)
10785 					tcp->tcp_ipv6_recvancillary |=
10786 					    TCP_IPV6_RECVRTHDR;
10787 				else
10788 					tcp->tcp_ipv6_recvancillary &=
10789 					    ~TCP_IPV6_RECVRTHDR;
10790 			}
10791 			break;
10792 		case IPV6_RECVRTHDRDSTOPTS:
10793 			if (!checkonly) {
10794 				if (onoff)
10795 					tcp->tcp_ipv6_recvancillary |=
10796 					    TCP_IPV6_RECVRTDSTOPTS;
10797 				else
10798 					tcp->tcp_ipv6_recvancillary &=
10799 					    ~TCP_IPV6_RECVRTDSTOPTS;
10800 			}
10801 			break;
10802 		case IPV6_PKTINFO:
10803 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10804 				return (EINVAL);
10805 			if (checkonly)
10806 				break;
10807 
10808 			if (inlen == 0) {
10809 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10810 			} else {
10811 				struct in6_pktinfo *pkti;
10812 
10813 				pkti = (struct in6_pktinfo *)invalp;
10814 				/*
10815 				 * RFC 3542 states that ipi6_addr must be
10816 				 * the unspecified address when setting the
10817 				 * IPV6_PKTINFO sticky socket option on a
10818 				 * TCP socket.
10819 				 */
10820 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10821 					return (EINVAL);
10822 				/*
10823 				 * ip6_set_pktinfo() validates the source
10824 				 * address and interface index.
10825 				 */
10826 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10827 				    pkti, mblk);
10828 				if (reterr != 0)
10829 					return (reterr);
10830 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10831 				ipp->ipp_addr = pkti->ipi6_addr;
10832 				if (ipp->ipp_ifindex != 0)
10833 					ipp->ipp_fields |= IPPF_IFINDEX;
10834 				else
10835 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10836 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10837 					ipp->ipp_fields |= IPPF_ADDR;
10838 				else
10839 					ipp->ipp_fields &= ~IPPF_ADDR;
10840 			}
10841 			reterr = tcp_build_hdrs(q, tcp);
10842 			if (reterr != 0)
10843 				return (reterr);
10844 			break;
10845 		case IPV6_TCLASS:
10846 			if (inlen != 0 && inlen != sizeof (int))
10847 				return (EINVAL);
10848 			if (checkonly)
10849 				break;
10850 
10851 			if (inlen == 0) {
10852 				ipp->ipp_fields &= ~IPPF_TCLASS;
10853 			} else {
10854 				if (*i1 > 255 || *i1 < -1)
10855 					return (EINVAL);
10856 				if (*i1 == -1) {
10857 					ipp->ipp_tclass = 0;
10858 					*i1 = 0;
10859 				} else {
10860 					ipp->ipp_tclass = *i1;
10861 				}
10862 				ipp->ipp_fields |= IPPF_TCLASS;
10863 			}
10864 			reterr = tcp_build_hdrs(q, tcp);
10865 			if (reterr != 0)
10866 				return (reterr);
10867 			break;
10868 		case IPV6_NEXTHOP:
10869 			/*
10870 			 * IP will verify that the nexthop is reachable
10871 			 * and fail for sticky options.
10872 			 */
10873 			if (inlen != 0 && inlen != sizeof (sin6_t))
10874 				return (EINVAL);
10875 			if (checkonly)
10876 				break;
10877 
10878 			if (inlen == 0) {
10879 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10880 			} else {
10881 				sin6_t *sin6 = (sin6_t *)invalp;
10882 
10883 				if (sin6->sin6_family != AF_INET6)
10884 					return (EAFNOSUPPORT);
10885 				if (IN6_IS_ADDR_V4MAPPED(
10886 				    &sin6->sin6_addr))
10887 					return (EADDRNOTAVAIL);
10888 				ipp->ipp_nexthop = sin6->sin6_addr;
10889 				if (!IN6_IS_ADDR_UNSPECIFIED(
10890 				    &ipp->ipp_nexthop))
10891 					ipp->ipp_fields |= IPPF_NEXTHOP;
10892 				else
10893 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10894 			}
10895 			reterr = tcp_build_hdrs(q, tcp);
10896 			if (reterr != 0)
10897 				return (reterr);
10898 			break;
10899 		case IPV6_HOPOPTS: {
10900 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10901 
10902 			/*
10903 			 * Sanity checks - minimum size, size a multiple of
10904 			 * eight bytes, and matching size passed in.
10905 			 */
10906 			if (inlen != 0 &&
10907 			    inlen != (8 * (hopts->ip6h_len + 1)))
10908 				return (EINVAL);
10909 
10910 			if (checkonly)
10911 				break;
10912 
10913 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10914 			    (uchar_t **)&ipp->ipp_hopopts,
10915 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10916 			if (reterr != 0)
10917 				return (reterr);
10918 			if (ipp->ipp_hopoptslen == 0)
10919 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10920 			else
10921 				ipp->ipp_fields |= IPPF_HOPOPTS;
10922 			reterr = tcp_build_hdrs(q, tcp);
10923 			if (reterr != 0)
10924 				return (reterr);
10925 			break;
10926 		}
10927 		case IPV6_RTHDRDSTOPTS: {
10928 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10929 
10930 			/*
10931 			 * Sanity checks - minimum size, size a multiple of
10932 			 * eight bytes, and matching size passed in.
10933 			 */
10934 			if (inlen != 0 &&
10935 			    inlen != (8 * (dopts->ip6d_len + 1)))
10936 				return (EINVAL);
10937 
10938 			if (checkonly)
10939 				break;
10940 
10941 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10942 			    (uchar_t **)&ipp->ipp_rtdstopts,
10943 			    &ipp->ipp_rtdstoptslen, 0);
10944 			if (reterr != 0)
10945 				return (reterr);
10946 			if (ipp->ipp_rtdstoptslen == 0)
10947 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10948 			else
10949 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10950 			reterr = tcp_build_hdrs(q, tcp);
10951 			if (reterr != 0)
10952 				return (reterr);
10953 			break;
10954 		}
10955 		case IPV6_DSTOPTS: {
10956 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10957 
10958 			/*
10959 			 * Sanity checks - minimum size, size a multiple of
10960 			 * eight bytes, and matching size passed in.
10961 			 */
10962 			if (inlen != 0 &&
10963 			    inlen != (8 * (dopts->ip6d_len + 1)))
10964 				return (EINVAL);
10965 
10966 			if (checkonly)
10967 				break;
10968 
10969 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10970 			    (uchar_t **)&ipp->ipp_dstopts,
10971 			    &ipp->ipp_dstoptslen, 0);
10972 			if (reterr != 0)
10973 				return (reterr);
10974 			if (ipp->ipp_dstoptslen == 0)
10975 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10976 			else
10977 				ipp->ipp_fields |= IPPF_DSTOPTS;
10978 			reterr = tcp_build_hdrs(q, tcp);
10979 			if (reterr != 0)
10980 				return (reterr);
10981 			break;
10982 		}
10983 		case IPV6_RTHDR: {
10984 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10985 
10986 			/*
10987 			 * Sanity checks - minimum size, size a multiple of
10988 			 * eight bytes, and matching size passed in.
10989 			 */
10990 			if (inlen != 0 &&
10991 			    inlen != (8 * (rt->ip6r_len + 1)))
10992 				return (EINVAL);
10993 
10994 			if (checkonly)
10995 				break;
10996 
10997 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10998 			    (uchar_t **)&ipp->ipp_rthdr,
10999 			    &ipp->ipp_rthdrlen, 0);
11000 			if (reterr != 0)
11001 				return (reterr);
11002 			if (ipp->ipp_rthdrlen == 0)
11003 				ipp->ipp_fields &= ~IPPF_RTHDR;
11004 			else
11005 				ipp->ipp_fields |= IPPF_RTHDR;
11006 			reterr = tcp_build_hdrs(q, tcp);
11007 			if (reterr != 0)
11008 				return (reterr);
11009 			break;
11010 		}
11011 		case IPV6_V6ONLY:
11012 			if (!checkonly)
11013 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
11014 			break;
11015 		case IPV6_USE_MIN_MTU:
11016 			if (inlen != sizeof (int))
11017 				return (EINVAL);
11018 
11019 			if (*i1 < -1 || *i1 > 1)
11020 				return (EINVAL);
11021 
11022 			if (checkonly)
11023 				break;
11024 
11025 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
11026 			ipp->ipp_use_min_mtu = *i1;
11027 			break;
11028 		case IPV6_BOUND_PIF:
11029 			/* Handled at the IP level */
11030 			return (-EINVAL);
11031 		case IPV6_SEC_OPT:
11032 			/*
11033 			 * We should not allow policy setting after
11034 			 * we start listening for connections.
11035 			 */
11036 			if (tcp->tcp_state == TCPS_LISTEN) {
11037 				return (EINVAL);
11038 			} else {
11039 				/* Handled at the IP level */
11040 				return (-EINVAL);
11041 			}
11042 		case IPV6_SRC_PREFERENCES:
11043 			if (inlen != sizeof (uint32_t))
11044 				return (EINVAL);
11045 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
11046 			    *(uint32_t *)invalp);
11047 			if (reterr != 0) {
11048 				*outlenp = 0;
11049 				return (reterr);
11050 			}
11051 			break;
11052 		default:
11053 			*outlenp = 0;
11054 			return (EINVAL);
11055 		}
11056 		break;
11057 	}		/* end IPPROTO_IPV6 */
11058 	default:
11059 		*outlenp = 0;
11060 		return (EINVAL);
11061 	}
11062 	/*
11063 	 * Common case of OK return with outval same as inval
11064 	 */
11065 	if (invalp != outvalp) {
11066 		/* don't trust bcopy for identical src/dst */
11067 		(void) bcopy(invalp, outvalp, inlen);
11068 	}
11069 	*outlenp = inlen;
11070 	return (0);
11071 }
11072 
11073 /*
11074  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11075  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11076  * headers, and the maximum size tcp header (to avoid reallocation
11077  * on the fly for additional tcp options).
11078  * Returns failure if can't allocate memory.
11079  */
11080 static int
11081 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11082 {
11083 	char	*hdrs;
11084 	uint_t	hdrs_len;
11085 	ip6i_t	*ip6i;
11086 	char	buf[TCP_MAX_HDR_LENGTH];
11087 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11088 	in6_addr_t src, dst;
11089 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11090 
11091 	/*
11092 	 * save the existing tcp header and source/dest IP addresses
11093 	 */
11094 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11095 	src = tcp->tcp_ip6h->ip6_src;
11096 	dst = tcp->tcp_ip6h->ip6_dst;
11097 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11098 	ASSERT(hdrs_len != 0);
11099 	if (hdrs_len > tcp->tcp_iphc_len) {
11100 		/* Need to reallocate */
11101 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11102 		if (hdrs == NULL)
11103 			return (ENOMEM);
11104 		if (tcp->tcp_iphc != NULL) {
11105 			if (tcp->tcp_hdr_grown) {
11106 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11107 			} else {
11108 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11109 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11110 			}
11111 			tcp->tcp_iphc_len = 0;
11112 		}
11113 		ASSERT(tcp->tcp_iphc_len == 0);
11114 		tcp->tcp_iphc = hdrs;
11115 		tcp->tcp_iphc_len = hdrs_len;
11116 		tcp->tcp_hdr_grown = B_TRUE;
11117 	}
11118 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11119 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11120 
11121 	/* Set header fields not in ipp */
11122 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11123 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11124 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11125 	} else {
11126 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11127 	}
11128 	/*
11129 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11130 	 *
11131 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11132 	 */
11133 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11134 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11135 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11136 
11137 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11138 
11139 	tcp->tcp_ip6h->ip6_src = src;
11140 	tcp->tcp_ip6h->ip6_dst = dst;
11141 
11142 	/*
11143 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11144 	 * the default value for TCP.
11145 	 */
11146 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11147 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
11148 
11149 	/*
11150 	 * If we're setting extension headers after a connection
11151 	 * has been established, and if we have a routing header
11152 	 * among the extension headers, call ip_massage_options_v6 to
11153 	 * manipulate the routing header/ip6_dst set the checksum
11154 	 * difference in the tcp header template.
11155 	 * (This happens in tcp_connect_ipv6 if the routing header
11156 	 * is set prior to the connect.)
11157 	 * Set the tcp_sum to zero first in case we've cleared a
11158 	 * routing header or don't have one at all.
11159 	 */
11160 	tcp->tcp_sum = 0;
11161 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11162 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11163 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11164 		    (uint8_t *)tcp->tcp_tcph);
11165 		if (rth != NULL) {
11166 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11167 			    rth, tcps->tcps_netstack);
11168 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11169 			    (tcp->tcp_sum >> 16));
11170 		}
11171 	}
11172 
11173 	/* Try to get everything in a single mblk */
11174 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcps->tcps_wroff_xtra);
11175 	return (0);
11176 }
11177 
11178 /*
11179  * Transfer any source route option from ipha to buf/dst in reversed form.
11180  */
11181 static int
11182 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11183 {
11184 	ipoptp_t	opts;
11185 	uchar_t		*opt;
11186 	uint8_t		optval;
11187 	uint8_t		optlen;
11188 	uint32_t	len = 0;
11189 
11190 	for (optval = ipoptp_first(&opts, ipha);
11191 	    optval != IPOPT_EOL;
11192 	    optval = ipoptp_next(&opts)) {
11193 		opt = opts.ipoptp_cur;
11194 		optlen = opts.ipoptp_len;
11195 		switch (optval) {
11196 			int	off1, off2;
11197 		case IPOPT_SSRR:
11198 		case IPOPT_LSRR:
11199 
11200 			/* Reverse source route */
11201 			/*
11202 			 * First entry should be the next to last one in the
11203 			 * current source route (the last entry is our
11204 			 * address.)
11205 			 * The last entry should be the final destination.
11206 			 */
11207 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11208 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11209 			off1 = IPOPT_MINOFF_SR - 1;
11210 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11211 			if (off2 < 0) {
11212 				/* No entries in source route */
11213 				break;
11214 			}
11215 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11216 			/*
11217 			 * Note: use src since ipha has not had its src
11218 			 * and dst reversed (it is in the state it was
11219 			 * received.
11220 			 */
11221 			bcopy(&ipha->ipha_src, buf + off2,
11222 			    IP_ADDR_LEN);
11223 			off2 -= IP_ADDR_LEN;
11224 
11225 			while (off2 > 0) {
11226 				bcopy(opt + off2, buf + off1,
11227 				    IP_ADDR_LEN);
11228 				off1 += IP_ADDR_LEN;
11229 				off2 -= IP_ADDR_LEN;
11230 			}
11231 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11232 			buf += optlen;
11233 			len += optlen;
11234 			break;
11235 		}
11236 	}
11237 done:
11238 	/* Pad the resulting options */
11239 	while (len & 0x3) {
11240 		*buf++ = IPOPT_EOL;
11241 		len++;
11242 	}
11243 	return (len);
11244 }
11245 
11246 
11247 /*
11248  * Extract and revert a source route from ipha (if any)
11249  * and then update the relevant fields in both tcp_t and the standard header.
11250  */
11251 static void
11252 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11253 {
11254 	char	buf[TCP_MAX_HDR_LENGTH];
11255 	uint_t	tcph_len;
11256 	int	len;
11257 
11258 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11259 	len = IPH_HDR_LENGTH(ipha);
11260 	if (len == IP_SIMPLE_HDR_LENGTH)
11261 		/* Nothing to do */
11262 		return;
11263 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11264 	    (len & 0x3))
11265 		return;
11266 
11267 	tcph_len = tcp->tcp_tcp_hdr_len;
11268 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11269 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11270 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11271 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11272 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11273 	len += IP_SIMPLE_HDR_LENGTH;
11274 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11275 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11276 	if ((int)tcp->tcp_sum < 0)
11277 		tcp->tcp_sum--;
11278 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11279 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11280 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11281 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11282 	tcp->tcp_ip_hdr_len = len;
11283 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11284 	    (IP_VERSION << 4) | (len >> 2);
11285 	len += tcph_len;
11286 	tcp->tcp_hdr_len = len;
11287 }
11288 
11289 /*
11290  * Copy the standard header into its new location,
11291  * lay in the new options and then update the relevant
11292  * fields in both tcp_t and the standard header.
11293  */
11294 static int
11295 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11296 {
11297 	uint_t	tcph_len;
11298 	uint8_t	*ip_optp;
11299 	tcph_t	*new_tcph;
11300 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11301 
11302 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11303 		return (EINVAL);
11304 
11305 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11306 		return (EINVAL);
11307 
11308 	if (checkonly) {
11309 		/*
11310 		 * do not really set, just pretend to - T_CHECK
11311 		 */
11312 		return (0);
11313 	}
11314 
11315 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11316 	if (tcp->tcp_label_len > 0) {
11317 		int padlen;
11318 		uint8_t opt;
11319 
11320 		/* convert list termination to no-ops */
11321 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11322 		ip_optp += ip_optp[IPOPT_OLEN];
11323 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11324 		while (--padlen >= 0)
11325 			*ip_optp++ = opt;
11326 	}
11327 	tcph_len = tcp->tcp_tcp_hdr_len;
11328 	new_tcph = (tcph_t *)(ip_optp + len);
11329 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11330 	tcp->tcp_tcph = new_tcph;
11331 	bcopy(ptr, ip_optp, len);
11332 
11333 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11334 
11335 	tcp->tcp_ip_hdr_len = len;
11336 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11337 	    (IP_VERSION << 4) | (len >> 2);
11338 	tcp->tcp_hdr_len = len + tcph_len;
11339 	if (!TCP_IS_DETACHED(tcp)) {
11340 		/* Always allocate room for all options. */
11341 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11342 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11343 	}
11344 	return (0);
11345 }
11346 
11347 /* Get callback routine passed to nd_load by tcp_param_register */
11348 /* ARGSUSED */
11349 static int
11350 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11351 {
11352 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11353 
11354 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11355 	return (0);
11356 }
11357 
11358 /*
11359  * Walk through the param array specified registering each element with the
11360  * named dispatch handler.
11361  */
11362 static boolean_t
11363 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11364 {
11365 	for (; cnt-- > 0; tcppa++) {
11366 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11367 			if (!nd_load(ndp, tcppa->tcp_param_name,
11368 			    tcp_param_get, tcp_param_set,
11369 			    (caddr_t)tcppa)) {
11370 				nd_free(ndp);
11371 				return (B_FALSE);
11372 			}
11373 		}
11374 	}
11375 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11376 	    KM_SLEEP);
11377 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11378 	    sizeof (tcpparam_t));
11379 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11380 	    tcp_param_get, tcp_param_set_aligned,
11381 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11382 		nd_free(ndp);
11383 		return (B_FALSE);
11384 	}
11385 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11386 	    KM_SLEEP);
11387 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11388 	    sizeof (tcpparam_t));
11389 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11390 	    tcp_param_get, tcp_param_set_aligned,
11391 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11392 		nd_free(ndp);
11393 		return (B_FALSE);
11394 	}
11395 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11396 	    KM_SLEEP);
11397 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11398 	    sizeof (tcpparam_t));
11399 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11400 	    tcp_param_get, tcp_param_set_aligned,
11401 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11402 		nd_free(ndp);
11403 		return (B_FALSE);
11404 	}
11405 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11406 	    KM_SLEEP);
11407 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11408 	    sizeof (tcpparam_t));
11409 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11410 	    tcp_param_get, tcp_param_set_aligned,
11411 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11412 		nd_free(ndp);
11413 		return (B_FALSE);
11414 	}
11415 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11416 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11417 		nd_free(ndp);
11418 		return (B_FALSE);
11419 	}
11420 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11421 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11422 		nd_free(ndp);
11423 		return (B_FALSE);
11424 	}
11425 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11426 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11427 		nd_free(ndp);
11428 		return (B_FALSE);
11429 	}
11430 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11431 	    NULL)) {
11432 		nd_free(ndp);
11433 		return (B_FALSE);
11434 	}
11435 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11436 	    NULL, NULL)) {
11437 		nd_free(ndp);
11438 		return (B_FALSE);
11439 	}
11440 	if (!nd_load(ndp, "tcp_listen_hash",
11441 	    tcp_listen_hash_report, NULL, NULL)) {
11442 		nd_free(ndp);
11443 		return (B_FALSE);
11444 	}
11445 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11446 	    NULL, NULL)) {
11447 		nd_free(ndp);
11448 		return (B_FALSE);
11449 	}
11450 	if (!nd_load(ndp, "tcp_acceptor_hash",
11451 	    tcp_acceptor_hash_report, NULL, NULL)) {
11452 		nd_free(ndp);
11453 		return (B_FALSE);
11454 	}
11455 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11456 	    tcp_1948_phrase_set, NULL)) {
11457 		nd_free(ndp);
11458 		return (B_FALSE);
11459 	}
11460 	/*
11461 	 * Dummy ndd variables - only to convey obsolescence information
11462 	 * through printing of their name (no get or set routines)
11463 	 * XXX Remove in future releases ?
11464 	 */
11465 	if (!nd_load(ndp,
11466 	    "tcp_close_wait_interval(obsoleted - "
11467 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11468 		nd_free(ndp);
11469 		return (B_FALSE);
11470 	}
11471 	return (B_TRUE);
11472 }
11473 
11474 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11475 /* ARGSUSED */
11476 static int
11477 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11478     cred_t *cr)
11479 {
11480 	long new_value;
11481 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11482 
11483 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11484 	    new_value < tcppa->tcp_param_min ||
11485 	    new_value > tcppa->tcp_param_max) {
11486 		return (EINVAL);
11487 	}
11488 	/*
11489 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11490 	 * round it up.  For future 64 bit requirement, we actually make it
11491 	 * a multiple of 8.
11492 	 */
11493 	if (new_value & 0x7) {
11494 		new_value = (new_value & ~0x7) + 0x8;
11495 	}
11496 	tcppa->tcp_param_val = new_value;
11497 	return (0);
11498 }
11499 
11500 /* Set callback routine passed to nd_load by tcp_param_register */
11501 /* ARGSUSED */
11502 static int
11503 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11504 {
11505 	long	new_value;
11506 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11507 
11508 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11509 	    new_value < tcppa->tcp_param_min ||
11510 	    new_value > tcppa->tcp_param_max) {
11511 		return (EINVAL);
11512 	}
11513 	tcppa->tcp_param_val = new_value;
11514 	return (0);
11515 }
11516 
11517 /*
11518  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11519  * is filled, return as much as we can.  The message passed in may be
11520  * multi-part, chained using b_cont.  "start" is the starting sequence
11521  * number for this piece.
11522  */
11523 static mblk_t *
11524 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11525 {
11526 	uint32_t	end;
11527 	mblk_t		*mp1;
11528 	mblk_t		*mp2;
11529 	mblk_t		*next_mp;
11530 	uint32_t	u1;
11531 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11532 
11533 	/* Walk through all the new pieces. */
11534 	do {
11535 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11536 		    (uintptr_t)INT_MAX);
11537 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11538 		next_mp = mp->b_cont;
11539 		if (start == end) {
11540 			/* Empty.  Blast it. */
11541 			freeb(mp);
11542 			continue;
11543 		}
11544 		mp->b_cont = NULL;
11545 		TCP_REASS_SET_SEQ(mp, start);
11546 		TCP_REASS_SET_END(mp, end);
11547 		mp1 = tcp->tcp_reass_tail;
11548 		if (!mp1) {
11549 			tcp->tcp_reass_tail = mp;
11550 			tcp->tcp_reass_head = mp;
11551 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11552 			UPDATE_MIB(&tcps->tcps_mib,
11553 			    tcpInDataUnorderBytes, end - start);
11554 			continue;
11555 		}
11556 		/* New stuff completely beyond tail? */
11557 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11558 			/* Link it on end. */
11559 			mp1->b_cont = mp;
11560 			tcp->tcp_reass_tail = mp;
11561 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11562 			UPDATE_MIB(&tcps->tcps_mib,
11563 			    tcpInDataUnorderBytes, end - start);
11564 			continue;
11565 		}
11566 		mp1 = tcp->tcp_reass_head;
11567 		u1 = TCP_REASS_SEQ(mp1);
11568 		/* New stuff at the front? */
11569 		if (SEQ_LT(start, u1)) {
11570 			/* Yes... Check for overlap. */
11571 			mp->b_cont = mp1;
11572 			tcp->tcp_reass_head = mp;
11573 			tcp_reass_elim_overlap(tcp, mp);
11574 			continue;
11575 		}
11576 		/*
11577 		 * The new piece fits somewhere between the head and tail.
11578 		 * We find our slot, where mp1 precedes us and mp2 trails.
11579 		 */
11580 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11581 			u1 = TCP_REASS_SEQ(mp2);
11582 			if (SEQ_LEQ(start, u1))
11583 				break;
11584 		}
11585 		/* Link ourselves in */
11586 		mp->b_cont = mp2;
11587 		mp1->b_cont = mp;
11588 
11589 		/* Trim overlap with following mblk(s) first */
11590 		tcp_reass_elim_overlap(tcp, mp);
11591 
11592 		/* Trim overlap with preceding mblk */
11593 		tcp_reass_elim_overlap(tcp, mp1);
11594 
11595 	} while (start = end, mp = next_mp);
11596 	mp1 = tcp->tcp_reass_head;
11597 	/* Anything ready to go? */
11598 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11599 		return (NULL);
11600 	/* Eat what we can off the queue */
11601 	for (;;) {
11602 		mp = mp1->b_cont;
11603 		end = TCP_REASS_END(mp1);
11604 		TCP_REASS_SET_SEQ(mp1, 0);
11605 		TCP_REASS_SET_END(mp1, 0);
11606 		if (!mp) {
11607 			tcp->tcp_reass_tail = NULL;
11608 			break;
11609 		}
11610 		if (end != TCP_REASS_SEQ(mp)) {
11611 			mp1->b_cont = NULL;
11612 			break;
11613 		}
11614 		mp1 = mp;
11615 	}
11616 	mp1 = tcp->tcp_reass_head;
11617 	tcp->tcp_reass_head = mp;
11618 	return (mp1);
11619 }
11620 
11621 /* Eliminate any overlap that mp may have over later mblks */
11622 static void
11623 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11624 {
11625 	uint32_t	end;
11626 	mblk_t		*mp1;
11627 	uint32_t	u1;
11628 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11629 
11630 	end = TCP_REASS_END(mp);
11631 	while ((mp1 = mp->b_cont) != NULL) {
11632 		u1 = TCP_REASS_SEQ(mp1);
11633 		if (!SEQ_GT(end, u1))
11634 			break;
11635 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11636 			mp->b_wptr -= end - u1;
11637 			TCP_REASS_SET_END(mp, u1);
11638 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11639 			UPDATE_MIB(&tcps->tcps_mib,
11640 			    tcpInDataPartDupBytes, end - u1);
11641 			break;
11642 		}
11643 		mp->b_cont = mp1->b_cont;
11644 		TCP_REASS_SET_SEQ(mp1, 0);
11645 		TCP_REASS_SET_END(mp1, 0);
11646 		freeb(mp1);
11647 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11648 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11649 	}
11650 	if (!mp1)
11651 		tcp->tcp_reass_tail = mp;
11652 }
11653 
11654 /*
11655  * Send up all messages queued on tcp_rcv_list.
11656  */
11657 static uint_t
11658 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11659 {
11660 	mblk_t *mp;
11661 	uint_t ret = 0;
11662 	uint_t thwin;
11663 #ifdef DEBUG
11664 	uint_t cnt = 0;
11665 #endif
11666 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11667 
11668 	/* Can't drain on an eager connection */
11669 	if (tcp->tcp_listener != NULL)
11670 		return (ret);
11671 
11672 	/* Can't be sodirect enabled */
11673 	ASSERT(SOD_NOT_ENABLED(tcp));
11674 
11675 	/* No need for the push timer now. */
11676 	if (tcp->tcp_push_tid != 0) {
11677 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11678 		tcp->tcp_push_tid = 0;
11679 	}
11680 
11681 	/*
11682 	 * Handle two cases here: we are currently fused or we were
11683 	 * previously fused and have some urgent data to be delivered
11684 	 * upstream.  The latter happens because we either ran out of
11685 	 * memory or were detached and therefore sending the SIGURG was
11686 	 * deferred until this point.  In either case we pass control
11687 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11688 	 * some work.
11689 	 */
11690 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11691 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11692 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11693 		    &tcp->tcp_fused_sigurg_mp))
11694 			return (ret);
11695 	}
11696 
11697 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11698 		tcp->tcp_rcv_list = mp->b_next;
11699 		mp->b_next = NULL;
11700 #ifdef DEBUG
11701 		cnt += msgdsize(mp);
11702 #endif
11703 		/* Does this need SSL processing first? */
11704 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11705 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11706 			    mblk_t *, mp);
11707 			tcp_kssl_input(tcp, mp);
11708 			continue;
11709 		}
11710 		putnext(q, mp);
11711 	}
11712 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11713 	tcp->tcp_rcv_last_head = NULL;
11714 	tcp->tcp_rcv_last_tail = NULL;
11715 	tcp->tcp_rcv_cnt = 0;
11716 
11717 	/* Learn the latest rwnd information that we sent to the other side. */
11718 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11719 	    << tcp->tcp_rcv_ws;
11720 	/* This is peer's calculated send window (our receive window). */
11721 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11722 	/*
11723 	 * Increase the receive window to max.  But we need to do receiver
11724 	 * SWS avoidance.  This means that we need to check the increase of
11725 	 * of receive window is at least 1 MSS.
11726 	 */
11727 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11728 		/*
11729 		 * If the window that the other side knows is less than max
11730 		 * deferred acks segments, send an update immediately.
11731 		 */
11732 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11733 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11734 			ret = TH_ACK_NEEDED;
11735 		}
11736 		tcp->tcp_rwnd = q->q_hiwat;
11737 	}
11738 	return (ret);
11739 }
11740 
11741 /*
11742  * Queue data on tcp_rcv_list which is a b_next chain.
11743  * tcp_rcv_last_head/tail is the last element of this chain.
11744  * Each element of the chain is a b_cont chain.
11745  *
11746  * M_DATA messages are added to the current element.
11747  * Other messages are added as new (b_next) elements.
11748  */
11749 void
11750 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11751 {
11752 	ASSERT(seg_len == msgdsize(mp));
11753 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11754 
11755 	if (tcp->tcp_rcv_list == NULL) {
11756 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11757 		tcp->tcp_rcv_list = mp;
11758 		tcp->tcp_rcv_last_head = mp;
11759 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11760 		tcp->tcp_rcv_last_tail->b_cont = mp;
11761 	} else {
11762 		tcp->tcp_rcv_last_head->b_next = mp;
11763 		tcp->tcp_rcv_last_head = mp;
11764 	}
11765 
11766 	while (mp->b_cont)
11767 		mp = mp->b_cont;
11768 
11769 	tcp->tcp_rcv_last_tail = mp;
11770 	tcp->tcp_rcv_cnt += seg_len;
11771 	tcp->tcp_rwnd -= seg_len;
11772 }
11773 
11774 /*
11775  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11776  * above, in addition when uioa is enabled schedule an asynchronous uio
11777  * prior to enqueuing. They implement the combinhed semantics of the
11778  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11779  * canputnext(), i.e. flow-control with backenable.
11780  *
11781  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11782  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11783  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11784  *
11785  * Must be called with sodp->sod_lockp held and will return with the lock
11786  * released.
11787  */
11788 static uint_t
11789 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11790 {
11791 	queue_t		*q = tcp->tcp_rq;
11792 	uint_t		thwin;
11793 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11794 	uint_t		ret = 0;
11795 
11796 	/* Can't be an eager connection */
11797 	ASSERT(tcp->tcp_listener == NULL);
11798 
11799 	/* Caller must have lock held */
11800 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11801 
11802 	/* Sodirect mode so must not be a tcp_rcv_list */
11803 	ASSERT(tcp->tcp_rcv_list == NULL);
11804 
11805 	if (SOD_QFULL(sodp)) {
11806 		/* Q is full, mark Q for need backenable */
11807 		SOD_QSETBE(sodp);
11808 	}
11809 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11810 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11811 	    << tcp->tcp_rcv_ws;
11812 	/* This is peer's calculated send window (our available rwnd). */
11813 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11814 	/*
11815 	 * Increase the receive window to max.  But we need to do receiver
11816 	 * SWS avoidance.  This means that we need to check the increase of
11817 	 * of receive window is at least 1 MSS.
11818 	 */
11819 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11820 		/*
11821 		 * If the window that the other side knows is less than max
11822 		 * deferred acks segments, send an update immediately.
11823 		 */
11824 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11825 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11826 			ret = TH_ACK_NEEDED;
11827 		}
11828 		tcp->tcp_rwnd = q->q_hiwat;
11829 	}
11830 
11831 	if (!SOD_QEMPTY(sodp)) {
11832 		/* Wakeup to socket */
11833 		sodp->sod_state &= SOD_WAKE_CLR;
11834 		sodp->sod_state |= SOD_WAKE_DONE;
11835 		(sodp->sod_wakeup)(sodp);
11836 		/* wakeup() does the mutex_ext() */
11837 	} else {
11838 		/* Q is empty, no need to wake */
11839 		sodp->sod_state &= SOD_WAKE_CLR;
11840 		sodp->sod_state |= SOD_WAKE_NOT;
11841 		mutex_exit(sodp->sod_lockp);
11842 	}
11843 
11844 	/* No need for the push timer now. */
11845 	if (tcp->tcp_push_tid != 0) {
11846 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11847 		tcp->tcp_push_tid = 0;
11848 	}
11849 
11850 	return (ret);
11851 }
11852 
11853 /*
11854  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11855  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11856  * to the user-land buffer and flag the mblk_t as such.
11857  *
11858  * Also, handle tcp_rwnd.
11859  */
11860 uint_t
11861 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11862 {
11863 	uioa_t		*uioap = &sodp->sod_uioa;
11864 	boolean_t	qfull;
11865 	uint_t		thwin;
11866 
11867 	/* Can't be an eager connection */
11868 	ASSERT(tcp->tcp_listener == NULL);
11869 
11870 	/* Caller must have lock held */
11871 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11872 
11873 	/* Sodirect mode so must not be a tcp_rcv_list */
11874 	ASSERT(tcp->tcp_rcv_list == NULL);
11875 
11876 	/* Passed in segment length must be equal to mblk_t chain data size */
11877 	ASSERT(seg_len == msgdsize(mp));
11878 
11879 	if (DB_TYPE(mp) != M_DATA) {
11880 		/* Only process M_DATA mblk_t's */
11881 		goto enq;
11882 	}
11883 	if (uioap->uioa_state & UIOA_ENABLED) {
11884 		/* Uioa is enabled */
11885 		mblk_t		*mp1 = mp;
11886 		mblk_t		*lmp = NULL;
11887 
11888 		if (seg_len > uioap->uio_resid) {
11889 			/*
11890 			 * There isn't enough uio space for the mblk_t chain
11891 			 * so disable uioa such that this and any additional
11892 			 * mblk_t data is handled by the socket and schedule
11893 			 * the socket for wakeup to finish this uioa.
11894 			 */
11895 			uioap->uioa_state &= UIOA_CLR;
11896 			uioap->uioa_state |= UIOA_FINI;
11897 			if (sodp->sod_state & SOD_WAKE_NOT) {
11898 				sodp->sod_state &= SOD_WAKE_CLR;
11899 				sodp->sod_state |= SOD_WAKE_NEED;
11900 			}
11901 			goto enq;
11902 		}
11903 		do {
11904 			uint32_t	len = MBLKL(mp1);
11905 
11906 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11907 				/* Scheduled, mark dblk_t as such */
11908 				DB_FLAGS(mp1) |= DBLK_UIOA;
11909 			} else {
11910 				/* Error, turn off async processing */
11911 				uioap->uioa_state &= UIOA_CLR;
11912 				uioap->uioa_state |= UIOA_FINI;
11913 				break;
11914 			}
11915 			lmp = mp1;
11916 		} while ((mp1 = mp1->b_cont) != NULL);
11917 
11918 		if (mp1 != NULL || uioap->uio_resid == 0) {
11919 			/*
11920 			 * Not all mblk_t(s) uioamoved (error) or all uio
11921 			 * space has been consumed so schedule the socket
11922 			 * for wakeup to finish this uio.
11923 			 */
11924 			sodp->sod_state &= SOD_WAKE_CLR;
11925 			sodp->sod_state |= SOD_WAKE_NEED;
11926 
11927 			/* Break the mblk chain if neccessary. */
11928 			if (mp1 != NULL && lmp != NULL) {
11929 				mp->b_next = mp1;
11930 				lmp->b_cont = NULL;
11931 			}
11932 		}
11933 	} else if (uioap->uioa_state & UIOA_FINI) {
11934 		/*
11935 		 * Post UIO_ENABLED waiting for socket to finish processing
11936 		 * so just enqueue and update tcp_rwnd.
11937 		 */
11938 		if (SOD_QFULL(sodp))
11939 			tcp->tcp_rwnd -= seg_len;
11940 	} else if (sodp->sod_want > 0) {
11941 		/*
11942 		 * Uioa isn't enabled but sodirect has a pending read().
11943 		 */
11944 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11945 			if (sodp->sod_state & SOD_WAKE_NOT) {
11946 				/* Schedule socket for wakeup */
11947 				sodp->sod_state &= SOD_WAKE_CLR;
11948 				sodp->sod_state |= SOD_WAKE_NEED;
11949 			}
11950 			tcp->tcp_rwnd -= seg_len;
11951 		}
11952 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11953 		/*
11954 		 * No pending sodirect read() so used the default
11955 		 * TCP push logic to guess that a push is needed.
11956 		 */
11957 		if (sodp->sod_state & SOD_WAKE_NOT) {
11958 			/* Schedule socket for wakeup */
11959 			sodp->sod_state &= SOD_WAKE_CLR;
11960 			sodp->sod_state |= SOD_WAKE_NEED;
11961 		}
11962 		tcp->tcp_rwnd -= seg_len;
11963 	} else {
11964 		/* Just update tcp_rwnd */
11965 		tcp->tcp_rwnd -= seg_len;
11966 	}
11967 enq:
11968 	qfull = SOD_QFULL(sodp);
11969 
11970 	(sodp->sod_enqueue)(sodp, mp);
11971 
11972 	if (! qfull && SOD_QFULL(sodp)) {
11973 		/* Wasn't QFULL, now QFULL, need back-enable */
11974 		SOD_QSETBE(sodp);
11975 	}
11976 
11977 	/*
11978 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11979 	 * first get advertised rwnd.
11980 	 */
11981 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11982 	/* Minus delayed ACK count */
11983 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11984 	if (thwin < tcp->tcp_mss) {
11985 		/* Remote avail swnd < mss, need ACK now */
11986 		return (TH_ACK_NEEDED);
11987 	}
11988 
11989 	return (0);
11990 }
11991 
11992 /*
11993  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11994  *
11995  * This is the default entry function into TCP on the read side. TCP is
11996  * always entered via squeue i.e. using squeue's for mutual exclusion.
11997  * When classifier does a lookup to find the tcp, it also puts a reference
11998  * on the conn structure associated so the tcp is guaranteed to exist
11999  * when we come here. We still need to check the state because it might
12000  * as well has been closed. The squeue processing function i.e. squeue_enter,
12001  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
12002  * CONN_DEC_REF.
12003  *
12004  * Apart from the default entry point, IP also sends packets directly to
12005  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
12006  * connections.
12007  */
12008 void
12009 tcp_input(void *arg, mblk_t *mp, void *arg2)
12010 {
12011 	conn_t	*connp = (conn_t *)arg;
12012 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
12013 
12014 	/* arg2 is the sqp */
12015 	ASSERT(arg2 != NULL);
12016 	ASSERT(mp != NULL);
12017 
12018 	/*
12019 	 * Don't accept any input on a closed tcp as this TCP logically does
12020 	 * not exist on the system. Don't proceed further with this TCP.
12021 	 * For eg. this packet could trigger another close of this tcp
12022 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
12023 	 * tcp_clean_death / tcp_closei_local must be called at most once
12024 	 * on a TCP. In this case we need to refeed the packet into the
12025 	 * classifier and figure out where the packet should go. Need to
12026 	 * preserve the recv_ill somehow. Until we figure that out, for
12027 	 * now just drop the packet if we can't classify the packet.
12028 	 */
12029 	if (tcp->tcp_state == TCPS_CLOSED ||
12030 	    tcp->tcp_state == TCPS_BOUND) {
12031 		conn_t	*new_connp;
12032 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
12033 
12034 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
12035 		if (new_connp != NULL) {
12036 			tcp_reinput(new_connp, mp, arg2);
12037 			return;
12038 		}
12039 		/* We failed to classify. For now just drop the packet */
12040 		freemsg(mp);
12041 		return;
12042 	}
12043 
12044 	if (DB_TYPE(mp) == M_DATA)
12045 		tcp_rput_data(connp, mp, arg2);
12046 	else
12047 		tcp_rput_common(tcp, mp);
12048 }
12049 
12050 /*
12051  * The read side put procedure.
12052  * The packets passed up by ip are assume to be aligned according to
12053  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
12054  */
12055 static void
12056 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
12057 {
12058 	/*
12059 	 * tcp_rput_data() does not expect M_CTL except for the case
12060 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
12061 	 * type. Need to make sure that any other M_CTLs don't make
12062 	 * it to tcp_rput_data since it is not expecting any and doesn't
12063 	 * check for it.
12064 	 */
12065 	if (DB_TYPE(mp) == M_CTL) {
12066 		switch (*(uint32_t *)(mp->b_rptr)) {
12067 		case TCP_IOC_ABORT_CONN:
12068 			/*
12069 			 * Handle connection abort request.
12070 			 */
12071 			tcp_ioctl_abort_handler(tcp, mp);
12072 			return;
12073 		case IPSEC_IN:
12074 			/*
12075 			 * Only secure icmp arrive in TCP and they
12076 			 * don't go through data path.
12077 			 */
12078 			tcp_icmp_error(tcp, mp);
12079 			return;
12080 		case IN_PKTINFO:
12081 			/*
12082 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
12083 			 * sockets that are receiving IPv4 traffic. tcp
12084 			 */
12085 			ASSERT(tcp->tcp_family == AF_INET6);
12086 			ASSERT(tcp->tcp_ipv6_recvancillary &
12087 			    TCP_IPV6_RECVPKTINFO);
12088 			tcp_rput_data(tcp->tcp_connp, mp,
12089 			    tcp->tcp_connp->conn_sqp);
12090 			return;
12091 		case MDT_IOC_INFO_UPDATE:
12092 			/*
12093 			 * Handle Multidata information update; the
12094 			 * following routine will free the message.
12095 			 */
12096 			if (tcp->tcp_connp->conn_mdt_ok) {
12097 				tcp_mdt_update(tcp,
12098 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
12099 				    B_FALSE);
12100 			}
12101 			freemsg(mp);
12102 			return;
12103 		case LSO_IOC_INFO_UPDATE:
12104 			/*
12105 			 * Handle LSO information update; the following
12106 			 * routine will free the message.
12107 			 */
12108 			if (tcp->tcp_connp->conn_lso_ok) {
12109 				tcp_lso_update(tcp,
12110 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
12111 			}
12112 			freemsg(mp);
12113 			return;
12114 		default:
12115 			/*
12116 			 * tcp_icmp_err() will process the M_CTL packets.
12117 			 * Non-ICMP packets, if any, will be discarded in
12118 			 * tcp_icmp_err(). We will process the ICMP packet
12119 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
12120 			 * incoming ICMP packet may result in changing
12121 			 * the tcp_mss, which we would need if we have
12122 			 * packets to retransmit.
12123 			 */
12124 			tcp_icmp_error(tcp, mp);
12125 			return;
12126 		}
12127 	}
12128 
12129 	/* No point processing the message if tcp is already closed */
12130 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
12131 		freemsg(mp);
12132 		return;
12133 	}
12134 
12135 	tcp_rput_other(tcp, mp);
12136 }
12137 
12138 
12139 /* The minimum of smoothed mean deviation in RTO calculation. */
12140 #define	TCP_SD_MIN	400
12141 
12142 /*
12143  * Set RTO for this connection.  The formula is from Jacobson and Karels'
12144  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
12145  * are the same as those in Appendix A.2 of that paper.
12146  *
12147  * m = new measurement
12148  * sa = smoothed RTT average (8 * average estimates).
12149  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
12150  */
12151 static void
12152 tcp_set_rto(tcp_t *tcp, clock_t rtt)
12153 {
12154 	long m = TICK_TO_MSEC(rtt);
12155 	clock_t sa = tcp->tcp_rtt_sa;
12156 	clock_t sv = tcp->tcp_rtt_sd;
12157 	clock_t rto;
12158 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12159 
12160 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
12161 	tcp->tcp_rtt_update++;
12162 
12163 	/* tcp_rtt_sa is not 0 means this is a new sample. */
12164 	if (sa != 0) {
12165 		/*
12166 		 * Update average estimator:
12167 		 *	new rtt = 7/8 old rtt + 1/8 Error
12168 		 */
12169 
12170 		/* m is now Error in estimate. */
12171 		m -= sa >> 3;
12172 		if ((sa += m) <= 0) {
12173 			/*
12174 			 * Don't allow the smoothed average to be negative.
12175 			 * We use 0 to denote reinitialization of the
12176 			 * variables.
12177 			 */
12178 			sa = 1;
12179 		}
12180 
12181 		/*
12182 		 * Update deviation estimator:
12183 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
12184 		 */
12185 		if (m < 0)
12186 			m = -m;
12187 		m -= sv >> 2;
12188 		sv += m;
12189 	} else {
12190 		/*
12191 		 * This follows BSD's implementation.  So the reinitialized
12192 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12193 		 * link is bandwidth dominated, doubling the window size
12194 		 * during slow start means doubling the RTT.  We want to be
12195 		 * more conservative when we reinitialize our estimates.  3
12196 		 * is just a convenient number.
12197 		 */
12198 		sa = m << 3;
12199 		sv = m << 1;
12200 	}
12201 	if (sv < TCP_SD_MIN) {
12202 		/*
12203 		 * We do not know that if sa captures the delay ACK
12204 		 * effect as in a long train of segments, a receiver
12205 		 * does not delay its ACKs.  So set the minimum of sv
12206 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12207 		 * of BSD DATO.  That means the minimum of mean
12208 		 * deviation is 100 ms.
12209 		 *
12210 		 */
12211 		sv = TCP_SD_MIN;
12212 	}
12213 	tcp->tcp_rtt_sa = sa;
12214 	tcp->tcp_rtt_sd = sv;
12215 	/*
12216 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12217 	 *
12218 	 * Add tcp_rexmit_interval extra in case of extreme environment
12219 	 * where the algorithm fails to work.  The default value of
12220 	 * tcp_rexmit_interval_extra should be 0.
12221 	 *
12222 	 * As we use a finer grained clock than BSD and update
12223 	 * RTO for every ACKs, add in another .25 of RTT to the
12224 	 * deviation of RTO to accomodate burstiness of 1/4 of
12225 	 * window size.
12226 	 */
12227 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12228 
12229 	if (rto > tcps->tcps_rexmit_interval_max) {
12230 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12231 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12232 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12233 	} else {
12234 		tcp->tcp_rto = rto;
12235 	}
12236 
12237 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12238 	tcp->tcp_timer_backoff = 0;
12239 }
12240 
12241 /*
12242  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12243  * send queue which starts at the given seq. no.
12244  *
12245  * Parameters:
12246  *	tcp_t *tcp: the tcp instance pointer.
12247  *	uint32_t seq: the starting seq. no of the requested segment.
12248  *	int32_t *off: after the execution, *off will be the offset to
12249  *		the returned mblk which points to the requested seq no.
12250  *		It is the caller's responsibility to send in a non-null off.
12251  *
12252  * Return:
12253  *	A mblk_t pointer pointing to the requested segment in send queue.
12254  */
12255 static mblk_t *
12256 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12257 {
12258 	int32_t	cnt;
12259 	mblk_t	*mp;
12260 
12261 	/* Defensive coding.  Make sure we don't send incorrect data. */
12262 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12263 		return (NULL);
12264 
12265 	cnt = seq - tcp->tcp_suna;
12266 	mp = tcp->tcp_xmit_head;
12267 	while (cnt > 0 && mp != NULL) {
12268 		cnt -= mp->b_wptr - mp->b_rptr;
12269 		if (cnt < 0) {
12270 			cnt += mp->b_wptr - mp->b_rptr;
12271 			break;
12272 		}
12273 		mp = mp->b_cont;
12274 	}
12275 	ASSERT(mp != NULL);
12276 	*off = cnt;
12277 	return (mp);
12278 }
12279 
12280 /*
12281  * This function handles all retransmissions if SACK is enabled for this
12282  * connection.  First it calculates how many segments can be retransmitted
12283  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12284  * segments.  A segment is eligible if sack_cnt for that segment is greater
12285  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12286  * all eligible segments, it checks to see if TCP can send some new segments
12287  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12288  *
12289  * Parameters:
12290  *	tcp_t *tcp: the tcp structure of the connection.
12291  *	uint_t *flags: in return, appropriate value will be set for
12292  *	tcp_rput_data().
12293  */
12294 static void
12295 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12296 {
12297 	notsack_blk_t	*notsack_blk;
12298 	int32_t		usable_swnd;
12299 	int32_t		mss;
12300 	uint32_t	seg_len;
12301 	mblk_t		*xmit_mp;
12302 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12303 
12304 	ASSERT(tcp->tcp_sack_info != NULL);
12305 	ASSERT(tcp->tcp_notsack_list != NULL);
12306 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12307 
12308 	/* Defensive coding in case there is a bug... */
12309 	if (tcp->tcp_notsack_list == NULL) {
12310 		return;
12311 	}
12312 	notsack_blk = tcp->tcp_notsack_list;
12313 	mss = tcp->tcp_mss;
12314 
12315 	/*
12316 	 * Limit the num of outstanding data in the network to be
12317 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12318 	 */
12319 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12320 
12321 	/* At least retransmit 1 MSS of data. */
12322 	if (usable_swnd <= 0) {
12323 		usable_swnd = mss;
12324 	}
12325 
12326 	/* Make sure no new RTT samples will be taken. */
12327 	tcp->tcp_csuna = tcp->tcp_snxt;
12328 
12329 	notsack_blk = tcp->tcp_notsack_list;
12330 	while (usable_swnd > 0) {
12331 		mblk_t		*snxt_mp, *tmp_mp;
12332 		tcp_seq		begin = tcp->tcp_sack_snxt;
12333 		tcp_seq		end;
12334 		int32_t		off;
12335 
12336 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12337 			if (SEQ_GT(notsack_blk->end, begin) &&
12338 			    (notsack_blk->sack_cnt >=
12339 			    tcps->tcps_dupack_fast_retransmit)) {
12340 				end = notsack_blk->end;
12341 				if (SEQ_LT(begin, notsack_blk->begin)) {
12342 					begin = notsack_blk->begin;
12343 				}
12344 				break;
12345 			}
12346 		}
12347 		/*
12348 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12349 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12350 		 * set to tcp_cwnd_ssthresh.
12351 		 */
12352 		if (notsack_blk == NULL) {
12353 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12354 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12355 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12356 				ASSERT(tcp->tcp_cwnd > 0);
12357 				return;
12358 			} else {
12359 				usable_swnd = usable_swnd / mss;
12360 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12361 				    MAX(usable_swnd * mss, mss);
12362 				*flags |= TH_XMIT_NEEDED;
12363 				return;
12364 			}
12365 		}
12366 
12367 		/*
12368 		 * Note that we may send more than usable_swnd allows here
12369 		 * because of round off, but no more than 1 MSS of data.
12370 		 */
12371 		seg_len = end - begin;
12372 		if (seg_len > mss)
12373 			seg_len = mss;
12374 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12375 		ASSERT(snxt_mp != NULL);
12376 		/* This should not happen.  Defensive coding again... */
12377 		if (snxt_mp == NULL) {
12378 			return;
12379 		}
12380 
12381 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12382 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12383 		if (xmit_mp == NULL)
12384 			return;
12385 
12386 		usable_swnd -= seg_len;
12387 		tcp->tcp_pipe += seg_len;
12388 		tcp->tcp_sack_snxt = begin + seg_len;
12389 
12390 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12391 
12392 		/*
12393 		 * Update the send timestamp to avoid false retransmission.
12394 		 */
12395 		snxt_mp->b_prev = (mblk_t *)lbolt;
12396 
12397 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12398 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12399 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12400 		/*
12401 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12402 		 * This happens when new data sent during fast recovery is
12403 		 * also lost.  If TCP retransmits those new data, it needs
12404 		 * to extend SACK recover phase to avoid starting another
12405 		 * fast retransmit/recovery unnecessarily.
12406 		 */
12407 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12408 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12409 		}
12410 	}
12411 }
12412 
12413 /*
12414  * This function handles policy checking at TCP level for non-hard_bound/
12415  * detached connections.
12416  */
12417 static boolean_t
12418 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12419     boolean_t secure, boolean_t mctl_present)
12420 {
12421 	ipsec_latch_t *ipl = NULL;
12422 	ipsec_action_t *act = NULL;
12423 	mblk_t *data_mp;
12424 	ipsec_in_t *ii;
12425 	const char *reason;
12426 	kstat_named_t *counter;
12427 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12428 	ipsec_stack_t	*ipss;
12429 	ip_stack_t	*ipst;
12430 
12431 	ASSERT(mctl_present || !secure);
12432 
12433 	ASSERT((ipha == NULL && ip6h != NULL) ||
12434 	    (ip6h == NULL && ipha != NULL));
12435 
12436 	/*
12437 	 * We don't necessarily have an ipsec_in_act action to verify
12438 	 * policy because of assymetrical policy where we have only
12439 	 * outbound policy and no inbound policy (possible with global
12440 	 * policy).
12441 	 */
12442 	if (!secure) {
12443 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12444 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12445 			return (B_TRUE);
12446 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12447 		    "tcp_check_policy", ipha, ip6h, secure,
12448 		    tcps->tcps_netstack);
12449 		ipss = tcps->tcps_netstack->netstack_ipsec;
12450 
12451 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12452 		    DROPPER(ipss, ipds_tcp_clear),
12453 		    &tcps->tcps_dropper);
12454 		return (B_FALSE);
12455 	}
12456 
12457 	/*
12458 	 * We have a secure packet.
12459 	 */
12460 	if (act == NULL) {
12461 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12462 		    "tcp_check_policy", ipha, ip6h, secure,
12463 		    tcps->tcps_netstack);
12464 		ipss = tcps->tcps_netstack->netstack_ipsec;
12465 
12466 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12467 		    DROPPER(ipss, ipds_tcp_secure),
12468 		    &tcps->tcps_dropper);
12469 		return (B_FALSE);
12470 	}
12471 
12472 	/*
12473 	 * XXX This whole routine is currently incorrect.  ipl should
12474 	 * be set to the latch pointer, but is currently not set, so
12475 	 * we initialize it to NULL to avoid picking up random garbage.
12476 	 */
12477 	if (ipl == NULL)
12478 		return (B_TRUE);
12479 
12480 	data_mp = first_mp->b_cont;
12481 
12482 	ii = (ipsec_in_t *)first_mp->b_rptr;
12483 
12484 	ipst = tcps->tcps_netstack->netstack_ip;
12485 
12486 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12487 	    &counter, tcp->tcp_connp)) {
12488 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12489 		return (B_TRUE);
12490 	}
12491 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12492 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12493 	    reason);
12494 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12495 
12496 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12497 	    &tcps->tcps_dropper);
12498 	return (B_FALSE);
12499 }
12500 
12501 /*
12502  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12503  * retransmission after a timeout.
12504  *
12505  * To limit the number of duplicate segments, we limit the number of segment
12506  * to be sent in one time to tcp_snd_burst, the burst variable.
12507  */
12508 static void
12509 tcp_ss_rexmit(tcp_t *tcp)
12510 {
12511 	uint32_t	snxt;
12512 	uint32_t	smax;
12513 	int32_t		win;
12514 	int32_t		mss;
12515 	int32_t		off;
12516 	int32_t		burst = tcp->tcp_snd_burst;
12517 	mblk_t		*snxt_mp;
12518 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12519 
12520 	/*
12521 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12522 	 * all unack'ed segments.
12523 	 */
12524 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12525 		smax = tcp->tcp_rexmit_max;
12526 		snxt = tcp->tcp_rexmit_nxt;
12527 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12528 			snxt = tcp->tcp_suna;
12529 		}
12530 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12531 		win -= snxt - tcp->tcp_suna;
12532 		mss = tcp->tcp_mss;
12533 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12534 
12535 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12536 		    (burst > 0) && (snxt_mp != NULL)) {
12537 			mblk_t	*xmit_mp;
12538 			mblk_t	*old_snxt_mp = snxt_mp;
12539 			uint32_t cnt = mss;
12540 
12541 			if (win < cnt) {
12542 				cnt = win;
12543 			}
12544 			if (SEQ_GT(snxt + cnt, smax)) {
12545 				cnt = smax - snxt;
12546 			}
12547 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12548 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12549 			if (xmit_mp == NULL)
12550 				return;
12551 
12552 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12553 
12554 			snxt += cnt;
12555 			win -= cnt;
12556 			/*
12557 			 * Update the send timestamp to avoid false
12558 			 * retransmission.
12559 			 */
12560 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12561 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12562 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12563 
12564 			tcp->tcp_rexmit_nxt = snxt;
12565 			burst--;
12566 		}
12567 		/*
12568 		 * If we have transmitted all we have at the time
12569 		 * we started the retranmission, we can leave
12570 		 * the rest of the job to tcp_wput_data().  But we
12571 		 * need to check the send window first.  If the
12572 		 * win is not 0, go on with tcp_wput_data().
12573 		 */
12574 		if (SEQ_LT(snxt, smax) || win == 0) {
12575 			return;
12576 		}
12577 	}
12578 	/* Only call tcp_wput_data() if there is data to be sent. */
12579 	if (tcp->tcp_unsent) {
12580 		tcp_wput_data(tcp, NULL, B_FALSE);
12581 	}
12582 }
12583 
12584 /*
12585  * Process all TCP option in SYN segment.  Note that this function should
12586  * be called after tcp_adapt_ire() is called so that the necessary info
12587  * from IRE is already set in the tcp structure.
12588  *
12589  * This function sets up the correct tcp_mss value according to the
12590  * MSS option value and our header size.  It also sets up the window scale
12591  * and timestamp values, and initialize SACK info blocks.  But it does not
12592  * change receive window size after setting the tcp_mss value.  The caller
12593  * should do the appropriate change.
12594  */
12595 void
12596 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12597 {
12598 	int options;
12599 	tcp_opt_t tcpopt;
12600 	uint32_t mss_max;
12601 	char *tmp_tcph;
12602 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12603 
12604 	tcpopt.tcp = NULL;
12605 	options = tcp_parse_options(tcph, &tcpopt);
12606 
12607 	/*
12608 	 * Process MSS option.  Note that MSS option value does not account
12609 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12610 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12611 	 * IPv6.
12612 	 */
12613 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12614 		if (tcp->tcp_ipversion == IPV4_VERSION)
12615 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12616 		else
12617 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12618 	} else {
12619 		if (tcp->tcp_ipversion == IPV4_VERSION)
12620 			mss_max = tcps->tcps_mss_max_ipv4;
12621 		else
12622 			mss_max = tcps->tcps_mss_max_ipv6;
12623 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12624 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12625 		else if (tcpopt.tcp_opt_mss > mss_max)
12626 			tcpopt.tcp_opt_mss = mss_max;
12627 	}
12628 
12629 	/* Process Window Scale option. */
12630 	if (options & TCP_OPT_WSCALE_PRESENT) {
12631 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12632 		tcp->tcp_snd_ws_ok = B_TRUE;
12633 	} else {
12634 		tcp->tcp_snd_ws = B_FALSE;
12635 		tcp->tcp_snd_ws_ok = B_FALSE;
12636 		tcp->tcp_rcv_ws = B_FALSE;
12637 	}
12638 
12639 	/* Process Timestamp option. */
12640 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12641 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12642 		tmp_tcph = (char *)tcp->tcp_tcph;
12643 
12644 		tcp->tcp_snd_ts_ok = B_TRUE;
12645 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12646 		tcp->tcp_last_rcv_lbolt = lbolt64;
12647 		ASSERT(OK_32PTR(tmp_tcph));
12648 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12649 
12650 		/* Fill in our template header with basic timestamp option. */
12651 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12652 		tmp_tcph[0] = TCPOPT_NOP;
12653 		tmp_tcph[1] = TCPOPT_NOP;
12654 		tmp_tcph[2] = TCPOPT_TSTAMP;
12655 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12656 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12657 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12658 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12659 	} else {
12660 		tcp->tcp_snd_ts_ok = B_FALSE;
12661 	}
12662 
12663 	/*
12664 	 * Process SACK options.  If SACK is enabled for this connection,
12665 	 * then allocate the SACK info structure.  Note the following ways
12666 	 * when tcp_snd_sack_ok is set to true.
12667 	 *
12668 	 * For active connection: in tcp_adapt_ire() called in
12669 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12670 	 * is checked.
12671 	 *
12672 	 * For passive connection: in tcp_adapt_ire() called in
12673 	 * tcp_accept_comm().
12674 	 *
12675 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12676 	 * That check makes sure that if we did not send a SACK OK option,
12677 	 * we will not enable SACK for this connection even though the other
12678 	 * side sends us SACK OK option.  For active connection, the SACK
12679 	 * info structure has already been allocated.  So we need to free
12680 	 * it if SACK is disabled.
12681 	 */
12682 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12683 	    (tcp->tcp_snd_sack_ok ||
12684 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12685 		/* This should be true only in the passive case. */
12686 		if (tcp->tcp_sack_info == NULL) {
12687 			ASSERT(TCP_IS_DETACHED(tcp));
12688 			tcp->tcp_sack_info =
12689 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12690 		}
12691 		if (tcp->tcp_sack_info == NULL) {
12692 			tcp->tcp_snd_sack_ok = B_FALSE;
12693 		} else {
12694 			tcp->tcp_snd_sack_ok = B_TRUE;
12695 			if (tcp->tcp_snd_ts_ok) {
12696 				tcp->tcp_max_sack_blk = 3;
12697 			} else {
12698 				tcp->tcp_max_sack_blk = 4;
12699 			}
12700 		}
12701 	} else {
12702 		/*
12703 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12704 		 * no SACK info will be used for this
12705 		 * connection.  This assumes that SACK usage
12706 		 * permission is negotiated.  This may need
12707 		 * to be changed once this is clarified.
12708 		 */
12709 		if (tcp->tcp_sack_info != NULL) {
12710 			ASSERT(tcp->tcp_notsack_list == NULL);
12711 			kmem_cache_free(tcp_sack_info_cache,
12712 			    tcp->tcp_sack_info);
12713 			tcp->tcp_sack_info = NULL;
12714 		}
12715 		tcp->tcp_snd_sack_ok = B_FALSE;
12716 	}
12717 
12718 	/*
12719 	 * Now we know the exact TCP/IP header length, subtract
12720 	 * that from tcp_mss to get our side's MSS.
12721 	 */
12722 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12723 	/*
12724 	 * Here we assume that the other side's header size will be equal to
12725 	 * our header size.  We calculate the real MSS accordingly.  Need to
12726 	 * take into additional stuffs IPsec puts in.
12727 	 *
12728 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12729 	 */
12730 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12731 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12732 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12733 
12734 	/*
12735 	 * Set MSS to the smaller one of both ends of the connection.
12736 	 * We should not have called tcp_mss_set() before, but our
12737 	 * side of the MSS should have been set to a proper value
12738 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12739 	 * STREAM head parameters properly.
12740 	 *
12741 	 * If we have a larger-than-16-bit window but the other side
12742 	 * didn't want to do window scale, tcp_rwnd_set() will take
12743 	 * care of that.
12744 	 */
12745 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12746 }
12747 
12748 /*
12749  * Sends the T_CONN_IND to the listener. The caller calls this
12750  * functions via squeue to get inside the listener's perimeter
12751  * once the 3 way hand shake is done a T_CONN_IND needs to be
12752  * sent. As an optimization, the caller can call this directly
12753  * if listener's perimeter is same as eager's.
12754  */
12755 /* ARGSUSED */
12756 void
12757 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12758 {
12759 	conn_t			*lconnp = (conn_t *)arg;
12760 	tcp_t			*listener = lconnp->conn_tcp;
12761 	tcp_t			*tcp;
12762 	struct T_conn_ind	*conn_ind;
12763 	ipaddr_t 		*addr_cache;
12764 	boolean_t		need_send_conn_ind = B_FALSE;
12765 	tcp_stack_t		*tcps = listener->tcp_tcps;
12766 
12767 	/* retrieve the eager */
12768 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12769 	ASSERT(conn_ind->OPT_offset != 0 &&
12770 	    conn_ind->OPT_length == sizeof (intptr_t));
12771 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12772 	    conn_ind->OPT_length);
12773 
12774 	/*
12775 	 * TLI/XTI applications will get confused by
12776 	 * sending eager as an option since it violates
12777 	 * the option semantics. So remove the eager as
12778 	 * option since TLI/XTI app doesn't need it anyway.
12779 	 */
12780 	if (!TCP_IS_SOCKET(listener)) {
12781 		conn_ind->OPT_length = 0;
12782 		conn_ind->OPT_offset = 0;
12783 	}
12784 	if (listener->tcp_state == TCPS_CLOSED ||
12785 	    TCP_IS_DETACHED(listener)) {
12786 		/*
12787 		 * If listener has closed, it would have caused a
12788 		 * a cleanup/blowoff to happen for the eager. We
12789 		 * just need to return.
12790 		 */
12791 		freemsg(mp);
12792 		return;
12793 	}
12794 
12795 
12796 	/*
12797 	 * if the conn_req_q is full defer passing up the
12798 	 * T_CONN_IND until space is availabe after t_accept()
12799 	 * processing
12800 	 */
12801 	mutex_enter(&listener->tcp_eager_lock);
12802 
12803 	/*
12804 	 * Take the eager out, if it is in the list of droppable eagers
12805 	 * as we are here because the 3W handshake is over.
12806 	 */
12807 	MAKE_UNDROPPABLE(tcp);
12808 
12809 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12810 		tcp_t *tail;
12811 
12812 		/*
12813 		 * The eager already has an extra ref put in tcp_rput_data
12814 		 * so that it stays till accept comes back even though it
12815 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12816 		 */
12817 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12818 		listener->tcp_conn_req_cnt_q0--;
12819 		listener->tcp_conn_req_cnt_q++;
12820 
12821 		/* Move from SYN_RCVD to ESTABLISHED list  */
12822 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12823 		    tcp->tcp_eager_prev_q0;
12824 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12825 		    tcp->tcp_eager_next_q0;
12826 		tcp->tcp_eager_prev_q0 = NULL;
12827 		tcp->tcp_eager_next_q0 = NULL;
12828 
12829 		/*
12830 		 * Insert at end of the queue because sockfs
12831 		 * sends down T_CONN_RES in chronological
12832 		 * order. Leaving the older conn indications
12833 		 * at front of the queue helps reducing search
12834 		 * time.
12835 		 */
12836 		tail = listener->tcp_eager_last_q;
12837 		if (tail != NULL)
12838 			tail->tcp_eager_next_q = tcp;
12839 		else
12840 			listener->tcp_eager_next_q = tcp;
12841 		listener->tcp_eager_last_q = tcp;
12842 		tcp->tcp_eager_next_q = NULL;
12843 		/*
12844 		 * Delay sending up the T_conn_ind until we are
12845 		 * done with the eager. Once we have have sent up
12846 		 * the T_conn_ind, the accept can potentially complete
12847 		 * any time and release the refhold we have on the eager.
12848 		 */
12849 		need_send_conn_ind = B_TRUE;
12850 	} else {
12851 		/*
12852 		 * Defer connection on q0 and set deferred
12853 		 * connection bit true
12854 		 */
12855 		tcp->tcp_conn_def_q0 = B_TRUE;
12856 
12857 		/* take tcp out of q0 ... */
12858 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12859 		    tcp->tcp_eager_next_q0;
12860 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12861 		    tcp->tcp_eager_prev_q0;
12862 
12863 		/* ... and place it at the end of q0 */
12864 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12865 		tcp->tcp_eager_next_q0 = listener;
12866 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12867 		listener->tcp_eager_prev_q0 = tcp;
12868 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12869 	}
12870 
12871 	/* we have timed out before */
12872 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12873 		tcp->tcp_syn_rcvd_timeout = 0;
12874 		listener->tcp_syn_rcvd_timeout--;
12875 		if (listener->tcp_syn_defense &&
12876 		    listener->tcp_syn_rcvd_timeout <=
12877 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12878 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12879 		    listener->tcp_last_rcv_lbolt)) {
12880 			/*
12881 			 * Turn off the defense mode if we
12882 			 * believe the SYN attack is over.
12883 			 */
12884 			listener->tcp_syn_defense = B_FALSE;
12885 			if (listener->tcp_ip_addr_cache) {
12886 				kmem_free((void *)listener->tcp_ip_addr_cache,
12887 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12888 				listener->tcp_ip_addr_cache = NULL;
12889 			}
12890 		}
12891 	}
12892 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12893 	if (addr_cache != NULL) {
12894 		/*
12895 		 * We have finished a 3-way handshake with this
12896 		 * remote host. This proves the IP addr is good.
12897 		 * Cache it!
12898 		 */
12899 		addr_cache[IP_ADDR_CACHE_HASH(
12900 		    tcp->tcp_remote)] = tcp->tcp_remote;
12901 	}
12902 	mutex_exit(&listener->tcp_eager_lock);
12903 	if (need_send_conn_ind)
12904 		putnext(listener->tcp_rq, mp);
12905 }
12906 
12907 mblk_t *
12908 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12909     uint_t *ifindexp, ip6_pkt_t *ippp)
12910 {
12911 	ip_pktinfo_t	*pinfo;
12912 	ip6_t		*ip6h;
12913 	uchar_t		*rptr;
12914 	mblk_t		*first_mp = mp;
12915 	boolean_t	mctl_present = B_FALSE;
12916 	uint_t 		ifindex = 0;
12917 	ip6_pkt_t	ipp;
12918 	uint_t		ipvers;
12919 	uint_t		ip_hdr_len;
12920 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12921 
12922 	rptr = mp->b_rptr;
12923 	ASSERT(OK_32PTR(rptr));
12924 	ASSERT(tcp != NULL);
12925 	ipp.ipp_fields = 0;
12926 
12927 	switch DB_TYPE(mp) {
12928 	case M_CTL:
12929 		mp = mp->b_cont;
12930 		if (mp == NULL) {
12931 			freemsg(first_mp);
12932 			return (NULL);
12933 		}
12934 		if (DB_TYPE(mp) != M_DATA) {
12935 			freemsg(first_mp);
12936 			return (NULL);
12937 		}
12938 		mctl_present = B_TRUE;
12939 		break;
12940 	case M_DATA:
12941 		break;
12942 	default:
12943 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12944 		freemsg(mp);
12945 		return (NULL);
12946 	}
12947 	ipvers = IPH_HDR_VERSION(rptr);
12948 	if (ipvers == IPV4_VERSION) {
12949 		if (tcp == NULL) {
12950 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12951 			goto done;
12952 		}
12953 
12954 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12955 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12956 
12957 		/*
12958 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12959 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12960 		 */
12961 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12962 		    mctl_present) {
12963 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12964 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12965 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12966 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12967 				ipp.ipp_fields |= IPPF_IFINDEX;
12968 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12969 				ifindex = pinfo->ip_pkt_ifindex;
12970 			}
12971 			freeb(first_mp);
12972 			mctl_present = B_FALSE;
12973 		}
12974 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12975 	} else {
12976 		ip6h = (ip6_t *)rptr;
12977 
12978 		ASSERT(ipvers == IPV6_VERSION);
12979 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12980 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12981 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12982 
12983 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12984 			uint8_t	nexthdrp;
12985 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12986 
12987 			/* Look for ifindex information */
12988 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12989 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12990 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12991 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12992 					freemsg(first_mp);
12993 					return (NULL);
12994 				}
12995 
12996 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12997 					ASSERT(ip6i->ip6i_ifindex != 0);
12998 					ipp.ipp_fields |= IPPF_IFINDEX;
12999 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
13000 					ifindex = ip6i->ip6i_ifindex;
13001 				}
13002 				rptr = (uchar_t *)&ip6i[1];
13003 				mp->b_rptr = rptr;
13004 				if (rptr == mp->b_wptr) {
13005 					mblk_t *mp1;
13006 					mp1 = mp->b_cont;
13007 					freeb(mp);
13008 					mp = mp1;
13009 					rptr = mp->b_rptr;
13010 				}
13011 				if (MBLKL(mp) < IPV6_HDR_LEN +
13012 				    sizeof (tcph_t)) {
13013 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13014 					freemsg(first_mp);
13015 					return (NULL);
13016 				}
13017 				ip6h = (ip6_t *)rptr;
13018 			}
13019 
13020 			/*
13021 			 * Find any potentially interesting extension headers
13022 			 * as well as the length of the IPv6 + extension
13023 			 * headers.
13024 			 */
13025 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
13026 			/* Verify if this is a TCP packet */
13027 			if (nexthdrp != IPPROTO_TCP) {
13028 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13029 				freemsg(first_mp);
13030 				return (NULL);
13031 			}
13032 		} else {
13033 			ip_hdr_len = IPV6_HDR_LEN;
13034 		}
13035 	}
13036 
13037 done:
13038 	if (ipversp != NULL)
13039 		*ipversp = ipvers;
13040 	if (ip_hdr_lenp != NULL)
13041 		*ip_hdr_lenp = ip_hdr_len;
13042 	if (ippp != NULL)
13043 		*ippp = ipp;
13044 	if (ifindexp != NULL)
13045 		*ifindexp = ifindex;
13046 	if (mctl_present) {
13047 		freeb(first_mp);
13048 	}
13049 	return (mp);
13050 }
13051 
13052 /*
13053  * Handle M_DATA messages from IP. Its called directly from IP via
13054  * squeue for AF_INET type sockets fast path. No M_CTL are expected
13055  * in this path.
13056  *
13057  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
13058  * v4 and v6), we are called through tcp_input() and a M_CTL can
13059  * be present for options but tcp_find_pktinfo() deals with it. We
13060  * only expect M_DATA packets after tcp_find_pktinfo() is done.
13061  *
13062  * The first argument is always the connp/tcp to which the mp belongs.
13063  * There are no exceptions to this rule. The caller has already put
13064  * a reference on this connp/tcp and once tcp_rput_data() returns,
13065  * the squeue will do the refrele.
13066  *
13067  * The TH_SYN for the listener directly go to tcp_conn_request via
13068  * squeue.
13069  *
13070  * sqp: NULL = recursive, sqp != NULL means called from squeue
13071  */
13072 void
13073 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
13074 {
13075 	int32_t		bytes_acked;
13076 	int32_t		gap;
13077 	mblk_t		*mp1;
13078 	uint_t		flags;
13079 	uint32_t	new_swnd = 0;
13080 	uchar_t		*iphdr;
13081 	uchar_t		*rptr;
13082 	int32_t		rgap;
13083 	uint32_t	seg_ack;
13084 	int		seg_len;
13085 	uint_t		ip_hdr_len;
13086 	uint32_t	seg_seq;
13087 	tcph_t		*tcph;
13088 	int		urp;
13089 	tcp_opt_t	tcpopt;
13090 	uint_t		ipvers;
13091 	ip6_pkt_t	ipp;
13092 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
13093 	uint32_t	cwnd;
13094 	uint32_t	add;
13095 	int		npkt;
13096 	int		mss;
13097 	conn_t		*connp = (conn_t *)arg;
13098 	squeue_t	*sqp = (squeue_t *)arg2;
13099 	tcp_t		*tcp = connp->conn_tcp;
13100 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13101 
13102 	/*
13103 	 * RST from fused tcp loopback peer should trigger an unfuse.
13104 	 */
13105 	if (tcp->tcp_fused) {
13106 		TCP_STAT(tcps, tcp_fusion_aborted);
13107 		tcp_unfuse(tcp);
13108 	}
13109 
13110 	iphdr = mp->b_rptr;
13111 	rptr = mp->b_rptr;
13112 	ASSERT(OK_32PTR(rptr));
13113 
13114 	/*
13115 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
13116 	 * processing here. For rest call tcp_find_pktinfo to fill up the
13117 	 * necessary information.
13118 	 */
13119 	if (IPCL_IS_TCP4(connp)) {
13120 		ipvers = IPV4_VERSION;
13121 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13122 	} else {
13123 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
13124 		    NULL, &ipp);
13125 		if (mp == NULL) {
13126 			TCP_STAT(tcps, tcp_rput_v6_error);
13127 			return;
13128 		}
13129 		iphdr = mp->b_rptr;
13130 		rptr = mp->b_rptr;
13131 	}
13132 	ASSERT(DB_TYPE(mp) == M_DATA);
13133 
13134 	tcph = (tcph_t *)&rptr[ip_hdr_len];
13135 	seg_seq = ABE32_TO_U32(tcph->th_seq);
13136 	seg_ack = ABE32_TO_U32(tcph->th_ack);
13137 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
13138 	seg_len = (int)(mp->b_wptr - rptr) -
13139 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
13140 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
13141 		do {
13142 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13143 			    (uintptr_t)INT_MAX);
13144 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
13145 		} while ((mp1 = mp1->b_cont) != NULL &&
13146 		    mp1->b_datap->db_type == M_DATA);
13147 	}
13148 
13149 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
13150 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
13151 		    seg_len, tcph);
13152 		return;
13153 	}
13154 
13155 	if (sqp != NULL) {
13156 		/*
13157 		 * This is the correct place to update tcp_last_recv_time. Note
13158 		 * that it is also updated for tcp structure that belongs to
13159 		 * global and listener queues which do not really need updating.
13160 		 * But that should not cause any harm.  And it is updated for
13161 		 * all kinds of incoming segments, not only for data segments.
13162 		 */
13163 		tcp->tcp_last_recv_time = lbolt;
13164 	}
13165 
13166 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13167 
13168 	BUMP_LOCAL(tcp->tcp_ibsegs);
13169 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13170 
13171 	if ((flags & TH_URG) && sqp != NULL) {
13172 		/*
13173 		 * TCP can't handle urgent pointers that arrive before
13174 		 * the connection has been accept()ed since it can't
13175 		 * buffer OOB data.  Discard segment if this happens.
13176 		 *
13177 		 * We can't just rely on a non-null tcp_listener to indicate
13178 		 * that the accept() has completed since unlinking of the
13179 		 * eager and completion of the accept are not atomic.
13180 		 * tcp_detached, when it is not set (B_FALSE) indicates
13181 		 * that the accept() has completed.
13182 		 *
13183 		 * Nor can it reassemble urgent pointers, so discard
13184 		 * if it's not the next segment expected.
13185 		 *
13186 		 * Otherwise, collapse chain into one mblk (discard if
13187 		 * that fails).  This makes sure the headers, retransmitted
13188 		 * data, and new data all are in the same mblk.
13189 		 */
13190 		ASSERT(mp != NULL);
13191 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13192 			freemsg(mp);
13193 			return;
13194 		}
13195 		/* Update pointers into message */
13196 		iphdr = rptr = mp->b_rptr;
13197 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13198 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13199 			/*
13200 			 * Since we can't handle any data with this urgent
13201 			 * pointer that is out of sequence, we expunge
13202 			 * the data.  This allows us to still register
13203 			 * the urgent mark and generate the M_PCSIG,
13204 			 * which we can do.
13205 			 */
13206 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13207 			seg_len = 0;
13208 		}
13209 	}
13210 
13211 	switch (tcp->tcp_state) {
13212 	case TCPS_SYN_SENT:
13213 		if (flags & TH_ACK) {
13214 			/*
13215 			 * Note that our stack cannot send data before a
13216 			 * connection is established, therefore the
13217 			 * following check is valid.  Otherwise, it has
13218 			 * to be changed.
13219 			 */
13220 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13221 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13222 				freemsg(mp);
13223 				if (flags & TH_RST)
13224 					return;
13225 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13226 				    tcp, seg_ack, 0, TH_RST);
13227 				return;
13228 			}
13229 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13230 		}
13231 		if (flags & TH_RST) {
13232 			freemsg(mp);
13233 			if (flags & TH_ACK)
13234 				(void) tcp_clean_death(tcp,
13235 				    ECONNREFUSED, 13);
13236 			return;
13237 		}
13238 		if (!(flags & TH_SYN)) {
13239 			freemsg(mp);
13240 			return;
13241 		}
13242 
13243 		/* Process all TCP options. */
13244 		tcp_process_options(tcp, tcph);
13245 		/*
13246 		 * The following changes our rwnd to be a multiple of the
13247 		 * MIN(peer MSS, our MSS) for performance reason.
13248 		 */
13249 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
13250 		    tcp->tcp_mss));
13251 
13252 		/* Is the other end ECN capable? */
13253 		if (tcp->tcp_ecn_ok) {
13254 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13255 				tcp->tcp_ecn_ok = B_FALSE;
13256 			}
13257 		}
13258 		/*
13259 		 * Clear ECN flags because it may interfere with later
13260 		 * processing.
13261 		 */
13262 		flags &= ~(TH_ECE|TH_CWR);
13263 
13264 		tcp->tcp_irs = seg_seq;
13265 		tcp->tcp_rack = seg_seq;
13266 		tcp->tcp_rnxt = seg_seq + 1;
13267 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13268 		if (!TCP_IS_DETACHED(tcp)) {
13269 			/* Allocate room for SACK options if needed. */
13270 			if (tcp->tcp_snd_sack_ok) {
13271 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13272 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13273 				    (tcp->tcp_loopback ? 0 :
13274 				    tcps->tcps_wroff_xtra));
13275 			} else {
13276 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13277 				    tcp->tcp_hdr_len +
13278 				    (tcp->tcp_loopback ? 0 :
13279 				    tcps->tcps_wroff_xtra));
13280 			}
13281 		}
13282 		if (flags & TH_ACK) {
13283 			/*
13284 			 * If we can't get the confirmation upstream, pretend
13285 			 * we didn't even see this one.
13286 			 *
13287 			 * XXX: how can we pretend we didn't see it if we
13288 			 * have updated rnxt et. al.
13289 			 *
13290 			 * For loopback we defer sending up the T_CONN_CON
13291 			 * until after some checks below.
13292 			 */
13293 			mp1 = NULL;
13294 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13295 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13296 				freemsg(mp);
13297 				return;
13298 			}
13299 			/* SYN was acked - making progress */
13300 			if (tcp->tcp_ipversion == IPV6_VERSION)
13301 				tcp->tcp_ip_forward_progress = B_TRUE;
13302 
13303 			/* One for the SYN */
13304 			tcp->tcp_suna = tcp->tcp_iss + 1;
13305 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13306 			tcp->tcp_state = TCPS_ESTABLISHED;
13307 
13308 			/*
13309 			 * If SYN was retransmitted, need to reset all
13310 			 * retransmission info.  This is because this
13311 			 * segment will be treated as a dup ACK.
13312 			 */
13313 			if (tcp->tcp_rexmit) {
13314 				tcp->tcp_rexmit = B_FALSE;
13315 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13316 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13317 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13318 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13319 				tcp->tcp_ms_we_have_waited = 0;
13320 
13321 				/*
13322 				 * Set tcp_cwnd back to 1 MSS, per
13323 				 * recommendation from
13324 				 * draft-floyd-incr-init-win-01.txt,
13325 				 * Increasing TCP's Initial Window.
13326 				 */
13327 				tcp->tcp_cwnd = tcp->tcp_mss;
13328 			}
13329 
13330 			tcp->tcp_swl1 = seg_seq;
13331 			tcp->tcp_swl2 = seg_ack;
13332 
13333 			new_swnd = BE16_TO_U16(tcph->th_win);
13334 			tcp->tcp_swnd = new_swnd;
13335 			if (new_swnd > tcp->tcp_max_swnd)
13336 				tcp->tcp_max_swnd = new_swnd;
13337 
13338 			/*
13339 			 * Always send the three-way handshake ack immediately
13340 			 * in order to make the connection complete as soon as
13341 			 * possible on the accepting host.
13342 			 */
13343 			flags |= TH_ACK_NEEDED;
13344 
13345 			/*
13346 			 * Special case for loopback.  At this point we have
13347 			 * received SYN-ACK from the remote endpoint.  In
13348 			 * order to ensure that both endpoints reach the
13349 			 * fused state prior to any data exchange, the final
13350 			 * ACK needs to be sent before we indicate T_CONN_CON
13351 			 * to the module upstream.
13352 			 */
13353 			if (tcp->tcp_loopback) {
13354 				mblk_t *ack_mp;
13355 
13356 				ASSERT(!tcp->tcp_unfusable);
13357 				ASSERT(mp1 != NULL);
13358 				/*
13359 				 * For loopback, we always get a pure SYN-ACK
13360 				 * and only need to send back the final ACK
13361 				 * with no data (this is because the other
13362 				 * tcp is ours and we don't do T/TCP).  This
13363 				 * final ACK triggers the passive side to
13364 				 * perform fusion in ESTABLISHED state.
13365 				 */
13366 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13367 					if (tcp->tcp_ack_tid != 0) {
13368 						(void) TCP_TIMER_CANCEL(tcp,
13369 						    tcp->tcp_ack_tid);
13370 						tcp->tcp_ack_tid = 0;
13371 					}
13372 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13373 					BUMP_LOCAL(tcp->tcp_obsegs);
13374 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13375 
13376 					/* Send up T_CONN_CON */
13377 					putnext(tcp->tcp_rq, mp1);
13378 
13379 					freemsg(mp);
13380 					return;
13381 				}
13382 				/*
13383 				 * Forget fusion; we need to handle more
13384 				 * complex cases below.  Send the deferred
13385 				 * T_CONN_CON message upstream and proceed
13386 				 * as usual.  Mark this tcp as not capable
13387 				 * of fusion.
13388 				 */
13389 				TCP_STAT(tcps, tcp_fusion_unfusable);
13390 				tcp->tcp_unfusable = B_TRUE;
13391 				putnext(tcp->tcp_rq, mp1);
13392 			}
13393 
13394 			/*
13395 			 * Check to see if there is data to be sent.  If
13396 			 * yes, set the transmit flag.  Then check to see
13397 			 * if received data processing needs to be done.
13398 			 * If not, go straight to xmit_check.  This short
13399 			 * cut is OK as we don't support T/TCP.
13400 			 */
13401 			if (tcp->tcp_unsent)
13402 				flags |= TH_XMIT_NEEDED;
13403 
13404 			if (seg_len == 0 && !(flags & TH_URG)) {
13405 				freemsg(mp);
13406 				goto xmit_check;
13407 			}
13408 
13409 			flags &= ~TH_SYN;
13410 			seg_seq++;
13411 			break;
13412 		}
13413 		tcp->tcp_state = TCPS_SYN_RCVD;
13414 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13415 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13416 		if (mp1) {
13417 			DB_CPID(mp1) = tcp->tcp_cpid;
13418 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13419 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13420 		}
13421 		freemsg(mp);
13422 		return;
13423 	case TCPS_SYN_RCVD:
13424 		if (flags & TH_ACK) {
13425 			/*
13426 			 * In this state, a SYN|ACK packet is either bogus
13427 			 * because the other side must be ACKing our SYN which
13428 			 * indicates it has seen the ACK for their SYN and
13429 			 * shouldn't retransmit it or we're crossing SYNs
13430 			 * on active open.
13431 			 */
13432 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13433 				freemsg(mp);
13434 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13435 				    tcp, seg_ack, 0, TH_RST);
13436 				return;
13437 			}
13438 			/*
13439 			 * NOTE: RFC 793 pg. 72 says this should be
13440 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13441 			 * but that would mean we have an ack that ignored
13442 			 * our SYN.
13443 			 */
13444 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13445 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13446 				freemsg(mp);
13447 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13448 				    tcp, seg_ack, 0, TH_RST);
13449 				return;
13450 			}
13451 		}
13452 		break;
13453 	case TCPS_LISTEN:
13454 		/*
13455 		 * Only a TLI listener can come through this path when a
13456 		 * acceptor is going back to be a listener and a packet
13457 		 * for the acceptor hits the classifier. For a socket
13458 		 * listener, this can never happen because a listener
13459 		 * can never accept connection on itself and hence a
13460 		 * socket acceptor can not go back to being a listener.
13461 		 */
13462 		ASSERT(!TCP_IS_SOCKET(tcp));
13463 		/*FALLTHRU*/
13464 	case TCPS_CLOSED:
13465 	case TCPS_BOUND: {
13466 		conn_t	*new_connp;
13467 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13468 
13469 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13470 		if (new_connp != NULL) {
13471 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13472 			return;
13473 		}
13474 		/* We failed to classify. For now just drop the packet */
13475 		freemsg(mp);
13476 		return;
13477 	}
13478 	case TCPS_IDLE:
13479 		/*
13480 		 * Handle the case where the tcp_clean_death() has happened
13481 		 * on a connection (application hasn't closed yet) but a packet
13482 		 * was already queued on squeue before tcp_clean_death()
13483 		 * was processed. Calling tcp_clean_death() twice on same
13484 		 * connection can result in weird behaviour.
13485 		 */
13486 		freemsg(mp);
13487 		return;
13488 	default:
13489 		break;
13490 	}
13491 
13492 	/*
13493 	 * Already on the correct queue/perimeter.
13494 	 * If this is a detached connection and not an eager
13495 	 * connection hanging off a listener then new data
13496 	 * (past the FIN) will cause a reset.
13497 	 * We do a special check here where it
13498 	 * is out of the main line, rather than check
13499 	 * if we are detached every time we see new
13500 	 * data down below.
13501 	 */
13502 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13503 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13504 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13505 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13506 
13507 		freemsg(mp);
13508 		/*
13509 		 * This could be an SSL closure alert. We're detached so just
13510 		 * acknowledge it this last time.
13511 		 */
13512 		if (tcp->tcp_kssl_ctx != NULL) {
13513 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13514 			tcp->tcp_kssl_ctx = NULL;
13515 
13516 			tcp->tcp_rnxt += seg_len;
13517 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13518 			flags |= TH_ACK_NEEDED;
13519 			goto ack_check;
13520 		}
13521 
13522 		tcp_xmit_ctl("new data when detached", tcp,
13523 		    tcp->tcp_snxt, 0, TH_RST);
13524 		(void) tcp_clean_death(tcp, EPROTO, 12);
13525 		return;
13526 	}
13527 
13528 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13529 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13530 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13531 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13532 
13533 	if (tcp->tcp_snd_ts_ok) {
13534 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13535 			/*
13536 			 * This segment is not acceptable.
13537 			 * Drop it and send back an ACK.
13538 			 */
13539 			freemsg(mp);
13540 			flags |= TH_ACK_NEEDED;
13541 			goto ack_check;
13542 		}
13543 	} else if (tcp->tcp_snd_sack_ok) {
13544 		ASSERT(tcp->tcp_sack_info != NULL);
13545 		tcpopt.tcp = tcp;
13546 		/*
13547 		 * SACK info in already updated in tcp_parse_options.  Ignore
13548 		 * all other TCP options...
13549 		 */
13550 		(void) tcp_parse_options(tcph, &tcpopt);
13551 	}
13552 try_again:;
13553 	mss = tcp->tcp_mss;
13554 	gap = seg_seq - tcp->tcp_rnxt;
13555 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13556 	/*
13557 	 * gap is the amount of sequence space between what we expect to see
13558 	 * and what we got for seg_seq.  A positive value for gap means
13559 	 * something got lost.  A negative value means we got some old stuff.
13560 	 */
13561 	if (gap < 0) {
13562 		/* Old stuff present.  Is the SYN in there? */
13563 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13564 		    (seg_len != 0)) {
13565 			flags &= ~TH_SYN;
13566 			seg_seq++;
13567 			urp--;
13568 			/* Recompute the gaps after noting the SYN. */
13569 			goto try_again;
13570 		}
13571 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13572 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13573 		    (seg_len > -gap ? -gap : seg_len));
13574 		/* Remove the old stuff from seg_len. */
13575 		seg_len += gap;
13576 		/*
13577 		 * Anything left?
13578 		 * Make sure to check for unack'd FIN when rest of data
13579 		 * has been previously ack'd.
13580 		 */
13581 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13582 			/*
13583 			 * Resets are only valid if they lie within our offered
13584 			 * window.  If the RST bit is set, we just ignore this
13585 			 * segment.
13586 			 */
13587 			if (flags & TH_RST) {
13588 				freemsg(mp);
13589 				return;
13590 			}
13591 
13592 			/*
13593 			 * The arriving of dup data packets indicate that we
13594 			 * may have postponed an ack for too long, or the other
13595 			 * side's RTT estimate is out of shape. Start acking
13596 			 * more often.
13597 			 */
13598 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13599 			    tcp->tcp_rack_cnt >= 1 &&
13600 			    tcp->tcp_rack_abs_max > 2) {
13601 				tcp->tcp_rack_abs_max--;
13602 			}
13603 			tcp->tcp_rack_cur_max = 1;
13604 
13605 			/*
13606 			 * This segment is "unacceptable".  None of its
13607 			 * sequence space lies within our advertized window.
13608 			 *
13609 			 * Adjust seg_len to the original value for tracing.
13610 			 */
13611 			seg_len -= gap;
13612 			if (tcp->tcp_debug) {
13613 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13614 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13615 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13616 				    "seg_len %d, rnxt %u, snxt %u, %s",
13617 				    gap, rgap, flags, seg_seq, seg_ack,
13618 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13619 				    tcp_display(tcp, NULL,
13620 				    DISP_ADDR_AND_PORT));
13621 			}
13622 
13623 			/*
13624 			 * Arrange to send an ACK in response to the
13625 			 * unacceptable segment per RFC 793 page 69. There
13626 			 * is only one small difference between ours and the
13627 			 * acceptability test in the RFC - we accept ACK-only
13628 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13629 			 * will be generated.
13630 			 *
13631 			 * Note that we have to ACK an ACK-only packet at least
13632 			 * for stacks that send 0-length keep-alives with
13633 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13634 			 * section 4.2.3.6. As long as we don't ever generate
13635 			 * an unacceptable packet in response to an incoming
13636 			 * packet that is unacceptable, it should not cause
13637 			 * "ACK wars".
13638 			 */
13639 			flags |=  TH_ACK_NEEDED;
13640 
13641 			/*
13642 			 * Continue processing this segment in order to use the
13643 			 * ACK information it contains, but skip all other
13644 			 * sequence-number processing.	Processing the ACK
13645 			 * information is necessary in order to
13646 			 * re-synchronize connections that may have lost
13647 			 * synchronization.
13648 			 *
13649 			 * We clear seg_len and flag fields related to
13650 			 * sequence number processing as they are not
13651 			 * to be trusted for an unacceptable segment.
13652 			 */
13653 			seg_len = 0;
13654 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13655 			goto process_ack;
13656 		}
13657 
13658 		/* Fix seg_seq, and chew the gap off the front. */
13659 		seg_seq = tcp->tcp_rnxt;
13660 		urp += gap;
13661 		do {
13662 			mblk_t	*mp2;
13663 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13664 			    (uintptr_t)UINT_MAX);
13665 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13666 			if (gap > 0) {
13667 				mp->b_rptr = mp->b_wptr - gap;
13668 				break;
13669 			}
13670 			mp2 = mp;
13671 			mp = mp->b_cont;
13672 			freeb(mp2);
13673 		} while (gap < 0);
13674 		/*
13675 		 * If the urgent data has already been acknowledged, we
13676 		 * should ignore TH_URG below
13677 		 */
13678 		if (urp < 0)
13679 			flags &= ~TH_URG;
13680 	}
13681 	/*
13682 	 * rgap is the amount of stuff received out of window.  A negative
13683 	 * value is the amount out of window.
13684 	 */
13685 	if (rgap < 0) {
13686 		mblk_t	*mp2;
13687 
13688 		if (tcp->tcp_rwnd == 0) {
13689 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13690 		} else {
13691 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13692 			UPDATE_MIB(&tcps->tcps_mib,
13693 			    tcpInDataPastWinBytes, -rgap);
13694 		}
13695 
13696 		/*
13697 		 * seg_len does not include the FIN, so if more than
13698 		 * just the FIN is out of window, we act like we don't
13699 		 * see it.  (If just the FIN is out of window, rgap
13700 		 * will be zero and we will go ahead and acknowledge
13701 		 * the FIN.)
13702 		 */
13703 		flags &= ~TH_FIN;
13704 
13705 		/* Fix seg_len and make sure there is something left. */
13706 		seg_len += rgap;
13707 		if (seg_len <= 0) {
13708 			/*
13709 			 * Resets are only valid if they lie within our offered
13710 			 * window.  If the RST bit is set, we just ignore this
13711 			 * segment.
13712 			 */
13713 			if (flags & TH_RST) {
13714 				freemsg(mp);
13715 				return;
13716 			}
13717 
13718 			/* Per RFC 793, we need to send back an ACK. */
13719 			flags |= TH_ACK_NEEDED;
13720 
13721 			/*
13722 			 * Send SIGURG as soon as possible i.e. even
13723 			 * if the TH_URG was delivered in a window probe
13724 			 * packet (which will be unacceptable).
13725 			 *
13726 			 * We generate a signal if none has been generated
13727 			 * for this connection or if this is a new urgent
13728 			 * byte. Also send a zero-length "unmarked" message
13729 			 * to inform SIOCATMARK that this is not the mark.
13730 			 *
13731 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13732 			 * is sent up. This plus the check for old data
13733 			 * (gap >= 0) handles the wraparound of the sequence
13734 			 * number space without having to always track the
13735 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13736 			 * this max in its rcv_up variable).
13737 			 *
13738 			 * This prevents duplicate SIGURGS due to a "late"
13739 			 * zero-window probe when the T_EXDATA_IND has already
13740 			 * been sent up.
13741 			 */
13742 			if ((flags & TH_URG) &&
13743 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13744 			    tcp->tcp_urp_last))) {
13745 				mp1 = allocb(0, BPRI_MED);
13746 				if (mp1 == NULL) {
13747 					freemsg(mp);
13748 					return;
13749 				}
13750 				if (!TCP_IS_DETACHED(tcp) &&
13751 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13752 				    SIGURG)) {
13753 					/* Try again on the rexmit. */
13754 					freemsg(mp1);
13755 					freemsg(mp);
13756 					return;
13757 				}
13758 				/*
13759 				 * If the next byte would be the mark
13760 				 * then mark with MARKNEXT else mark
13761 				 * with NOTMARKNEXT.
13762 				 */
13763 				if (gap == 0 && urp == 0)
13764 					mp1->b_flag |= MSGMARKNEXT;
13765 				else
13766 					mp1->b_flag |= MSGNOTMARKNEXT;
13767 				freemsg(tcp->tcp_urp_mark_mp);
13768 				tcp->tcp_urp_mark_mp = mp1;
13769 				flags |= TH_SEND_URP_MARK;
13770 				tcp->tcp_urp_last_valid = B_TRUE;
13771 				tcp->tcp_urp_last = urp + seg_seq;
13772 			}
13773 			/*
13774 			 * If this is a zero window probe, continue to
13775 			 * process the ACK part.  But we need to set seg_len
13776 			 * to 0 to avoid data processing.  Otherwise just
13777 			 * drop the segment and send back an ACK.
13778 			 */
13779 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13780 				flags &= ~(TH_SYN | TH_URG);
13781 				seg_len = 0;
13782 				goto process_ack;
13783 			} else {
13784 				freemsg(mp);
13785 				goto ack_check;
13786 			}
13787 		}
13788 		/* Pitch out of window stuff off the end. */
13789 		rgap = seg_len;
13790 		mp2 = mp;
13791 		do {
13792 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13793 			    (uintptr_t)INT_MAX);
13794 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13795 			if (rgap < 0) {
13796 				mp2->b_wptr += rgap;
13797 				if ((mp1 = mp2->b_cont) != NULL) {
13798 					mp2->b_cont = NULL;
13799 					freemsg(mp1);
13800 				}
13801 				break;
13802 			}
13803 		} while ((mp2 = mp2->b_cont) != NULL);
13804 	}
13805 ok:;
13806 	/*
13807 	 * TCP should check ECN info for segments inside the window only.
13808 	 * Therefore the check should be done here.
13809 	 */
13810 	if (tcp->tcp_ecn_ok) {
13811 		if (flags & TH_CWR) {
13812 			tcp->tcp_ecn_echo_on = B_FALSE;
13813 		}
13814 		/*
13815 		 * Note that both ECN_CE and CWR can be set in the
13816 		 * same segment.  In this case, we once again turn
13817 		 * on ECN_ECHO.
13818 		 */
13819 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13820 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13821 
13822 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13823 				tcp->tcp_ecn_echo_on = B_TRUE;
13824 			}
13825 		} else {
13826 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13827 
13828 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13829 			    htonl(IPH_ECN_CE << 20)) {
13830 				tcp->tcp_ecn_echo_on = B_TRUE;
13831 			}
13832 		}
13833 	}
13834 
13835 	/*
13836 	 * Check whether we can update tcp_ts_recent.  This test is
13837 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13838 	 * Extensions for High Performance: An Update", Internet Draft.
13839 	 */
13840 	if (tcp->tcp_snd_ts_ok &&
13841 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13842 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13843 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13844 		tcp->tcp_last_rcv_lbolt = lbolt64;
13845 	}
13846 
13847 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13848 		/*
13849 		 * FIN in an out of order segment.  We record this in
13850 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13851 		 * Clear the FIN so that any check on FIN flag will fail.
13852 		 * Remember that FIN also counts in the sequence number
13853 		 * space.  So we need to ack out of order FIN only segments.
13854 		 */
13855 		if (flags & TH_FIN) {
13856 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13857 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13858 			flags &= ~TH_FIN;
13859 			flags |= TH_ACK_NEEDED;
13860 		}
13861 		if (seg_len > 0) {
13862 			/* Fill in the SACK blk list. */
13863 			if (tcp->tcp_snd_sack_ok) {
13864 				ASSERT(tcp->tcp_sack_info != NULL);
13865 				tcp_sack_insert(tcp->tcp_sack_list,
13866 				    seg_seq, seg_seq + seg_len,
13867 				    &(tcp->tcp_num_sack_blk));
13868 			}
13869 
13870 			/*
13871 			 * Attempt reassembly and see if we have something
13872 			 * ready to go.
13873 			 */
13874 			mp = tcp_reass(tcp, mp, seg_seq);
13875 			/* Always ack out of order packets */
13876 			flags |= TH_ACK_NEEDED | TH_PUSH;
13877 			if (mp) {
13878 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13879 				    (uintptr_t)INT_MAX);
13880 				seg_len = mp->b_cont ? msgdsize(mp) :
13881 				    (int)(mp->b_wptr - mp->b_rptr);
13882 				seg_seq = tcp->tcp_rnxt;
13883 				/*
13884 				 * A gap is filled and the seq num and len
13885 				 * of the gap match that of a previously
13886 				 * received FIN, put the FIN flag back in.
13887 				 */
13888 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13889 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13890 					flags |= TH_FIN;
13891 					tcp->tcp_valid_bits &=
13892 					    ~TCP_OFO_FIN_VALID;
13893 				}
13894 			} else {
13895 				/*
13896 				 * Keep going even with NULL mp.
13897 				 * There may be a useful ACK or something else
13898 				 * we don't want to miss.
13899 				 *
13900 				 * But TCP should not perform fast retransmit
13901 				 * because of the ack number.  TCP uses
13902 				 * seg_len == 0 to determine if it is a pure
13903 				 * ACK.  And this is not a pure ACK.
13904 				 */
13905 				seg_len = 0;
13906 				ofo_seg = B_TRUE;
13907 			}
13908 		}
13909 	} else if (seg_len > 0) {
13910 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13911 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13912 		/*
13913 		 * If an out of order FIN was received before, and the seq
13914 		 * num and len of the new segment match that of the FIN,
13915 		 * put the FIN flag back in.
13916 		 */
13917 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13918 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13919 			flags |= TH_FIN;
13920 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13921 		}
13922 	}
13923 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13924 	if (flags & TH_RST) {
13925 		freemsg(mp);
13926 		switch (tcp->tcp_state) {
13927 		case TCPS_SYN_RCVD:
13928 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13929 			break;
13930 		case TCPS_ESTABLISHED:
13931 		case TCPS_FIN_WAIT_1:
13932 		case TCPS_FIN_WAIT_2:
13933 		case TCPS_CLOSE_WAIT:
13934 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13935 			break;
13936 		case TCPS_CLOSING:
13937 		case TCPS_LAST_ACK:
13938 			(void) tcp_clean_death(tcp, 0, 16);
13939 			break;
13940 		default:
13941 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13942 			(void) tcp_clean_death(tcp, ENXIO, 17);
13943 			break;
13944 		}
13945 		return;
13946 	}
13947 	if (flags & TH_SYN) {
13948 		/*
13949 		 * See RFC 793, Page 71
13950 		 *
13951 		 * The seq number must be in the window as it should
13952 		 * be "fixed" above.  If it is outside window, it should
13953 		 * be already rejected.  Note that we allow seg_seq to be
13954 		 * rnxt + rwnd because we want to accept 0 window probe.
13955 		 */
13956 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13957 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13958 		freemsg(mp);
13959 		/*
13960 		 * If the ACK flag is not set, just use our snxt as the
13961 		 * seq number of the RST segment.
13962 		 */
13963 		if (!(flags & TH_ACK)) {
13964 			seg_ack = tcp->tcp_snxt;
13965 		}
13966 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13967 		    TH_RST|TH_ACK);
13968 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13969 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13970 		return;
13971 	}
13972 	/*
13973 	 * urp could be -1 when the urp field in the packet is 0
13974 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13975 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13976 	 */
13977 	if (flags & TH_URG && urp >= 0) {
13978 		if (!tcp->tcp_urp_last_valid ||
13979 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13980 			/*
13981 			 * If we haven't generated the signal yet for this
13982 			 * urgent pointer value, do it now.  Also, send up a
13983 			 * zero-length M_DATA indicating whether or not this is
13984 			 * the mark. The latter is not needed when a
13985 			 * T_EXDATA_IND is sent up. However, if there are
13986 			 * allocation failures this code relies on the sender
13987 			 * retransmitting and the socket code for determining
13988 			 * the mark should not block waiting for the peer to
13989 			 * transmit. Thus, for simplicity we always send up the
13990 			 * mark indication.
13991 			 */
13992 			mp1 = allocb(0, BPRI_MED);
13993 			if (mp1 == NULL) {
13994 				freemsg(mp);
13995 				return;
13996 			}
13997 			if (!TCP_IS_DETACHED(tcp) &&
13998 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
13999 				/* Try again on the rexmit. */
14000 				freemsg(mp1);
14001 				freemsg(mp);
14002 				return;
14003 			}
14004 			/*
14005 			 * Mark with NOTMARKNEXT for now.
14006 			 * The code below will change this to MARKNEXT
14007 			 * if we are at the mark.
14008 			 *
14009 			 * If there are allocation failures (e.g. in dupmsg
14010 			 * below) the next time tcp_rput_data sees the urgent
14011 			 * segment it will send up the MSG*MARKNEXT message.
14012 			 */
14013 			mp1->b_flag |= MSGNOTMARKNEXT;
14014 			freemsg(tcp->tcp_urp_mark_mp);
14015 			tcp->tcp_urp_mark_mp = mp1;
14016 			flags |= TH_SEND_URP_MARK;
14017 #ifdef DEBUG
14018 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14019 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
14020 			    "last %x, %s",
14021 			    seg_seq, urp, tcp->tcp_urp_last,
14022 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14023 #endif /* DEBUG */
14024 			tcp->tcp_urp_last_valid = B_TRUE;
14025 			tcp->tcp_urp_last = urp + seg_seq;
14026 		} else if (tcp->tcp_urp_mark_mp != NULL) {
14027 			/*
14028 			 * An allocation failure prevented the previous
14029 			 * tcp_rput_data from sending up the allocated
14030 			 * MSG*MARKNEXT message - send it up this time
14031 			 * around.
14032 			 */
14033 			flags |= TH_SEND_URP_MARK;
14034 		}
14035 
14036 		/*
14037 		 * If the urgent byte is in this segment, make sure that it is
14038 		 * all by itself.  This makes it much easier to deal with the
14039 		 * possibility of an allocation failure on the T_exdata_ind.
14040 		 * Note that seg_len is the number of bytes in the segment, and
14041 		 * urp is the offset into the segment of the urgent byte.
14042 		 * urp < seg_len means that the urgent byte is in this segment.
14043 		 */
14044 		if (urp < seg_len) {
14045 			if (seg_len != 1) {
14046 				uint32_t  tmp_rnxt;
14047 				/*
14048 				 * Break it up and feed it back in.
14049 				 * Re-attach the IP header.
14050 				 */
14051 				mp->b_rptr = iphdr;
14052 				if (urp > 0) {
14053 					/*
14054 					 * There is stuff before the urgent
14055 					 * byte.
14056 					 */
14057 					mp1 = dupmsg(mp);
14058 					if (!mp1) {
14059 						/*
14060 						 * Trim from urgent byte on.
14061 						 * The rest will come back.
14062 						 */
14063 						(void) adjmsg(mp,
14064 						    urp - seg_len);
14065 						tcp_rput_data(connp,
14066 						    mp, NULL);
14067 						return;
14068 					}
14069 					(void) adjmsg(mp1, urp - seg_len);
14070 					/* Feed this piece back in. */
14071 					tmp_rnxt = tcp->tcp_rnxt;
14072 					tcp_rput_data(connp, mp1, NULL);
14073 					/*
14074 					 * If the data passed back in was not
14075 					 * processed (ie: bad ACK) sending
14076 					 * the remainder back in will cause a
14077 					 * loop. In this case, drop the
14078 					 * packet and let the sender try
14079 					 * sending a good packet.
14080 					 */
14081 					if (tmp_rnxt == tcp->tcp_rnxt) {
14082 						freemsg(mp);
14083 						return;
14084 					}
14085 				}
14086 				if (urp != seg_len - 1) {
14087 					uint32_t  tmp_rnxt;
14088 					/*
14089 					 * There is stuff after the urgent
14090 					 * byte.
14091 					 */
14092 					mp1 = dupmsg(mp);
14093 					if (!mp1) {
14094 						/*
14095 						 * Trim everything beyond the
14096 						 * urgent byte.  The rest will
14097 						 * come back.
14098 						 */
14099 						(void) adjmsg(mp,
14100 						    urp + 1 - seg_len);
14101 						tcp_rput_data(connp,
14102 						    mp, NULL);
14103 						return;
14104 					}
14105 					(void) adjmsg(mp1, urp + 1 - seg_len);
14106 					tmp_rnxt = tcp->tcp_rnxt;
14107 					tcp_rput_data(connp, mp1, NULL);
14108 					/*
14109 					 * If the data passed back in was not
14110 					 * processed (ie: bad ACK) sending
14111 					 * the remainder back in will cause a
14112 					 * loop. In this case, drop the
14113 					 * packet and let the sender try
14114 					 * sending a good packet.
14115 					 */
14116 					if (tmp_rnxt == tcp->tcp_rnxt) {
14117 						freemsg(mp);
14118 						return;
14119 					}
14120 				}
14121 				tcp_rput_data(connp, mp, NULL);
14122 				return;
14123 			}
14124 			/*
14125 			 * This segment contains only the urgent byte.  We
14126 			 * have to allocate the T_exdata_ind, if we can.
14127 			 */
14128 			if (!tcp->tcp_urp_mp) {
14129 				struct T_exdata_ind *tei;
14130 				mp1 = allocb(sizeof (struct T_exdata_ind),
14131 				    BPRI_MED);
14132 				if (!mp1) {
14133 					/*
14134 					 * Sigh... It'll be back.
14135 					 * Generate any MSG*MARK message now.
14136 					 */
14137 					freemsg(mp);
14138 					seg_len = 0;
14139 					if (flags & TH_SEND_URP_MARK) {
14140 
14141 
14142 						ASSERT(tcp->tcp_urp_mark_mp);
14143 						tcp->tcp_urp_mark_mp->b_flag &=
14144 						    ~MSGNOTMARKNEXT;
14145 						tcp->tcp_urp_mark_mp->b_flag |=
14146 						    MSGMARKNEXT;
14147 					}
14148 					goto ack_check;
14149 				}
14150 				mp1->b_datap->db_type = M_PROTO;
14151 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14152 				tei->PRIM_type = T_EXDATA_IND;
14153 				tei->MORE_flag = 0;
14154 				mp1->b_wptr = (uchar_t *)&tei[1];
14155 				tcp->tcp_urp_mp = mp1;
14156 #ifdef DEBUG
14157 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14158 				    "tcp_rput: allocated exdata_ind %s",
14159 				    tcp_display(tcp, NULL,
14160 				    DISP_PORT_ONLY));
14161 #endif /* DEBUG */
14162 				/*
14163 				 * There is no need to send a separate MSG*MARK
14164 				 * message since the T_EXDATA_IND will be sent
14165 				 * now.
14166 				 */
14167 				flags &= ~TH_SEND_URP_MARK;
14168 				freemsg(tcp->tcp_urp_mark_mp);
14169 				tcp->tcp_urp_mark_mp = NULL;
14170 			}
14171 			/*
14172 			 * Now we are all set.  On the next putnext upstream,
14173 			 * tcp_urp_mp will be non-NULL and will get prepended
14174 			 * to what has to be this piece containing the urgent
14175 			 * byte.  If for any reason we abort this segment below,
14176 			 * if it comes back, we will have this ready, or it
14177 			 * will get blown off in close.
14178 			 */
14179 		} else if (urp == seg_len) {
14180 			/*
14181 			 * The urgent byte is the next byte after this sequence
14182 			 * number. If there is data it is marked with
14183 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14184 			 * since it is not needed. Otherwise, if the code
14185 			 * above just allocated a zero-length tcp_urp_mark_mp
14186 			 * message, that message is tagged with MSGMARKNEXT.
14187 			 * Sending up these MSGMARKNEXT messages makes
14188 			 * SIOCATMARK work correctly even though
14189 			 * the T_EXDATA_IND will not be sent up until the
14190 			 * urgent byte arrives.
14191 			 */
14192 			if (seg_len != 0) {
14193 				flags |= TH_MARKNEXT_NEEDED;
14194 				freemsg(tcp->tcp_urp_mark_mp);
14195 				tcp->tcp_urp_mark_mp = NULL;
14196 				flags &= ~TH_SEND_URP_MARK;
14197 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14198 				flags |= TH_SEND_URP_MARK;
14199 				tcp->tcp_urp_mark_mp->b_flag &=
14200 				    ~MSGNOTMARKNEXT;
14201 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14202 			}
14203 #ifdef DEBUG
14204 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14205 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14206 			    seg_len, flags,
14207 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14208 #endif /* DEBUG */
14209 		} else {
14210 			/* Data left until we hit mark */
14211 #ifdef DEBUG
14212 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14213 			    "tcp_rput: URP %d bytes left, %s",
14214 			    urp - seg_len, tcp_display(tcp, NULL,
14215 			    DISP_PORT_ONLY));
14216 #endif /* DEBUG */
14217 		}
14218 	}
14219 
14220 process_ack:
14221 	if (!(flags & TH_ACK)) {
14222 		freemsg(mp);
14223 		goto xmit_check;
14224 	}
14225 	}
14226 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14227 
14228 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14229 		tcp->tcp_ip_forward_progress = B_TRUE;
14230 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14231 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14232 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14233 			/* 3-way handshake complete - pass up the T_CONN_IND */
14234 			tcp_t	*listener = tcp->tcp_listener;
14235 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14236 
14237 			tcp->tcp_tconnind_started = B_TRUE;
14238 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14239 			/*
14240 			 * We are here means eager is fine but it can
14241 			 * get a TH_RST at any point between now and till
14242 			 * accept completes and disappear. We need to
14243 			 * ensure that reference to eager is valid after
14244 			 * we get out of eager's perimeter. So we do
14245 			 * an extra refhold.
14246 			 */
14247 			CONN_INC_REF(connp);
14248 
14249 			/*
14250 			 * The listener also exists because of the refhold
14251 			 * done in tcp_conn_request. Its possible that it
14252 			 * might have closed. We will check that once we
14253 			 * get inside listeners context.
14254 			 */
14255 			CONN_INC_REF(listener->tcp_connp);
14256 			if (listener->tcp_connp->conn_sqp ==
14257 			    connp->conn_sqp) {
14258 				tcp_send_conn_ind(listener->tcp_connp, mp,
14259 				    listener->tcp_connp->conn_sqp);
14260 				CONN_DEC_REF(listener->tcp_connp);
14261 			} else if (!tcp->tcp_loopback) {
14262 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14263 				    tcp_send_conn_ind,
14264 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14265 			} else {
14266 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14267 				    tcp_send_conn_ind, listener->tcp_connp,
14268 				    SQTAG_TCP_CONN_IND);
14269 			}
14270 		}
14271 
14272 		if (tcp->tcp_active_open) {
14273 			/*
14274 			 * We are seeing the final ack in the three way
14275 			 * hand shake of a active open'ed connection
14276 			 * so we must send up a T_CONN_CON
14277 			 */
14278 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14279 				freemsg(mp);
14280 				return;
14281 			}
14282 			/*
14283 			 * Don't fuse the loopback endpoints for
14284 			 * simultaneous active opens.
14285 			 */
14286 			if (tcp->tcp_loopback) {
14287 				TCP_STAT(tcps, tcp_fusion_unfusable);
14288 				tcp->tcp_unfusable = B_TRUE;
14289 			}
14290 		}
14291 
14292 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14293 		bytes_acked--;
14294 		/* SYN was acked - making progress */
14295 		if (tcp->tcp_ipversion == IPV6_VERSION)
14296 			tcp->tcp_ip_forward_progress = B_TRUE;
14297 
14298 		/*
14299 		 * If SYN was retransmitted, need to reset all
14300 		 * retransmission info as this segment will be
14301 		 * treated as a dup ACK.
14302 		 */
14303 		if (tcp->tcp_rexmit) {
14304 			tcp->tcp_rexmit = B_FALSE;
14305 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14306 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14307 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14308 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14309 			tcp->tcp_ms_we_have_waited = 0;
14310 			tcp->tcp_cwnd = mss;
14311 		}
14312 
14313 		/*
14314 		 * We set the send window to zero here.
14315 		 * This is needed if there is data to be
14316 		 * processed already on the queue.
14317 		 * Later (at swnd_update label), the
14318 		 * "new_swnd > tcp_swnd" condition is satisfied
14319 		 * the XMIT_NEEDED flag is set in the current
14320 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14321 		 * called if there is already data on queue in
14322 		 * this state.
14323 		 */
14324 		tcp->tcp_swnd = 0;
14325 
14326 		if (new_swnd > tcp->tcp_max_swnd)
14327 			tcp->tcp_max_swnd = new_swnd;
14328 		tcp->tcp_swl1 = seg_seq;
14329 		tcp->tcp_swl2 = seg_ack;
14330 		tcp->tcp_state = TCPS_ESTABLISHED;
14331 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14332 
14333 		/* Fuse when both sides are in ESTABLISHED state */
14334 		if (tcp->tcp_loopback && do_tcp_fusion)
14335 			tcp_fuse(tcp, iphdr, tcph);
14336 
14337 	}
14338 	/* This code follows 4.4BSD-Lite2 mostly. */
14339 	if (bytes_acked < 0)
14340 		goto est;
14341 
14342 	/*
14343 	 * If TCP is ECN capable and the congestion experience bit is
14344 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14345 	 * done once per window (or more loosely, per RTT).
14346 	 */
14347 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14348 		tcp->tcp_cwr = B_FALSE;
14349 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14350 		if (!tcp->tcp_cwr) {
14351 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14352 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14353 			tcp->tcp_cwnd = npkt * mss;
14354 			/*
14355 			 * If the cwnd is 0, use the timer to clock out
14356 			 * new segments.  This is required by the ECN spec.
14357 			 */
14358 			if (npkt == 0) {
14359 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14360 				/*
14361 				 * This makes sure that when the ACK comes
14362 				 * back, we will increase tcp_cwnd by 1 MSS.
14363 				 */
14364 				tcp->tcp_cwnd_cnt = 0;
14365 			}
14366 			tcp->tcp_cwr = B_TRUE;
14367 			/*
14368 			 * This marks the end of the current window of in
14369 			 * flight data.  That is why we don't use
14370 			 * tcp_suna + tcp_swnd.  Only data in flight can
14371 			 * provide ECN info.
14372 			 */
14373 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14374 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14375 		}
14376 	}
14377 
14378 	mp1 = tcp->tcp_xmit_head;
14379 	if (bytes_acked == 0) {
14380 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14381 			int dupack_cnt;
14382 
14383 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14384 			/*
14385 			 * Fast retransmit.  When we have seen exactly three
14386 			 * identical ACKs while we have unacked data
14387 			 * outstanding we take it as a hint that our peer
14388 			 * dropped something.
14389 			 *
14390 			 * If TCP is retransmitting, don't do fast retransmit.
14391 			 */
14392 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14393 			    ! tcp->tcp_rexmit) {
14394 				/* Do Limited Transmit */
14395 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14396 				    tcps->tcps_dupack_fast_retransmit) {
14397 					/*
14398 					 * RFC 3042
14399 					 *
14400 					 * What we need to do is temporarily
14401 					 * increase tcp_cwnd so that new
14402 					 * data can be sent if it is allowed
14403 					 * by the receive window (tcp_rwnd).
14404 					 * tcp_wput_data() will take care of
14405 					 * the rest.
14406 					 *
14407 					 * If the connection is SACK capable,
14408 					 * only do limited xmit when there
14409 					 * is SACK info.
14410 					 *
14411 					 * Note how tcp_cwnd is incremented.
14412 					 * The first dup ACK will increase
14413 					 * it by 1 MSS.  The second dup ACK
14414 					 * will increase it by 2 MSS.  This
14415 					 * means that only 1 new segment will
14416 					 * be sent for each dup ACK.
14417 					 */
14418 					if (tcp->tcp_unsent > 0 &&
14419 					    (!tcp->tcp_snd_sack_ok ||
14420 					    (tcp->tcp_snd_sack_ok &&
14421 					    tcp->tcp_notsack_list != NULL))) {
14422 						tcp->tcp_cwnd += mss <<
14423 						    (tcp->tcp_dupack_cnt - 1);
14424 						flags |= TH_LIMIT_XMIT;
14425 					}
14426 				} else if (dupack_cnt ==
14427 				    tcps->tcps_dupack_fast_retransmit) {
14428 
14429 				/*
14430 				 * If we have reduced tcp_ssthresh
14431 				 * because of ECN, do not reduce it again
14432 				 * unless it is already one window of data
14433 				 * away.  After one window of data, tcp_cwr
14434 				 * should then be cleared.  Note that
14435 				 * for non ECN capable connection, tcp_cwr
14436 				 * should always be false.
14437 				 *
14438 				 * Adjust cwnd since the duplicate
14439 				 * ack indicates that a packet was
14440 				 * dropped (due to congestion.)
14441 				 */
14442 				if (!tcp->tcp_cwr) {
14443 					npkt = ((tcp->tcp_snxt -
14444 					    tcp->tcp_suna) >> 1) / mss;
14445 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14446 					    mss;
14447 					tcp->tcp_cwnd = (npkt +
14448 					    tcp->tcp_dupack_cnt) * mss;
14449 				}
14450 				if (tcp->tcp_ecn_ok) {
14451 					tcp->tcp_cwr = B_TRUE;
14452 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14453 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14454 				}
14455 
14456 				/*
14457 				 * We do Hoe's algorithm.  Refer to her
14458 				 * paper "Improving the Start-up Behavior
14459 				 * of a Congestion Control Scheme for TCP,"
14460 				 * appeared in SIGCOMM'96.
14461 				 *
14462 				 * Save highest seq no we have sent so far.
14463 				 * Be careful about the invisible FIN byte.
14464 				 */
14465 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14466 				    (tcp->tcp_unsent == 0)) {
14467 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14468 				} else {
14469 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14470 				}
14471 
14472 				/*
14473 				 * Do not allow bursty traffic during.
14474 				 * fast recovery.  Refer to Fall and Floyd's
14475 				 * paper "Simulation-based Comparisons of
14476 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14477 				 * This is a best current practise.
14478 				 */
14479 				tcp->tcp_snd_burst = TCP_CWND_SS;
14480 
14481 				/*
14482 				 * For SACK:
14483 				 * Calculate tcp_pipe, which is the
14484 				 * estimated number of bytes in
14485 				 * network.
14486 				 *
14487 				 * tcp_fack is the highest sack'ed seq num
14488 				 * TCP has received.
14489 				 *
14490 				 * tcp_pipe is explained in the above quoted
14491 				 * Fall and Floyd's paper.  tcp_fack is
14492 				 * explained in Mathis and Mahdavi's
14493 				 * "Forward Acknowledgment: Refining TCP
14494 				 * Congestion Control" in SIGCOMM '96.
14495 				 */
14496 				if (tcp->tcp_snd_sack_ok) {
14497 					ASSERT(tcp->tcp_sack_info != NULL);
14498 					if (tcp->tcp_notsack_list != NULL) {
14499 						tcp->tcp_pipe = tcp->tcp_snxt -
14500 						    tcp->tcp_fack;
14501 						tcp->tcp_sack_snxt = seg_ack;
14502 						flags |= TH_NEED_SACK_REXMIT;
14503 					} else {
14504 						/*
14505 						 * Always initialize tcp_pipe
14506 						 * even though we don't have
14507 						 * any SACK info.  If later
14508 						 * we get SACK info and
14509 						 * tcp_pipe is not initialized,
14510 						 * funny things will happen.
14511 						 */
14512 						tcp->tcp_pipe =
14513 						    tcp->tcp_cwnd_ssthresh;
14514 					}
14515 				} else {
14516 					flags |= TH_REXMIT_NEEDED;
14517 				} /* tcp_snd_sack_ok */
14518 
14519 				} else {
14520 					/*
14521 					 * Here we perform congestion
14522 					 * avoidance, but NOT slow start.
14523 					 * This is known as the Fast
14524 					 * Recovery Algorithm.
14525 					 */
14526 					if (tcp->tcp_snd_sack_ok &&
14527 					    tcp->tcp_notsack_list != NULL) {
14528 						flags |= TH_NEED_SACK_REXMIT;
14529 						tcp->tcp_pipe -= mss;
14530 						if (tcp->tcp_pipe < 0)
14531 							tcp->tcp_pipe = 0;
14532 					} else {
14533 					/*
14534 					 * We know that one more packet has
14535 					 * left the pipe thus we can update
14536 					 * cwnd.
14537 					 */
14538 					cwnd = tcp->tcp_cwnd + mss;
14539 					if (cwnd > tcp->tcp_cwnd_max)
14540 						cwnd = tcp->tcp_cwnd_max;
14541 					tcp->tcp_cwnd = cwnd;
14542 					if (tcp->tcp_unsent > 0)
14543 						flags |= TH_XMIT_NEEDED;
14544 					}
14545 				}
14546 			}
14547 		} else if (tcp->tcp_zero_win_probe) {
14548 			/*
14549 			 * If the window has opened, need to arrange
14550 			 * to send additional data.
14551 			 */
14552 			if (new_swnd != 0) {
14553 				/* tcp_suna != tcp_snxt */
14554 				/* Packet contains a window update */
14555 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14556 				tcp->tcp_zero_win_probe = 0;
14557 				tcp->tcp_timer_backoff = 0;
14558 				tcp->tcp_ms_we_have_waited = 0;
14559 
14560 				/*
14561 				 * Transmit starting with tcp_suna since
14562 				 * the one byte probe is not ack'ed.
14563 				 * If TCP has sent more than one identical
14564 				 * probe, tcp_rexmit will be set.  That means
14565 				 * tcp_ss_rexmit() will send out the one
14566 				 * byte along with new data.  Otherwise,
14567 				 * fake the retransmission.
14568 				 */
14569 				flags |= TH_XMIT_NEEDED;
14570 				if (!tcp->tcp_rexmit) {
14571 					tcp->tcp_rexmit = B_TRUE;
14572 					tcp->tcp_dupack_cnt = 0;
14573 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14574 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14575 				}
14576 			}
14577 		}
14578 		goto swnd_update;
14579 	}
14580 
14581 	/*
14582 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14583 	 * If the ACK value acks something that we have not yet sent, it might
14584 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14585 	 * other side.
14586 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14587 	 * state is handled above, so we can always just drop the segment and
14588 	 * send an ACK here.
14589 	 *
14590 	 * Should we send ACKs in response to ACK only segments?
14591 	 */
14592 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14593 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14594 		/* drop the received segment */
14595 		freemsg(mp);
14596 
14597 		/*
14598 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14599 		 * greater than 0, check if the number of such
14600 		 * bogus ACks is greater than that count.  If yes,
14601 		 * don't send back any ACK.  This prevents TCP from
14602 		 * getting into an ACK storm if somehow an attacker
14603 		 * successfully spoofs an acceptable segment to our
14604 		 * peer.
14605 		 */
14606 		if (tcp_drop_ack_unsent_cnt > 0 &&
14607 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14608 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14609 			return;
14610 		}
14611 		mp = tcp_ack_mp(tcp);
14612 		if (mp != NULL) {
14613 			BUMP_LOCAL(tcp->tcp_obsegs);
14614 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14615 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14616 		}
14617 		return;
14618 	}
14619 
14620 	/*
14621 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14622 	 * blocks that are covered by this ACK.
14623 	 */
14624 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14625 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14626 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14627 	}
14628 
14629 	/*
14630 	 * If we got an ACK after fast retransmit, check to see
14631 	 * if it is a partial ACK.  If it is not and the congestion
14632 	 * window was inflated to account for the other side's
14633 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14634 	 */
14635 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14636 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14637 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14638 			tcp->tcp_dupack_cnt = 0;
14639 			/*
14640 			 * Restore the orig tcp_cwnd_ssthresh after
14641 			 * fast retransmit phase.
14642 			 */
14643 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14644 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14645 			}
14646 			tcp->tcp_rexmit_max = seg_ack;
14647 			tcp->tcp_cwnd_cnt = 0;
14648 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14649 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14650 
14651 			/*
14652 			 * Remove all notsack info to avoid confusion with
14653 			 * the next fast retrasnmit/recovery phase.
14654 			 */
14655 			if (tcp->tcp_snd_sack_ok &&
14656 			    tcp->tcp_notsack_list != NULL) {
14657 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14658 			}
14659 		} else {
14660 			if (tcp->tcp_snd_sack_ok &&
14661 			    tcp->tcp_notsack_list != NULL) {
14662 				flags |= TH_NEED_SACK_REXMIT;
14663 				tcp->tcp_pipe -= mss;
14664 				if (tcp->tcp_pipe < 0)
14665 					tcp->tcp_pipe = 0;
14666 			} else {
14667 				/*
14668 				 * Hoe's algorithm:
14669 				 *
14670 				 * Retransmit the unack'ed segment and
14671 				 * restart fast recovery.  Note that we
14672 				 * need to scale back tcp_cwnd to the
14673 				 * original value when we started fast
14674 				 * recovery.  This is to prevent overly
14675 				 * aggressive behaviour in sending new
14676 				 * segments.
14677 				 */
14678 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14679 				    tcps->tcps_dupack_fast_retransmit * mss;
14680 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14681 				flags |= TH_REXMIT_NEEDED;
14682 			}
14683 		}
14684 	} else {
14685 		tcp->tcp_dupack_cnt = 0;
14686 		if (tcp->tcp_rexmit) {
14687 			/*
14688 			 * TCP is retranmitting.  If the ACK ack's all
14689 			 * outstanding data, update tcp_rexmit_max and
14690 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14691 			 * to the correct value.
14692 			 *
14693 			 * Note that SEQ_LEQ() is used.  This is to avoid
14694 			 * unnecessary fast retransmit caused by dup ACKs
14695 			 * received when TCP does slow start retransmission
14696 			 * after a time out.  During this phase, TCP may
14697 			 * send out segments which are already received.
14698 			 * This causes dup ACKs to be sent back.
14699 			 */
14700 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14701 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14702 					tcp->tcp_rexmit_nxt = seg_ack;
14703 				}
14704 				if (seg_ack != tcp->tcp_rexmit_max) {
14705 					flags |= TH_XMIT_NEEDED;
14706 				}
14707 			} else {
14708 				tcp->tcp_rexmit = B_FALSE;
14709 				tcp->tcp_xmit_zc_clean = B_FALSE;
14710 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14711 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14712 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14713 			}
14714 			tcp->tcp_ms_we_have_waited = 0;
14715 		}
14716 	}
14717 
14718 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14719 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14720 	tcp->tcp_suna = seg_ack;
14721 	if (tcp->tcp_zero_win_probe != 0) {
14722 		tcp->tcp_zero_win_probe = 0;
14723 		tcp->tcp_timer_backoff = 0;
14724 	}
14725 
14726 	/*
14727 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14728 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14729 	 * will not reach here.
14730 	 */
14731 	if (mp1 == NULL) {
14732 		goto fin_acked;
14733 	}
14734 
14735 	/*
14736 	 * Update the congestion window.
14737 	 *
14738 	 * If TCP is not ECN capable or TCP is ECN capable but the
14739 	 * congestion experience bit is not set, increase the tcp_cwnd as
14740 	 * usual.
14741 	 */
14742 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14743 		cwnd = tcp->tcp_cwnd;
14744 		add = mss;
14745 
14746 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14747 			/*
14748 			 * This is to prevent an increase of less than 1 MSS of
14749 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14750 			 * may send out tinygrams in order to preserve mblk
14751 			 * boundaries.
14752 			 *
14753 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14754 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14755 			 * increased by 1 MSS for every RTTs.
14756 			 */
14757 			if (tcp->tcp_cwnd_cnt <= 0) {
14758 				tcp->tcp_cwnd_cnt = cwnd + add;
14759 			} else {
14760 				tcp->tcp_cwnd_cnt -= add;
14761 				add = 0;
14762 			}
14763 		}
14764 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14765 	}
14766 
14767 	/* See if the latest urgent data has been acknowledged */
14768 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14769 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14770 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14771 
14772 	/* Can we update the RTT estimates? */
14773 	if (tcp->tcp_snd_ts_ok) {
14774 		/* Ignore zero timestamp echo-reply. */
14775 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14776 			tcp_set_rto(tcp, (int32_t)lbolt -
14777 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14778 		}
14779 
14780 		/* If needed, restart the timer. */
14781 		if (tcp->tcp_set_timer == 1) {
14782 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14783 			tcp->tcp_set_timer = 0;
14784 		}
14785 		/*
14786 		 * Update tcp_csuna in case the other side stops sending
14787 		 * us timestamps.
14788 		 */
14789 		tcp->tcp_csuna = tcp->tcp_snxt;
14790 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14791 		/*
14792 		 * An ACK sequence we haven't seen before, so get the RTT
14793 		 * and update the RTO. But first check if the timestamp is
14794 		 * valid to use.
14795 		 */
14796 		if ((mp1->b_next != NULL) &&
14797 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14798 			tcp_set_rto(tcp, (int32_t)lbolt -
14799 			    (int32_t)(intptr_t)mp1->b_prev);
14800 		else
14801 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14802 
14803 		/* Remeber the last sequence to be ACKed */
14804 		tcp->tcp_csuna = seg_ack;
14805 		if (tcp->tcp_set_timer == 1) {
14806 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14807 			tcp->tcp_set_timer = 0;
14808 		}
14809 	} else {
14810 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14811 	}
14812 
14813 	/* Eat acknowledged bytes off the xmit queue. */
14814 	for (;;) {
14815 		mblk_t	*mp2;
14816 		uchar_t	*wptr;
14817 
14818 		wptr = mp1->b_wptr;
14819 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14820 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14821 		if (bytes_acked < 0) {
14822 			mp1->b_rptr = wptr + bytes_acked;
14823 			/*
14824 			 * Set a new timestamp if all the bytes timed by the
14825 			 * old timestamp have been ack'ed.
14826 			 */
14827 			if (SEQ_GT(seg_ack,
14828 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14829 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14830 				mp1->b_next = NULL;
14831 			}
14832 			break;
14833 		}
14834 		mp1->b_next = NULL;
14835 		mp1->b_prev = NULL;
14836 		mp2 = mp1;
14837 		mp1 = mp1->b_cont;
14838 
14839 		/*
14840 		 * This notification is required for some zero-copy
14841 		 * clients to maintain a copy semantic. After the data
14842 		 * is ack'ed, client is safe to modify or reuse the buffer.
14843 		 */
14844 		if (tcp->tcp_snd_zcopy_aware &&
14845 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14846 			tcp_zcopy_notify(tcp);
14847 		freeb(mp2);
14848 		if (bytes_acked == 0) {
14849 			if (mp1 == NULL) {
14850 				/* Everything is ack'ed, clear the tail. */
14851 				tcp->tcp_xmit_tail = NULL;
14852 				/*
14853 				 * Cancel the timer unless we are still
14854 				 * waiting for an ACK for the FIN packet.
14855 				 */
14856 				if (tcp->tcp_timer_tid != 0 &&
14857 				    tcp->tcp_snxt == tcp->tcp_suna) {
14858 					(void) TCP_TIMER_CANCEL(tcp,
14859 					    tcp->tcp_timer_tid);
14860 					tcp->tcp_timer_tid = 0;
14861 				}
14862 				goto pre_swnd_update;
14863 			}
14864 			if (mp2 != tcp->tcp_xmit_tail)
14865 				break;
14866 			tcp->tcp_xmit_tail = mp1;
14867 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14868 			    (uintptr_t)INT_MAX);
14869 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14870 			    mp1->b_rptr);
14871 			break;
14872 		}
14873 		if (mp1 == NULL) {
14874 			/*
14875 			 * More was acked but there is nothing more
14876 			 * outstanding.  This means that the FIN was
14877 			 * just acked or that we're talking to a clown.
14878 			 */
14879 fin_acked:
14880 			ASSERT(tcp->tcp_fin_sent);
14881 			tcp->tcp_xmit_tail = NULL;
14882 			if (tcp->tcp_fin_sent) {
14883 				/* FIN was acked - making progress */
14884 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14885 				    !tcp->tcp_fin_acked)
14886 					tcp->tcp_ip_forward_progress = B_TRUE;
14887 				tcp->tcp_fin_acked = B_TRUE;
14888 				if (tcp->tcp_linger_tid != 0 &&
14889 				    TCP_TIMER_CANCEL(tcp,
14890 				    tcp->tcp_linger_tid) >= 0) {
14891 					tcp_stop_lingering(tcp);
14892 					freemsg(mp);
14893 					mp = NULL;
14894 				}
14895 			} else {
14896 				/*
14897 				 * We should never get here because
14898 				 * we have already checked that the
14899 				 * number of bytes ack'ed should be
14900 				 * smaller than or equal to what we
14901 				 * have sent so far (it is the
14902 				 * acceptability check of the ACK).
14903 				 * We can only get here if the send
14904 				 * queue is corrupted.
14905 				 *
14906 				 * Terminate the connection and
14907 				 * panic the system.  It is better
14908 				 * for us to panic instead of
14909 				 * continuing to avoid other disaster.
14910 				 */
14911 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14912 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14913 				panic("Memory corruption "
14914 				    "detected for connection %s.",
14915 				    tcp_display(tcp, NULL,
14916 				    DISP_ADDR_AND_PORT));
14917 				/*NOTREACHED*/
14918 			}
14919 			goto pre_swnd_update;
14920 		}
14921 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14922 	}
14923 	if (tcp->tcp_unsent) {
14924 		flags |= TH_XMIT_NEEDED;
14925 	}
14926 pre_swnd_update:
14927 	tcp->tcp_xmit_head = mp1;
14928 swnd_update:
14929 	/*
14930 	 * The following check is different from most other implementations.
14931 	 * For bi-directional transfer, when segments are dropped, the
14932 	 * "normal" check will not accept a window update in those
14933 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14934 	 * segments which are outside receiver's window.  As TCP accepts
14935 	 * the ack in those retransmitted segments, if the window update in
14936 	 * the same segment is not accepted, TCP will incorrectly calculates
14937 	 * that it can send more segments.  This can create a deadlock
14938 	 * with the receiver if its window becomes zero.
14939 	 */
14940 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14941 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14942 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14943 		/*
14944 		 * The criteria for update is:
14945 		 *
14946 		 * 1. the segment acknowledges some data.  Or
14947 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14948 		 * 3. the segment is not old and the advertised window is
14949 		 * larger than the previous advertised window.
14950 		 */
14951 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14952 			flags |= TH_XMIT_NEEDED;
14953 		tcp->tcp_swnd = new_swnd;
14954 		if (new_swnd > tcp->tcp_max_swnd)
14955 			tcp->tcp_max_swnd = new_swnd;
14956 		tcp->tcp_swl1 = seg_seq;
14957 		tcp->tcp_swl2 = seg_ack;
14958 	}
14959 est:
14960 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14961 
14962 		switch (tcp->tcp_state) {
14963 		case TCPS_FIN_WAIT_1:
14964 			if (tcp->tcp_fin_acked) {
14965 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14966 				/*
14967 				 * We implement the non-standard BSD/SunOS
14968 				 * FIN_WAIT_2 flushing algorithm.
14969 				 * If there is no user attached to this
14970 				 * TCP endpoint, then this TCP struct
14971 				 * could hang around forever in FIN_WAIT_2
14972 				 * state if the peer forgets to send us
14973 				 * a FIN.  To prevent this, we wait only
14974 				 * 2*MSL (a convenient time value) for
14975 				 * the FIN to arrive.  If it doesn't show up,
14976 				 * we flush the TCP endpoint.  This algorithm,
14977 				 * though a violation of RFC-793, has worked
14978 				 * for over 10 years in BSD systems.
14979 				 * Note: SunOS 4.x waits 675 seconds before
14980 				 * flushing the FIN_WAIT_2 connection.
14981 				 */
14982 				TCP_TIMER_RESTART(tcp,
14983 				    tcps->tcps_fin_wait_2_flush_interval);
14984 			}
14985 			break;
14986 		case TCPS_FIN_WAIT_2:
14987 			break;	/* Shutdown hook? */
14988 		case TCPS_LAST_ACK:
14989 			freemsg(mp);
14990 			if (tcp->tcp_fin_acked) {
14991 				(void) tcp_clean_death(tcp, 0, 19);
14992 				return;
14993 			}
14994 			goto xmit_check;
14995 		case TCPS_CLOSING:
14996 			if (tcp->tcp_fin_acked) {
14997 				tcp->tcp_state = TCPS_TIME_WAIT;
14998 				/*
14999 				 * Unconditionally clear the exclusive binding
15000 				 * bit so this TIME-WAIT connection won't
15001 				 * interfere with new ones.
15002 				 */
15003 				tcp->tcp_exclbind = 0;
15004 				if (!TCP_IS_DETACHED(tcp)) {
15005 					TCP_TIMER_RESTART(tcp,
15006 					    tcps->tcps_time_wait_interval);
15007 				} else {
15008 					tcp_time_wait_append(tcp);
15009 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15010 				}
15011 			}
15012 			/*FALLTHRU*/
15013 		case TCPS_CLOSE_WAIT:
15014 			freemsg(mp);
15015 			goto xmit_check;
15016 		default:
15017 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
15018 			break;
15019 		}
15020 	}
15021 	if (flags & TH_FIN) {
15022 		/* Make sure we ack the fin */
15023 		flags |= TH_ACK_NEEDED;
15024 		if (!tcp->tcp_fin_rcvd) {
15025 			tcp->tcp_fin_rcvd = B_TRUE;
15026 			tcp->tcp_rnxt++;
15027 			tcph = tcp->tcp_tcph;
15028 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15029 
15030 			/*
15031 			 * Generate the ordrel_ind at the end unless we
15032 			 * are an eager guy.
15033 			 * In the eager case tcp_rsrv will do this when run
15034 			 * after tcp_accept is done.
15035 			 */
15036 			if (tcp->tcp_listener == NULL &&
15037 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
15038 				flags |= TH_ORDREL_NEEDED;
15039 			switch (tcp->tcp_state) {
15040 			case TCPS_SYN_RCVD:
15041 			case TCPS_ESTABLISHED:
15042 				tcp->tcp_state = TCPS_CLOSE_WAIT;
15043 				/* Keepalive? */
15044 				break;
15045 			case TCPS_FIN_WAIT_1:
15046 				if (!tcp->tcp_fin_acked) {
15047 					tcp->tcp_state = TCPS_CLOSING;
15048 					break;
15049 				}
15050 				/* FALLTHRU */
15051 			case TCPS_FIN_WAIT_2:
15052 				tcp->tcp_state = TCPS_TIME_WAIT;
15053 				/*
15054 				 * Unconditionally clear the exclusive binding
15055 				 * bit so this TIME-WAIT connection won't
15056 				 * interfere with new ones.
15057 				 */
15058 				tcp->tcp_exclbind = 0;
15059 				if (!TCP_IS_DETACHED(tcp)) {
15060 					TCP_TIMER_RESTART(tcp,
15061 					    tcps->tcps_time_wait_interval);
15062 				} else {
15063 					tcp_time_wait_append(tcp);
15064 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15065 				}
15066 				if (seg_len) {
15067 					/*
15068 					 * implies data piggybacked on FIN.
15069 					 * break to handle data.
15070 					 */
15071 					break;
15072 				}
15073 				freemsg(mp);
15074 				goto ack_check;
15075 			}
15076 		}
15077 	}
15078 	if (mp == NULL)
15079 		goto xmit_check;
15080 	if (seg_len == 0) {
15081 		freemsg(mp);
15082 		goto xmit_check;
15083 	}
15084 	if (mp->b_rptr == mp->b_wptr) {
15085 		/*
15086 		 * The header has been consumed, so we remove the
15087 		 * zero-length mblk here.
15088 		 */
15089 		mp1 = mp;
15090 		mp = mp->b_cont;
15091 		freeb(mp1);
15092 	}
15093 	tcph = tcp->tcp_tcph;
15094 	tcp->tcp_rack_cnt++;
15095 	{
15096 		uint32_t cur_max;
15097 
15098 		cur_max = tcp->tcp_rack_cur_max;
15099 		if (tcp->tcp_rack_cnt >= cur_max) {
15100 			/*
15101 			 * We have more unacked data than we should - send
15102 			 * an ACK now.
15103 			 */
15104 			flags |= TH_ACK_NEEDED;
15105 			cur_max++;
15106 			if (cur_max > tcp->tcp_rack_abs_max)
15107 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15108 			else
15109 				tcp->tcp_rack_cur_max = cur_max;
15110 		} else if (TCP_IS_DETACHED(tcp)) {
15111 			/* We don't have an ACK timer for detached TCP. */
15112 			flags |= TH_ACK_NEEDED;
15113 		} else if (seg_len < mss) {
15114 			/*
15115 			 * If we get a segment that is less than an mss, and we
15116 			 * already have unacknowledged data, and the amount
15117 			 * unacknowledged is not a multiple of mss, then we
15118 			 * better generate an ACK now.  Otherwise, this may be
15119 			 * the tail piece of a transaction, and we would rather
15120 			 * wait for the response.
15121 			 */
15122 			uint32_t udif;
15123 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15124 			    (uintptr_t)INT_MAX);
15125 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15126 			if (udif && (udif % mss))
15127 				flags |= TH_ACK_NEEDED;
15128 			else
15129 				flags |= TH_ACK_TIMER_NEEDED;
15130 		} else {
15131 			/* Start delayed ack timer */
15132 			flags |= TH_ACK_TIMER_NEEDED;
15133 		}
15134 	}
15135 	tcp->tcp_rnxt += seg_len;
15136 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15137 
15138 	/* Update SACK list */
15139 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15140 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15141 		    &(tcp->tcp_num_sack_blk));
15142 	}
15143 
15144 	if (tcp->tcp_urp_mp) {
15145 		tcp->tcp_urp_mp->b_cont = mp;
15146 		mp = tcp->tcp_urp_mp;
15147 		tcp->tcp_urp_mp = NULL;
15148 		/* Ready for a new signal. */
15149 		tcp->tcp_urp_last_valid = B_FALSE;
15150 #ifdef DEBUG
15151 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15152 		    "tcp_rput: sending exdata_ind %s",
15153 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15154 #endif /* DEBUG */
15155 	}
15156 
15157 	/*
15158 	 * Check for ancillary data changes compared to last segment.
15159 	 */
15160 	if (tcp->tcp_ipv6_recvancillary != 0) {
15161 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15162 		if (mp == NULL)
15163 			return;
15164 	}
15165 
15166 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15167 		/*
15168 		 * Side queue inbound data until the accept happens.
15169 		 * tcp_accept/tcp_rput drains this when the accept happens.
15170 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15171 		 * T_EXDATA_IND) it is queued on b_next.
15172 		 * XXX Make urgent data use this. Requires:
15173 		 *	Removing tcp_listener check for TH_URG
15174 		 *	Making M_PCPROTO and MARK messages skip the eager case
15175 		 */
15176 
15177 		if (tcp->tcp_kssl_pending) {
15178 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15179 			    mblk_t *, mp);
15180 			tcp_kssl_input(tcp, mp);
15181 		} else {
15182 			tcp_rcv_enqueue(tcp, mp, seg_len);
15183 		}
15184 	} else {
15185 		sodirect_t	*sodp = tcp->tcp_sodirect;
15186 
15187 		/*
15188 		 * If an sodirect connection and an enabled sodirect_t then
15189 		 * sodp will be set to point to the tcp_t/sonode_t shared
15190 		 * sodirect_t and the sodirect_t's lock will be held.
15191 		 */
15192 		if (sodp != NULL) {
15193 			mutex_enter(sodp->sod_lockp);
15194 			if (!(sodp->sod_state & SOD_ENABLED) ||
15195 			    (tcp->tcp_kssl_ctx != NULL &&
15196 			    DB_TYPE(mp) == M_DATA)) {
15197 				mutex_exit(sodp->sod_lockp);
15198 				sodp = NULL;
15199 			}
15200 		}
15201 		if (mp->b_datap->db_type != M_DATA ||
15202 		    (flags & TH_MARKNEXT_NEEDED)) {
15203 			if (sodp != NULL) {
15204 				if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15205 					sodp->sod_uioa.uioa_state &= UIOA_CLR;
15206 					sodp->sod_uioa.uioa_state |= UIOA_FINI;
15207 				}
15208 				if (!SOD_QEMPTY(sodp) &&
15209 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15210 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15211 					/* sod_wakeup() did the mutex_exit() */
15212 				} else {
15213 					mutex_exit(sodp->sod_lockp);
15214 				}
15215 			} else if (tcp->tcp_rcv_list != NULL) {
15216 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15217 			}
15218 			ASSERT(tcp->tcp_rcv_list == NULL ||
15219 			    tcp->tcp_fused_sigurg);
15220 
15221 			if (flags & TH_MARKNEXT_NEEDED) {
15222 #ifdef DEBUG
15223 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15224 				    "tcp_rput: sending MSGMARKNEXT %s",
15225 				    tcp_display(tcp, NULL,
15226 				    DISP_PORT_ONLY));
15227 #endif /* DEBUG */
15228 				mp->b_flag |= MSGMARKNEXT;
15229 				flags &= ~TH_MARKNEXT_NEEDED;
15230 			}
15231 
15232 			/* Does this need SSL processing first? */
15233 			if ((tcp->tcp_kssl_ctx != NULL) &&
15234 			    (DB_TYPE(mp) == M_DATA)) {
15235 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15236 				    mblk_t *, mp);
15237 				tcp_kssl_input(tcp, mp);
15238 			} else {
15239 				putnext(tcp->tcp_rq, mp);
15240 				if (!canputnext(tcp->tcp_rq))
15241 					tcp->tcp_rwnd -= seg_len;
15242 			}
15243 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15244 		    (DB_TYPE(mp) == M_DATA)) {
15245 			/* Do SSL processing first */
15246 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2,
15247 			    mblk_t *, mp);
15248 			tcp_kssl_input(tcp, mp);
15249 		} else if (sodp != NULL) {
15250 			/*
15251 			 * Sodirect so all mblk_t's are queued on the
15252 			 * socket directly, check for wakeup of blocked
15253 			 * reader (if any), and last if flow-controled.
15254 			 */
15255 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15256 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15257 			    (flags & (TH_PUSH|TH_FIN))) {
15258 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15259 				/* sod_wakeup() did the mutex_exit() */
15260 			} else {
15261 				if (SOD_QFULL(sodp)) {
15262 					/* Q is full, need backenable */
15263 					SOD_QSETBE(sodp);
15264 				}
15265 				mutex_exit(sodp->sod_lockp);
15266 			}
15267 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15268 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
15269 			if (tcp->tcp_rcv_list != NULL) {
15270 				/*
15271 				 * Enqueue the new segment first and then
15272 				 * call tcp_rcv_drain() to send all data
15273 				 * up.  The other way to do this is to
15274 				 * send all queued data up and then call
15275 				 * putnext() to send the new segment up.
15276 				 * This way can remove the else part later
15277 				 * on.
15278 				 *
15279 				 * We don't this to avoid one more call to
15280 				 * canputnext() as tcp_rcv_drain() needs to
15281 				 * call canputnext().
15282 				 */
15283 				tcp_rcv_enqueue(tcp, mp, seg_len);
15284 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15285 			} else {
15286 				putnext(tcp->tcp_rq, mp);
15287 				if (!canputnext(tcp->tcp_rq))
15288 					tcp->tcp_rwnd -= seg_len;
15289 			}
15290 		} else {
15291 			/*
15292 			 * Enqueue all packets when processing an mblk
15293 			 * from the co queue and also enqueue normal packets.
15294 			 */
15295 			tcp_rcv_enqueue(tcp, mp, seg_len);
15296 		}
15297 		/*
15298 		 * Make sure the timer is running if we have data waiting
15299 		 * for a push bit. This provides resiliency against
15300 		 * implementations that do not correctly generate push bits.
15301 		 *
15302 		 * Note, for sodirect if Q isn't empty and there's not a
15303 		 * pending wakeup then we need a timer. Also note that sodp
15304 		 * is assumed to be still valid after exit()ing the sod_lockp
15305 		 * above and while the SOD state can change it can only change
15306 		 * such that the Q is empty now even though data was added
15307 		 * above.
15308 		 */
15309 		if (((sodp != NULL && !SOD_QEMPTY(sodp) &&
15310 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15311 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15312 		    tcp->tcp_push_tid == 0) {
15313 			/*
15314 			 * The connection may be closed at this point, so don't
15315 			 * do anything for a detached tcp.
15316 			 */
15317 			if (!TCP_IS_DETACHED(tcp))
15318 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15319 				    tcp_push_timer,
15320 				    MSEC_TO_TICK(
15321 				    tcps->tcps_push_timer_interval));
15322 		}
15323 	}
15324 
15325 xmit_check:
15326 	/* Is there anything left to do? */
15327 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15328 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15329 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15330 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15331 		goto done;
15332 
15333 	/* Any transmit work to do and a non-zero window? */
15334 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15335 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15336 		if (flags & TH_REXMIT_NEEDED) {
15337 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15338 
15339 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15340 			if (snd_size > mss)
15341 				snd_size = mss;
15342 			if (snd_size > tcp->tcp_swnd)
15343 				snd_size = tcp->tcp_swnd;
15344 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15345 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15346 			    B_TRUE);
15347 
15348 			if (mp1 != NULL) {
15349 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15350 				tcp->tcp_csuna = tcp->tcp_snxt;
15351 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15352 				UPDATE_MIB(&tcps->tcps_mib,
15353 				    tcpRetransBytes, snd_size);
15354 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15355 			}
15356 		}
15357 		if (flags & TH_NEED_SACK_REXMIT) {
15358 			tcp_sack_rxmit(tcp, &flags);
15359 		}
15360 		/*
15361 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15362 		 * out new segment.  Note that tcp_rexmit should not be
15363 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15364 		 */
15365 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15366 			if (!tcp->tcp_rexmit) {
15367 				tcp_wput_data(tcp, NULL, B_FALSE);
15368 			} else {
15369 				tcp_ss_rexmit(tcp);
15370 			}
15371 		}
15372 		/*
15373 		 * Adjust tcp_cwnd back to normal value after sending
15374 		 * new data segments.
15375 		 */
15376 		if (flags & TH_LIMIT_XMIT) {
15377 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15378 			/*
15379 			 * This will restart the timer.  Restarting the
15380 			 * timer is used to avoid a timeout before the
15381 			 * limited transmitted segment's ACK gets back.
15382 			 */
15383 			if (tcp->tcp_xmit_head != NULL)
15384 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15385 		}
15386 
15387 		/* Anything more to do? */
15388 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15389 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15390 			goto done;
15391 	}
15392 ack_check:
15393 	if (flags & TH_SEND_URP_MARK) {
15394 		ASSERT(tcp->tcp_urp_mark_mp);
15395 		/*
15396 		 * Send up any queued data and then send the mark message
15397 		 */
15398 		sodirect_t *sodp;
15399 
15400 		SOD_PTR_ENTER(tcp, sodp);
15401 
15402 		mp1 = tcp->tcp_urp_mark_mp;
15403 		tcp->tcp_urp_mark_mp = NULL;
15404 		if (sodp != NULL) {
15405 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15406 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15407 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15408 			}
15409 			ASSERT(tcp->tcp_rcv_list == NULL);
15410 
15411 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15412 			/* sod_wakeup() does the mutex_exit() */
15413 		} else if (tcp->tcp_rcv_list != NULL) {
15414 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15415 
15416 			ASSERT(tcp->tcp_rcv_list == NULL ||
15417 			    tcp->tcp_fused_sigurg);
15418 
15419 		}
15420 		putnext(tcp->tcp_rq, mp1);
15421 #ifdef DEBUG
15422 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15423 		    "tcp_rput: sending zero-length %s %s",
15424 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15425 		    "MSGNOTMARKNEXT"),
15426 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15427 #endif /* DEBUG */
15428 		flags &= ~TH_SEND_URP_MARK;
15429 	}
15430 	if (flags & TH_ACK_NEEDED) {
15431 		/*
15432 		 * Time to send an ack for some reason.
15433 		 */
15434 		mp1 = tcp_ack_mp(tcp);
15435 
15436 		if (mp1 != NULL) {
15437 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15438 			BUMP_LOCAL(tcp->tcp_obsegs);
15439 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15440 		}
15441 		if (tcp->tcp_ack_tid != 0) {
15442 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15443 			tcp->tcp_ack_tid = 0;
15444 		}
15445 	}
15446 	if (flags & TH_ACK_TIMER_NEEDED) {
15447 		/*
15448 		 * Arrange for deferred ACK or push wait timeout.
15449 		 * Start timer if it is not already running.
15450 		 */
15451 		if (tcp->tcp_ack_tid == 0) {
15452 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15453 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15454 			    (clock_t)tcps->tcps_local_dack_interval :
15455 			    (clock_t)tcps->tcps_deferred_ack_interval));
15456 		}
15457 	}
15458 	if (flags & TH_ORDREL_NEEDED) {
15459 		/*
15460 		 * Send up the ordrel_ind unless we are an eager guy.
15461 		 * In the eager case tcp_rsrv will do this when run
15462 		 * after tcp_accept is done.
15463 		 */
15464 		sodirect_t *sodp;
15465 
15466 		ASSERT(tcp->tcp_listener == NULL);
15467 
15468 		SOD_PTR_ENTER(tcp, sodp);
15469 		if (sodp != NULL) {
15470 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15471 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15472 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15473 			}
15474 			/* No more sodirect */
15475 			tcp->tcp_sodirect = NULL;
15476 			if (!SOD_QEMPTY(sodp)) {
15477 				/* Mblk(s) to process, notify */
15478 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15479 				/* sod_wakeup() does the mutex_exit() */
15480 			} else {
15481 				/* Nothing to process */
15482 				mutex_exit(sodp->sod_lockp);
15483 			}
15484 		} else if (tcp->tcp_rcv_list != NULL) {
15485 			/*
15486 			 * Push any mblk(s) enqueued from co processing.
15487 			 */
15488 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15489 
15490 			ASSERT(tcp->tcp_rcv_list == NULL ||
15491 			    tcp->tcp_fused_sigurg);
15492 		}
15493 
15494 		if ((mp1 = mi_tpi_ordrel_ind()) != NULL) {
15495 			tcp->tcp_ordrel_done = B_TRUE;
15496 			putnext(tcp->tcp_rq, mp1);
15497 			if (tcp->tcp_deferred_clean_death) {
15498 				/*
15499 				 * tcp_clean_death was deferred
15500 				 * for T_ORDREL_IND - do it now
15501 				 */
15502 				(void) tcp_clean_death(tcp,
15503 				    tcp->tcp_client_errno, 20);
15504 				tcp->tcp_deferred_clean_death =	B_FALSE;
15505 			}
15506 		} else {
15507 			/*
15508 			 * Run the orderly release in the
15509 			 * service routine.
15510 			 */
15511 			qenable(tcp->tcp_rq);
15512 			/*
15513 			 * Caveat(XXX): The machine may be so
15514 			 * overloaded that tcp_rsrv() is not scheduled
15515 			 * until after the endpoint has transitioned
15516 			 * to TCPS_TIME_WAIT
15517 			 * and tcp_time_wait_interval expires. Then
15518 			 * tcp_timer() will blow away state in tcp_t
15519 			 * and T_ORDREL_IND will never be delivered
15520 			 * upstream. Unlikely but potentially
15521 			 * a problem.
15522 			 */
15523 		}
15524 	}
15525 done:
15526 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15527 }
15528 
15529 /*
15530  * This function does PAWS protection check. Returns B_TRUE if the
15531  * segment passes the PAWS test, else returns B_FALSE.
15532  */
15533 boolean_t
15534 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15535 {
15536 	uint8_t	flags;
15537 	int	options;
15538 	uint8_t *up;
15539 
15540 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15541 	/*
15542 	 * If timestamp option is aligned nicely, get values inline,
15543 	 * otherwise call general routine to parse.  Only do that
15544 	 * if timestamp is the only option.
15545 	 */
15546 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15547 	    TCPOPT_REAL_TS_LEN &&
15548 	    OK_32PTR((up = ((uint8_t *)tcph) +
15549 	    TCP_MIN_HEADER_LENGTH)) &&
15550 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15551 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15552 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15553 
15554 		options = TCP_OPT_TSTAMP_PRESENT;
15555 	} else {
15556 		if (tcp->tcp_snd_sack_ok) {
15557 			tcpoptp->tcp = tcp;
15558 		} else {
15559 			tcpoptp->tcp = NULL;
15560 		}
15561 		options = tcp_parse_options(tcph, tcpoptp);
15562 	}
15563 
15564 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15565 		/*
15566 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15567 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15568 		 */
15569 		if ((flags & TH_RST) == 0 &&
15570 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15571 		    tcp->tcp_ts_recent)) {
15572 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15573 			    PAWS_TIMEOUT)) {
15574 				/* This segment is not acceptable. */
15575 				return (B_FALSE);
15576 			} else {
15577 				/*
15578 				 * Connection has been idle for
15579 				 * too long.  Reset the timestamp
15580 				 * and assume the segment is valid.
15581 				 */
15582 				tcp->tcp_ts_recent =
15583 				    tcpoptp->tcp_opt_ts_val;
15584 			}
15585 		}
15586 	} else {
15587 		/*
15588 		 * If we don't get a timestamp on every packet, we
15589 		 * figure we can't really trust 'em, so we stop sending
15590 		 * and parsing them.
15591 		 */
15592 		tcp->tcp_snd_ts_ok = B_FALSE;
15593 
15594 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15595 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15596 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15597 		/*
15598 		 * Adjust the tcp_mss accordingly. We also need to
15599 		 * adjust tcp_cwnd here in accordance with the new mss.
15600 		 * But we avoid doing a slow start here so as to not
15601 		 * to lose on the transfer rate built up so far.
15602 		 */
15603 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15604 		if (tcp->tcp_snd_sack_ok) {
15605 			ASSERT(tcp->tcp_sack_info != NULL);
15606 			tcp->tcp_max_sack_blk = 4;
15607 		}
15608 	}
15609 	return (B_TRUE);
15610 }
15611 
15612 /*
15613  * Attach ancillary data to a received TCP segments for the
15614  * ancillary pieces requested by the application that are
15615  * different than they were in the previous data segment.
15616  *
15617  * Save the "current" values once memory allocation is ok so that
15618  * when memory allocation fails we can just wait for the next data segment.
15619  */
15620 static mblk_t *
15621 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15622 {
15623 	struct T_optdata_ind *todi;
15624 	int optlen;
15625 	uchar_t *optptr;
15626 	struct T_opthdr *toh;
15627 	uint_t addflag;	/* Which pieces to add */
15628 	mblk_t *mp1;
15629 
15630 	optlen = 0;
15631 	addflag = 0;
15632 	/* If app asked for pktinfo and the index has changed ... */
15633 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15634 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15635 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15636 		optlen += sizeof (struct T_opthdr) +
15637 		    sizeof (struct in6_pktinfo);
15638 		addflag |= TCP_IPV6_RECVPKTINFO;
15639 	}
15640 	/* If app asked for hoplimit and it has changed ... */
15641 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15642 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15643 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15644 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15645 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15646 	}
15647 	/* If app asked for tclass and it has changed ... */
15648 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15649 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15650 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15651 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15652 		addflag |= TCP_IPV6_RECVTCLASS;
15653 	}
15654 	/*
15655 	 * If app asked for hopbyhop headers and it has changed ...
15656 	 * For security labels, note that (1) security labels can't change on
15657 	 * a connected socket at all, (2) we're connected to at most one peer,
15658 	 * (3) if anything changes, then it must be some other extra option.
15659 	 */
15660 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15661 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15662 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15663 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15664 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15665 		    tcp->tcp_label_len;
15666 		addflag |= TCP_IPV6_RECVHOPOPTS;
15667 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15668 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15669 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15670 			return (mp);
15671 	}
15672 	/* If app asked for dst headers before routing headers ... */
15673 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15674 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15675 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15676 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15677 		optlen += sizeof (struct T_opthdr) +
15678 		    ipp->ipp_rtdstoptslen;
15679 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15680 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15681 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15682 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15683 			return (mp);
15684 	}
15685 	/* If app asked for routing headers and it has changed ... */
15686 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15687 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15688 	    (ipp->ipp_fields & IPPF_RTHDR),
15689 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15690 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15691 		addflag |= TCP_IPV6_RECVRTHDR;
15692 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15693 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15694 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15695 			return (mp);
15696 	}
15697 	/* If app asked for dest headers and it has changed ... */
15698 	if ((tcp->tcp_ipv6_recvancillary &
15699 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15700 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15701 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15702 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15703 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15704 		addflag |= TCP_IPV6_RECVDSTOPTS;
15705 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15706 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15707 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15708 			return (mp);
15709 	}
15710 
15711 	if (optlen == 0) {
15712 		/* Nothing to add */
15713 		return (mp);
15714 	}
15715 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15716 	if (mp1 == NULL) {
15717 		/*
15718 		 * Defer sending ancillary data until the next TCP segment
15719 		 * arrives.
15720 		 */
15721 		return (mp);
15722 	}
15723 	mp1->b_cont = mp;
15724 	mp = mp1;
15725 	mp->b_wptr += sizeof (*todi) + optlen;
15726 	mp->b_datap->db_type = M_PROTO;
15727 	todi = (struct T_optdata_ind *)mp->b_rptr;
15728 	todi->PRIM_type = T_OPTDATA_IND;
15729 	todi->DATA_flag = 1;	/* MORE data */
15730 	todi->OPT_length = optlen;
15731 	todi->OPT_offset = sizeof (*todi);
15732 	optptr = (uchar_t *)&todi[1];
15733 	/*
15734 	 * If app asked for pktinfo and the index has changed ...
15735 	 * Note that the local address never changes for the connection.
15736 	 */
15737 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15738 		struct in6_pktinfo *pkti;
15739 
15740 		toh = (struct T_opthdr *)optptr;
15741 		toh->level = IPPROTO_IPV6;
15742 		toh->name = IPV6_PKTINFO;
15743 		toh->len = sizeof (*toh) + sizeof (*pkti);
15744 		toh->status = 0;
15745 		optptr += sizeof (*toh);
15746 		pkti = (struct in6_pktinfo *)optptr;
15747 		if (tcp->tcp_ipversion == IPV6_VERSION)
15748 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15749 		else
15750 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15751 			    &pkti->ipi6_addr);
15752 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15753 		optptr += sizeof (*pkti);
15754 		ASSERT(OK_32PTR(optptr));
15755 		/* Save as "last" value */
15756 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15757 	}
15758 	/* If app asked for hoplimit and it has changed ... */
15759 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15760 		toh = (struct T_opthdr *)optptr;
15761 		toh->level = IPPROTO_IPV6;
15762 		toh->name = IPV6_HOPLIMIT;
15763 		toh->len = sizeof (*toh) + sizeof (uint_t);
15764 		toh->status = 0;
15765 		optptr += sizeof (*toh);
15766 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15767 		optptr += sizeof (uint_t);
15768 		ASSERT(OK_32PTR(optptr));
15769 		/* Save as "last" value */
15770 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15771 	}
15772 	/* If app asked for tclass and it has changed ... */
15773 	if (addflag & TCP_IPV6_RECVTCLASS) {
15774 		toh = (struct T_opthdr *)optptr;
15775 		toh->level = IPPROTO_IPV6;
15776 		toh->name = IPV6_TCLASS;
15777 		toh->len = sizeof (*toh) + sizeof (uint_t);
15778 		toh->status = 0;
15779 		optptr += sizeof (*toh);
15780 		*(uint_t *)optptr = ipp->ipp_tclass;
15781 		optptr += sizeof (uint_t);
15782 		ASSERT(OK_32PTR(optptr));
15783 		/* Save as "last" value */
15784 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15785 	}
15786 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15787 		toh = (struct T_opthdr *)optptr;
15788 		toh->level = IPPROTO_IPV6;
15789 		toh->name = IPV6_HOPOPTS;
15790 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15791 		    tcp->tcp_label_len;
15792 		toh->status = 0;
15793 		optptr += sizeof (*toh);
15794 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15795 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15796 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15797 		ASSERT(OK_32PTR(optptr));
15798 		/* Save as last value */
15799 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15800 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15801 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15802 	}
15803 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15804 		toh = (struct T_opthdr *)optptr;
15805 		toh->level = IPPROTO_IPV6;
15806 		toh->name = IPV6_RTHDRDSTOPTS;
15807 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15808 		toh->status = 0;
15809 		optptr += sizeof (*toh);
15810 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15811 		optptr += ipp->ipp_rtdstoptslen;
15812 		ASSERT(OK_32PTR(optptr));
15813 		/* Save as last value */
15814 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15815 		    &tcp->tcp_rtdstoptslen,
15816 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15817 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15818 	}
15819 	if (addflag & TCP_IPV6_RECVRTHDR) {
15820 		toh = (struct T_opthdr *)optptr;
15821 		toh->level = IPPROTO_IPV6;
15822 		toh->name = IPV6_RTHDR;
15823 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15824 		toh->status = 0;
15825 		optptr += sizeof (*toh);
15826 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15827 		optptr += ipp->ipp_rthdrlen;
15828 		ASSERT(OK_32PTR(optptr));
15829 		/* Save as last value */
15830 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15831 		    (ipp->ipp_fields & IPPF_RTHDR),
15832 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15833 	}
15834 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15835 		toh = (struct T_opthdr *)optptr;
15836 		toh->level = IPPROTO_IPV6;
15837 		toh->name = IPV6_DSTOPTS;
15838 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15839 		toh->status = 0;
15840 		optptr += sizeof (*toh);
15841 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15842 		optptr += ipp->ipp_dstoptslen;
15843 		ASSERT(OK_32PTR(optptr));
15844 		/* Save as last value */
15845 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15846 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15847 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15848 	}
15849 	ASSERT(optptr == mp->b_wptr);
15850 	return (mp);
15851 }
15852 
15853 
15854 /*
15855  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15856  * or a "bad" IRE detected by tcp_adapt_ire.
15857  * We can't tell if the failure was due to the laddr or the faddr
15858  * thus we clear out all addresses and ports.
15859  */
15860 static void
15861 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15862 {
15863 	queue_t	*q = tcp->tcp_rq;
15864 	tcph_t	*tcph;
15865 	struct T_error_ack *tea;
15866 	conn_t	*connp = tcp->tcp_connp;
15867 
15868 
15869 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15870 
15871 	if (mp->b_cont) {
15872 		freemsg(mp->b_cont);
15873 		mp->b_cont = NULL;
15874 	}
15875 	tea = (struct T_error_ack *)mp->b_rptr;
15876 	switch (tea->PRIM_type) {
15877 	case T_BIND_ACK:
15878 		/*
15879 		 * Need to unbind with classifier since we were just told that
15880 		 * our bind succeeded.
15881 		 */
15882 		tcp->tcp_hard_bound = B_FALSE;
15883 		tcp->tcp_hard_binding = B_FALSE;
15884 
15885 		ipcl_hash_remove(connp);
15886 		/* Reuse the mblk if possible */
15887 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15888 		    sizeof (*tea));
15889 		mp->b_rptr = mp->b_datap->db_base;
15890 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15891 		tea = (struct T_error_ack *)mp->b_rptr;
15892 		tea->PRIM_type = T_ERROR_ACK;
15893 		tea->TLI_error = TSYSERR;
15894 		tea->UNIX_error = error;
15895 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15896 			tea->ERROR_prim = T_CONN_REQ;
15897 		} else {
15898 			tea->ERROR_prim = O_T_BIND_REQ;
15899 		}
15900 		break;
15901 
15902 	case T_ERROR_ACK:
15903 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15904 			tea->ERROR_prim = T_CONN_REQ;
15905 		break;
15906 	default:
15907 		panic("tcp_bind_failed: unexpected TPI type");
15908 		/*NOTREACHED*/
15909 	}
15910 
15911 	tcp->tcp_state = TCPS_IDLE;
15912 	if (tcp->tcp_ipversion == IPV4_VERSION)
15913 		tcp->tcp_ipha->ipha_src = 0;
15914 	else
15915 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15916 	/*
15917 	 * Copy of the src addr. in tcp_t is needed since
15918 	 * the lookup funcs. can only look at tcp_t
15919 	 */
15920 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15921 
15922 	tcph = tcp->tcp_tcph;
15923 	tcph->th_lport[0] = 0;
15924 	tcph->th_lport[1] = 0;
15925 	tcp_bind_hash_remove(tcp);
15926 	bzero(&connp->u_port, sizeof (connp->u_port));
15927 	/* blow away saved option results if any */
15928 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15929 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15930 
15931 	conn_delete_ire(tcp->tcp_connp, NULL);
15932 	putnext(q, mp);
15933 }
15934 
15935 /*
15936  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15937  * messages.
15938  */
15939 void
15940 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15941 {
15942 	mblk_t	*mp1;
15943 	uchar_t	*rptr = mp->b_rptr;
15944 	queue_t	*q = tcp->tcp_rq;
15945 	struct T_error_ack *tea;
15946 	uint32_t mss;
15947 	mblk_t *syn_mp;
15948 	mblk_t *mdti;
15949 	mblk_t *lsoi;
15950 	int	retval;
15951 	mblk_t *ire_mp;
15952 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15953 
15954 	switch (mp->b_datap->db_type) {
15955 	case M_PROTO:
15956 	case M_PCPROTO:
15957 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15958 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15959 			break;
15960 		tea = (struct T_error_ack *)rptr;
15961 		switch (tea->PRIM_type) {
15962 		case T_BIND_ACK:
15963 			/*
15964 			 * Adapt Multidata information, if any.  The
15965 			 * following tcp_mdt_update routine will free
15966 			 * the message.
15967 			 */
15968 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15969 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15970 				    b_rptr)->mdt_capab, B_TRUE);
15971 				freemsg(mdti);
15972 			}
15973 
15974 			/*
15975 			 * Check to update LSO information with tcp, and
15976 			 * tcp_lso_update routine will free the message.
15977 			 */
15978 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
15979 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
15980 				    b_rptr)->lso_capab);
15981 				freemsg(lsoi);
15982 			}
15983 
15984 			/* Get the IRE, if we had requested for it */
15985 			ire_mp = tcp_ire_mp(mp);
15986 
15987 			if (tcp->tcp_hard_binding) {
15988 				tcp->tcp_hard_binding = B_FALSE;
15989 				tcp->tcp_hard_bound = B_TRUE;
15990 				CL_INET_CONNECT(tcp);
15991 			} else {
15992 				if (ire_mp != NULL)
15993 					freeb(ire_mp);
15994 				goto after_syn_sent;
15995 			}
15996 
15997 			retval = tcp_adapt_ire(tcp, ire_mp);
15998 			if (ire_mp != NULL)
15999 				freeb(ire_mp);
16000 			if (retval == 0) {
16001 				tcp_bind_failed(tcp, mp,
16002 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
16003 				    ENETUNREACH : EADDRNOTAVAIL));
16004 				return;
16005 			}
16006 			/*
16007 			 * Don't let an endpoint connect to itself.
16008 			 * Also checked in tcp_connect() but that
16009 			 * check can't handle the case when the
16010 			 * local IP address is INADDR_ANY.
16011 			 */
16012 			if (tcp->tcp_ipversion == IPV4_VERSION) {
16013 				if ((tcp->tcp_ipha->ipha_dst ==
16014 				    tcp->tcp_ipha->ipha_src) &&
16015 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16016 				    tcp->tcp_tcph->th_fport))) {
16017 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16018 					return;
16019 				}
16020 			} else {
16021 				if (IN6_ARE_ADDR_EQUAL(
16022 				    &tcp->tcp_ip6h->ip6_dst,
16023 				    &tcp->tcp_ip6h->ip6_src) &&
16024 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16025 				    tcp->tcp_tcph->th_fport))) {
16026 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16027 					return;
16028 				}
16029 			}
16030 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
16031 			/*
16032 			 * This should not be possible!  Just for
16033 			 * defensive coding...
16034 			 */
16035 			if (tcp->tcp_state != TCPS_SYN_SENT)
16036 				goto after_syn_sent;
16037 
16038 			if (is_system_labeled() &&
16039 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
16040 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
16041 				return;
16042 			}
16043 
16044 			ASSERT(q == tcp->tcp_rq);
16045 			/*
16046 			 * tcp_adapt_ire() does not adjust
16047 			 * for TCP/IP header length.
16048 			 */
16049 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
16050 
16051 			/*
16052 			 * Just make sure our rwnd is at
16053 			 * least tcp_recv_hiwat_mss * MSS
16054 			 * large, and round up to the nearest
16055 			 * MSS.
16056 			 *
16057 			 * We do the round up here because
16058 			 * we need to get the interface
16059 			 * MTU first before we can do the
16060 			 * round up.
16061 			 */
16062 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
16063 			    tcps->tcps_recv_hiwat_minmss * mss);
16064 			q->q_hiwat = tcp->tcp_rwnd;
16065 			tcp_set_ws_value(tcp);
16066 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
16067 			    tcp->tcp_tcph->th_win);
16068 			if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
16069 				tcp->tcp_snd_ws_ok = B_TRUE;
16070 
16071 			/*
16072 			 * Set tcp_snd_ts_ok to true
16073 			 * so that tcp_xmit_mp will
16074 			 * include the timestamp
16075 			 * option in the SYN segment.
16076 			 */
16077 			if (tcps->tcps_tstamp_always ||
16078 			    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
16079 				tcp->tcp_snd_ts_ok = B_TRUE;
16080 			}
16081 
16082 			/*
16083 			 * tcp_snd_sack_ok can be set in
16084 			 * tcp_adapt_ire() if the sack metric
16085 			 * is set.  So check it here also.
16086 			 */
16087 			if (tcps->tcps_sack_permitted == 2 ||
16088 			    tcp->tcp_snd_sack_ok) {
16089 				if (tcp->tcp_sack_info == NULL) {
16090 					tcp->tcp_sack_info =
16091 					    kmem_cache_alloc(
16092 					    tcp_sack_info_cache,
16093 					    KM_SLEEP);
16094 				}
16095 				tcp->tcp_snd_sack_ok = B_TRUE;
16096 			}
16097 
16098 			/*
16099 			 * Should we use ECN?  Note that the current
16100 			 * default value (SunOS 5.9) of tcp_ecn_permitted
16101 			 * is 1.  The reason for doing this is that there
16102 			 * are equipments out there that will drop ECN
16103 			 * enabled IP packets.  Setting it to 1 avoids
16104 			 * compatibility problems.
16105 			 */
16106 			if (tcps->tcps_ecn_permitted == 2)
16107 				tcp->tcp_ecn_ok = B_TRUE;
16108 
16109 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16110 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
16111 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
16112 			if (syn_mp) {
16113 				cred_t *cr;
16114 				pid_t pid;
16115 
16116 				/*
16117 				 * Obtain the credential from the
16118 				 * thread calling connect(); the credential
16119 				 * lives on in the second mblk which
16120 				 * originated from T_CONN_REQ and is echoed
16121 				 * with the T_BIND_ACK from ip.  If none
16122 				 * can be found, default to the creator
16123 				 * of the socket.
16124 				 */
16125 				if (mp->b_cont == NULL ||
16126 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
16127 					cr = tcp->tcp_cred;
16128 					pid = tcp->tcp_cpid;
16129 				} else {
16130 					pid = DB_CPID(mp->b_cont);
16131 				}
16132 				mblk_setcred(syn_mp, cr);
16133 				DB_CPID(syn_mp) = pid;
16134 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
16135 			}
16136 		after_syn_sent:
16137 			/*
16138 			 * A trailer mblk indicates a waiting client upstream.
16139 			 * We complete here the processing begun in
16140 			 * either tcp_bind() or tcp_connect() by passing
16141 			 * upstream the reply message they supplied.
16142 			 */
16143 			mp1 = mp;
16144 			mp = mp->b_cont;
16145 			freeb(mp1);
16146 			if (mp)
16147 				break;
16148 			return;
16149 		case T_ERROR_ACK:
16150 			if (tcp->tcp_debug) {
16151 				(void) strlog(TCP_MOD_ID, 0, 1,
16152 				    SL_TRACE|SL_ERROR,
16153 				    "tcp_rput_other: case T_ERROR_ACK, "
16154 				    "ERROR_prim == %d",
16155 				    tea->ERROR_prim);
16156 			}
16157 			switch (tea->ERROR_prim) {
16158 			case O_T_BIND_REQ:
16159 			case T_BIND_REQ:
16160 				tcp_bind_failed(tcp, mp,
16161 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
16162 				    ENETUNREACH : EADDRNOTAVAIL));
16163 				return;
16164 			case T_UNBIND_REQ:
16165 				tcp->tcp_hard_binding = B_FALSE;
16166 				tcp->tcp_hard_bound = B_FALSE;
16167 				if (mp->b_cont) {
16168 					freemsg(mp->b_cont);
16169 					mp->b_cont = NULL;
16170 				}
16171 				if (tcp->tcp_unbind_pending)
16172 					tcp->tcp_unbind_pending = 0;
16173 				else {
16174 					/* From tcp_ip_unbind() - free */
16175 					freemsg(mp);
16176 					return;
16177 				}
16178 				break;
16179 			case T_SVR4_OPTMGMT_REQ:
16180 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
16181 					/* T_OPTMGMT_REQ generated by TCP */
16182 					printf("T_SVR4_OPTMGMT_REQ failed "
16183 					    "%d/%d - dropped (cnt %d)\n",
16184 					    tea->TLI_error, tea->UNIX_error,
16185 					    tcp->tcp_drop_opt_ack_cnt);
16186 					freemsg(mp);
16187 					tcp->tcp_drop_opt_ack_cnt--;
16188 					return;
16189 				}
16190 				break;
16191 			}
16192 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
16193 			    tcp->tcp_drop_opt_ack_cnt > 0) {
16194 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
16195 				    "- dropped (cnt %d)\n",
16196 				    tea->TLI_error, tea->UNIX_error,
16197 				    tcp->tcp_drop_opt_ack_cnt);
16198 				freemsg(mp);
16199 				tcp->tcp_drop_opt_ack_cnt--;
16200 				return;
16201 			}
16202 			break;
16203 		case T_OPTMGMT_ACK:
16204 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
16205 				/* T_OPTMGMT_REQ generated by TCP */
16206 				freemsg(mp);
16207 				tcp->tcp_drop_opt_ack_cnt--;
16208 				return;
16209 			}
16210 			break;
16211 		default:
16212 			break;
16213 		}
16214 		break;
16215 	case M_FLUSH:
16216 		if (*rptr & FLUSHR)
16217 			flushq(q, FLUSHDATA);
16218 		break;
16219 	default:
16220 		/* M_CTL will be directly sent to tcp_icmp_error() */
16221 		ASSERT(DB_TYPE(mp) != M_CTL);
16222 		break;
16223 	}
16224 	/*
16225 	 * Make sure we set this bit before sending the ACK for
16226 	 * bind. Otherwise accept could possibly run and free
16227 	 * this tcp struct.
16228 	 */
16229 	putnext(q, mp);
16230 }
16231 
16232 /*
16233  * Called as the result of a qbufcall or a qtimeout to remedy a failure
16234  * to allocate a T_ordrel_ind in tcp_rsrv().  qenable(q) will make
16235  * tcp_rsrv() try again.
16236  */
16237 static void
16238 tcp_ordrel_kick(void *arg)
16239 {
16240 	conn_t 	*connp = (conn_t *)arg;
16241 	tcp_t	*tcp = connp->conn_tcp;
16242 
16243 	tcp->tcp_ordrelid = 0;
16244 	tcp->tcp_timeout = B_FALSE;
16245 	if (!TCP_IS_DETACHED(tcp) && tcp->tcp_rq != NULL &&
16246 	    tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
16247 		qenable(tcp->tcp_rq);
16248 	}
16249 }
16250 
16251 /* ARGSUSED */
16252 static void
16253 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
16254 {
16255 	conn_t	*connp = (conn_t *)arg;
16256 	tcp_t	*tcp = connp->conn_tcp;
16257 	queue_t	*q = tcp->tcp_rq;
16258 	uint_t	thwin;
16259 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16260 	sodirect_t	*sodp;
16261 	boolean_t	fc;
16262 
16263 	freeb(mp);
16264 
16265 	TCP_STAT(tcps, tcp_rsrv_calls);
16266 
16267 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
16268 		return;
16269 	}
16270 
16271 	if (tcp->tcp_fused) {
16272 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16273 
16274 		ASSERT(tcp->tcp_fused);
16275 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
16276 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
16277 		ASSERT(!TCP_IS_DETACHED(tcp));
16278 		ASSERT(tcp->tcp_connp->conn_sqp ==
16279 		    peer_tcp->tcp_connp->conn_sqp);
16280 
16281 		/*
16282 		 * Normally we would not get backenabled in synchronous
16283 		 * streams mode, but in case this happens, we need to plug
16284 		 * synchronous streams during our drain to prevent a race
16285 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
16286 		 */
16287 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
16288 		if (tcp->tcp_rcv_list != NULL)
16289 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
16290 
16291 		if (peer_tcp > tcp) {
16292 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16293 			mutex_enter(&tcp->tcp_non_sq_lock);
16294 		} else {
16295 			mutex_enter(&tcp->tcp_non_sq_lock);
16296 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16297 		}
16298 
16299 		if (peer_tcp->tcp_flow_stopped &&
16300 		    (TCP_UNSENT_BYTES(peer_tcp) <=
16301 		    peer_tcp->tcp_xmit_lowater)) {
16302 			tcp_clrqfull(peer_tcp);
16303 		}
16304 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
16305 		mutex_exit(&tcp->tcp_non_sq_lock);
16306 
16307 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
16308 		TCP_STAT(tcps, tcp_fusion_backenabled);
16309 		return;
16310 	}
16311 
16312 	SOD_PTR_ENTER(tcp, sodp);
16313 	if (sodp != NULL) {
16314 		/* An sodirect connection */
16315 		if (SOD_QFULL(sodp)) {
16316 			/* Flow-controlled, need another back-enable */
16317 			fc = B_TRUE;
16318 			SOD_QSETBE(sodp);
16319 		} else {
16320 			/* Not flow-controlled */
16321 			fc = B_FALSE;
16322 		}
16323 		mutex_exit(sodp->sod_lockp);
16324 	} else if (canputnext(q)) {
16325 		/* STREAMS, not flow-controlled */
16326 		fc = B_FALSE;
16327 	} else {
16328 		/* STREAMS, flow-controlled */
16329 		fc = B_TRUE;
16330 	}
16331 	if (!fc) {
16332 		/* Not flow-controlled, open rwnd */
16333 		tcp->tcp_rwnd = q->q_hiwat;
16334 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16335 		    << tcp->tcp_rcv_ws;
16336 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16337 		/*
16338 		 * Send back a window update immediately if TCP is above
16339 		 * ESTABLISHED state and the increase of the rcv window
16340 		 * that the other side knows is at least 1 MSS after flow
16341 		 * control is lifted.
16342 		 */
16343 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16344 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16345 			tcp_xmit_ctl(NULL, tcp,
16346 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16347 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16348 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
16349 		}
16350 	}
16351 
16352 	/* Handle a failure to allocate a T_ORDREL_IND here */
16353 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
16354 		ASSERT(tcp->tcp_listener == NULL);
16355 
16356 		SOD_PTR_ENTER(tcp, sodp);
16357 		if (sodp != NULL) {
16358 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
16359 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
16360 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
16361 			}
16362 			/* No more sodirect */
16363 			tcp->tcp_sodirect = NULL;
16364 			if (!SOD_QEMPTY(sodp)) {
16365 				/* Notify mblk(s) to process */
16366 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
16367 				/* sod_wakeup() does the mutex_exit() */
16368 			} else {
16369 				/* Nothing to process */
16370 				mutex_exit(sodp->sod_lockp);
16371 			}
16372 		} else if (tcp->tcp_rcv_list != NULL) {
16373 			/*
16374 			 * Push any mblk(s) enqueued from co processing.
16375 			 */
16376 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
16377 			ASSERT(tcp->tcp_rcv_list == NULL ||
16378 			    tcp->tcp_fused_sigurg);
16379 		}
16380 
16381 		mp = mi_tpi_ordrel_ind();
16382 		if (mp) {
16383 			tcp->tcp_ordrel_done = B_TRUE;
16384 			putnext(q, mp);
16385 			if (tcp->tcp_deferred_clean_death) {
16386 				/*
16387 				 * tcp_clean_death was deferred for
16388 				 * T_ORDREL_IND - do it now
16389 				 */
16390 				tcp->tcp_deferred_clean_death = B_FALSE;
16391 				(void) tcp_clean_death(tcp,
16392 				    tcp->tcp_client_errno, 22);
16393 			}
16394 		} else if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16395 			/*
16396 			 * If there isn't already a timer running
16397 			 * start one.  Use a 4 second
16398 			 * timer as a fallback since it can't fail.
16399 			 */
16400 			tcp->tcp_timeout = B_TRUE;
16401 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16402 			    MSEC_TO_TICK(4000));
16403 		}
16404 	}
16405 }
16406 
16407 /*
16408  * The read side service routine is called mostly when we get back-enabled as a
16409  * result of flow control relief.  Since we don't actually queue anything in
16410  * TCP, we have no data to send out of here.  What we do is clear the receive
16411  * window, and send out a window update.
16412  * This routine is also called to drive an orderly release message upstream
16413  * if the attempt in tcp_rput failed.
16414  */
16415 static void
16416 tcp_rsrv(queue_t *q)
16417 {
16418 	conn_t *connp = Q_TO_CONN(q);
16419 	tcp_t	*tcp = connp->conn_tcp;
16420 	mblk_t	*mp;
16421 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16422 
16423 	/* No code does a putq on the read side */
16424 	ASSERT(q->q_first == NULL);
16425 
16426 	/* Nothing to do for the default queue */
16427 	if (q == tcps->tcps_g_q) {
16428 		return;
16429 	}
16430 
16431 	mp = allocb(0, BPRI_HI);
16432 	if (mp == NULL) {
16433 		/*
16434 		 * We are under memory pressure. Return for now and we
16435 		 * we will be called again later.
16436 		 */
16437 		if (!tcp->tcp_timeout && tcp->tcp_ordrelid == 0) {
16438 			/*
16439 			 * If there isn't already a timer running
16440 			 * start one.  Use a 4 second
16441 			 * timer as a fallback since it can't fail.
16442 			 */
16443 			tcp->tcp_timeout = B_TRUE;
16444 			tcp->tcp_ordrelid = TCP_TIMER(tcp, tcp_ordrel_kick,
16445 			    MSEC_TO_TICK(4000));
16446 		}
16447 		return;
16448 	}
16449 	CONN_INC_REF(connp);
16450 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16451 	    SQTAG_TCP_RSRV);
16452 }
16453 
16454 /*
16455  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16456  * We do not allow the receive window to shrink.  After setting rwnd,
16457  * set the flow control hiwat of the stream.
16458  *
16459  * This function is called in 2 cases:
16460  *
16461  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16462  *    connection (passive open) and in tcp_rput_data() for active connect.
16463  *    This is called after tcp_mss_set() when the desired MSS value is known.
16464  *    This makes sure that our window size is a mutiple of the other side's
16465  *    MSS.
16466  * 2) Handling SO_RCVBUF option.
16467  *
16468  * It is ASSUMED that the requested size is a multiple of the current MSS.
16469  *
16470  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16471  * user requests so.
16472  */
16473 static int
16474 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16475 {
16476 	uint32_t	mss = tcp->tcp_mss;
16477 	uint32_t	old_max_rwnd;
16478 	uint32_t	max_transmittable_rwnd;
16479 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16480 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16481 
16482 	if (tcp->tcp_fused) {
16483 		size_t sth_hiwat;
16484 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16485 
16486 		ASSERT(peer_tcp != NULL);
16487 		/*
16488 		 * Record the stream head's high water mark for
16489 		 * this endpoint; this is used for flow-control
16490 		 * purposes in tcp_fuse_output().
16491 		 */
16492 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16493 		if (!tcp_detached)
16494 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
16495 
16496 		/*
16497 		 * In the fusion case, the maxpsz stream head value of
16498 		 * our peer is set according to its send buffer size
16499 		 * and our receive buffer size; since the latter may
16500 		 * have changed we need to update the peer's maxpsz.
16501 		 */
16502 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16503 		return (rwnd);
16504 	}
16505 
16506 	if (tcp_detached)
16507 		old_max_rwnd = tcp->tcp_rwnd;
16508 	else
16509 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16510 
16511 	/*
16512 	 * Insist on a receive window that is at least
16513 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16514 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16515 	 * and delayed acknowledgement.
16516 	 */
16517 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16518 
16519 	/*
16520 	 * If window size info has already been exchanged, TCP should not
16521 	 * shrink the window.  Shrinking window is doable if done carefully.
16522 	 * We may add that support later.  But so far there is not a real
16523 	 * need to do that.
16524 	 */
16525 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16526 		/* MSS may have changed, do a round up again. */
16527 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16528 	}
16529 
16530 	/*
16531 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16532 	 * can be applied even before the window scale option is decided.
16533 	 */
16534 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16535 	if (rwnd > max_transmittable_rwnd) {
16536 		rwnd = max_transmittable_rwnd -
16537 		    (max_transmittable_rwnd % mss);
16538 		if (rwnd < mss)
16539 			rwnd = max_transmittable_rwnd;
16540 		/*
16541 		 * If we're over the limit we may have to back down tcp_rwnd.
16542 		 * The increment below won't work for us. So we set all three
16543 		 * here and the increment below will have no effect.
16544 		 */
16545 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16546 	}
16547 	if (tcp->tcp_localnet) {
16548 		tcp->tcp_rack_abs_max =
16549 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16550 	} else {
16551 		/*
16552 		 * For a remote host on a different subnet (through a router),
16553 		 * we ack every other packet to be conforming to RFC1122.
16554 		 * tcp_deferred_acks_max is default to 2.
16555 		 */
16556 		tcp->tcp_rack_abs_max =
16557 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16558 	}
16559 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16560 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16561 	else
16562 		tcp->tcp_rack_cur_max = 0;
16563 	/*
16564 	 * Increment the current rwnd by the amount the maximum grew (we
16565 	 * can not overwrite it since we might be in the middle of a
16566 	 * connection.)
16567 	 */
16568 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16569 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16570 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16571 		tcp->tcp_cwnd_max = rwnd;
16572 
16573 	if (tcp_detached)
16574 		return (rwnd);
16575 	/*
16576 	 * We set the maximum receive window into rq->q_hiwat.
16577 	 * This is not actually used for flow control.
16578 	 */
16579 	tcp->tcp_rq->q_hiwat = rwnd;
16580 	/*
16581 	 * Set the Stream head high water mark. This doesn't have to be
16582 	 * here, since we are simply using default values, but we would
16583 	 * prefer to choose these values algorithmically, with a likely
16584 	 * relationship to rwnd.
16585 	 */
16586 	(void) mi_set_sth_hiwat(tcp->tcp_rq,
16587 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16588 	return (rwnd);
16589 }
16590 
16591 /*
16592  * Return SNMP stuff in buffer in mpdata.
16593  */
16594 mblk_t *
16595 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16596 {
16597 	mblk_t			*mpdata;
16598 	mblk_t			*mp_conn_ctl = NULL;
16599 	mblk_t			*mp_conn_tail;
16600 	mblk_t			*mp_attr_ctl = NULL;
16601 	mblk_t			*mp_attr_tail;
16602 	mblk_t			*mp6_conn_ctl = NULL;
16603 	mblk_t			*mp6_conn_tail;
16604 	mblk_t			*mp6_attr_ctl = NULL;
16605 	mblk_t			*mp6_attr_tail;
16606 	struct opthdr		*optp;
16607 	mib2_tcpConnEntry_t	tce;
16608 	mib2_tcp6ConnEntry_t	tce6;
16609 	mib2_transportMLPEntry_t mlp;
16610 	connf_t			*connfp;
16611 	int			i;
16612 	boolean_t 		ispriv;
16613 	zoneid_t 		zoneid;
16614 	int			v4_conn_idx;
16615 	int			v6_conn_idx;
16616 	conn_t			*connp = Q_TO_CONN(q);
16617 	tcp_stack_t		*tcps;
16618 	ip_stack_t		*ipst;
16619 	mblk_t			*mp2ctl;
16620 
16621 	/*
16622 	 * make a copy of the original message
16623 	 */
16624 	mp2ctl = copymsg(mpctl);
16625 
16626 	if (mpctl == NULL ||
16627 	    (mpdata = mpctl->b_cont) == NULL ||
16628 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16629 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16630 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16631 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16632 		freemsg(mp_conn_ctl);
16633 		freemsg(mp_attr_ctl);
16634 		freemsg(mp6_conn_ctl);
16635 		freemsg(mp6_attr_ctl);
16636 		freemsg(mpctl);
16637 		freemsg(mp2ctl);
16638 		return (NULL);
16639 	}
16640 
16641 	ipst = connp->conn_netstack->netstack_ip;
16642 	tcps = connp->conn_netstack->netstack_tcp;
16643 
16644 	/* build table of connections -- need count in fixed part */
16645 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16646 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16647 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16648 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16649 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16650 
16651 	ispriv =
16652 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16653 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16654 
16655 	v4_conn_idx = v6_conn_idx = 0;
16656 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16657 
16658 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16659 		ipst = tcps->tcps_netstack->netstack_ip;
16660 
16661 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16662 
16663 		connp = NULL;
16664 
16665 		while ((connp =
16666 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16667 			tcp_t *tcp;
16668 			boolean_t needattr;
16669 
16670 			if (connp->conn_zoneid != zoneid)
16671 				continue;	/* not in this zone */
16672 
16673 			tcp = connp->conn_tcp;
16674 			UPDATE_MIB(&tcps->tcps_mib,
16675 			    tcpHCInSegs, tcp->tcp_ibsegs);
16676 			tcp->tcp_ibsegs = 0;
16677 			UPDATE_MIB(&tcps->tcps_mib,
16678 			    tcpHCOutSegs, tcp->tcp_obsegs);
16679 			tcp->tcp_obsegs = 0;
16680 
16681 			tce6.tcp6ConnState = tce.tcpConnState =
16682 			    tcp_snmp_state(tcp);
16683 			if (tce.tcpConnState == MIB2_TCP_established ||
16684 			    tce.tcpConnState == MIB2_TCP_closeWait)
16685 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16686 
16687 			needattr = B_FALSE;
16688 			bzero(&mlp, sizeof (mlp));
16689 			if (connp->conn_mlp_type != mlptSingle) {
16690 				if (connp->conn_mlp_type == mlptShared ||
16691 				    connp->conn_mlp_type == mlptBoth)
16692 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16693 				if (connp->conn_mlp_type == mlptPrivate ||
16694 				    connp->conn_mlp_type == mlptBoth)
16695 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16696 				needattr = B_TRUE;
16697 			}
16698 			if (connp->conn_peercred != NULL) {
16699 				ts_label_t *tsl;
16700 
16701 				tsl = crgetlabel(connp->conn_peercred);
16702 				mlp.tme_doi = label2doi(tsl);
16703 				mlp.tme_label = *label2bslabel(tsl);
16704 				needattr = B_TRUE;
16705 			}
16706 
16707 			/* Create a message to report on IPv6 entries */
16708 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16709 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16710 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16711 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16712 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16713 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16714 			/* Don't want just anybody seeing these... */
16715 			if (ispriv) {
16716 				tce6.tcp6ConnEntryInfo.ce_snxt =
16717 				    tcp->tcp_snxt;
16718 				tce6.tcp6ConnEntryInfo.ce_suna =
16719 				    tcp->tcp_suna;
16720 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16721 				    tcp->tcp_rnxt;
16722 				tce6.tcp6ConnEntryInfo.ce_rack =
16723 				    tcp->tcp_rack;
16724 			} else {
16725 				/*
16726 				 * Netstat, unfortunately, uses this to
16727 				 * get send/receive queue sizes.  How to fix?
16728 				 * Why not compute the difference only?
16729 				 */
16730 				tce6.tcp6ConnEntryInfo.ce_snxt =
16731 				    tcp->tcp_snxt - tcp->tcp_suna;
16732 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16733 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16734 				    tcp->tcp_rnxt - tcp->tcp_rack;
16735 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16736 			}
16737 
16738 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16739 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16740 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16741 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16742 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16743 
16744 			tce6.tcp6ConnCreationProcess =
16745 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16746 			    tcp->tcp_cpid;
16747 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16748 
16749 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16750 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16751 
16752 			mlp.tme_connidx = v6_conn_idx++;
16753 			if (needattr)
16754 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16755 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16756 			}
16757 			/*
16758 			 * Create an IPv4 table entry for IPv4 entries and also
16759 			 * for IPv6 entries which are bound to in6addr_any
16760 			 * but don't have IPV6_V6ONLY set.
16761 			 * (i.e. anything an IPv4 peer could connect to)
16762 			 */
16763 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16764 			    (tcp->tcp_state <= TCPS_LISTEN &&
16765 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16766 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16767 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16768 					tce.tcpConnRemAddress = INADDR_ANY;
16769 					tce.tcpConnLocalAddress = INADDR_ANY;
16770 				} else {
16771 					tce.tcpConnRemAddress =
16772 					    tcp->tcp_remote;
16773 					tce.tcpConnLocalAddress =
16774 					    tcp->tcp_ip_src;
16775 				}
16776 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16777 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16778 				/* Don't want just anybody seeing these... */
16779 				if (ispriv) {
16780 					tce.tcpConnEntryInfo.ce_snxt =
16781 					    tcp->tcp_snxt;
16782 					tce.tcpConnEntryInfo.ce_suna =
16783 					    tcp->tcp_suna;
16784 					tce.tcpConnEntryInfo.ce_rnxt =
16785 					    tcp->tcp_rnxt;
16786 					tce.tcpConnEntryInfo.ce_rack =
16787 					    tcp->tcp_rack;
16788 				} else {
16789 					/*
16790 					 * Netstat, unfortunately, uses this to
16791 					 * get send/receive queue sizes.  How
16792 					 * to fix?
16793 					 * Why not compute the difference only?
16794 					 */
16795 					tce.tcpConnEntryInfo.ce_snxt =
16796 					    tcp->tcp_snxt - tcp->tcp_suna;
16797 					tce.tcpConnEntryInfo.ce_suna = 0;
16798 					tce.tcpConnEntryInfo.ce_rnxt =
16799 					    tcp->tcp_rnxt - tcp->tcp_rack;
16800 					tce.tcpConnEntryInfo.ce_rack = 0;
16801 				}
16802 
16803 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16804 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16805 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16806 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16807 				tce.tcpConnEntryInfo.ce_state =
16808 				    tcp->tcp_state;
16809 
16810 				tce.tcpConnCreationProcess =
16811 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16812 				    tcp->tcp_cpid;
16813 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16814 
16815 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16816 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16817 
16818 				mlp.tme_connidx = v4_conn_idx++;
16819 				if (needattr)
16820 					(void) snmp_append_data2(
16821 					    mp_attr_ctl->b_cont,
16822 					    &mp_attr_tail, (char *)&mlp,
16823 					    sizeof (mlp));
16824 			}
16825 		}
16826 	}
16827 
16828 	/* fixed length structure for IPv4 and IPv6 counters */
16829 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16830 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16831 	    sizeof (mib2_tcp6ConnEntry_t));
16832 	/* synchronize 32- and 64-bit counters */
16833 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16834 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16835 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16836 	optp->level = MIB2_TCP;
16837 	optp->name = 0;
16838 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16839 	    sizeof (tcps->tcps_mib));
16840 	optp->len = msgdsize(mpdata);
16841 	qreply(q, mpctl);
16842 
16843 	/* table of connections... */
16844 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16845 	    sizeof (struct T_optmgmt_ack)];
16846 	optp->level = MIB2_TCP;
16847 	optp->name = MIB2_TCP_CONN;
16848 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16849 	qreply(q, mp_conn_ctl);
16850 
16851 	/* table of MLP attributes... */
16852 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16853 	    sizeof (struct T_optmgmt_ack)];
16854 	optp->level = MIB2_TCP;
16855 	optp->name = EXPER_XPORT_MLP;
16856 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16857 	if (optp->len == 0)
16858 		freemsg(mp_attr_ctl);
16859 	else
16860 		qreply(q, mp_attr_ctl);
16861 
16862 	/* table of IPv6 connections... */
16863 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16864 	    sizeof (struct T_optmgmt_ack)];
16865 	optp->level = MIB2_TCP6;
16866 	optp->name = MIB2_TCP6_CONN;
16867 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16868 	qreply(q, mp6_conn_ctl);
16869 
16870 	/* table of IPv6 MLP attributes... */
16871 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16872 	    sizeof (struct T_optmgmt_ack)];
16873 	optp->level = MIB2_TCP6;
16874 	optp->name = EXPER_XPORT_MLP;
16875 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16876 	if (optp->len == 0)
16877 		freemsg(mp6_attr_ctl);
16878 	else
16879 		qreply(q, mp6_attr_ctl);
16880 	return (mp2ctl);
16881 }
16882 
16883 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16884 /* ARGSUSED */
16885 int
16886 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16887 {
16888 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16889 
16890 	switch (level) {
16891 	case MIB2_TCP:
16892 		switch (name) {
16893 		case 13:
16894 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16895 				return (0);
16896 			/* TODO: delete entry defined by tce */
16897 			return (1);
16898 		default:
16899 			return (0);
16900 		}
16901 	default:
16902 		return (1);
16903 	}
16904 }
16905 
16906 /* Translate TCP state to MIB2 TCP state. */
16907 static int
16908 tcp_snmp_state(tcp_t *tcp)
16909 {
16910 	if (tcp == NULL)
16911 		return (0);
16912 
16913 	switch (tcp->tcp_state) {
16914 	case TCPS_CLOSED:
16915 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16916 	case TCPS_BOUND:
16917 		return (MIB2_TCP_closed);
16918 	case TCPS_LISTEN:
16919 		return (MIB2_TCP_listen);
16920 	case TCPS_SYN_SENT:
16921 		return (MIB2_TCP_synSent);
16922 	case TCPS_SYN_RCVD:
16923 		return (MIB2_TCP_synReceived);
16924 	case TCPS_ESTABLISHED:
16925 		return (MIB2_TCP_established);
16926 	case TCPS_CLOSE_WAIT:
16927 		return (MIB2_TCP_closeWait);
16928 	case TCPS_FIN_WAIT_1:
16929 		return (MIB2_TCP_finWait1);
16930 	case TCPS_CLOSING:
16931 		return (MIB2_TCP_closing);
16932 	case TCPS_LAST_ACK:
16933 		return (MIB2_TCP_lastAck);
16934 	case TCPS_FIN_WAIT_2:
16935 		return (MIB2_TCP_finWait2);
16936 	case TCPS_TIME_WAIT:
16937 		return (MIB2_TCP_timeWait);
16938 	default:
16939 		return (0);
16940 	}
16941 }
16942 
16943 static char tcp_report_header[] =
16944 	"TCP     " MI_COL_HDRPAD_STR
16945 	"zone dest            snxt     suna     "
16946 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16947 	"recent   [lport,fport] state";
16948 
16949 /*
16950  * TCP status report triggered via the Named Dispatch mechanism.
16951  */
16952 /* ARGSUSED */
16953 static void
16954 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16955     cred_t *cr)
16956 {
16957 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16958 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16959 	char cflag;
16960 	in6_addr_t	v6dst;
16961 	char buf[80];
16962 	uint_t print_len, buf_len;
16963 
16964 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16965 	if (buf_len <= 0)
16966 		return;
16967 
16968 	if (hashval >= 0)
16969 		(void) sprintf(hash, "%03d ", hashval);
16970 	else
16971 		hash[0] = '\0';
16972 
16973 	/*
16974 	 * Note that we use the remote address in the tcp_b  structure.
16975 	 * This means that it will print out the real destination address,
16976 	 * not the next hop's address if source routing is used.  This
16977 	 * avoid the confusion on the output because user may not
16978 	 * know that source routing is used for a connection.
16979 	 */
16980 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16981 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16982 	} else {
16983 		v6dst = tcp->tcp_remote_v6;
16984 	}
16985 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16986 	/*
16987 	 * the ispriv checks are so that normal users cannot determine
16988 	 * sequence number information using NDD.
16989 	 */
16990 
16991 	if (TCP_IS_DETACHED(tcp))
16992 		cflag = '*';
16993 	else
16994 		cflag = ' ';
16995 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16996 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16997 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16998 	    hash,
16999 	    (void *)tcp,
17000 	    tcp->tcp_connp->conn_zoneid,
17001 	    addrbuf,
17002 	    (ispriv) ? tcp->tcp_snxt : 0,
17003 	    (ispriv) ? tcp->tcp_suna : 0,
17004 	    tcp->tcp_swnd,
17005 	    (ispriv) ? tcp->tcp_rnxt : 0,
17006 	    (ispriv) ? tcp->tcp_rack : 0,
17007 	    tcp->tcp_rwnd,
17008 	    tcp->tcp_rto,
17009 	    tcp->tcp_mss,
17010 	    tcp->tcp_snd_ws_ok,
17011 	    tcp->tcp_snd_ws,
17012 	    tcp->tcp_rcv_ws,
17013 	    tcp->tcp_snd_ts_ok,
17014 	    tcp->tcp_ts_recent,
17015 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
17016 	if (print_len < buf_len) {
17017 		((mblk_t *)mp)->b_wptr += print_len;
17018 	} else {
17019 		((mblk_t *)mp)->b_wptr += buf_len;
17020 	}
17021 }
17022 
17023 /*
17024  * TCP status report (for listeners only) triggered via the Named Dispatch
17025  * mechanism.
17026  */
17027 /* ARGSUSED */
17028 static void
17029 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
17030 {
17031 	char addrbuf[INET6_ADDRSTRLEN];
17032 	in6_addr_t	v6dst;
17033 	uint_t print_len, buf_len;
17034 
17035 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
17036 	if (buf_len <= 0)
17037 		return;
17038 
17039 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17040 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
17041 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
17042 	} else {
17043 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
17044 		    addrbuf, sizeof (addrbuf));
17045 	}
17046 	print_len = snprintf((char *)mp->b_wptr, buf_len,
17047 	    "%03d "
17048 	    MI_COL_PTRFMT_STR
17049 	    "%d %s %05u %08u %d/%d/%d%c\n",
17050 	    hashval, (void *)tcp,
17051 	    tcp->tcp_connp->conn_zoneid,
17052 	    addrbuf,
17053 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
17054 	    tcp->tcp_conn_req_seqnum,
17055 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
17056 	    tcp->tcp_conn_req_max,
17057 	    tcp->tcp_syn_defense ? '*' : ' ');
17058 	if (print_len < buf_len) {
17059 		((mblk_t *)mp)->b_wptr += print_len;
17060 	} else {
17061 		((mblk_t *)mp)->b_wptr += buf_len;
17062 	}
17063 }
17064 
17065 /* TCP status report triggered via the Named Dispatch mechanism. */
17066 /* ARGSUSED */
17067 static int
17068 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17069 {
17070 	tcp_t	*tcp;
17071 	int	i;
17072 	conn_t	*connp;
17073 	connf_t	*connfp;
17074 	zoneid_t zoneid;
17075 	tcp_stack_t *tcps;
17076 	ip_stack_t *ipst;
17077 
17078 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17079 	tcps = Q_TO_TCP(q)->tcp_tcps;
17080 
17081 	/*
17082 	 * Because of the ndd constraint, at most we can have 64K buffer
17083 	 * to put in all TCP info.  So to be more efficient, just
17084 	 * allocate a 64K buffer here, assuming we need that large buffer.
17085 	 * This may be a problem as any user can read tcp_status.  Therefore
17086 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
17087 	 * This should be OK as normal users should not do this too often.
17088 	 */
17089 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17090 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17091 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17092 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17093 			return (0);
17094 		}
17095 	}
17096 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17097 		/* The following may work even if we cannot get a large buf. */
17098 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17099 		return (0);
17100 	}
17101 
17102 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
17103 
17104 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
17105 
17106 		ipst = tcps->tcps_netstack->netstack_ip;
17107 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
17108 
17109 		connp = NULL;
17110 
17111 		while ((connp =
17112 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17113 			tcp = connp->conn_tcp;
17114 			if (zoneid != GLOBAL_ZONEID &&
17115 			    zoneid != connp->conn_zoneid)
17116 				continue;
17117 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
17118 			    cr);
17119 		}
17120 
17121 	}
17122 
17123 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17124 	return (0);
17125 }
17126 
17127 /* TCP status report triggered via the Named Dispatch mechanism. */
17128 /* ARGSUSED */
17129 static int
17130 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17131 {
17132 	tf_t	*tbf;
17133 	tcp_t	*tcp;
17134 	int	i;
17135 	zoneid_t zoneid;
17136 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17137 
17138 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17139 
17140 	/* Refer to comments in tcp_status_report(). */
17141 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17142 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17143 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17144 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17145 			return (0);
17146 		}
17147 	}
17148 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17149 		/* The following may work even if we cannot get a large buf. */
17150 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17151 		return (0);
17152 	}
17153 
17154 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17155 
17156 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
17157 		tbf = &tcps->tcps_bind_fanout[i];
17158 		mutex_enter(&tbf->tf_lock);
17159 		for (tcp = tbf->tf_tcp; tcp != NULL;
17160 		    tcp = tcp->tcp_bind_hash) {
17161 			if (zoneid != GLOBAL_ZONEID &&
17162 			    zoneid != tcp->tcp_connp->conn_zoneid)
17163 				continue;
17164 			CONN_INC_REF(tcp->tcp_connp);
17165 			tcp_report_item(mp->b_cont, tcp, i,
17166 			    Q_TO_TCP(q), cr);
17167 			CONN_DEC_REF(tcp->tcp_connp);
17168 		}
17169 		mutex_exit(&tbf->tf_lock);
17170 	}
17171 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17172 	return (0);
17173 }
17174 
17175 /* TCP status report triggered via the Named Dispatch mechanism. */
17176 /* ARGSUSED */
17177 static int
17178 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17179 {
17180 	connf_t	*connfp;
17181 	conn_t	*connp;
17182 	tcp_t	*tcp;
17183 	int	i;
17184 	zoneid_t zoneid;
17185 	tcp_stack_t *tcps;
17186 	ip_stack_t	*ipst;
17187 
17188 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17189 	tcps = Q_TO_TCP(q)->tcp_tcps;
17190 
17191 	/* Refer to comments in tcp_status_report(). */
17192 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17193 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17194 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17195 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17196 			return (0);
17197 		}
17198 	}
17199 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17200 		/* The following may work even if we cannot get a large buf. */
17201 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17202 		return (0);
17203 	}
17204 
17205 	(void) mi_mpprintf(mp,
17206 	    "    TCP    " MI_COL_HDRPAD_STR
17207 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
17208 
17209 	ipst = tcps->tcps_netstack->netstack_ip;
17210 
17211 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
17212 		connfp = &ipst->ips_ipcl_bind_fanout[i];
17213 		connp = NULL;
17214 		while ((connp =
17215 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17216 			tcp = connp->conn_tcp;
17217 			if (zoneid != GLOBAL_ZONEID &&
17218 			    zoneid != connp->conn_zoneid)
17219 				continue;
17220 			tcp_report_listener(mp->b_cont, tcp, i);
17221 		}
17222 	}
17223 
17224 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17225 	return (0);
17226 }
17227 
17228 /* TCP status report triggered via the Named Dispatch mechanism. */
17229 /* ARGSUSED */
17230 static int
17231 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17232 {
17233 	connf_t	*connfp;
17234 	conn_t	*connp;
17235 	tcp_t	*tcp;
17236 	int	i;
17237 	zoneid_t zoneid;
17238 	tcp_stack_t *tcps;
17239 	ip_stack_t *ipst;
17240 
17241 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17242 	tcps = Q_TO_TCP(q)->tcp_tcps;
17243 	ipst = tcps->tcps_netstack->netstack_ip;
17244 
17245 	/* Refer to comments in tcp_status_report(). */
17246 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17247 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17248 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17249 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17250 			return (0);
17251 		}
17252 	}
17253 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17254 		/* The following may work even if we cannot get a large buf. */
17255 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17256 		return (0);
17257 	}
17258 
17259 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
17260 	    ipst->ips_ipcl_conn_fanout_size);
17261 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17262 
17263 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
17264 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
17265 		connp = NULL;
17266 		while ((connp =
17267 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17268 			tcp = connp->conn_tcp;
17269 			if (zoneid != GLOBAL_ZONEID &&
17270 			    zoneid != connp->conn_zoneid)
17271 				continue;
17272 			tcp_report_item(mp->b_cont, tcp, i,
17273 			    Q_TO_TCP(q), cr);
17274 		}
17275 	}
17276 
17277 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17278 	return (0);
17279 }
17280 
17281 /* TCP status report triggered via the Named Dispatch mechanism. */
17282 /* ARGSUSED */
17283 static int
17284 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17285 {
17286 	tf_t	*tf;
17287 	tcp_t	*tcp;
17288 	int	i;
17289 	zoneid_t zoneid;
17290 	tcp_stack_t	*tcps;
17291 
17292 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17293 	tcps = Q_TO_TCP(q)->tcp_tcps;
17294 
17295 	/* Refer to comments in tcp_status_report(). */
17296 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17297 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17298 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17299 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17300 			return (0);
17301 		}
17302 	}
17303 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17304 		/* The following may work even if we cannot get a large buf. */
17305 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17306 		return (0);
17307 	}
17308 
17309 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17310 
17311 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
17312 		tf = &tcps->tcps_acceptor_fanout[i];
17313 		mutex_enter(&tf->tf_lock);
17314 		for (tcp = tf->tf_tcp; tcp != NULL;
17315 		    tcp = tcp->tcp_acceptor_hash) {
17316 			if (zoneid != GLOBAL_ZONEID &&
17317 			    zoneid != tcp->tcp_connp->conn_zoneid)
17318 				continue;
17319 			tcp_report_item(mp->b_cont, tcp, i,
17320 			    Q_TO_TCP(q), cr);
17321 		}
17322 		mutex_exit(&tf->tf_lock);
17323 	}
17324 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17325 	return (0);
17326 }
17327 
17328 /*
17329  * tcp_timer is the timer service routine.  It handles the retransmission,
17330  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
17331  * from the state of the tcp instance what kind of action needs to be done
17332  * at the time it is called.
17333  */
17334 static void
17335 tcp_timer(void *arg)
17336 {
17337 	mblk_t		*mp;
17338 	clock_t		first_threshold;
17339 	clock_t		second_threshold;
17340 	clock_t		ms;
17341 	uint32_t	mss;
17342 	conn_t		*connp = (conn_t *)arg;
17343 	tcp_t		*tcp = connp->conn_tcp;
17344 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17345 
17346 	tcp->tcp_timer_tid = 0;
17347 
17348 	if (tcp->tcp_fused)
17349 		return;
17350 
17351 	first_threshold =  tcp->tcp_first_timer_threshold;
17352 	second_threshold = tcp->tcp_second_timer_threshold;
17353 	switch (tcp->tcp_state) {
17354 	case TCPS_IDLE:
17355 	case TCPS_BOUND:
17356 	case TCPS_LISTEN:
17357 		return;
17358 	case TCPS_SYN_RCVD: {
17359 		tcp_t	*listener = tcp->tcp_listener;
17360 
17361 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
17362 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
17363 			/* it's our first timeout */
17364 			tcp->tcp_syn_rcvd_timeout = 1;
17365 			mutex_enter(&listener->tcp_eager_lock);
17366 			listener->tcp_syn_rcvd_timeout++;
17367 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
17368 				/*
17369 				 * Make this eager available for drop if we
17370 				 * need to drop one to accomodate a new
17371 				 * incoming SYN request.
17372 				 */
17373 				MAKE_DROPPABLE(listener, tcp);
17374 			}
17375 			if (!listener->tcp_syn_defense &&
17376 			    (listener->tcp_syn_rcvd_timeout >
17377 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
17378 			    (tcps->tcps_conn_req_max_q0 > 200)) {
17379 				/* We may be under attack. Put on a defense. */
17380 				listener->tcp_syn_defense = B_TRUE;
17381 				cmn_err(CE_WARN, "High TCP connect timeout "
17382 				    "rate! System (port %d) may be under a "
17383 				    "SYN flood attack!",
17384 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
17385 
17386 				listener->tcp_ip_addr_cache = kmem_zalloc(
17387 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
17388 				    KM_NOSLEEP);
17389 			}
17390 			mutex_exit(&listener->tcp_eager_lock);
17391 		} else if (listener != NULL) {
17392 			mutex_enter(&listener->tcp_eager_lock);
17393 			tcp->tcp_syn_rcvd_timeout++;
17394 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17395 			    !tcp->tcp_closemp_used) {
17396 				/*
17397 				 * This is our second timeout. Put the tcp in
17398 				 * the list of droppable eagers to allow it to
17399 				 * be dropped, if needed. We don't check
17400 				 * whether tcp_dontdrop is set or not to
17401 				 * protect ourselve from a SYN attack where a
17402 				 * remote host can spoof itself as one of the
17403 				 * good IP source and continue to hold
17404 				 * resources too long.
17405 				 */
17406 				MAKE_DROPPABLE(listener, tcp);
17407 			}
17408 			mutex_exit(&listener->tcp_eager_lock);
17409 		}
17410 	}
17411 		/* FALLTHRU */
17412 	case TCPS_SYN_SENT:
17413 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17414 		second_threshold = tcp->tcp_second_ctimer_threshold;
17415 		break;
17416 	case TCPS_ESTABLISHED:
17417 	case TCPS_FIN_WAIT_1:
17418 	case TCPS_CLOSING:
17419 	case TCPS_CLOSE_WAIT:
17420 	case TCPS_LAST_ACK:
17421 		/* If we have data to rexmit */
17422 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17423 			clock_t	time_to_wait;
17424 
17425 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17426 			if (!tcp->tcp_xmit_head)
17427 				break;
17428 			time_to_wait = lbolt -
17429 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17430 			time_to_wait = tcp->tcp_rto -
17431 			    TICK_TO_MSEC(time_to_wait);
17432 			/*
17433 			 * If the timer fires too early, 1 clock tick earlier,
17434 			 * restart the timer.
17435 			 */
17436 			if (time_to_wait > msec_per_tick) {
17437 				TCP_STAT(tcps, tcp_timer_fire_early);
17438 				TCP_TIMER_RESTART(tcp, time_to_wait);
17439 				return;
17440 			}
17441 			/*
17442 			 * When we probe zero windows, we force the swnd open.
17443 			 * If our peer acks with a closed window swnd will be
17444 			 * set to zero by tcp_rput(). As long as we are
17445 			 * receiving acks tcp_rput will
17446 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17447 			 * first and second interval actions.  NOTE: the timer
17448 			 * interval is allowed to continue its exponential
17449 			 * backoff.
17450 			 */
17451 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17452 				if (tcp->tcp_debug) {
17453 					(void) strlog(TCP_MOD_ID, 0, 1,
17454 					    SL_TRACE, "tcp_timer: zero win");
17455 				}
17456 			} else {
17457 				/*
17458 				 * After retransmission, we need to do
17459 				 * slow start.  Set the ssthresh to one
17460 				 * half of current effective window and
17461 				 * cwnd to one MSS.  Also reset
17462 				 * tcp_cwnd_cnt.
17463 				 *
17464 				 * Note that if tcp_ssthresh is reduced because
17465 				 * of ECN, do not reduce it again unless it is
17466 				 * already one window of data away (tcp_cwr
17467 				 * should then be cleared) or this is a
17468 				 * timeout for a retransmitted segment.
17469 				 */
17470 				uint32_t npkt;
17471 
17472 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17473 					npkt = ((tcp->tcp_timer_backoff ?
17474 					    tcp->tcp_cwnd_ssthresh :
17475 					    tcp->tcp_snxt -
17476 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17477 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17478 					    tcp->tcp_mss;
17479 				}
17480 				tcp->tcp_cwnd = tcp->tcp_mss;
17481 				tcp->tcp_cwnd_cnt = 0;
17482 				if (tcp->tcp_ecn_ok) {
17483 					tcp->tcp_cwr = B_TRUE;
17484 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17485 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17486 				}
17487 			}
17488 			break;
17489 		}
17490 		/*
17491 		 * We have something to send yet we cannot send.  The
17492 		 * reason can be:
17493 		 *
17494 		 * 1. Zero send window: we need to do zero window probe.
17495 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17496 		 * segments.
17497 		 * 3. SWS avoidance: receiver may have shrunk window,
17498 		 * reset our knowledge.
17499 		 *
17500 		 * Note that condition 2 can happen with either 1 or
17501 		 * 3.  But 1 and 3 are exclusive.
17502 		 */
17503 		if (tcp->tcp_unsent != 0) {
17504 			if (tcp->tcp_cwnd == 0) {
17505 				/*
17506 				 * Set tcp_cwnd to 1 MSS so that a
17507 				 * new segment can be sent out.  We
17508 				 * are "clocking out" new data when
17509 				 * the network is really congested.
17510 				 */
17511 				ASSERT(tcp->tcp_ecn_ok);
17512 				tcp->tcp_cwnd = tcp->tcp_mss;
17513 			}
17514 			if (tcp->tcp_swnd == 0) {
17515 				/* Extend window for zero window probe */
17516 				tcp->tcp_swnd++;
17517 				tcp->tcp_zero_win_probe = B_TRUE;
17518 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17519 			} else {
17520 				/*
17521 				 * Handle timeout from sender SWS avoidance.
17522 				 * Reset our knowledge of the max send window
17523 				 * since the receiver might have reduced its
17524 				 * receive buffer.  Avoid setting tcp_max_swnd
17525 				 * to one since that will essentially disable
17526 				 * the SWS checks.
17527 				 *
17528 				 * Note that since we don't have a SWS
17529 				 * state variable, if the timeout is set
17530 				 * for ECN but not for SWS, this
17531 				 * code will also be executed.  This is
17532 				 * fine as tcp_max_swnd is updated
17533 				 * constantly and it will not affect
17534 				 * anything.
17535 				 */
17536 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17537 			}
17538 			tcp_wput_data(tcp, NULL, B_FALSE);
17539 			return;
17540 		}
17541 		/* Is there a FIN that needs to be to re retransmitted? */
17542 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17543 		    !tcp->tcp_fin_acked)
17544 			break;
17545 		/* Nothing to do, return without restarting timer. */
17546 		TCP_STAT(tcps, tcp_timer_fire_miss);
17547 		return;
17548 	case TCPS_FIN_WAIT_2:
17549 		/*
17550 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17551 		 * We waited some time for for peer's FIN, but it hasn't
17552 		 * arrived.  We flush the connection now to avoid
17553 		 * case where the peer has rebooted.
17554 		 */
17555 		if (TCP_IS_DETACHED(tcp)) {
17556 			(void) tcp_clean_death(tcp, 0, 23);
17557 		} else {
17558 			TCP_TIMER_RESTART(tcp,
17559 			    tcps->tcps_fin_wait_2_flush_interval);
17560 		}
17561 		return;
17562 	case TCPS_TIME_WAIT:
17563 		(void) tcp_clean_death(tcp, 0, 24);
17564 		return;
17565 	default:
17566 		if (tcp->tcp_debug) {
17567 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17568 			    "tcp_timer: strange state (%d) %s",
17569 			    tcp->tcp_state, tcp_display(tcp, NULL,
17570 			    DISP_PORT_ONLY));
17571 		}
17572 		return;
17573 	}
17574 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17575 		/*
17576 		 * For zero window probe, we need to send indefinitely,
17577 		 * unless we have not heard from the other side for some
17578 		 * time...
17579 		 */
17580 		if ((tcp->tcp_zero_win_probe == 0) ||
17581 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17582 		    second_threshold)) {
17583 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17584 			/*
17585 			 * If TCP is in SYN_RCVD state, send back a
17586 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17587 			 * should be zero in TCPS_SYN_RCVD state.
17588 			 */
17589 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17590 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17591 				    "in SYN_RCVD",
17592 				    tcp, tcp->tcp_snxt,
17593 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17594 			}
17595 			(void) tcp_clean_death(tcp,
17596 			    tcp->tcp_client_errno ?
17597 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17598 			return;
17599 		} else {
17600 			/*
17601 			 * Set tcp_ms_we_have_waited to second_threshold
17602 			 * so that in next timeout, we will do the above
17603 			 * check (lbolt - tcp_last_recv_time).  This is
17604 			 * also to avoid overflow.
17605 			 *
17606 			 * We don't need to decrement tcp_timer_backoff
17607 			 * to avoid overflow because it will be decremented
17608 			 * later if new timeout value is greater than
17609 			 * tcp_rexmit_interval_max.  In the case when
17610 			 * tcp_rexmit_interval_max is greater than
17611 			 * second_threshold, it means that we will wait
17612 			 * longer than second_threshold to send the next
17613 			 * window probe.
17614 			 */
17615 			tcp->tcp_ms_we_have_waited = second_threshold;
17616 		}
17617 	} else if (ms > first_threshold) {
17618 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17619 		    tcp->tcp_xmit_head != NULL) {
17620 			tcp->tcp_xmit_head =
17621 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17622 		}
17623 		/*
17624 		 * We have been retransmitting for too long...  The RTT
17625 		 * we calculated is probably incorrect.  Reinitialize it.
17626 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17627 		 * tcp_rtt_update so that we won't accidentally cache a
17628 		 * bad value.  But only do this if this is not a zero
17629 		 * window probe.
17630 		 */
17631 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17632 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17633 			    (tcp->tcp_rtt_sa >> 5);
17634 			tcp->tcp_rtt_sa = 0;
17635 			tcp_ip_notify(tcp);
17636 			tcp->tcp_rtt_update = 0;
17637 		}
17638 	}
17639 	tcp->tcp_timer_backoff++;
17640 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17641 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17642 	    tcps->tcps_rexmit_interval_min) {
17643 		/*
17644 		 * This means the original RTO is tcp_rexmit_interval_min.
17645 		 * So we will use tcp_rexmit_interval_min as the RTO value
17646 		 * and do the backoff.
17647 		 */
17648 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17649 	} else {
17650 		ms <<= tcp->tcp_timer_backoff;
17651 	}
17652 	if (ms > tcps->tcps_rexmit_interval_max) {
17653 		ms = tcps->tcps_rexmit_interval_max;
17654 		/*
17655 		 * ms is at max, decrement tcp_timer_backoff to avoid
17656 		 * overflow.
17657 		 */
17658 		tcp->tcp_timer_backoff--;
17659 	}
17660 	tcp->tcp_ms_we_have_waited += ms;
17661 	if (tcp->tcp_zero_win_probe == 0) {
17662 		tcp->tcp_rto = ms;
17663 	}
17664 	TCP_TIMER_RESTART(tcp, ms);
17665 	/*
17666 	 * This is after a timeout and tcp_rto is backed off.  Set
17667 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17668 	 * restart the timer with a correct value.
17669 	 */
17670 	tcp->tcp_set_timer = 1;
17671 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17672 	if (mss > tcp->tcp_mss)
17673 		mss = tcp->tcp_mss;
17674 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17675 		mss = tcp->tcp_swnd;
17676 
17677 	if ((mp = tcp->tcp_xmit_head) != NULL)
17678 		mp->b_prev = (mblk_t *)lbolt;
17679 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17680 	    B_TRUE);
17681 
17682 	/*
17683 	 * When slow start after retransmission begins, start with
17684 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17685 	 * start phase.  tcp_snd_burst controls how many segments
17686 	 * can be sent because of an ack.
17687 	 */
17688 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17689 	tcp->tcp_snd_burst = TCP_CWND_SS;
17690 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17691 	    (tcp->tcp_unsent == 0)) {
17692 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17693 	} else {
17694 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17695 	}
17696 	tcp->tcp_rexmit = B_TRUE;
17697 	tcp->tcp_dupack_cnt = 0;
17698 
17699 	/*
17700 	 * Remove all rexmit SACK blk to start from fresh.
17701 	 */
17702 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17703 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17704 		tcp->tcp_num_notsack_blk = 0;
17705 		tcp->tcp_cnt_notsack_list = 0;
17706 	}
17707 	if (mp == NULL) {
17708 		return;
17709 	}
17710 	/* Attach credentials to retransmitted initial SYNs. */
17711 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17712 		mblk_setcred(mp, tcp->tcp_cred);
17713 		DB_CPID(mp) = tcp->tcp_cpid;
17714 	}
17715 
17716 	tcp->tcp_csuna = tcp->tcp_snxt;
17717 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17718 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17719 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17720 
17721 }
17722 
17723 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17724 static void
17725 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17726 {
17727 	conn_t	*connp;
17728 
17729 	switch (tcp->tcp_state) {
17730 	case TCPS_BOUND:
17731 	case TCPS_LISTEN:
17732 		break;
17733 	default:
17734 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17735 		return;
17736 	}
17737 
17738 	/*
17739 	 * Need to clean up all the eagers since after the unbind, segments
17740 	 * will no longer be delivered to this listener stream.
17741 	 */
17742 	mutex_enter(&tcp->tcp_eager_lock);
17743 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17744 		tcp_eager_cleanup(tcp, 0);
17745 	}
17746 	mutex_exit(&tcp->tcp_eager_lock);
17747 
17748 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17749 		tcp->tcp_ipha->ipha_src = 0;
17750 	} else {
17751 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17752 	}
17753 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17754 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17755 	tcp_bind_hash_remove(tcp);
17756 	tcp->tcp_state = TCPS_IDLE;
17757 	tcp->tcp_mdt = B_FALSE;
17758 	/* Send M_FLUSH according to TPI */
17759 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17760 	connp = tcp->tcp_connp;
17761 	connp->conn_mdt_ok = B_FALSE;
17762 	ipcl_hash_remove(connp);
17763 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17764 	mp = mi_tpi_ok_ack_alloc(mp);
17765 	putnext(tcp->tcp_rq, mp);
17766 }
17767 
17768 /*
17769  * Don't let port fall into the privileged range.
17770  * Since the extra privileged ports can be arbitrary we also
17771  * ensure that we exclude those from consideration.
17772  * tcp_g_epriv_ports is not sorted thus we loop over it until
17773  * there are no changes.
17774  *
17775  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17776  * but instead the code relies on:
17777  * - the fact that the address of the array and its size never changes
17778  * - the atomic assignment of the elements of the array
17779  *
17780  * Returns 0 if there are no more ports available.
17781  *
17782  * TS note: skip multilevel ports.
17783  */
17784 static in_port_t
17785 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17786 {
17787 	int i;
17788 	boolean_t restart = B_FALSE;
17789 	tcp_stack_t *tcps = tcp->tcp_tcps;
17790 
17791 	if (random && tcp_random_anon_port != 0) {
17792 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17793 		    sizeof (in_port_t));
17794 		/*
17795 		 * Unless changed by a sys admin, the smallest anon port
17796 		 * is 32768 and the largest anon port is 65535.  It is
17797 		 * very likely (50%) for the random port to be smaller
17798 		 * than the smallest anon port.  When that happens,
17799 		 * add port % (anon port range) to the smallest anon
17800 		 * port to get the random port.  It should fall into the
17801 		 * valid anon port range.
17802 		 */
17803 		if (port < tcps->tcps_smallest_anon_port) {
17804 			port = tcps->tcps_smallest_anon_port +
17805 			    port % (tcps->tcps_largest_anon_port -
17806 			    tcps->tcps_smallest_anon_port);
17807 		}
17808 	}
17809 
17810 retry:
17811 	if (port < tcps->tcps_smallest_anon_port)
17812 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17813 
17814 	if (port > tcps->tcps_largest_anon_port) {
17815 		if (restart)
17816 			return (0);
17817 		restart = B_TRUE;
17818 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17819 	}
17820 
17821 	if (port < tcps->tcps_smallest_nonpriv_port)
17822 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17823 
17824 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17825 		if (port == tcps->tcps_g_epriv_ports[i]) {
17826 			port++;
17827 			/*
17828 			 * Make sure whether the port is in the
17829 			 * valid range.
17830 			 */
17831 			goto retry;
17832 		}
17833 	}
17834 	if (is_system_labeled() &&
17835 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17836 	    IPPROTO_TCP, B_TRUE)) != 0) {
17837 		port = i;
17838 		goto retry;
17839 	}
17840 	return (port);
17841 }
17842 
17843 /*
17844  * Return the next anonymous port in the privileged port range for
17845  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17846  * downwards.  This is the same behavior as documented in the userland
17847  * library call rresvport(3N).
17848  *
17849  * TS note: skip multilevel ports.
17850  */
17851 static in_port_t
17852 tcp_get_next_priv_port(const tcp_t *tcp)
17853 {
17854 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17855 	in_port_t nextport;
17856 	boolean_t restart = B_FALSE;
17857 	tcp_stack_t *tcps = tcp->tcp_tcps;
17858 retry:
17859 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17860 	    next_priv_port >= IPPORT_RESERVED) {
17861 		next_priv_port = IPPORT_RESERVED - 1;
17862 		if (restart)
17863 			return (0);
17864 		restart = B_TRUE;
17865 	}
17866 	if (is_system_labeled() &&
17867 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17868 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17869 		next_priv_port = nextport;
17870 		goto retry;
17871 	}
17872 	return (next_priv_port--);
17873 }
17874 
17875 /* The write side r/w procedure. */
17876 
17877 #if CCS_STATS
17878 struct {
17879 	struct {
17880 		int64_t count, bytes;
17881 	} tot, hit;
17882 } wrw_stats;
17883 #endif
17884 
17885 /*
17886  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17887  * messages.
17888  */
17889 /* ARGSUSED */
17890 static void
17891 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17892 {
17893 	conn_t	*connp = (conn_t *)arg;
17894 	tcp_t	*tcp = connp->conn_tcp;
17895 	queue_t	*q = tcp->tcp_wq;
17896 
17897 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17898 	/*
17899 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17900 	 * Once the close starts, streamhead and sockfs will not let any data
17901 	 * packets come down (close ensures that there are no threads using the
17902 	 * queue and no new threads will come down) but since qprocsoff()
17903 	 * hasn't happened yet, a M_FLUSH or some non data message might
17904 	 * get reflected back (in response to our own FLUSHRW) and get
17905 	 * processed after tcp_close() is done. The conn would still be valid
17906 	 * because a ref would have added but we need to check the state
17907 	 * before actually processing the packet.
17908 	 */
17909 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17910 		freemsg(mp);
17911 		return;
17912 	}
17913 
17914 	switch (DB_TYPE(mp)) {
17915 	case M_IOCDATA:
17916 		tcp_wput_iocdata(tcp, mp);
17917 		break;
17918 	case M_FLUSH:
17919 		tcp_wput_flush(tcp, mp);
17920 		break;
17921 	default:
17922 		CALL_IP_WPUT(connp, q, mp);
17923 		break;
17924 	}
17925 }
17926 
17927 /*
17928  * The TCP fast path write put procedure.
17929  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17930  */
17931 /* ARGSUSED */
17932 void
17933 tcp_output(void *arg, mblk_t *mp, void *arg2)
17934 {
17935 	int		len;
17936 	int		hdrlen;
17937 	int		plen;
17938 	mblk_t		*mp1;
17939 	uchar_t		*rptr;
17940 	uint32_t	snxt;
17941 	tcph_t		*tcph;
17942 	struct datab	*db;
17943 	uint32_t	suna;
17944 	uint32_t	mss;
17945 	ipaddr_t	*dst;
17946 	ipaddr_t	*src;
17947 	uint32_t	sum;
17948 	int		usable;
17949 	conn_t		*connp = (conn_t *)arg;
17950 	tcp_t		*tcp = connp->conn_tcp;
17951 	uint32_t	msize;
17952 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17953 
17954 	/*
17955 	 * Try and ASSERT the minimum possible references on the
17956 	 * conn early enough. Since we are executing on write side,
17957 	 * the connection is obviously not detached and that means
17958 	 * there is a ref each for TCP and IP. Since we are behind
17959 	 * the squeue, the minimum references needed are 3. If the
17960 	 * conn is in classifier hash list, there should be an
17961 	 * extra ref for that (we check both the possibilities).
17962 	 */
17963 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17964 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17965 
17966 	ASSERT(DB_TYPE(mp) == M_DATA);
17967 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17968 
17969 	mutex_enter(&tcp->tcp_non_sq_lock);
17970 	tcp->tcp_squeue_bytes -= msize;
17971 	mutex_exit(&tcp->tcp_non_sq_lock);
17972 
17973 	/* Bypass tcp protocol for fused tcp loopback */
17974 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17975 		return;
17976 
17977 	mss = tcp->tcp_mss;
17978 	if (tcp->tcp_xmit_zc_clean)
17979 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17980 
17981 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17982 	len = (int)(mp->b_wptr - mp->b_rptr);
17983 
17984 	/*
17985 	 * Criteria for fast path:
17986 	 *
17987 	 *   1. no unsent data
17988 	 *   2. single mblk in request
17989 	 *   3. connection established
17990 	 *   4. data in mblk
17991 	 *   5. len <= mss
17992 	 *   6. no tcp_valid bits
17993 	 */
17994 	if ((tcp->tcp_unsent != 0) ||
17995 	    (tcp->tcp_cork) ||
17996 	    (mp->b_cont != NULL) ||
17997 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17998 	    (len == 0) ||
17999 	    (len > mss) ||
18000 	    (tcp->tcp_valid_bits != 0)) {
18001 		tcp_wput_data(tcp, mp, B_FALSE);
18002 		return;
18003 	}
18004 
18005 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
18006 	ASSERT(tcp->tcp_fin_sent == 0);
18007 
18008 	/* queue new packet onto retransmission queue */
18009 	if (tcp->tcp_xmit_head == NULL) {
18010 		tcp->tcp_xmit_head = mp;
18011 	} else {
18012 		tcp->tcp_xmit_last->b_cont = mp;
18013 	}
18014 	tcp->tcp_xmit_last = mp;
18015 	tcp->tcp_xmit_tail = mp;
18016 
18017 	/* find out how much we can send */
18018 	/* BEGIN CSTYLED */
18019 	/*
18020 	 *    un-acked           usable
18021 	 *  |--------------|-----------------|
18022 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
18023 	 */
18024 	/* END CSTYLED */
18025 
18026 	/* start sending from tcp_snxt */
18027 	snxt = tcp->tcp_snxt;
18028 
18029 	/*
18030 	 * Check to see if this connection has been idled for some
18031 	 * time and no ACK is expected.  If it is, we need to slow
18032 	 * start again to get back the connection's "self-clock" as
18033 	 * described in VJ's paper.
18034 	 *
18035 	 * Refer to the comment in tcp_mss_set() for the calculation
18036 	 * of tcp_cwnd after idle.
18037 	 */
18038 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
18039 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
18040 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
18041 	}
18042 
18043 	usable = tcp->tcp_swnd;		/* tcp window size */
18044 	if (usable > tcp->tcp_cwnd)
18045 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
18046 	usable -= snxt;		/* subtract stuff already sent */
18047 	suna = tcp->tcp_suna;
18048 	usable += suna;
18049 	/* usable can be < 0 if the congestion window is smaller */
18050 	if (len > usable) {
18051 		/* Can't send complete M_DATA in one shot */
18052 		goto slow;
18053 	}
18054 
18055 	mutex_enter(&tcp->tcp_non_sq_lock);
18056 	if (tcp->tcp_flow_stopped &&
18057 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18058 		tcp_clrqfull(tcp);
18059 	}
18060 	mutex_exit(&tcp->tcp_non_sq_lock);
18061 
18062 	/*
18063 	 * determine if anything to send (Nagle).
18064 	 *
18065 	 *   1. len < tcp_mss (i.e. small)
18066 	 *   2. unacknowledged data present
18067 	 *   3. len < nagle limit
18068 	 *   4. last packet sent < nagle limit (previous packet sent)
18069 	 */
18070 	if ((len < mss) && (snxt != suna) &&
18071 	    (len < (int)tcp->tcp_naglim) &&
18072 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
18073 		/*
18074 		 * This was the first unsent packet and normally
18075 		 * mss < xmit_hiwater so there is no need to worry
18076 		 * about flow control. The next packet will go
18077 		 * through the flow control check in tcp_wput_data().
18078 		 */
18079 		/* leftover work from above */
18080 		tcp->tcp_unsent = len;
18081 		tcp->tcp_xmit_tail_unsent = len;
18082 
18083 		return;
18084 	}
18085 
18086 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
18087 
18088 	if (snxt == suna) {
18089 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18090 	}
18091 
18092 	/* we have always sent something */
18093 	tcp->tcp_rack_cnt = 0;
18094 
18095 	tcp->tcp_snxt = snxt + len;
18096 	tcp->tcp_rack = tcp->tcp_rnxt;
18097 
18098 	if ((mp1 = dupb(mp)) == 0)
18099 		goto no_memory;
18100 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
18101 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
18102 
18103 	/* adjust tcp header information */
18104 	tcph = tcp->tcp_tcph;
18105 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
18106 
18107 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
18108 	sum = (sum >> 16) + (sum & 0xFFFF);
18109 	U16_TO_ABE16(sum, tcph->th_sum);
18110 
18111 	U32_TO_ABE32(snxt, tcph->th_seq);
18112 
18113 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
18114 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
18115 	BUMP_LOCAL(tcp->tcp_obsegs);
18116 
18117 	/* Update the latest receive window size in TCP header. */
18118 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18119 	    tcph->th_win);
18120 
18121 	tcp->tcp_last_sent_len = (ushort_t)len;
18122 
18123 	plen = len + tcp->tcp_hdr_len;
18124 
18125 	if (tcp->tcp_ipversion == IPV4_VERSION) {
18126 		tcp->tcp_ipha->ipha_length = htons(plen);
18127 	} else {
18128 		tcp->tcp_ip6h->ip6_plen = htons(plen -
18129 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
18130 	}
18131 
18132 	/* see if we need to allocate a mblk for the headers */
18133 	hdrlen = tcp->tcp_hdr_len;
18134 	rptr = mp1->b_rptr - hdrlen;
18135 	db = mp1->b_datap;
18136 	if ((db->db_ref != 2) || rptr < db->db_base ||
18137 	    (!OK_32PTR(rptr))) {
18138 		/* NOTE: we assume allocb returns an OK_32PTR */
18139 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
18140 		    tcps->tcps_wroff_xtra, BPRI_MED);
18141 		if (!mp) {
18142 			freemsg(mp1);
18143 			goto no_memory;
18144 		}
18145 		mp->b_cont = mp1;
18146 		mp1 = mp;
18147 		/* Leave room for Link Level header */
18148 		/* hdrlen = tcp->tcp_hdr_len; */
18149 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
18150 		mp1->b_wptr = &rptr[hdrlen];
18151 	}
18152 	mp1->b_rptr = rptr;
18153 
18154 	/* Fill in the timestamp option. */
18155 	if (tcp->tcp_snd_ts_ok) {
18156 		U32_TO_BE32((uint32_t)lbolt,
18157 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
18158 		U32_TO_BE32(tcp->tcp_ts_recent,
18159 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
18160 	} else {
18161 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18162 	}
18163 
18164 	/* copy header into outgoing packet */
18165 	dst = (ipaddr_t *)rptr;
18166 	src = (ipaddr_t *)tcp->tcp_iphc;
18167 	dst[0] = src[0];
18168 	dst[1] = src[1];
18169 	dst[2] = src[2];
18170 	dst[3] = src[3];
18171 	dst[4] = src[4];
18172 	dst[5] = src[5];
18173 	dst[6] = src[6];
18174 	dst[7] = src[7];
18175 	dst[8] = src[8];
18176 	dst[9] = src[9];
18177 	if (hdrlen -= 40) {
18178 		hdrlen >>= 2;
18179 		dst += 10;
18180 		src += 10;
18181 		do {
18182 			*dst++ = *src++;
18183 		} while (--hdrlen);
18184 	}
18185 
18186 	/*
18187 	 * Set the ECN info in the TCP header.  Note that this
18188 	 * is not the template header.
18189 	 */
18190 	if (tcp->tcp_ecn_ok) {
18191 		SET_ECT(tcp, rptr);
18192 
18193 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18194 		if (tcp->tcp_ecn_echo_on)
18195 			tcph->th_flags[0] |= TH_ECE;
18196 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18197 			tcph->th_flags[0] |= TH_CWR;
18198 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18199 		}
18200 	}
18201 
18202 	if (tcp->tcp_ip_forward_progress) {
18203 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
18204 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
18205 		tcp->tcp_ip_forward_progress = B_FALSE;
18206 	}
18207 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
18208 	return;
18209 
18210 	/*
18211 	 * If we ran out of memory, we pretend to have sent the packet
18212 	 * and that it was lost on the wire.
18213 	 */
18214 no_memory:
18215 	return;
18216 
18217 slow:
18218 	/* leftover work from above */
18219 	tcp->tcp_unsent = len;
18220 	tcp->tcp_xmit_tail_unsent = len;
18221 	tcp_wput_data(tcp, NULL, B_FALSE);
18222 }
18223 
18224 /*
18225  * The function called through squeue to get behind eager's perimeter to
18226  * finish the accept processing.
18227  */
18228 /* ARGSUSED */
18229 void
18230 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
18231 {
18232 	conn_t			*connp = (conn_t *)arg;
18233 	tcp_t			*tcp = connp->conn_tcp;
18234 	queue_t			*q = tcp->tcp_rq;
18235 	mblk_t			*mp1;
18236 	mblk_t			*stropt_mp = mp;
18237 	struct  stroptions	*stropt;
18238 	uint_t			thwin;
18239 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18240 
18241 	/*
18242 	 * Drop the eager's ref on the listener, that was placed when
18243 	 * this eager began life in tcp_conn_request.
18244 	 */
18245 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
18246 
18247 	tcp->tcp_detached = B_FALSE;
18248 
18249 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
18250 		/*
18251 		 * Someone blewoff the eager before we could finish
18252 		 * the accept.
18253 		 *
18254 		 * The only reason eager exists it because we put in
18255 		 * a ref on it when conn ind went up. We need to send
18256 		 * a disconnect indication up while the last reference
18257 		 * on the eager will be dropped by the squeue when we
18258 		 * return.
18259 		 */
18260 		ASSERT(tcp->tcp_listener == NULL);
18261 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
18262 			struct	T_discon_ind	*tdi;
18263 
18264 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
18265 			/*
18266 			 * Let us reuse the incoming mblk to avoid memory
18267 			 * allocation failure problems. We know that the
18268 			 * size of the incoming mblk i.e. stroptions is greater
18269 			 * than sizeof T_discon_ind. So the reallocb below
18270 			 * can't fail.
18271 			 */
18272 			freemsg(mp->b_cont);
18273 			mp->b_cont = NULL;
18274 			ASSERT(DB_REF(mp) == 1);
18275 			mp = reallocb(mp, sizeof (struct T_discon_ind),
18276 			    B_FALSE);
18277 			ASSERT(mp != NULL);
18278 			DB_TYPE(mp) = M_PROTO;
18279 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
18280 			tdi = (struct T_discon_ind *)mp->b_rptr;
18281 			if (tcp->tcp_issocket) {
18282 				tdi->DISCON_reason = ECONNREFUSED;
18283 				tdi->SEQ_number = 0;
18284 			} else {
18285 				tdi->DISCON_reason = ENOPROTOOPT;
18286 				tdi->SEQ_number =
18287 				    tcp->tcp_conn_req_seqnum;
18288 			}
18289 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
18290 			putnext(q, mp);
18291 		} else {
18292 			freemsg(mp);
18293 		}
18294 		if (tcp->tcp_hard_binding) {
18295 			tcp->tcp_hard_binding = B_FALSE;
18296 			tcp->tcp_hard_bound = B_TRUE;
18297 		}
18298 		return;
18299 	}
18300 
18301 	mp1 = stropt_mp->b_cont;
18302 	stropt_mp->b_cont = NULL;
18303 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
18304 	stropt = (struct stroptions *)stropt_mp->b_rptr;
18305 
18306 	while (mp1 != NULL) {
18307 		mp = mp1;
18308 		mp1 = mp1->b_cont;
18309 		mp->b_cont = NULL;
18310 		tcp->tcp_drop_opt_ack_cnt++;
18311 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
18312 	}
18313 	mp = NULL;
18314 
18315 	/*
18316 	 * For a loopback connection with tcp_direct_sockfs on, note that
18317 	 * we don't have to protect tcp_rcv_list yet because synchronous
18318 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
18319 	 * possibly race with us.
18320 	 */
18321 
18322 	/*
18323 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
18324 	 * properly.  This is the first time we know of the acceptor'
18325 	 * queue.  So we do it here.
18326 	 */
18327 	if (tcp->tcp_rcv_list == NULL) {
18328 		/*
18329 		 * Recv queue is empty, tcp_rwnd should not have changed.
18330 		 * That means it should be equal to the listener's tcp_rwnd.
18331 		 */
18332 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
18333 	} else {
18334 #ifdef DEBUG
18335 		uint_t cnt = 0;
18336 
18337 		mp1 = tcp->tcp_rcv_list;
18338 		while ((mp = mp1) != NULL) {
18339 			mp1 = mp->b_next;
18340 			cnt += msgdsize(mp);
18341 		}
18342 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
18343 #endif
18344 		/* There is some data, add them back to get the max. */
18345 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18346 	}
18347 	/*
18348 	 * This is the first time we run on the correct
18349 	 * queue after tcp_accept. So fix all the q parameters
18350 	 * here.
18351 	 */
18352 	stropt->so_flags = SO_HIWAT | SO_MAXBLK | SO_WROFF;
18353 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
18354 
18355 	/*
18356 	 * Record the stream head's high water mark for this endpoint;
18357 	 * this is used for flow-control purposes.
18358 	 */
18359 	stropt->so_hiwat = tcp->tcp_fused ?
18360 	    tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat) :
18361 	    MAX(q->q_hiwat, tcps->tcps_sth_rcv_hiwat);
18362 
18363 	/*
18364 	 * Determine what write offset value to use depending on SACK and
18365 	 * whether the endpoint is fused or not.
18366 	 */
18367 	if (tcp->tcp_fused) {
18368 		ASSERT(tcp->tcp_loopback);
18369 		ASSERT(tcp->tcp_loopback_peer != NULL);
18370 		/*
18371 		 * For fused tcp loopback, set the stream head's write
18372 		 * offset value to zero since we won't be needing any room
18373 		 * for TCP/IP headers.  This would also improve performance
18374 		 * since it would reduce the amount of work done by kmem.
18375 		 * Non-fused tcp loopback case is handled separately below.
18376 		 */
18377 		stropt->so_wroff = 0;
18378 		/*
18379 		 * Update the peer's transmit parameters according to
18380 		 * our recently calculated high water mark value.
18381 		 */
18382 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18383 	} else if (tcp->tcp_snd_sack_ok) {
18384 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18385 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18386 	} else {
18387 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18388 		    tcps->tcps_wroff_xtra);
18389 	}
18390 
18391 	/*
18392 	 * If this is endpoint is handling SSL, then reserve extra
18393 	 * offset and space at the end.
18394 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18395 	 * overriding the previous setting. The extra cost of signing and
18396 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18397 	 * instead of a single contiguous one by the stream head
18398 	 * largely outweighs the statistical reduction of ACKs, when
18399 	 * applicable. The peer will also save on decryption and verification
18400 	 * costs.
18401 	 */
18402 	if (tcp->tcp_kssl_ctx != NULL) {
18403 		stropt->so_wroff += SSL3_WROFFSET;
18404 
18405 		stropt->so_flags |= SO_TAIL;
18406 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
18407 
18408 		stropt->so_flags |= SO_COPYOPT;
18409 		stropt->so_copyopt = ZCVMUNSAFE;
18410 
18411 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
18412 	}
18413 
18414 	/* Send the options up */
18415 	putnext(q, stropt_mp);
18416 
18417 	/*
18418 	 * Pass up any data and/or a fin that has been received.
18419 	 *
18420 	 * Adjust receive window in case it had decreased
18421 	 * (because there is data <=> tcp_rcv_list != NULL)
18422 	 * while the connection was detached. Note that
18423 	 * in case the eager was flow-controlled, w/o this
18424 	 * code, the rwnd may never open up again!
18425 	 */
18426 	if (tcp->tcp_rcv_list != NULL) {
18427 		/* We drain directly in case of fused tcp loopback */
18428 		sodirect_t *sodp;
18429 
18430 		if (!tcp->tcp_fused && canputnext(q)) {
18431 			tcp->tcp_rwnd = q->q_hiwat;
18432 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
18433 			    << tcp->tcp_rcv_ws;
18434 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
18435 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18436 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
18437 				tcp_xmit_ctl(NULL,
18438 				    tcp, (tcp->tcp_swnd == 0) ?
18439 				    tcp->tcp_suna : tcp->tcp_snxt,
18440 				    tcp->tcp_rnxt, TH_ACK);
18441 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
18442 			}
18443 
18444 		}
18445 
18446 		SOD_PTR_ENTER(tcp, sodp);
18447 		if (sodp != NULL) {
18448 			/* Sodirect, move from rcv_list */
18449 			ASSERT(!tcp->tcp_fused);
18450 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18451 				tcp->tcp_rcv_list = mp->b_next;
18452 				mp->b_next = NULL;
18453 				(void) tcp_rcv_sod_enqueue(tcp, sodp, mp,
18454 				    msgdsize(mp));
18455 			}
18456 			tcp->tcp_rcv_last_head = NULL;
18457 			tcp->tcp_rcv_last_tail = NULL;
18458 			tcp->tcp_rcv_cnt = 0;
18459 			(void) tcp_rcv_sod_wakeup(tcp, sodp);
18460 			/* sod_wakeup() did the mutex_exit() */
18461 		} else {
18462 			/* Not sodirect, drain */
18463 			(void) tcp_rcv_drain(q, tcp);
18464 		}
18465 
18466 		/*
18467 		 * For fused tcp loopback, back-enable peer endpoint
18468 		 * if it's currently flow-controlled.
18469 		 */
18470 		if (tcp->tcp_fused) {
18471 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18472 
18473 			ASSERT(peer_tcp != NULL);
18474 			ASSERT(peer_tcp->tcp_fused);
18475 			/*
18476 			 * In order to change the peer's tcp_flow_stopped,
18477 			 * we need to take locks for both end points. The
18478 			 * highest address is taken first.
18479 			 */
18480 			if (peer_tcp > tcp) {
18481 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18482 				mutex_enter(&tcp->tcp_non_sq_lock);
18483 			} else {
18484 				mutex_enter(&tcp->tcp_non_sq_lock);
18485 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18486 			}
18487 			if (peer_tcp->tcp_flow_stopped) {
18488 				tcp_clrqfull(peer_tcp);
18489 				TCP_STAT(tcps, tcp_fusion_backenabled);
18490 			}
18491 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18492 			mutex_exit(&tcp->tcp_non_sq_lock);
18493 		}
18494 	}
18495 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18496 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18497 		mp = mi_tpi_ordrel_ind();
18498 		if (mp) {
18499 			tcp->tcp_ordrel_done = B_TRUE;
18500 			putnext(q, mp);
18501 			if (tcp->tcp_deferred_clean_death) {
18502 				/*
18503 				 * tcp_clean_death was deferred
18504 				 * for T_ORDREL_IND - do it now
18505 				 */
18506 				(void) tcp_clean_death(tcp,
18507 				    tcp->tcp_client_errno, 21);
18508 				tcp->tcp_deferred_clean_death = B_FALSE;
18509 			}
18510 		} else {
18511 			/*
18512 			 * Run the orderly release in the
18513 			 * service routine.
18514 			 */
18515 			qenable(q);
18516 		}
18517 	}
18518 	if (tcp->tcp_hard_binding) {
18519 		tcp->tcp_hard_binding = B_FALSE;
18520 		tcp->tcp_hard_bound = B_TRUE;
18521 	}
18522 
18523 	/* We can enable synchronous streams now */
18524 	if (tcp->tcp_fused) {
18525 		tcp_fuse_syncstr_enable_pair(tcp);
18526 	}
18527 
18528 	if (tcp->tcp_ka_enabled) {
18529 		tcp->tcp_ka_last_intrvl = 0;
18530 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18531 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18532 	}
18533 
18534 	/*
18535 	 * At this point, eager is fully established and will
18536 	 * have the following references -
18537 	 *
18538 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18539 	 * 1 reference for the squeue which will be dropped by the squeue as
18540 	 *	soon as this function returns.
18541 	 * There will be 1 additonal reference for being in classifier
18542 	 *	hash list provided something bad hasn't happened.
18543 	 */
18544 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18545 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18546 }
18547 
18548 /*
18549  * The function called through squeue to get behind listener's perimeter to
18550  * send a deffered conn_ind.
18551  */
18552 /* ARGSUSED */
18553 void
18554 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18555 {
18556 	conn_t	*connp = (conn_t *)arg;
18557 	tcp_t *listener = connp->conn_tcp;
18558 
18559 	if (listener->tcp_state == TCPS_CLOSED ||
18560 	    TCP_IS_DETACHED(listener)) {
18561 		/*
18562 		 * If listener has closed, it would have caused a
18563 		 * a cleanup/blowoff to happen for the eager.
18564 		 */
18565 		tcp_t *tcp;
18566 		struct T_conn_ind	*conn_ind;
18567 
18568 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18569 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18570 		    conn_ind->OPT_length);
18571 		/*
18572 		 * We need to drop the ref on eager that was put
18573 		 * tcp_rput_data() before trying to send the conn_ind
18574 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18575 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18576 		 * listener is closed so we drop the ref.
18577 		 */
18578 		CONN_DEC_REF(tcp->tcp_connp);
18579 		freemsg(mp);
18580 		return;
18581 	}
18582 	putnext(listener->tcp_rq, mp);
18583 }
18584 
18585 
18586 /*
18587  * This is the STREAMS entry point for T_CONN_RES coming down on
18588  * Acceptor STREAM when  sockfs listener does accept processing.
18589  * Read the block comment on top of tcp_conn_request().
18590  */
18591 void
18592 tcp_wput_accept(queue_t *q, mblk_t *mp)
18593 {
18594 	queue_t *rq = RD(q);
18595 	struct T_conn_res *conn_res;
18596 	tcp_t *eager;
18597 	tcp_t *listener;
18598 	struct T_ok_ack *ok;
18599 	t_scalar_t PRIM_type;
18600 	mblk_t *opt_mp;
18601 	conn_t *econnp;
18602 
18603 	ASSERT(DB_TYPE(mp) == M_PROTO);
18604 
18605 	conn_res = (struct T_conn_res *)mp->b_rptr;
18606 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18607 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18608 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18609 		if (mp != NULL)
18610 			putnext(rq, mp);
18611 		return;
18612 	}
18613 	switch (conn_res->PRIM_type) {
18614 	case O_T_CONN_RES:
18615 	case T_CONN_RES:
18616 		/*
18617 		 * We pass up an err ack if allocb fails. This will
18618 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18619 		 * tcp_eager_blowoff to be called. sockfs will then call
18620 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18621 		 * we need to do the allocb up here because we have to
18622 		 * make sure rq->q_qinfo->qi_qclose still points to the
18623 		 * correct function (tcpclose_accept) in case allocb
18624 		 * fails.
18625 		 */
18626 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18627 		if (opt_mp == NULL) {
18628 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18629 			if (mp != NULL)
18630 				putnext(rq, mp);
18631 			return;
18632 		}
18633 
18634 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18635 		    &eager, conn_res->OPT_length);
18636 		PRIM_type = conn_res->PRIM_type;
18637 		mp->b_datap->db_type = M_PCPROTO;
18638 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18639 		ok = (struct T_ok_ack *)mp->b_rptr;
18640 		ok->PRIM_type = T_OK_ACK;
18641 		ok->CORRECT_prim = PRIM_type;
18642 		econnp = eager->tcp_connp;
18643 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18644 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18645 		eager->tcp_rq = rq;
18646 		eager->tcp_wq = q;
18647 		rq->q_ptr = econnp;
18648 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18649 		q->q_ptr = econnp;
18650 		q->q_qinfo = &tcp_winit;
18651 		listener = eager->tcp_listener;
18652 		eager->tcp_issocket = B_TRUE;
18653 
18654 		/*
18655 		 * TCP is _D_SODIRECT and sockfs is directly above so
18656 		 * save shared sodirect_t pointer (if any).
18657 		 *
18658 		 * If tcp_fused and sodirect enabled disable it.
18659 		 */
18660 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18661 		if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18662 			/* Fused, disable sodirect */
18663 			mutex_enter(eager->tcp_sodirect->sod_lockp);
18664 			SOD_DISABLE(eager->tcp_sodirect);
18665 			mutex_exit(eager->tcp_sodirect->sod_lockp);
18666 			eager->tcp_sodirect = NULL;
18667 		}
18668 
18669 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18670 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18671 		ASSERT(econnp->conn_netstack ==
18672 		    listener->tcp_connp->conn_netstack);
18673 		ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18674 
18675 		/* Put the ref for IP */
18676 		CONN_INC_REF(econnp);
18677 
18678 		/*
18679 		 * We should have minimum of 3 references on the conn
18680 		 * at this point. One each for TCP and IP and one for
18681 		 * the T_conn_ind that was sent up when the 3-way handshake
18682 		 * completed. In the normal case we would also have another
18683 		 * reference (making a total of 4) for the conn being in the
18684 		 * classifier hash list. However the eager could have received
18685 		 * an RST subsequently and tcp_closei_local could have removed
18686 		 * the eager from the classifier hash list, hence we can't
18687 		 * assert that reference.
18688 		 */
18689 		ASSERT(econnp->conn_ref >= 3);
18690 
18691 		/*
18692 		 * Send the new local address also up to sockfs. There
18693 		 * should already be enough space in the mp that came
18694 		 * down from soaccept().
18695 		 */
18696 		if (eager->tcp_family == AF_INET) {
18697 			sin_t *sin;
18698 
18699 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18700 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18701 			sin = (sin_t *)mp->b_wptr;
18702 			mp->b_wptr += sizeof (sin_t);
18703 			sin->sin_family = AF_INET;
18704 			sin->sin_port = eager->tcp_lport;
18705 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18706 		} else {
18707 			sin6_t *sin6;
18708 
18709 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18710 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18711 			sin6 = (sin6_t *)mp->b_wptr;
18712 			mp->b_wptr += sizeof (sin6_t);
18713 			sin6->sin6_family = AF_INET6;
18714 			sin6->sin6_port = eager->tcp_lport;
18715 			if (eager->tcp_ipversion == IPV4_VERSION) {
18716 				sin6->sin6_flowinfo = 0;
18717 				IN6_IPADDR_TO_V4MAPPED(
18718 				    eager->tcp_ipha->ipha_src,
18719 				    &sin6->sin6_addr);
18720 			} else {
18721 				ASSERT(eager->tcp_ip6h != NULL);
18722 				sin6->sin6_flowinfo =
18723 				    eager->tcp_ip6h->ip6_vcf &
18724 				    ~IPV6_VERS_AND_FLOW_MASK;
18725 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18726 			}
18727 			sin6->sin6_scope_id = 0;
18728 			sin6->__sin6_src_id = 0;
18729 		}
18730 
18731 		putnext(rq, mp);
18732 
18733 		opt_mp->b_datap->db_type = M_SETOPTS;
18734 		opt_mp->b_wptr += sizeof (struct stroptions);
18735 
18736 		/*
18737 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18738 		 * from listener to acceptor. The message is chained on the
18739 		 * bind_mp which tcp_rput_other will send down to IP.
18740 		 */
18741 		if (listener->tcp_bound_if != 0) {
18742 			/* allocate optmgmt req */
18743 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18744 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18745 			    sizeof (int));
18746 			if (mp != NULL)
18747 				linkb(opt_mp, mp);
18748 		}
18749 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18750 			uint_t on = 1;
18751 
18752 			/* allocate optmgmt req */
18753 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18754 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18755 			if (mp != NULL)
18756 				linkb(opt_mp, mp);
18757 		}
18758 
18759 
18760 		mutex_enter(&listener->tcp_eager_lock);
18761 
18762 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18763 
18764 			tcp_t *tail;
18765 			tcp_t *tcp;
18766 			mblk_t *mp1;
18767 
18768 			tcp = listener->tcp_eager_prev_q0;
18769 			/*
18770 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18771 			 * deferred T_conn_ind queue. We need to get to the head
18772 			 * of the queue in order to send up T_conn_ind the same
18773 			 * order as how the 3WHS is completed.
18774 			 */
18775 			while (tcp != listener) {
18776 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18777 				    !tcp->tcp_kssl_pending)
18778 					break;
18779 				else
18780 					tcp = tcp->tcp_eager_prev_q0;
18781 			}
18782 			/* None of the pending eagers can be sent up now */
18783 			if (tcp == listener)
18784 				goto no_more_eagers;
18785 
18786 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18787 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18788 			/* Move from q0 to q */
18789 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18790 			listener->tcp_conn_req_cnt_q0--;
18791 			listener->tcp_conn_req_cnt_q++;
18792 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18793 			    tcp->tcp_eager_prev_q0;
18794 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18795 			    tcp->tcp_eager_next_q0;
18796 			tcp->tcp_eager_prev_q0 = NULL;
18797 			tcp->tcp_eager_next_q0 = NULL;
18798 			tcp->tcp_conn_def_q0 = B_FALSE;
18799 
18800 			/* Make sure the tcp isn't in the list of droppables */
18801 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18802 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18803 
18804 			/*
18805 			 * Insert at end of the queue because sockfs sends
18806 			 * down T_CONN_RES in chronological order. Leaving
18807 			 * the older conn indications at front of the queue
18808 			 * helps reducing search time.
18809 			 */
18810 			tail = listener->tcp_eager_last_q;
18811 			if (tail != NULL) {
18812 				tail->tcp_eager_next_q = tcp;
18813 			} else {
18814 				listener->tcp_eager_next_q = tcp;
18815 			}
18816 			listener->tcp_eager_last_q = tcp;
18817 			tcp->tcp_eager_next_q = NULL;
18818 
18819 			/* Need to get inside the listener perimeter */
18820 			CONN_INC_REF(listener->tcp_connp);
18821 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18822 			    tcp_send_pending, listener->tcp_connp,
18823 			    SQTAG_TCP_SEND_PENDING);
18824 		}
18825 no_more_eagers:
18826 		tcp_eager_unlink(eager);
18827 		mutex_exit(&listener->tcp_eager_lock);
18828 
18829 		/*
18830 		 * At this point, the eager is detached from the listener
18831 		 * but we still have an extra refs on eager (apart from the
18832 		 * usual tcp references). The ref was placed in tcp_rput_data
18833 		 * before sending the conn_ind in tcp_send_conn_ind.
18834 		 * The ref will be dropped in tcp_accept_finish().
18835 		 */
18836 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18837 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18838 		return;
18839 	default:
18840 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18841 		if (mp != NULL)
18842 			putnext(rq, mp);
18843 		return;
18844 	}
18845 }
18846 
18847 static int
18848 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18849 {
18850 	sin_t *sin = (sin_t *)sa;
18851 	sin6_t *sin6 = (sin6_t *)sa;
18852 
18853 	switch (tcp->tcp_family) {
18854 	case AF_INET:
18855 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18856 
18857 		if (*salenp < sizeof (sin_t))
18858 			return (EINVAL);
18859 
18860 		*sin = sin_null;
18861 		sin->sin_family = AF_INET;
18862 		sin->sin_port = tcp->tcp_lport;
18863 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18864 		break;
18865 
18866 	case AF_INET6:
18867 		if (*salenp < sizeof (sin6_t))
18868 			return (EINVAL);
18869 
18870 		*sin6 = sin6_null;
18871 		sin6->sin6_family = AF_INET6;
18872 		sin6->sin6_port = tcp->tcp_lport;
18873 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18874 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18875 			    &sin6->sin6_addr);
18876 		} else {
18877 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18878 		}
18879 		break;
18880 	}
18881 
18882 	return (0);
18883 }
18884 
18885 static int
18886 tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18887 {
18888 	sin_t *sin = (sin_t *)sa;
18889 	sin6_t *sin6 = (sin6_t *)sa;
18890 
18891 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18892 		return (ENOTCONN);
18893 
18894 	switch (tcp->tcp_family) {
18895 	case AF_INET:
18896 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18897 
18898 		if (*salenp < sizeof (sin_t))
18899 			return (EINVAL);
18900 
18901 		*sin = sin_null;
18902 		sin->sin_family = AF_INET;
18903 		sin->sin_port = tcp->tcp_fport;
18904 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18905 		    sin->sin_addr.s_addr);
18906 		break;
18907 
18908 	case AF_INET6:
18909 		if (*salenp < sizeof (sin6_t))
18910 			return (EINVAL);
18911 
18912 		*sin6 = sin6_null;
18913 		sin6->sin6_family = AF_INET6;
18914 		sin6->sin6_port = tcp->tcp_fport;
18915 		sin6->sin6_addr = tcp->tcp_remote_v6;
18916 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18917 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18918 			    ~IPV6_VERS_AND_FLOW_MASK;
18919 		}
18920 		break;
18921 	}
18922 
18923 	return (0);
18924 }
18925 
18926 /*
18927  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18928  */
18929 static void
18930 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18931 {
18932 	void	*data;
18933 	mblk_t	*datamp = mp->b_cont;
18934 	tcp_t	*tcp = Q_TO_TCP(q);
18935 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18936 
18937 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18938 		cmdp->cb_error = EPROTO;
18939 		qreply(q, mp);
18940 		return;
18941 	}
18942 
18943 	data = datamp->b_rptr;
18944 
18945 	switch (cmdp->cb_cmd) {
18946 	case TI_GETPEERNAME:
18947 		cmdp->cb_error = tcp_getpeername(tcp, data, &cmdp->cb_len);
18948 		break;
18949 	case TI_GETMYNAME:
18950 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
18951 		break;
18952 	default:
18953 		cmdp->cb_error = EINVAL;
18954 		break;
18955 	}
18956 
18957 	qreply(q, mp);
18958 }
18959 
18960 void
18961 tcp_wput(queue_t *q, mblk_t *mp)
18962 {
18963 	conn_t	*connp = Q_TO_CONN(q);
18964 	tcp_t	*tcp;
18965 	void (*output_proc)();
18966 	t_scalar_t type;
18967 	uchar_t *rptr;
18968 	struct iocblk	*iocp;
18969 	uint32_t	msize;
18970 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18971 
18972 	ASSERT(connp->conn_ref >= 2);
18973 
18974 	switch (DB_TYPE(mp)) {
18975 	case M_DATA:
18976 		tcp = connp->conn_tcp;
18977 		ASSERT(tcp != NULL);
18978 
18979 		msize = msgdsize(mp);
18980 
18981 		mutex_enter(&tcp->tcp_non_sq_lock);
18982 		tcp->tcp_squeue_bytes += msize;
18983 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18984 			tcp_setqfull(tcp);
18985 		}
18986 		mutex_exit(&tcp->tcp_non_sq_lock);
18987 
18988 		CONN_INC_REF(connp);
18989 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18990 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18991 		return;
18992 
18993 	case M_CMD:
18994 		tcp_wput_cmdblk(q, mp);
18995 		return;
18996 
18997 	case M_PROTO:
18998 	case M_PCPROTO:
18999 		/*
19000 		 * if it is a snmp message, don't get behind the squeue
19001 		 */
19002 		tcp = connp->conn_tcp;
19003 		rptr = mp->b_rptr;
19004 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
19005 			type = ((union T_primitives *)rptr)->type;
19006 		} else {
19007 			if (tcp->tcp_debug) {
19008 				(void) strlog(TCP_MOD_ID, 0, 1,
19009 				    SL_ERROR|SL_TRACE,
19010 				    "tcp_wput_proto, dropping one...");
19011 			}
19012 			freemsg(mp);
19013 			return;
19014 		}
19015 		if (type == T_SVR4_OPTMGMT_REQ) {
19016 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
19017 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
19018 			    cr)) {
19019 				/*
19020 				 * This was a SNMP request
19021 				 */
19022 				return;
19023 			} else {
19024 				output_proc = tcp_wput_proto;
19025 			}
19026 		} else {
19027 			output_proc = tcp_wput_proto;
19028 		}
19029 		break;
19030 	case M_IOCTL:
19031 		/*
19032 		 * Most ioctls can be processed right away without going via
19033 		 * squeues - process them right here. Those that do require
19034 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
19035 		 * are processed by tcp_wput_ioctl().
19036 		 */
19037 		iocp = (struct iocblk *)mp->b_rptr;
19038 		tcp = connp->conn_tcp;
19039 
19040 		switch (iocp->ioc_cmd) {
19041 		case TCP_IOC_ABORT_CONN:
19042 			tcp_ioctl_abort_conn(q, mp);
19043 			return;
19044 		case TI_GETPEERNAME:
19045 		case TI_GETMYNAME:
19046 			mi_copyin(q, mp, NULL,
19047 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
19048 			return;
19049 		case ND_SET:
19050 			/* nd_getset does the necessary checks */
19051 		case ND_GET:
19052 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
19053 				CALL_IP_WPUT(connp, q, mp);
19054 				return;
19055 			}
19056 			qreply(q, mp);
19057 			return;
19058 		case TCP_IOC_DEFAULT_Q:
19059 			/*
19060 			 * Wants to be the default wq. Check the credentials
19061 			 * first, the rest is executed via squeue.
19062 			 */
19063 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19064 				iocp->ioc_error = EPERM;
19065 				iocp->ioc_count = 0;
19066 				mp->b_datap->db_type = M_IOCACK;
19067 				qreply(q, mp);
19068 				return;
19069 			}
19070 			output_proc = tcp_wput_ioctl;
19071 			break;
19072 		default:
19073 			output_proc = tcp_wput_ioctl;
19074 			break;
19075 		}
19076 		break;
19077 	default:
19078 		output_proc = tcp_wput_nondata;
19079 		break;
19080 	}
19081 
19082 	CONN_INC_REF(connp);
19083 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
19084 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
19085 }
19086 
19087 /*
19088  * Initial STREAMS write side put() procedure for sockets. It tries to
19089  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
19090  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
19091  * are handled by tcp_wput() as usual.
19092  *
19093  * All further messages will also be handled by tcp_wput() because we cannot
19094  * be sure that the above short cut is safe later.
19095  */
19096 static void
19097 tcp_wput_sock(queue_t *wq, mblk_t *mp)
19098 {
19099 	conn_t			*connp = Q_TO_CONN(wq);
19100 	tcp_t			*tcp = connp->conn_tcp;
19101 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
19102 
19103 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
19104 	wq->q_qinfo = &tcp_winit;
19105 
19106 	ASSERT(IPCL_IS_TCP(connp));
19107 	ASSERT(TCP_IS_SOCKET(tcp));
19108 
19109 	if (DB_TYPE(mp) == M_PCPROTO &&
19110 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
19111 	    car->PRIM_type == T_CAPABILITY_REQ) {
19112 		tcp_capability_req(tcp, mp);
19113 		return;
19114 	}
19115 
19116 	tcp_wput(wq, mp);
19117 }
19118 
19119 static boolean_t
19120 tcp_zcopy_check(tcp_t *tcp)
19121 {
19122 	conn_t	*connp = tcp->tcp_connp;
19123 	ire_t	*ire;
19124 	boolean_t	zc_enabled = B_FALSE;
19125 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19126 
19127 	if (do_tcpzcopy == 2)
19128 		zc_enabled = B_TRUE;
19129 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
19130 	    IPCL_IS_CONNECTED(connp) &&
19131 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
19132 	    connp->conn_dontroute == 0 &&
19133 	    !connp->conn_nexthop_set &&
19134 	    connp->conn_outgoing_ill == NULL &&
19135 	    connp->conn_nofailover_ill == NULL &&
19136 	    do_tcpzcopy == 1) {
19137 		/*
19138 		 * the checks above  closely resemble the fast path checks
19139 		 * in tcp_send_data().
19140 		 */
19141 		mutex_enter(&connp->conn_lock);
19142 		ire = connp->conn_ire_cache;
19143 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19144 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19145 			IRE_REFHOLD(ire);
19146 			if (ire->ire_stq != NULL) {
19147 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
19148 
19149 				zc_enabled = ill && (ill->ill_capabilities &
19150 				    ILL_CAPAB_ZEROCOPY) &&
19151 				    (ill->ill_zerocopy_capab->
19152 				    ill_zerocopy_flags != 0);
19153 			}
19154 			IRE_REFRELE(ire);
19155 		}
19156 		mutex_exit(&connp->conn_lock);
19157 	}
19158 	tcp->tcp_snd_zcopy_on = zc_enabled;
19159 	if (!TCP_IS_DETACHED(tcp)) {
19160 		if (zc_enabled) {
19161 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
19162 			TCP_STAT(tcps, tcp_zcopy_on);
19163 		} else {
19164 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19165 			TCP_STAT(tcps, tcp_zcopy_off);
19166 		}
19167 	}
19168 	return (zc_enabled);
19169 }
19170 
19171 static mblk_t *
19172 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
19173 {
19174 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19175 
19176 	if (do_tcpzcopy == 2)
19177 		return (bp);
19178 	else if (tcp->tcp_snd_zcopy_on) {
19179 		tcp->tcp_snd_zcopy_on = B_FALSE;
19180 		if (!TCP_IS_DETACHED(tcp)) {
19181 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19182 			TCP_STAT(tcps, tcp_zcopy_disable);
19183 		}
19184 	}
19185 	return (tcp_zcopy_backoff(tcp, bp, 0));
19186 }
19187 
19188 /*
19189  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
19190  * the original desballoca'ed segmapped mblk.
19191  */
19192 static mblk_t *
19193 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
19194 {
19195 	mblk_t *head, *tail, *nbp;
19196 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19197 
19198 	if (IS_VMLOANED_MBLK(bp)) {
19199 		TCP_STAT(tcps, tcp_zcopy_backoff);
19200 		if ((head = copyb(bp)) == NULL) {
19201 			/* fail to backoff; leave it for the next backoff */
19202 			tcp->tcp_xmit_zc_clean = B_FALSE;
19203 			return (bp);
19204 		}
19205 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19206 			if (fix_xmitlist)
19207 				tcp_zcopy_notify(tcp);
19208 			else
19209 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19210 		}
19211 		nbp = bp->b_cont;
19212 		if (fix_xmitlist) {
19213 			head->b_prev = bp->b_prev;
19214 			head->b_next = bp->b_next;
19215 			if (tcp->tcp_xmit_tail == bp)
19216 				tcp->tcp_xmit_tail = head;
19217 		}
19218 		bp->b_next = NULL;
19219 		bp->b_prev = NULL;
19220 		freeb(bp);
19221 	} else {
19222 		head = bp;
19223 		nbp = bp->b_cont;
19224 	}
19225 	tail = head;
19226 	while (nbp) {
19227 		if (IS_VMLOANED_MBLK(nbp)) {
19228 			TCP_STAT(tcps, tcp_zcopy_backoff);
19229 			if ((tail->b_cont = copyb(nbp)) == NULL) {
19230 				tcp->tcp_xmit_zc_clean = B_FALSE;
19231 				tail->b_cont = nbp;
19232 				return (head);
19233 			}
19234 			tail = tail->b_cont;
19235 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19236 				if (fix_xmitlist)
19237 					tcp_zcopy_notify(tcp);
19238 				else
19239 					tail->b_datap->db_struioflag |=
19240 					    STRUIO_ZCNOTIFY;
19241 			}
19242 			bp = nbp;
19243 			nbp = nbp->b_cont;
19244 			if (fix_xmitlist) {
19245 				tail->b_prev = bp->b_prev;
19246 				tail->b_next = bp->b_next;
19247 				if (tcp->tcp_xmit_tail == bp)
19248 					tcp->tcp_xmit_tail = tail;
19249 			}
19250 			bp->b_next = NULL;
19251 			bp->b_prev = NULL;
19252 			freeb(bp);
19253 		} else {
19254 			tail->b_cont = nbp;
19255 			tail = nbp;
19256 			nbp = nbp->b_cont;
19257 		}
19258 	}
19259 	if (fix_xmitlist) {
19260 		tcp->tcp_xmit_last = tail;
19261 		tcp->tcp_xmit_zc_clean = B_TRUE;
19262 	}
19263 	return (head);
19264 }
19265 
19266 static void
19267 tcp_zcopy_notify(tcp_t *tcp)
19268 {
19269 	struct stdata	*stp;
19270 
19271 	if (tcp->tcp_detached)
19272 		return;
19273 	stp = STREAM(tcp->tcp_rq);
19274 	mutex_enter(&stp->sd_lock);
19275 	stp->sd_flag |= STZCNOTIFY;
19276 	cv_broadcast(&stp->sd_zcopy_wait);
19277 	mutex_exit(&stp->sd_lock);
19278 }
19279 
19280 static boolean_t
19281 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19282 {
19283 	ire_t	*ire;
19284 	conn_t	*connp = tcp->tcp_connp;
19285 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19286 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19287 
19288 	mutex_enter(&connp->conn_lock);
19289 	ire = connp->conn_ire_cache;
19290 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19291 
19292 	if ((ire != NULL) &&
19293 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19294 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19295 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19296 		IRE_REFHOLD(ire);
19297 		mutex_exit(&connp->conn_lock);
19298 	} else {
19299 		boolean_t cached = B_FALSE;
19300 		ts_label_t *tsl;
19301 
19302 		/* force a recheck later on */
19303 		tcp->tcp_ire_ill_check_done = B_FALSE;
19304 
19305 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19306 		connp->conn_ire_cache = NULL;
19307 		mutex_exit(&connp->conn_lock);
19308 
19309 		if (ire != NULL)
19310 			IRE_REFRELE_NOTR(ire);
19311 
19312 		tsl = crgetlabel(CONN_CRED(connp));
19313 		ire = (dst ?
19314 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19315 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19316 		    connp->conn_zoneid, tsl, ipst));
19317 
19318 		if (ire == NULL) {
19319 			TCP_STAT(tcps, tcp_ire_null);
19320 			return (B_FALSE);
19321 		}
19322 
19323 		IRE_REFHOLD_NOTR(ire);
19324 
19325 		mutex_enter(&connp->conn_lock);
19326 		if (CONN_CACHE_IRE(connp)) {
19327 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19328 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19329 				TCP_CHECK_IREINFO(tcp, ire);
19330 				connp->conn_ire_cache = ire;
19331 				cached = B_TRUE;
19332 			}
19333 			rw_exit(&ire->ire_bucket->irb_lock);
19334 		}
19335 		mutex_exit(&connp->conn_lock);
19336 
19337 		/*
19338 		 * We can continue to use the ire but since it was
19339 		 * not cached, we should drop the extra reference.
19340 		 */
19341 		if (!cached)
19342 			IRE_REFRELE_NOTR(ire);
19343 
19344 		/*
19345 		 * Rampart note: no need to select a new label here, since
19346 		 * labels are not allowed to change during the life of a TCP
19347 		 * connection.
19348 		 */
19349 	}
19350 
19351 	*irep = ire;
19352 
19353 	return (B_TRUE);
19354 }
19355 
19356 /*
19357  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19358  *
19359  * 0 = success;
19360  * 1 = failed to find ire and ill.
19361  */
19362 static boolean_t
19363 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19364 {
19365 	ipha_t		*ipha;
19366 	ipaddr_t	dst;
19367 	ire_t		*ire;
19368 	ill_t		*ill;
19369 	conn_t		*connp = tcp->tcp_connp;
19370 	mblk_t		*ire_fp_mp;
19371 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19372 
19373 	if (mp != NULL)
19374 		ipha = (ipha_t *)mp->b_rptr;
19375 	else
19376 		ipha = tcp->tcp_ipha;
19377 	dst = ipha->ipha_dst;
19378 
19379 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19380 		return (B_FALSE);
19381 
19382 	if ((ire->ire_flags & RTF_MULTIRT) ||
19383 	    (ire->ire_stq == NULL) ||
19384 	    (ire->ire_nce == NULL) ||
19385 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19386 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19387 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19388 		TCP_STAT(tcps, tcp_ip_ire_send);
19389 		IRE_REFRELE(ire);
19390 		return (B_FALSE);
19391 	}
19392 
19393 	ill = ire_to_ill(ire);
19394 	if (connp->conn_outgoing_ill != NULL) {
19395 		ill_t *conn_outgoing_ill = NULL;
19396 		/*
19397 		 * Choose a good ill in the group to send the packets on.
19398 		 */
19399 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
19400 		ill = ire_to_ill(ire);
19401 	}
19402 	ASSERT(ill != NULL);
19403 
19404 	if (!tcp->tcp_ire_ill_check_done) {
19405 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19406 		tcp->tcp_ire_ill_check_done = B_TRUE;
19407 	}
19408 
19409 	*irep = ire;
19410 	*illp = ill;
19411 
19412 	return (B_TRUE);
19413 }
19414 
19415 static void
19416 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19417 {
19418 	ipha_t		*ipha;
19419 	ipaddr_t	src;
19420 	ipaddr_t	dst;
19421 	uint32_t	cksum;
19422 	ire_t		*ire;
19423 	uint16_t	*up;
19424 	ill_t		*ill;
19425 	conn_t		*connp = tcp->tcp_connp;
19426 	uint32_t	hcksum_txflags = 0;
19427 	mblk_t		*ire_fp_mp;
19428 	uint_t		ire_fp_mp_len;
19429 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19430 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19431 
19432 	ASSERT(DB_TYPE(mp) == M_DATA);
19433 
19434 	if (DB_CRED(mp) == NULL)
19435 		mblk_setcred(mp, CONN_CRED(connp));
19436 
19437 	ipha = (ipha_t *)mp->b_rptr;
19438 	src = ipha->ipha_src;
19439 	dst = ipha->ipha_dst;
19440 
19441 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19442 
19443 	/*
19444 	 * Drop off fast path for IPv6 and also if options are present or
19445 	 * we need to resolve a TS label.
19446 	 */
19447 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19448 	    !IPCL_IS_CONNECTED(connp) ||
19449 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19450 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19451 	    !connp->conn_ulp_labeled ||
19452 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19453 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19454 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19455 		if (tcp->tcp_snd_zcopy_aware)
19456 			mp = tcp_zcopy_disable(tcp, mp);
19457 		TCP_STAT(tcps, tcp_ip_send);
19458 		CALL_IP_WPUT(connp, q, mp);
19459 		return;
19460 	}
19461 
19462 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19463 		if (tcp->tcp_snd_zcopy_aware)
19464 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19465 		CALL_IP_WPUT(connp, q, mp);
19466 		return;
19467 	}
19468 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19469 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19470 
19471 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19472 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19473 #ifndef _BIG_ENDIAN
19474 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19475 #endif
19476 
19477 	/*
19478 	 * Check to see if we need to re-enable LSO/MDT for this connection
19479 	 * because it was previously disabled due to changes in the ill;
19480 	 * note that by doing it here, this re-enabling only applies when
19481 	 * the packet is not dispatched through CALL_IP_WPUT().
19482 	 *
19483 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19484 	 * case, since that's how we ended up here.  For IPv6, we do the
19485 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19486 	 */
19487 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19488 		/*
19489 		 * Restore LSO for this connection, so that next time around
19490 		 * it is eligible to go through tcp_lsosend() path again.
19491 		 */
19492 		TCP_STAT(tcps, tcp_lso_enabled);
19493 		tcp->tcp_lso = B_TRUE;
19494 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19495 		    "interface %s\n", (void *)connp, ill->ill_name));
19496 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19497 		/*
19498 		 * Restore MDT for this connection, so that next time around
19499 		 * it is eligible to go through tcp_multisend() path again.
19500 		 */
19501 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19502 		tcp->tcp_mdt = B_TRUE;
19503 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19504 		    "interface %s\n", (void *)connp, ill->ill_name));
19505 	}
19506 
19507 	if (tcp->tcp_snd_zcopy_aware) {
19508 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19509 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19510 			mp = tcp_zcopy_disable(tcp, mp);
19511 		/*
19512 		 * we shouldn't need to reset ipha as the mp containing
19513 		 * ipha should never be a zero-copy mp.
19514 		 */
19515 	}
19516 
19517 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19518 		ASSERT(ill->ill_hcksum_capab != NULL);
19519 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19520 	}
19521 
19522 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19523 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19524 
19525 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19526 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19527 
19528 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19529 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19530 
19531 	/* Software checksum? */
19532 	if (DB_CKSUMFLAGS(mp) == 0) {
19533 		TCP_STAT(tcps, tcp_out_sw_cksum);
19534 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19535 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19536 	}
19537 
19538 	ipha->ipha_fragment_offset_and_flags |=
19539 	    (uint32_t)htons(ire->ire_frag_flag);
19540 
19541 	/* Calculate IP header checksum if hardware isn't capable */
19542 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19543 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19544 		    ((uint16_t *)ipha)[4]);
19545 	}
19546 
19547 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19548 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19549 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19550 
19551 	UPDATE_OB_PKT_COUNT(ire);
19552 	ire->ire_last_used_time = lbolt;
19553 
19554 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19555 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19556 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19557 	    ntohs(ipha->ipha_length));
19558 
19559 	if (ILL_DLS_CAPABLE(ill)) {
19560 		/*
19561 		 * Send the packet directly to DLD, where it may be queued
19562 		 * depending on the availability of transmit resources at
19563 		 * the media layer.
19564 		 */
19565 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
19566 	} else {
19567 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
19568 		DTRACE_PROBE4(ip4__physical__out__start,
19569 		    ill_t *, NULL, ill_t *, out_ill,
19570 		    ipha_t *, ipha, mblk_t *, mp);
19571 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
19572 		    ipst->ips_ipv4firewall_physical_out,
19573 		    NULL, out_ill, ipha, mp, mp, 0, ipst);
19574 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19575 
19576 		if (mp != NULL) {
19577 			DTRACE_IP_FASTPATH(mp, ipha, out_ill, ipha, NULL);
19578 			putnext(ire->ire_stq, mp);
19579 		}
19580 	}
19581 	IRE_REFRELE(ire);
19582 }
19583 
19584 /*
19585  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19586  * if the receiver shrinks the window, i.e. moves the right window to the
19587  * left, the we should not send new data, but should retransmit normally the
19588  * old unacked data between suna and suna + swnd. We might has sent data
19589  * that is now outside the new window, pretend that we didn't send  it.
19590  */
19591 static void
19592 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19593 {
19594 	uint32_t	snxt = tcp->tcp_snxt;
19595 	mblk_t		*xmit_tail;
19596 	int32_t		offset;
19597 
19598 	ASSERT(shrunk_count > 0);
19599 
19600 	/* Pretend we didn't send the data outside the window */
19601 	snxt -= shrunk_count;
19602 
19603 	/* Get the mblk and the offset in it per the shrunk window */
19604 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19605 
19606 	ASSERT(xmit_tail != NULL);
19607 
19608 	/* Reset all the values per the now shrunk window */
19609 	tcp->tcp_snxt = snxt;
19610 	tcp->tcp_xmit_tail = xmit_tail;
19611 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19612 	    offset;
19613 	tcp->tcp_unsent += shrunk_count;
19614 
19615 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19616 		/*
19617 		 * Make sure the timer is running so that we will probe a zero
19618 		 * window.
19619 		 */
19620 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19621 }
19622 
19623 
19624 /*
19625  * The TCP normal data output path.
19626  * NOTE: the logic of the fast path is duplicated from this function.
19627  */
19628 static void
19629 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19630 {
19631 	int		len;
19632 	mblk_t		*local_time;
19633 	mblk_t		*mp1;
19634 	uint32_t	snxt;
19635 	int		tail_unsent;
19636 	int		tcpstate;
19637 	int		usable = 0;
19638 	mblk_t		*xmit_tail;
19639 	queue_t		*q = tcp->tcp_wq;
19640 	int32_t		mss;
19641 	int32_t		num_sack_blk = 0;
19642 	int32_t		tcp_hdr_len;
19643 	int32_t		tcp_tcp_hdr_len;
19644 	int		mdt_thres;
19645 	int		rc;
19646 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19647 	ip_stack_t	*ipst;
19648 
19649 	tcpstate = tcp->tcp_state;
19650 	if (mp == NULL) {
19651 		/*
19652 		 * tcp_wput_data() with NULL mp should only be called when
19653 		 * there is unsent data.
19654 		 */
19655 		ASSERT(tcp->tcp_unsent > 0);
19656 		/* Really tacky... but we need this for detached closes. */
19657 		len = tcp->tcp_unsent;
19658 		goto data_null;
19659 	}
19660 
19661 #if CCS_STATS
19662 	wrw_stats.tot.count++;
19663 	wrw_stats.tot.bytes += msgdsize(mp);
19664 #endif
19665 	ASSERT(mp->b_datap->db_type == M_DATA);
19666 	/*
19667 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19668 	 * or before a connection attempt has begun.
19669 	 */
19670 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19671 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19672 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19673 #ifdef DEBUG
19674 			cmn_err(CE_WARN,
19675 			    "tcp_wput_data: data after ordrel, %s",
19676 			    tcp_display(tcp, NULL,
19677 			    DISP_ADDR_AND_PORT));
19678 #else
19679 			if (tcp->tcp_debug) {
19680 				(void) strlog(TCP_MOD_ID, 0, 1,
19681 				    SL_TRACE|SL_ERROR,
19682 				    "tcp_wput_data: data after ordrel, %s\n",
19683 				    tcp_display(tcp, NULL,
19684 				    DISP_ADDR_AND_PORT));
19685 			}
19686 #endif /* DEBUG */
19687 		}
19688 		if (tcp->tcp_snd_zcopy_aware &&
19689 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19690 			tcp_zcopy_notify(tcp);
19691 		freemsg(mp);
19692 		mutex_enter(&tcp->tcp_non_sq_lock);
19693 		if (tcp->tcp_flow_stopped &&
19694 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19695 			tcp_clrqfull(tcp);
19696 		}
19697 		mutex_exit(&tcp->tcp_non_sq_lock);
19698 		return;
19699 	}
19700 
19701 	/* Strip empties */
19702 	for (;;) {
19703 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19704 		    (uintptr_t)INT_MAX);
19705 		len = (int)(mp->b_wptr - mp->b_rptr);
19706 		if (len > 0)
19707 			break;
19708 		mp1 = mp;
19709 		mp = mp->b_cont;
19710 		freeb(mp1);
19711 		if (!mp) {
19712 			return;
19713 		}
19714 	}
19715 
19716 	/* If we are the first on the list ... */
19717 	if (tcp->tcp_xmit_head == NULL) {
19718 		tcp->tcp_xmit_head = mp;
19719 		tcp->tcp_xmit_tail = mp;
19720 		tcp->tcp_xmit_tail_unsent = len;
19721 	} else {
19722 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19723 		struct datab *dp;
19724 
19725 		mp1 = tcp->tcp_xmit_last;
19726 		if (len < tcp_tx_pull_len &&
19727 		    (dp = mp1->b_datap)->db_ref == 1 &&
19728 		    dp->db_lim - mp1->b_wptr >= len) {
19729 			ASSERT(len > 0);
19730 			ASSERT(!mp1->b_cont);
19731 			if (len == 1) {
19732 				*mp1->b_wptr++ = *mp->b_rptr;
19733 			} else {
19734 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19735 				mp1->b_wptr += len;
19736 			}
19737 			if (mp1 == tcp->tcp_xmit_tail)
19738 				tcp->tcp_xmit_tail_unsent += len;
19739 			mp1->b_cont = mp->b_cont;
19740 			if (tcp->tcp_snd_zcopy_aware &&
19741 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19742 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19743 			freeb(mp);
19744 			mp = mp1;
19745 		} else {
19746 			tcp->tcp_xmit_last->b_cont = mp;
19747 		}
19748 		len += tcp->tcp_unsent;
19749 	}
19750 
19751 	/* Tack on however many more positive length mblks we have */
19752 	if ((mp1 = mp->b_cont) != NULL) {
19753 		do {
19754 			int tlen;
19755 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19756 			    (uintptr_t)INT_MAX);
19757 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19758 			if (tlen <= 0) {
19759 				mp->b_cont = mp1->b_cont;
19760 				freeb(mp1);
19761 			} else {
19762 				len += tlen;
19763 				mp = mp1;
19764 			}
19765 		} while ((mp1 = mp->b_cont) != NULL);
19766 	}
19767 	tcp->tcp_xmit_last = mp;
19768 	tcp->tcp_unsent = len;
19769 
19770 	if (urgent)
19771 		usable = 1;
19772 
19773 data_null:
19774 	snxt = tcp->tcp_snxt;
19775 	xmit_tail = tcp->tcp_xmit_tail;
19776 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19777 
19778 	/*
19779 	 * Note that tcp_mss has been adjusted to take into account the
19780 	 * timestamp option if applicable.  Because SACK options do not
19781 	 * appear in every TCP segments and they are of variable lengths,
19782 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19783 	 * the actual segment length when we need to send a segment which
19784 	 * includes SACK options.
19785 	 */
19786 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19787 		int32_t	opt_len;
19788 
19789 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19790 		    tcp->tcp_num_sack_blk);
19791 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19792 		    2 + TCPOPT_HEADER_LEN;
19793 		mss = tcp->tcp_mss - opt_len;
19794 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19795 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19796 	} else {
19797 		mss = tcp->tcp_mss;
19798 		tcp_hdr_len = tcp->tcp_hdr_len;
19799 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19800 	}
19801 
19802 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19803 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19804 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19805 	}
19806 	if (tcpstate == TCPS_SYN_RCVD) {
19807 		/*
19808 		 * The three-way connection establishment handshake is not
19809 		 * complete yet. We want to queue the data for transmission
19810 		 * after entering ESTABLISHED state (RFC793). A jump to
19811 		 * "done" label effectively leaves data on the queue.
19812 		 */
19813 		goto done;
19814 	} else {
19815 		int usable_r;
19816 
19817 		/*
19818 		 * In the special case when cwnd is zero, which can only
19819 		 * happen if the connection is ECN capable, return now.
19820 		 * New segments is sent using tcp_timer().  The timer
19821 		 * is set in tcp_rput_data().
19822 		 */
19823 		if (tcp->tcp_cwnd == 0) {
19824 			/*
19825 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19826 			 * finished.
19827 			 */
19828 			ASSERT(tcp->tcp_ecn_ok ||
19829 			    tcp->tcp_state < TCPS_ESTABLISHED);
19830 			return;
19831 		}
19832 
19833 		/* NOTE: trouble if xmitting while SYN not acked? */
19834 		usable_r = snxt - tcp->tcp_suna;
19835 		usable_r = tcp->tcp_swnd - usable_r;
19836 
19837 		/*
19838 		 * Check if the receiver has shrunk the window.  If
19839 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19840 		 * cannot be set as there is unsent data, so FIN cannot
19841 		 * be sent out.  Otherwise, we need to take into account
19842 		 * of FIN as it consumes an "invisible" sequence number.
19843 		 */
19844 		ASSERT(tcp->tcp_fin_sent == 0);
19845 		if (usable_r < 0) {
19846 			/*
19847 			 * The receiver has shrunk the window and we have sent
19848 			 * -usable_r date beyond the window, re-adjust.
19849 			 *
19850 			 * If TCP window scaling is enabled, there can be
19851 			 * round down error as the advertised receive window
19852 			 * is actually right shifted n bits.  This means that
19853 			 * the lower n bits info is wiped out.  It will look
19854 			 * like the window is shrunk.  Do a check here to
19855 			 * see if the shrunk amount is actually within the
19856 			 * error in window calculation.  If it is, just
19857 			 * return.  Note that this check is inside the
19858 			 * shrunk window check.  This makes sure that even
19859 			 * though tcp_process_shrunk_swnd() is not called,
19860 			 * we will stop further processing.
19861 			 */
19862 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19863 				tcp_process_shrunk_swnd(tcp, -usable_r);
19864 			}
19865 			return;
19866 		}
19867 
19868 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19869 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19870 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19871 
19872 		/* usable = MIN(usable, unsent) */
19873 		if (usable_r > len)
19874 			usable_r = len;
19875 
19876 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19877 		if (usable_r > 0) {
19878 			usable = usable_r;
19879 		} else {
19880 			/* Bypass all other unnecessary processing. */
19881 			goto done;
19882 		}
19883 	}
19884 
19885 	local_time = (mblk_t *)lbolt;
19886 
19887 	/*
19888 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19889 	 * BSD.  This is more in line with the true intent of Nagle.
19890 	 *
19891 	 * The conditions are:
19892 	 * 1. The amount of unsent data (or amount of data which can be
19893 	 *    sent, whichever is smaller) is less than Nagle limit.
19894 	 * 2. The last sent size is also less than Nagle limit.
19895 	 * 3. There is unack'ed data.
19896 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19897 	 *    Nagle algorithm.  This reduces the probability that urgent
19898 	 *    bytes get "merged" together.
19899 	 * 5. The app has not closed the connection.  This eliminates the
19900 	 *    wait time of the receiving side waiting for the last piece of
19901 	 *    (small) data.
19902 	 *
19903 	 * If all are satisified, exit without sending anything.  Note
19904 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19905 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19906 	 * 4095).
19907 	 */
19908 	if (usable < (int)tcp->tcp_naglim &&
19909 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19910 	    snxt != tcp->tcp_suna &&
19911 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19912 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19913 		goto done;
19914 	}
19915 
19916 	if (tcp->tcp_cork) {
19917 		/*
19918 		 * if the tcp->tcp_cork option is set, then we have to force
19919 		 * TCP not to send partial segment (smaller than MSS bytes).
19920 		 * We are calculating the usable now based on full mss and
19921 		 * will save the rest of remaining data for later.
19922 		 */
19923 		if (usable < mss)
19924 			goto done;
19925 		usable = (usable / mss) * mss;
19926 	}
19927 
19928 	/* Update the latest receive window size in TCP header. */
19929 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19930 	    tcp->tcp_tcph->th_win);
19931 
19932 	/*
19933 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19934 	 *
19935 	 * 1. Simple TCP/IP{v4,v6} (no options).
19936 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19937 	 * 3. If the TCP connection is in ESTABLISHED state.
19938 	 * 4. The TCP is not detached.
19939 	 *
19940 	 * If any of the above conditions have changed during the
19941 	 * connection, stop using LSO/MDT and restore the stream head
19942 	 * parameters accordingly.
19943 	 */
19944 	ipst = tcps->tcps_netstack->netstack_ip;
19945 
19946 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19947 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19948 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19949 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19950 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19951 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19952 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19953 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19954 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19955 		if (tcp->tcp_lso) {
19956 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19957 			tcp->tcp_lso = B_FALSE;
19958 		} else {
19959 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19960 			tcp->tcp_mdt = B_FALSE;
19961 		}
19962 
19963 		/* Anything other than detached is considered pathological */
19964 		if (!TCP_IS_DETACHED(tcp)) {
19965 			if (tcp->tcp_lso)
19966 				TCP_STAT(tcps, tcp_lso_disabled);
19967 			else
19968 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19969 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19970 		}
19971 	}
19972 
19973 	/* Use MDT if sendable amount is greater than the threshold */
19974 	if (tcp->tcp_mdt &&
19975 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19976 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19977 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19978 	    (tcp->tcp_valid_bits == 0 ||
19979 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19980 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19981 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19982 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19983 		    local_time, mdt_thres);
19984 	} else {
19985 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19986 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19987 		    local_time, INT_MAX);
19988 	}
19989 
19990 	/* Pretend that all we were trying to send really got sent */
19991 	if (rc < 0 && tail_unsent < 0) {
19992 		do {
19993 			xmit_tail = xmit_tail->b_cont;
19994 			xmit_tail->b_prev = local_time;
19995 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19996 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19997 			tail_unsent += (int)(xmit_tail->b_wptr -
19998 			    xmit_tail->b_rptr);
19999 		} while (tail_unsent < 0);
20000 	}
20001 done:;
20002 	tcp->tcp_xmit_tail = xmit_tail;
20003 	tcp->tcp_xmit_tail_unsent = tail_unsent;
20004 	len = tcp->tcp_snxt - snxt;
20005 	if (len) {
20006 		/*
20007 		 * If new data was sent, need to update the notsack
20008 		 * list, which is, afterall, data blocks that have
20009 		 * not been sack'ed by the receiver.  New data is
20010 		 * not sack'ed.
20011 		 */
20012 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
20013 			/* len is a negative value. */
20014 			tcp->tcp_pipe -= len;
20015 			tcp_notsack_update(&(tcp->tcp_notsack_list),
20016 			    tcp->tcp_snxt, snxt,
20017 			    &(tcp->tcp_num_notsack_blk),
20018 			    &(tcp->tcp_cnt_notsack_list));
20019 		}
20020 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
20021 		tcp->tcp_rack = tcp->tcp_rnxt;
20022 		tcp->tcp_rack_cnt = 0;
20023 		if ((snxt + len) == tcp->tcp_suna) {
20024 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20025 		}
20026 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
20027 		/*
20028 		 * Didn't send anything. Make sure the timer is running
20029 		 * so that we will probe a zero window.
20030 		 */
20031 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20032 	}
20033 	/* Note that len is the amount we just sent but with a negative sign */
20034 	tcp->tcp_unsent += len;
20035 	mutex_enter(&tcp->tcp_non_sq_lock);
20036 	if (tcp->tcp_flow_stopped) {
20037 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
20038 			tcp_clrqfull(tcp);
20039 		}
20040 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
20041 		tcp_setqfull(tcp);
20042 	}
20043 	mutex_exit(&tcp->tcp_non_sq_lock);
20044 }
20045 
20046 /*
20047  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
20048  * outgoing TCP header with the template header, as well as other
20049  * options such as time-stamp, ECN and/or SACK.
20050  */
20051 static void
20052 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
20053 {
20054 	tcph_t *tcp_tmpl, *tcp_h;
20055 	uint32_t *dst, *src;
20056 	int hdrlen;
20057 
20058 	ASSERT(OK_32PTR(rptr));
20059 
20060 	/* Template header */
20061 	tcp_tmpl = tcp->tcp_tcph;
20062 
20063 	/* Header of outgoing packet */
20064 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20065 
20066 	/* dst and src are opaque 32-bit fields, used for copying */
20067 	dst = (uint32_t *)rptr;
20068 	src = (uint32_t *)tcp->tcp_iphc;
20069 	hdrlen = tcp->tcp_hdr_len;
20070 
20071 	/* Fill time-stamp option if needed */
20072 	if (tcp->tcp_snd_ts_ok) {
20073 		U32_TO_BE32((uint32_t)now,
20074 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
20075 		U32_TO_BE32(tcp->tcp_ts_recent,
20076 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
20077 	} else {
20078 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
20079 	}
20080 
20081 	/*
20082 	 * Copy the template header; is this really more efficient than
20083 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
20084 	 * but perhaps not for other scenarios.
20085 	 */
20086 	dst[0] = src[0];
20087 	dst[1] = src[1];
20088 	dst[2] = src[2];
20089 	dst[3] = src[3];
20090 	dst[4] = src[4];
20091 	dst[5] = src[5];
20092 	dst[6] = src[6];
20093 	dst[7] = src[7];
20094 	dst[8] = src[8];
20095 	dst[9] = src[9];
20096 	if (hdrlen -= 40) {
20097 		hdrlen >>= 2;
20098 		dst += 10;
20099 		src += 10;
20100 		do {
20101 			*dst++ = *src++;
20102 		} while (--hdrlen);
20103 	}
20104 
20105 	/*
20106 	 * Set the ECN info in the TCP header if it is not a zero
20107 	 * window probe.  Zero window probe is only sent in
20108 	 * tcp_wput_data() and tcp_timer().
20109 	 */
20110 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
20111 		SET_ECT(tcp, rptr);
20112 
20113 		if (tcp->tcp_ecn_echo_on)
20114 			tcp_h->th_flags[0] |= TH_ECE;
20115 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
20116 			tcp_h->th_flags[0] |= TH_CWR;
20117 			tcp->tcp_ecn_cwr_sent = B_TRUE;
20118 		}
20119 	}
20120 
20121 	/* Fill in SACK options */
20122 	if (num_sack_blk > 0) {
20123 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
20124 		sack_blk_t *tmp;
20125 		int32_t	i;
20126 
20127 		wptr[0] = TCPOPT_NOP;
20128 		wptr[1] = TCPOPT_NOP;
20129 		wptr[2] = TCPOPT_SACK;
20130 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
20131 		    sizeof (sack_blk_t);
20132 		wptr += TCPOPT_REAL_SACK_LEN;
20133 
20134 		tmp = tcp->tcp_sack_list;
20135 		for (i = 0; i < num_sack_blk; i++) {
20136 			U32_TO_BE32(tmp[i].begin, wptr);
20137 			wptr += sizeof (tcp_seq);
20138 			U32_TO_BE32(tmp[i].end, wptr);
20139 			wptr += sizeof (tcp_seq);
20140 		}
20141 		tcp_h->th_offset_and_rsrvd[0] +=
20142 		    ((num_sack_blk * 2 + 1) << 4);
20143 	}
20144 }
20145 
20146 /*
20147  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
20148  * the destination address and SAP attribute, and if necessary, the
20149  * hardware checksum offload attribute to a Multidata message.
20150  */
20151 static int
20152 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
20153     const uint32_t start, const uint32_t stuff, const uint32_t end,
20154     const uint32_t flags, tcp_stack_t *tcps)
20155 {
20156 	/* Add global destination address & SAP attribute */
20157 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
20158 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
20159 		    "destination address+SAP\n"));
20160 
20161 		if (dlmp != NULL)
20162 			TCP_STAT(tcps, tcp_mdt_allocfail);
20163 		return (-1);
20164 	}
20165 
20166 	/* Add global hwcksum attribute */
20167 	if (hwcksum &&
20168 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
20169 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
20170 		    "checksum attribute\n"));
20171 
20172 		TCP_STAT(tcps, tcp_mdt_allocfail);
20173 		return (-1);
20174 	}
20175 
20176 	return (0);
20177 }
20178 
20179 /*
20180  * Smaller and private version of pdescinfo_t used specifically for TCP,
20181  * which allows for only two payload spans per packet.
20182  */
20183 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
20184 
20185 /*
20186  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
20187  * scheme, and returns one the following:
20188  *
20189  * -1 = failed allocation.
20190  *  0 = success; burst count reached, or usable send window is too small,
20191  *      and that we'd rather wait until later before sending again.
20192  */
20193 static int
20194 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20195     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20196     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20197     const int mdt_thres)
20198 {
20199 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
20200 	multidata_t	*mmd;
20201 	uint_t		obsegs, obbytes, hdr_frag_sz;
20202 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
20203 	int		num_burst_seg, max_pld;
20204 	pdesc_t		*pkt;
20205 	tcp_pdescinfo_t	tcp_pkt_info;
20206 	pdescinfo_t	*pkt_info;
20207 	int		pbuf_idx, pbuf_idx_nxt;
20208 	int		seg_len, len, spill, af;
20209 	boolean_t	add_buffer, zcopy, clusterwide;
20210 	boolean_t	buf_trunked = B_FALSE;
20211 	boolean_t	rconfirm = B_FALSE;
20212 	boolean_t	done = B_FALSE;
20213 	uint32_t	cksum;
20214 	uint32_t	hwcksum_flags;
20215 	ire_t		*ire = NULL;
20216 	ill_t		*ill;
20217 	ipha_t		*ipha;
20218 	ip6_t		*ip6h;
20219 	ipaddr_t	src, dst;
20220 	ill_zerocopy_capab_t *zc_cap = NULL;
20221 	uint16_t	*up;
20222 	int		err;
20223 	conn_t		*connp;
20224 	mblk_t		*mp, *mp1, *fw_mp_head = NULL;
20225 	uchar_t		*pld_start;
20226 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20227 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
20228 
20229 #ifdef	_BIG_ENDIAN
20230 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20231 #else
20232 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20233 #endif
20234 
20235 #define	PREP_NEW_MULTIDATA() {			\
20236 	mmd = NULL;				\
20237 	md_mp = md_hbuf = NULL;			\
20238 	cur_hdr_off = 0;			\
20239 	max_pld = tcp->tcp_mdt_max_pld;		\
20240 	pbuf_idx = pbuf_idx_nxt = -1;		\
20241 	add_buffer = B_TRUE;			\
20242 	zcopy = B_FALSE;			\
20243 }
20244 
20245 #define	PREP_NEW_PBUF() {			\
20246 	md_pbuf = md_pbuf_nxt = NULL;		\
20247 	pbuf_idx = pbuf_idx_nxt = -1;		\
20248 	cur_pld_off = 0;			\
20249 	first_snxt = *snxt;			\
20250 	ASSERT(*tail_unsent > 0);		\
20251 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20252 }
20253 
20254 	ASSERT(mdt_thres >= mss);
20255 	ASSERT(*usable > 0 && *usable > mdt_thres);
20256 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20257 	ASSERT(!TCP_IS_DETACHED(tcp));
20258 	ASSERT(tcp->tcp_valid_bits == 0 ||
20259 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20260 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20261 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20262 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20263 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20264 
20265 	connp = tcp->tcp_connp;
20266 	ASSERT(connp != NULL);
20267 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20268 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20269 
20270 	/*
20271 	 * Note that tcp will only declare at most 2 payload spans per
20272 	 * packet, which is much lower than the maximum allowable number
20273 	 * of packet spans per Multidata.  For this reason, we use the
20274 	 * privately declared and smaller descriptor info structure, in
20275 	 * order to save some stack space.
20276 	 */
20277 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20278 
20279 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20280 	if (af == AF_INET) {
20281 		dst = tcp->tcp_ipha->ipha_dst;
20282 		src = tcp->tcp_ipha->ipha_src;
20283 		ASSERT(!CLASSD(dst));
20284 	}
20285 	ASSERT(af == AF_INET ||
20286 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20287 
20288 	obsegs = obbytes = 0;
20289 	num_burst_seg = tcp->tcp_snd_burst;
20290 	md_mp_head = NULL;
20291 	PREP_NEW_MULTIDATA();
20292 
20293 	/*
20294 	 * Before we go on further, make sure there is an IRE that we can
20295 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20296 	 * in proceeding any further, and we should just hand everything
20297 	 * off to the legacy path.
20298 	 */
20299 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20300 		goto legacy_send_no_md;
20301 
20302 	ASSERT(ire != NULL);
20303 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20304 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20305 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20306 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20307 	/*
20308 	 * If we do support loopback for MDT (which requires modifications
20309 	 * to the receiving paths), the following assertions should go away,
20310 	 * and we would be sending the Multidata to loopback conn later on.
20311 	 */
20312 	ASSERT(!IRE_IS_LOCAL(ire));
20313 	ASSERT(ire->ire_stq != NULL);
20314 
20315 	ill = ire_to_ill(ire);
20316 	ASSERT(ill != NULL);
20317 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20318 
20319 	if (!tcp->tcp_ire_ill_check_done) {
20320 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20321 		tcp->tcp_ire_ill_check_done = B_TRUE;
20322 	}
20323 
20324 	/*
20325 	 * If the underlying interface conditions have changed, or if the
20326 	 * new interface does not support MDT, go back to legacy path.
20327 	 */
20328 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20329 		/* don't go through this path anymore for this connection */
20330 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20331 		tcp->tcp_mdt = B_FALSE;
20332 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20333 		    "interface %s\n", (void *)connp, ill->ill_name));
20334 		/* IRE will be released prior to returning */
20335 		goto legacy_send_no_md;
20336 	}
20337 
20338 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20339 		zc_cap = ill->ill_zerocopy_capab;
20340 
20341 	/*
20342 	 * Check if we can take tcp fast-path. Note that "incomplete"
20343 	 * ire's (where the link-layer for next hop is not resolved
20344 	 * or where the fast-path header in nce_fp_mp is not available
20345 	 * yet) are sent down the legacy (slow) path.
20346 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20347 	 */
20348 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20349 		/* IRE will be released prior to returning */
20350 		goto legacy_send_no_md;
20351 	}
20352 
20353 	/* go to legacy path if interface doesn't support zerocopy */
20354 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20355 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20356 		/* IRE will be released prior to returning */
20357 		goto legacy_send_no_md;
20358 	}
20359 
20360 	/* does the interface support hardware checksum offload? */
20361 	hwcksum_flags = 0;
20362 	if (ILL_HCKSUM_CAPABLE(ill) &&
20363 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20364 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20365 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20366 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20367 		    HCKSUM_IPHDRCKSUM)
20368 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20369 
20370 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20371 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20372 			hwcksum_flags |= HCK_FULLCKSUM;
20373 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20374 		    HCKSUM_INET_PARTIAL)
20375 			hwcksum_flags |= HCK_PARTIALCKSUM;
20376 	}
20377 
20378 	/*
20379 	 * Each header fragment consists of the leading extra space,
20380 	 * followed by the TCP/IP header, and the trailing extra space.
20381 	 * We make sure that each header fragment begins on a 32-bit
20382 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20383 	 * aligned in tcp_mdt_update).
20384 	 */
20385 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20386 	    tcp->tcp_mdt_hdr_tail), 4);
20387 
20388 	/* are we starting from the beginning of data block? */
20389 	if (*tail_unsent == 0) {
20390 		*xmit_tail = (*xmit_tail)->b_cont;
20391 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20392 		*tail_unsent = (int)MBLKL(*xmit_tail);
20393 	}
20394 
20395 	/*
20396 	 * Here we create one or more Multidata messages, each made up of
20397 	 * one header buffer and up to N payload buffers.  This entire
20398 	 * operation is done within two loops:
20399 	 *
20400 	 * The outer loop mostly deals with creating the Multidata message,
20401 	 * as well as the header buffer that gets added to it.  It also
20402 	 * links the Multidata messages together such that all of them can
20403 	 * be sent down to the lower layer in a single putnext call; this
20404 	 * linking behavior depends on the tcp_mdt_chain tunable.
20405 	 *
20406 	 * The inner loop takes an existing Multidata message, and adds
20407 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20408 	 * packetizes those buffers by filling up the corresponding header
20409 	 * buffer fragments with the proper IP and TCP headers, and by
20410 	 * describing the layout of each packet in the packet descriptors
20411 	 * that get added to the Multidata.
20412 	 */
20413 	do {
20414 		/*
20415 		 * If usable send window is too small, or data blocks in
20416 		 * transmit list are smaller than our threshold (i.e. app
20417 		 * performs large writes followed by small ones), we hand
20418 		 * off the control over to the legacy path.  Note that we'll
20419 		 * get back the control once it encounters a large block.
20420 		 */
20421 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20422 		    (*xmit_tail)->b_cont != NULL &&
20423 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20424 			/* send down what we've got so far */
20425 			if (md_mp_head != NULL) {
20426 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20427 				    obsegs, obbytes, &rconfirm);
20428 			}
20429 			/*
20430 			 * Pass control over to tcp_send(), but tell it to
20431 			 * return to us once a large-size transmission is
20432 			 * possible.
20433 			 */
20434 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20435 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20436 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20437 			    tail_unsent, xmit_tail, local_time,
20438 			    mdt_thres)) <= 0) {
20439 				/* burst count reached, or alloc failed */
20440 				IRE_REFRELE(ire);
20441 				return (err);
20442 			}
20443 
20444 			/* tcp_send() may have sent everything, so check */
20445 			if (*usable <= 0) {
20446 				IRE_REFRELE(ire);
20447 				return (0);
20448 			}
20449 
20450 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20451 			/*
20452 			 * We may have delivered the Multidata, so make sure
20453 			 * to re-initialize before the next round.
20454 			 */
20455 			md_mp_head = NULL;
20456 			obsegs = obbytes = 0;
20457 			num_burst_seg = tcp->tcp_snd_burst;
20458 			PREP_NEW_MULTIDATA();
20459 
20460 			/* are we starting from the beginning of data block? */
20461 			if (*tail_unsent == 0) {
20462 				*xmit_tail = (*xmit_tail)->b_cont;
20463 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20464 				    (uintptr_t)INT_MAX);
20465 				*tail_unsent = (int)MBLKL(*xmit_tail);
20466 			}
20467 		}
20468 
20469 		/*
20470 		 * max_pld limits the number of mblks in tcp's transmit
20471 		 * queue that can be added to a Multidata message.  Once
20472 		 * this counter reaches zero, no more additional mblks
20473 		 * can be added to it.  What happens afterwards depends
20474 		 * on whether or not we are set to chain the Multidata
20475 		 * messages.  If we are to link them together, reset
20476 		 * max_pld to its original value (tcp_mdt_max_pld) and
20477 		 * prepare to create a new Multidata message which will
20478 		 * get linked to md_mp_head.  Else, leave it alone and
20479 		 * let the inner loop break on its own.
20480 		 */
20481 		if (tcp_mdt_chain && max_pld == 0)
20482 			PREP_NEW_MULTIDATA();
20483 
20484 		/* adding a payload buffer; re-initialize values */
20485 		if (add_buffer)
20486 			PREP_NEW_PBUF();
20487 
20488 		/*
20489 		 * If we don't have a Multidata, either because we just
20490 		 * (re)entered this outer loop, or after we branched off
20491 		 * to tcp_send above, setup the Multidata and header
20492 		 * buffer to be used.
20493 		 */
20494 		if (md_mp == NULL) {
20495 			int md_hbuflen;
20496 			uint32_t start, stuff;
20497 
20498 			/*
20499 			 * Calculate Multidata header buffer size large enough
20500 			 * to hold all of the headers that can possibly be
20501 			 * sent at this moment.  We'd rather over-estimate
20502 			 * the size than running out of space; this is okay
20503 			 * since this buffer is small anyway.
20504 			 */
20505 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20506 
20507 			/*
20508 			 * Start and stuff offset for partial hardware
20509 			 * checksum offload; these are currently for IPv4.
20510 			 * For full checksum offload, they are set to zero.
20511 			 */
20512 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20513 				if (af == AF_INET) {
20514 					start = IP_SIMPLE_HDR_LENGTH;
20515 					stuff = IP_SIMPLE_HDR_LENGTH +
20516 					    TCP_CHECKSUM_OFFSET;
20517 				} else {
20518 					start = IPV6_HDR_LEN;
20519 					stuff = IPV6_HDR_LEN +
20520 					    TCP_CHECKSUM_OFFSET;
20521 				}
20522 			} else {
20523 				start = stuff = 0;
20524 			}
20525 
20526 			/*
20527 			 * Create the header buffer, Multidata, as well as
20528 			 * any necessary attributes (destination address,
20529 			 * SAP and hardware checksum offload) that should
20530 			 * be associated with the Multidata message.
20531 			 */
20532 			ASSERT(cur_hdr_off == 0);
20533 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20534 			    ((md_hbuf->b_wptr += md_hbuflen),
20535 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20536 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20537 			    /* fastpath mblk */
20538 			    ire->ire_nce->nce_res_mp,
20539 			    /* hardware checksum enabled */
20540 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20541 			    /* hardware checksum offsets */
20542 			    start, stuff, 0,
20543 			    /* hardware checksum flag */
20544 			    hwcksum_flags, tcps) != 0)) {
20545 legacy_send:
20546 				if (md_mp != NULL) {
20547 					/* Unlink message from the chain */
20548 					if (md_mp_head != NULL) {
20549 						err = (intptr_t)rmvb(md_mp_head,
20550 						    md_mp);
20551 						/*
20552 						 * We can't assert that rmvb
20553 						 * did not return -1, since we
20554 						 * may get here before linkb
20555 						 * happens.  We do, however,
20556 						 * check if we just removed the
20557 						 * only element in the list.
20558 						 */
20559 						if (err == 0)
20560 							md_mp_head = NULL;
20561 					}
20562 					/* md_hbuf gets freed automatically */
20563 					TCP_STAT(tcps, tcp_mdt_discarded);
20564 					freeb(md_mp);
20565 				} else {
20566 					/* Either allocb or mmd_alloc failed */
20567 					TCP_STAT(tcps, tcp_mdt_allocfail);
20568 					if (md_hbuf != NULL)
20569 						freeb(md_hbuf);
20570 				}
20571 
20572 				/* send down what we've got so far */
20573 				if (md_mp_head != NULL) {
20574 					tcp_multisend_data(tcp, ire, ill,
20575 					    md_mp_head, obsegs, obbytes,
20576 					    &rconfirm);
20577 				}
20578 legacy_send_no_md:
20579 				if (ire != NULL)
20580 					IRE_REFRELE(ire);
20581 				/*
20582 				 * Too bad; let the legacy path handle this.
20583 				 * We specify INT_MAX for the threshold, since
20584 				 * we gave up with the Multidata processings
20585 				 * and let the old path have it all.
20586 				 */
20587 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20588 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20589 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20590 				    snxt, tail_unsent, xmit_tail, local_time,
20591 				    INT_MAX));
20592 			}
20593 
20594 			/* link to any existing ones, if applicable */
20595 			TCP_STAT(tcps, tcp_mdt_allocd);
20596 			if (md_mp_head == NULL) {
20597 				md_mp_head = md_mp;
20598 			} else if (tcp_mdt_chain) {
20599 				TCP_STAT(tcps, tcp_mdt_linked);
20600 				linkb(md_mp_head, md_mp);
20601 			}
20602 		}
20603 
20604 		ASSERT(md_mp_head != NULL);
20605 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20606 		ASSERT(md_mp != NULL && mmd != NULL);
20607 		ASSERT(md_hbuf != NULL);
20608 
20609 		/*
20610 		 * Packetize the transmittable portion of the data block;
20611 		 * each data block is essentially added to the Multidata
20612 		 * as a payload buffer.  We also deal with adding more
20613 		 * than one payload buffers, which happens when the remaining
20614 		 * packetized portion of the current payload buffer is less
20615 		 * than MSS, while the next data block in transmit queue
20616 		 * has enough data to make up for one.  This "spillover"
20617 		 * case essentially creates a split-packet, where portions
20618 		 * of the packet's payload fragments may span across two
20619 		 * virtually discontiguous address blocks.
20620 		 */
20621 		seg_len = mss;
20622 		do {
20623 			len = seg_len;
20624 
20625 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20626 			ipha = NULL;
20627 			ip6h = NULL;
20628 
20629 			ASSERT(len > 0);
20630 			ASSERT(max_pld >= 0);
20631 			ASSERT(!add_buffer || cur_pld_off == 0);
20632 
20633 			/*
20634 			 * First time around for this payload buffer; note
20635 			 * in the case of a spillover, the following has
20636 			 * been done prior to adding the split-packet
20637 			 * descriptor to Multidata, and we don't want to
20638 			 * repeat the process.
20639 			 */
20640 			if (add_buffer) {
20641 				ASSERT(mmd != NULL);
20642 				ASSERT(md_pbuf == NULL);
20643 				ASSERT(md_pbuf_nxt == NULL);
20644 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20645 
20646 				/*
20647 				 * Have we reached the limit?  We'd get to
20648 				 * this case when we're not chaining the
20649 				 * Multidata messages together, and since
20650 				 * we're done, terminate this loop.
20651 				 */
20652 				if (max_pld == 0)
20653 					break; /* done */
20654 
20655 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20656 					TCP_STAT(tcps, tcp_mdt_allocfail);
20657 					goto legacy_send; /* out_of_mem */
20658 				}
20659 
20660 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20661 				    zc_cap != NULL) {
20662 					if (!ip_md_zcopy_attr(mmd, NULL,
20663 					    zc_cap->ill_zerocopy_flags)) {
20664 						freeb(md_pbuf);
20665 						TCP_STAT(tcps,
20666 						    tcp_mdt_allocfail);
20667 						/* out_of_mem */
20668 						goto legacy_send;
20669 					}
20670 					zcopy = B_TRUE;
20671 				}
20672 
20673 				md_pbuf->b_rptr += base_pld_off;
20674 
20675 				/*
20676 				 * Add a payload buffer to the Multidata; this
20677 				 * operation must not fail, or otherwise our
20678 				 * logic in this routine is broken.  There
20679 				 * is no memory allocation done by the
20680 				 * routine, so any returned failure simply
20681 				 * tells us that we've done something wrong.
20682 				 *
20683 				 * A failure tells us that either we're adding
20684 				 * the same payload buffer more than once, or
20685 				 * we're trying to add more buffers than
20686 				 * allowed (max_pld calculation is wrong).
20687 				 * None of the above cases should happen, and
20688 				 * we panic because either there's horrible
20689 				 * heap corruption, and/or programming mistake.
20690 				 */
20691 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20692 				if (pbuf_idx < 0) {
20693 					cmn_err(CE_PANIC, "tcp_multisend: "
20694 					    "payload buffer logic error "
20695 					    "detected for tcp %p mmd %p "
20696 					    "pbuf %p (%d)\n",
20697 					    (void *)tcp, (void *)mmd,
20698 					    (void *)md_pbuf, pbuf_idx);
20699 				}
20700 
20701 				ASSERT(max_pld > 0);
20702 				--max_pld;
20703 				add_buffer = B_FALSE;
20704 			}
20705 
20706 			ASSERT(md_mp_head != NULL);
20707 			ASSERT(md_pbuf != NULL);
20708 			ASSERT(md_pbuf_nxt == NULL);
20709 			ASSERT(pbuf_idx != -1);
20710 			ASSERT(pbuf_idx_nxt == -1);
20711 			ASSERT(*usable > 0);
20712 
20713 			/*
20714 			 * We spillover to the next payload buffer only
20715 			 * if all of the following is true:
20716 			 *
20717 			 *   1. There is not enough data on the current
20718 			 *	payload buffer to make up `len',
20719 			 *   2. We are allowed to send `len',
20720 			 *   3. The next payload buffer length is large
20721 			 *	enough to accomodate `spill'.
20722 			 */
20723 			if ((spill = len - *tail_unsent) > 0 &&
20724 			    *usable >= len &&
20725 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20726 			    max_pld > 0) {
20727 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20728 				if (md_pbuf_nxt == NULL) {
20729 					TCP_STAT(tcps, tcp_mdt_allocfail);
20730 					goto legacy_send; /* out_of_mem */
20731 				}
20732 
20733 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20734 				    zc_cap != NULL) {
20735 					if (!ip_md_zcopy_attr(mmd, NULL,
20736 					    zc_cap->ill_zerocopy_flags)) {
20737 						freeb(md_pbuf_nxt);
20738 						TCP_STAT(tcps,
20739 						    tcp_mdt_allocfail);
20740 						/* out_of_mem */
20741 						goto legacy_send;
20742 					}
20743 					zcopy = B_TRUE;
20744 				}
20745 
20746 				/*
20747 				 * See comments above on the first call to
20748 				 * mmd_addpldbuf for explanation on the panic.
20749 				 */
20750 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20751 				if (pbuf_idx_nxt < 0) {
20752 					panic("tcp_multisend: "
20753 					    "next payload buffer logic error "
20754 					    "detected for tcp %p mmd %p "
20755 					    "pbuf %p (%d)\n",
20756 					    (void *)tcp, (void *)mmd,
20757 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20758 				}
20759 
20760 				ASSERT(max_pld > 0);
20761 				--max_pld;
20762 			} else if (spill > 0) {
20763 				/*
20764 				 * If there's a spillover, but the following
20765 				 * xmit_tail couldn't give us enough octets
20766 				 * to reach "len", then stop the current
20767 				 * Multidata creation and let the legacy
20768 				 * tcp_send() path take over.  We don't want
20769 				 * to send the tiny segment as part of this
20770 				 * Multidata for performance reasons; instead,
20771 				 * we let the legacy path deal with grouping
20772 				 * it with the subsequent small mblks.
20773 				 */
20774 				if (*usable >= len &&
20775 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20776 					max_pld = 0;
20777 					break;	/* done */
20778 				}
20779 
20780 				/*
20781 				 * We can't spillover, and we are near
20782 				 * the end of the current payload buffer,
20783 				 * so send what's left.
20784 				 */
20785 				ASSERT(*tail_unsent > 0);
20786 				len = *tail_unsent;
20787 			}
20788 
20789 			/* tail_unsent is negated if there is a spillover */
20790 			*tail_unsent -= len;
20791 			*usable -= len;
20792 			ASSERT(*usable >= 0);
20793 
20794 			if (*usable < mss)
20795 				seg_len = *usable;
20796 			/*
20797 			 * Sender SWS avoidance; see comments in tcp_send();
20798 			 * everything else is the same, except that we only
20799 			 * do this here if there is no more data to be sent
20800 			 * following the current xmit_tail.  We don't check
20801 			 * for 1-byte urgent data because we shouldn't get
20802 			 * here if TCP_URG_VALID is set.
20803 			 */
20804 			if (*usable > 0 && *usable < mss &&
20805 			    ((md_pbuf_nxt == NULL &&
20806 			    (*xmit_tail)->b_cont == NULL) ||
20807 			    (md_pbuf_nxt != NULL &&
20808 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20809 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20810 			    (tcp->tcp_unsent -
20811 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20812 			    !tcp->tcp_zero_win_probe) {
20813 				if ((*snxt + len) == tcp->tcp_snxt &&
20814 				    (*snxt + len) == tcp->tcp_suna) {
20815 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20816 				}
20817 				done = B_TRUE;
20818 			}
20819 
20820 			/*
20821 			 * Prime pump for IP's checksumming on our behalf;
20822 			 * include the adjustment for a source route if any.
20823 			 * Do this only for software/partial hardware checksum
20824 			 * offload, as this field gets zeroed out later for
20825 			 * the full hardware checksum offload case.
20826 			 */
20827 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20828 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20829 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20830 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20831 			}
20832 
20833 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20834 			*snxt += len;
20835 
20836 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20837 			/*
20838 			 * We set the PUSH bit only if TCP has no more buffered
20839 			 * data to be transmitted (or if sender SWS avoidance
20840 			 * takes place), as opposed to setting it for every
20841 			 * last packet in the burst.
20842 			 */
20843 			if (done ||
20844 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20845 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20846 
20847 			/*
20848 			 * Set FIN bit if this is our last segment; snxt
20849 			 * already includes its length, and it will not
20850 			 * be adjusted after this point.
20851 			 */
20852 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20853 			    *snxt == tcp->tcp_fss) {
20854 				if (!tcp->tcp_fin_acked) {
20855 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20856 					BUMP_MIB(&tcps->tcps_mib,
20857 					    tcpOutControl);
20858 				}
20859 				if (!tcp->tcp_fin_sent) {
20860 					tcp->tcp_fin_sent = B_TRUE;
20861 					/*
20862 					 * tcp state must be ESTABLISHED
20863 					 * in order for us to get here in
20864 					 * the first place.
20865 					 */
20866 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20867 
20868 					/*
20869 					 * Upon returning from this routine,
20870 					 * tcp_wput_data() will set tcp_snxt
20871 					 * to be equal to snxt + tcp_fin_sent.
20872 					 * This is essentially the same as
20873 					 * setting it to tcp_fss + 1.
20874 					 */
20875 				}
20876 			}
20877 
20878 			tcp->tcp_last_sent_len = (ushort_t)len;
20879 
20880 			len += tcp_hdr_len;
20881 			if (tcp->tcp_ipversion == IPV4_VERSION)
20882 				tcp->tcp_ipha->ipha_length = htons(len);
20883 			else
20884 				tcp->tcp_ip6h->ip6_plen = htons(len -
20885 				    ((char *)&tcp->tcp_ip6h[1] -
20886 				    tcp->tcp_iphc));
20887 
20888 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20889 
20890 			/* setup header fragment */
20891 			PDESC_HDR_ADD(pkt_info,
20892 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20893 			    tcp->tcp_mdt_hdr_head,		/* head room */
20894 			    tcp_hdr_len,			/* len */
20895 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20896 
20897 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20898 			    hdr_frag_sz);
20899 			ASSERT(MBLKIN(md_hbuf,
20900 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20901 			    PDESC_HDRSIZE(pkt_info)));
20902 
20903 			/* setup first payload fragment */
20904 			PDESC_PLD_INIT(pkt_info);
20905 			PDESC_PLD_SPAN_ADD(pkt_info,
20906 			    pbuf_idx,				/* index */
20907 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20908 			    tcp->tcp_last_sent_len);		/* len */
20909 
20910 			/* create a split-packet in case of a spillover */
20911 			if (md_pbuf_nxt != NULL) {
20912 				ASSERT(spill > 0);
20913 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20914 				ASSERT(!add_buffer);
20915 
20916 				md_pbuf = md_pbuf_nxt;
20917 				md_pbuf_nxt = NULL;
20918 				pbuf_idx = pbuf_idx_nxt;
20919 				pbuf_idx_nxt = -1;
20920 				cur_pld_off = spill;
20921 
20922 				/* trim out first payload fragment */
20923 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20924 
20925 				/* setup second payload fragment */
20926 				PDESC_PLD_SPAN_ADD(pkt_info,
20927 				    pbuf_idx,			/* index */
20928 				    md_pbuf->b_rptr,		/* start */
20929 				    spill);			/* len */
20930 
20931 				if ((*xmit_tail)->b_next == NULL) {
20932 					/*
20933 					 * Store the lbolt used for RTT
20934 					 * estimation. We can only record one
20935 					 * timestamp per mblk so we do it when
20936 					 * we reach the end of the payload
20937 					 * buffer.  Also we only take a new
20938 					 * timestamp sample when the previous
20939 					 * timed data from the same mblk has
20940 					 * been ack'ed.
20941 					 */
20942 					(*xmit_tail)->b_prev = local_time;
20943 					(*xmit_tail)->b_next =
20944 					    (mblk_t *)(uintptr_t)first_snxt;
20945 				}
20946 
20947 				first_snxt = *snxt - spill;
20948 
20949 				/*
20950 				 * Advance xmit_tail; usable could be 0 by
20951 				 * the time we got here, but we made sure
20952 				 * above that we would only spillover to
20953 				 * the next data block if usable includes
20954 				 * the spilled-over amount prior to the
20955 				 * subtraction.  Therefore, we are sure
20956 				 * that xmit_tail->b_cont can't be NULL.
20957 				 */
20958 				ASSERT((*xmit_tail)->b_cont != NULL);
20959 				*xmit_tail = (*xmit_tail)->b_cont;
20960 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20961 				    (uintptr_t)INT_MAX);
20962 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20963 			} else {
20964 				cur_pld_off += tcp->tcp_last_sent_len;
20965 			}
20966 
20967 			/*
20968 			 * Fill in the header using the template header, and
20969 			 * add options such as time-stamp, ECN and/or SACK,
20970 			 * as needed.
20971 			 */
20972 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20973 			    (clock_t)local_time, num_sack_blk);
20974 
20975 			/* take care of some IP header businesses */
20976 			if (af == AF_INET) {
20977 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20978 
20979 				ASSERT(OK_32PTR((uchar_t *)ipha));
20980 				ASSERT(PDESC_HDRL(pkt_info) >=
20981 				    IP_SIMPLE_HDR_LENGTH);
20982 				ASSERT(ipha->ipha_version_and_hdr_length ==
20983 				    IP_SIMPLE_HDR_VERSION);
20984 
20985 				/*
20986 				 * Assign ident value for current packet; see
20987 				 * related comments in ip_wput_ire() about the
20988 				 * contract private interface with clustering
20989 				 * group.
20990 				 */
20991 				clusterwide = B_FALSE;
20992 				if (cl_inet_ipident != NULL) {
20993 					ASSERT(cl_inet_isclusterwide != NULL);
20994 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20995 					    AF_INET,
20996 					    (uint8_t *)(uintptr_t)src)) {
20997 						ipha->ipha_ident =
20998 						    (*cl_inet_ipident)
20999 						    (IPPROTO_IP, AF_INET,
21000 						    (uint8_t *)(uintptr_t)src,
21001 						    (uint8_t *)(uintptr_t)dst);
21002 						clusterwide = B_TRUE;
21003 					}
21004 				}
21005 
21006 				if (!clusterwide) {
21007 					ipha->ipha_ident = (uint16_t)
21008 					    atomic_add_32_nv(
21009 						&ire->ire_ident, 1);
21010 				}
21011 #ifndef _BIG_ENDIAN
21012 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
21013 				    (ipha->ipha_ident >> 8);
21014 #endif
21015 			} else {
21016 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
21017 
21018 				ASSERT(OK_32PTR((uchar_t *)ip6h));
21019 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
21020 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
21021 				ASSERT(PDESC_HDRL(pkt_info) >=
21022 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
21023 				    TCP_CHECKSUM_SIZE));
21024 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21025 
21026 				if (tcp->tcp_ip_forward_progress) {
21027 					rconfirm = B_TRUE;
21028 					tcp->tcp_ip_forward_progress = B_FALSE;
21029 				}
21030 			}
21031 
21032 			/* at least one payload span, and at most two */
21033 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
21034 
21035 			/* add the packet descriptor to Multidata */
21036 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
21037 			    KM_NOSLEEP)) == NULL) {
21038 				/*
21039 				 * Any failure other than ENOMEM indicates
21040 				 * that we have passed in invalid pkt_info
21041 				 * or parameters to mmd_addpdesc, which must
21042 				 * not happen.
21043 				 *
21044 				 * EINVAL is a result of failure on boundary
21045 				 * checks against the pkt_info contents.  It
21046 				 * should not happen, and we panic because
21047 				 * either there's horrible heap corruption,
21048 				 * and/or programming mistake.
21049 				 */
21050 				if (err != ENOMEM) {
21051 					cmn_err(CE_PANIC, "tcp_multisend: "
21052 					    "pdesc logic error detected for "
21053 					    "tcp %p mmd %p pinfo %p (%d)\n",
21054 					    (void *)tcp, (void *)mmd,
21055 					    (void *)pkt_info, err);
21056 				}
21057 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
21058 				goto legacy_send; /* out_of_mem */
21059 			}
21060 			ASSERT(pkt != NULL);
21061 
21062 			/* calculate IP header and TCP checksums */
21063 			if (af == AF_INET) {
21064 				/* calculate pseudo-header checksum */
21065 				cksum = (dst >> 16) + (dst & 0xFFFF) +
21066 				    (src >> 16) + (src & 0xFFFF);
21067 
21068 				/* offset for TCP header checksum */
21069 				up = IPH_TCPH_CHECKSUMP(ipha,
21070 				    IP_SIMPLE_HDR_LENGTH);
21071 			} else {
21072 				up = (uint16_t *)&ip6h->ip6_src;
21073 
21074 				/* calculate pseudo-header checksum */
21075 				cksum = up[0] + up[1] + up[2] + up[3] +
21076 				    up[4] + up[5] + up[6] + up[7] +
21077 				    up[8] + up[9] + up[10] + up[11] +
21078 				    up[12] + up[13] + up[14] + up[15];
21079 
21080 				/* Fold the initial sum */
21081 				cksum = (cksum & 0xffff) + (cksum >> 16);
21082 
21083 				up = (uint16_t *)(((uchar_t *)ip6h) +
21084 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
21085 			}
21086 
21087 			if (hwcksum_flags & HCK_FULLCKSUM) {
21088 				/* clear checksum field for hardware */
21089 				*up = 0;
21090 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
21091 				uint32_t sum;
21092 
21093 				/* pseudo-header checksumming */
21094 				sum = *up + cksum + IP_TCP_CSUM_COMP;
21095 				sum = (sum & 0xFFFF) + (sum >> 16);
21096 				*up = (sum & 0xFFFF) + (sum >> 16);
21097 			} else {
21098 				/* software checksumming */
21099 				TCP_STAT(tcps, tcp_out_sw_cksum);
21100 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
21101 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
21102 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
21103 				    cksum + IP_TCP_CSUM_COMP);
21104 				if (*up == 0)
21105 					*up = 0xFFFF;
21106 			}
21107 
21108 			/* IPv4 header checksum */
21109 			if (af == AF_INET) {
21110 				ipha->ipha_fragment_offset_and_flags |=
21111 				    (uint32_t)htons(ire->ire_frag_flag);
21112 
21113 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
21114 					ipha->ipha_hdr_checksum = 0;
21115 				} else {
21116 					IP_HDR_CKSUM(ipha, cksum,
21117 					    ((uint32_t *)ipha)[0],
21118 					    ((uint16_t *)ipha)[4]);
21119 				}
21120 			}
21121 
21122 			if (af == AF_INET &&
21123 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
21124 			    af == AF_INET6 &&
21125 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
21126 				/* build header(IP/TCP) mblk for this segment */
21127 				if ((mp = dupb(md_hbuf)) == NULL)
21128 					goto legacy_send;
21129 
21130 				mp->b_rptr = pkt_info->hdr_rptr;
21131 				mp->b_wptr = pkt_info->hdr_wptr;
21132 
21133 				/* build payload mblk for this segment */
21134 				if ((mp1 = dupb(*xmit_tail)) == NULL) {
21135 					freemsg(mp);
21136 					goto legacy_send;
21137 				}
21138 				mp1->b_wptr = md_pbuf->b_rptr + cur_pld_off;
21139 				mp1->b_rptr = mp1->b_wptr -
21140 				    tcp->tcp_last_sent_len;
21141 				linkb(mp, mp1);
21142 
21143 				pld_start = mp1->b_rptr;
21144 
21145 				if (af == AF_INET) {
21146 					DTRACE_PROBE4(
21147 					    ip4__physical__out__start,
21148 					    ill_t *, NULL,
21149 					    ill_t *, ill,
21150 					    ipha_t *, ipha,
21151 					    mblk_t *, mp);
21152 					FW_HOOKS(
21153 					    ipst->ips_ip4_physical_out_event,
21154 					    ipst->ips_ipv4firewall_physical_out,
21155 					    NULL, ill, ipha, mp, mp, 0, ipst);
21156 					DTRACE_PROBE1(
21157 					    ip4__physical__out__end,
21158 					    mblk_t *, mp);
21159 				} else {
21160 					DTRACE_PROBE4(
21161 					    ip6__physical__out_start,
21162 					    ill_t *, NULL,
21163 					    ill_t *, ill,
21164 					    ip6_t *, ip6h,
21165 					    mblk_t *, mp);
21166 					FW_HOOKS6(
21167 					    ipst->ips_ip6_physical_out_event,
21168 					    ipst->ips_ipv6firewall_physical_out,
21169 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21170 					DTRACE_PROBE1(
21171 					    ip6__physical__out__end,
21172 					    mblk_t *, mp);
21173 				}
21174 
21175 				if (buf_trunked && mp != NULL) {
21176 					/*
21177 					 * Need to pass it to normal path.
21178 					 */
21179 					CALL_IP_WPUT(tcp->tcp_connp, q, mp);
21180 					mp = NULL;
21181 				} else if (mp == NULL ||
21182 				    mp->b_rptr != pkt_info->hdr_rptr ||
21183 				    mp->b_wptr != pkt_info->hdr_wptr ||
21184 				    (mp1 = mp->b_cont) == NULL ||
21185 				    mp1->b_rptr != pld_start ||
21186 				    mp1->b_wptr != pld_start +
21187 				    tcp->tcp_last_sent_len ||
21188 				    mp1->b_cont != NULL) {
21189 					/*
21190 					 * Need to pass all packets of this
21191 					 * buffer to normal path, either when
21192 					 * packet is blocked, or when boundary
21193 					 * of header buffer or payload buffer
21194 					 * has been changed by FW_HOOKS[6].
21195 					 */
21196 					buf_trunked = B_TRUE;
21197 					if (md_mp_head != NULL) {
21198 						err = (intptr_t)rmvb(md_mp_head,
21199 						    md_mp);
21200 						if (err == 0)
21201 							md_mp_head = NULL;
21202 					}
21203 
21204 					/* send down what we've got so far */
21205 					if (md_mp_head != NULL) {
21206 						tcp_multisend_data(tcp, ire,
21207 						    ill, md_mp_head, obsegs,
21208 						    obbytes, &rconfirm);
21209 					}
21210 					md_mp_head = NULL;
21211 
21212 					if (mp != NULL)
21213 						CALL_IP_WPUT(tcp->tcp_connp,
21214 						    q, mp);
21215 
21216 					mp1 = fw_mp_head;
21217 					do {
21218 						mp = mp1;
21219 						mp1 = mp1->b_next;
21220 						mp->b_next = NULL;
21221 						mp->b_prev = NULL;
21222 						CALL_IP_WPUT(tcp->tcp_connp,
21223 						    q, mp);
21224 					} while (mp1 != NULL);
21225 
21226 					fw_mp_head = mp = NULL;
21227 				} else {
21228 					if (fw_mp_head == NULL)
21229 						fw_mp_head = mp;
21230 					else
21231 						fw_mp_head->b_prev->b_next = mp;
21232 					fw_mp_head->b_prev = mp;
21233 				}
21234 			}
21235 
21236 			if (mp != NULL) {
21237 				DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21238 				    ill, ipha, ip6h);
21239 			}
21240 
21241 			/* advance header offset */
21242 			cur_hdr_off += hdr_frag_sz;
21243 
21244 			obbytes += tcp->tcp_last_sent_len;
21245 			++obsegs;
21246 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21247 		    *tail_unsent > 0);
21248 
21249 		if ((*xmit_tail)->b_next == NULL) {
21250 			/*
21251 			 * Store the lbolt used for RTT estimation. We can only
21252 			 * record one timestamp per mblk so we do it when we
21253 			 * reach the end of the payload buffer. Also we only
21254 			 * take a new timestamp sample when the previous timed
21255 			 * data from the same mblk has been ack'ed.
21256 			 */
21257 			(*xmit_tail)->b_prev = local_time;
21258 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21259 		}
21260 
21261 		ASSERT(*tail_unsent >= 0);
21262 		if (*tail_unsent > 0) {
21263 			/*
21264 			 * We got here because we broke out of the above
21265 			 * loop due to of one of the following cases:
21266 			 *
21267 			 *   1. len < adjusted MSS (i.e. small),
21268 			 *   2. Sender SWS avoidance,
21269 			 *   3. max_pld is zero.
21270 			 *
21271 			 * We are done for this Multidata, so trim our
21272 			 * last payload buffer (if any) accordingly.
21273 			 */
21274 			if (md_pbuf != NULL)
21275 				md_pbuf->b_wptr -= *tail_unsent;
21276 		} else if (*usable > 0) {
21277 			*xmit_tail = (*xmit_tail)->b_cont;
21278 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21279 			    (uintptr_t)INT_MAX);
21280 			*tail_unsent = (int)MBLKL(*xmit_tail);
21281 			add_buffer = B_TRUE;
21282 		}
21283 
21284 		while (fw_mp_head) {
21285 			mp = fw_mp_head;
21286 			fw_mp_head = fw_mp_head->b_next;
21287 			mp->b_prev = mp->b_next = NULL;
21288 			freemsg(mp);
21289 		}
21290 		if (buf_trunked) {
21291 			TCP_STAT(tcps, tcp_mdt_discarded);
21292 			freeb(md_mp);
21293 			buf_trunked = B_FALSE;
21294 		}
21295 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21296 	    (tcp_mdt_chain || max_pld > 0));
21297 
21298 	if (md_mp_head != NULL) {
21299 		/* send everything down */
21300 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21301 		    &rconfirm);
21302 	}
21303 
21304 #undef PREP_NEW_MULTIDATA
21305 #undef PREP_NEW_PBUF
21306 #undef IPVER
21307 
21308 	IRE_REFRELE(ire);
21309 	return (0);
21310 }
21311 
21312 /*
21313  * A wrapper function for sending one or more Multidata messages down to
21314  * the module below ip; this routine does not release the reference of the
21315  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21316  */
21317 static void
21318 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21319     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21320 {
21321 	uint64_t delta;
21322 	nce_t *nce;
21323 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21324 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21325 
21326 	ASSERT(ire != NULL && ill != NULL);
21327 	ASSERT(ire->ire_stq != NULL);
21328 	ASSERT(md_mp_head != NULL);
21329 	ASSERT(rconfirm != NULL);
21330 
21331 	/* adjust MIBs and IRE timestamp */
21332 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21333 	tcp->tcp_obsegs += obsegs;
21334 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21335 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21336 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21337 
21338 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21339 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21340 	} else {
21341 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21342 	}
21343 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21344 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21345 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21346 
21347 	ire->ire_ob_pkt_count += obsegs;
21348 	if (ire->ire_ipif != NULL)
21349 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21350 	ire->ire_last_used_time = lbolt;
21351 
21352 	/* send it down */
21353 	if (ILL_DLS_CAPABLE(ill)) {
21354 		ill_dls_capab_t *ill_dls = ill->ill_dls_capab;
21355 		ill_dls->ill_tx(ill_dls->ill_tx_handle, md_mp_head);
21356 	} else {
21357 		putnext(ire->ire_stq, md_mp_head);
21358 	}
21359 
21360 	/* we're done for TCP/IPv4 */
21361 	if (tcp->tcp_ipversion == IPV4_VERSION)
21362 		return;
21363 
21364 	nce = ire->ire_nce;
21365 
21366 	ASSERT(nce != NULL);
21367 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21368 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21369 
21370 	/* reachability confirmation? */
21371 	if (*rconfirm) {
21372 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21373 		if (nce->nce_state != ND_REACHABLE) {
21374 			mutex_enter(&nce->nce_lock);
21375 			nce->nce_state = ND_REACHABLE;
21376 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21377 			mutex_exit(&nce->nce_lock);
21378 			(void) untimeout(nce->nce_timeout_id);
21379 			if (ip_debug > 2) {
21380 				/* ip1dbg */
21381 				pr_addr_dbg("tcp_multisend_data: state "
21382 				    "for %s changed to REACHABLE\n",
21383 				    AF_INET6, &ire->ire_addr_v6);
21384 			}
21385 		}
21386 		/* reset transport reachability confirmation */
21387 		*rconfirm = B_FALSE;
21388 	}
21389 
21390 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21391 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21392 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21393 
21394 	if (delta > (uint64_t)ill->ill_reachable_time) {
21395 		mutex_enter(&nce->nce_lock);
21396 		switch (nce->nce_state) {
21397 		case ND_REACHABLE:
21398 		case ND_STALE:
21399 			/*
21400 			 * ND_REACHABLE is identical to ND_STALE in this
21401 			 * specific case. If reachable time has expired for
21402 			 * this neighbor (delta is greater than reachable
21403 			 * time), conceptually, the neighbor cache is no
21404 			 * longer in REACHABLE state, but already in STALE
21405 			 * state.  So the correct transition here is to
21406 			 * ND_DELAY.
21407 			 */
21408 			nce->nce_state = ND_DELAY;
21409 			mutex_exit(&nce->nce_lock);
21410 			NDP_RESTART_TIMER(nce,
21411 			    ipst->ips_delay_first_probe_time);
21412 			if (ip_debug > 3) {
21413 				/* ip2dbg */
21414 				pr_addr_dbg("tcp_multisend_data: state "
21415 				    "for %s changed to DELAY\n",
21416 				    AF_INET6, &ire->ire_addr_v6);
21417 			}
21418 			break;
21419 		case ND_DELAY:
21420 		case ND_PROBE:
21421 			mutex_exit(&nce->nce_lock);
21422 			/* Timers have already started */
21423 			break;
21424 		case ND_UNREACHABLE:
21425 			/*
21426 			 * ndp timer has detected that this nce is
21427 			 * unreachable and initiated deleting this nce
21428 			 * and all its associated IREs. This is a race
21429 			 * where we found the ire before it was deleted
21430 			 * and have just sent out a packet using this
21431 			 * unreachable nce.
21432 			 */
21433 			mutex_exit(&nce->nce_lock);
21434 			break;
21435 		default:
21436 			ASSERT(0);
21437 		}
21438 	}
21439 }
21440 
21441 /*
21442  * Derived from tcp_send_data().
21443  */
21444 static void
21445 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21446     int num_lso_seg)
21447 {
21448 	ipha_t		*ipha;
21449 	mblk_t		*ire_fp_mp;
21450 	uint_t		ire_fp_mp_len;
21451 	uint32_t	hcksum_txflags = 0;
21452 	ipaddr_t	src;
21453 	ipaddr_t	dst;
21454 	uint32_t	cksum;
21455 	uint16_t	*up;
21456 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21457 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21458 
21459 	ASSERT(DB_TYPE(mp) == M_DATA);
21460 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21461 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21462 	ASSERT(tcp->tcp_connp != NULL);
21463 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21464 
21465 	ipha = (ipha_t *)mp->b_rptr;
21466 	src = ipha->ipha_src;
21467 	dst = ipha->ipha_dst;
21468 
21469 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21470 
21471 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21472 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21473 	    num_lso_seg);
21474 #ifndef _BIG_ENDIAN
21475 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21476 #endif
21477 	if (tcp->tcp_snd_zcopy_aware) {
21478 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21479 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21480 			mp = tcp_zcopy_disable(tcp, mp);
21481 	}
21482 
21483 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21484 		ASSERT(ill->ill_hcksum_capab != NULL);
21485 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21486 	}
21487 
21488 	/*
21489 	 * Since the TCP checksum should be recalculated by h/w, we can just
21490 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21491 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21492 	 * The partial pseudo-header excludes TCP length, that was calculated
21493 	 * in tcp_send(), so to zero *up before further processing.
21494 	 */
21495 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21496 
21497 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21498 	*up = 0;
21499 
21500 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21501 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21502 
21503 	/*
21504 	 * Append LSO flag to DB_LSOFLAGS(mp) and set the mss to DB_LSOMSS(mp).
21505 	 */
21506 	DB_LSOFLAGS(mp) |= HW_LSO;
21507 	DB_LSOMSS(mp) = mss;
21508 
21509 	ipha->ipha_fragment_offset_and_flags |=
21510 	    (uint32_t)htons(ire->ire_frag_flag);
21511 
21512 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21513 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21514 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21515 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21516 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21517 
21518 	UPDATE_OB_PKT_COUNT(ire);
21519 	ire->ire_last_used_time = lbolt;
21520 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21521 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21522 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21523 	    ntohs(ipha->ipha_length));
21524 
21525 	if (ILL_DLS_CAPABLE(ill)) {
21526 		/*
21527 		 * Send the packet directly to DLD, where it may be queued
21528 		 * depending on the availability of transmit resources at
21529 		 * the media layer.
21530 		 */
21531 		IP_DLS_ILL_TX(ill, ipha, mp, ipst);
21532 	} else {
21533 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
21534 		DTRACE_PROBE4(ip4__physical__out__start,
21535 		    ill_t *, NULL, ill_t *, out_ill,
21536 		    ipha_t *, ipha, mblk_t *, mp);
21537 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
21538 		    ipst->ips_ipv4firewall_physical_out,
21539 		    NULL, out_ill, ipha, mp, mp, 0, ipst);
21540 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21541 
21542 		if (mp != NULL) {
21543 			DTRACE_IP_FASTPATH(mp, ipha, out_ill, ipha, NULL);
21544 			putnext(ire->ire_stq, mp);
21545 		}
21546 	}
21547 }
21548 
21549 /*
21550  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21551  * scheme, and returns one of the following:
21552  *
21553  * -1 = failed allocation.
21554  *  0 = success; burst count reached, or usable send window is too small,
21555  *      and that we'd rather wait until later before sending again.
21556  *  1 = success; we are called from tcp_multisend(), and both usable send
21557  *      window and tail_unsent are greater than the MDT threshold, and thus
21558  *      Multidata Transmit should be used instead.
21559  */
21560 static int
21561 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21562     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21563     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21564     const int mdt_thres)
21565 {
21566 	int num_burst_seg = tcp->tcp_snd_burst;
21567 	ire_t		*ire = NULL;
21568 	ill_t		*ill = NULL;
21569 	mblk_t		*ire_fp_mp = NULL;
21570 	uint_t		ire_fp_mp_len = 0;
21571 	int		num_lso_seg = 1;
21572 	uint_t		lso_usable;
21573 	boolean_t	do_lso_send = B_FALSE;
21574 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21575 
21576 	/*
21577 	 * Check LSO capability before any further work. And the similar check
21578 	 * need to be done in for(;;) loop.
21579 	 * LSO will be deployed when therer is more than one mss of available
21580 	 * data and a burst transmission is allowed.
21581 	 */
21582 	if (tcp->tcp_lso &&
21583 	    (tcp->tcp_valid_bits == 0 ||
21584 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21585 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21586 		/*
21587 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21588 		 */
21589 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21590 			/*
21591 			 * Enable LSO with this transmission.
21592 			 * Since IRE has been hold in
21593 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21594 			 * should be called before return.
21595 			 */
21596 			do_lso_send = B_TRUE;
21597 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21598 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21599 			/* Round up to multiple of 4 */
21600 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21601 		} else {
21602 			do_lso_send = B_FALSE;
21603 			ill = NULL;
21604 		}
21605 	}
21606 
21607 	for (;;) {
21608 		struct datab	*db;
21609 		tcph_t		*tcph;
21610 		uint32_t	sum;
21611 		mblk_t		*mp, *mp1;
21612 		uchar_t		*rptr;
21613 		int		len;
21614 
21615 		/*
21616 		 * If we're called by tcp_multisend(), and the amount of
21617 		 * sendable data as well as the size of current xmit_tail
21618 		 * is beyond the MDT threshold, return to the caller and
21619 		 * let the large data transmit be done using MDT.
21620 		 */
21621 		if (*usable > 0 && *usable > mdt_thres &&
21622 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21623 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21624 			ASSERT(tcp->tcp_mdt);
21625 			return (1);	/* success; do large send */
21626 		}
21627 
21628 		if (num_burst_seg == 0)
21629 			break;		/* success; burst count reached */
21630 
21631 		/*
21632 		 * Calculate the maximum payload length we can send in *one*
21633 		 * time.
21634 		 */
21635 		if (do_lso_send) {
21636 			/*
21637 			 * Check whether need to do LSO any more.
21638 			 */
21639 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21640 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21641 				lso_usable = MIN(lso_usable,
21642 				    num_burst_seg * mss);
21643 
21644 				num_lso_seg = lso_usable / mss;
21645 				if (lso_usable % mss) {
21646 					num_lso_seg++;
21647 					tcp->tcp_last_sent_len = (ushort_t)
21648 					    (lso_usable % mss);
21649 				} else {
21650 					tcp->tcp_last_sent_len = (ushort_t)mss;
21651 				}
21652 			} else {
21653 				do_lso_send = B_FALSE;
21654 				num_lso_seg = 1;
21655 				lso_usable = mss;
21656 			}
21657 		}
21658 
21659 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21660 
21661 		/*
21662 		 * Adjust num_burst_seg here.
21663 		 */
21664 		num_burst_seg -= num_lso_seg;
21665 
21666 		len = mss;
21667 		if (len > *usable) {
21668 			ASSERT(do_lso_send == B_FALSE);
21669 
21670 			len = *usable;
21671 			if (len <= 0) {
21672 				/* Terminate the loop */
21673 				break;	/* success; too small */
21674 			}
21675 			/*
21676 			 * Sender silly-window avoidance.
21677 			 * Ignore this if we are going to send a
21678 			 * zero window probe out.
21679 			 *
21680 			 * TODO: force data into microscopic window?
21681 			 *	==> (!pushed || (unsent > usable))
21682 			 */
21683 			if (len < (tcp->tcp_max_swnd >> 1) &&
21684 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21685 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21686 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21687 				/*
21688 				 * If the retransmit timer is not running
21689 				 * we start it so that we will retransmit
21690 				 * in the case when the the receiver has
21691 				 * decremented the window.
21692 				 */
21693 				if (*snxt == tcp->tcp_snxt &&
21694 				    *snxt == tcp->tcp_suna) {
21695 					/*
21696 					 * We are not supposed to send
21697 					 * anything.  So let's wait a little
21698 					 * bit longer before breaking SWS
21699 					 * avoidance.
21700 					 *
21701 					 * What should the value be?
21702 					 * Suggestion: MAX(init rexmit time,
21703 					 * tcp->tcp_rto)
21704 					 */
21705 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21706 				}
21707 				break;	/* success; too small */
21708 			}
21709 		}
21710 
21711 		tcph = tcp->tcp_tcph;
21712 
21713 		/*
21714 		 * The reason to adjust len here is that we need to set flags
21715 		 * and calculate checksum.
21716 		 */
21717 		if (do_lso_send)
21718 			len = lso_usable;
21719 
21720 		*usable -= len; /* Approximate - can be adjusted later */
21721 		if (*usable > 0)
21722 			tcph->th_flags[0] = TH_ACK;
21723 		else
21724 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21725 
21726 		/*
21727 		 * Prime pump for IP's checksumming on our behalf
21728 		 * Include the adjustment for a source route if any.
21729 		 */
21730 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21731 		sum = (sum >> 16) + (sum & 0xFFFF);
21732 		U16_TO_ABE16(sum, tcph->th_sum);
21733 
21734 		U32_TO_ABE32(*snxt, tcph->th_seq);
21735 
21736 		/*
21737 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21738 		 * set.  For the case when TCP_FSS_VALID is the only valid
21739 		 * bit (normal active close), branch off only when we think
21740 		 * that the FIN flag needs to be set.  Note for this case,
21741 		 * that (snxt + len) may not reflect the actual seg_len,
21742 		 * as len may be further reduced in tcp_xmit_mp().  If len
21743 		 * gets modified, we will end up here again.
21744 		 */
21745 		if (tcp->tcp_valid_bits != 0 &&
21746 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21747 		    ((*snxt + len) == tcp->tcp_fss))) {
21748 			uchar_t		*prev_rptr;
21749 			uint32_t	prev_snxt = tcp->tcp_snxt;
21750 
21751 			if (*tail_unsent == 0) {
21752 				ASSERT((*xmit_tail)->b_cont != NULL);
21753 				*xmit_tail = (*xmit_tail)->b_cont;
21754 				prev_rptr = (*xmit_tail)->b_rptr;
21755 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21756 				    (*xmit_tail)->b_rptr);
21757 			} else {
21758 				prev_rptr = (*xmit_tail)->b_rptr;
21759 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21760 				    *tail_unsent;
21761 			}
21762 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21763 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21764 			/* Restore tcp_snxt so we get amount sent right. */
21765 			tcp->tcp_snxt = prev_snxt;
21766 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21767 				/*
21768 				 * If the previous timestamp is still in use,
21769 				 * don't stomp on it.
21770 				 */
21771 				if ((*xmit_tail)->b_next == NULL) {
21772 					(*xmit_tail)->b_prev = local_time;
21773 					(*xmit_tail)->b_next =
21774 					    (mblk_t *)(uintptr_t)(*snxt);
21775 				}
21776 			} else
21777 				(*xmit_tail)->b_rptr = prev_rptr;
21778 
21779 			if (mp == NULL) {
21780 				if (ire != NULL)
21781 					IRE_REFRELE(ire);
21782 				return (-1);
21783 			}
21784 			mp1 = mp->b_cont;
21785 
21786 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21787 				tcp->tcp_last_sent_len = (ushort_t)len;
21788 			while (mp1->b_cont) {
21789 				*xmit_tail = (*xmit_tail)->b_cont;
21790 				(*xmit_tail)->b_prev = local_time;
21791 				(*xmit_tail)->b_next =
21792 				    (mblk_t *)(uintptr_t)(*snxt);
21793 				mp1 = mp1->b_cont;
21794 			}
21795 			*snxt += len;
21796 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21797 			BUMP_LOCAL(tcp->tcp_obsegs);
21798 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21799 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21800 			tcp_send_data(tcp, q, mp);
21801 			continue;
21802 		}
21803 
21804 		*snxt += len;	/* Adjust later if we don't send all of len */
21805 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21806 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21807 
21808 		if (*tail_unsent) {
21809 			/* Are the bytes above us in flight? */
21810 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21811 			if (rptr != (*xmit_tail)->b_rptr) {
21812 				*tail_unsent -= len;
21813 				if (len <= mss) /* LSO is unusable */
21814 					tcp->tcp_last_sent_len = (ushort_t)len;
21815 				len += tcp_hdr_len;
21816 				if (tcp->tcp_ipversion == IPV4_VERSION)
21817 					tcp->tcp_ipha->ipha_length = htons(len);
21818 				else
21819 					tcp->tcp_ip6h->ip6_plen =
21820 					    htons(len -
21821 					    ((char *)&tcp->tcp_ip6h[1] -
21822 					    tcp->tcp_iphc));
21823 				mp = dupb(*xmit_tail);
21824 				if (mp == NULL) {
21825 					if (ire != NULL)
21826 						IRE_REFRELE(ire);
21827 					return (-1);	/* out_of_mem */
21828 				}
21829 				mp->b_rptr = rptr;
21830 				/*
21831 				 * If the old timestamp is no longer in use,
21832 				 * sample a new timestamp now.
21833 				 */
21834 				if ((*xmit_tail)->b_next == NULL) {
21835 					(*xmit_tail)->b_prev = local_time;
21836 					(*xmit_tail)->b_next =
21837 					    (mblk_t *)(uintptr_t)(*snxt-len);
21838 				}
21839 				goto must_alloc;
21840 			}
21841 		} else {
21842 			*xmit_tail = (*xmit_tail)->b_cont;
21843 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21844 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21845 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21846 			    (*xmit_tail)->b_rptr);
21847 		}
21848 
21849 		(*xmit_tail)->b_prev = local_time;
21850 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21851 
21852 		*tail_unsent -= len;
21853 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21854 			tcp->tcp_last_sent_len = (ushort_t)len;
21855 
21856 		len += tcp_hdr_len;
21857 		if (tcp->tcp_ipversion == IPV4_VERSION)
21858 			tcp->tcp_ipha->ipha_length = htons(len);
21859 		else
21860 			tcp->tcp_ip6h->ip6_plen = htons(len -
21861 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21862 
21863 		mp = dupb(*xmit_tail);
21864 		if (mp == NULL) {
21865 			if (ire != NULL)
21866 				IRE_REFRELE(ire);
21867 			return (-1);	/* out_of_mem */
21868 		}
21869 
21870 		len = tcp_hdr_len;
21871 		/*
21872 		 * There are four reasons to allocate a new hdr mblk:
21873 		 *  1) The bytes above us are in use by another packet
21874 		 *  2) We don't have good alignment
21875 		 *  3) The mblk is being shared
21876 		 *  4) We don't have enough room for a header
21877 		 */
21878 		rptr = mp->b_rptr - len;
21879 		if (!OK_32PTR(rptr) ||
21880 		    ((db = mp->b_datap), db->db_ref != 2) ||
21881 		    rptr < db->db_base + ire_fp_mp_len) {
21882 			/* NOTE: we assume allocb returns an OK_32PTR */
21883 
21884 		must_alloc:;
21885 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21886 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21887 			if (mp1 == NULL) {
21888 				freemsg(mp);
21889 				if (ire != NULL)
21890 					IRE_REFRELE(ire);
21891 				return (-1);	/* out_of_mem */
21892 			}
21893 			mp1->b_cont = mp;
21894 			mp = mp1;
21895 			/* Leave room for Link Level header */
21896 			len = tcp_hdr_len;
21897 			rptr =
21898 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21899 			mp->b_wptr = &rptr[len];
21900 		}
21901 
21902 		/*
21903 		 * Fill in the header using the template header, and add
21904 		 * options such as time-stamp, ECN and/or SACK, as needed.
21905 		 */
21906 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21907 
21908 		mp->b_rptr = rptr;
21909 
21910 		if (*tail_unsent) {
21911 			int spill = *tail_unsent;
21912 
21913 			mp1 = mp->b_cont;
21914 			if (mp1 == NULL)
21915 				mp1 = mp;
21916 
21917 			/*
21918 			 * If we're a little short, tack on more mblks until
21919 			 * there is no more spillover.
21920 			 */
21921 			while (spill < 0) {
21922 				mblk_t *nmp;
21923 				int nmpsz;
21924 
21925 				nmp = (*xmit_tail)->b_cont;
21926 				nmpsz = MBLKL(nmp);
21927 
21928 				/*
21929 				 * Excess data in mblk; can we split it?
21930 				 * If MDT is enabled for the connection,
21931 				 * keep on splitting as this is a transient
21932 				 * send path.
21933 				 */
21934 				if (!do_lso_send && !tcp->tcp_mdt &&
21935 				    (spill + nmpsz > 0)) {
21936 					/*
21937 					 * Don't split if stream head was
21938 					 * told to break up larger writes
21939 					 * into smaller ones.
21940 					 */
21941 					if (tcp->tcp_maxpsz > 0)
21942 						break;
21943 
21944 					/*
21945 					 * Next mblk is less than SMSS/2
21946 					 * rounded up to nearest 64-byte;
21947 					 * let it get sent as part of the
21948 					 * next segment.
21949 					 */
21950 					if (tcp->tcp_localnet &&
21951 					    !tcp->tcp_cork &&
21952 					    (nmpsz < roundup((mss >> 1), 64)))
21953 						break;
21954 				}
21955 
21956 				*xmit_tail = nmp;
21957 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21958 				/* Stash for rtt use later */
21959 				(*xmit_tail)->b_prev = local_time;
21960 				(*xmit_tail)->b_next =
21961 				    (mblk_t *)(uintptr_t)(*snxt - len);
21962 				mp1->b_cont = dupb(*xmit_tail);
21963 				mp1 = mp1->b_cont;
21964 
21965 				spill += nmpsz;
21966 				if (mp1 == NULL) {
21967 					*tail_unsent = spill;
21968 					freemsg(mp);
21969 					if (ire != NULL)
21970 						IRE_REFRELE(ire);
21971 					return (-1);	/* out_of_mem */
21972 				}
21973 			}
21974 
21975 			/* Trim back any surplus on the last mblk */
21976 			if (spill >= 0) {
21977 				mp1->b_wptr -= spill;
21978 				*tail_unsent = spill;
21979 			} else {
21980 				/*
21981 				 * We did not send everything we could in
21982 				 * order to remain within the b_cont limit.
21983 				 */
21984 				*usable -= spill;
21985 				*snxt += spill;
21986 				tcp->tcp_last_sent_len += spill;
21987 				UPDATE_MIB(&tcps->tcps_mib,
21988 				    tcpOutDataBytes, spill);
21989 				/*
21990 				 * Adjust the checksum
21991 				 */
21992 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21993 				sum += spill;
21994 				sum = (sum >> 16) + (sum & 0xFFFF);
21995 				U16_TO_ABE16(sum, tcph->th_sum);
21996 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21997 					sum = ntohs(
21998 					    ((ipha_t *)rptr)->ipha_length) +
21999 					    spill;
22000 					((ipha_t *)rptr)->ipha_length =
22001 					    htons(sum);
22002 				} else {
22003 					sum = ntohs(
22004 					    ((ip6_t *)rptr)->ip6_plen) +
22005 					    spill;
22006 					((ip6_t *)rptr)->ip6_plen =
22007 					    htons(sum);
22008 				}
22009 				*tail_unsent = 0;
22010 			}
22011 		}
22012 		if (tcp->tcp_ip_forward_progress) {
22013 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
22014 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
22015 			tcp->tcp_ip_forward_progress = B_FALSE;
22016 		}
22017 
22018 		if (do_lso_send) {
22019 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
22020 			    num_lso_seg);
22021 			tcp->tcp_obsegs += num_lso_seg;
22022 
22023 			TCP_STAT(tcps, tcp_lso_times);
22024 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
22025 		} else {
22026 			tcp_send_data(tcp, q, mp);
22027 			BUMP_LOCAL(tcp->tcp_obsegs);
22028 		}
22029 	}
22030 
22031 	if (ire != NULL)
22032 		IRE_REFRELE(ire);
22033 	return (0);
22034 }
22035 
22036 /* Unlink and return any mblk that looks like it contains a MDT info */
22037 static mblk_t *
22038 tcp_mdt_info_mp(mblk_t *mp)
22039 {
22040 	mblk_t	*prev_mp;
22041 
22042 	for (;;) {
22043 		prev_mp = mp;
22044 		/* no more to process? */
22045 		if ((mp = mp->b_cont) == NULL)
22046 			break;
22047 
22048 		switch (DB_TYPE(mp)) {
22049 		case M_CTL:
22050 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
22051 				continue;
22052 			ASSERT(prev_mp != NULL);
22053 			prev_mp->b_cont = mp->b_cont;
22054 			mp->b_cont = NULL;
22055 			return (mp);
22056 		default:
22057 			break;
22058 		}
22059 	}
22060 	return (mp);
22061 }
22062 
22063 /* MDT info update routine, called when IP notifies us about MDT */
22064 static void
22065 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
22066 {
22067 	boolean_t prev_state;
22068 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22069 
22070 	/*
22071 	 * IP is telling us to abort MDT on this connection?  We know
22072 	 * this because the capability is only turned off when IP
22073 	 * encounters some pathological cases, e.g. link-layer change
22074 	 * where the new driver doesn't support MDT, or in situation
22075 	 * where MDT usage on the link-layer has been switched off.
22076 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
22077 	 * if the link-layer doesn't support MDT, and if it does, it
22078 	 * will indicate that the feature is to be turned on.
22079 	 */
22080 	prev_state = tcp->tcp_mdt;
22081 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
22082 	if (!tcp->tcp_mdt && !first) {
22083 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
22084 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
22085 		    (void *)tcp->tcp_connp));
22086 	}
22087 
22088 	/*
22089 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
22090 	 * so disable MDT otherwise.  The checks are done here
22091 	 * and in tcp_wput_data().
22092 	 */
22093 	if (tcp->tcp_mdt &&
22094 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22095 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22096 	    (tcp->tcp_ipversion == IPV6_VERSION &&
22097 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
22098 		tcp->tcp_mdt = B_FALSE;
22099 
22100 	if (tcp->tcp_mdt) {
22101 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
22102 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
22103 			    "version (%d), expected version is %d",
22104 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
22105 			tcp->tcp_mdt = B_FALSE;
22106 			return;
22107 		}
22108 
22109 		/*
22110 		 * We need the driver to be able to handle at least three
22111 		 * spans per packet in order for tcp MDT to be utilized.
22112 		 * The first is for the header portion, while the rest are
22113 		 * needed to handle a packet that straddles across two
22114 		 * virtually non-contiguous buffers; a typical tcp packet
22115 		 * therefore consists of only two spans.  Note that we take
22116 		 * a zero as "don't care".
22117 		 */
22118 		if (mdt_capab->ill_mdt_span_limit > 0 &&
22119 		    mdt_capab->ill_mdt_span_limit < 3) {
22120 			tcp->tcp_mdt = B_FALSE;
22121 			return;
22122 		}
22123 
22124 		/* a zero means driver wants default value */
22125 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
22126 		    tcps->tcps_mdt_max_pbufs);
22127 		if (tcp->tcp_mdt_max_pld == 0)
22128 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
22129 
22130 		/* ensure 32-bit alignment */
22131 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
22132 		    mdt_capab->ill_mdt_hdr_head), 4);
22133 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
22134 		    mdt_capab->ill_mdt_hdr_tail), 4);
22135 
22136 		if (!first && !prev_state) {
22137 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
22138 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
22139 			    (void *)tcp->tcp_connp));
22140 		}
22141 	}
22142 }
22143 
22144 /* Unlink and return any mblk that looks like it contains a LSO info */
22145 static mblk_t *
22146 tcp_lso_info_mp(mblk_t *mp)
22147 {
22148 	mblk_t	*prev_mp;
22149 
22150 	for (;;) {
22151 		prev_mp = mp;
22152 		/* no more to process? */
22153 		if ((mp = mp->b_cont) == NULL)
22154 			break;
22155 
22156 		switch (DB_TYPE(mp)) {
22157 		case M_CTL:
22158 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
22159 				continue;
22160 			ASSERT(prev_mp != NULL);
22161 			prev_mp->b_cont = mp->b_cont;
22162 			mp->b_cont = NULL;
22163 			return (mp);
22164 		default:
22165 			break;
22166 		}
22167 	}
22168 
22169 	return (mp);
22170 }
22171 
22172 /* LSO info update routine, called when IP notifies us about LSO */
22173 static void
22174 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
22175 {
22176 	tcp_stack_t *tcps = tcp->tcp_tcps;
22177 
22178 	/*
22179 	 * IP is telling us to abort LSO on this connection?  We know
22180 	 * this because the capability is only turned off when IP
22181 	 * encounters some pathological cases, e.g. link-layer change
22182 	 * where the new NIC/driver doesn't support LSO, or in situation
22183 	 * where LSO usage on the link-layer has been switched off.
22184 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
22185 	 * if the link-layer doesn't support LSO, and if it does, it
22186 	 * will indicate that the feature is to be turned on.
22187 	 */
22188 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
22189 	TCP_STAT(tcps, tcp_lso_enabled);
22190 
22191 	/*
22192 	 * We currently only support LSO on simple TCP/IPv4,
22193 	 * so disable LSO otherwise.  The checks are done here
22194 	 * and in tcp_wput_data().
22195 	 */
22196 	if (tcp->tcp_lso &&
22197 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22198 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22199 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
22200 		tcp->tcp_lso = B_FALSE;
22201 		TCP_STAT(tcps, tcp_lso_disabled);
22202 	} else {
22203 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
22204 		    lso_capab->ill_lso_max);
22205 	}
22206 }
22207 
22208 static void
22209 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22210 {
22211 	conn_t *connp = tcp->tcp_connp;
22212 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22213 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22214 
22215 	ASSERT(ire != NULL);
22216 
22217 	/*
22218 	 * We may be in the fastpath here, and although we essentially do
22219 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22220 	 * we try to keep things as brief as possible.  After all, these
22221 	 * are only best-effort checks, and we do more thorough ones prior
22222 	 * to calling tcp_send()/tcp_multisend().
22223 	 */
22224 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22225 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22226 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22227 	    !(ire->ire_flags & RTF_MULTIRT) &&
22228 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22229 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22230 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22231 			/* Cache the result */
22232 			connp->conn_lso_ok = B_TRUE;
22233 
22234 			ASSERT(ill->ill_lso_capab != NULL);
22235 			if (!ill->ill_lso_capab->ill_lso_on) {
22236 				ill->ill_lso_capab->ill_lso_on = 1;
22237 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22238 				    "LSO for interface %s\n", (void *)connp,
22239 				    ill->ill_name));
22240 			}
22241 			tcp_lso_update(tcp, ill->ill_lso_capab);
22242 		} else if (ipst->ips_ip_multidata_outbound &&
22243 		    ILL_MDT_CAPABLE(ill)) {
22244 			/* Cache the result */
22245 			connp->conn_mdt_ok = B_TRUE;
22246 
22247 			ASSERT(ill->ill_mdt_capab != NULL);
22248 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22249 				ill->ill_mdt_capab->ill_mdt_on = 1;
22250 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22251 				    "MDT for interface %s\n", (void *)connp,
22252 				    ill->ill_name));
22253 			}
22254 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22255 		}
22256 	}
22257 
22258 	/*
22259 	 * The goal is to reduce the number of generated tcp segments by
22260 	 * setting the maxpsz multiplier to 0; this will have an affect on
22261 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22262 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22263 	 * of outbound segments and incoming ACKs, thus allowing for better
22264 	 * network and system performance.  In contrast the legacy behavior
22265 	 * may result in sending less than SMSS size, because the last mblk
22266 	 * for some packets may have more data than needed to make up SMSS,
22267 	 * and the legacy code refused to "split" it.
22268 	 *
22269 	 * We apply the new behavior on following situations:
22270 	 *
22271 	 *   1) Loopback connections,
22272 	 *   2) Connections in which the remote peer is not on local subnet,
22273 	 *   3) Local subnet connections over the bge interface (see below).
22274 	 *
22275 	 * Ideally, we would like this behavior to apply for interfaces other
22276 	 * than bge.  However, doing so would negatively impact drivers which
22277 	 * perform dynamic mapping and unmapping of DMA resources, which are
22278 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22279 	 * packet will be generated by tcp).  The bge driver does not suffer
22280 	 * from this, as it copies the mblks into pre-mapped buffers, and
22281 	 * therefore does not require more I/O resources than before.
22282 	 *
22283 	 * Otherwise, this behavior is present on all network interfaces when
22284 	 * the destination endpoint is non-local, since reducing the number
22285 	 * of packets in general is good for the network.
22286 	 *
22287 	 * TODO We need to remove this hard-coded conditional for bge once
22288 	 *	a better "self-tuning" mechanism, or a way to comprehend
22289 	 *	the driver transmit strategy is devised.  Until the solution
22290 	 *	is found and well understood, we live with this hack.
22291 	 */
22292 	if (!tcp_static_maxpsz &&
22293 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22294 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22295 		/* override the default value */
22296 		tcp->tcp_maxpsz = 0;
22297 
22298 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22299 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22300 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22301 	}
22302 
22303 	/* set the stream head parameters accordingly */
22304 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22305 }
22306 
22307 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22308 static void
22309 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22310 {
22311 	uchar_t	fval = *mp->b_rptr;
22312 	mblk_t	*tail;
22313 	queue_t	*q = tcp->tcp_wq;
22314 
22315 	/* TODO: How should flush interact with urgent data? */
22316 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22317 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22318 		/*
22319 		 * Flush only data that has not yet been put on the wire.  If
22320 		 * we flush data that we have already transmitted, life, as we
22321 		 * know it, may come to an end.
22322 		 */
22323 		tail = tcp->tcp_xmit_tail;
22324 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22325 		tcp->tcp_xmit_tail_unsent = 0;
22326 		tcp->tcp_unsent = 0;
22327 		if (tail->b_wptr != tail->b_rptr)
22328 			tail = tail->b_cont;
22329 		if (tail) {
22330 			mblk_t **excess = &tcp->tcp_xmit_head;
22331 			for (;;) {
22332 				mblk_t *mp1 = *excess;
22333 				if (mp1 == tail)
22334 					break;
22335 				tcp->tcp_xmit_tail = mp1;
22336 				tcp->tcp_xmit_last = mp1;
22337 				excess = &mp1->b_cont;
22338 			}
22339 			*excess = NULL;
22340 			tcp_close_mpp(&tail);
22341 			if (tcp->tcp_snd_zcopy_aware)
22342 				tcp_zcopy_notify(tcp);
22343 		}
22344 		/*
22345 		 * We have no unsent data, so unsent must be less than
22346 		 * tcp_xmit_lowater, so re-enable flow.
22347 		 */
22348 		mutex_enter(&tcp->tcp_non_sq_lock);
22349 		if (tcp->tcp_flow_stopped) {
22350 			tcp_clrqfull(tcp);
22351 		}
22352 		mutex_exit(&tcp->tcp_non_sq_lock);
22353 	}
22354 	/*
22355 	 * TODO: you can't just flush these, you have to increase rwnd for one
22356 	 * thing.  For another, how should urgent data interact?
22357 	 */
22358 	if (fval & FLUSHR) {
22359 		*mp->b_rptr = fval & ~FLUSHW;
22360 		/* XXX */
22361 		qreply(q, mp);
22362 		return;
22363 	}
22364 	freemsg(mp);
22365 }
22366 
22367 /*
22368  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22369  * messages.
22370  */
22371 static void
22372 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22373 {
22374 	mblk_t	*mp1;
22375 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22376 	STRUCT_HANDLE(strbuf, sb);
22377 	queue_t *q = tcp->tcp_wq;
22378 	int	error;
22379 	uint_t	addrlen;
22380 
22381 	/* Make sure it is one of ours. */
22382 	switch (iocp->ioc_cmd) {
22383 	case TI_GETMYNAME:
22384 	case TI_GETPEERNAME:
22385 		break;
22386 	default:
22387 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22388 		return;
22389 	}
22390 	switch (mi_copy_state(q, mp, &mp1)) {
22391 	case -1:
22392 		return;
22393 	case MI_COPY_CASE(MI_COPY_IN, 1):
22394 		break;
22395 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22396 		/* Copy out the strbuf. */
22397 		mi_copyout(q, mp);
22398 		return;
22399 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22400 		/* All done. */
22401 		mi_copy_done(q, mp, 0);
22402 		return;
22403 	default:
22404 		mi_copy_done(q, mp, EPROTO);
22405 		return;
22406 	}
22407 	/* Check alignment of the strbuf */
22408 	if (!OK_32PTR(mp1->b_rptr)) {
22409 		mi_copy_done(q, mp, EINVAL);
22410 		return;
22411 	}
22412 
22413 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22414 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22415 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22416 		mi_copy_done(q, mp, EINVAL);
22417 		return;
22418 	}
22419 
22420 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22421 	if (mp1 == NULL)
22422 		return;
22423 
22424 	switch (iocp->ioc_cmd) {
22425 	case TI_GETMYNAME:
22426 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22427 		break;
22428 	case TI_GETPEERNAME:
22429 		error = tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22430 		break;
22431 	}
22432 
22433 	if (error != 0) {
22434 		mi_copy_done(q, mp, error);
22435 	} else {
22436 		mp1->b_wptr += addrlen;
22437 		STRUCT_FSET(sb, len, addrlen);
22438 
22439 		/* Copy out the address */
22440 		mi_copyout(q, mp);
22441 	}
22442 }
22443 
22444 /*
22445  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22446  * messages.
22447  */
22448 /* ARGSUSED */
22449 static void
22450 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22451 {
22452 	conn_t 	*connp = (conn_t *)arg;
22453 	tcp_t	*tcp = connp->conn_tcp;
22454 	queue_t	*q = tcp->tcp_wq;
22455 	struct iocblk	*iocp;
22456 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22457 
22458 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22459 	/*
22460 	 * Try and ASSERT the minimum possible references on the
22461 	 * conn early enough. Since we are executing on write side,
22462 	 * the connection is obviously not detached and that means
22463 	 * there is a ref each for TCP and IP. Since we are behind
22464 	 * the squeue, the minimum references needed are 3. If the
22465 	 * conn is in classifier hash list, there should be an
22466 	 * extra ref for that (we check both the possibilities).
22467 	 */
22468 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22469 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22470 
22471 	iocp = (struct iocblk *)mp->b_rptr;
22472 	switch (iocp->ioc_cmd) {
22473 	case TCP_IOC_DEFAULT_Q:
22474 		/* Wants to be the default wq. */
22475 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22476 			iocp->ioc_error = EPERM;
22477 			iocp->ioc_count = 0;
22478 			mp->b_datap->db_type = M_IOCACK;
22479 			qreply(q, mp);
22480 			return;
22481 		}
22482 		tcp_def_q_set(tcp, mp);
22483 		return;
22484 	case _SIOCSOCKFALLBACK:
22485 		/*
22486 		 * Either sockmod is about to be popped and the socket
22487 		 * would now be treated as a plain stream, or a module
22488 		 * is about to be pushed so we could no longer use read-
22489 		 * side synchronous streams for fused loopback tcp.
22490 		 * Drain any queued data and disable direct sockfs
22491 		 * interface from now on.
22492 		 */
22493 		if (!tcp->tcp_issocket) {
22494 			DB_TYPE(mp) = M_IOCNAK;
22495 			iocp->ioc_error = EINVAL;
22496 		} else {
22497 #ifdef	_ILP32
22498 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
22499 #else
22500 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22501 #endif
22502 			/*
22503 			 * Insert this socket into the acceptor hash.
22504 			 * We might need it for T_CONN_RES message
22505 			 */
22506 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22507 
22508 			if (tcp->tcp_fused) {
22509 				/*
22510 				 * This is a fused loopback tcp; disable
22511 				 * read-side synchronous streams interface
22512 				 * and drain any queued data.  It is okay
22513 				 * to do this for non-synchronous streams
22514 				 * fused tcp as well.
22515 				 */
22516 				tcp_fuse_disable_pair(tcp, B_FALSE);
22517 			}
22518 			tcp->tcp_issocket = B_FALSE;
22519 			tcp->tcp_sodirect = NULL;
22520 			TCP_STAT(tcps, tcp_sock_fallback);
22521 
22522 			DB_TYPE(mp) = M_IOCACK;
22523 			iocp->ioc_error = 0;
22524 		}
22525 		iocp->ioc_count = 0;
22526 		iocp->ioc_rval = 0;
22527 		qreply(q, mp);
22528 		return;
22529 	}
22530 	CALL_IP_WPUT(connp, q, mp);
22531 }
22532 
22533 /*
22534  * This routine is called by tcp_wput() to handle all TPI requests.
22535  */
22536 /* ARGSUSED */
22537 static void
22538 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22539 {
22540 	conn_t 	*connp = (conn_t *)arg;
22541 	tcp_t	*tcp = connp->conn_tcp;
22542 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22543 	uchar_t *rptr;
22544 	t_scalar_t type;
22545 	int len;
22546 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22547 
22548 	/*
22549 	 * Try and ASSERT the minimum possible references on the
22550 	 * conn early enough. Since we are executing on write side,
22551 	 * the connection is obviously not detached and that means
22552 	 * there is a ref each for TCP and IP. Since we are behind
22553 	 * the squeue, the minimum references needed are 3. If the
22554 	 * conn is in classifier hash list, there should be an
22555 	 * extra ref for that (we check both the possibilities).
22556 	 */
22557 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22558 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22559 
22560 	rptr = mp->b_rptr;
22561 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22562 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22563 		type = ((union T_primitives *)rptr)->type;
22564 		if (type == T_EXDATA_REQ) {
22565 			uint32_t msize = msgdsize(mp->b_cont);
22566 
22567 			len = msize - 1;
22568 			if (len < 0) {
22569 				freemsg(mp);
22570 				return;
22571 			}
22572 			/*
22573 			 * Try to force urgent data out on the wire.
22574 			 * Even if we have unsent data this will
22575 			 * at least send the urgent flag.
22576 			 * XXX does not handle more flag correctly.
22577 			 */
22578 			len += tcp->tcp_unsent;
22579 			len += tcp->tcp_snxt;
22580 			tcp->tcp_urg = len;
22581 			tcp->tcp_valid_bits |= TCP_URG_VALID;
22582 
22583 			/* Bypass tcp protocol for fused tcp loopback */
22584 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
22585 				return;
22586 		} else if (type != T_DATA_REQ) {
22587 			goto non_urgent_data;
22588 		}
22589 		/* TODO: options, flags, ... from user */
22590 		/* Set length to zero for reclamation below */
22591 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22592 		freeb(mp);
22593 		return;
22594 	} else {
22595 		if (tcp->tcp_debug) {
22596 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22597 			    "tcp_wput_proto, dropping one...");
22598 		}
22599 		freemsg(mp);
22600 		return;
22601 	}
22602 
22603 non_urgent_data:
22604 
22605 	switch ((int)tprim->type) {
22606 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22607 		/*
22608 		 * save the kssl_ent_t from the next block, and convert this
22609 		 * back to a normal bind_req.
22610 		 */
22611 		if (mp->b_cont != NULL) {
22612 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22613 
22614 			if (tcp->tcp_kssl_ent != NULL) {
22615 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22616 				    KSSL_NO_PROXY);
22617 				tcp->tcp_kssl_ent = NULL;
22618 			}
22619 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22620 			    sizeof (kssl_ent_t));
22621 			kssl_hold_ent(tcp->tcp_kssl_ent);
22622 			freemsg(mp->b_cont);
22623 			mp->b_cont = NULL;
22624 		}
22625 		tprim->type = T_BIND_REQ;
22626 
22627 	/* FALLTHROUGH */
22628 	case O_T_BIND_REQ:	/* bind request */
22629 	case T_BIND_REQ:	/* new semantics bind request */
22630 		tcp_bind(tcp, mp);
22631 		break;
22632 	case T_UNBIND_REQ:	/* unbind request */
22633 		tcp_unbind(tcp, mp);
22634 		break;
22635 	case O_T_CONN_RES:	/* old connection response XXX */
22636 	case T_CONN_RES:	/* connection response */
22637 		tcp_accept(tcp, mp);
22638 		break;
22639 	case T_CONN_REQ:	/* connection request */
22640 		tcp_connect(tcp, mp);
22641 		break;
22642 	case T_DISCON_REQ:	/* disconnect request */
22643 		tcp_disconnect(tcp, mp);
22644 		break;
22645 	case T_CAPABILITY_REQ:
22646 		tcp_capability_req(tcp, mp);	/* capability request */
22647 		break;
22648 	case T_INFO_REQ:	/* information request */
22649 		tcp_info_req(tcp, mp);
22650 		break;
22651 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22652 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22653 		    &tcp_opt_obj, B_TRUE);
22654 		break;
22655 	case T_OPTMGMT_REQ:
22656 		/*
22657 		 * Note:  no support for snmpcom_req() through new
22658 		 * T_OPTMGMT_REQ. See comments in ip.c
22659 		 */
22660 		/* Only IP is allowed to return meaningful value */
22661 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22662 		    B_TRUE);
22663 		break;
22664 
22665 	case T_UNITDATA_REQ:	/* unitdata request */
22666 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22667 		break;
22668 	case T_ORDREL_REQ:	/* orderly release req */
22669 		freemsg(mp);
22670 
22671 		if (tcp->tcp_fused)
22672 			tcp_unfuse(tcp);
22673 
22674 		if (tcp_xmit_end(tcp) != 0) {
22675 			/*
22676 			 * We were crossing FINs and got a reset from
22677 			 * the other side. Just ignore it.
22678 			 */
22679 			if (tcp->tcp_debug) {
22680 				(void) strlog(TCP_MOD_ID, 0, 1,
22681 				    SL_ERROR|SL_TRACE,
22682 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22683 				    "state %s",
22684 				    tcp_display(tcp, NULL,
22685 				    DISP_ADDR_AND_PORT));
22686 			}
22687 		}
22688 		break;
22689 	case T_ADDR_REQ:
22690 		tcp_addr_req(tcp, mp);
22691 		break;
22692 	default:
22693 		if (tcp->tcp_debug) {
22694 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22695 			    "tcp_wput_proto, bogus TPI msg, type %d",
22696 			    tprim->type);
22697 		}
22698 		/*
22699 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22700 		 * to recover.
22701 		 */
22702 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22703 		break;
22704 	}
22705 }
22706 
22707 /*
22708  * The TCP write service routine should never be called...
22709  */
22710 /* ARGSUSED */
22711 static void
22712 tcp_wsrv(queue_t *q)
22713 {
22714 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22715 
22716 	TCP_STAT(tcps, tcp_wsrv_called);
22717 }
22718 
22719 /* Non overlapping byte exchanger */
22720 static void
22721 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22722 {
22723 	uchar_t	uch;
22724 
22725 	while (len-- > 0) {
22726 		uch = a[len];
22727 		a[len] = b[len];
22728 		b[len] = uch;
22729 	}
22730 }
22731 
22732 /*
22733  * Send out a control packet on the tcp connection specified.  This routine
22734  * is typically called where we need a simple ACK or RST generated.
22735  */
22736 static void
22737 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22738 {
22739 	uchar_t		*rptr;
22740 	tcph_t		*tcph;
22741 	ipha_t		*ipha = NULL;
22742 	ip6_t		*ip6h = NULL;
22743 	uint32_t	sum;
22744 	int		tcp_hdr_len;
22745 	int		tcp_ip_hdr_len;
22746 	mblk_t		*mp;
22747 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22748 
22749 	/*
22750 	 * Save sum for use in source route later.
22751 	 */
22752 	ASSERT(tcp != NULL);
22753 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22754 	tcp_hdr_len = tcp->tcp_hdr_len;
22755 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22756 
22757 	/* If a text string is passed in with the request, pass it to strlog. */
22758 	if (str != NULL && tcp->tcp_debug) {
22759 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22760 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22761 		    str, seq, ack, ctl);
22762 	}
22763 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22764 	    BPRI_MED);
22765 	if (mp == NULL) {
22766 		return;
22767 	}
22768 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22769 	mp->b_rptr = rptr;
22770 	mp->b_wptr = &rptr[tcp_hdr_len];
22771 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22772 
22773 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22774 		ipha = (ipha_t *)rptr;
22775 		ipha->ipha_length = htons(tcp_hdr_len);
22776 	} else {
22777 		ip6h = (ip6_t *)rptr;
22778 		ASSERT(tcp != NULL);
22779 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22780 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22781 	}
22782 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22783 	tcph->th_flags[0] = (uint8_t)ctl;
22784 	if (ctl & TH_RST) {
22785 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22786 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22787 		/*
22788 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22789 		 */
22790 		if (tcp->tcp_snd_ts_ok &&
22791 		    tcp->tcp_state > TCPS_SYN_SENT) {
22792 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22793 			*(mp->b_wptr) = TCPOPT_EOL;
22794 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22795 				ipha->ipha_length = htons(tcp_hdr_len -
22796 				    TCPOPT_REAL_TS_LEN);
22797 			} else {
22798 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22799 				    TCPOPT_REAL_TS_LEN);
22800 			}
22801 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22802 			sum -= TCPOPT_REAL_TS_LEN;
22803 		}
22804 	}
22805 	if (ctl & TH_ACK) {
22806 		if (tcp->tcp_snd_ts_ok) {
22807 			U32_TO_BE32(lbolt,
22808 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22809 			U32_TO_BE32(tcp->tcp_ts_recent,
22810 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22811 		}
22812 
22813 		/* Update the latest receive window size in TCP header. */
22814 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22815 		    tcph->th_win);
22816 		tcp->tcp_rack = ack;
22817 		tcp->tcp_rack_cnt = 0;
22818 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22819 	}
22820 	BUMP_LOCAL(tcp->tcp_obsegs);
22821 	U32_TO_BE32(seq, tcph->th_seq);
22822 	U32_TO_BE32(ack, tcph->th_ack);
22823 	/*
22824 	 * Include the adjustment for a source route if any.
22825 	 */
22826 	sum = (sum >> 16) + (sum & 0xFFFF);
22827 	U16_TO_BE16(sum, tcph->th_sum);
22828 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22829 }
22830 
22831 /*
22832  * If this routine returns B_TRUE, TCP can generate a RST in response
22833  * to a segment.  If it returns B_FALSE, TCP should not respond.
22834  */
22835 static boolean_t
22836 tcp_send_rst_chk(tcp_stack_t *tcps)
22837 {
22838 	clock_t	now;
22839 
22840 	/*
22841 	 * TCP needs to protect itself from generating too many RSTs.
22842 	 * This can be a DoS attack by sending us random segments
22843 	 * soliciting RSTs.
22844 	 *
22845 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22846 	 * in each 1 second interval.  In this way, TCP still generate
22847 	 * RSTs in normal cases but when under attack, the impact is
22848 	 * limited.
22849 	 */
22850 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22851 		now = lbolt;
22852 		/* lbolt can wrap around. */
22853 		if ((tcps->tcps_last_rst_intrvl > now) ||
22854 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22855 		    1*SECONDS)) {
22856 			tcps->tcps_last_rst_intrvl = now;
22857 			tcps->tcps_rst_cnt = 1;
22858 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22859 			return (B_FALSE);
22860 		}
22861 	}
22862 	return (B_TRUE);
22863 }
22864 
22865 /*
22866  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22867  */
22868 static void
22869 tcp_ip_ire_mark_advice(tcp_t *tcp)
22870 {
22871 	mblk_t *mp;
22872 	ipic_t *ipic;
22873 
22874 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22875 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22876 		    &ipic);
22877 	} else {
22878 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22879 		    &ipic);
22880 	}
22881 	if (mp == NULL)
22882 		return;
22883 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22884 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22885 }
22886 
22887 /*
22888  * Return an IP advice ioctl mblk and set ipic to be the pointer
22889  * to the advice structure.
22890  */
22891 static mblk_t *
22892 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22893 {
22894 	struct iocblk *ioc;
22895 	mblk_t *mp, *mp1;
22896 
22897 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22898 	if (mp == NULL)
22899 		return (NULL);
22900 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22901 	*ipic = (ipic_t *)mp->b_rptr;
22902 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22903 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22904 
22905 	bcopy(addr, *ipic + 1, addr_len);
22906 
22907 	(*ipic)->ipic_addr_length = addr_len;
22908 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22909 
22910 	mp1 = mkiocb(IP_IOCTL);
22911 	if (mp1 == NULL) {
22912 		freemsg(mp);
22913 		return (NULL);
22914 	}
22915 	mp1->b_cont = mp;
22916 	ioc = (struct iocblk *)mp1->b_rptr;
22917 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22918 
22919 	return (mp1);
22920 }
22921 
22922 /*
22923  * Generate a reset based on an inbound packet, connp is set by caller
22924  * when RST is in response to an unexpected inbound packet for which
22925  * there is active tcp state in the system.
22926  *
22927  * IPSEC NOTE : Try to send the reply with the same protection as it came
22928  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22929  * the packet will go out at the same level of protection as it came in by
22930  * converting the IPSEC_IN to IPSEC_OUT.
22931  */
22932 static void
22933 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22934     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22935     tcp_stack_t *tcps, conn_t *connp)
22936 {
22937 	ipha_t		*ipha = NULL;
22938 	ip6_t		*ip6h = NULL;
22939 	ushort_t	len;
22940 	tcph_t		*tcph;
22941 	int		i;
22942 	mblk_t		*ipsec_mp;
22943 	boolean_t	mctl_present;
22944 	ipic_t		*ipic;
22945 	ipaddr_t	v4addr;
22946 	in6_addr_t	v6addr;
22947 	int		addr_len;
22948 	void		*addr;
22949 	queue_t		*q = tcps->tcps_g_q;
22950 	tcp_t		*tcp;
22951 	cred_t		*cr;
22952 	mblk_t		*nmp;
22953 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22954 
22955 	if (tcps->tcps_g_q == NULL) {
22956 		/*
22957 		 * For non-zero stackids the default queue isn't created
22958 		 * until the first open, thus there can be a need to send
22959 		 * a reset before then. But we can't do that, hence we just
22960 		 * drop the packet. Later during boot, when the default queue
22961 		 * has been setup, a retransmitted packet from the peer
22962 		 * will result in a reset.
22963 		 */
22964 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22965 		    GLOBAL_NETSTACKID);
22966 		freemsg(mp);
22967 		return;
22968 	}
22969 
22970 	if (connp != NULL)
22971 		tcp = connp->conn_tcp;
22972 	else
22973 		tcp = Q_TO_TCP(q);
22974 
22975 	if (!tcp_send_rst_chk(tcps)) {
22976 		tcps->tcps_rst_unsent++;
22977 		freemsg(mp);
22978 		return;
22979 	}
22980 
22981 	if (mp->b_datap->db_type == M_CTL) {
22982 		ipsec_mp = mp;
22983 		mp = mp->b_cont;
22984 		mctl_present = B_TRUE;
22985 	} else {
22986 		ipsec_mp = mp;
22987 		mctl_present = B_FALSE;
22988 	}
22989 
22990 	if (str && q && tcps->tcps_dbg) {
22991 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22992 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22993 		    "flags 0x%x",
22994 		    str, seq, ack, ctl);
22995 	}
22996 	if (mp->b_datap->db_ref != 1) {
22997 		mblk_t *mp1 = copyb(mp);
22998 		freemsg(mp);
22999 		mp = mp1;
23000 		if (!mp) {
23001 			if (mctl_present)
23002 				freeb(ipsec_mp);
23003 			return;
23004 		} else {
23005 			if (mctl_present) {
23006 				ipsec_mp->b_cont = mp;
23007 			} else {
23008 				ipsec_mp = mp;
23009 			}
23010 		}
23011 	} else if (mp->b_cont) {
23012 		freemsg(mp->b_cont);
23013 		mp->b_cont = NULL;
23014 	}
23015 	/*
23016 	 * We skip reversing source route here.
23017 	 * (for now we replace all IP options with EOL)
23018 	 */
23019 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23020 		ipha = (ipha_t *)mp->b_rptr;
23021 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
23022 			mp->b_rptr[i] = IPOPT_EOL;
23023 		/*
23024 		 * Make sure that src address isn't flagrantly invalid.
23025 		 * Not all broadcast address checking for the src address
23026 		 * is possible, since we don't know the netmask of the src
23027 		 * addr.  No check for destination address is done, since
23028 		 * IP will not pass up a packet with a broadcast dest
23029 		 * address to TCP.  Similar checks are done below for IPv6.
23030 		 */
23031 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
23032 		    CLASSD(ipha->ipha_src)) {
23033 			freemsg(ipsec_mp);
23034 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
23035 			return;
23036 		}
23037 	} else {
23038 		ip6h = (ip6_t *)mp->b_rptr;
23039 
23040 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
23041 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
23042 			freemsg(ipsec_mp);
23043 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
23044 			return;
23045 		}
23046 
23047 		/* Remove any extension headers assuming partial overlay */
23048 		if (ip_hdr_len > IPV6_HDR_LEN) {
23049 			uint8_t *to;
23050 
23051 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
23052 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
23053 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
23054 			ip_hdr_len = IPV6_HDR_LEN;
23055 			ip6h = (ip6_t *)mp->b_rptr;
23056 			ip6h->ip6_nxt = IPPROTO_TCP;
23057 		}
23058 	}
23059 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
23060 	if (tcph->th_flags[0] & TH_RST) {
23061 		freemsg(ipsec_mp);
23062 		return;
23063 	}
23064 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
23065 	len = ip_hdr_len + sizeof (tcph_t);
23066 	mp->b_wptr = &mp->b_rptr[len];
23067 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23068 		ipha->ipha_length = htons(len);
23069 		/* Swap addresses */
23070 		v4addr = ipha->ipha_src;
23071 		ipha->ipha_src = ipha->ipha_dst;
23072 		ipha->ipha_dst = v4addr;
23073 		ipha->ipha_ident = 0;
23074 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
23075 		addr_len = IP_ADDR_LEN;
23076 		addr = &v4addr;
23077 	} else {
23078 		/* No ip6i_t in this case */
23079 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
23080 		/* Swap addresses */
23081 		v6addr = ip6h->ip6_src;
23082 		ip6h->ip6_src = ip6h->ip6_dst;
23083 		ip6h->ip6_dst = v6addr;
23084 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
23085 		addr_len = IPV6_ADDR_LEN;
23086 		addr = &v6addr;
23087 	}
23088 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
23089 	U32_TO_BE32(ack, tcph->th_ack);
23090 	U32_TO_BE32(seq, tcph->th_seq);
23091 	U16_TO_BE16(0, tcph->th_win);
23092 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
23093 	tcph->th_flags[0] = (uint8_t)ctl;
23094 	if (ctl & TH_RST) {
23095 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
23096 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23097 	}
23098 
23099 	/* IP trusts us to set up labels when required. */
23100 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
23101 	    crgetlabel(cr) != NULL) {
23102 		int err;
23103 
23104 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
23105 			err = tsol_check_label(cr, &mp,
23106 			    tcp->tcp_connp->conn_mac_exempt,
23107 			    tcps->tcps_netstack->netstack_ip);
23108 		else
23109 			err = tsol_check_label_v6(cr, &mp,
23110 			    tcp->tcp_connp->conn_mac_exempt,
23111 			    tcps->tcps_netstack->netstack_ip);
23112 		if (mctl_present)
23113 			ipsec_mp->b_cont = mp;
23114 		else
23115 			ipsec_mp = mp;
23116 		if (err != 0) {
23117 			freemsg(ipsec_mp);
23118 			return;
23119 		}
23120 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23121 			ipha = (ipha_t *)mp->b_rptr;
23122 		} else {
23123 			ip6h = (ip6_t *)mp->b_rptr;
23124 		}
23125 	}
23126 
23127 	if (mctl_present) {
23128 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23129 
23130 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23131 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
23132 			return;
23133 		}
23134 	}
23135 	if (zoneid == ALL_ZONES)
23136 		zoneid = GLOBAL_ZONEID;
23137 
23138 	/* Add the zoneid so ip_output routes it properly */
23139 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
23140 		freemsg(ipsec_mp);
23141 		return;
23142 	}
23143 	ipsec_mp = nmp;
23144 
23145 	/*
23146 	 * NOTE:  one might consider tracing a TCP packet here, but
23147 	 * this function has no active TCP state and no tcp structure
23148 	 * that has a trace buffer.  If we traced here, we would have
23149 	 * to keep a local trace buffer in tcp_record_trace().
23150 	 *
23151 	 * TSol note: The mblk that contains the incoming packet was
23152 	 * reused by tcp_xmit_listener_reset, so it already contains
23153 	 * the right credentials and we don't need to call mblk_setcred.
23154 	 * Also the conn's cred is not right since it is associated
23155 	 * with tcps_g_q.
23156 	 */
23157 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
23158 
23159 	/*
23160 	 * Tell IP to mark the IRE used for this destination temporary.
23161 	 * This way, we can limit our exposure to DoS attack because IP
23162 	 * creates an IRE for each destination.  If there are too many,
23163 	 * the time to do any routing lookup will be extremely long.  And
23164 	 * the lookup can be in interrupt context.
23165 	 *
23166 	 * Note that in normal circumstances, this marking should not
23167 	 * affect anything.  It would be nice if only 1 message is
23168 	 * needed to inform IP that the IRE created for this RST should
23169 	 * not be added to the cache table.  But there is currently
23170 	 * not such communication mechanism between TCP and IP.  So
23171 	 * the best we can do now is to send the advice ioctl to IP
23172 	 * to mark the IRE temporary.
23173 	 */
23174 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
23175 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
23176 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23177 	}
23178 }
23179 
23180 /*
23181  * Initiate closedown sequence on an active connection.  (May be called as
23182  * writer.)  Return value zero for OK return, non-zero for error return.
23183  */
23184 static int
23185 tcp_xmit_end(tcp_t *tcp)
23186 {
23187 	ipic_t	*ipic;
23188 	mblk_t	*mp;
23189 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23190 
23191 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
23192 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
23193 		/*
23194 		 * Invalid state, only states TCPS_SYN_RCVD,
23195 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
23196 		 */
23197 		return (-1);
23198 	}
23199 
23200 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
23201 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
23202 	/*
23203 	 * If there is nothing more unsent, send the FIN now.
23204 	 * Otherwise, it will go out with the last segment.
23205 	 */
23206 	if (tcp->tcp_unsent == 0) {
23207 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
23208 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
23209 
23210 		if (mp) {
23211 			tcp_send_data(tcp, tcp->tcp_wq, mp);
23212 		} else {
23213 			/*
23214 			 * Couldn't allocate msg.  Pretend we got it out.
23215 			 * Wait for rexmit timeout.
23216 			 */
23217 			tcp->tcp_snxt = tcp->tcp_fss + 1;
23218 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23219 		}
23220 
23221 		/*
23222 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23223 		 * changed.
23224 		 */
23225 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23226 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23227 		}
23228 	} else {
23229 		/*
23230 		 * If tcp->tcp_cork is set, then the data will not get sent,
23231 		 * so we have to check that and unset it first.
23232 		 */
23233 		if (tcp->tcp_cork)
23234 			tcp->tcp_cork = B_FALSE;
23235 		tcp_wput_data(tcp, NULL, B_FALSE);
23236 	}
23237 
23238 	/*
23239 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23240 	 * is 0, don't update the cache.
23241 	 */
23242 	if (tcps->tcps_rtt_updates == 0 ||
23243 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23244 		return (0);
23245 
23246 	/*
23247 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23248 	 * different from the destination.
23249 	 */
23250 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23251 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23252 			return (0);
23253 		}
23254 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23255 		    &ipic);
23256 	} else {
23257 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23258 		    &tcp->tcp_ip6h->ip6_dst))) {
23259 			return (0);
23260 		}
23261 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23262 		    &ipic);
23263 	}
23264 
23265 	/* Record route attributes in the IRE for use by future connections. */
23266 	if (mp == NULL)
23267 		return (0);
23268 
23269 	/*
23270 	 * We do not have a good algorithm to update ssthresh at this time.
23271 	 * So don't do any update.
23272 	 */
23273 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23274 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23275 
23276 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23277 	return (0);
23278 }
23279 
23280 /*
23281  * Generate a "no listener here" RST in response to an "unknown" segment.
23282  * connp is set by caller when RST is in response to an unexpected
23283  * inbound packet for which there is active tcp state in the system.
23284  * Note that we are reusing the incoming mp to construct the outgoing RST.
23285  */
23286 void
23287 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23288     tcp_stack_t *tcps, conn_t *connp)
23289 {
23290 	uchar_t		*rptr;
23291 	uint32_t	seg_len;
23292 	tcph_t		*tcph;
23293 	uint32_t	seg_seq;
23294 	uint32_t	seg_ack;
23295 	uint_t		flags;
23296 	mblk_t		*ipsec_mp;
23297 	ipha_t 		*ipha;
23298 	ip6_t 		*ip6h;
23299 	boolean_t	mctl_present = B_FALSE;
23300 	boolean_t	check = B_TRUE;
23301 	boolean_t	policy_present;
23302 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23303 
23304 	TCP_STAT(tcps, tcp_no_listener);
23305 
23306 	ipsec_mp = mp;
23307 
23308 	if (mp->b_datap->db_type == M_CTL) {
23309 		ipsec_in_t *ii;
23310 
23311 		mctl_present = B_TRUE;
23312 		mp = mp->b_cont;
23313 
23314 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23315 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23316 		if (ii->ipsec_in_dont_check) {
23317 			check = B_FALSE;
23318 			if (!ii->ipsec_in_secure) {
23319 				freeb(ipsec_mp);
23320 				mctl_present = B_FALSE;
23321 				ipsec_mp = mp;
23322 			}
23323 		}
23324 	}
23325 
23326 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23327 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23328 		ipha = (ipha_t *)mp->b_rptr;
23329 		ip6h = NULL;
23330 	} else {
23331 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23332 		ipha = NULL;
23333 		ip6h = (ip6_t *)mp->b_rptr;
23334 	}
23335 
23336 	if (check && policy_present) {
23337 		/*
23338 		 * The conn_t parameter is NULL because we already know
23339 		 * nobody's home.
23340 		 */
23341 		ipsec_mp = ipsec_check_global_policy(
23342 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23343 		    tcps->tcps_netstack);
23344 		if (ipsec_mp == NULL)
23345 			return;
23346 	}
23347 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23348 		DTRACE_PROBE2(
23349 		    tx__ip__log__error__nolistener__tcp,
23350 		    char *, "Could not reply with RST to mp(1)",
23351 		    mblk_t *, mp);
23352 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23353 		freemsg(ipsec_mp);
23354 		return;
23355 	}
23356 
23357 	rptr = mp->b_rptr;
23358 
23359 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23360 	seg_seq = BE32_TO_U32(tcph->th_seq);
23361 	seg_ack = BE32_TO_U32(tcph->th_ack);
23362 	flags = tcph->th_flags[0];
23363 
23364 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23365 	if (flags & TH_RST) {
23366 		freemsg(ipsec_mp);
23367 	} else if (flags & TH_ACK) {
23368 		tcp_xmit_early_reset("no tcp, reset",
23369 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23370 		    connp);
23371 	} else {
23372 		if (flags & TH_SYN) {
23373 			seg_len++;
23374 		} else {
23375 			/*
23376 			 * Here we violate the RFC.  Note that a normal
23377 			 * TCP will never send a segment without the ACK
23378 			 * flag, except for RST or SYN segment.  This
23379 			 * segment is neither.  Just drop it on the
23380 			 * floor.
23381 			 */
23382 			freemsg(ipsec_mp);
23383 			tcps->tcps_rst_unsent++;
23384 			return;
23385 		}
23386 
23387 		tcp_xmit_early_reset("no tcp, reset/ack",
23388 		    ipsec_mp, 0, seg_seq + seg_len,
23389 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23390 	}
23391 }
23392 
23393 /*
23394  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23395  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23396  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23397  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23398  * otherwise it will dup partial mblks.)
23399  * Otherwise, an appropriate ACK packet will be generated.  This
23400  * routine is not usually called to send new data for the first time.  It
23401  * is mostly called out of the timer for retransmits, and to generate ACKs.
23402  *
23403  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23404  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23405  * of the original mblk chain will be returned in *offset and *end_mp.
23406  */
23407 mblk_t *
23408 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23409     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23410     boolean_t rexmit)
23411 {
23412 	int	data_length;
23413 	int32_t	off = 0;
23414 	uint_t	flags;
23415 	mblk_t	*mp1;
23416 	mblk_t	*mp2;
23417 	uchar_t	*rptr;
23418 	tcph_t	*tcph;
23419 	int32_t	num_sack_blk = 0;
23420 	int32_t	sack_opt_len = 0;
23421 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23422 
23423 	/* Allocate for our maximum TCP header + link-level */
23424 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23425 	    tcps->tcps_wroff_xtra, BPRI_MED);
23426 	if (!mp1)
23427 		return (NULL);
23428 	data_length = 0;
23429 
23430 	/*
23431 	 * Note that tcp_mss has been adjusted to take into account the
23432 	 * timestamp option if applicable.  Because SACK options do not
23433 	 * appear in every TCP segments and they are of variable lengths,
23434 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23435 	 * the actual segment length when we need to send a segment which
23436 	 * includes SACK options.
23437 	 */
23438 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23439 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23440 		    tcp->tcp_num_sack_blk);
23441 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23442 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23443 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23444 			max_to_send -= sack_opt_len;
23445 	}
23446 
23447 	if (offset != NULL) {
23448 		off = *offset;
23449 		/* We use offset as an indicator that end_mp is not NULL. */
23450 		*end_mp = NULL;
23451 	}
23452 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23453 		/* This could be faster with cooperation from downstream */
23454 		if (mp2 != mp1 && !sendall &&
23455 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23456 		    max_to_send)
23457 			/*
23458 			 * Don't send the next mblk since the whole mblk
23459 			 * does not fit.
23460 			 */
23461 			break;
23462 		mp2->b_cont = dupb(mp);
23463 		mp2 = mp2->b_cont;
23464 		if (!mp2) {
23465 			freemsg(mp1);
23466 			return (NULL);
23467 		}
23468 		mp2->b_rptr += off;
23469 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23470 		    (uintptr_t)INT_MAX);
23471 
23472 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23473 		if (data_length > max_to_send) {
23474 			mp2->b_wptr -= data_length - max_to_send;
23475 			data_length = max_to_send;
23476 			off = mp2->b_wptr - mp->b_rptr;
23477 			break;
23478 		} else {
23479 			off = 0;
23480 		}
23481 	}
23482 	if (offset != NULL) {
23483 		*offset = off;
23484 		*end_mp = mp;
23485 	}
23486 	if (seg_len != NULL) {
23487 		*seg_len = data_length;
23488 	}
23489 
23490 	/* Update the latest receive window size in TCP header. */
23491 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23492 	    tcp->tcp_tcph->th_win);
23493 
23494 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23495 	mp1->b_rptr = rptr;
23496 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23497 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23498 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23499 	U32_TO_ABE32(seq, tcph->th_seq);
23500 
23501 	/*
23502 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23503 	 * that this function was called from tcp_wput_data. Thus, when called
23504 	 * to retransmit data the setting of the PUSH bit may appear some
23505 	 * what random in that it might get set when it should not. This
23506 	 * should not pose any performance issues.
23507 	 */
23508 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23509 	    tcp->tcp_unsent == data_length)) {
23510 		flags = TH_ACK | TH_PUSH;
23511 	} else {
23512 		flags = TH_ACK;
23513 	}
23514 
23515 	if (tcp->tcp_ecn_ok) {
23516 		if (tcp->tcp_ecn_echo_on)
23517 			flags |= TH_ECE;
23518 
23519 		/*
23520 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23521 		 * There is no TCP flow control for non-data segments, and
23522 		 * only data segment is transmitted reliably.
23523 		 */
23524 		if (data_length > 0 && !rexmit) {
23525 			SET_ECT(tcp, rptr);
23526 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23527 				flags |= TH_CWR;
23528 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23529 			}
23530 		}
23531 	}
23532 
23533 	if (tcp->tcp_valid_bits) {
23534 		uint32_t u1;
23535 
23536 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23537 		    seq == tcp->tcp_iss) {
23538 			uchar_t	*wptr;
23539 
23540 			/*
23541 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23542 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23543 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23544 			 * our SYN is not ack'ed but the app closes this
23545 			 * TCP connection.
23546 			 */
23547 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23548 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23549 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23550 
23551 			/*
23552 			 * Tack on the MSS option.  It is always needed
23553 			 * for both active and passive open.
23554 			 *
23555 			 * MSS option value should be interface MTU - MIN
23556 			 * TCP/IP header according to RFC 793 as it means
23557 			 * the maximum segment size TCP can receive.  But
23558 			 * to get around some broken middle boxes/end hosts
23559 			 * out there, we allow the option value to be the
23560 			 * same as the MSS option size on the peer side.
23561 			 * In this way, the other side will not send
23562 			 * anything larger than they can receive.
23563 			 *
23564 			 * Note that for SYN_SENT state, the ndd param
23565 			 * tcp_use_smss_as_mss_opt has no effect as we
23566 			 * don't know the peer's MSS option value. So
23567 			 * the only case we need to take care of is in
23568 			 * SYN_RCVD state, which is done later.
23569 			 */
23570 			wptr = mp1->b_wptr;
23571 			wptr[0] = TCPOPT_MAXSEG;
23572 			wptr[1] = TCPOPT_MAXSEG_LEN;
23573 			wptr += 2;
23574 			u1 = tcp->tcp_if_mtu -
23575 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23576 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23577 			    TCP_MIN_HEADER_LENGTH;
23578 			U16_TO_BE16(u1, wptr);
23579 			mp1->b_wptr = wptr + 2;
23580 			/* Update the offset to cover the additional word */
23581 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23582 
23583 			/*
23584 			 * Note that the following way of filling in
23585 			 * TCP options are not optimal.  Some NOPs can
23586 			 * be saved.  But there is no need at this time
23587 			 * to optimize it.  When it is needed, we will
23588 			 * do it.
23589 			 */
23590 			switch (tcp->tcp_state) {
23591 			case TCPS_SYN_SENT:
23592 				flags = TH_SYN;
23593 
23594 				if (tcp->tcp_snd_ts_ok) {
23595 					uint32_t llbolt = (uint32_t)lbolt;
23596 
23597 					wptr = mp1->b_wptr;
23598 					wptr[0] = TCPOPT_NOP;
23599 					wptr[1] = TCPOPT_NOP;
23600 					wptr[2] = TCPOPT_TSTAMP;
23601 					wptr[3] = TCPOPT_TSTAMP_LEN;
23602 					wptr += 4;
23603 					U32_TO_BE32(llbolt, wptr);
23604 					wptr += 4;
23605 					ASSERT(tcp->tcp_ts_recent == 0);
23606 					U32_TO_BE32(0L, wptr);
23607 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23608 					tcph->th_offset_and_rsrvd[0] +=
23609 					    (3 << 4);
23610 				}
23611 
23612 				/*
23613 				 * Set up all the bits to tell other side
23614 				 * we are ECN capable.
23615 				 */
23616 				if (tcp->tcp_ecn_ok) {
23617 					flags |= (TH_ECE | TH_CWR);
23618 				}
23619 				break;
23620 			case TCPS_SYN_RCVD:
23621 				flags |= TH_SYN;
23622 
23623 				/*
23624 				 * Reset the MSS option value to be SMSS
23625 				 * We should probably add back the bytes
23626 				 * for timestamp option and IPsec.  We
23627 				 * don't do that as this is a workaround
23628 				 * for broken middle boxes/end hosts, it
23629 				 * is better for us to be more cautious.
23630 				 * They may not take these things into
23631 				 * account in their SMSS calculation.  Thus
23632 				 * the peer's calculated SMSS may be smaller
23633 				 * than what it can be.  This should be OK.
23634 				 */
23635 				if (tcps->tcps_use_smss_as_mss_opt) {
23636 					u1 = tcp->tcp_mss;
23637 					U16_TO_BE16(u1, wptr);
23638 				}
23639 
23640 				/*
23641 				 * If the other side is ECN capable, reply
23642 				 * that we are also ECN capable.
23643 				 */
23644 				if (tcp->tcp_ecn_ok)
23645 					flags |= TH_ECE;
23646 				break;
23647 			default:
23648 				/*
23649 				 * The above ASSERT() makes sure that this
23650 				 * must be FIN-WAIT-1 state.  Our SYN has
23651 				 * not been ack'ed so retransmit it.
23652 				 */
23653 				flags |= TH_SYN;
23654 				break;
23655 			}
23656 
23657 			if (tcp->tcp_snd_ws_ok) {
23658 				wptr = mp1->b_wptr;
23659 				wptr[0] =  TCPOPT_NOP;
23660 				wptr[1] =  TCPOPT_WSCALE;
23661 				wptr[2] =  TCPOPT_WS_LEN;
23662 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23663 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23664 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23665 			}
23666 
23667 			if (tcp->tcp_snd_sack_ok) {
23668 				wptr = mp1->b_wptr;
23669 				wptr[0] = TCPOPT_NOP;
23670 				wptr[1] = TCPOPT_NOP;
23671 				wptr[2] = TCPOPT_SACK_PERMITTED;
23672 				wptr[3] = TCPOPT_SACK_OK_LEN;
23673 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23674 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23675 			}
23676 
23677 			/* allocb() of adequate mblk assures space */
23678 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23679 			    (uintptr_t)INT_MAX);
23680 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23681 			/*
23682 			 * Get IP set to checksum on our behalf
23683 			 * Include the adjustment for a source route if any.
23684 			 */
23685 			u1 += tcp->tcp_sum;
23686 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23687 			U16_TO_BE16(u1, tcph->th_sum);
23688 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23689 		}
23690 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23691 		    (seq + data_length) == tcp->tcp_fss) {
23692 			if (!tcp->tcp_fin_acked) {
23693 				flags |= TH_FIN;
23694 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23695 			}
23696 			if (!tcp->tcp_fin_sent) {
23697 				tcp->tcp_fin_sent = B_TRUE;
23698 				switch (tcp->tcp_state) {
23699 				case TCPS_SYN_RCVD:
23700 				case TCPS_ESTABLISHED:
23701 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23702 					break;
23703 				case TCPS_CLOSE_WAIT:
23704 					tcp->tcp_state = TCPS_LAST_ACK;
23705 					break;
23706 				}
23707 				if (tcp->tcp_suna == tcp->tcp_snxt)
23708 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23709 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23710 			}
23711 		}
23712 		/*
23713 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23714 		 * is smaller than seq, u1 will become a very huge value.
23715 		 * So the comparison will fail.  Also note that tcp_urp
23716 		 * should be positive, see RFC 793 page 17.
23717 		 */
23718 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23719 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23720 		    u1 < (uint32_t)(64 * 1024)) {
23721 			flags |= TH_URG;
23722 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23723 			U32_TO_ABE16(u1, tcph->th_urp);
23724 		}
23725 	}
23726 	tcph->th_flags[0] = (uchar_t)flags;
23727 	tcp->tcp_rack = tcp->tcp_rnxt;
23728 	tcp->tcp_rack_cnt = 0;
23729 
23730 	if (tcp->tcp_snd_ts_ok) {
23731 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23732 			uint32_t llbolt = (uint32_t)lbolt;
23733 
23734 			U32_TO_BE32(llbolt,
23735 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23736 			U32_TO_BE32(tcp->tcp_ts_recent,
23737 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23738 		}
23739 	}
23740 
23741 	if (num_sack_blk > 0) {
23742 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23743 		sack_blk_t *tmp;
23744 		int32_t	i;
23745 
23746 		wptr[0] = TCPOPT_NOP;
23747 		wptr[1] = TCPOPT_NOP;
23748 		wptr[2] = TCPOPT_SACK;
23749 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23750 		    sizeof (sack_blk_t);
23751 		wptr += TCPOPT_REAL_SACK_LEN;
23752 
23753 		tmp = tcp->tcp_sack_list;
23754 		for (i = 0; i < num_sack_blk; i++) {
23755 			U32_TO_BE32(tmp[i].begin, wptr);
23756 			wptr += sizeof (tcp_seq);
23757 			U32_TO_BE32(tmp[i].end, wptr);
23758 			wptr += sizeof (tcp_seq);
23759 		}
23760 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23761 	}
23762 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23763 	data_length += (int)(mp1->b_wptr - rptr);
23764 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23765 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23766 	} else {
23767 		ip6_t *ip6 = (ip6_t *)(rptr +
23768 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23769 		    sizeof (ip6i_t) : 0));
23770 
23771 		ip6->ip6_plen = htons(data_length -
23772 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23773 	}
23774 
23775 	/*
23776 	 * Prime pump for IP
23777 	 * Include the adjustment for a source route if any.
23778 	 */
23779 	data_length -= tcp->tcp_ip_hdr_len;
23780 	data_length += tcp->tcp_sum;
23781 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23782 	U16_TO_ABE16(data_length, tcph->th_sum);
23783 	if (tcp->tcp_ip_forward_progress) {
23784 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23785 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23786 		tcp->tcp_ip_forward_progress = B_FALSE;
23787 	}
23788 	return (mp1);
23789 }
23790 
23791 /* This function handles the push timeout. */
23792 void
23793 tcp_push_timer(void *arg)
23794 {
23795 	conn_t	*connp = (conn_t *)arg;
23796 	tcp_t *tcp = connp->conn_tcp;
23797 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23798 	uint_t		flags;
23799 	sodirect_t	*sodp;
23800 
23801 	TCP_DBGSTAT(tcps, tcp_push_timer_cnt);
23802 
23803 	ASSERT(tcp->tcp_listener == NULL);
23804 
23805 	/*
23806 	 * We need to plug synchronous streams during our drain to prevent
23807 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23808 	 */
23809 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23810 	tcp->tcp_push_tid = 0;
23811 
23812 	SOD_PTR_ENTER(tcp, sodp);
23813 	if (sodp != NULL) {
23814 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23815 		/* sod_wakeup() does the mutex_exit() */
23816 	} else if (tcp->tcp_rcv_list != NULL) {
23817 		flags = tcp_rcv_drain(tcp->tcp_rq, tcp);
23818 	}
23819 	if (flags == TH_ACK_NEEDED)
23820 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23821 
23822 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23823 }
23824 
23825 /*
23826  * This function handles delayed ACK timeout.
23827  */
23828 static void
23829 tcp_ack_timer(void *arg)
23830 {
23831 	conn_t	*connp = (conn_t *)arg;
23832 	tcp_t *tcp = connp->conn_tcp;
23833 	mblk_t *mp;
23834 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23835 
23836 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23837 
23838 	tcp->tcp_ack_tid = 0;
23839 
23840 	if (tcp->tcp_fused)
23841 		return;
23842 
23843 	/*
23844 	 * Do not send ACK if there is no outstanding unack'ed data.
23845 	 */
23846 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23847 		return;
23848 	}
23849 
23850 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23851 		/*
23852 		 * Make sure we don't allow deferred ACKs to result in
23853 		 * timer-based ACKing.  If we have held off an ACK
23854 		 * when there was more than an mss here, and the timer
23855 		 * goes off, we have to worry about the possibility
23856 		 * that the sender isn't doing slow-start, or is out
23857 		 * of step with us for some other reason.  We fall
23858 		 * permanently back in the direction of
23859 		 * ACK-every-other-packet as suggested in RFC 1122.
23860 		 */
23861 		if (tcp->tcp_rack_abs_max > 2)
23862 			tcp->tcp_rack_abs_max--;
23863 		tcp->tcp_rack_cur_max = 2;
23864 	}
23865 	mp = tcp_ack_mp(tcp);
23866 
23867 	if (mp != NULL) {
23868 		BUMP_LOCAL(tcp->tcp_obsegs);
23869 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23870 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23871 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23872 	}
23873 }
23874 
23875 
23876 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23877 static mblk_t *
23878 tcp_ack_mp(tcp_t *tcp)
23879 {
23880 	uint32_t	seq_no;
23881 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23882 
23883 	/*
23884 	 * There are a few cases to be considered while setting the sequence no.
23885 	 * Essentially, we can come here while processing an unacceptable pkt
23886 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23887 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23888 	 * If we are here for a zero window probe, stick with suna. In all
23889 	 * other cases, we check if suna + swnd encompasses snxt and set
23890 	 * the sequence number to snxt, if so. If snxt falls outside the
23891 	 * window (the receiver probably shrunk its window), we will go with
23892 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23893 	 * receiver.
23894 	 */
23895 	if (tcp->tcp_zero_win_probe) {
23896 		seq_no = tcp->tcp_suna;
23897 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23898 		ASSERT(tcp->tcp_swnd == 0);
23899 		seq_no = tcp->tcp_snxt;
23900 	} else {
23901 		seq_no = SEQ_GT(tcp->tcp_snxt,
23902 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23903 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23904 	}
23905 
23906 	if (tcp->tcp_valid_bits) {
23907 		/*
23908 		 * For the complex case where we have to send some
23909 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23910 		 */
23911 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23912 		    NULL, B_FALSE));
23913 	} else {
23914 		/* Generate a simple ACK */
23915 		int	data_length;
23916 		uchar_t	*rptr;
23917 		tcph_t	*tcph;
23918 		mblk_t	*mp1;
23919 		int32_t	tcp_hdr_len;
23920 		int32_t	tcp_tcp_hdr_len;
23921 		int32_t	num_sack_blk = 0;
23922 		int32_t sack_opt_len;
23923 
23924 		/*
23925 		 * Allocate space for TCP + IP headers
23926 		 * and link-level header
23927 		 */
23928 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23929 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23930 			    tcp->tcp_num_sack_blk);
23931 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23932 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23933 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23934 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23935 		} else {
23936 			tcp_hdr_len = tcp->tcp_hdr_len;
23937 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23938 		}
23939 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23940 		if (!mp1)
23941 			return (NULL);
23942 
23943 		/* Update the latest receive window size in TCP header. */
23944 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23945 		    tcp->tcp_tcph->th_win);
23946 		/* copy in prototype TCP + IP header */
23947 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23948 		mp1->b_rptr = rptr;
23949 		mp1->b_wptr = rptr + tcp_hdr_len;
23950 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23951 
23952 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23953 
23954 		/* Set the TCP sequence number. */
23955 		U32_TO_ABE32(seq_no, tcph->th_seq);
23956 
23957 		/* Set up the TCP flag field. */
23958 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23959 		if (tcp->tcp_ecn_echo_on)
23960 			tcph->th_flags[0] |= TH_ECE;
23961 
23962 		tcp->tcp_rack = tcp->tcp_rnxt;
23963 		tcp->tcp_rack_cnt = 0;
23964 
23965 		/* fill in timestamp option if in use */
23966 		if (tcp->tcp_snd_ts_ok) {
23967 			uint32_t llbolt = (uint32_t)lbolt;
23968 
23969 			U32_TO_BE32(llbolt,
23970 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23971 			U32_TO_BE32(tcp->tcp_ts_recent,
23972 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23973 		}
23974 
23975 		/* Fill in SACK options */
23976 		if (num_sack_blk > 0) {
23977 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23978 			sack_blk_t *tmp;
23979 			int32_t	i;
23980 
23981 			wptr[0] = TCPOPT_NOP;
23982 			wptr[1] = TCPOPT_NOP;
23983 			wptr[2] = TCPOPT_SACK;
23984 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23985 			    sizeof (sack_blk_t);
23986 			wptr += TCPOPT_REAL_SACK_LEN;
23987 
23988 			tmp = tcp->tcp_sack_list;
23989 			for (i = 0; i < num_sack_blk; i++) {
23990 				U32_TO_BE32(tmp[i].begin, wptr);
23991 				wptr += sizeof (tcp_seq);
23992 				U32_TO_BE32(tmp[i].end, wptr);
23993 				wptr += sizeof (tcp_seq);
23994 			}
23995 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23996 			    << 4);
23997 		}
23998 
23999 		if (tcp->tcp_ipversion == IPV4_VERSION) {
24000 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
24001 		} else {
24002 			/* Check for ip6i_t header in sticky hdrs */
24003 			ip6_t *ip6 = (ip6_t *)(rptr +
24004 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
24005 			    sizeof (ip6i_t) : 0));
24006 
24007 			ip6->ip6_plen = htons(tcp_hdr_len -
24008 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
24009 		}
24010 
24011 		/*
24012 		 * Prime pump for checksum calculation in IP.  Include the
24013 		 * adjustment for a source route if any.
24014 		 */
24015 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
24016 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
24017 		U16_TO_ABE16(data_length, tcph->th_sum);
24018 
24019 		if (tcp->tcp_ip_forward_progress) {
24020 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
24021 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
24022 			tcp->tcp_ip_forward_progress = B_FALSE;
24023 		}
24024 		return (mp1);
24025 	}
24026 }
24027 
24028 /*
24029  * Hash list insertion routine for tcp_t structures.
24030  * Inserts entries with the ones bound to a specific IP address first
24031  * followed by those bound to INADDR_ANY.
24032  */
24033 static void
24034 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
24035 {
24036 	tcp_t	**tcpp;
24037 	tcp_t	*tcpnext;
24038 
24039 	if (tcp->tcp_ptpbhn != NULL) {
24040 		ASSERT(!caller_holds_lock);
24041 		tcp_bind_hash_remove(tcp);
24042 	}
24043 	tcpp = &tbf->tf_tcp;
24044 	if (!caller_holds_lock) {
24045 		mutex_enter(&tbf->tf_lock);
24046 	} else {
24047 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
24048 	}
24049 	tcpnext = tcpp[0];
24050 	if (tcpnext) {
24051 		/*
24052 		 * If the new tcp bound to the INADDR_ANY address
24053 		 * and the first one in the list is not bound to
24054 		 * INADDR_ANY we skip all entries until we find the
24055 		 * first one bound to INADDR_ANY.
24056 		 * This makes sure that applications binding to a
24057 		 * specific address get preference over those binding to
24058 		 * INADDR_ANY.
24059 		 */
24060 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
24061 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
24062 			while ((tcpnext = tcpp[0]) != NULL &&
24063 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
24064 				tcpp = &(tcpnext->tcp_bind_hash);
24065 			if (tcpnext)
24066 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24067 		} else
24068 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24069 	}
24070 	tcp->tcp_bind_hash = tcpnext;
24071 	tcp->tcp_ptpbhn = tcpp;
24072 	tcpp[0] = tcp;
24073 	if (!caller_holds_lock)
24074 		mutex_exit(&tbf->tf_lock);
24075 }
24076 
24077 /*
24078  * Hash list removal routine for tcp_t structures.
24079  */
24080 static void
24081 tcp_bind_hash_remove(tcp_t *tcp)
24082 {
24083 	tcp_t	*tcpnext;
24084 	kmutex_t *lockp;
24085 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24086 
24087 	if (tcp->tcp_ptpbhn == NULL)
24088 		return;
24089 
24090 	/*
24091 	 * Extract the lock pointer in case there are concurrent
24092 	 * hash_remove's for this instance.
24093 	 */
24094 	ASSERT(tcp->tcp_lport != 0);
24095 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
24096 
24097 	ASSERT(lockp != NULL);
24098 	mutex_enter(lockp);
24099 	if (tcp->tcp_ptpbhn) {
24100 		tcpnext = tcp->tcp_bind_hash;
24101 		if (tcpnext) {
24102 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24103 			tcp->tcp_bind_hash = NULL;
24104 		}
24105 		*tcp->tcp_ptpbhn = tcpnext;
24106 		tcp->tcp_ptpbhn = NULL;
24107 	}
24108 	mutex_exit(lockp);
24109 }
24110 
24111 
24112 /*
24113  * Hash list lookup routine for tcp_t structures.
24114  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24115  */
24116 static tcp_t *
24117 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24118 {
24119 	tf_t	*tf;
24120 	tcp_t	*tcp;
24121 
24122 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24123 	mutex_enter(&tf->tf_lock);
24124 	for (tcp = tf->tf_tcp; tcp != NULL;
24125 	    tcp = tcp->tcp_acceptor_hash) {
24126 		if (tcp->tcp_acceptor_id == id) {
24127 			CONN_INC_REF(tcp->tcp_connp);
24128 			mutex_exit(&tf->tf_lock);
24129 			return (tcp);
24130 		}
24131 	}
24132 	mutex_exit(&tf->tf_lock);
24133 	return (NULL);
24134 }
24135 
24136 
24137 /*
24138  * Hash list insertion routine for tcp_t structures.
24139  */
24140 void
24141 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24142 {
24143 	tf_t	*tf;
24144 	tcp_t	**tcpp;
24145 	tcp_t	*tcpnext;
24146 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24147 
24148 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24149 
24150 	if (tcp->tcp_ptpahn != NULL)
24151 		tcp_acceptor_hash_remove(tcp);
24152 	tcpp = &tf->tf_tcp;
24153 	mutex_enter(&tf->tf_lock);
24154 	tcpnext = tcpp[0];
24155 	if (tcpnext)
24156 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24157 	tcp->tcp_acceptor_hash = tcpnext;
24158 	tcp->tcp_ptpahn = tcpp;
24159 	tcpp[0] = tcp;
24160 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24161 	mutex_exit(&tf->tf_lock);
24162 }
24163 
24164 /*
24165  * Hash list removal routine for tcp_t structures.
24166  */
24167 static void
24168 tcp_acceptor_hash_remove(tcp_t *tcp)
24169 {
24170 	tcp_t	*tcpnext;
24171 	kmutex_t *lockp;
24172 
24173 	/*
24174 	 * Extract the lock pointer in case there are concurrent
24175 	 * hash_remove's for this instance.
24176 	 */
24177 	lockp = tcp->tcp_acceptor_lockp;
24178 
24179 	if (tcp->tcp_ptpahn == NULL)
24180 		return;
24181 
24182 	ASSERT(lockp != NULL);
24183 	mutex_enter(lockp);
24184 	if (tcp->tcp_ptpahn) {
24185 		tcpnext = tcp->tcp_acceptor_hash;
24186 		if (tcpnext) {
24187 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24188 			tcp->tcp_acceptor_hash = NULL;
24189 		}
24190 		*tcp->tcp_ptpahn = tcpnext;
24191 		tcp->tcp_ptpahn = NULL;
24192 	}
24193 	mutex_exit(lockp);
24194 	tcp->tcp_acceptor_lockp = NULL;
24195 }
24196 
24197 /* Data for fast netmask macro used by tcp_hsp_lookup */
24198 
24199 static ipaddr_t netmasks[] = {
24200 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24201 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24202 };
24203 
24204 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24205 
24206 /*
24207  * XXX This routine should go away and instead we should use the metrics
24208  * associated with the routes to determine the default sndspace and rcvspace.
24209  */
24210 static tcp_hsp_t *
24211 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24212 {
24213 	tcp_hsp_t *hsp = NULL;
24214 
24215 	/* Quick check without acquiring the lock. */
24216 	if (tcps->tcps_hsp_hash == NULL)
24217 		return (NULL);
24218 
24219 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24220 
24221 	/* This routine finds the best-matching HSP for address addr. */
24222 
24223 	if (tcps->tcps_hsp_hash) {
24224 		int i;
24225 		ipaddr_t srchaddr;
24226 		tcp_hsp_t *hsp_net;
24227 
24228 		/* We do three passes: host, network, and subnet. */
24229 
24230 		srchaddr = addr;
24231 
24232 		for (i = 1; i <= 3; i++) {
24233 			/* Look for exact match on srchaddr */
24234 
24235 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24236 			while (hsp) {
24237 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24238 				    hsp->tcp_hsp_addr == srchaddr)
24239 					break;
24240 				hsp = hsp->tcp_hsp_next;
24241 			}
24242 			ASSERT(hsp == NULL ||
24243 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24244 
24245 			/*
24246 			 * If this is the first pass:
24247 			 *   If we found a match, great, return it.
24248 			 *   If not, search for the network on the second pass.
24249 			 */
24250 
24251 			if (i == 1)
24252 				if (hsp)
24253 					break;
24254 				else
24255 				{
24256 					srchaddr = addr & netmask(addr);
24257 					continue;
24258 				}
24259 
24260 			/*
24261 			 * If this is the second pass:
24262 			 *   If we found a match, but there's a subnet mask,
24263 			 *    save the match but try again using the subnet
24264 			 *    mask on the third pass.
24265 			 *   Otherwise, return whatever we found.
24266 			 */
24267 
24268 			if (i == 2) {
24269 				if (hsp && hsp->tcp_hsp_subnet) {
24270 					hsp_net = hsp;
24271 					srchaddr = addr & hsp->tcp_hsp_subnet;
24272 					continue;
24273 				} else {
24274 					break;
24275 				}
24276 			}
24277 
24278 			/*
24279 			 * This must be the third pass.  If we didn't find
24280 			 * anything, return the saved network HSP instead.
24281 			 */
24282 
24283 			if (!hsp)
24284 				hsp = hsp_net;
24285 		}
24286 	}
24287 
24288 	rw_exit(&tcps->tcps_hsp_lock);
24289 	return (hsp);
24290 }
24291 
24292 /*
24293  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24294  * match lookup.
24295  */
24296 static tcp_hsp_t *
24297 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24298 {
24299 	tcp_hsp_t *hsp = NULL;
24300 
24301 	/* Quick check without acquiring the lock. */
24302 	if (tcps->tcps_hsp_hash == NULL)
24303 		return (NULL);
24304 
24305 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24306 
24307 	/* This routine finds the best-matching HSP for address addr. */
24308 
24309 	if (tcps->tcps_hsp_hash) {
24310 		int i;
24311 		in6_addr_t v6srchaddr;
24312 		tcp_hsp_t *hsp_net;
24313 
24314 		/* We do three passes: host, network, and subnet. */
24315 
24316 		v6srchaddr = *v6addr;
24317 
24318 		for (i = 1; i <= 3; i++) {
24319 			/* Look for exact match on srchaddr */
24320 
24321 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24322 			    V4_PART_OF_V6(v6srchaddr))];
24323 			while (hsp) {
24324 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24325 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24326 				    &v6srchaddr))
24327 					break;
24328 				hsp = hsp->tcp_hsp_next;
24329 			}
24330 
24331 			/*
24332 			 * If this is the first pass:
24333 			 *   If we found a match, great, return it.
24334 			 *   If not, search for the network on the second pass.
24335 			 */
24336 
24337 			if (i == 1)
24338 				if (hsp)
24339 					break;
24340 				else {
24341 					/* Assume a 64 bit mask */
24342 					v6srchaddr.s6_addr32[0] =
24343 					    v6addr->s6_addr32[0];
24344 					v6srchaddr.s6_addr32[1] =
24345 					    v6addr->s6_addr32[1];
24346 					v6srchaddr.s6_addr32[2] = 0;
24347 					v6srchaddr.s6_addr32[3] = 0;
24348 					continue;
24349 				}
24350 
24351 			/*
24352 			 * If this is the second pass:
24353 			 *   If we found a match, but there's a subnet mask,
24354 			 *    save the match but try again using the subnet
24355 			 *    mask on the third pass.
24356 			 *   Otherwise, return whatever we found.
24357 			 */
24358 
24359 			if (i == 2) {
24360 				ASSERT(hsp == NULL ||
24361 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24362 				if (hsp &&
24363 				    !IN6_IS_ADDR_UNSPECIFIED(
24364 				    &hsp->tcp_hsp_subnet_v6)) {
24365 					hsp_net = hsp;
24366 					V6_MASK_COPY(*v6addr,
24367 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24368 					continue;
24369 				} else {
24370 					break;
24371 				}
24372 			}
24373 
24374 			/*
24375 			 * This must be the third pass.  If we didn't find
24376 			 * anything, return the saved network HSP instead.
24377 			 */
24378 
24379 			if (!hsp)
24380 				hsp = hsp_net;
24381 		}
24382 	}
24383 
24384 	rw_exit(&tcps->tcps_hsp_lock);
24385 	return (hsp);
24386 }
24387 
24388 /*
24389  * Type three generator adapted from the random() function in 4.4 BSD:
24390  */
24391 
24392 /*
24393  * Copyright (c) 1983, 1993
24394  *	The Regents of the University of California.  All rights reserved.
24395  *
24396  * Redistribution and use in source and binary forms, with or without
24397  * modification, are permitted provided that the following conditions
24398  * are met:
24399  * 1. Redistributions of source code must retain the above copyright
24400  *    notice, this list of conditions and the following disclaimer.
24401  * 2. Redistributions in binary form must reproduce the above copyright
24402  *    notice, this list of conditions and the following disclaimer in the
24403  *    documentation and/or other materials provided with the distribution.
24404  * 3. All advertising materials mentioning features or use of this software
24405  *    must display the following acknowledgement:
24406  *	This product includes software developed by the University of
24407  *	California, Berkeley and its contributors.
24408  * 4. Neither the name of the University nor the names of its contributors
24409  *    may be used to endorse or promote products derived from this software
24410  *    without specific prior written permission.
24411  *
24412  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24413  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24414  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24415  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24416  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24417  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24418  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24419  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24420  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24421  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24422  * SUCH DAMAGE.
24423  */
24424 
24425 /* Type 3 -- x**31 + x**3 + 1 */
24426 #define	DEG_3		31
24427 #define	SEP_3		3
24428 
24429 
24430 /* Protected by tcp_random_lock */
24431 static int tcp_randtbl[DEG_3 + 1];
24432 
24433 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24434 static int *tcp_random_rptr = &tcp_randtbl[1];
24435 
24436 static int *tcp_random_state = &tcp_randtbl[1];
24437 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24438 
24439 kmutex_t tcp_random_lock;
24440 
24441 void
24442 tcp_random_init(void)
24443 {
24444 	int i;
24445 	hrtime_t hrt;
24446 	time_t wallclock;
24447 	uint64_t result;
24448 
24449 	/*
24450 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24451 	 * a longlong, which may contain resolution down to nanoseconds.
24452 	 * The current time will either be a 32-bit or a 64-bit quantity.
24453 	 * XOR the two together in a 64-bit result variable.
24454 	 * Convert the result to a 32-bit value by multiplying the high-order
24455 	 * 32-bits by the low-order 32-bits.
24456 	 */
24457 
24458 	hrt = gethrtime();
24459 	(void) drv_getparm(TIME, &wallclock);
24460 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24461 	mutex_enter(&tcp_random_lock);
24462 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24463 	    (result & 0xffffffff);
24464 
24465 	for (i = 1; i < DEG_3; i++)
24466 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24467 		    + 12345;
24468 	tcp_random_fptr = &tcp_random_state[SEP_3];
24469 	tcp_random_rptr = &tcp_random_state[0];
24470 	mutex_exit(&tcp_random_lock);
24471 	for (i = 0; i < 10 * DEG_3; i++)
24472 		(void) tcp_random();
24473 }
24474 
24475 /*
24476  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24477  * This range is selected to be approximately centered on TCP_ISS / 2,
24478  * and easy to compute. We get this value by generating a 32-bit random
24479  * number, selecting out the high-order 17 bits, and then adding one so
24480  * that we never return zero.
24481  */
24482 int
24483 tcp_random(void)
24484 {
24485 	int i;
24486 
24487 	mutex_enter(&tcp_random_lock);
24488 	*tcp_random_fptr += *tcp_random_rptr;
24489 
24490 	/*
24491 	 * The high-order bits are more random than the low-order bits,
24492 	 * so we select out the high-order 17 bits and add one so that
24493 	 * we never return zero.
24494 	 */
24495 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24496 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24497 		tcp_random_fptr = tcp_random_state;
24498 		++tcp_random_rptr;
24499 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24500 		tcp_random_rptr = tcp_random_state;
24501 
24502 	mutex_exit(&tcp_random_lock);
24503 	return (i);
24504 }
24505 
24506 /*
24507  * XXX This will go away when TPI is extended to send
24508  * info reqs to sockfs/timod .....
24509  * Given a queue, set the max packet size for the write
24510  * side of the queue below stream head.  This value is
24511  * cached on the stream head.
24512  * Returns 1 on success, 0 otherwise.
24513  */
24514 static int
24515 setmaxps(queue_t *q, int maxpsz)
24516 {
24517 	struct stdata	*stp;
24518 	queue_t		*wq;
24519 	stp = STREAM(q);
24520 
24521 	/*
24522 	 * At this point change of a queue parameter is not allowed
24523 	 * when a multiplexor is sitting on top.
24524 	 */
24525 	if (stp->sd_flag & STPLEX)
24526 		return (0);
24527 
24528 	claimstr(stp->sd_wrq);
24529 	wq = stp->sd_wrq->q_next;
24530 	ASSERT(wq != NULL);
24531 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
24532 	releasestr(stp->sd_wrq);
24533 	return (1);
24534 }
24535 
24536 static int
24537 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24538     int *t_errorp, int *sys_errorp)
24539 {
24540 	int error;
24541 	int is_absreq_failure;
24542 	t_scalar_t *opt_lenp;
24543 	t_scalar_t opt_offset;
24544 	int prim_type;
24545 	struct T_conn_req *tcreqp;
24546 	struct T_conn_res *tcresp;
24547 	cred_t *cr;
24548 
24549 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24550 
24551 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24552 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24553 	    prim_type == T_CONN_RES);
24554 
24555 	switch (prim_type) {
24556 	case T_CONN_REQ:
24557 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24558 		opt_offset = tcreqp->OPT_offset;
24559 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24560 		break;
24561 	case O_T_CONN_RES:
24562 	case T_CONN_RES:
24563 		tcresp = (struct T_conn_res *)mp->b_rptr;
24564 		opt_offset = tcresp->OPT_offset;
24565 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24566 		break;
24567 	}
24568 
24569 	*t_errorp = 0;
24570 	*sys_errorp = 0;
24571 	*do_disconnectp = 0;
24572 
24573 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24574 	    opt_offset, cr, &tcp_opt_obj,
24575 	    NULL, &is_absreq_failure);
24576 
24577 	switch (error) {
24578 	case  0:		/* no error */
24579 		ASSERT(is_absreq_failure == 0);
24580 		return (0);
24581 	case ENOPROTOOPT:
24582 		*t_errorp = TBADOPT;
24583 		break;
24584 	case EACCES:
24585 		*t_errorp = TACCES;
24586 		break;
24587 	default:
24588 		*t_errorp = TSYSERR; *sys_errorp = error;
24589 		break;
24590 	}
24591 	if (is_absreq_failure != 0) {
24592 		/*
24593 		 * The connection request should get the local ack
24594 		 * T_OK_ACK and then a T_DISCON_IND.
24595 		 */
24596 		*do_disconnectp = 1;
24597 	}
24598 	return (-1);
24599 }
24600 
24601 /*
24602  * Split this function out so that if the secret changes, I'm okay.
24603  *
24604  * Initialize the tcp_iss_cookie and tcp_iss_key.
24605  */
24606 
24607 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24608 
24609 static void
24610 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24611 {
24612 	struct {
24613 		int32_t current_time;
24614 		uint32_t randnum;
24615 		uint16_t pad;
24616 		uint8_t ether[6];
24617 		uint8_t passwd[PASSWD_SIZE];
24618 	} tcp_iss_cookie;
24619 	time_t t;
24620 
24621 	/*
24622 	 * Start with the current absolute time.
24623 	 */
24624 	(void) drv_getparm(TIME, &t);
24625 	tcp_iss_cookie.current_time = t;
24626 
24627 	/*
24628 	 * XXX - Need a more random number per RFC 1750, not this crap.
24629 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24630 	 */
24631 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24632 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24633 
24634 	/*
24635 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24636 	 * as a good template.
24637 	 */
24638 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24639 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24640 
24641 	/*
24642 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24643 	 */
24644 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24645 
24646 	/*
24647 	 * See 4010593 if this section becomes a problem again,
24648 	 * but the local ethernet address is useful here.
24649 	 */
24650 	(void) localetheraddr(NULL,
24651 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24652 
24653 	/*
24654 	 * Hash 'em all together.  The MD5Final is called per-connection.
24655 	 */
24656 	mutex_enter(&tcps->tcps_iss_key_lock);
24657 	MD5Init(&tcps->tcps_iss_key);
24658 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24659 	    sizeof (tcp_iss_cookie));
24660 	mutex_exit(&tcps->tcps_iss_key_lock);
24661 }
24662 
24663 /*
24664  * Set the RFC 1948 pass phrase
24665  */
24666 /* ARGSUSED */
24667 static int
24668 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24669     cred_t *cr)
24670 {
24671 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24672 
24673 	/*
24674 	 * Basically, value contains a new pass phrase.  Pass it along!
24675 	 */
24676 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24677 	return (0);
24678 }
24679 
24680 /* ARGSUSED */
24681 static int
24682 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24683 {
24684 	bzero(buf, sizeof (tcp_sack_info_t));
24685 	return (0);
24686 }
24687 
24688 /* ARGSUSED */
24689 static int
24690 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24691 {
24692 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24693 	return (0);
24694 }
24695 
24696 /*
24697  * Make sure we wait until the default queue is setup, yet allow
24698  * tcp_g_q_create() to open a TCP stream.
24699  * We need to allow tcp_g_q_create() do do an open
24700  * of tcp, hence we compare curhread.
24701  * All others have to wait until the tcps_g_q has been
24702  * setup.
24703  */
24704 void
24705 tcp_g_q_setup(tcp_stack_t *tcps)
24706 {
24707 	mutex_enter(&tcps->tcps_g_q_lock);
24708 	if (tcps->tcps_g_q != NULL) {
24709 		mutex_exit(&tcps->tcps_g_q_lock);
24710 		return;
24711 	}
24712 	if (tcps->tcps_g_q_creator == NULL) {
24713 		/* This thread will set it up */
24714 		tcps->tcps_g_q_creator = curthread;
24715 		mutex_exit(&tcps->tcps_g_q_lock);
24716 		tcp_g_q_create(tcps);
24717 		mutex_enter(&tcps->tcps_g_q_lock);
24718 		ASSERT(tcps->tcps_g_q_creator == curthread);
24719 		tcps->tcps_g_q_creator = NULL;
24720 		cv_signal(&tcps->tcps_g_q_cv);
24721 		ASSERT(tcps->tcps_g_q != NULL);
24722 		mutex_exit(&tcps->tcps_g_q_lock);
24723 		return;
24724 	}
24725 	/* Everybody but the creator has to wait */
24726 	if (tcps->tcps_g_q_creator != curthread) {
24727 		while (tcps->tcps_g_q == NULL)
24728 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24729 	}
24730 	mutex_exit(&tcps->tcps_g_q_lock);
24731 }
24732 
24733 #define	IP	"ip"
24734 
24735 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24736 
24737 /*
24738  * Create a default tcp queue here instead of in strplumb
24739  */
24740 void
24741 tcp_g_q_create(tcp_stack_t *tcps)
24742 {
24743 	int error;
24744 	ldi_handle_t	lh = NULL;
24745 	ldi_ident_t	li = NULL;
24746 	int		rval;
24747 	cred_t		*cr;
24748 	major_t IP_MAJ;
24749 
24750 #ifdef NS_DEBUG
24751 	(void) printf("tcp_g_q_create()\n");
24752 #endif
24753 
24754 	IP_MAJ = ddi_name_to_major(IP);
24755 
24756 	ASSERT(tcps->tcps_g_q_creator == curthread);
24757 
24758 	error = ldi_ident_from_major(IP_MAJ, &li);
24759 	if (error) {
24760 #ifdef DEBUG
24761 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24762 		    error);
24763 #endif
24764 		return;
24765 	}
24766 
24767 	cr = zone_get_kcred(netstackid_to_zoneid(
24768 	    tcps->tcps_netstack->netstack_stackid));
24769 	ASSERT(cr != NULL);
24770 	/*
24771 	 * We set the tcp default queue to IPv6 because IPv4 falls
24772 	 * back to IPv6 when it can't find a client, but
24773 	 * IPv6 does not fall back to IPv4.
24774 	 */
24775 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24776 	if (error) {
24777 #ifdef DEBUG
24778 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24779 		    error);
24780 #endif
24781 		goto out;
24782 	}
24783 
24784 	/*
24785 	 * This ioctl causes the tcp framework to cache a pointer to
24786 	 * this stream, so we don't want to close the stream after
24787 	 * this operation.
24788 	 * Use the kernel credentials that are for the zone we're in.
24789 	 */
24790 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24791 	    (intptr_t)0, FKIOCTL, cr, &rval);
24792 	if (error) {
24793 #ifdef DEBUG
24794 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24795 		    "error %d\n", error);
24796 #endif
24797 		goto out;
24798 	}
24799 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24800 	lh = NULL;
24801 out:
24802 	/* Close layered handles */
24803 	if (li)
24804 		ldi_ident_release(li);
24805 	/* Keep cred around until _inactive needs it */
24806 	tcps->tcps_g_q_cr = cr;
24807 }
24808 
24809 /*
24810  * We keep tcp_g_q set until all other tcp_t's in the zone
24811  * has gone away, and then when tcp_g_q_inactive() is called
24812  * we clear it.
24813  */
24814 void
24815 tcp_g_q_destroy(tcp_stack_t *tcps)
24816 {
24817 #ifdef NS_DEBUG
24818 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24819 	    tcps->tcps_netstack->netstack_stackid);
24820 #endif
24821 
24822 	if (tcps->tcps_g_q == NULL) {
24823 		return;	/* Nothing to cleanup */
24824 	}
24825 	/*
24826 	 * Drop reference corresponding to the default queue.
24827 	 * This reference was added from tcp_open when the default queue
24828 	 * was created, hence we compensate for this extra drop in
24829 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24830 	 * the default queue was the last one to be open, in which
24831 	 * case, then tcp_g_q_inactive will be
24832 	 * called as a result of the refrele.
24833 	 */
24834 	TCPS_REFRELE(tcps);
24835 }
24836 
24837 /*
24838  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24839  * Run by tcp_q_q_inactive using a taskq.
24840  */
24841 static void
24842 tcp_g_q_close(void *arg)
24843 {
24844 	tcp_stack_t *tcps = arg;
24845 	int error;
24846 	ldi_handle_t	lh = NULL;
24847 	ldi_ident_t	li = NULL;
24848 	cred_t		*cr;
24849 	major_t IP_MAJ;
24850 
24851 	IP_MAJ = ddi_name_to_major(IP);
24852 
24853 #ifdef NS_DEBUG
24854 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24855 	    tcps->tcps_netstack->netstack_stackid,
24856 	    tcps->tcps_netstack->netstack_refcnt);
24857 #endif
24858 	lh = tcps->tcps_g_q_lh;
24859 	if (lh == NULL)
24860 		return;	/* Nothing to cleanup */
24861 
24862 	ASSERT(tcps->tcps_refcnt == 1);
24863 	ASSERT(tcps->tcps_g_q != NULL);
24864 
24865 	error = ldi_ident_from_major(IP_MAJ, &li);
24866 	if (error) {
24867 #ifdef DEBUG
24868 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24869 		    error);
24870 #endif
24871 		return;
24872 	}
24873 
24874 	cr = tcps->tcps_g_q_cr;
24875 	tcps->tcps_g_q_cr = NULL;
24876 	ASSERT(cr != NULL);
24877 
24878 	/*
24879 	 * Make sure we can break the recursion when tcp_close decrements
24880 	 * the reference count causing g_q_inactive to be called again.
24881 	 */
24882 	tcps->tcps_g_q_lh = NULL;
24883 
24884 	/* close the default queue */
24885 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24886 	/*
24887 	 * At this point in time tcps and the rest of netstack_t might
24888 	 * have been deleted.
24889 	 */
24890 	tcps = NULL;
24891 
24892 	/* Close layered handles */
24893 	ldi_ident_release(li);
24894 	crfree(cr);
24895 }
24896 
24897 /*
24898  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24899  *
24900  * Have to ensure that the ldi routines are not used by an
24901  * interrupt thread by using a taskq.
24902  */
24903 void
24904 tcp_g_q_inactive(tcp_stack_t *tcps)
24905 {
24906 	if (tcps->tcps_g_q_lh == NULL)
24907 		return;	/* Nothing to cleanup */
24908 
24909 	ASSERT(tcps->tcps_refcnt == 0);
24910 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24911 
24912 	if (servicing_interrupt()) {
24913 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24914 		    (void *) tcps, TQ_SLEEP);
24915 	} else {
24916 		tcp_g_q_close(tcps);
24917 	}
24918 }
24919 
24920 /*
24921  * Called by IP when IP is loaded into the kernel
24922  */
24923 void
24924 tcp_ddi_g_init(void)
24925 {
24926 	tcp_timercache = kmem_cache_create("tcp_timercache",
24927 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24928 	    NULL, NULL, NULL, NULL, NULL, 0);
24929 
24930 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24931 	    sizeof (tcp_sack_info_t), 0,
24932 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24933 
24934 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24935 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24936 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24937 
24938 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24939 
24940 	/* Initialize the random number generator */
24941 	tcp_random_init();
24942 
24943 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
24944 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
24945 
24946 	/* A single callback independently of how many netstacks we have */
24947 	ip_squeue_init(tcp_squeue_add);
24948 
24949 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24950 
24951 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24952 	    TASKQ_PREPOPULATE);
24953 
24954 	/*
24955 	 * We want to be informed each time a stack is created or
24956 	 * destroyed in the kernel, so we can maintain the
24957 	 * set of tcp_stack_t's.
24958 	 */
24959 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24960 	    tcp_stack_fini);
24961 }
24962 
24963 
24964 /*
24965  * Initialize the TCP stack instance.
24966  */
24967 static void *
24968 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24969 {
24970 	tcp_stack_t	*tcps;
24971 	tcpparam_t	*pa;
24972 	int		i;
24973 
24974 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24975 	tcps->tcps_netstack = ns;
24976 
24977 	/* Initialize locks */
24978 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24979 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24980 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24981 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24982 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24983 
24984 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24985 	tcps->tcps_g_epriv_ports[0] = 2049;
24986 	tcps->tcps_g_epriv_ports[1] = 4045;
24987 	tcps->tcps_min_anonpriv_port = 512;
24988 
24989 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24990 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24991 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24992 	    TCP_FANOUT_SIZE, KM_SLEEP);
24993 
24994 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24995 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24996 		    MUTEX_DEFAULT, NULL);
24997 	}
24998 
24999 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25000 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
25001 		    MUTEX_DEFAULT, NULL);
25002 	}
25003 
25004 	/* TCP's IPsec code calls the packet dropper. */
25005 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
25006 
25007 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
25008 	tcps->tcps_params = pa;
25009 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25010 
25011 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
25012 	    A_CNT(lcl_tcp_param_arr), tcps);
25013 
25014 	/*
25015 	 * Note: To really walk the device tree you need the devinfo
25016 	 * pointer to your device which is only available after probe/attach.
25017 	 * The following is safe only because it uses ddi_root_node()
25018 	 */
25019 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
25020 	    tcp_opt_obj.odb_opt_arr_cnt);
25021 
25022 	/*
25023 	 * Initialize RFC 1948 secret values.  This will probably be reset once
25024 	 * by the boot scripts.
25025 	 *
25026 	 * Use NULL name, as the name is caught by the new lockstats.
25027 	 *
25028 	 * Initialize with some random, non-guessable string, like the global
25029 	 * T_INFO_ACK.
25030 	 */
25031 
25032 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
25033 	    sizeof (tcp_g_t_info_ack), tcps);
25034 
25035 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
25036 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
25037 
25038 	return (tcps);
25039 }
25040 
25041 /*
25042  * Called when the IP module is about to be unloaded.
25043  */
25044 void
25045 tcp_ddi_g_destroy(void)
25046 {
25047 	tcp_g_kstat_fini(tcp_g_kstat);
25048 	tcp_g_kstat = NULL;
25049 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25050 
25051 	mutex_destroy(&tcp_random_lock);
25052 
25053 	kmem_cache_destroy(tcp_timercache);
25054 	kmem_cache_destroy(tcp_sack_info_cache);
25055 	kmem_cache_destroy(tcp_iphc_cache);
25056 
25057 	netstack_unregister(NS_TCP);
25058 	taskq_destroy(tcp_taskq);
25059 }
25060 
25061 /*
25062  * Shut down the TCP stack instance.
25063  */
25064 /* ARGSUSED */
25065 static void
25066 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25067 {
25068 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25069 
25070 	tcp_g_q_destroy(tcps);
25071 }
25072 
25073 /*
25074  * Free the TCP stack instance.
25075  */
25076 static void
25077 tcp_stack_fini(netstackid_t stackid, void *arg)
25078 {
25079 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25080 	int i;
25081 
25082 	nd_free(&tcps->tcps_g_nd);
25083 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25084 	tcps->tcps_params = NULL;
25085 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25086 	tcps->tcps_wroff_xtra_param = NULL;
25087 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25088 	tcps->tcps_mdt_head_param = NULL;
25089 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25090 	tcps->tcps_mdt_tail_param = NULL;
25091 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25092 	tcps->tcps_mdt_max_pbufs_param = NULL;
25093 
25094 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25095 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25096 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25097 	}
25098 
25099 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25100 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25101 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25102 	}
25103 
25104 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25105 	tcps->tcps_bind_fanout = NULL;
25106 
25107 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25108 	tcps->tcps_acceptor_fanout = NULL;
25109 
25110 	mutex_destroy(&tcps->tcps_iss_key_lock);
25111 	rw_destroy(&tcps->tcps_hsp_lock);
25112 	mutex_destroy(&tcps->tcps_g_q_lock);
25113 	cv_destroy(&tcps->tcps_g_q_cv);
25114 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25115 
25116 	ip_drop_unregister(&tcps->tcps_dropper);
25117 
25118 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25119 	tcps->tcps_kstat = NULL;
25120 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25121 
25122 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25123 	tcps->tcps_mibkp = NULL;
25124 
25125 	kmem_free(tcps, sizeof (*tcps));
25126 }
25127 
25128 /*
25129  * Generate ISS, taking into account NDD changes may happen halfway through.
25130  * (If the iss is not zero, set it.)
25131  */
25132 
25133 static void
25134 tcp_iss_init(tcp_t *tcp)
25135 {
25136 	MD5_CTX context;
25137 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25138 	uint32_t answer[4];
25139 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25140 
25141 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25142 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25143 	switch (tcps->tcps_strong_iss) {
25144 	case 2:
25145 		mutex_enter(&tcps->tcps_iss_key_lock);
25146 		context = tcps->tcps_iss_key;
25147 		mutex_exit(&tcps->tcps_iss_key_lock);
25148 		arg.ports = tcp->tcp_ports;
25149 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25150 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25151 			    &arg.src);
25152 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25153 			    &arg.dst);
25154 		} else {
25155 			arg.src = tcp->tcp_ip6h->ip6_src;
25156 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25157 		}
25158 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25159 		MD5Final((uchar_t *)answer, &context);
25160 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25161 		/*
25162 		 * Now that we've hashed into a unique per-connection sequence
25163 		 * space, add a random increment per strong_iss == 1.  So I
25164 		 * guess we'll have to...
25165 		 */
25166 		/* FALLTHRU */
25167 	case 1:
25168 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25169 		break;
25170 	default:
25171 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25172 		break;
25173 	}
25174 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25175 	tcp->tcp_fss = tcp->tcp_iss - 1;
25176 	tcp->tcp_suna = tcp->tcp_iss;
25177 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25178 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25179 	tcp->tcp_csuna = tcp->tcp_snxt;
25180 }
25181 
25182 /*
25183  * Exported routine for extracting active tcp connection status.
25184  *
25185  * This is used by the Solaris Cluster Networking software to
25186  * gather a list of connections that need to be forwarded to
25187  * specific nodes in the cluster when configuration changes occur.
25188  *
25189  * The callback is invoked for each tcp_t structure. Returning
25190  * non-zero from the callback routine terminates the search.
25191  */
25192 int
25193 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25194     void *arg)
25195 {
25196 	netstack_handle_t nh;
25197 	netstack_t *ns;
25198 	int ret = 0;
25199 
25200 	netstack_next_init(&nh);
25201 	while ((ns = netstack_next(&nh)) != NULL) {
25202 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25203 		    ns->netstack_tcp);
25204 		netstack_rele(ns);
25205 	}
25206 	netstack_next_fini(&nh);
25207 	return (ret);
25208 }
25209 
25210 static int
25211 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25212     tcp_stack_t *tcps)
25213 {
25214 	tcp_t *tcp;
25215 	cl_tcp_info_t	cl_tcpi;
25216 	connf_t	*connfp;
25217 	conn_t	*connp;
25218 	int	i;
25219 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25220 
25221 	ASSERT(callback != NULL);
25222 
25223 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25224 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25225 		connp = NULL;
25226 
25227 		while ((connp =
25228 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25229 
25230 			tcp = connp->conn_tcp;
25231 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25232 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25233 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25234 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25235 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25236 			/*
25237 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25238 			 * addresses. They are copied implicitly below as
25239 			 * mapped addresses.
25240 			 */
25241 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25242 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25243 				cl_tcpi.cl_tcpi_faddr =
25244 				    tcp->tcp_ipha->ipha_dst;
25245 			} else {
25246 				cl_tcpi.cl_tcpi_faddr_v6 =
25247 				    tcp->tcp_ip6h->ip6_dst;
25248 			}
25249 
25250 			/*
25251 			 * If the callback returns non-zero
25252 			 * we terminate the traversal.
25253 			 */
25254 			if ((*callback)(&cl_tcpi, arg) != 0) {
25255 				CONN_DEC_REF(tcp->tcp_connp);
25256 				return (1);
25257 			}
25258 		}
25259 	}
25260 
25261 	return (0);
25262 }
25263 
25264 /*
25265  * Macros used for accessing the different types of sockaddr
25266  * structures inside a tcp_ioc_abort_conn_t.
25267  */
25268 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25269 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25270 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25271 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25272 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25273 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25274 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25275 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25276 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25277 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25278 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25279 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25280 
25281 /*
25282  * Return the correct error code to mimic the behavior
25283  * of a connection reset.
25284  */
25285 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25286 		switch ((state)) {		\
25287 		case TCPS_SYN_SENT:		\
25288 		case TCPS_SYN_RCVD:		\
25289 			(err) = ECONNREFUSED;	\
25290 			break;			\
25291 		case TCPS_ESTABLISHED:		\
25292 		case TCPS_FIN_WAIT_1:		\
25293 		case TCPS_FIN_WAIT_2:		\
25294 		case TCPS_CLOSE_WAIT:		\
25295 			(err) = ECONNRESET;	\
25296 			break;			\
25297 		case TCPS_CLOSING:		\
25298 		case TCPS_LAST_ACK:		\
25299 		case TCPS_TIME_WAIT:		\
25300 			(err) = 0;		\
25301 			break;			\
25302 		default:			\
25303 			(err) = ENXIO;		\
25304 		}				\
25305 	}
25306 
25307 /*
25308  * Check if a tcp structure matches the info in acp.
25309  */
25310 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25311 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25312 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25313 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25314 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25315 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25316 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25317 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25318 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25319 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25320 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25321 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25322 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25323 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25324 	&(tcp)->tcp_ip_src_v6)) &&				\
25325 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25326 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25327 	&(tcp)->tcp_remote_v6)) &&				\
25328 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25329 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25330 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25331 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25332 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25333 	(acp)->ac_end >= (tcp)->tcp_state))
25334 
25335 #define	TCP_AC_MATCH(acp, tcp)					\
25336 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25337 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25338 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25339 
25340 /*
25341  * Build a message containing a tcp_ioc_abort_conn_t structure
25342  * which is filled in with information from acp and tp.
25343  */
25344 static mblk_t *
25345 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25346 {
25347 	mblk_t *mp;
25348 	tcp_ioc_abort_conn_t *tacp;
25349 
25350 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25351 	if (mp == NULL)
25352 		return (NULL);
25353 
25354 	mp->b_datap->db_type = M_CTL;
25355 
25356 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25357 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25358 	    sizeof (uint32_t));
25359 
25360 	tacp->ac_start = acp->ac_start;
25361 	tacp->ac_end = acp->ac_end;
25362 	tacp->ac_zoneid = acp->ac_zoneid;
25363 
25364 	if (acp->ac_local.ss_family == AF_INET) {
25365 		tacp->ac_local.ss_family = AF_INET;
25366 		tacp->ac_remote.ss_family = AF_INET;
25367 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25368 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25369 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25370 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25371 	} else {
25372 		tacp->ac_local.ss_family = AF_INET6;
25373 		tacp->ac_remote.ss_family = AF_INET6;
25374 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25375 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25376 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25377 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25378 	}
25379 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25380 	return (mp);
25381 }
25382 
25383 /*
25384  * Print a tcp_ioc_abort_conn_t structure.
25385  */
25386 static void
25387 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25388 {
25389 	char lbuf[128];
25390 	char rbuf[128];
25391 	sa_family_t af;
25392 	in_port_t lport, rport;
25393 	ushort_t logflags;
25394 
25395 	af = acp->ac_local.ss_family;
25396 
25397 	if (af == AF_INET) {
25398 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25399 		    lbuf, 128);
25400 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25401 		    rbuf, 128);
25402 		lport = ntohs(TCP_AC_V4LPORT(acp));
25403 		rport = ntohs(TCP_AC_V4RPORT(acp));
25404 	} else {
25405 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25406 		    lbuf, 128);
25407 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25408 		    rbuf, 128);
25409 		lport = ntohs(TCP_AC_V6LPORT(acp));
25410 		rport = ntohs(TCP_AC_V6RPORT(acp));
25411 	}
25412 
25413 	logflags = SL_TRACE | SL_NOTE;
25414 	/*
25415 	 * Don't print this message to the console if the operation was done
25416 	 * to a non-global zone.
25417 	 */
25418 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25419 		logflags |= SL_CONSOLE;
25420 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25421 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25422 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25423 	    acp->ac_start, acp->ac_end);
25424 }
25425 
25426 /*
25427  * Called inside tcp_rput when a message built using
25428  * tcp_ioctl_abort_build_msg is put into a queue.
25429  * Note that when we get here there is no wildcard in acp any more.
25430  */
25431 static void
25432 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25433 {
25434 	tcp_ioc_abort_conn_t *acp;
25435 
25436 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25437 	if (tcp->tcp_state <= acp->ac_end) {
25438 		/*
25439 		 * If we get here, we are already on the correct
25440 		 * squeue. This ioctl follows the following path
25441 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25442 		 * ->tcp_ioctl_abort->squeue_fill (if on a
25443 		 * different squeue)
25444 		 */
25445 		int errcode;
25446 
25447 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25448 		(void) tcp_clean_death(tcp, errcode, 26);
25449 	}
25450 	freemsg(mp);
25451 }
25452 
25453 /*
25454  * Abort all matching connections on a hash chain.
25455  */
25456 static int
25457 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25458     boolean_t exact, tcp_stack_t *tcps)
25459 {
25460 	int nmatch, err = 0;
25461 	tcp_t *tcp;
25462 	MBLKP mp, last, listhead = NULL;
25463 	conn_t	*tconnp;
25464 	connf_t	*connfp;
25465 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25466 
25467 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25468 
25469 startover:
25470 	nmatch = 0;
25471 
25472 	mutex_enter(&connfp->connf_lock);
25473 	for (tconnp = connfp->connf_head; tconnp != NULL;
25474 	    tconnp = tconnp->conn_next) {
25475 		tcp = tconnp->conn_tcp;
25476 		if (TCP_AC_MATCH(acp, tcp)) {
25477 			CONN_INC_REF(tcp->tcp_connp);
25478 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25479 			if (mp == NULL) {
25480 				err = ENOMEM;
25481 				CONN_DEC_REF(tcp->tcp_connp);
25482 				break;
25483 			}
25484 			mp->b_prev = (mblk_t *)tcp;
25485 
25486 			if (listhead == NULL) {
25487 				listhead = mp;
25488 				last = mp;
25489 			} else {
25490 				last->b_next = mp;
25491 				last = mp;
25492 			}
25493 			nmatch++;
25494 			if (exact)
25495 				break;
25496 		}
25497 
25498 		/* Avoid holding lock for too long. */
25499 		if (nmatch >= 500)
25500 			break;
25501 	}
25502 	mutex_exit(&connfp->connf_lock);
25503 
25504 	/* Pass mp into the correct tcp */
25505 	while ((mp = listhead) != NULL) {
25506 		listhead = listhead->b_next;
25507 		tcp = (tcp_t *)mp->b_prev;
25508 		mp->b_next = mp->b_prev = NULL;
25509 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
25510 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
25511 	}
25512 
25513 	*count += nmatch;
25514 	if (nmatch >= 500 && err == 0)
25515 		goto startover;
25516 	return (err);
25517 }
25518 
25519 /*
25520  * Abort all connections that matches the attributes specified in acp.
25521  */
25522 static int
25523 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25524 {
25525 	sa_family_t af;
25526 	uint32_t  ports;
25527 	uint16_t *pports;
25528 	int err = 0, count = 0;
25529 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25530 	int index = -1;
25531 	ushort_t logflags;
25532 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25533 
25534 	af = acp->ac_local.ss_family;
25535 
25536 	if (af == AF_INET) {
25537 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25538 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25539 			pports = (uint16_t *)&ports;
25540 			pports[1] = TCP_AC_V4LPORT(acp);
25541 			pports[0] = TCP_AC_V4RPORT(acp);
25542 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25543 		}
25544 	} else {
25545 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25546 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25547 			pports = (uint16_t *)&ports;
25548 			pports[1] = TCP_AC_V6LPORT(acp);
25549 			pports[0] = TCP_AC_V6RPORT(acp);
25550 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25551 		}
25552 	}
25553 
25554 	/*
25555 	 * For cases where remote addr, local port, and remote port are non-
25556 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25557 	 */
25558 	if (index != -1) {
25559 		err = tcp_ioctl_abort_bucket(acp, index,
25560 		    &count, exact, tcps);
25561 	} else {
25562 		/*
25563 		 * loop through all entries for wildcard case
25564 		 */
25565 		for (index = 0;
25566 		    index < ipst->ips_ipcl_conn_fanout_size;
25567 		    index++) {
25568 			err = tcp_ioctl_abort_bucket(acp, index,
25569 			    &count, exact, tcps);
25570 			if (err != 0)
25571 				break;
25572 		}
25573 	}
25574 
25575 	logflags = SL_TRACE | SL_NOTE;
25576 	/*
25577 	 * Don't print this message to the console if the operation was done
25578 	 * to a non-global zone.
25579 	 */
25580 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25581 		logflags |= SL_CONSOLE;
25582 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25583 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25584 	if (err == 0 && count == 0)
25585 		err = ENOENT;
25586 	return (err);
25587 }
25588 
25589 /*
25590  * Process the TCP_IOC_ABORT_CONN ioctl request.
25591  */
25592 static void
25593 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25594 {
25595 	int	err;
25596 	IOCP    iocp;
25597 	MBLKP   mp1;
25598 	sa_family_t laf, raf;
25599 	tcp_ioc_abort_conn_t *acp;
25600 	zone_t		*zptr;
25601 	conn_t		*connp = Q_TO_CONN(q);
25602 	zoneid_t	zoneid = connp->conn_zoneid;
25603 	tcp_t		*tcp = connp->conn_tcp;
25604 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25605 
25606 	iocp = (IOCP)mp->b_rptr;
25607 
25608 	if ((mp1 = mp->b_cont) == NULL ||
25609 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25610 		err = EINVAL;
25611 		goto out;
25612 	}
25613 
25614 	/* check permissions */
25615 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25616 		err = EPERM;
25617 		goto out;
25618 	}
25619 
25620 	if (mp1->b_cont != NULL) {
25621 		freemsg(mp1->b_cont);
25622 		mp1->b_cont = NULL;
25623 	}
25624 
25625 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25626 	laf = acp->ac_local.ss_family;
25627 	raf = acp->ac_remote.ss_family;
25628 
25629 	/* check that a zone with the supplied zoneid exists */
25630 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25631 		zptr = zone_find_by_id(zoneid);
25632 		if (zptr != NULL) {
25633 			zone_rele(zptr);
25634 		} else {
25635 			err = EINVAL;
25636 			goto out;
25637 		}
25638 	}
25639 
25640 	/*
25641 	 * For exclusive stacks we set the zoneid to zero
25642 	 * to make TCP operate as if in the global zone.
25643 	 */
25644 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25645 		acp->ac_zoneid = GLOBAL_ZONEID;
25646 
25647 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25648 	    acp->ac_start > acp->ac_end || laf != raf ||
25649 	    (laf != AF_INET && laf != AF_INET6)) {
25650 		err = EINVAL;
25651 		goto out;
25652 	}
25653 
25654 	tcp_ioctl_abort_dump(acp);
25655 	err = tcp_ioctl_abort(acp, tcps);
25656 
25657 out:
25658 	if (mp1 != NULL) {
25659 		freemsg(mp1);
25660 		mp->b_cont = NULL;
25661 	}
25662 
25663 	if (err != 0)
25664 		miocnak(q, mp, 0, err);
25665 	else
25666 		miocack(q, mp, 0, 0);
25667 }
25668 
25669 /*
25670  * tcp_time_wait_processing() handles processing of incoming packets when
25671  * the tcp is in the TIME_WAIT state.
25672  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25673  * on the time wait list.
25674  */
25675 void
25676 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25677     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25678 {
25679 	int32_t		bytes_acked;
25680 	int32_t		gap;
25681 	int32_t		rgap;
25682 	tcp_opt_t	tcpopt;
25683 	uint_t		flags;
25684 	uint32_t	new_swnd = 0;
25685 	conn_t		*connp;
25686 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25687 
25688 	BUMP_LOCAL(tcp->tcp_ibsegs);
25689 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25690 
25691 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25692 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25693 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25694 	if (tcp->tcp_snd_ts_ok) {
25695 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25696 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25697 			    tcp->tcp_rnxt, TH_ACK);
25698 			goto done;
25699 		}
25700 	}
25701 	gap = seg_seq - tcp->tcp_rnxt;
25702 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25703 	if (gap < 0) {
25704 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25705 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25706 		    (seg_len > -gap ? -gap : seg_len));
25707 		seg_len += gap;
25708 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25709 			if (flags & TH_RST) {
25710 				goto done;
25711 			}
25712 			if ((flags & TH_FIN) && seg_len == -1) {
25713 				/*
25714 				 * When TCP receives a duplicate FIN in
25715 				 * TIME_WAIT state, restart the 2 MSL timer.
25716 				 * See page 73 in RFC 793. Make sure this TCP
25717 				 * is already on the TIME_WAIT list. If not,
25718 				 * just restart the timer.
25719 				 */
25720 				if (TCP_IS_DETACHED(tcp)) {
25721 					if (tcp_time_wait_remove(tcp, NULL) ==
25722 					    B_TRUE) {
25723 						tcp_time_wait_append(tcp);
25724 						TCP_DBGSTAT(tcps,
25725 						    tcp_rput_time_wait);
25726 					}
25727 				} else {
25728 					ASSERT(tcp != NULL);
25729 					TCP_TIMER_RESTART(tcp,
25730 					    tcps->tcps_time_wait_interval);
25731 				}
25732 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25733 				    tcp->tcp_rnxt, TH_ACK);
25734 				goto done;
25735 			}
25736 			flags |=  TH_ACK_NEEDED;
25737 			seg_len = 0;
25738 			goto process_ack;
25739 		}
25740 
25741 		/* Fix seg_seq, and chew the gap off the front. */
25742 		seg_seq = tcp->tcp_rnxt;
25743 	}
25744 
25745 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25746 		/*
25747 		 * Make sure that when we accept the connection, pick
25748 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25749 		 * old connection.
25750 		 *
25751 		 * The next ISS generated is equal to tcp_iss_incr_extra
25752 		 * + ISS_INCR/2 + other components depending on the
25753 		 * value of tcp_strong_iss.  We pre-calculate the new
25754 		 * ISS here and compare with tcp_snxt to determine if
25755 		 * we need to make adjustment to tcp_iss_incr_extra.
25756 		 *
25757 		 * The above calculation is ugly and is a
25758 		 * waste of CPU cycles...
25759 		 */
25760 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25761 		int32_t adj;
25762 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25763 
25764 		switch (tcps->tcps_strong_iss) {
25765 		case 2: {
25766 			/* Add time and MD5 components. */
25767 			uint32_t answer[4];
25768 			struct {
25769 				uint32_t ports;
25770 				in6_addr_t src;
25771 				in6_addr_t dst;
25772 			} arg;
25773 			MD5_CTX context;
25774 
25775 			mutex_enter(&tcps->tcps_iss_key_lock);
25776 			context = tcps->tcps_iss_key;
25777 			mutex_exit(&tcps->tcps_iss_key_lock);
25778 			arg.ports = tcp->tcp_ports;
25779 			/* We use MAPPED addresses in tcp_iss_init */
25780 			arg.src = tcp->tcp_ip_src_v6;
25781 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25782 				IN6_IPADDR_TO_V4MAPPED(
25783 				    tcp->tcp_ipha->ipha_dst,
25784 				    &arg.dst);
25785 			} else {
25786 				arg.dst =
25787 				    tcp->tcp_ip6h->ip6_dst;
25788 			}
25789 			MD5Update(&context, (uchar_t *)&arg,
25790 			    sizeof (arg));
25791 			MD5Final((uchar_t *)answer, &context);
25792 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25793 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25794 			break;
25795 		}
25796 		case 1:
25797 			/* Add time component and min random (i.e. 1). */
25798 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25799 			break;
25800 		default:
25801 			/* Add only time component. */
25802 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25803 			break;
25804 		}
25805 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25806 			/*
25807 			 * New ISS not guaranteed to be ISS_INCR/2
25808 			 * ahead of the current tcp_snxt, so add the
25809 			 * difference to tcp_iss_incr_extra.
25810 			 */
25811 			tcps->tcps_iss_incr_extra += adj;
25812 		}
25813 		/*
25814 		 * If tcp_clean_death() can not perform the task now,
25815 		 * drop the SYN packet and let the other side re-xmit.
25816 		 * Otherwise pass the SYN packet back in, since the
25817 		 * old tcp state has been cleaned up or freed.
25818 		 */
25819 		if (tcp_clean_death(tcp, 0, 27) == -1)
25820 			goto done;
25821 		/*
25822 		 * We will come back to tcp_rput_data
25823 		 * on the global queue. Packets destined
25824 		 * for the global queue will be checked
25825 		 * with global policy. But the policy for
25826 		 * this packet has already been checked as
25827 		 * this was destined for the detached
25828 		 * connection. We need to bypass policy
25829 		 * check this time by attaching a dummy
25830 		 * ipsec_in with ipsec_in_dont_check set.
25831 		 */
25832 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25833 		if (connp != NULL) {
25834 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25835 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25836 			return;
25837 		}
25838 		goto done;
25839 	}
25840 
25841 	/*
25842 	 * rgap is the amount of stuff received out of window.  A negative
25843 	 * value is the amount out of window.
25844 	 */
25845 	if (rgap < 0) {
25846 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25847 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25848 		/* Fix seg_len and make sure there is something left. */
25849 		seg_len += rgap;
25850 		if (seg_len <= 0) {
25851 			if (flags & TH_RST) {
25852 				goto done;
25853 			}
25854 			flags |=  TH_ACK_NEEDED;
25855 			seg_len = 0;
25856 			goto process_ack;
25857 		}
25858 	}
25859 	/*
25860 	 * Check whether we can update tcp_ts_recent.  This test is
25861 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25862 	 * Extensions for High Performance: An Update", Internet Draft.
25863 	 */
25864 	if (tcp->tcp_snd_ts_ok &&
25865 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25866 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25867 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25868 		tcp->tcp_last_rcv_lbolt = lbolt64;
25869 	}
25870 
25871 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25872 		/* Always ack out of order packets */
25873 		flags |= TH_ACK_NEEDED;
25874 		seg_len = 0;
25875 	} else if (seg_len > 0) {
25876 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25877 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25878 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25879 	}
25880 	if (flags & TH_RST) {
25881 		(void) tcp_clean_death(tcp, 0, 28);
25882 		goto done;
25883 	}
25884 	if (flags & TH_SYN) {
25885 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25886 		    TH_RST|TH_ACK);
25887 		/*
25888 		 * Do not delete the TCP structure if it is in
25889 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25890 		 */
25891 		goto done;
25892 	}
25893 process_ack:
25894 	if (flags & TH_ACK) {
25895 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25896 		if (bytes_acked <= 0) {
25897 			if (bytes_acked == 0 && seg_len == 0 &&
25898 			    new_swnd == tcp->tcp_swnd)
25899 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25900 		} else {
25901 			/* Acks something not sent */
25902 			flags |= TH_ACK_NEEDED;
25903 		}
25904 	}
25905 	if (flags & TH_ACK_NEEDED) {
25906 		/*
25907 		 * Time to send an ack for some reason.
25908 		 */
25909 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25910 		    tcp->tcp_rnxt, TH_ACK);
25911 	}
25912 done:
25913 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25914 		DB_CKSUMSTART(mp) = 0;
25915 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25916 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25917 	}
25918 	freemsg(mp);
25919 }
25920 
25921 /*
25922  * Allocate a T_SVR4_OPTMGMT_REQ.
25923  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
25924  * that tcp_rput_other can drop the acks.
25925  */
25926 static mblk_t *
25927 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
25928 {
25929 	mblk_t *mp;
25930 	struct T_optmgmt_req *tor;
25931 	struct opthdr *oh;
25932 	uint_t size;
25933 	char *optptr;
25934 
25935 	size = sizeof (*tor) + sizeof (*oh) + optlen;
25936 	mp = allocb(size, BPRI_MED);
25937 	if (mp == NULL)
25938 		return (NULL);
25939 
25940 	mp->b_wptr += size;
25941 	mp->b_datap->db_type = M_PROTO;
25942 	tor = (struct T_optmgmt_req *)mp->b_rptr;
25943 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
25944 	tor->MGMT_flags = T_NEGOTIATE;
25945 	tor->OPT_length = sizeof (*oh) + optlen;
25946 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
25947 
25948 	oh = (struct opthdr *)&tor[1];
25949 	oh->level = level;
25950 	oh->name = cmd;
25951 	oh->len = optlen;
25952 	if (optlen != 0) {
25953 		optptr = (char *)&oh[1];
25954 		bcopy(opt, optptr, optlen);
25955 	}
25956 	return (mp);
25957 }
25958 
25959 /*
25960  * TCP Timers Implementation.
25961  */
25962 timeout_id_t
25963 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25964 {
25965 	mblk_t *mp;
25966 	tcp_timer_t *tcpt;
25967 	tcp_t *tcp = connp->conn_tcp;
25968 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25969 
25970 	ASSERT(connp->conn_sqp != NULL);
25971 
25972 	TCP_DBGSTAT(tcps, tcp_timeout_calls);
25973 
25974 	if (tcp->tcp_timercache == NULL) {
25975 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25976 	} else {
25977 		TCP_DBGSTAT(tcps, tcp_timeout_cached_alloc);
25978 		mp = tcp->tcp_timercache;
25979 		tcp->tcp_timercache = mp->b_next;
25980 		mp->b_next = NULL;
25981 		ASSERT(mp->b_wptr == NULL);
25982 	}
25983 
25984 	CONN_INC_REF(connp);
25985 	tcpt = (tcp_timer_t *)mp->b_rptr;
25986 	tcpt->connp = connp;
25987 	tcpt->tcpt_proc = f;
25988 	tcpt->tcpt_tid = timeout(tcp_timer_callback, mp, tim);
25989 	return ((timeout_id_t)mp);
25990 }
25991 
25992 static void
25993 tcp_timer_callback(void *arg)
25994 {
25995 	mblk_t *mp = (mblk_t *)arg;
25996 	tcp_timer_t *tcpt;
25997 	conn_t	*connp;
25998 
25999 	tcpt = (tcp_timer_t *)mp->b_rptr;
26000 	connp = tcpt->connp;
26001 	squeue_fill(connp->conn_sqp, mp,
26002 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
26003 }
26004 
26005 static void
26006 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
26007 {
26008 	tcp_timer_t *tcpt;
26009 	conn_t *connp = (conn_t *)arg;
26010 	tcp_t *tcp = connp->conn_tcp;
26011 
26012 	tcpt = (tcp_timer_t *)mp->b_rptr;
26013 	ASSERT(connp == tcpt->connp);
26014 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
26015 
26016 	/*
26017 	 * If the TCP has reached the closed state, don't proceed any
26018 	 * further. This TCP logically does not exist on the system.
26019 	 * tcpt_proc could for example access queues, that have already
26020 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
26021 	 */
26022 	if (tcp->tcp_state != TCPS_CLOSED) {
26023 		(*tcpt->tcpt_proc)(connp);
26024 	} else {
26025 		tcp->tcp_timer_tid = 0;
26026 	}
26027 	tcp_timer_free(connp->conn_tcp, mp);
26028 }
26029 
26030 /*
26031  * There is potential race with untimeout and the handler firing at the same
26032  * time. The mblock may be freed by the handler while we are trying to use
26033  * it. But since both should execute on the same squeue, this race should not
26034  * occur.
26035  */
26036 clock_t
26037 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
26038 {
26039 	mblk_t	*mp = (mblk_t *)id;
26040 	tcp_timer_t *tcpt;
26041 	clock_t delta;
26042 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26043 
26044 	TCP_DBGSTAT(tcps, tcp_timeout_cancel_reqs);
26045 
26046 	if (mp == NULL)
26047 		return (-1);
26048 
26049 	tcpt = (tcp_timer_t *)mp->b_rptr;
26050 	ASSERT(tcpt->connp == connp);
26051 
26052 	delta = untimeout(tcpt->tcpt_tid);
26053 
26054 	if (delta >= 0) {
26055 		TCP_DBGSTAT(tcps, tcp_timeout_canceled);
26056 		tcp_timer_free(connp->conn_tcp, mp);
26057 		CONN_DEC_REF(connp);
26058 	}
26059 
26060 	return (delta);
26061 }
26062 
26063 /*
26064  * Allocate space for the timer event. The allocation looks like mblk, but it is
26065  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26066  *
26067  * Dealing with failures: If we can't allocate from the timer cache we try
26068  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26069  * points to b_rptr.
26070  * If we can't allocate anything using allocb_tryhard(), we perform a last
26071  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26072  * save the actual allocation size in b_datap.
26073  */
26074 mblk_t *
26075 tcp_timermp_alloc(int kmflags)
26076 {
26077 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26078 	    kmflags & ~KM_PANIC);
26079 
26080 	if (mp != NULL) {
26081 		mp->b_next = mp->b_prev = NULL;
26082 		mp->b_rptr = (uchar_t *)(&mp[1]);
26083 		mp->b_wptr = NULL;
26084 		mp->b_datap = NULL;
26085 		mp->b_queue = NULL;
26086 		mp->b_cont = NULL;
26087 	} else if (kmflags & KM_PANIC) {
26088 		/*
26089 		 * Failed to allocate memory for the timer. Try allocating from
26090 		 * dblock caches.
26091 		 */
26092 		/* ipclassifier calls this from a constructor - hence no tcps */
26093 		TCP_G_STAT(tcp_timermp_allocfail);
26094 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26095 		if (mp == NULL) {
26096 			size_t size = 0;
26097 			/*
26098 			 * Memory is really low. Try tryhard allocation.
26099 			 *
26100 			 * ipclassifier calls this from a constructor -
26101 			 * hence no tcps
26102 			 */
26103 			TCP_G_STAT(tcp_timermp_allocdblfail);
26104 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26105 			    sizeof (tcp_timer_t), &size, kmflags);
26106 			mp->b_rptr = (uchar_t *)(&mp[1]);
26107 			mp->b_next = mp->b_prev = NULL;
26108 			mp->b_wptr = (uchar_t *)-1;
26109 			mp->b_datap = (dblk_t *)size;
26110 			mp->b_queue = NULL;
26111 			mp->b_cont = NULL;
26112 		}
26113 		ASSERT(mp->b_wptr != NULL);
26114 	}
26115 	/* ipclassifier calls this from a constructor - hence no tcps */
26116 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26117 
26118 	return (mp);
26119 }
26120 
26121 /*
26122  * Free per-tcp timer cache.
26123  * It can only contain entries from tcp_timercache.
26124  */
26125 void
26126 tcp_timermp_free(tcp_t *tcp)
26127 {
26128 	mblk_t *mp;
26129 
26130 	while ((mp = tcp->tcp_timercache) != NULL) {
26131 		ASSERT(mp->b_wptr == NULL);
26132 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26133 		kmem_cache_free(tcp_timercache, mp);
26134 	}
26135 }
26136 
26137 /*
26138  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26139  * events there already (currently at most two events are cached).
26140  * If the event is not allocated from the timer cache, free it right away.
26141  */
26142 static void
26143 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26144 {
26145 	mblk_t *mp1 = tcp->tcp_timercache;
26146 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26147 
26148 	if (mp->b_wptr != NULL) {
26149 		/*
26150 		 * This allocation is not from a timer cache, free it right
26151 		 * away.
26152 		 */
26153 		if (mp->b_wptr != (uchar_t *)-1)
26154 			freeb(mp);
26155 		else
26156 			kmem_free(mp, (size_t)mp->b_datap);
26157 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26158 		/* Cache this timer block for future allocations */
26159 		mp->b_rptr = (uchar_t *)(&mp[1]);
26160 		mp->b_next = mp1;
26161 		tcp->tcp_timercache = mp;
26162 	} else {
26163 		kmem_cache_free(tcp_timercache, mp);
26164 		TCP_DBGSTAT(tcps, tcp_timermp_freed);
26165 	}
26166 }
26167 
26168 /*
26169  * End of TCP Timers implementation.
26170  */
26171 
26172 /*
26173  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26174  * on the specified backing STREAMS q. Note, the caller may make the
26175  * decision to call based on the tcp_t.tcp_flow_stopped value which
26176  * when check outside the q's lock is only an advisory check ...
26177  */
26178 
26179 void
26180 tcp_setqfull(tcp_t *tcp)
26181 {
26182 	queue_t *q = tcp->tcp_wq;
26183 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26184 
26185 	if (!(q->q_flag & QFULL)) {
26186 		mutex_enter(QLOCK(q));
26187 		if (!(q->q_flag & QFULL)) {
26188 			/* still need to set QFULL */
26189 			q->q_flag |= QFULL;
26190 			tcp->tcp_flow_stopped = B_TRUE;
26191 			mutex_exit(QLOCK(q));
26192 			TCP_STAT(tcps, tcp_flwctl_on);
26193 		} else {
26194 			mutex_exit(QLOCK(q));
26195 		}
26196 	}
26197 }
26198 
26199 void
26200 tcp_clrqfull(tcp_t *tcp)
26201 {
26202 	queue_t *q = tcp->tcp_wq;
26203 
26204 	if (q->q_flag & QFULL) {
26205 		mutex_enter(QLOCK(q));
26206 		if (q->q_flag & QFULL) {
26207 			q->q_flag &= ~QFULL;
26208 			tcp->tcp_flow_stopped = B_FALSE;
26209 			mutex_exit(QLOCK(q));
26210 			if (q->q_flag & QWANTW)
26211 				qbackenable(q, 0);
26212 		} else {
26213 			mutex_exit(QLOCK(q));
26214 		}
26215 	}
26216 }
26217 
26218 
26219 /*
26220  * kstats related to squeues i.e. not per IP instance
26221  */
26222 static void *
26223 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26224 {
26225 	kstat_t *ksp;
26226 
26227 	tcp_g_stat_t template = {
26228 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26229 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26230 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26231 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26232 	};
26233 
26234 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26235 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26236 	    KSTAT_FLAG_VIRTUAL);
26237 
26238 	if (ksp == NULL)
26239 		return (NULL);
26240 
26241 	bcopy(&template, tcp_g_statp, sizeof (template));
26242 	ksp->ks_data = (void *)tcp_g_statp;
26243 
26244 	kstat_install(ksp);
26245 	return (ksp);
26246 }
26247 
26248 static void
26249 tcp_g_kstat_fini(kstat_t *ksp)
26250 {
26251 	if (ksp != NULL) {
26252 		kstat_delete(ksp);
26253 	}
26254 }
26255 
26256 
26257 static void *
26258 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26259 {
26260 	kstat_t *ksp;
26261 
26262 	tcp_stat_t template = {
26263 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26264 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26265 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26266 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26267 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26268 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26269 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26270 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26271 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26272 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26273 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26274 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26275 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26276 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26277 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26278 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26279 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26280 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26281 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26282 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26283 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26284 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26285 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26286 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26287 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26288 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26289 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26290 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26291 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26292 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26293 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26294 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26295 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26296 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26297 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26298 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26299 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26300 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26301 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26302 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26303 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26304 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26305 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26306 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26307 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26308 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26309 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26310 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26311 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26312 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26313 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26314 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26315 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26316 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26317 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26318 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26319 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26320 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26321 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26322 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26323 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26324 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26325 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26326 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26327 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26328 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26329 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26330 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26331 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26332 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26333 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26334 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26335 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26336 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26337 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26338 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26339 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26340 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26341 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26342 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26343 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26344 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26345 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26346 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26347 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26348 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26349 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26350 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26351 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26352 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26353 	};
26354 
26355 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26356 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26357 	    KSTAT_FLAG_VIRTUAL, stackid);
26358 
26359 	if (ksp == NULL)
26360 		return (NULL);
26361 
26362 	bcopy(&template, tcps_statisticsp, sizeof (template));
26363 	ksp->ks_data = (void *)tcps_statisticsp;
26364 	ksp->ks_private = (void *)(uintptr_t)stackid;
26365 
26366 	kstat_install(ksp);
26367 	return (ksp);
26368 }
26369 
26370 static void
26371 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26372 {
26373 	if (ksp != NULL) {
26374 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26375 		kstat_delete_netstack(ksp, stackid);
26376 	}
26377 }
26378 
26379 /*
26380  * TCP Kstats implementation
26381  */
26382 static void *
26383 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26384 {
26385 	kstat_t	*ksp;
26386 
26387 	tcp_named_kstat_t template = {
26388 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26389 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26390 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26391 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26392 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26393 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26394 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26395 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26396 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26397 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26398 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26399 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26400 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26401 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26402 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26403 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26404 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26405 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26406 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26407 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26408 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26409 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26410 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26411 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26412 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26413 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26414 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26415 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26416 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26417 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26418 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26419 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26420 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26421 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26422 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26423 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26424 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26425 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26426 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26427 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26428 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26429 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26430 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26431 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26432 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26433 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26434 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26435 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26436 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26437 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26438 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26439 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26440 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26441 	};
26442 
26443 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26444 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26445 
26446 	if (ksp == NULL)
26447 		return (NULL);
26448 
26449 	template.rtoAlgorithm.value.ui32 = 4;
26450 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26451 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26452 	template.maxConn.value.i32 = -1;
26453 
26454 	bcopy(&template, ksp->ks_data, sizeof (template));
26455 	ksp->ks_update = tcp_kstat_update;
26456 	ksp->ks_private = (void *)(uintptr_t)stackid;
26457 
26458 	kstat_install(ksp);
26459 	return (ksp);
26460 }
26461 
26462 static void
26463 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26464 {
26465 	if (ksp != NULL) {
26466 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26467 		kstat_delete_netstack(ksp, stackid);
26468 	}
26469 }
26470 
26471 static int
26472 tcp_kstat_update(kstat_t *kp, int rw)
26473 {
26474 	tcp_named_kstat_t *tcpkp;
26475 	tcp_t		*tcp;
26476 	connf_t		*connfp;
26477 	conn_t		*connp;
26478 	int 		i;
26479 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26480 	netstack_t	*ns;
26481 	tcp_stack_t	*tcps;
26482 	ip_stack_t	*ipst;
26483 
26484 	if ((kp == NULL) || (kp->ks_data == NULL))
26485 		return (EIO);
26486 
26487 	if (rw == KSTAT_WRITE)
26488 		return (EACCES);
26489 
26490 	ns = netstack_find_by_stackid(stackid);
26491 	if (ns == NULL)
26492 		return (-1);
26493 	tcps = ns->netstack_tcp;
26494 	if (tcps == NULL) {
26495 		netstack_rele(ns);
26496 		return (-1);
26497 	}
26498 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26499 
26500 	tcpkp->currEstab.value.ui32 = 0;
26501 
26502 	ipst = ns->netstack_ip;
26503 
26504 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26505 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26506 		connp = NULL;
26507 		while ((connp =
26508 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26509 			tcp = connp->conn_tcp;
26510 			switch (tcp_snmp_state(tcp)) {
26511 			case MIB2_TCP_established:
26512 			case MIB2_TCP_closeWait:
26513 				tcpkp->currEstab.value.ui32++;
26514 				break;
26515 			}
26516 		}
26517 	}
26518 
26519 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26520 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26521 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26522 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26523 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26524 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26525 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26526 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26527 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26528 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26529 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26530 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26531 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26532 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26533 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26534 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26535 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26536 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26537 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26538 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26539 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26540 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26541 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26542 	tcpkp->inDataInorderSegs.value.ui32 =
26543 	    tcps->tcps_mib.tcpInDataInorderSegs;
26544 	tcpkp->inDataInorderBytes.value.ui32 =
26545 	    tcps->tcps_mib.tcpInDataInorderBytes;
26546 	tcpkp->inDataUnorderSegs.value.ui32 =
26547 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26548 	tcpkp->inDataUnorderBytes.value.ui32 =
26549 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26550 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26551 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26552 	tcpkp->inDataPartDupSegs.value.ui32 =
26553 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26554 	tcpkp->inDataPartDupBytes.value.ui32 =
26555 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26556 	tcpkp->inDataPastWinSegs.value.ui32 =
26557 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26558 	tcpkp->inDataPastWinBytes.value.ui32 =
26559 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26560 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26561 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26562 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26563 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26564 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26565 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26566 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26567 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26568 	tcpkp->timKeepaliveProbe.value.ui32 =
26569 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26570 	tcpkp->timKeepaliveDrop.value.ui32 =
26571 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26572 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26573 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26574 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26575 	tcpkp->outSackRetransSegs.value.ui32 =
26576 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26577 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26578 
26579 	netstack_rele(ns);
26580 	return (0);
26581 }
26582 
26583 void
26584 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26585 {
26586 	uint16_t	hdr_len;
26587 	ipha_t		*ipha;
26588 	uint8_t		*nexthdrp;
26589 	tcph_t		*tcph;
26590 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26591 
26592 	/* Already has an eager */
26593 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26594 		TCP_STAT(tcps, tcp_reinput_syn);
26595 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
26596 		    connp, SQTAG_TCP_REINPUT_EAGER);
26597 		return;
26598 	}
26599 
26600 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26601 	case IPV4_VERSION:
26602 		ipha = (ipha_t *)mp->b_rptr;
26603 		hdr_len = IPH_HDR_LENGTH(ipha);
26604 		break;
26605 	case IPV6_VERSION:
26606 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26607 		    &hdr_len, &nexthdrp)) {
26608 			CONN_DEC_REF(connp);
26609 			freemsg(mp);
26610 			return;
26611 		}
26612 		break;
26613 	}
26614 
26615 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26616 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26617 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26618 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26619 	}
26620 
26621 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
26622 	    SQTAG_TCP_REINPUT);
26623 }
26624 
26625 static squeue_func_t
26626 tcp_squeue_switch(int val)
26627 {
26628 	squeue_func_t rval = squeue_fill;
26629 
26630 	switch (val) {
26631 	case 1:
26632 		rval = squeue_enter_nodrain;
26633 		break;
26634 	case 2:
26635 		rval = squeue_enter;
26636 		break;
26637 	default:
26638 		break;
26639 	}
26640 	return (rval);
26641 }
26642 
26643 /*
26644  * This is called once for each squeue - globally for all stack
26645  * instances.
26646  */
26647 static void
26648 tcp_squeue_add(squeue_t *sqp)
26649 {
26650 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26651 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26652 
26653 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26654 	tcp_time_wait->tcp_time_wait_tid = timeout(tcp_time_wait_collector,
26655 	    sqp, TCP_TIME_WAIT_DELAY);
26656 	if (tcp_free_list_max_cnt == 0) {
26657 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26658 		    max_ncpus : boot_max_ncpus);
26659 
26660 		/*
26661 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26662 		 */
26663 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26664 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26665 	}
26666 	tcp_time_wait->tcp_free_list_cnt = 0;
26667 }
26668