xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision d0f3f37e7f24f68fdbd85386c60e576883622762)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #include <sys/strsun.h>
35 #define	_SUN_TPI_VERSION 2
36 #include <sys/tihdr.h>
37 #include <sys/timod.h>
38 #include <sys/ddi.h>
39 #include <sys/sunddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/xti_inet.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/sdt.h>
45 #include <sys/vtrace.h>
46 #include <sys/kmem.h>
47 #include <sys/ethernet.h>
48 #include <sys/cpuvar.h>
49 #include <sys/dlpi.h>
50 #include <sys/multidata.h>
51 #include <sys/multidata_impl.h>
52 #include <sys/pattr.h>
53 #include <sys/policy.h>
54 #include <sys/priv.h>
55 #include <sys/zone.h>
56 #include <sys/sunldi.h>
57 
58 #include <sys/errno.h>
59 #include <sys/signal.h>
60 #include <sys/socket.h>
61 #include <sys/sockio.h>
62 #include <sys/isa_defs.h>
63 #include <sys/md5.h>
64 #include <sys/random.h>
65 #include <sys/sodirect.h>
66 #include <sys/uio.h>
67 #include <sys/systm.h>
68 #include <netinet/in.h>
69 #include <netinet/tcp.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <net/if.h>
73 #include <net/route.h>
74 #include <inet/ipsec_impl.h>
75 
76 #include <inet/common.h>
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip_ndp.h>
81 #include <inet/mi.h>
82 #include <inet/mib2.h>
83 #include <inet/nd.h>
84 #include <inet/optcom.h>
85 #include <inet/snmpcom.h>
86 #include <inet/kstatcom.h>
87 #include <inet/tcp.h>
88 #include <inet/tcp_impl.h>
89 #include <net/pfkeyv2.h>
90 #include <inet/ipsec_info.h>
91 #include <inet/ipdrop.h>
92 
93 #include <inet/ipclassifier.h>
94 #include <inet/ip_ire.h>
95 #include <inet/ip_ftable.h>
96 #include <inet/ip_if.h>
97 #include <inet/ipp_common.h>
98 #include <inet/ip_netinfo.h>
99 #include <sys/squeue.h>
100 #include <inet/kssl/ksslapi.h>
101 #include <sys/tsol/label.h>
102 #include <sys/tsol/tnet.h>
103 #include <rpc/pmap_prot.h>
104 #include <sys/callo.h>
105 
106 /*
107  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
108  *
109  * (Read the detailed design doc in PSARC case directory)
110  *
111  * The entire tcp state is contained in tcp_t and conn_t structure
112  * which are allocated in tandem using ipcl_conn_create() and passing
113  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
114  * the references on the tcp_t. The tcp_t structure is never compressed
115  * and packets always land on the correct TCP perimeter from the time
116  * eager is created till the time tcp_t dies (as such the old mentat
117  * TCP global queue is not used for detached state and no IPSEC checking
118  * is required). The global queue is still allocated to send out resets
119  * for connection which have no listeners and IP directly calls
120  * tcp_xmit_listeners_reset() which does any policy check.
121  *
122  * Protection and Synchronisation mechanism:
123  *
124  * The tcp data structure does not use any kind of lock for protecting
125  * its state but instead uses 'squeues' for mutual exclusion from various
126  * read and write side threads. To access a tcp member, the thread should
127  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
128  * squeue_fill). Since the squeues allow a direct function call, caller
129  * can pass any tcp function having prototype of edesc_t as argument
130  * (different from traditional STREAMs model where packets come in only
131  * designated entry points). The list of functions that can be directly
132  * called via squeue are listed before the usual function prototype.
133  *
134  * Referencing:
135  *
136  * TCP is MT-Hot and we use a reference based scheme to make sure that the
137  * tcp structure doesn't disappear when its needed. When the application
138  * creates an outgoing connection or accepts an incoming connection, we
139  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
140  * The IP reference is just a symbolic reference since ip_tcpclose()
141  * looks at tcp structure after tcp_close_output() returns which could
142  * have dropped the last TCP reference. So as long as the connection is
143  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
144  * conn_t. The classifier puts its own reference when the connection is
145  * inserted in listen or connected hash. Anytime a thread needs to enter
146  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
147  * on write side or by doing a classify on read side and then puts a
148  * reference on the conn before doing squeue_enter/tryenter/fill. For
149  * read side, the classifier itself puts the reference under fanout lock
150  * to make sure that tcp can't disappear before it gets processed. The
151  * squeue will drop this reference automatically so the called function
152  * doesn't have to do a DEC_REF.
153  *
154  * Opening a new connection:
155  *
156  * The outgoing connection open is pretty simple. tcp_open() does the
157  * work in creating the conn/tcp structure and initializing it. The
158  * squeue assignment is done based on the CPU the application
159  * is running on. So for outbound connections, processing is always done
160  * on application CPU which might be different from the incoming CPU
161  * being interrupted by the NIC. An optimal way would be to figure out
162  * the NIC <-> CPU binding at listen time, and assign the outgoing
163  * connection to the squeue attached to the CPU that will be interrupted
164  * for incoming packets (we know the NIC based on the bind IP address).
165  * This might seem like a problem if more data is going out but the
166  * fact is that in most cases the transmit is ACK driven transmit where
167  * the outgoing data normally sits on TCP's xmit queue waiting to be
168  * transmitted.
169  *
170  * Accepting a connection:
171  *
172  * This is a more interesting case because of various races involved in
173  * establishing a eager in its own perimeter. Read the meta comment on
174  * top of tcp_conn_request(). But briefly, the squeue is picked by
175  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
176  *
177  * Closing a connection:
178  *
179  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
180  * via squeue to do the close and mark the tcp as detached if the connection
181  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
182  * reference but tcp_close() drop IP's reference always. So if tcp was
183  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
184  * and 1 because it is in classifier's connected hash. This is the condition
185  * we use to determine that its OK to clean up the tcp outside of squeue
186  * when time wait expires (check the ref under fanout and conn_lock and
187  * if it is 2, remove it from fanout hash and kill it).
188  *
189  * Although close just drops the necessary references and marks the
190  * tcp_detached state, tcp_close needs to know the tcp_detached has been
191  * set (under squeue) before letting the STREAM go away (because a
192  * inbound packet might attempt to go up the STREAM while the close
193  * has happened and tcp_detached is not set). So a special lock and
194  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
195  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
196  * tcp_detached.
197  *
198  * Special provisions and fast paths:
199  *
200  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
201  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
202  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
203  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
204  * check to send packets directly to tcp_rput_data via squeue. Everyone
205  * else comes through tcp_input() on the read side.
206  *
207  * We also make special provisions for sockfs by marking tcp_issocket
208  * whenever we have only sockfs on top of TCP. This allows us to skip
209  * putting the tcp in acceptor hash since a sockfs listener can never
210  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
211  * since eager has already been allocated and the accept now happens
212  * on acceptor STREAM. There is a big blob of comment on top of
213  * tcp_conn_request explaining the new accept. When socket is POP'd,
214  * sockfs sends us an ioctl to mark the fact and we go back to old
215  * behaviour. Once tcp_issocket is unset, its never set for the
216  * life of that connection.
217  *
218  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
219  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
220  * directly to the socket (sodirect) and start an asynchronous copyout
221  * to a user-land receive-side buffer (uioa) when a blocking socket read
222  * (e.g. read, recv, ...) is pending.
223  *
224  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
225  * NULL so points to an sodirect_t and if marked enabled then we enqueue
226  * all mblk_t's directly to the socket.
227  *
228  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
229  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
230  * copyout will be started directly to the user-land uio buffer. Also, as we
231  * have a pending read, TCP's push logic can take into account the number of
232  * bytes to be received and only awake the blocked read()er when the uioa_t
233  * byte count has been satisfied.
234  *
235  * IPsec notes :
236  *
237  * Since a packet is always executed on the correct TCP perimeter
238  * all IPsec processing is defered to IP including checking new
239  * connections and setting IPSEC policies for new connection. The
240  * only exception is tcp_xmit_listeners_reset() which is called
241  * directly from IP and needs to policy check to see if TH_RST
242  * can be sent out.
243  *
244  * PFHooks notes :
245  *
246  * For mdt case, one meta buffer contains multiple packets. Mblks for every
247  * packet are assembled and passed to the hooks. When packets are blocked,
248  * or boundary of any packet is changed, the mdt processing is stopped, and
249  * packets of the meta buffer are send to the IP path one by one.
250  */
251 
252 /*
253  * Values for squeue switch:
254  * 1: squeue_enter_nodrain
255  * 2: squeue_enter
256  * 3: squeue_fill
257  */
258 int tcp_squeue_close = 2;	/* Setable in /etc/system */
259 int tcp_squeue_wput = 2;
260 
261 squeue_func_t tcp_squeue_close_proc;
262 squeue_func_t tcp_squeue_wput_proc;
263 
264 /*
265  * Macros for sodirect:
266  *
267  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
268  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
269  * if it exists and is enabled, else to NULL. Note, in the current
270  * sodirect implementation the sod_lockp must not be held across any
271  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
272  * will result as sod_lockp is the streamhead stdata.sd_lock.
273  *
274  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
275  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
276  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
277  * being used when sodirect code paths should be.
278  */
279 
280 #define	SOD_PTR_ENTER(tcp, sodp)					\
281 	(sodp) = (tcp)->tcp_sodirect;					\
282 									\
283 	if ((sodp) != NULL) {						\
284 		mutex_enter((sodp)->sod_lockp);				\
285 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
286 			mutex_exit((sodp)->sod_lockp);			\
287 			(sodp) = NULL;					\
288 		}							\
289 	}
290 
291 #define	SOD_NOT_ENABLED(tcp)						\
292 	((tcp)->tcp_sodirect == NULL ||					\
293 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
294 
295 /*
296  * This controls how tiny a write must be before we try to copy it
297  * into the the mblk on the tail of the transmit queue.  Not much
298  * speedup is observed for values larger than sixteen.  Zero will
299  * disable the optimisation.
300  */
301 int tcp_tx_pull_len = 16;
302 
303 /*
304  * TCP Statistics.
305  *
306  * How TCP statistics work.
307  *
308  * There are two types of statistics invoked by two macros.
309  *
310  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
311  * supposed to be used in non MT-hot paths of the code.
312  *
313  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
314  * supposed to be used for DEBUG purposes and may be used on a hot path.
315  *
316  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
317  * (use "kstat tcp" to get them).
318  *
319  * There is also additional debugging facility that marks tcp_clean_death()
320  * instances and saves them in tcp_t structure. It is triggered by
321  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
322  * tcp_clean_death() calls that counts the number of times each tag was hit. It
323  * is triggered by TCP_CLD_COUNTERS define.
324  *
325  * How to add new counters.
326  *
327  * 1) Add a field in the tcp_stat structure describing your counter.
328  * 2) Add a line in the template in tcp_kstat2_init() with the name
329  *    of the counter.
330  *
331  *    IMPORTANT!! - make sure that both are in sync !!
332  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
333  *
334  * Please avoid using private counters which are not kstat-exported.
335  *
336  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
337  * in tcp_t structure.
338  *
339  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
340  */
341 
342 #ifndef TCP_DEBUG_COUNTER
343 #ifdef DEBUG
344 #define	TCP_DEBUG_COUNTER 1
345 #else
346 #define	TCP_DEBUG_COUNTER 0
347 #endif
348 #endif
349 
350 #define	TCP_CLD_COUNTERS 0
351 
352 #define	TCP_TAG_CLEAN_DEATH 1
353 #define	TCP_MAX_CLEAN_DEATH_TAG 32
354 
355 #ifdef lint
356 static int _lint_dummy_;
357 #endif
358 
359 #if TCP_CLD_COUNTERS
360 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
361 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
362 #elif defined(lint)
363 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
364 #else
365 #define	TCP_CLD_STAT(x)
366 #endif
367 
368 #if TCP_DEBUG_COUNTER
369 #define	TCP_DBGSTAT(tcps, x)	\
370 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
371 #define	TCP_G_DBGSTAT(x)	\
372 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
373 #elif defined(lint)
374 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
375 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
376 #else
377 #define	TCP_DBGSTAT(tcps, x)
378 #define	TCP_G_DBGSTAT(x)
379 #endif
380 
381 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
382 
383 tcp_g_stat_t	tcp_g_statistics;
384 kstat_t		*tcp_g_kstat;
385 
386 /*
387  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
388  * tcp write side.
389  */
390 #define	CALL_IP_WPUT(connp, q, mp) {					\
391 	tcp_stack_t	*tcps;						\
392 									\
393 	tcps = connp->conn_netstack->netstack_tcp;			\
394 	ASSERT(((q)->q_flag & QREADR) == 0);				\
395 	TCP_DBGSTAT(tcps, tcp_ip_output);				\
396 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
397 }
398 
399 /* Macros for timestamp comparisons */
400 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
401 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
402 
403 /*
404  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
405  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
406  * by adding three components: a time component which grows by 1 every 4096
407  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
408  * a per-connection component which grows by 125000 for every new connection;
409  * and an "extra" component that grows by a random amount centered
410  * approximately on 64000.  This causes the the ISS generator to cycle every
411  * 4.89 hours if no TCP connections are made, and faster if connections are
412  * made.
413  *
414  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
415  * components: a time component which grows by 250000 every second; and
416  * a per-connection component which grows by 125000 for every new connections.
417  *
418  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
419  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
420  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
421  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
422  * password.
423  */
424 #define	ISS_INCR	250000
425 #define	ISS_NSEC_SHT	12
426 
427 static sin_t	sin_null;	/* Zero address for quick clears */
428 static sin6_t	sin6_null;	/* Zero address for quick clears */
429 
430 /*
431  * This implementation follows the 4.3BSD interpretation of the urgent
432  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
433  * incompatible changes in protocols like telnet and rlogin.
434  */
435 #define	TCP_OLD_URP_INTERPRETATION	1
436 
437 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
438 	(TCP_IS_DETACHED(tcp) && \
439 	    (!(tcp)->tcp_hard_binding))
440 
441 /*
442  * TCP reassembly macros.  We hide starting and ending sequence numbers in
443  * b_next and b_prev of messages on the reassembly queue.  The messages are
444  * chained using b_cont.  These macros are used in tcp_reass() so we don't
445  * have to see the ugly casts and assignments.
446  */
447 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
448 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
449 					(mblk_t *)(uintptr_t)(u))
450 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
451 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
452 					(mblk_t *)(uintptr_t)(u))
453 
454 /*
455  * Implementation of TCP Timers.
456  * =============================
457  *
458  * INTERFACE:
459  *
460  * There are two basic functions dealing with tcp timers:
461  *
462  *	timeout_id_t	tcp_timeout(connp, func, time)
463  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
464  *	TCP_TIMER_RESTART(tcp, intvl)
465  *
466  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
467  * after 'time' ticks passed. The function called by timeout() must adhere to
468  * the same restrictions as a driver soft interrupt handler - it must not sleep
469  * or call other functions that might sleep. The value returned is the opaque
470  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
471  * cancel the request. The call to tcp_timeout() may fail in which case it
472  * returns zero. This is different from the timeout(9F) function which never
473  * fails.
474  *
475  * The call-back function 'func' always receives 'connp' as its single
476  * argument. It is always executed in the squeue corresponding to the tcp
477  * structure. The tcp structure is guaranteed to be present at the time the
478  * call-back is called.
479  *
480  * NOTE: The call-back function 'func' is never called if tcp is in
481  * 	the TCPS_CLOSED state.
482  *
483  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
484  * request. locks acquired by the call-back routine should not be held across
485  * the call to tcp_timeout_cancel() or a deadlock may result.
486  *
487  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
488  * Otherwise, it returns an integer value greater than or equal to 0. In
489  * particular, if the call-back function is already placed on the squeue, it can
490  * not be canceled.
491  *
492  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
493  * 	within squeue context corresponding to the tcp instance. Since the
494  *	call-back is also called via the same squeue, there are no race
495  *	conditions described in untimeout(9F) manual page since all calls are
496  *	strictly serialized.
497  *
498  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
499  *	stored in tcp_timer_tid and starts a new one using
500  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
501  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
502  *	field.
503  *
504  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
505  *	call-back may still be called, so it is possible tcp_timer() will be
506  *	called several times. This should not be a problem since tcp_timer()
507  *	should always check the tcp instance state.
508  *
509  *
510  * IMPLEMENTATION:
511  *
512  * TCP timers are implemented using three-stage process. The call to
513  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
514  * when the timer expires. The tcp_timer_callback() arranges the call of the
515  * tcp_timer_handler() function via squeue corresponding to the tcp
516  * instance. The tcp_timer_handler() calls actual requested timeout call-back
517  * and passes tcp instance as an argument to it. Information is passed between
518  * stages using the tcp_timer_t structure which contains the connp pointer, the
519  * tcp call-back to call and the timeout id returned by the timeout(9F).
520  *
521  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
522  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
523  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
524  * returns the pointer to this mblk.
525  *
526  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
527  * looks like a normal mblk without actual dblk attached to it.
528  *
529  * To optimize performance each tcp instance holds a small cache of timer
530  * mblocks. In the current implementation it caches up to two timer mblocks per
531  * tcp instance. The cache is preserved over tcp frees and is only freed when
532  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
533  * timer processing happens on a corresponding squeue, the cache manipulation
534  * does not require any locks. Experiments show that majority of timer mblocks
535  * allocations are satisfied from the tcp cache and do not involve kmem calls.
536  *
537  * The tcp_timeout() places a refhold on the connp instance which guarantees
538  * that it will be present at the time the call-back function fires. The
539  * tcp_timer_handler() drops the reference after calling the call-back, so the
540  * call-back function does not need to manipulate the references explicitly.
541  */
542 
543 typedef struct tcp_timer_s {
544 	conn_t	*connp;
545 	void 	(*tcpt_proc)(void *);
546 	callout_id_t   tcpt_tid;
547 } tcp_timer_t;
548 
549 static kmem_cache_t *tcp_timercache;
550 kmem_cache_t	*tcp_sack_info_cache;
551 kmem_cache_t	*tcp_iphc_cache;
552 
553 /*
554  * For scalability, we must not run a timer for every TCP connection
555  * in TIME_WAIT state.  To see why, consider (for time wait interval of
556  * 4 minutes):
557  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
558  *
559  * This list is ordered by time, so you need only delete from the head
560  * until you get to entries which aren't old enough to delete yet.
561  * The list consists of only the detached TIME_WAIT connections.
562  *
563  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
564  * becomes detached TIME_WAIT (either by changing the state and already
565  * being detached or the other way around). This means that the TIME_WAIT
566  * state can be extended (up to doubled) if the connection doesn't become
567  * detached for a long time.
568  *
569  * The list manipulations (including tcp_time_wait_next/prev)
570  * are protected by the tcp_time_wait_lock. The content of the
571  * detached TIME_WAIT connections is protected by the normal perimeters.
572  *
573  * This list is per squeue and squeues are shared across the tcp_stack_t's.
574  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
575  * and conn_netstack.
576  * The tcp_t's that are added to tcp_free_list are disassociated and
577  * have NULL tcp_tcps and conn_netstack pointers.
578  */
579 typedef struct tcp_squeue_priv_s {
580 	kmutex_t	tcp_time_wait_lock;
581 	callout_id_t	tcp_time_wait_tid;
582 	tcp_t		*tcp_time_wait_head;
583 	tcp_t		*tcp_time_wait_tail;
584 	tcp_t		*tcp_free_list;
585 	uint_t		tcp_free_list_cnt;
586 } tcp_squeue_priv_t;
587 
588 /*
589  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
590  * Running it every 5 seconds seems to give the best results.
591  */
592 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
593 
594 /*
595  * To prevent memory hog, limit the number of entries in tcp_free_list
596  * to 1% of available memory / number of cpus
597  */
598 uint_t tcp_free_list_max_cnt = 0;
599 
600 #define	TCP_XMIT_LOWATER	4096
601 #define	TCP_XMIT_HIWATER	49152
602 #define	TCP_RECV_LOWATER	2048
603 #define	TCP_RECV_HIWATER	49152
604 
605 /*
606  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
607  */
608 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
609 
610 #define	TIDUSZ	4096	/* transport interface data unit size */
611 
612 /*
613  * Bind hash list size and has function.  It has to be a power of 2 for
614  * hashing.
615  */
616 #define	TCP_BIND_FANOUT_SIZE	512
617 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
618 /*
619  * Size of listen and acceptor hash list.  It has to be a power of 2 for
620  * hashing.
621  */
622 #define	TCP_FANOUT_SIZE		256
623 
624 #ifdef	_ILP32
625 #define	TCP_ACCEPTOR_HASH(accid)					\
626 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
627 #else
628 #define	TCP_ACCEPTOR_HASH(accid)					\
629 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
630 #endif	/* _ILP32 */
631 
632 #define	IP_ADDR_CACHE_SIZE	2048
633 #define	IP_ADDR_CACHE_HASH(faddr)					\
634 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
635 
636 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
637 #define	TCP_HSP_HASH_SIZE 256
638 
639 #define	TCP_HSP_HASH(addr)					\
640 	(((addr>>24) ^ (addr >>16) ^			\
641 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
642 
643 /*
644  * TCP options struct returned from tcp_parse_options.
645  */
646 typedef struct tcp_opt_s {
647 	uint32_t	tcp_opt_mss;
648 	uint32_t	tcp_opt_wscale;
649 	uint32_t	tcp_opt_ts_val;
650 	uint32_t	tcp_opt_ts_ecr;
651 	tcp_t		*tcp;
652 } tcp_opt_t;
653 
654 /*
655  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
656  */
657 
658 #ifdef _BIG_ENDIAN
659 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
660 	(TCPOPT_TSTAMP << 8) | 10)
661 #else
662 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
663 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
664 #endif
665 
666 /*
667  * Flags returned from tcp_parse_options.
668  */
669 #define	TCP_OPT_MSS_PRESENT	1
670 #define	TCP_OPT_WSCALE_PRESENT	2
671 #define	TCP_OPT_TSTAMP_PRESENT	4
672 #define	TCP_OPT_SACK_OK_PRESENT	8
673 #define	TCP_OPT_SACK_PRESENT	16
674 
675 /* TCP option length */
676 #define	TCPOPT_NOP_LEN		1
677 #define	TCPOPT_MAXSEG_LEN	4
678 #define	TCPOPT_WS_LEN		3
679 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
680 #define	TCPOPT_TSTAMP_LEN	10
681 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
682 #define	TCPOPT_SACK_OK_LEN	2
683 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
684 #define	TCPOPT_REAL_SACK_LEN	4
685 #define	TCPOPT_MAX_SACK_LEN	36
686 #define	TCPOPT_HEADER_LEN	2
687 
688 /* TCP cwnd burst factor. */
689 #define	TCP_CWND_INFINITE	65535
690 #define	TCP_CWND_SS		3
691 #define	TCP_CWND_NORMAL		5
692 
693 /* Maximum TCP initial cwin (start/restart). */
694 #define	TCP_MAX_INIT_CWND	8
695 
696 /*
697  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
698  * either tcp_slow_start_initial or tcp_slow_start_after idle
699  * depending on the caller.  If the upper layer has not used the
700  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
701  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
702  * If the upper layer has changed set the tcp_init_cwnd, just use
703  * it to calculate the tcp_cwnd.
704  */
705 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
706 {									\
707 	if ((tcp)->tcp_init_cwnd == 0) {				\
708 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
709 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
710 	} else {							\
711 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
712 	}								\
713 	tcp->tcp_cwnd_cnt = 0;						\
714 }
715 
716 /* TCP Timer control structure */
717 typedef struct tcpt_s {
718 	pfv_t	tcpt_pfv;	/* The routine we are to call */
719 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
720 } tcpt_t;
721 
722 /* Host Specific Parameter structure */
723 typedef struct tcp_hsp {
724 	struct tcp_hsp	*tcp_hsp_next;
725 	in6_addr_t	tcp_hsp_addr_v6;
726 	in6_addr_t	tcp_hsp_subnet_v6;
727 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
728 	int32_t		tcp_hsp_sendspace;
729 	int32_t		tcp_hsp_recvspace;
730 	int32_t		tcp_hsp_tstamp;
731 } tcp_hsp_t;
732 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
733 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
734 
735 /*
736  * Functions called directly via squeue having a prototype of edesc_t.
737  */
738 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
739 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
740 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
741 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
742 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
743 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
744 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
745 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
746 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
747 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
748 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
749 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
750 
751 
752 /* Prototype for TCP functions */
753 static void	tcp_random_init(void);
754 int		tcp_random(void);
755 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
756 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
757 		    tcp_t *eager);
758 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
759 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
760     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
761     boolean_t user_specified);
762 static void	tcp_closei_local(tcp_t *tcp);
763 static void	tcp_close_detached(tcp_t *tcp);
764 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
765 			mblk_t *idmp, mblk_t **defermp);
766 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
767 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
768 		    in_port_t dstport, uint_t srcid);
769 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
770 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
771 		    uint32_t scope_id);
772 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
773 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
774 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
775 static char	*tcp_display(tcp_t *tcp, char *, char);
776 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
777 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
778 static void	tcp_eager_unlink(tcp_t *tcp);
779 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
780 		    int unixerr);
781 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
782 		    int tlierr, int unixerr);
783 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
784 		    cred_t *cr);
785 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
786 		    char *value, caddr_t cp, cred_t *cr);
787 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
788 		    char *value, caddr_t cp, cred_t *cr);
789 static int	tcp_tpistate(tcp_t *tcp);
790 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
791     int caller_holds_lock);
792 static void	tcp_bind_hash_remove(tcp_t *tcp);
793 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
794 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
795 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
796 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
797 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
798 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
799 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
800 void		tcp_g_q_setup(tcp_stack_t *);
801 void		tcp_g_q_create(tcp_stack_t *);
802 void		tcp_g_q_destroy(tcp_stack_t *);
803 static int	tcp_header_init_ipv4(tcp_t *tcp);
804 static int	tcp_header_init_ipv6(tcp_t *tcp);
805 int		tcp_init(tcp_t *tcp, queue_t *q);
806 static int	tcp_init_values(tcp_t *tcp);
807 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
808 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
809 		    t_scalar_t addr_length);
810 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
811 static void	tcp_ip_notify(tcp_t *tcp);
812 static mblk_t	*tcp_ire_mp(mblk_t *mp);
813 static void	tcp_iss_init(tcp_t *tcp);
814 static void	tcp_keepalive_killer(void *arg);
815 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
816 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
817 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
818 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
819 static boolean_t tcp_allow_connopt_set(int level, int name);
820 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
821 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
822 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
823 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
824 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
825 		    mblk_t *mblk);
826 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
827 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
828 		    uchar_t *ptr, uint_t len);
829 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
830 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
831     tcp_stack_t *);
832 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
833 		    caddr_t cp, cred_t *cr);
834 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
835 		    caddr_t cp, cred_t *cr);
836 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
837 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
838 		    caddr_t cp, cred_t *cr);
839 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
840 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
841 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
842 static void	tcp_reinit(tcp_t *tcp);
843 static void	tcp_reinit_values(tcp_t *tcp);
844 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
845 		    tcp_t *thisstream, cred_t *cr);
846 
847 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
848 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
849 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
850 static void	tcp_ss_rexmit(tcp_t *tcp);
851 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
852 static void	tcp_process_options(tcp_t *, tcph_t *);
853 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
854 static void	tcp_rsrv(queue_t *q);
855 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
856 static int	tcp_snmp_state(tcp_t *tcp);
857 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
858 		    cred_t *cr);
859 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
860 		    cred_t *cr);
861 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
862 		    cred_t *cr);
863 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
864 		    cred_t *cr);
865 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
866 		    cred_t *cr);
867 static void	tcp_timer(void *arg);
868 static void	tcp_timer_callback(void *);
869 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
870     boolean_t random);
871 static in_port_t tcp_get_next_priv_port(const tcp_t *);
872 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
873 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
874 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
875 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
876 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
877 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
878 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
879 		    const int num_sack_blk, int *usable, uint_t *snxt,
880 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
881 		    const int mdt_thres);
882 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
883 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
884 		    const int num_sack_blk, int *usable, uint_t *snxt,
885 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
886 		    const int mdt_thres);
887 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
888 		    int num_sack_blk);
889 static void	tcp_wsrv(queue_t *q);
890 static int	tcp_xmit_end(tcp_t *tcp);
891 static void	tcp_ack_timer(void *arg);
892 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
893 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
894 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
895 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
896 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
897 		    uint32_t ack, int ctl);
898 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
899 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
900 static int	setmaxps(queue_t *q, int maxpsz);
901 static void	tcp_set_rto(tcp_t *, time_t);
902 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
903 		    boolean_t, boolean_t);
904 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
905 		    boolean_t ipsec_mctl);
906 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
907 		    char *opt, int optlen);
908 static int	tcp_build_hdrs(queue_t *, tcp_t *);
909 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
910 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
911 		    tcph_t *tcph);
912 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
913 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
914 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
915 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
916 		    const boolean_t, const uint32_t, const uint32_t,
917 		    const uint32_t, const uint32_t, tcp_stack_t *);
918 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
919 		    const uint_t, const uint_t, boolean_t *);
920 static mblk_t	*tcp_lso_info_mp(mblk_t *);
921 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
922 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
923 extern mblk_t	*tcp_timermp_alloc(int);
924 extern void	tcp_timermp_free(tcp_t *);
925 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
926 static void	tcp_stop_lingering(tcp_t *tcp);
927 static void	tcp_close_linger_timeout(void *arg);
928 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
929 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
930 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
931 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
932 static void	tcp_g_kstat_fini(kstat_t *);
933 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
934 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
935 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
936 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
937 static int	tcp_kstat_update(kstat_t *kp, int rw);
938 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
939 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
940 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
941 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
942 			tcph_t *tcph, mblk_t *idmp);
943 static squeue_func_t tcp_squeue_switch(int);
944 
945 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
946 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
947 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
948 static int	tcp_close(queue_t *, int);
949 static int	tcpclose_accept(queue_t *);
950 
951 static void	tcp_squeue_add(squeue_t *);
952 static boolean_t tcp_zcopy_check(tcp_t *);
953 static void	tcp_zcopy_notify(tcp_t *);
954 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
955 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
956 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
957 
958 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
959 
960 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
961 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
962 
963 /*
964  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
965  *
966  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
967  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
968  * (defined in tcp.h) needs to be filled in and passed into the kernel
969  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
970  * structure contains the four-tuple of a TCP connection and a range of TCP
971  * states (specified by ac_start and ac_end). The use of wildcard addresses
972  * and ports is allowed. Connections with a matching four tuple and a state
973  * within the specified range will be aborted. The valid states for the
974  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
975  * inclusive.
976  *
977  * An application which has its connection aborted by this ioctl will receive
978  * an error that is dependent on the connection state at the time of the abort.
979  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
980  * though a RST packet has been received.  If the connection state is equal to
981  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
982  * and all resources associated with the connection will be freed.
983  */
984 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
985 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
986 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
987 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
988 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
989 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
990     boolean_t, tcp_stack_t *);
991 
992 static struct module_info tcp_rinfo =  {
993 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
994 };
995 
996 static struct module_info tcp_winfo =  {
997 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
998 };
999 
1000 /*
1001  * Entry points for TCP as a device. The normal case which supports
1002  * the TCP functionality.
1003  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
1004  */
1005 struct qinit tcp_rinitv4 = {
1006 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, NULL, &tcp_rinfo
1007 };
1008 
1009 struct qinit tcp_rinitv6 = {
1010 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_close, NULL, &tcp_rinfo
1011 };
1012 
1013 struct qinit tcp_winit = {
1014 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1015 };
1016 
1017 /* Initial entry point for TCP in socket mode. */
1018 struct qinit tcp_sock_winit = {
1019 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1020 };
1021 
1022 /*
1023  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1024  * an accept. Avoid allocating data structures since eager has already
1025  * been created.
1026  */
1027 struct qinit tcp_acceptor_rinit = {
1028 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1029 };
1030 
1031 struct qinit tcp_acceptor_winit = {
1032 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1033 };
1034 
1035 /*
1036  * Entry points for TCP loopback (read side only)
1037  * The open routine is only used for reopens, thus no need to
1038  * have a separate one for tcp_openv6.
1039  */
1040 struct qinit tcp_loopback_rinit = {
1041 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, (pfi_t)0,
1042 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1043 };
1044 
1045 /* For AF_INET aka /dev/tcp */
1046 struct streamtab tcpinfov4 = {
1047 	&tcp_rinitv4, &tcp_winit
1048 };
1049 
1050 /* For AF_INET6 aka /dev/tcp6 */
1051 struct streamtab tcpinfov6 = {
1052 	&tcp_rinitv6, &tcp_winit
1053 };
1054 
1055 /*
1056  * Have to ensure that tcp_g_q_close is not done by an
1057  * interrupt thread.
1058  */
1059 static taskq_t *tcp_taskq;
1060 
1061 /* Setable only in /etc/system. Move to ndd? */
1062 boolean_t tcp_icmp_source_quench = B_FALSE;
1063 
1064 /*
1065  * Following assumes TPI alignment requirements stay along 32 bit
1066  * boundaries
1067  */
1068 #define	ROUNDUP32(x) \
1069 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1070 
1071 /* Template for response to info request. */
1072 static struct T_info_ack tcp_g_t_info_ack = {
1073 	T_INFO_ACK,		/* PRIM_type */
1074 	0,			/* TSDU_size */
1075 	T_INFINITE,		/* ETSDU_size */
1076 	T_INVALID,		/* CDATA_size */
1077 	T_INVALID,		/* DDATA_size */
1078 	sizeof (sin_t),		/* ADDR_size */
1079 	0,			/* OPT_size - not initialized here */
1080 	TIDUSZ,			/* TIDU_size */
1081 	T_COTS_ORD,		/* SERV_type */
1082 	TCPS_IDLE,		/* CURRENT_state */
1083 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1084 };
1085 
1086 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1087 	T_INFO_ACK,		/* PRIM_type */
1088 	0,			/* TSDU_size */
1089 	T_INFINITE,		/* ETSDU_size */
1090 	T_INVALID,		/* CDATA_size */
1091 	T_INVALID,		/* DDATA_size */
1092 	sizeof (sin6_t),	/* ADDR_size */
1093 	0,			/* OPT_size - not initialized here */
1094 	TIDUSZ,		/* TIDU_size */
1095 	T_COTS_ORD,		/* SERV_type */
1096 	TCPS_IDLE,		/* CURRENT_state */
1097 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1098 };
1099 
1100 #define	MS	1L
1101 #define	SECONDS	(1000 * MS)
1102 #define	MINUTES	(60 * SECONDS)
1103 #define	HOURS	(60 * MINUTES)
1104 #define	DAYS	(24 * HOURS)
1105 
1106 #define	PARAM_MAX (~(uint32_t)0)
1107 
1108 /* Max size IP datagram is 64k - 1 */
1109 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1110 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1111 /* Max of the above */
1112 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1113 
1114 /* Largest TCP port number */
1115 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1116 
1117 /*
1118  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1119  * layer header.  It has to be a multiple of 4.
1120  */
1121 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1122 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1123 
1124 /*
1125  * All of these are alterable, within the min/max values given, at run time.
1126  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1127  * per the TCP spec.
1128  */
1129 /* BEGIN CSTYLED */
1130 static tcpparam_t	lcl_tcp_param_arr[] = {
1131  /*min		max		value		name */
1132  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1133  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1134  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1135  { 1,		1024,		1,		"tcp_conn_req_min" },
1136  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1137  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1138  { 0,		10,		0,		"tcp_debug" },
1139  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1140  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1141  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1142  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1143  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1144  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1145  { 1,		255,		64,		"tcp_ipv4_ttl"},
1146  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1147  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1148  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1149  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1150  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1151  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1152  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1153  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1154  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1155  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1156  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1157  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1158  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1159  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1160  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1161  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1162  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1163  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1164  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1165  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1166  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1167  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1168  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1169 /*
1170  * Question:  What default value should I set for tcp_strong_iss?
1171  */
1172  { 0,		2,		1,		"tcp_strong_iss"},
1173  { 0,		65536,		20,		"tcp_rtt_updates"},
1174  { 0,		1,		1,		"tcp_wscale_always"},
1175  { 0,		1,		0,		"tcp_tstamp_always"},
1176  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1177  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1178  { 0,		16,		2,		"tcp_deferred_acks_max"},
1179  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1180  { 1,		4,		4,		"tcp_slow_start_initial"},
1181  { 0,		2,		2,		"tcp_sack_permitted"},
1182  { 0,		1,		1,		"tcp_compression_enabled"},
1183  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1184  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1185  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1186  { 0,		1,		0,		"tcp_rev_src_routes"},
1187  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1188  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1189  { 0,		16,		8,		"tcp_local_dacks_max"},
1190  { 0,		2,		1,		"tcp_ecn_permitted"},
1191  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1192  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1193  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1194  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1195  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1196 };
1197 /* END CSTYLED */
1198 
1199 /*
1200  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1201  * each header fragment in the header buffer.  Each parameter value has
1202  * to be a multiple of 4 (32-bit aligned).
1203  */
1204 static tcpparam_t lcl_tcp_mdt_head_param =
1205 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1206 static tcpparam_t lcl_tcp_mdt_tail_param =
1207 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1208 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1209 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1210 
1211 /*
1212  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1213  * the maximum number of payload buffers associated per Multidata.
1214  */
1215 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1216 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1217 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1218 
1219 /* Round up the value to the nearest mss. */
1220 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1221 
1222 /*
1223  * Set ECN capable transport (ECT) code point in IP header.
1224  *
1225  * Note that there are 2 ECT code points '01' and '10', which are called
1226  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1227  * point ECT(0) for TCP as described in RFC 2481.
1228  */
1229 #define	SET_ECT(tcp, iph) \
1230 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1231 		/* We need to clear the code point first. */ \
1232 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1233 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1234 	} else { \
1235 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1236 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1237 	}
1238 
1239 /*
1240  * The format argument to pass to tcp_display().
1241  * DISP_PORT_ONLY means that the returned string has only port info.
1242  * DISP_ADDR_AND_PORT means that the returned string also contains the
1243  * remote and local IP address.
1244  */
1245 #define	DISP_PORT_ONLY		1
1246 #define	DISP_ADDR_AND_PORT	2
1247 
1248 #define	NDD_TOO_QUICK_MSG \
1249 	"ndd get info rate too high for non-privileged users, try again " \
1250 	"later.\n"
1251 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1252 
1253 #define	IS_VMLOANED_MBLK(mp) \
1254 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1255 
1256 
1257 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1258 boolean_t tcp_mdt_chain = B_TRUE;
1259 
1260 /*
1261  * MDT threshold in the form of effective send MSS multiplier; we take
1262  * the MDT path if the amount of unsent data exceeds the threshold value
1263  * (default threshold is 1*SMSS).
1264  */
1265 uint_t tcp_mdt_smss_threshold = 1;
1266 
1267 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1268 
1269 /*
1270  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1271  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1272  * determined dynamically during tcp_adapt_ire(), which is the default.
1273  */
1274 boolean_t tcp_static_maxpsz = B_FALSE;
1275 
1276 /* Setable in /etc/system */
1277 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1278 uint32_t tcp_random_anon_port = 1;
1279 
1280 /*
1281  * To reach to an eager in Q0 which can be dropped due to an incoming
1282  * new SYN request when Q0 is full, a new doubly linked list is
1283  * introduced. This list allows to select an eager from Q0 in O(1) time.
1284  * This is needed to avoid spending too much time walking through the
1285  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1286  * this new list has to be a member of Q0.
1287  * This list is headed by listener's tcp_t. When the list is empty,
1288  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1289  * of listener's tcp_t point to listener's tcp_t itself.
1290  *
1291  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1292  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1293  * These macros do not affect the eager's membership to Q0.
1294  */
1295 
1296 
1297 #define	MAKE_DROPPABLE(listener, eager)					\
1298 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1299 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1300 		    = (eager);						\
1301 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1302 		(eager)->tcp_eager_next_drop_q0 =			\
1303 		    (listener)->tcp_eager_next_drop_q0;			\
1304 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1305 	}
1306 
1307 #define	MAKE_UNDROPPABLE(eager)						\
1308 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1309 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1310 		    = (eager)->tcp_eager_prev_drop_q0;			\
1311 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1312 		    = (eager)->tcp_eager_next_drop_q0;			\
1313 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1314 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1315 	}
1316 
1317 /*
1318  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1319  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1320  * data, TCP will not respond with an ACK.  RFC 793 requires that
1321  * TCP responds with an ACK for such a bogus ACK.  By not following
1322  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1323  * an attacker successfully spoofs an acceptable segment to our
1324  * peer; or when our peer is "confused."
1325  */
1326 uint32_t tcp_drop_ack_unsent_cnt = 10;
1327 
1328 /*
1329  * Hook functions to enable cluster networking
1330  * On non-clustered systems these vectors must always be NULL.
1331  */
1332 
1333 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1334 			    uint8_t *laddrp, in_port_t lport) = NULL;
1335 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1336 			    uint8_t *laddrp, in_port_t lport) = NULL;
1337 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1338 			    uint8_t *laddrp, in_port_t lport,
1339 			    uint8_t *faddrp, in_port_t fport) = NULL;
1340 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1341 			    uint8_t *laddrp, in_port_t lport,
1342 			    uint8_t *faddrp, in_port_t fport) = NULL;
1343 
1344 /*
1345  * The following are defined in ip.c
1346  */
1347 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1348 				uint8_t *laddrp);
1349 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1350 				uint8_t *laddrp, uint8_t *faddrp);
1351 
1352 #define	CL_INET_CONNECT(tcp)		{			\
1353 	if (cl_inet_connect != NULL) {				\
1354 		/*						\
1355 		 * Running in cluster mode - register active connection	\
1356 		 * information						\
1357 		 */							\
1358 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1359 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1360 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1361 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1362 				    (in_port_t)(tcp)->tcp_lport,	\
1363 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1364 				    (in_port_t)(tcp)->tcp_fport);	\
1365 			}						\
1366 		} else {						\
1367 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1368 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1369 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1370 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1371 				    (in_port_t)(tcp)->tcp_lport,	\
1372 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1373 				    (in_port_t)(tcp)->tcp_fport);	\
1374 			}						\
1375 		}							\
1376 	}								\
1377 }
1378 
1379 #define	CL_INET_DISCONNECT(tcp)	{				\
1380 	if (cl_inet_disconnect != NULL) {				\
1381 		/*							\
1382 		 * Running in cluster mode - deregister active		\
1383 		 * connection information				\
1384 		 */							\
1385 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1386 			if ((tcp)->tcp_ip_src != 0) {			\
1387 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1388 				    AF_INET,				\
1389 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1390 				    (in_port_t)(tcp)->tcp_lport,	\
1391 				    (uint8_t *)				\
1392 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1393 				    (in_port_t)(tcp)->tcp_fport);	\
1394 			}						\
1395 		} else {						\
1396 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1397 			    &(tcp)->tcp_ip_src_v6)) {			\
1398 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1399 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1400 				    (in_port_t)(tcp)->tcp_lport,	\
1401 				    (uint8_t *)				\
1402 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1403 				    (in_port_t)(tcp)->tcp_fport);	\
1404 			}						\
1405 		}							\
1406 	}								\
1407 }
1408 
1409 /*
1410  * Cluster networking hook for traversing current connection list.
1411  * This routine is used to extract the current list of live connections
1412  * which must continue to to be dispatched to this node.
1413  */
1414 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1415 
1416 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1417     void *arg, tcp_stack_t *tcps);
1418 
1419 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1420 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1421 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1422 	    ip6_t *, ip6h, int, 0);
1423 
1424 /*
1425  * Figure out the value of window scale opton.  Note that the rwnd is
1426  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1427  * We cannot find the scale value and then do a round up of tcp_rwnd
1428  * because the scale value may not be correct after that.
1429  *
1430  * Set the compiler flag to make this function inline.
1431  */
1432 static void
1433 tcp_set_ws_value(tcp_t *tcp)
1434 {
1435 	int i;
1436 	uint32_t rwnd = tcp->tcp_rwnd;
1437 
1438 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1439 	    i++, rwnd >>= 1)
1440 		;
1441 	tcp->tcp_rcv_ws = i;
1442 }
1443 
1444 /*
1445  * Remove a connection from the list of detached TIME_WAIT connections.
1446  * It returns B_FALSE if it can't remove the connection from the list
1447  * as the connection has already been removed from the list due to an
1448  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1449  */
1450 static boolean_t
1451 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1452 {
1453 	boolean_t	locked = B_FALSE;
1454 
1455 	if (tcp_time_wait == NULL) {
1456 		tcp_time_wait = *((tcp_squeue_priv_t **)
1457 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1458 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1459 		locked = B_TRUE;
1460 	} else {
1461 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1462 	}
1463 
1464 	if (tcp->tcp_time_wait_expire == 0) {
1465 		ASSERT(tcp->tcp_time_wait_next == NULL);
1466 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1467 		if (locked)
1468 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1469 		return (B_FALSE);
1470 	}
1471 	ASSERT(TCP_IS_DETACHED(tcp));
1472 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1473 
1474 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1475 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1476 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1477 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1478 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1479 			    NULL;
1480 		} else {
1481 			tcp_time_wait->tcp_time_wait_tail = NULL;
1482 		}
1483 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1484 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1485 		ASSERT(tcp->tcp_time_wait_next == NULL);
1486 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1487 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1488 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1489 	} else {
1490 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1491 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1492 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1493 		    tcp->tcp_time_wait_next;
1494 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1495 		    tcp->tcp_time_wait_prev;
1496 	}
1497 	tcp->tcp_time_wait_next = NULL;
1498 	tcp->tcp_time_wait_prev = NULL;
1499 	tcp->tcp_time_wait_expire = 0;
1500 
1501 	if (locked)
1502 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1503 	return (B_TRUE);
1504 }
1505 
1506 /*
1507  * Add a connection to the list of detached TIME_WAIT connections
1508  * and set its time to expire.
1509  */
1510 static void
1511 tcp_time_wait_append(tcp_t *tcp)
1512 {
1513 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1514 	tcp_squeue_priv_t *tcp_time_wait =
1515 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1516 	    SQPRIVATE_TCP));
1517 
1518 	tcp_timers_stop(tcp);
1519 
1520 	/* Freed above */
1521 	ASSERT(tcp->tcp_timer_tid == 0);
1522 	ASSERT(tcp->tcp_ack_tid == 0);
1523 
1524 	/* must have happened at the time of detaching the tcp */
1525 	ASSERT(tcp->tcp_ptpahn == NULL);
1526 	ASSERT(tcp->tcp_flow_stopped == 0);
1527 	ASSERT(tcp->tcp_time_wait_next == NULL);
1528 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1529 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1530 	ASSERT(tcp->tcp_listener == NULL);
1531 
1532 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1533 	/*
1534 	 * The value computed below in tcp->tcp_time_wait_expire may
1535 	 * appear negative or wrap around. That is ok since our
1536 	 * interest is only in the difference between the current lbolt
1537 	 * value and tcp->tcp_time_wait_expire. But the value should not
1538 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1539 	 * The corresponding comparison in tcp_time_wait_collector() uses
1540 	 * modular arithmetic.
1541 	 */
1542 	tcp->tcp_time_wait_expire +=
1543 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1544 	if (tcp->tcp_time_wait_expire == 0)
1545 		tcp->tcp_time_wait_expire = 1;
1546 
1547 	ASSERT(TCP_IS_DETACHED(tcp));
1548 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1549 	ASSERT(tcp->tcp_time_wait_next == NULL);
1550 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1551 	TCP_DBGSTAT(tcps, tcp_time_wait);
1552 
1553 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1554 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1555 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1556 		tcp_time_wait->tcp_time_wait_head = tcp;
1557 	} else {
1558 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1559 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1560 		    TCPS_TIME_WAIT);
1561 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1562 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1563 	}
1564 	tcp_time_wait->tcp_time_wait_tail = tcp;
1565 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1566 }
1567 
1568 /* ARGSUSED */
1569 void
1570 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1571 {
1572 	conn_t	*connp = (conn_t *)arg;
1573 	tcp_t	*tcp = connp->conn_tcp;
1574 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1575 
1576 	ASSERT(tcp != NULL);
1577 	if (tcp->tcp_state == TCPS_CLOSED) {
1578 		return;
1579 	}
1580 
1581 	ASSERT((tcp->tcp_family == AF_INET &&
1582 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1583 	    (tcp->tcp_family == AF_INET6 &&
1584 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1585 	    tcp->tcp_ipversion == IPV6_VERSION)));
1586 	ASSERT(!tcp->tcp_listener);
1587 
1588 	TCP_STAT(tcps, tcp_time_wait_reap);
1589 	ASSERT(TCP_IS_DETACHED(tcp));
1590 
1591 	/*
1592 	 * Because they have no upstream client to rebind or tcp_close()
1593 	 * them later, we axe the connection here and now.
1594 	 */
1595 	tcp_close_detached(tcp);
1596 }
1597 
1598 /*
1599  * Remove cached/latched IPsec references.
1600  */
1601 void
1602 tcp_ipsec_cleanup(tcp_t *tcp)
1603 {
1604 	conn_t		*connp = tcp->tcp_connp;
1605 
1606 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1607 
1608 	if (connp->conn_latch != NULL) {
1609 		IPLATCH_REFRELE(connp->conn_latch,
1610 		    connp->conn_netstack);
1611 		connp->conn_latch = NULL;
1612 	}
1613 	if (connp->conn_policy != NULL) {
1614 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1615 		connp->conn_policy = NULL;
1616 	}
1617 }
1618 
1619 /*
1620  * Cleaup before placing on free list.
1621  * Disassociate from the netstack/tcp_stack_t since the freelist
1622  * is per squeue and not per netstack.
1623  */
1624 void
1625 tcp_cleanup(tcp_t *tcp)
1626 {
1627 	mblk_t		*mp;
1628 	char		*tcp_iphc;
1629 	int		tcp_iphc_len;
1630 	int		tcp_hdr_grown;
1631 	tcp_sack_info_t	*tcp_sack_info;
1632 	conn_t		*connp = tcp->tcp_connp;
1633 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1634 	netstack_t	*ns = tcps->tcps_netstack;
1635 	mblk_t		*tcp_rsrv_mp;
1636 
1637 	tcp_bind_hash_remove(tcp);
1638 
1639 	/* Cleanup that which needs the netstack first */
1640 	tcp_ipsec_cleanup(tcp);
1641 
1642 	tcp_free(tcp);
1643 
1644 	/* Release any SSL context */
1645 	if (tcp->tcp_kssl_ent != NULL) {
1646 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1647 		tcp->tcp_kssl_ent = NULL;
1648 	}
1649 
1650 	if (tcp->tcp_kssl_ctx != NULL) {
1651 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1652 		tcp->tcp_kssl_ctx = NULL;
1653 	}
1654 	tcp->tcp_kssl_pending = B_FALSE;
1655 
1656 	conn_delete_ire(connp, NULL);
1657 
1658 	/*
1659 	 * Since we will bzero the entire structure, we need to
1660 	 * remove it and reinsert it in global hash list. We
1661 	 * know the walkers can't get to this conn because we
1662 	 * had set CONDEMNED flag earlier and checked reference
1663 	 * under conn_lock so walker won't pick it and when we
1664 	 * go the ipcl_globalhash_remove() below, no walker
1665 	 * can get to it.
1666 	 */
1667 	ipcl_globalhash_remove(connp);
1668 
1669 	/*
1670 	 * Now it is safe to decrement the reference counts.
1671 	 * This might be the last reference on the netstack and TCPS
1672 	 * in which case it will cause the tcp_g_q_close and
1673 	 * the freeing of the IP Instance.
1674 	 */
1675 	connp->conn_netstack = NULL;
1676 	netstack_rele(ns);
1677 	ASSERT(tcps != NULL);
1678 	tcp->tcp_tcps = NULL;
1679 	TCPS_REFRELE(tcps);
1680 
1681 	/* Save some state */
1682 	mp = tcp->tcp_timercache;
1683 
1684 	tcp_sack_info = tcp->tcp_sack_info;
1685 	tcp_iphc = tcp->tcp_iphc;
1686 	tcp_iphc_len = tcp->tcp_iphc_len;
1687 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1688 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1689 
1690 	if (connp->conn_cred != NULL) {
1691 		crfree(connp->conn_cred);
1692 		connp->conn_cred = NULL;
1693 	}
1694 	if (connp->conn_peercred != NULL) {
1695 		crfree(connp->conn_peercred);
1696 		connp->conn_peercred = NULL;
1697 	}
1698 	ipcl_conn_cleanup(connp);
1699 	connp->conn_flags = IPCL_TCPCONN;
1700 	bzero(tcp, sizeof (tcp_t));
1701 
1702 	/* restore the state */
1703 	tcp->tcp_timercache = mp;
1704 
1705 	tcp->tcp_sack_info = tcp_sack_info;
1706 	tcp->tcp_iphc = tcp_iphc;
1707 	tcp->tcp_iphc_len = tcp_iphc_len;
1708 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1709 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1710 
1711 	tcp->tcp_connp = connp;
1712 
1713 	ASSERT(connp->conn_tcp == tcp);
1714 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1715 	connp->conn_state_flags = CONN_INCIPIENT;
1716 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1717 	ASSERT(connp->conn_ref == 1);
1718 }
1719 
1720 /*
1721  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1722  * is done forwards from the head.
1723  * This walks all stack instances since
1724  * tcp_time_wait remains global across all stacks.
1725  */
1726 /* ARGSUSED */
1727 void
1728 tcp_time_wait_collector(void *arg)
1729 {
1730 	tcp_t *tcp;
1731 	clock_t now;
1732 	mblk_t *mp;
1733 	conn_t *connp;
1734 	kmutex_t *lock;
1735 	boolean_t removed;
1736 
1737 	squeue_t *sqp = (squeue_t *)arg;
1738 	tcp_squeue_priv_t *tcp_time_wait =
1739 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1740 
1741 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1742 	tcp_time_wait->tcp_time_wait_tid = 0;
1743 
1744 	if (tcp_time_wait->tcp_free_list != NULL &&
1745 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1746 		TCP_G_STAT(tcp_freelist_cleanup);
1747 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1748 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1749 			tcp->tcp_time_wait_next = NULL;
1750 			tcp_time_wait->tcp_free_list_cnt--;
1751 			ASSERT(tcp->tcp_tcps == NULL);
1752 			CONN_DEC_REF(tcp->tcp_connp);
1753 		}
1754 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1755 	}
1756 
1757 	/*
1758 	 * In order to reap time waits reliably, we should use a
1759 	 * source of time that is not adjustable by the user -- hence
1760 	 * the call to ddi_get_lbolt().
1761 	 */
1762 	now = ddi_get_lbolt();
1763 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1764 		/*
1765 		 * Compare times using modular arithmetic, since
1766 		 * lbolt can wrapover.
1767 		 */
1768 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1769 			break;
1770 		}
1771 
1772 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1773 		ASSERT(removed);
1774 
1775 		connp = tcp->tcp_connp;
1776 		ASSERT(connp->conn_fanout != NULL);
1777 		lock = &connp->conn_fanout->connf_lock;
1778 		/*
1779 		 * This is essentially a TW reclaim fast path optimization for
1780 		 * performance where the timewait collector checks under the
1781 		 * fanout lock (so that no one else can get access to the
1782 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1783 		 * the classifier hash list. If ref count is indeed 2, we can
1784 		 * just remove the conn under the fanout lock and avoid
1785 		 * cleaning up the conn under the squeue, provided that
1786 		 * clustering callbacks are not enabled. If clustering is
1787 		 * enabled, we need to make the clustering callback before
1788 		 * setting the CONDEMNED flag and after dropping all locks and
1789 		 * so we forego this optimization and fall back to the slow
1790 		 * path. Also please see the comments in tcp_closei_local
1791 		 * regarding the refcnt logic.
1792 		 *
1793 		 * Since we are holding the tcp_time_wait_lock, its better
1794 		 * not to block on the fanout_lock because other connections
1795 		 * can't add themselves to time_wait list. So we do a
1796 		 * tryenter instead of mutex_enter.
1797 		 */
1798 		if (mutex_tryenter(lock)) {
1799 			mutex_enter(&connp->conn_lock);
1800 			if ((connp->conn_ref == 2) &&
1801 			    (cl_inet_disconnect == NULL)) {
1802 				ipcl_hash_remove_locked(connp,
1803 				    connp->conn_fanout);
1804 				/*
1805 				 * Set the CONDEMNED flag now itself so that
1806 				 * the refcnt cannot increase due to any
1807 				 * walker. But we have still not cleaned up
1808 				 * conn_ire_cache. This is still ok since
1809 				 * we are going to clean it up in tcp_cleanup
1810 				 * immediately and any interface unplumb
1811 				 * thread will wait till the ire is blown away
1812 				 */
1813 				connp->conn_state_flags |= CONN_CONDEMNED;
1814 				mutex_exit(lock);
1815 				mutex_exit(&connp->conn_lock);
1816 				if (tcp_time_wait->tcp_free_list_cnt <
1817 				    tcp_free_list_max_cnt) {
1818 					/* Add to head of tcp_free_list */
1819 					mutex_exit(
1820 					    &tcp_time_wait->tcp_time_wait_lock);
1821 					tcp_cleanup(tcp);
1822 					ASSERT(connp->conn_latch == NULL);
1823 					ASSERT(connp->conn_policy == NULL);
1824 					ASSERT(tcp->tcp_tcps == NULL);
1825 					ASSERT(connp->conn_netstack == NULL);
1826 
1827 					mutex_enter(
1828 					    &tcp_time_wait->tcp_time_wait_lock);
1829 					tcp->tcp_time_wait_next =
1830 					    tcp_time_wait->tcp_free_list;
1831 					tcp_time_wait->tcp_free_list = tcp;
1832 					tcp_time_wait->tcp_free_list_cnt++;
1833 					continue;
1834 				} else {
1835 					/* Do not add to tcp_free_list */
1836 					mutex_exit(
1837 					    &tcp_time_wait->tcp_time_wait_lock);
1838 					tcp_bind_hash_remove(tcp);
1839 					conn_delete_ire(tcp->tcp_connp, NULL);
1840 					tcp_ipsec_cleanup(tcp);
1841 					CONN_DEC_REF(tcp->tcp_connp);
1842 				}
1843 			} else {
1844 				CONN_INC_REF_LOCKED(connp);
1845 				mutex_exit(lock);
1846 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1847 				mutex_exit(&connp->conn_lock);
1848 				/*
1849 				 * We can reuse the closemp here since conn has
1850 				 * detached (otherwise we wouldn't even be in
1851 				 * time_wait list). tcp_closemp_used can safely
1852 				 * be changed without taking a lock as no other
1853 				 * thread can concurrently access it at this
1854 				 * point in the connection lifecycle.
1855 				 */
1856 
1857 				if (tcp->tcp_closemp.b_prev == NULL)
1858 					tcp->tcp_closemp_used = B_TRUE;
1859 				else
1860 					cmn_err(CE_PANIC,
1861 					    "tcp_timewait_collector: "
1862 					    "concurrent use of tcp_closemp: "
1863 					    "connp %p tcp %p\n", (void *)connp,
1864 					    (void *)tcp);
1865 
1866 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1867 				mp = &tcp->tcp_closemp;
1868 				squeue_fill(connp->conn_sqp, mp,
1869 				    tcp_timewait_output, connp,
1870 				    SQTAG_TCP_TIMEWAIT);
1871 			}
1872 		} else {
1873 			mutex_enter(&connp->conn_lock);
1874 			CONN_INC_REF_LOCKED(connp);
1875 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1876 			mutex_exit(&connp->conn_lock);
1877 			/*
1878 			 * We can reuse the closemp here since conn has
1879 			 * detached (otherwise we wouldn't even be in
1880 			 * time_wait list). tcp_closemp_used can safely
1881 			 * be changed without taking a lock as no other
1882 			 * thread can concurrently access it at this
1883 			 * point in the connection lifecycle.
1884 			 */
1885 
1886 			if (tcp->tcp_closemp.b_prev == NULL)
1887 				tcp->tcp_closemp_used = B_TRUE;
1888 			else
1889 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1890 				    "concurrent use of tcp_closemp: "
1891 				    "connp %p tcp %p\n", (void *)connp,
1892 				    (void *)tcp);
1893 
1894 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1895 			mp = &tcp->tcp_closemp;
1896 			squeue_fill(connp->conn_sqp, mp,
1897 			    tcp_timewait_output, connp, 0);
1898 		}
1899 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1900 	}
1901 
1902 	if (tcp_time_wait->tcp_free_list != NULL)
1903 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1904 
1905 	tcp_time_wait->tcp_time_wait_tid =
1906 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1907 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1908 	    CALLOUT_FLAG_ROUNDUP);
1909 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1910 }
1911 /*
1912  * Reply to a clients T_CONN_RES TPI message. This function
1913  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1914  * on the acceptor STREAM and processed in tcp_wput_accept().
1915  * Read the block comment on top of tcp_conn_request().
1916  */
1917 static void
1918 tcp_accept(tcp_t *listener, mblk_t *mp)
1919 {
1920 	tcp_t	*acceptor;
1921 	tcp_t	*eager;
1922 	tcp_t   *tcp;
1923 	struct T_conn_res	*tcr;
1924 	t_uscalar_t	acceptor_id;
1925 	t_scalar_t	seqnum;
1926 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1927 	mblk_t	*ok_mp;
1928 	mblk_t	*mp1;
1929 	tcp_stack_t	*tcps = listener->tcp_tcps;
1930 
1931 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1932 		tcp_err_ack(listener, mp, TPROTO, 0);
1933 		return;
1934 	}
1935 	tcr = (struct T_conn_res *)mp->b_rptr;
1936 
1937 	/*
1938 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1939 	 * read side queue of the streams device underneath us i.e. the
1940 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1941 	 * look it up in the queue_hash.  Under LP64 it sends down the
1942 	 * minor_t of the accepting endpoint.
1943 	 *
1944 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1945 	 * fanout hash lock is held.
1946 	 * This prevents any thread from entering the acceptor queue from
1947 	 * below (since it has not been hard bound yet i.e. any inbound
1948 	 * packets will arrive on the listener or default tcp queue and
1949 	 * go through tcp_lookup).
1950 	 * The CONN_INC_REF will prevent the acceptor from closing.
1951 	 *
1952 	 * XXX It is still possible for a tli application to send down data
1953 	 * on the accepting stream while another thread calls t_accept.
1954 	 * This should not be a problem for well-behaved applications since
1955 	 * the T_OK_ACK is sent after the queue swapping is completed.
1956 	 *
1957 	 * If the accepting fd is the same as the listening fd, avoid
1958 	 * queue hash lookup since that will return an eager listener in a
1959 	 * already established state.
1960 	 */
1961 	acceptor_id = tcr->ACCEPTOR_id;
1962 	mutex_enter(&listener->tcp_eager_lock);
1963 	if (listener->tcp_acceptor_id == acceptor_id) {
1964 		eager = listener->tcp_eager_next_q;
1965 		/* only count how many T_CONN_INDs so don't count q0 */
1966 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1967 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1968 			mutex_exit(&listener->tcp_eager_lock);
1969 			tcp_err_ack(listener, mp, TBADF, 0);
1970 			return;
1971 		}
1972 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1973 			/* Throw away all the eagers on q0. */
1974 			tcp_eager_cleanup(listener, 1);
1975 		}
1976 		if (listener->tcp_syn_defense) {
1977 			listener->tcp_syn_defense = B_FALSE;
1978 			if (listener->tcp_ip_addr_cache != NULL) {
1979 				kmem_free(listener->tcp_ip_addr_cache,
1980 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1981 				listener->tcp_ip_addr_cache = NULL;
1982 			}
1983 		}
1984 		/*
1985 		 * Transfer tcp_conn_req_max to the eager so that when
1986 		 * a disconnect occurs we can revert the endpoint to the
1987 		 * listen state.
1988 		 */
1989 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1990 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1991 		/*
1992 		 * Get a reference on the acceptor just like the
1993 		 * tcp_acceptor_hash_lookup below.
1994 		 */
1995 		acceptor = listener;
1996 		CONN_INC_REF(acceptor->tcp_connp);
1997 	} else {
1998 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1999 		if (acceptor == NULL) {
2000 			if (listener->tcp_debug) {
2001 				(void) strlog(TCP_MOD_ID, 0, 1,
2002 				    SL_ERROR|SL_TRACE,
2003 				    "tcp_accept: did not find acceptor 0x%x\n",
2004 				    acceptor_id);
2005 			}
2006 			mutex_exit(&listener->tcp_eager_lock);
2007 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2008 			return;
2009 		}
2010 		/*
2011 		 * Verify acceptor state. The acceptable states for an acceptor
2012 		 * include TCPS_IDLE and TCPS_BOUND.
2013 		 */
2014 		switch (acceptor->tcp_state) {
2015 		case TCPS_IDLE:
2016 			/* FALLTHRU */
2017 		case TCPS_BOUND:
2018 			break;
2019 		default:
2020 			CONN_DEC_REF(acceptor->tcp_connp);
2021 			mutex_exit(&listener->tcp_eager_lock);
2022 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2023 			return;
2024 		}
2025 	}
2026 
2027 	/* The listener must be in TCPS_LISTEN */
2028 	if (listener->tcp_state != TCPS_LISTEN) {
2029 		CONN_DEC_REF(acceptor->tcp_connp);
2030 		mutex_exit(&listener->tcp_eager_lock);
2031 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2032 		return;
2033 	}
2034 
2035 	/*
2036 	 * Rendezvous with an eager connection request packet hanging off
2037 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2038 	 * tcp structure when the connection packet arrived in
2039 	 * tcp_conn_request().
2040 	 */
2041 	seqnum = tcr->SEQ_number;
2042 	eager = listener;
2043 	do {
2044 		eager = eager->tcp_eager_next_q;
2045 		if (eager == NULL) {
2046 			CONN_DEC_REF(acceptor->tcp_connp);
2047 			mutex_exit(&listener->tcp_eager_lock);
2048 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2049 			return;
2050 		}
2051 	} while (eager->tcp_conn_req_seqnum != seqnum);
2052 	mutex_exit(&listener->tcp_eager_lock);
2053 
2054 	/*
2055 	 * At this point, both acceptor and listener have 2 ref
2056 	 * that they begin with. Acceptor has one additional ref
2057 	 * we placed in lookup while listener has 3 additional
2058 	 * ref for being behind the squeue (tcp_accept() is
2059 	 * done on listener's squeue); being in classifier hash;
2060 	 * and eager's ref on listener.
2061 	 */
2062 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2063 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2064 
2065 	/*
2066 	 * The eager at this point is set in its own squeue and
2067 	 * could easily have been killed (tcp_accept_finish will
2068 	 * deal with that) because of a TH_RST so we can only
2069 	 * ASSERT for a single ref.
2070 	 */
2071 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2072 
2073 	/* Pre allocate the stroptions mblk also */
2074 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2075 	if (opt_mp == NULL) {
2076 		CONN_DEC_REF(acceptor->tcp_connp);
2077 		CONN_DEC_REF(eager->tcp_connp);
2078 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2079 		return;
2080 	}
2081 	DB_TYPE(opt_mp) = M_SETOPTS;
2082 	opt_mp->b_wptr += sizeof (struct stroptions);
2083 
2084 	/*
2085 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2086 	 * from listener to acceptor. The message is chained on opt_mp
2087 	 * which will be sent onto eager's squeue.
2088 	 */
2089 	if (listener->tcp_bound_if != 0) {
2090 		/* allocate optmgmt req */
2091 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2092 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2093 		    sizeof (int));
2094 		if (mp1 != NULL)
2095 			linkb(opt_mp, mp1);
2096 	}
2097 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2098 		uint_t on = 1;
2099 
2100 		/* allocate optmgmt req */
2101 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2102 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2103 		if (mp1 != NULL)
2104 			linkb(opt_mp, mp1);
2105 	}
2106 
2107 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2108 	if ((mp1 = copymsg(mp)) == NULL) {
2109 		CONN_DEC_REF(acceptor->tcp_connp);
2110 		CONN_DEC_REF(eager->tcp_connp);
2111 		freemsg(opt_mp);
2112 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2113 		return;
2114 	}
2115 
2116 	tcr = (struct T_conn_res *)mp1->b_rptr;
2117 
2118 	/*
2119 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2120 	 * which allocates a larger mblk and appends the new
2121 	 * local address to the ok_ack.  The address is copied by
2122 	 * soaccept() for getsockname().
2123 	 */
2124 	{
2125 		int extra;
2126 
2127 		extra = (eager->tcp_family == AF_INET) ?
2128 		    sizeof (sin_t) : sizeof (sin6_t);
2129 
2130 		/*
2131 		 * Try to re-use mp, if possible.  Otherwise, allocate
2132 		 * an mblk and return it as ok_mp.  In any case, mp
2133 		 * is no longer usable upon return.
2134 		 */
2135 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2136 			CONN_DEC_REF(acceptor->tcp_connp);
2137 			CONN_DEC_REF(eager->tcp_connp);
2138 			freemsg(opt_mp);
2139 			/* Original mp has been freed by now, so use mp1 */
2140 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2141 			return;
2142 		}
2143 
2144 		mp = NULL;	/* We should never use mp after this point */
2145 
2146 		switch (extra) {
2147 		case sizeof (sin_t): {
2148 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2149 
2150 				ok_mp->b_wptr += extra;
2151 				sin->sin_family = AF_INET;
2152 				sin->sin_port = eager->tcp_lport;
2153 				sin->sin_addr.s_addr =
2154 				    eager->tcp_ipha->ipha_src;
2155 				break;
2156 			}
2157 		case sizeof (sin6_t): {
2158 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2159 
2160 				ok_mp->b_wptr += extra;
2161 				sin6->sin6_family = AF_INET6;
2162 				sin6->sin6_port = eager->tcp_lport;
2163 				if (eager->tcp_ipversion == IPV4_VERSION) {
2164 					sin6->sin6_flowinfo = 0;
2165 					IN6_IPADDR_TO_V4MAPPED(
2166 					    eager->tcp_ipha->ipha_src,
2167 					    &sin6->sin6_addr);
2168 				} else {
2169 					ASSERT(eager->tcp_ip6h != NULL);
2170 					sin6->sin6_flowinfo =
2171 					    eager->tcp_ip6h->ip6_vcf &
2172 					    ~IPV6_VERS_AND_FLOW_MASK;
2173 					sin6->sin6_addr =
2174 					    eager->tcp_ip6h->ip6_src;
2175 				}
2176 				sin6->sin6_scope_id = 0;
2177 				sin6->__sin6_src_id = 0;
2178 				break;
2179 			}
2180 		default:
2181 			break;
2182 		}
2183 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2184 	}
2185 
2186 	/*
2187 	 * If there are no options we know that the T_CONN_RES will
2188 	 * succeed. However, we can't send the T_OK_ACK upstream until
2189 	 * the tcp_accept_swap is done since it would be dangerous to
2190 	 * let the application start using the new fd prior to the swap.
2191 	 */
2192 	tcp_accept_swap(listener, acceptor, eager);
2193 
2194 	/*
2195 	 * tcp_accept_swap unlinks eager from listener but does not drop
2196 	 * the eager's reference on the listener.
2197 	 */
2198 	ASSERT(eager->tcp_listener == NULL);
2199 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2200 
2201 	/*
2202 	 * The eager is now associated with its own queue. Insert in
2203 	 * the hash so that the connection can be reused for a future
2204 	 * T_CONN_RES.
2205 	 */
2206 	tcp_acceptor_hash_insert(acceptor_id, eager);
2207 
2208 	/*
2209 	 * We now do the processing of options with T_CONN_RES.
2210 	 * We delay till now since we wanted to have queue to pass to
2211 	 * option processing routines that points back to the right
2212 	 * instance structure which does not happen until after
2213 	 * tcp_accept_swap().
2214 	 *
2215 	 * Note:
2216 	 * The sanity of the logic here assumes that whatever options
2217 	 * are appropriate to inherit from listner=>eager are done
2218 	 * before this point, and whatever were to be overridden (or not)
2219 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2220 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2221 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2222 	 * This may not be true at this point in time but can be fixed
2223 	 * independently. This option processing code starts with
2224 	 * the instantiated acceptor instance and the final queue at
2225 	 * this point.
2226 	 */
2227 
2228 	if (tcr->OPT_length != 0) {
2229 		/* Options to process */
2230 		int t_error = 0;
2231 		int sys_error = 0;
2232 		int do_disconnect = 0;
2233 
2234 		if (tcp_conprim_opt_process(eager, mp1,
2235 		    &do_disconnect, &t_error, &sys_error) < 0) {
2236 			eager->tcp_accept_error = 1;
2237 			if (do_disconnect) {
2238 				/*
2239 				 * An option failed which does not allow
2240 				 * connection to be accepted.
2241 				 *
2242 				 * We allow T_CONN_RES to succeed and
2243 				 * put a T_DISCON_IND on the eager queue.
2244 				 */
2245 				ASSERT(t_error == 0 && sys_error == 0);
2246 				eager->tcp_send_discon_ind = 1;
2247 			} else {
2248 				ASSERT(t_error != 0);
2249 				freemsg(ok_mp);
2250 				/*
2251 				 * Original mp was either freed or set
2252 				 * to ok_mp above, so use mp1 instead.
2253 				 */
2254 				tcp_err_ack(listener, mp1, t_error, sys_error);
2255 				goto finish;
2256 			}
2257 		}
2258 		/*
2259 		 * Most likely success in setting options (except if
2260 		 * eager->tcp_send_discon_ind set).
2261 		 * mp1 option buffer represented by OPT_length/offset
2262 		 * potentially modified and contains results of setting
2263 		 * options at this point
2264 		 */
2265 	}
2266 
2267 	/* We no longer need mp1, since all options processing has passed */
2268 	freemsg(mp1);
2269 
2270 	putnext(listener->tcp_rq, ok_mp);
2271 
2272 	mutex_enter(&listener->tcp_eager_lock);
2273 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2274 		tcp_t	*tail;
2275 		mblk_t	*conn_ind;
2276 
2277 		/*
2278 		 * This path should not be executed if listener and
2279 		 * acceptor streams are the same.
2280 		 */
2281 		ASSERT(listener != acceptor);
2282 
2283 		tcp = listener->tcp_eager_prev_q0;
2284 		/*
2285 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2286 		 * deferred T_conn_ind queue. We need to get to the head of
2287 		 * the queue in order to send up T_conn_ind the same order as
2288 		 * how the 3WHS is completed.
2289 		 */
2290 		while (tcp != listener) {
2291 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2292 				break;
2293 			else
2294 				tcp = tcp->tcp_eager_prev_q0;
2295 		}
2296 		ASSERT(tcp != listener);
2297 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2298 		ASSERT(conn_ind != NULL);
2299 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2300 
2301 		/* Move from q0 to q */
2302 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2303 		listener->tcp_conn_req_cnt_q0--;
2304 		listener->tcp_conn_req_cnt_q++;
2305 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2306 		    tcp->tcp_eager_prev_q0;
2307 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2308 		    tcp->tcp_eager_next_q0;
2309 		tcp->tcp_eager_prev_q0 = NULL;
2310 		tcp->tcp_eager_next_q0 = NULL;
2311 		tcp->tcp_conn_def_q0 = B_FALSE;
2312 
2313 		/* Make sure the tcp isn't in the list of droppables */
2314 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2315 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2316 
2317 		/*
2318 		 * Insert at end of the queue because sockfs sends
2319 		 * down T_CONN_RES in chronological order. Leaving
2320 		 * the older conn indications at front of the queue
2321 		 * helps reducing search time.
2322 		 */
2323 		tail = listener->tcp_eager_last_q;
2324 		if (tail != NULL)
2325 			tail->tcp_eager_next_q = tcp;
2326 		else
2327 			listener->tcp_eager_next_q = tcp;
2328 		listener->tcp_eager_last_q = tcp;
2329 		tcp->tcp_eager_next_q = NULL;
2330 		mutex_exit(&listener->tcp_eager_lock);
2331 		putnext(tcp->tcp_rq, conn_ind);
2332 	} else {
2333 		mutex_exit(&listener->tcp_eager_lock);
2334 	}
2335 
2336 	/*
2337 	 * Done with the acceptor - free it
2338 	 *
2339 	 * Note: from this point on, no access to listener should be made
2340 	 * as listener can be equal to acceptor.
2341 	 */
2342 finish:
2343 	ASSERT(acceptor->tcp_detached);
2344 	ASSERT(tcps->tcps_g_q != NULL);
2345 	acceptor->tcp_rq = tcps->tcps_g_q;
2346 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2347 	(void) tcp_clean_death(acceptor, 0, 2);
2348 	CONN_DEC_REF(acceptor->tcp_connp);
2349 
2350 	/*
2351 	 * In case we already received a FIN we have to make tcp_rput send
2352 	 * the ordrel_ind. This will also send up a window update if the window
2353 	 * has opened up.
2354 	 *
2355 	 * In the normal case of a successful connection acceptance
2356 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2357 	 * indication that this was just accepted. This tells tcp_rput to
2358 	 * pass up any data queued in tcp_rcv_list.
2359 	 *
2360 	 * In the fringe case where options sent with T_CONN_RES failed and
2361 	 * we required, we would be indicating a T_DISCON_IND to blow
2362 	 * away this connection.
2363 	 */
2364 
2365 	/*
2366 	 * XXX: we currently have a problem if XTI application closes the
2367 	 * acceptor stream in between. This problem exists in on10-gate also
2368 	 * and is well know but nothing can be done short of major rewrite
2369 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2370 	 * eager same squeue as listener (we can distinguish non socket
2371 	 * listeners at the time of handling a SYN in tcp_conn_request)
2372 	 * and do most of the work that tcp_accept_finish does here itself
2373 	 * and then get behind the acceptor squeue to access the acceptor
2374 	 * queue.
2375 	 */
2376 	/*
2377 	 * We already have a ref on tcp so no need to do one before squeue_fill
2378 	 */
2379 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2380 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2381 }
2382 
2383 /*
2384  * Swap information between the eager and acceptor for a TLI/XTI client.
2385  * The sockfs accept is done on the acceptor stream and control goes
2386  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2387  * called. In either case, both the eager and listener are in their own
2388  * perimeter (squeue) and the code has to deal with potential race.
2389  *
2390  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2391  */
2392 static void
2393 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2394 {
2395 	conn_t	*econnp, *aconnp;
2396 
2397 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2398 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2399 	ASSERT(!eager->tcp_hard_bound);
2400 	ASSERT(!TCP_IS_SOCKET(acceptor));
2401 	ASSERT(!TCP_IS_SOCKET(eager));
2402 	ASSERT(!TCP_IS_SOCKET(listener));
2403 
2404 	acceptor->tcp_detached = B_TRUE;
2405 	/*
2406 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2407 	 * the acceptor id.
2408 	 */
2409 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2410 
2411 	/* remove eager from listen list... */
2412 	mutex_enter(&listener->tcp_eager_lock);
2413 	tcp_eager_unlink(eager);
2414 	ASSERT(eager->tcp_eager_next_q == NULL &&
2415 	    eager->tcp_eager_last_q == NULL);
2416 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2417 	    eager->tcp_eager_prev_q0 == NULL);
2418 	mutex_exit(&listener->tcp_eager_lock);
2419 	eager->tcp_rq = acceptor->tcp_rq;
2420 	eager->tcp_wq = acceptor->tcp_wq;
2421 
2422 	econnp = eager->tcp_connp;
2423 	aconnp = acceptor->tcp_connp;
2424 
2425 	eager->tcp_rq->q_ptr = econnp;
2426 	eager->tcp_wq->q_ptr = econnp;
2427 
2428 	/*
2429 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2430 	 * which might be a different squeue from our peer TCP instance.
2431 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2432 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2433 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2434 	 * above reach global visibility prior to the clearing of tcp_detached.
2435 	 */
2436 	membar_producer();
2437 	eager->tcp_detached = B_FALSE;
2438 
2439 	ASSERT(eager->tcp_ack_tid == 0);
2440 
2441 	econnp->conn_dev = aconnp->conn_dev;
2442 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2443 	ASSERT(econnp->conn_minor_arena != NULL);
2444 	if (eager->tcp_cred != NULL)
2445 		crfree(eager->tcp_cred);
2446 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2447 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2448 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2449 
2450 	aconnp->conn_cred = NULL;
2451 
2452 	econnp->conn_zoneid = aconnp->conn_zoneid;
2453 	econnp->conn_allzones = aconnp->conn_allzones;
2454 
2455 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2456 	aconnp->conn_mac_exempt = B_FALSE;
2457 
2458 	ASSERT(aconnp->conn_peercred == NULL);
2459 
2460 	/* Do the IPC initialization */
2461 	CONN_INC_REF(econnp);
2462 
2463 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2464 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2465 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2466 
2467 	/* Done with old IPC. Drop its ref on its connp */
2468 	CONN_DEC_REF(aconnp);
2469 }
2470 
2471 
2472 /*
2473  * Adapt to the information, such as rtt and rtt_sd, provided from the
2474  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2475  *
2476  * Checks for multicast and broadcast destination address.
2477  * Returns zero on failure; non-zero if ok.
2478  *
2479  * Note that the MSS calculation here is based on the info given in
2480  * the IRE.  We do not do any calculation based on TCP options.  They
2481  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2482  * knows which options to use.
2483  *
2484  * Note on how TCP gets its parameters for a connection.
2485  *
2486  * When a tcp_t structure is allocated, it gets all the default parameters.
2487  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2488  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2489  * default.
2490  *
2491  * An incoming SYN with a multicast or broadcast destination address, is dropped
2492  * in 1 of 2 places.
2493  *
2494  * 1. If the packet was received over the wire it is dropped in
2495  * ip_rput_process_broadcast()
2496  *
2497  * 2. If the packet was received through internal IP loopback, i.e. the packet
2498  * was generated and received on the same machine, it is dropped in
2499  * ip_wput_local()
2500  *
2501  * An incoming SYN with a multicast or broadcast source address is always
2502  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2503  * reject an attempt to connect to a broadcast or multicast (destination)
2504  * address.
2505  */
2506 static int
2507 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2508 {
2509 	tcp_hsp_t	*hsp;
2510 	ire_t		*ire;
2511 	ire_t		*sire = NULL;
2512 	iulp_t		*ire_uinfo = NULL;
2513 	uint32_t	mss_max;
2514 	uint32_t	mss;
2515 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2516 	conn_t		*connp = tcp->tcp_connp;
2517 	boolean_t	ire_cacheable = B_FALSE;
2518 	zoneid_t	zoneid = connp->conn_zoneid;
2519 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2520 	    MATCH_IRE_SECATTR;
2521 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2522 	ill_t		*ill = NULL;
2523 	boolean_t	incoming = (ire_mp == NULL);
2524 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2525 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2526 
2527 	ASSERT(connp->conn_ire_cache == NULL);
2528 
2529 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2530 
2531 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2532 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2533 			return (0);
2534 		}
2535 		/*
2536 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2537 		 * for the destination with the nexthop as gateway.
2538 		 * ire_ctable_lookup() is used because this particular
2539 		 * ire, if it exists, will be marked private.
2540 		 * If that is not available, use the interface ire
2541 		 * for the nexthop.
2542 		 *
2543 		 * TSol: tcp_update_label will detect label mismatches based
2544 		 * only on the destination's label, but that would not
2545 		 * detect label mismatches based on the security attributes
2546 		 * of routes or next hop gateway. Hence we need to pass the
2547 		 * label to ire_ftable_lookup below in order to locate the
2548 		 * right prefix (and/or) ire cache. Similarly we also need
2549 		 * pass the label to the ire_cache_lookup below to locate
2550 		 * the right ire that also matches on the label.
2551 		 */
2552 		if (tcp->tcp_connp->conn_nexthop_set) {
2553 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2554 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2555 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2556 			    ipst);
2557 			if (ire == NULL) {
2558 				ire = ire_ftable_lookup(
2559 				    tcp->tcp_connp->conn_nexthop_v4,
2560 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2561 				    tsl, match_flags, ipst);
2562 				if (ire == NULL)
2563 					return (0);
2564 			} else {
2565 				ire_uinfo = &ire->ire_uinfo;
2566 			}
2567 		} else {
2568 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2569 			    zoneid, tsl, ipst);
2570 			if (ire != NULL) {
2571 				ire_cacheable = B_TRUE;
2572 				ire_uinfo = (ire_mp != NULL) ?
2573 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2574 				    &ire->ire_uinfo;
2575 
2576 			} else {
2577 				if (ire_mp == NULL) {
2578 					ire = ire_ftable_lookup(
2579 					    tcp->tcp_connp->conn_rem,
2580 					    0, 0, 0, NULL, &sire, zoneid, 0,
2581 					    tsl, (MATCH_IRE_RECURSIVE |
2582 					    MATCH_IRE_DEFAULT), ipst);
2583 					if (ire == NULL)
2584 						return (0);
2585 					ire_uinfo = (sire != NULL) ?
2586 					    &sire->ire_uinfo :
2587 					    &ire->ire_uinfo;
2588 				} else {
2589 					ire = (ire_t *)ire_mp->b_rptr;
2590 					ire_uinfo =
2591 					    &((ire_t *)
2592 					    ire_mp->b_rptr)->ire_uinfo;
2593 				}
2594 			}
2595 		}
2596 		ASSERT(ire != NULL);
2597 
2598 		if ((ire->ire_src_addr == INADDR_ANY) ||
2599 		    (ire->ire_type & IRE_BROADCAST)) {
2600 			/*
2601 			 * ire->ire_mp is non null when ire_mp passed in is used
2602 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2603 			 */
2604 			if (ire->ire_mp == NULL)
2605 				ire_refrele(ire);
2606 			if (sire != NULL)
2607 				ire_refrele(sire);
2608 			return (0);
2609 		}
2610 
2611 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2612 			ipaddr_t src_addr;
2613 
2614 			/*
2615 			 * ip_bind_connected() has stored the correct source
2616 			 * address in conn_src.
2617 			 */
2618 			src_addr = tcp->tcp_connp->conn_src;
2619 			tcp->tcp_ipha->ipha_src = src_addr;
2620 			/*
2621 			 * Copy of the src addr. in tcp_t is needed
2622 			 * for the lookup funcs.
2623 			 */
2624 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2625 		}
2626 		/*
2627 		 * Set the fragment bit so that IP will tell us if the MTU
2628 		 * should change. IP tells us the latest setting of
2629 		 * ip_path_mtu_discovery through ire_frag_flag.
2630 		 */
2631 		if (ipst->ips_ip_path_mtu_discovery) {
2632 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2633 			    htons(IPH_DF);
2634 		}
2635 		/*
2636 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2637 		 * for IP_NEXTHOP. No cache ire has been found for the
2638 		 * destination and we are working with the nexthop's
2639 		 * interface ire. Since we need to forward all packets
2640 		 * to the nexthop first, we "blindly" set tcp_localnet
2641 		 * to false, eventhough the destination may also be
2642 		 * onlink.
2643 		 */
2644 		if (ire_uinfo == NULL)
2645 			tcp->tcp_localnet = 0;
2646 		else
2647 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2648 	} else {
2649 		/*
2650 		 * For incoming connection ire_mp = NULL
2651 		 * For outgoing connection ire_mp != NULL
2652 		 * Technically we should check conn_incoming_ill
2653 		 * when ire_mp is NULL and conn_outgoing_ill when
2654 		 * ire_mp is non-NULL. But this is performance
2655 		 * critical path and for IPV*_BOUND_IF, outgoing
2656 		 * and incoming ill are always set to the same value.
2657 		 */
2658 		ill_t	*dst_ill = NULL;
2659 		ipif_t  *dst_ipif = NULL;
2660 
2661 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2662 
2663 		if (connp->conn_outgoing_ill != NULL) {
2664 			/* Outgoing or incoming path */
2665 			int   err;
2666 
2667 			dst_ill = conn_get_held_ill(connp,
2668 			    &connp->conn_outgoing_ill, &err);
2669 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2670 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2671 				return (0);
2672 			}
2673 			match_flags |= MATCH_IRE_ILL;
2674 			dst_ipif = dst_ill->ill_ipif;
2675 		}
2676 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2677 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2678 
2679 		if (ire != NULL) {
2680 			ire_cacheable = B_TRUE;
2681 			ire_uinfo = (ire_mp != NULL) ?
2682 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2683 			    &ire->ire_uinfo;
2684 		} else {
2685 			if (ire_mp == NULL) {
2686 				ire = ire_ftable_lookup_v6(
2687 				    &tcp->tcp_connp->conn_remv6,
2688 				    0, 0, 0, dst_ipif, &sire, zoneid,
2689 				    0, tsl, match_flags, ipst);
2690 				if (ire == NULL) {
2691 					if (dst_ill != NULL)
2692 						ill_refrele(dst_ill);
2693 					return (0);
2694 				}
2695 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2696 				    &ire->ire_uinfo;
2697 			} else {
2698 				ire = (ire_t *)ire_mp->b_rptr;
2699 				ire_uinfo =
2700 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2701 			}
2702 		}
2703 		if (dst_ill != NULL)
2704 			ill_refrele(dst_ill);
2705 
2706 		ASSERT(ire != NULL);
2707 		ASSERT(ire_uinfo != NULL);
2708 
2709 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2710 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2711 			/*
2712 			 * ire->ire_mp is non null when ire_mp passed in is used
2713 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2714 			 */
2715 			if (ire->ire_mp == NULL)
2716 				ire_refrele(ire);
2717 			if (sire != NULL)
2718 				ire_refrele(sire);
2719 			return (0);
2720 		}
2721 
2722 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2723 			in6_addr_t	src_addr;
2724 
2725 			/*
2726 			 * ip_bind_connected_v6() has stored the correct source
2727 			 * address per IPv6 addr. selection policy in
2728 			 * conn_src_v6.
2729 			 */
2730 			src_addr = tcp->tcp_connp->conn_srcv6;
2731 
2732 			tcp->tcp_ip6h->ip6_src = src_addr;
2733 			/*
2734 			 * Copy of the src addr. in tcp_t is needed
2735 			 * for the lookup funcs.
2736 			 */
2737 			tcp->tcp_ip_src_v6 = src_addr;
2738 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2739 			    &connp->conn_srcv6));
2740 		}
2741 		tcp->tcp_localnet =
2742 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2743 	}
2744 
2745 	/*
2746 	 * This allows applications to fail quickly when connections are made
2747 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2748 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2749 	 */
2750 	if ((ire->ire_flags & RTF_REJECT) &&
2751 	    (ire->ire_flags & RTF_PRIVATE))
2752 		goto error;
2753 
2754 	/*
2755 	 * Make use of the cached rtt and rtt_sd values to calculate the
2756 	 * initial RTO.  Note that they are already initialized in
2757 	 * tcp_init_values().
2758 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2759 	 * IP_NEXTHOP, but instead are using the interface ire for the
2760 	 * nexthop, then we do not use the ire_uinfo from that ire to
2761 	 * do any initializations.
2762 	 */
2763 	if (ire_uinfo != NULL) {
2764 		if (ire_uinfo->iulp_rtt != 0) {
2765 			clock_t	rto;
2766 
2767 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2768 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2769 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2770 			    tcps->tcps_rexmit_interval_extra +
2771 			    (tcp->tcp_rtt_sa >> 5);
2772 
2773 			if (rto > tcps->tcps_rexmit_interval_max) {
2774 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2775 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2776 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2777 			} else {
2778 				tcp->tcp_rto = rto;
2779 			}
2780 		}
2781 		if (ire_uinfo->iulp_ssthresh != 0)
2782 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2783 		else
2784 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2785 		if (ire_uinfo->iulp_spipe > 0) {
2786 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2787 			    tcps->tcps_max_buf);
2788 			if (tcps->tcps_snd_lowat_fraction != 0)
2789 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2790 				    tcps->tcps_snd_lowat_fraction;
2791 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2792 		}
2793 		/*
2794 		 * Note that up till now, acceptor always inherits receive
2795 		 * window from the listener.  But if there is a metrics
2796 		 * associated with a host, we should use that instead of
2797 		 * inheriting it from listener. Thus we need to pass this
2798 		 * info back to the caller.
2799 		 */
2800 		if (ire_uinfo->iulp_rpipe > 0) {
2801 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2802 			    tcps->tcps_max_buf);
2803 		}
2804 
2805 		if (ire_uinfo->iulp_rtomax > 0) {
2806 			tcp->tcp_second_timer_threshold =
2807 			    ire_uinfo->iulp_rtomax;
2808 		}
2809 
2810 		/*
2811 		 * Use the metric option settings, iulp_tstamp_ok and
2812 		 * iulp_wscale_ok, only for active open. What this means
2813 		 * is that if the other side uses timestamp or window
2814 		 * scale option, TCP will also use those options. That
2815 		 * is for passive open.  If the application sets a
2816 		 * large window, window scale is enabled regardless of
2817 		 * the value in iulp_wscale_ok.  This is the behavior
2818 		 * since 2.6.  So we keep it.
2819 		 * The only case left in passive open processing is the
2820 		 * check for SACK.
2821 		 * For ECN, it should probably be like SACK.  But the
2822 		 * current value is binary, so we treat it like the other
2823 		 * cases.  The metric only controls active open.For passive
2824 		 * open, the ndd param, tcp_ecn_permitted, controls the
2825 		 * behavior.
2826 		 */
2827 		if (!tcp_detached) {
2828 			/*
2829 			 * The if check means that the following can only
2830 			 * be turned on by the metrics only IRE, but not off.
2831 			 */
2832 			if (ire_uinfo->iulp_tstamp_ok)
2833 				tcp->tcp_snd_ts_ok = B_TRUE;
2834 			if (ire_uinfo->iulp_wscale_ok)
2835 				tcp->tcp_snd_ws_ok = B_TRUE;
2836 			if (ire_uinfo->iulp_sack == 2)
2837 				tcp->tcp_snd_sack_ok = B_TRUE;
2838 			if (ire_uinfo->iulp_ecn_ok)
2839 				tcp->tcp_ecn_ok = B_TRUE;
2840 		} else {
2841 			/*
2842 			 * Passive open.
2843 			 *
2844 			 * As above, the if check means that SACK can only be
2845 			 * turned on by the metric only IRE.
2846 			 */
2847 			if (ire_uinfo->iulp_sack > 0) {
2848 				tcp->tcp_snd_sack_ok = B_TRUE;
2849 			}
2850 		}
2851 	}
2852 
2853 
2854 	/*
2855 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2856 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2857 	 * length of all those options exceeds 28 bytes.  But because
2858 	 * of the tcp_mss_min check below, we may not have a problem if
2859 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2860 	 * the negative problem still exists.  And the check defeats PMTUd.
2861 	 * In fact, if PMTUd finds that the MSS should be smaller than
2862 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2863 	 * value.
2864 	 *
2865 	 * We do not deal with that now.  All those problems related to
2866 	 * PMTUd will be fixed later.
2867 	 */
2868 	ASSERT(ire->ire_max_frag != 0);
2869 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2870 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2871 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2872 			mss = MIN(mss, IPV6_MIN_MTU);
2873 		}
2874 	}
2875 
2876 	/* Sanity check for MSS value. */
2877 	if (tcp->tcp_ipversion == IPV4_VERSION)
2878 		mss_max = tcps->tcps_mss_max_ipv4;
2879 	else
2880 		mss_max = tcps->tcps_mss_max_ipv6;
2881 
2882 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2883 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2884 		/*
2885 		 * After receiving an ICMPv6 "packet too big" message with a
2886 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2887 		 * will insert a 8-byte fragment header in every packet; we
2888 		 * reduce the MSS by that amount here.
2889 		 */
2890 		mss -= sizeof (ip6_frag_t);
2891 	}
2892 
2893 	if (tcp->tcp_ipsec_overhead == 0)
2894 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2895 
2896 	mss -= tcp->tcp_ipsec_overhead;
2897 
2898 	if (mss < tcps->tcps_mss_min)
2899 		mss = tcps->tcps_mss_min;
2900 	if (mss > mss_max)
2901 		mss = mss_max;
2902 
2903 	/* Note that this is the maximum MSS, excluding all options. */
2904 	tcp->tcp_mss = mss;
2905 
2906 	/*
2907 	 * Initialize the ISS here now that we have the full connection ID.
2908 	 * The RFC 1948 method of initial sequence number generation requires
2909 	 * knowledge of the full connection ID before setting the ISS.
2910 	 */
2911 
2912 	tcp_iss_init(tcp);
2913 
2914 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2915 		tcp->tcp_loopback = B_TRUE;
2916 
2917 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2918 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2919 	} else {
2920 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2921 	}
2922 
2923 	if (hsp != NULL) {
2924 		/* Only modify if we're going to make them bigger */
2925 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2926 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2927 			if (tcps->tcps_snd_lowat_fraction != 0)
2928 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2929 				    tcps->tcps_snd_lowat_fraction;
2930 		}
2931 
2932 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2933 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2934 		}
2935 
2936 		/* Copy timestamp flag only for active open */
2937 		if (!tcp_detached)
2938 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2939 	}
2940 
2941 	if (sire != NULL)
2942 		IRE_REFRELE(sire);
2943 
2944 	/*
2945 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2946 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2947 	 */
2948 	if (tcp->tcp_loopback ||
2949 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2950 		/*
2951 		 * For incoming, see if this tcp may be MDT-capable.  For
2952 		 * outgoing, this process has been taken care of through
2953 		 * tcp_rput_other.
2954 		 */
2955 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2956 		tcp->tcp_ire_ill_check_done = B_TRUE;
2957 	}
2958 
2959 	mutex_enter(&connp->conn_lock);
2960 	/*
2961 	 * Make sure that conn is not marked incipient
2962 	 * for incoming connections. A blind
2963 	 * removal of incipient flag is cheaper than
2964 	 * check and removal.
2965 	 */
2966 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2967 
2968 	/*
2969 	 * Must not cache forwarding table routes
2970 	 * or recache an IRE after the conn_t has
2971 	 * had conn_ire_cache cleared and is flagged
2972 	 * unusable, (see the CONN_CACHE_IRE() macro).
2973 	 */
2974 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2975 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2976 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2977 			connp->conn_ire_cache = ire;
2978 			IRE_UNTRACE_REF(ire);
2979 			rw_exit(&ire->ire_bucket->irb_lock);
2980 			mutex_exit(&connp->conn_lock);
2981 			return (1);
2982 		}
2983 		rw_exit(&ire->ire_bucket->irb_lock);
2984 	}
2985 	mutex_exit(&connp->conn_lock);
2986 
2987 	if (ire->ire_mp == NULL)
2988 		ire_refrele(ire);
2989 	return (1);
2990 
2991 error:
2992 	if (ire->ire_mp == NULL)
2993 		ire_refrele(ire);
2994 	if (sire != NULL)
2995 		ire_refrele(sire);
2996 	return (0);
2997 }
2998 
2999 /*
3000  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
3001  * O_T_BIND_REQ/T_BIND_REQ message.
3002  */
3003 static void
3004 tcp_bind(tcp_t *tcp, mblk_t *mp)
3005 {
3006 	sin_t	*sin;
3007 	sin6_t	*sin6;
3008 	mblk_t	*mp1;
3009 	in_port_t requested_port;
3010 	in_port_t allocated_port;
3011 	struct T_bind_req *tbr;
3012 	boolean_t	bind_to_req_port_only;
3013 	boolean_t	backlog_update = B_FALSE;
3014 	boolean_t	user_specified;
3015 	in6_addr_t	v6addr;
3016 	ipaddr_t	v4addr;
3017 	uint_t	origipversion;
3018 	int	err;
3019 	queue_t *q = tcp->tcp_wq;
3020 	conn_t	*connp = tcp->tcp_connp;
3021 	mlp_type_t addrtype, mlptype;
3022 	zone_t	*zone;
3023 	cred_t	*cr;
3024 	in_port_t mlp_port;
3025 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3026 
3027 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3028 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3029 		if (tcp->tcp_debug) {
3030 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3031 			    "tcp_bind: bad req, len %u",
3032 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3033 		}
3034 		tcp_err_ack(tcp, mp, TPROTO, 0);
3035 		return;
3036 	}
3037 	/* Make sure the largest address fits */
3038 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3039 	if (mp1 == NULL) {
3040 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3041 		return;
3042 	}
3043 	mp = mp1;
3044 	tbr = (struct T_bind_req *)mp->b_rptr;
3045 	if (tcp->tcp_state >= TCPS_BOUND) {
3046 		if ((tcp->tcp_state == TCPS_BOUND ||
3047 		    tcp->tcp_state == TCPS_LISTEN) &&
3048 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3049 		    tbr->CONIND_number > 0) {
3050 			/*
3051 			 * Handle listen() increasing CONIND_number.
3052 			 * This is more "liberal" then what the TPI spec
3053 			 * requires but is needed to avoid a t_unbind
3054 			 * when handling listen() since the port number
3055 			 * might be "stolen" between the unbind and bind.
3056 			 */
3057 			backlog_update = B_TRUE;
3058 			goto do_bind;
3059 		}
3060 		if (tcp->tcp_debug) {
3061 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3062 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3063 		}
3064 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3065 		return;
3066 	}
3067 	origipversion = tcp->tcp_ipversion;
3068 
3069 	switch (tbr->ADDR_length) {
3070 	case 0:			/* request for a generic port */
3071 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3072 		if (tcp->tcp_family == AF_INET) {
3073 			tbr->ADDR_length = sizeof (sin_t);
3074 			sin = (sin_t *)&tbr[1];
3075 			*sin = sin_null;
3076 			sin->sin_family = AF_INET;
3077 			mp->b_wptr = (uchar_t *)&sin[1];
3078 			tcp->tcp_ipversion = IPV4_VERSION;
3079 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3080 		} else {
3081 			ASSERT(tcp->tcp_family == AF_INET6);
3082 			tbr->ADDR_length = sizeof (sin6_t);
3083 			sin6 = (sin6_t *)&tbr[1];
3084 			*sin6 = sin6_null;
3085 			sin6->sin6_family = AF_INET6;
3086 			mp->b_wptr = (uchar_t *)&sin6[1];
3087 			tcp->tcp_ipversion = IPV6_VERSION;
3088 			V6_SET_ZERO(v6addr);
3089 		}
3090 		requested_port = 0;
3091 		break;
3092 
3093 	case sizeof (sin_t):	/* Complete IPv4 address */
3094 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3095 		    sizeof (sin_t));
3096 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3097 			if (tcp->tcp_debug) {
3098 				(void) strlog(TCP_MOD_ID, 0, 1,
3099 				    SL_ERROR|SL_TRACE,
3100 				    "tcp_bind: bad address parameter, "
3101 				    "offset %d, len %d",
3102 				    tbr->ADDR_offset, tbr->ADDR_length);
3103 			}
3104 			tcp_err_ack(tcp, mp, TPROTO, 0);
3105 			return;
3106 		}
3107 		/*
3108 		 * With sockets sockfs will accept bogus sin_family in
3109 		 * bind() and replace it with the family used in the socket
3110 		 * call.
3111 		 */
3112 		if (sin->sin_family != AF_INET ||
3113 		    tcp->tcp_family != AF_INET) {
3114 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3115 			return;
3116 		}
3117 		requested_port = ntohs(sin->sin_port);
3118 		tcp->tcp_ipversion = IPV4_VERSION;
3119 		v4addr = sin->sin_addr.s_addr;
3120 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3121 		break;
3122 
3123 	case sizeof (sin6_t): /* Complete IPv6 address */
3124 		sin6 = (sin6_t *)mi_offset_param(mp,
3125 		    tbr->ADDR_offset, sizeof (sin6_t));
3126 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3127 			if (tcp->tcp_debug) {
3128 				(void) strlog(TCP_MOD_ID, 0, 1,
3129 				    SL_ERROR|SL_TRACE,
3130 				    "tcp_bind: bad IPv6 address parameter, "
3131 				    "offset %d, len %d", tbr->ADDR_offset,
3132 				    tbr->ADDR_length);
3133 			}
3134 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3135 			return;
3136 		}
3137 		if (sin6->sin6_family != AF_INET6 ||
3138 		    tcp->tcp_family != AF_INET6) {
3139 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3140 			return;
3141 		}
3142 		requested_port = ntohs(sin6->sin6_port);
3143 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3144 		    IPV4_VERSION : IPV6_VERSION;
3145 		v6addr = sin6->sin6_addr;
3146 		break;
3147 
3148 	default:
3149 		if (tcp->tcp_debug) {
3150 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3151 			    "tcp_bind: bad address length, %d",
3152 			    tbr->ADDR_length);
3153 		}
3154 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3155 		return;
3156 	}
3157 	tcp->tcp_bound_source_v6 = v6addr;
3158 
3159 	/* Check for change in ipversion */
3160 	if (origipversion != tcp->tcp_ipversion) {
3161 		ASSERT(tcp->tcp_family == AF_INET6);
3162 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3163 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3164 		if (err) {
3165 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3166 			return;
3167 		}
3168 	}
3169 
3170 	/*
3171 	 * Initialize family specific fields. Copy of the src addr.
3172 	 * in tcp_t is needed for the lookup funcs.
3173 	 */
3174 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3175 		tcp->tcp_ip6h->ip6_src = v6addr;
3176 	} else {
3177 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3178 	}
3179 	tcp->tcp_ip_src_v6 = v6addr;
3180 
3181 	/*
3182 	 * For O_T_BIND_REQ:
3183 	 * Verify that the target port/addr is available, or choose
3184 	 * another.
3185 	 * For  T_BIND_REQ:
3186 	 * Verify that the target port/addr is available or fail.
3187 	 * In both cases when it succeeds the tcp is inserted in the
3188 	 * bind hash table. This ensures that the operation is atomic
3189 	 * under the lock on the hash bucket.
3190 	 */
3191 	bind_to_req_port_only = requested_port != 0 &&
3192 	    tbr->PRIM_type != O_T_BIND_REQ;
3193 	/*
3194 	 * Get a valid port (within the anonymous range and should not
3195 	 * be a privileged one) to use if the user has not given a port.
3196 	 * If multiple threads are here, they may all start with
3197 	 * with the same initial port. But, it should be fine as long as
3198 	 * tcp_bindi will ensure that no two threads will be assigned
3199 	 * the same port.
3200 	 *
3201 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3202 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3203 	 * unless TCP_ANONPRIVBIND option is set.
3204 	 */
3205 	mlptype = mlptSingle;
3206 	mlp_port = requested_port;
3207 	if (requested_port == 0) {
3208 		requested_port = tcp->tcp_anon_priv_bind ?
3209 		    tcp_get_next_priv_port(tcp) :
3210 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
3211 		    tcp, B_TRUE);
3212 		if (requested_port == 0) {
3213 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3214 			return;
3215 		}
3216 		user_specified = B_FALSE;
3217 
3218 		/*
3219 		 * If the user went through one of the RPC interfaces to create
3220 		 * this socket and RPC is MLP in this zone, then give him an
3221 		 * anonymous MLP.
3222 		 */
3223 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3224 		if (connp->conn_anon_mlp && is_system_labeled()) {
3225 			zone = crgetzone(cr);
3226 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3227 			    IPV6_VERSION, &v6addr,
3228 			    tcps->tcps_netstack->netstack_ip);
3229 			if (addrtype == mlptSingle) {
3230 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3231 				return;
3232 			}
3233 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3234 			    PMAPPORT, addrtype);
3235 			mlp_port = PMAPPORT;
3236 		}
3237 	} else {
3238 		int i;
3239 		boolean_t priv = B_FALSE;
3240 
3241 		/*
3242 		 * If the requested_port is in the well-known privileged range,
3243 		 * verify that the stream was opened by a privileged user.
3244 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3245 		 * but instead the code relies on:
3246 		 * - the fact that the address of the array and its size never
3247 		 *   changes
3248 		 * - the atomic assignment of the elements of the array
3249 		 */
3250 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3251 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
3252 			priv = B_TRUE;
3253 		} else {
3254 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
3255 				if (requested_port ==
3256 				    tcps->tcps_g_epriv_ports[i]) {
3257 					priv = B_TRUE;
3258 					break;
3259 				}
3260 			}
3261 		}
3262 		if (priv) {
3263 			if (secpolicy_net_privaddr(cr, requested_port,
3264 			    IPPROTO_TCP) != 0) {
3265 				if (tcp->tcp_debug) {
3266 					(void) strlog(TCP_MOD_ID, 0, 1,
3267 					    SL_ERROR|SL_TRACE,
3268 					    "tcp_bind: no priv for port %d",
3269 					    requested_port);
3270 				}
3271 				tcp_err_ack(tcp, mp, TACCES, 0);
3272 				return;
3273 			}
3274 		}
3275 		user_specified = B_TRUE;
3276 
3277 		if (is_system_labeled()) {
3278 			zone = crgetzone(cr);
3279 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3280 			    IPV6_VERSION, &v6addr,
3281 			    tcps->tcps_netstack->netstack_ip);
3282 			if (addrtype == mlptSingle) {
3283 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3284 				return;
3285 			}
3286 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3287 			    requested_port, addrtype);
3288 		}
3289 	}
3290 
3291 	if (mlptype != mlptSingle) {
3292 		if (secpolicy_net_bindmlp(cr) != 0) {
3293 			if (tcp->tcp_debug) {
3294 				(void) strlog(TCP_MOD_ID, 0, 1,
3295 				    SL_ERROR|SL_TRACE,
3296 				    "tcp_bind: no priv for multilevel port %d",
3297 				    requested_port);
3298 			}
3299 			tcp_err_ack(tcp, mp, TACCES, 0);
3300 			return;
3301 		}
3302 
3303 		/*
3304 		 * If we're specifically binding a shared IP address and the
3305 		 * port is MLP on shared addresses, then check to see if this
3306 		 * zone actually owns the MLP.  Reject if not.
3307 		 */
3308 		if (mlptype == mlptShared && addrtype == mlptShared) {
3309 			/*
3310 			 * No need to handle exclusive-stack zones since
3311 			 * ALL_ZONES only applies to the shared stack.
3312 			 */
3313 			zoneid_t mlpzone;
3314 
3315 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3316 			    htons(mlp_port));
3317 			if (connp->conn_zoneid != mlpzone) {
3318 				if (tcp->tcp_debug) {
3319 					(void) strlog(TCP_MOD_ID, 0, 1,
3320 					    SL_ERROR|SL_TRACE,
3321 					    "tcp_bind: attempt to bind port "
3322 					    "%d on shared addr in zone %d "
3323 					    "(should be %d)",
3324 					    mlp_port, connp->conn_zoneid,
3325 					    mlpzone);
3326 				}
3327 				tcp_err_ack(tcp, mp, TACCES, 0);
3328 				return;
3329 			}
3330 		}
3331 
3332 		if (!user_specified) {
3333 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3334 			    requested_port, B_TRUE);
3335 			if (err != 0) {
3336 				if (tcp->tcp_debug) {
3337 					(void) strlog(TCP_MOD_ID, 0, 1,
3338 					    SL_ERROR|SL_TRACE,
3339 					    "tcp_bind: cannot establish anon "
3340 					    "MLP for port %d",
3341 					    requested_port);
3342 				}
3343 				tcp_err_ack(tcp, mp, TSYSERR, err);
3344 				return;
3345 			}
3346 			connp->conn_anon_port = B_TRUE;
3347 		}
3348 		connp->conn_mlp_type = mlptype;
3349 	}
3350 
3351 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3352 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3353 
3354 	if (allocated_port == 0) {
3355 		connp->conn_mlp_type = mlptSingle;
3356 		if (connp->conn_anon_port) {
3357 			connp->conn_anon_port = B_FALSE;
3358 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3359 			    requested_port, B_FALSE);
3360 		}
3361 		if (bind_to_req_port_only) {
3362 			if (tcp->tcp_debug) {
3363 				(void) strlog(TCP_MOD_ID, 0, 1,
3364 				    SL_ERROR|SL_TRACE,
3365 				    "tcp_bind: requested addr busy");
3366 			}
3367 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3368 		} else {
3369 			/* If we are out of ports, fail the bind. */
3370 			if (tcp->tcp_debug) {
3371 				(void) strlog(TCP_MOD_ID, 0, 1,
3372 				    SL_ERROR|SL_TRACE,
3373 				    "tcp_bind: out of ports?");
3374 			}
3375 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3376 		}
3377 		return;
3378 	}
3379 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3380 do_bind:
3381 	if (!backlog_update) {
3382 		if (tcp->tcp_family == AF_INET)
3383 			sin->sin_port = htons(allocated_port);
3384 		else
3385 			sin6->sin6_port = htons(allocated_port);
3386 	}
3387 	if (tcp->tcp_family == AF_INET) {
3388 		if (tbr->CONIND_number != 0) {
3389 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3390 			    sizeof (sin_t));
3391 		} else {
3392 			/* Just verify the local IP address */
3393 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3394 		}
3395 	} else {
3396 		if (tbr->CONIND_number != 0) {
3397 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3398 			    sizeof (sin6_t));
3399 		} else {
3400 			/* Just verify the local IP address */
3401 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3402 			    IPV6_ADDR_LEN);
3403 		}
3404 	}
3405 	if (mp1 == NULL) {
3406 		if (connp->conn_anon_port) {
3407 			connp->conn_anon_port = B_FALSE;
3408 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3409 			    requested_port, B_FALSE);
3410 		}
3411 		connp->conn_mlp_type = mlptSingle;
3412 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3413 		return;
3414 	}
3415 
3416 	tbr->PRIM_type = T_BIND_ACK;
3417 	mp->b_datap->db_type = M_PCPROTO;
3418 
3419 	/* Chain in the reply mp for tcp_rput() */
3420 	mp1->b_cont = mp;
3421 	mp = mp1;
3422 
3423 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3424 	if (tcp->tcp_conn_req_max) {
3425 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
3426 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
3427 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
3428 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
3429 		/*
3430 		 * If this is a listener, do not reset the eager list
3431 		 * and other stuffs.  Note that we don't check if the
3432 		 * existing eager list meets the new tcp_conn_req_max
3433 		 * requirement.
3434 		 */
3435 		if (tcp->tcp_state != TCPS_LISTEN) {
3436 			tcp->tcp_state = TCPS_LISTEN;
3437 			/* Initialize the chain. Don't need the eager_lock */
3438 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3439 			tcp->tcp_eager_next_drop_q0 = tcp;
3440 			tcp->tcp_eager_prev_drop_q0 = tcp;
3441 			tcp->tcp_second_ctimer_threshold =
3442 			    tcps->tcps_ip_abort_linterval;
3443 		}
3444 	}
3445 
3446 	/*
3447 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3448 	 * processing continues in tcp_rput_other().
3449 	 *
3450 	 * We need to make sure that the conn_recv is set to a non-null
3451 	 * value before we insert the conn into the classifier table.
3452 	 * This is to avoid a race with an incoming packet which does an
3453 	 * ipcl_classify().
3454 	 */
3455 	connp->conn_recv = tcp_conn_request;
3456 	if (tcp->tcp_family == AF_INET6) {
3457 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3458 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3459 	} else {
3460 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3461 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3462 	}
3463 	/*
3464 	 * If the bind cannot complete immediately
3465 	 * IP will arrange to call tcp_rput_other
3466 	 * when the bind completes.
3467 	 */
3468 	if (mp != NULL) {
3469 		tcp_rput_other(tcp, mp);
3470 	} else {
3471 		/*
3472 		 * Bind will be resumed later. Need to ensure
3473 		 * that conn doesn't disappear when that happens.
3474 		 * This will be decremented in ip_resume_tcp_bind().
3475 		 */
3476 		CONN_INC_REF(tcp->tcp_connp);
3477 	}
3478 }
3479 
3480 
3481 /*
3482  * If the "bind_to_req_port_only" parameter is set, if the requested port
3483  * number is available, return it, If not return 0
3484  *
3485  * If "bind_to_req_port_only" parameter is not set and
3486  * If the requested port number is available, return it.  If not, return
3487  * the first anonymous port we happen across.  If no anonymous ports are
3488  * available, return 0. addr is the requested local address, if any.
3489  *
3490  * In either case, when succeeding update the tcp_t to record the port number
3491  * and insert it in the bind hash table.
3492  *
3493  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3494  * without setting SO_REUSEADDR. This is needed so that they
3495  * can be viewed as two independent transport protocols.
3496  */
3497 static in_port_t
3498 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3499     int reuseaddr, boolean_t quick_connect,
3500     boolean_t bind_to_req_port_only, boolean_t user_specified)
3501 {
3502 	/* number of times we have run around the loop */
3503 	int count = 0;
3504 	/* maximum number of times to run around the loop */
3505 	int loopmax;
3506 	conn_t *connp = tcp->tcp_connp;
3507 	zoneid_t zoneid = connp->conn_zoneid;
3508 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3509 
3510 	/*
3511 	 * Lookup for free addresses is done in a loop and "loopmax"
3512 	 * influences how long we spin in the loop
3513 	 */
3514 	if (bind_to_req_port_only) {
3515 		/*
3516 		 * If the requested port is busy, don't bother to look
3517 		 * for a new one. Setting loop maximum count to 1 has
3518 		 * that effect.
3519 		 */
3520 		loopmax = 1;
3521 	} else {
3522 		/*
3523 		 * If the requested port is busy, look for a free one
3524 		 * in the anonymous port range.
3525 		 * Set loopmax appropriately so that one does not look
3526 		 * forever in the case all of the anonymous ports are in use.
3527 		 */
3528 		if (tcp->tcp_anon_priv_bind) {
3529 			/*
3530 			 * loopmax =
3531 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3532 			 */
3533 			loopmax = IPPORT_RESERVED -
3534 			    tcps->tcps_min_anonpriv_port;
3535 		} else {
3536 			loopmax = (tcps->tcps_largest_anon_port -
3537 			    tcps->tcps_smallest_anon_port + 1);
3538 		}
3539 	}
3540 	do {
3541 		uint16_t	lport;
3542 		tf_t		*tbf;
3543 		tcp_t		*ltcp;
3544 		conn_t		*lconnp;
3545 
3546 		lport = htons(port);
3547 
3548 		/*
3549 		 * Ensure that the tcp_t is not currently in the bind hash.
3550 		 * Hold the lock on the hash bucket to ensure that
3551 		 * the duplicate check plus the insertion is an atomic
3552 		 * operation.
3553 		 *
3554 		 * This function does an inline lookup on the bind hash list
3555 		 * Make sure that we access only members of tcp_t
3556 		 * and that we don't look at tcp_tcp, since we are not
3557 		 * doing a CONN_INC_REF.
3558 		 */
3559 		tcp_bind_hash_remove(tcp);
3560 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3561 		mutex_enter(&tbf->tf_lock);
3562 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3563 		    ltcp = ltcp->tcp_bind_hash) {
3564 			boolean_t not_socket;
3565 			boolean_t exclbind;
3566 
3567 			if (lport != ltcp->tcp_lport)
3568 				continue;
3569 
3570 			lconnp = ltcp->tcp_connp;
3571 
3572 			/*
3573 			 * On a labeled system, we must treat bindings to ports
3574 			 * on shared IP addresses by sockets with MAC exemption
3575 			 * privilege as being in all zones, as there's
3576 			 * otherwise no way to identify the right receiver.
3577 			 */
3578 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3579 			    IPCL_ZONE_MATCH(connp,
3580 			    ltcp->tcp_connp->conn_zoneid)) &&
3581 			    !lconnp->conn_mac_exempt &&
3582 			    !connp->conn_mac_exempt)
3583 				continue;
3584 
3585 			/*
3586 			 * If TCP_EXCLBIND is set for either the bound or
3587 			 * binding endpoint, the semantics of bind
3588 			 * is changed according to the following.
3589 			 *
3590 			 * spec = specified address (v4 or v6)
3591 			 * unspec = unspecified address (v4 or v6)
3592 			 * A = specified addresses are different for endpoints
3593 			 *
3594 			 * bound	bind to		allowed
3595 			 * -------------------------------------
3596 			 * unspec	unspec		no
3597 			 * unspec	spec		no
3598 			 * spec		unspec		no
3599 			 * spec		spec		yes if A
3600 			 *
3601 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3602 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3603 			 *
3604 			 * Note:
3605 			 *
3606 			 * 1. Because of TLI semantics, an endpoint can go
3607 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3608 			 * TCPS_BOUND, depending on whether it is originally
3609 			 * a listener or not.  That is why we need to check
3610 			 * for states greater than or equal to TCPS_BOUND
3611 			 * here.
3612 			 *
3613 			 * 2. Ideally, we should only check for state equals
3614 			 * to TCPS_LISTEN. And the following check should be
3615 			 * added.
3616 			 *
3617 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3618 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3619 			 *		...
3620 			 * }
3621 			 *
3622 			 * The semantics will be changed to this.  If the
3623 			 * endpoint on the list is in state not equal to
3624 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3625 			 * set, let the bind succeed.
3626 			 *
3627 			 * Because of (1), we cannot do that for TLI
3628 			 * endpoints.  But we can do that for socket endpoints.
3629 			 * If in future, we can change this going back
3630 			 * semantics, we can use the above check for TLI also.
3631 			 */
3632 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3633 			    TCP_IS_SOCKET(tcp));
3634 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3635 
3636 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3637 			    (exclbind && (not_socket ||
3638 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3639 				if (V6_OR_V4_INADDR_ANY(
3640 				    ltcp->tcp_bound_source_v6) ||
3641 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3642 				    IN6_ARE_ADDR_EQUAL(laddr,
3643 				    &ltcp->tcp_bound_source_v6)) {
3644 					break;
3645 				}
3646 				continue;
3647 			}
3648 
3649 			/*
3650 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3651 			 * have disjoint port number spaces, if *_EXCLBIND
3652 			 * is not set and only if the application binds to a
3653 			 * specific port. We use the same autoassigned port
3654 			 * number space for IPv4 and IPv6 sockets.
3655 			 */
3656 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3657 			    bind_to_req_port_only)
3658 				continue;
3659 
3660 			/*
3661 			 * Ideally, we should make sure that the source
3662 			 * address, remote address, and remote port in the
3663 			 * four tuple for this tcp-connection is unique.
3664 			 * However, trying to find out the local source
3665 			 * address would require too much code duplication
3666 			 * with IP, since IP needs needs to have that code
3667 			 * to support userland TCP implementations.
3668 			 */
3669 			if (quick_connect &&
3670 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3671 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3672 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3673 			    &ltcp->tcp_remote_v6)))
3674 				continue;
3675 
3676 			if (!reuseaddr) {
3677 				/*
3678 				 * No socket option SO_REUSEADDR.
3679 				 * If existing port is bound to
3680 				 * a non-wildcard IP address
3681 				 * and the requesting stream is
3682 				 * bound to a distinct
3683 				 * different IP addresses
3684 				 * (non-wildcard, also), keep
3685 				 * going.
3686 				 */
3687 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3688 				    !V6_OR_V4_INADDR_ANY(
3689 				    ltcp->tcp_bound_source_v6) &&
3690 				    !IN6_ARE_ADDR_EQUAL(laddr,
3691 				    &ltcp->tcp_bound_source_v6))
3692 					continue;
3693 				if (ltcp->tcp_state >= TCPS_BOUND) {
3694 					/*
3695 					 * This port is being used and
3696 					 * its state is >= TCPS_BOUND,
3697 					 * so we can't bind to it.
3698 					 */
3699 					break;
3700 				}
3701 			} else {
3702 				/*
3703 				 * socket option SO_REUSEADDR is set on the
3704 				 * binding tcp_t.
3705 				 *
3706 				 * If two streams are bound to
3707 				 * same IP address or both addr
3708 				 * and bound source are wildcards
3709 				 * (INADDR_ANY), we want to stop
3710 				 * searching.
3711 				 * We have found a match of IP source
3712 				 * address and source port, which is
3713 				 * refused regardless of the
3714 				 * SO_REUSEADDR setting, so we break.
3715 				 */
3716 				if (IN6_ARE_ADDR_EQUAL(laddr,
3717 				    &ltcp->tcp_bound_source_v6) &&
3718 				    (ltcp->tcp_state == TCPS_LISTEN ||
3719 				    ltcp->tcp_state == TCPS_BOUND))
3720 					break;
3721 			}
3722 		}
3723 		if (ltcp != NULL) {
3724 			/* The port number is busy */
3725 			mutex_exit(&tbf->tf_lock);
3726 		} else {
3727 			/*
3728 			 * This port is ours. Insert in fanout and mark as
3729 			 * bound to prevent others from getting the port
3730 			 * number.
3731 			 */
3732 			tcp->tcp_state = TCPS_BOUND;
3733 			tcp->tcp_lport = htons(port);
3734 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3735 
3736 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3737 			    tcp->tcp_lport)] == tbf);
3738 			tcp_bind_hash_insert(tbf, tcp, 1);
3739 
3740 			mutex_exit(&tbf->tf_lock);
3741 
3742 			/*
3743 			 * We don't want tcp_next_port_to_try to "inherit"
3744 			 * a port number supplied by the user in a bind.
3745 			 */
3746 			if (user_specified)
3747 				return (port);
3748 
3749 			/*
3750 			 * This is the only place where tcp_next_port_to_try
3751 			 * is updated. After the update, it may or may not
3752 			 * be in the valid range.
3753 			 */
3754 			if (!tcp->tcp_anon_priv_bind)
3755 				tcps->tcps_next_port_to_try = port + 1;
3756 			return (port);
3757 		}
3758 
3759 		if (tcp->tcp_anon_priv_bind) {
3760 			port = tcp_get_next_priv_port(tcp);
3761 		} else {
3762 			if (count == 0 && user_specified) {
3763 				/*
3764 				 * We may have to return an anonymous port. So
3765 				 * get one to start with.
3766 				 */
3767 				port =
3768 				    tcp_update_next_port(
3769 				    tcps->tcps_next_port_to_try,
3770 				    tcp, B_TRUE);
3771 				user_specified = B_FALSE;
3772 			} else {
3773 				port = tcp_update_next_port(port + 1, tcp,
3774 				    B_FALSE);
3775 			}
3776 		}
3777 		if (port == 0)
3778 			break;
3779 
3780 		/*
3781 		 * Don't let this loop run forever in the case where
3782 		 * all of the anonymous ports are in use.
3783 		 */
3784 	} while (++count < loopmax);
3785 	return (0);
3786 }
3787 
3788 /*
3789  * tcp_clean_death / tcp_close_detached must not be called more than once
3790  * on a tcp. Thus every function that potentially calls tcp_clean_death
3791  * must check for the tcp state before calling tcp_clean_death.
3792  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3793  * tcp_timer_handler, all check for the tcp state.
3794  */
3795 /* ARGSUSED */
3796 void
3797 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3798 {
3799 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3800 
3801 	freemsg(mp);
3802 	if (tcp->tcp_state > TCPS_BOUND)
3803 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3804 		    ETIMEDOUT, 5);
3805 }
3806 
3807 /*
3808  * We are dying for some reason.  Try to do it gracefully.  (May be called
3809  * as writer.)
3810  *
3811  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3812  * done by a service procedure).
3813  * TBD - Should the return value distinguish between the tcp_t being
3814  * freed and it being reinitialized?
3815  */
3816 static int
3817 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3818 {
3819 	mblk_t	*mp;
3820 	queue_t	*q;
3821 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3822 	sodirect_t	*sodp;
3823 
3824 	TCP_CLD_STAT(tag);
3825 
3826 #if TCP_TAG_CLEAN_DEATH
3827 	tcp->tcp_cleandeathtag = tag;
3828 #endif
3829 
3830 	if (tcp->tcp_fused)
3831 		tcp_unfuse(tcp);
3832 
3833 	if (tcp->tcp_linger_tid != 0 &&
3834 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3835 		tcp_stop_lingering(tcp);
3836 	}
3837 
3838 	ASSERT(tcp != NULL);
3839 	ASSERT((tcp->tcp_family == AF_INET &&
3840 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3841 	    (tcp->tcp_family == AF_INET6 &&
3842 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3843 	    tcp->tcp_ipversion == IPV6_VERSION)));
3844 
3845 	if (TCP_IS_DETACHED(tcp)) {
3846 		if (tcp->tcp_hard_binding) {
3847 			/*
3848 			 * Its an eager that we are dealing with. We close the
3849 			 * eager but in case a conn_ind has already gone to the
3850 			 * listener, let tcp_accept_finish() send a discon_ind
3851 			 * to the listener and drop the last reference. If the
3852 			 * listener doesn't even know about the eager i.e. the
3853 			 * conn_ind hasn't gone up, blow away the eager and drop
3854 			 * the last reference as well. If the conn_ind has gone
3855 			 * up, state should be BOUND. tcp_accept_finish
3856 			 * will figure out that the connection has received a
3857 			 * RST and will send a DISCON_IND to the application.
3858 			 */
3859 			tcp_closei_local(tcp);
3860 			if (!tcp->tcp_tconnind_started) {
3861 				CONN_DEC_REF(tcp->tcp_connp);
3862 			} else {
3863 				tcp->tcp_state = TCPS_BOUND;
3864 			}
3865 		} else {
3866 			tcp_close_detached(tcp);
3867 		}
3868 		return (0);
3869 	}
3870 
3871 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3872 
3873 	/* If sodirect, not anymore */
3874 	SOD_PTR_ENTER(tcp, sodp);
3875 	if (sodp != NULL) {
3876 		tcp->tcp_sodirect = NULL;
3877 		mutex_exit(sodp->sod_lockp);
3878 	}
3879 
3880 	q = tcp->tcp_rq;
3881 
3882 	/* Trash all inbound data */
3883 	flushq(q, FLUSHALL);
3884 
3885 	/*
3886 	 * If we are at least part way open and there is error
3887 	 * (err==0 implies no error)
3888 	 * notify our client by a T_DISCON_IND.
3889 	 */
3890 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3891 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3892 		    !TCP_IS_SOCKET(tcp)) {
3893 			/*
3894 			 * Send M_FLUSH according to TPI. Because sockets will
3895 			 * (and must) ignore FLUSHR we do that only for TPI
3896 			 * endpoints and sockets in STREAMS mode.
3897 			 */
3898 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3899 		}
3900 		if (tcp->tcp_debug) {
3901 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3902 			    "tcp_clean_death: discon err %d", err);
3903 		}
3904 		mp = mi_tpi_discon_ind(NULL, err, 0);
3905 		if (mp != NULL) {
3906 			putnext(q, mp);
3907 		} else {
3908 			if (tcp->tcp_debug) {
3909 				(void) strlog(TCP_MOD_ID, 0, 1,
3910 				    SL_ERROR|SL_TRACE,
3911 				    "tcp_clean_death, sending M_ERROR");
3912 			}
3913 			(void) putnextctl1(q, M_ERROR, EPROTO);
3914 		}
3915 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3916 			/* SYN_SENT or SYN_RCVD */
3917 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3918 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3919 			/* ESTABLISHED or CLOSE_WAIT */
3920 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3921 		}
3922 	}
3923 
3924 	tcp_reinit(tcp);
3925 	return (-1);
3926 }
3927 
3928 /*
3929  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3930  * to expire, stop the wait and finish the close.
3931  */
3932 static void
3933 tcp_stop_lingering(tcp_t *tcp)
3934 {
3935 	clock_t	delta = 0;
3936 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3937 
3938 	tcp->tcp_linger_tid = 0;
3939 	if (tcp->tcp_state > TCPS_LISTEN) {
3940 		tcp_acceptor_hash_remove(tcp);
3941 		mutex_enter(&tcp->tcp_non_sq_lock);
3942 		if (tcp->tcp_flow_stopped) {
3943 			tcp_clrqfull(tcp);
3944 		}
3945 		mutex_exit(&tcp->tcp_non_sq_lock);
3946 
3947 		if (tcp->tcp_timer_tid != 0) {
3948 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3949 			tcp->tcp_timer_tid = 0;
3950 		}
3951 		/*
3952 		 * Need to cancel those timers which will not be used when
3953 		 * TCP is detached.  This has to be done before the tcp_wq
3954 		 * is set to the global queue.
3955 		 */
3956 		tcp_timers_stop(tcp);
3957 
3958 
3959 		tcp->tcp_detached = B_TRUE;
3960 		ASSERT(tcps->tcps_g_q != NULL);
3961 		tcp->tcp_rq = tcps->tcps_g_q;
3962 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3963 
3964 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3965 			tcp_time_wait_append(tcp);
3966 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3967 			goto finish;
3968 		}
3969 
3970 		/*
3971 		 * If delta is zero the timer event wasn't executed and was
3972 		 * successfully canceled. In this case we need to restart it
3973 		 * with the minimal delta possible.
3974 		 */
3975 		if (delta >= 0) {
3976 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3977 			    delta ? delta : 1);
3978 		}
3979 	} else {
3980 		tcp_closei_local(tcp);
3981 		CONN_DEC_REF(tcp->tcp_connp);
3982 	}
3983 finish:
3984 	/* Signal closing thread that it can complete close */
3985 	mutex_enter(&tcp->tcp_closelock);
3986 	tcp->tcp_detached = B_TRUE;
3987 	ASSERT(tcps->tcps_g_q != NULL);
3988 	tcp->tcp_rq = tcps->tcps_g_q;
3989 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3990 	tcp->tcp_closed = 1;
3991 	cv_signal(&tcp->tcp_closecv);
3992 	mutex_exit(&tcp->tcp_closelock);
3993 }
3994 
3995 /*
3996  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3997  * expires.
3998  */
3999 static void
4000 tcp_close_linger_timeout(void *arg)
4001 {
4002 	conn_t	*connp = (conn_t *)arg;
4003 	tcp_t 	*tcp = connp->conn_tcp;
4004 
4005 	tcp->tcp_client_errno = ETIMEDOUT;
4006 	tcp_stop_lingering(tcp);
4007 }
4008 
4009 static int
4010 tcp_close(queue_t *q, int flags)
4011 {
4012 	conn_t		*connp = Q_TO_CONN(q);
4013 	tcp_t		*tcp = connp->conn_tcp;
4014 	mblk_t 		*mp = &tcp->tcp_closemp;
4015 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4016 	mblk_t		*bp;
4017 
4018 	ASSERT(WR(q)->q_next == NULL);
4019 	ASSERT(connp->conn_ref >= 2);
4020 
4021 	/*
4022 	 * We are being closed as /dev/tcp or /dev/tcp6.
4023 	 *
4024 	 * Mark the conn as closing. ill_pending_mp_add will not
4025 	 * add any mp to the pending mp list, after this conn has
4026 	 * started closing. Same for sq_pending_mp_add
4027 	 */
4028 	mutex_enter(&connp->conn_lock);
4029 	connp->conn_state_flags |= CONN_CLOSING;
4030 	if (connp->conn_oper_pending_ill != NULL)
4031 		conn_ioctl_cleanup_reqd = B_TRUE;
4032 	CONN_INC_REF_LOCKED(connp);
4033 	mutex_exit(&connp->conn_lock);
4034 	tcp->tcp_closeflags = (uint8_t)flags;
4035 	ASSERT(connp->conn_ref >= 3);
4036 
4037 	/*
4038 	 * tcp_closemp_used is used below without any protection of a lock
4039 	 * as we don't expect any one else to use it concurrently at this
4040 	 * point otherwise it would be a major defect.
4041 	 */
4042 
4043 	if (mp->b_prev == NULL)
4044 		tcp->tcp_closemp_used = B_TRUE;
4045 	else
4046 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
4047 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
4048 
4049 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
4050 
4051 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4052 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4053 
4054 	mutex_enter(&tcp->tcp_closelock);
4055 	while (!tcp->tcp_closed) {
4056 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
4057 			/*
4058 			 * The cv_wait_sig() was interrupted. We now do the
4059 			 * following:
4060 			 *
4061 			 * 1) If the endpoint was lingering, we allow this
4062 			 * to be interrupted by cancelling the linger timeout
4063 			 * and closing normally.
4064 			 *
4065 			 * 2) Revert to calling cv_wait()
4066 			 *
4067 			 * We revert to using cv_wait() to avoid an
4068 			 * infinite loop which can occur if the calling
4069 			 * thread is higher priority than the squeue worker
4070 			 * thread and is bound to the same cpu.
4071 			 */
4072 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
4073 				mutex_exit(&tcp->tcp_closelock);
4074 				/* Entering squeue, bump ref count. */
4075 				CONN_INC_REF(connp);
4076 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
4077 				squeue_enter(connp->conn_sqp, bp,
4078 				    tcp_linger_interrupted, connp,
4079 				    SQTAG_IP_TCP_CLOSE);
4080 				mutex_enter(&tcp->tcp_closelock);
4081 			}
4082 			break;
4083 		}
4084 	}
4085 	while (!tcp->tcp_closed)
4086 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
4087 	mutex_exit(&tcp->tcp_closelock);
4088 
4089 	/*
4090 	 * In the case of listener streams that have eagers in the q or q0
4091 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4092 	 * tcp_wq of the eagers point to our queues. By waiting for the
4093 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4094 	 * up their queue pointers and also dropped their references to us.
4095 	 */
4096 	if (tcp->tcp_wait_for_eagers) {
4097 		mutex_enter(&connp->conn_lock);
4098 		while (connp->conn_ref != 1) {
4099 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4100 		}
4101 		mutex_exit(&connp->conn_lock);
4102 	}
4103 	/*
4104 	 * ioctl cleanup. The mp is queued in the
4105 	 * ill_pending_mp or in the sq_pending_mp.
4106 	 */
4107 	if (conn_ioctl_cleanup_reqd)
4108 		conn_ioctl_cleanup(connp);
4109 
4110 	qprocsoff(q);
4111 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4112 
4113 	tcp->tcp_cpid = -1;
4114 
4115 	/*
4116 	 * Drop IP's reference on the conn. This is the last reference
4117 	 * on the connp if the state was less than established. If the
4118 	 * connection has gone into timewait state, then we will have
4119 	 * one ref for the TCP and one more ref (total of two) for the
4120 	 * classifier connected hash list (a timewait connections stays
4121 	 * in connected hash till closed).
4122 	 *
4123 	 * We can't assert the references because there might be other
4124 	 * transient reference places because of some walkers or queued
4125 	 * packets in squeue for the timewait state.
4126 	 */
4127 	CONN_DEC_REF(connp);
4128 	q->q_ptr = WR(q)->q_ptr = NULL;
4129 	return (0);
4130 }
4131 
4132 static int
4133 tcpclose_accept(queue_t *q)
4134 {
4135 	vmem_t	*minor_arena;
4136 	dev_t	conn_dev;
4137 
4138 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4139 
4140 	/*
4141 	 * We had opened an acceptor STREAM for sockfs which is
4142 	 * now being closed due to some error.
4143 	 */
4144 	qprocsoff(q);
4145 
4146 	minor_arena = (vmem_t *)WR(q)->q_ptr;
4147 	conn_dev = (dev_t)RD(q)->q_ptr;
4148 	ASSERT(minor_arena != NULL);
4149 	ASSERT(conn_dev != 0);
4150 	inet_minor_free(minor_arena, conn_dev);
4151 	q->q_ptr = WR(q)->q_ptr = NULL;
4152 	return (0);
4153 }
4154 
4155 /*
4156  * Called by tcp_close() routine via squeue when lingering is
4157  * interrupted by a signal.
4158  */
4159 
4160 /* ARGSUSED */
4161 static void
4162 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4163 {
4164 	conn_t	*connp = (conn_t *)arg;
4165 	tcp_t	*tcp = connp->conn_tcp;
4166 
4167 	freeb(mp);
4168 	if (tcp->tcp_linger_tid != 0 &&
4169 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4170 		tcp_stop_lingering(tcp);
4171 		tcp->tcp_client_errno = EINTR;
4172 	}
4173 }
4174 
4175 /*
4176  * Called by streams close routine via squeues when our client blows off her
4177  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4178  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4179  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4180  * acked.
4181  *
4182  * NOTE: tcp_close potentially returns error when lingering.
4183  * However, the stream head currently does not pass these errors
4184  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4185  * errors to the application (from tsleep()) and not errors
4186  * like ECONNRESET caused by receiving a reset packet.
4187  */
4188 
4189 /* ARGSUSED */
4190 static void
4191 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4192 {
4193 	char	*msg;
4194 	conn_t	*connp = (conn_t *)arg;
4195 	tcp_t	*tcp = connp->conn_tcp;
4196 	clock_t	delta = 0;
4197 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4198 
4199 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4200 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4201 
4202 	mutex_enter(&tcp->tcp_eager_lock);
4203 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4204 		/* Cleanup for listener */
4205 		tcp_eager_cleanup(tcp, 0);
4206 		tcp->tcp_wait_for_eagers = 1;
4207 	}
4208 	mutex_exit(&tcp->tcp_eager_lock);
4209 
4210 	connp->conn_mdt_ok = B_FALSE;
4211 	tcp->tcp_mdt = B_FALSE;
4212 
4213 	connp->conn_lso_ok = B_FALSE;
4214 	tcp->tcp_lso = B_FALSE;
4215 
4216 	msg = NULL;
4217 	switch (tcp->tcp_state) {
4218 	case TCPS_CLOSED:
4219 	case TCPS_IDLE:
4220 	case TCPS_BOUND:
4221 	case TCPS_LISTEN:
4222 		break;
4223 	case TCPS_SYN_SENT:
4224 		msg = "tcp_close, during connect";
4225 		break;
4226 	case TCPS_SYN_RCVD:
4227 		/*
4228 		 * Close during the connect 3-way handshake
4229 		 * but here there may or may not be pending data
4230 		 * already on queue. Process almost same as in
4231 		 * the ESTABLISHED state.
4232 		 */
4233 		/* FALLTHRU */
4234 	default:
4235 		if (tcp->tcp_sodirect != NULL) {
4236 			/* Ok, no more sodirect */
4237 			tcp->tcp_sodirect = NULL;
4238 		}
4239 
4240 		if (tcp->tcp_fused)
4241 			tcp_unfuse(tcp);
4242 
4243 		/*
4244 		 * If SO_LINGER has set a zero linger time, abort the
4245 		 * connection with a reset.
4246 		 */
4247 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4248 			msg = "tcp_close, zero lingertime";
4249 			break;
4250 		}
4251 
4252 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4253 		/*
4254 		 * Abort connection if there is unread data queued.
4255 		 */
4256 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4257 			msg = "tcp_close, unread data";
4258 			break;
4259 		}
4260 		/*
4261 		 * tcp_hard_bound is now cleared thus all packets go through
4262 		 * tcp_lookup. This fact is used by tcp_detach below.
4263 		 *
4264 		 * We have done a qwait() above which could have possibly
4265 		 * drained more messages in turn causing transition to a
4266 		 * different state. Check whether we have to do the rest
4267 		 * of the processing or not.
4268 		 */
4269 		if (tcp->tcp_state <= TCPS_LISTEN)
4270 			break;
4271 
4272 		/*
4273 		 * Transmit the FIN before detaching the tcp_t.
4274 		 * After tcp_detach returns this queue/perimeter
4275 		 * no longer owns the tcp_t thus others can modify it.
4276 		 */
4277 		(void) tcp_xmit_end(tcp);
4278 
4279 		/*
4280 		 * If lingering on close then wait until the fin is acked,
4281 		 * the SO_LINGER time passes, or a reset is sent/received.
4282 		 */
4283 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4284 		    !(tcp->tcp_fin_acked) &&
4285 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4286 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4287 				tcp->tcp_client_errno = EWOULDBLOCK;
4288 			} else if (tcp->tcp_client_errno == 0) {
4289 
4290 				ASSERT(tcp->tcp_linger_tid == 0);
4291 
4292 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4293 				    tcp_close_linger_timeout,
4294 				    tcp->tcp_lingertime * hz);
4295 
4296 				/* tcp_close_linger_timeout will finish close */
4297 				if (tcp->tcp_linger_tid == 0)
4298 					tcp->tcp_client_errno = ENOSR;
4299 				else
4300 					return;
4301 			}
4302 
4303 			/*
4304 			 * Check if we need to detach or just close
4305 			 * the instance.
4306 			 */
4307 			if (tcp->tcp_state <= TCPS_LISTEN)
4308 				break;
4309 		}
4310 
4311 		/*
4312 		 * Make sure that no other thread will access the tcp_rq of
4313 		 * this instance (through lookups etc.) as tcp_rq will go
4314 		 * away shortly.
4315 		 */
4316 		tcp_acceptor_hash_remove(tcp);
4317 
4318 		mutex_enter(&tcp->tcp_non_sq_lock);
4319 		if (tcp->tcp_flow_stopped) {
4320 			tcp_clrqfull(tcp);
4321 		}
4322 		mutex_exit(&tcp->tcp_non_sq_lock);
4323 
4324 		if (tcp->tcp_timer_tid != 0) {
4325 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4326 			tcp->tcp_timer_tid = 0;
4327 		}
4328 		/*
4329 		 * Need to cancel those timers which will not be used when
4330 		 * TCP is detached.  This has to be done before the tcp_wq
4331 		 * is set to the global queue.
4332 		 */
4333 		tcp_timers_stop(tcp);
4334 
4335 		tcp->tcp_detached = B_TRUE;
4336 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4337 			tcp_time_wait_append(tcp);
4338 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4339 			ASSERT(connp->conn_ref >= 3);
4340 			goto finish;
4341 		}
4342 
4343 		/*
4344 		 * If delta is zero the timer event wasn't executed and was
4345 		 * successfully canceled. In this case we need to restart it
4346 		 * with the minimal delta possible.
4347 		 */
4348 		if (delta >= 0)
4349 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4350 			    delta ? delta : 1);
4351 
4352 		ASSERT(connp->conn_ref >= 3);
4353 		goto finish;
4354 	}
4355 
4356 	/* Detach did not complete. Still need to remove q from stream. */
4357 	if (msg) {
4358 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4359 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4360 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4361 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4362 		    tcp->tcp_state == TCPS_SYN_RCVD)
4363 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4364 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4365 	}
4366 
4367 	tcp_closei_local(tcp);
4368 	CONN_DEC_REF(connp);
4369 	ASSERT(connp->conn_ref >= 2);
4370 
4371 finish:
4372 	/*
4373 	 * Although packets are always processed on the correct
4374 	 * tcp's perimeter and access is serialized via squeue's,
4375 	 * IP still needs a queue when sending packets in time_wait
4376 	 * state so use WR(tcps_g_q) till ip_output() can be
4377 	 * changed to deal with just connp. For read side, we
4378 	 * could have set tcp_rq to NULL but there are some cases
4379 	 * in tcp_rput_data() from early days of this code which
4380 	 * do a putnext without checking if tcp is closed. Those
4381 	 * need to be identified before both tcp_rq and tcp_wq
4382 	 * can be set to NULL and tcps_g_q can disappear forever.
4383 	 */
4384 	mutex_enter(&tcp->tcp_closelock);
4385 	/*
4386 	 * Don't change the queues in the case of a listener that has
4387 	 * eagers in its q or q0. It could surprise the eagers.
4388 	 * Instead wait for the eagers outside the squeue.
4389 	 */
4390 	if (!tcp->tcp_wait_for_eagers) {
4391 		tcp->tcp_detached = B_TRUE;
4392 		/*
4393 		 * When default queue is closing we set tcps_g_q to NULL
4394 		 * after the close is done.
4395 		 */
4396 		ASSERT(tcps->tcps_g_q != NULL);
4397 		tcp->tcp_rq = tcps->tcps_g_q;
4398 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4399 	}
4400 
4401 	/* Signal tcp_close() to finish closing. */
4402 	tcp->tcp_closed = 1;
4403 	cv_signal(&tcp->tcp_closecv);
4404 	mutex_exit(&tcp->tcp_closelock);
4405 }
4406 
4407 
4408 /*
4409  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4410  * Some stream heads get upset if they see these later on as anything but NULL.
4411  */
4412 static void
4413 tcp_close_mpp(mblk_t **mpp)
4414 {
4415 	mblk_t	*mp;
4416 
4417 	if ((mp = *mpp) != NULL) {
4418 		do {
4419 			mp->b_next = NULL;
4420 			mp->b_prev = NULL;
4421 		} while ((mp = mp->b_cont) != NULL);
4422 
4423 		mp = *mpp;
4424 		*mpp = NULL;
4425 		freemsg(mp);
4426 	}
4427 }
4428 
4429 /* Do detached close. */
4430 static void
4431 tcp_close_detached(tcp_t *tcp)
4432 {
4433 	if (tcp->tcp_fused)
4434 		tcp_unfuse(tcp);
4435 
4436 	/*
4437 	 * Clustering code serializes TCP disconnect callbacks and
4438 	 * cluster tcp list walks by blocking a TCP disconnect callback
4439 	 * if a cluster tcp list walk is in progress. This ensures
4440 	 * accurate accounting of TCPs in the cluster code even though
4441 	 * the TCP list walk itself is not atomic.
4442 	 */
4443 	tcp_closei_local(tcp);
4444 	CONN_DEC_REF(tcp->tcp_connp);
4445 }
4446 
4447 /*
4448  * Stop all TCP timers, and free the timer mblks if requested.
4449  */
4450 void
4451 tcp_timers_stop(tcp_t *tcp)
4452 {
4453 	if (tcp->tcp_timer_tid != 0) {
4454 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4455 		tcp->tcp_timer_tid = 0;
4456 	}
4457 	if (tcp->tcp_ka_tid != 0) {
4458 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4459 		tcp->tcp_ka_tid = 0;
4460 	}
4461 	if (tcp->tcp_ack_tid != 0) {
4462 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4463 		tcp->tcp_ack_tid = 0;
4464 	}
4465 	if (tcp->tcp_push_tid != 0) {
4466 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4467 		tcp->tcp_push_tid = 0;
4468 	}
4469 }
4470 
4471 /*
4472  * The tcp_t is going away. Remove it from all lists and set it
4473  * to TCPS_CLOSED. The freeing up of memory is deferred until
4474  * tcp_inactive. This is needed since a thread in tcp_rput might have
4475  * done a CONN_INC_REF on this structure before it was removed from the
4476  * hashes.
4477  */
4478 static void
4479 tcp_closei_local(tcp_t *tcp)
4480 {
4481 	ire_t 	*ire;
4482 	conn_t	*connp = tcp->tcp_connp;
4483 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4484 
4485 	if (!TCP_IS_SOCKET(tcp))
4486 		tcp_acceptor_hash_remove(tcp);
4487 
4488 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4489 	tcp->tcp_ibsegs = 0;
4490 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4491 	tcp->tcp_obsegs = 0;
4492 
4493 	/*
4494 	 * If we are an eager connection hanging off a listener that
4495 	 * hasn't formally accepted the connection yet, get off his
4496 	 * list and blow off any data that we have accumulated.
4497 	 */
4498 	if (tcp->tcp_listener != NULL) {
4499 		tcp_t	*listener = tcp->tcp_listener;
4500 		mutex_enter(&listener->tcp_eager_lock);
4501 		/*
4502 		 * tcp_tconnind_started == B_TRUE means that the
4503 		 * conn_ind has already gone to listener. At
4504 		 * this point, eager will be closed but we
4505 		 * leave it in listeners eager list so that
4506 		 * if listener decides to close without doing
4507 		 * accept, we can clean this up. In tcp_wput_accept
4508 		 * we take care of the case of accept on closed
4509 		 * eager.
4510 		 */
4511 		if (!tcp->tcp_tconnind_started) {
4512 			tcp_eager_unlink(tcp);
4513 			mutex_exit(&listener->tcp_eager_lock);
4514 			/*
4515 			 * We don't want to have any pointers to the
4516 			 * listener queue, after we have released our
4517 			 * reference on the listener
4518 			 */
4519 			ASSERT(tcps->tcps_g_q != NULL);
4520 			tcp->tcp_rq = tcps->tcps_g_q;
4521 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4522 			CONN_DEC_REF(listener->tcp_connp);
4523 		} else {
4524 			mutex_exit(&listener->tcp_eager_lock);
4525 		}
4526 	}
4527 
4528 	/* Stop all the timers */
4529 	tcp_timers_stop(tcp);
4530 
4531 	if (tcp->tcp_state == TCPS_LISTEN) {
4532 		if (tcp->tcp_ip_addr_cache) {
4533 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4534 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4535 			tcp->tcp_ip_addr_cache = NULL;
4536 		}
4537 	}
4538 	mutex_enter(&tcp->tcp_non_sq_lock);
4539 	if (tcp->tcp_flow_stopped)
4540 		tcp_clrqfull(tcp);
4541 	mutex_exit(&tcp->tcp_non_sq_lock);
4542 
4543 	tcp_bind_hash_remove(tcp);
4544 	/*
4545 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4546 	 * is trying to remove this tcp from the time wait list, we will
4547 	 * block in tcp_time_wait_remove while trying to acquire the
4548 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4549 	 * requires the ipcl_hash_remove to be ordered after the
4550 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4551 	 */
4552 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4553 		(void) tcp_time_wait_remove(tcp, NULL);
4554 	CL_INET_DISCONNECT(tcp);
4555 	ipcl_hash_remove(connp);
4556 
4557 	/*
4558 	 * Delete the cached ire in conn_ire_cache and also mark
4559 	 * the conn as CONDEMNED
4560 	 */
4561 	mutex_enter(&connp->conn_lock);
4562 	connp->conn_state_flags |= CONN_CONDEMNED;
4563 	ire = connp->conn_ire_cache;
4564 	connp->conn_ire_cache = NULL;
4565 	mutex_exit(&connp->conn_lock);
4566 	if (ire != NULL)
4567 		IRE_REFRELE_NOTR(ire);
4568 
4569 	/* Need to cleanup any pending ioctls */
4570 	ASSERT(tcp->tcp_time_wait_next == NULL);
4571 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4572 	ASSERT(tcp->tcp_time_wait_expire == 0);
4573 	tcp->tcp_state = TCPS_CLOSED;
4574 
4575 	/* Release any SSL context */
4576 	if (tcp->tcp_kssl_ent != NULL) {
4577 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4578 		tcp->tcp_kssl_ent = NULL;
4579 	}
4580 	if (tcp->tcp_kssl_ctx != NULL) {
4581 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4582 		tcp->tcp_kssl_ctx = NULL;
4583 	}
4584 	tcp->tcp_kssl_pending = B_FALSE;
4585 
4586 	tcp_ipsec_cleanup(tcp);
4587 }
4588 
4589 /*
4590  * tcp is dying (called from ipcl_conn_destroy and error cases).
4591  * Free the tcp_t in either case.
4592  */
4593 void
4594 tcp_free(tcp_t *tcp)
4595 {
4596 	mblk_t	*mp;
4597 	ip6_pkt_t	*ipp;
4598 
4599 	ASSERT(tcp != NULL);
4600 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4601 
4602 	tcp->tcp_rq = NULL;
4603 	tcp->tcp_wq = NULL;
4604 
4605 	tcp_close_mpp(&tcp->tcp_xmit_head);
4606 	tcp_close_mpp(&tcp->tcp_reass_head);
4607 	if (tcp->tcp_rcv_list != NULL) {
4608 		/* Free b_next chain */
4609 		tcp_close_mpp(&tcp->tcp_rcv_list);
4610 	}
4611 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4612 		freemsg(mp);
4613 	}
4614 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4615 		freemsg(mp);
4616 	}
4617 
4618 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4619 		freeb(tcp->tcp_fused_sigurg_mp);
4620 		tcp->tcp_fused_sigurg_mp = NULL;
4621 	}
4622 
4623 	if (tcp->tcp_sack_info != NULL) {
4624 		if (tcp->tcp_notsack_list != NULL) {
4625 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4626 		}
4627 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4628 	}
4629 
4630 	if (tcp->tcp_hopopts != NULL) {
4631 		mi_free(tcp->tcp_hopopts);
4632 		tcp->tcp_hopopts = NULL;
4633 		tcp->tcp_hopoptslen = 0;
4634 	}
4635 	ASSERT(tcp->tcp_hopoptslen == 0);
4636 	if (tcp->tcp_dstopts != NULL) {
4637 		mi_free(tcp->tcp_dstopts);
4638 		tcp->tcp_dstopts = NULL;
4639 		tcp->tcp_dstoptslen = 0;
4640 	}
4641 	ASSERT(tcp->tcp_dstoptslen == 0);
4642 	if (tcp->tcp_rtdstopts != NULL) {
4643 		mi_free(tcp->tcp_rtdstopts);
4644 		tcp->tcp_rtdstopts = NULL;
4645 		tcp->tcp_rtdstoptslen = 0;
4646 	}
4647 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4648 	if (tcp->tcp_rthdr != NULL) {
4649 		mi_free(tcp->tcp_rthdr);
4650 		tcp->tcp_rthdr = NULL;
4651 		tcp->tcp_rthdrlen = 0;
4652 	}
4653 	ASSERT(tcp->tcp_rthdrlen == 0);
4654 
4655 	ipp = &tcp->tcp_sticky_ipp;
4656 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4657 	    IPPF_RTHDR))
4658 		ip6_pkt_free(ipp);
4659 
4660 	/*
4661 	 * Free memory associated with the tcp/ip header template.
4662 	 */
4663 
4664 	if (tcp->tcp_iphc != NULL)
4665 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4666 
4667 	/*
4668 	 * Following is really a blowing away a union.
4669 	 * It happens to have exactly two members of identical size
4670 	 * the following code is enough.
4671 	 */
4672 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4673 }
4674 
4675 
4676 /*
4677  * Put a connection confirmation message upstream built from the
4678  * address information within 'iph' and 'tcph'.  Report our success or failure.
4679  */
4680 static boolean_t
4681 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4682     mblk_t **defermp)
4683 {
4684 	sin_t	sin;
4685 	sin6_t	sin6;
4686 	mblk_t	*mp;
4687 	char	*optp = NULL;
4688 	int	optlen = 0;
4689 	cred_t	*cr;
4690 
4691 	if (defermp != NULL)
4692 		*defermp = NULL;
4693 
4694 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4695 		/*
4696 		 * Return in T_CONN_CON results of option negotiation through
4697 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4698 		 * negotiation, then what is received from remote end needs
4699 		 * to be taken into account but there is no such thing (yet?)
4700 		 * in our TCP/IP.
4701 		 * Note: We do not use mi_offset_param() here as
4702 		 * tcp_opts_conn_req contents do not directly come from
4703 		 * an application and are either generated in kernel or
4704 		 * from user input that was already verified.
4705 		 */
4706 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4707 		optp = (char *)(mp->b_rptr +
4708 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4709 		optlen = (int)
4710 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4711 	}
4712 
4713 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4714 		ipha_t *ipha = (ipha_t *)iphdr;
4715 
4716 		/* packet is IPv4 */
4717 		if (tcp->tcp_family == AF_INET) {
4718 			sin = sin_null;
4719 			sin.sin_addr.s_addr = ipha->ipha_src;
4720 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4721 			sin.sin_family = AF_INET;
4722 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4723 			    (int)sizeof (sin_t), optp, optlen);
4724 		} else {
4725 			sin6 = sin6_null;
4726 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4727 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4728 			sin6.sin6_family = AF_INET6;
4729 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4730 			    (int)sizeof (sin6_t), optp, optlen);
4731 
4732 		}
4733 	} else {
4734 		ip6_t	*ip6h = (ip6_t *)iphdr;
4735 
4736 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4737 		ASSERT(tcp->tcp_family == AF_INET6);
4738 		sin6 = sin6_null;
4739 		sin6.sin6_addr = ip6h->ip6_src;
4740 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4741 		sin6.sin6_family = AF_INET6;
4742 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4743 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4744 		    (int)sizeof (sin6_t), optp, optlen);
4745 	}
4746 
4747 	if (!mp)
4748 		return (B_FALSE);
4749 
4750 	if ((cr = DB_CRED(idmp)) != NULL) {
4751 		mblk_setcred(mp, cr);
4752 		DB_CPID(mp) = DB_CPID(idmp);
4753 	}
4754 
4755 	if (defermp == NULL)
4756 		putnext(tcp->tcp_rq, mp);
4757 	else
4758 		*defermp = mp;
4759 
4760 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4761 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4762 	return (B_TRUE);
4763 }
4764 
4765 /*
4766  * Defense for the SYN attack -
4767  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4768  *    one from the list of droppable eagers. This list is a subset of q0.
4769  *    see comments before the definition of MAKE_DROPPABLE().
4770  * 2. Don't drop a SYN request before its first timeout. This gives every
4771  *    request at least til the first timeout to complete its 3-way handshake.
4772  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4773  *    requests currently on the queue that has timed out. This will be used
4774  *    as an indicator of whether an attack is under way, so that appropriate
4775  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4776  *    either when eager goes into ESTABLISHED, or gets freed up.)
4777  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4778  *    # of timeout drops back to <= q0len/32 => SYN alert off
4779  */
4780 static boolean_t
4781 tcp_drop_q0(tcp_t *tcp)
4782 {
4783 	tcp_t	*eager;
4784 	mblk_t	*mp;
4785 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4786 
4787 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4788 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4789 
4790 	/* Pick oldest eager from the list of droppable eagers */
4791 	eager = tcp->tcp_eager_prev_drop_q0;
4792 
4793 	/* If list is empty. return B_FALSE */
4794 	if (eager == tcp) {
4795 		return (B_FALSE);
4796 	}
4797 
4798 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4799 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4800 		return (B_FALSE);
4801 
4802 	/*
4803 	 * Take this eager out from the list of droppable eagers since we are
4804 	 * going to drop it.
4805 	 */
4806 	MAKE_UNDROPPABLE(eager);
4807 
4808 	if (tcp->tcp_debug) {
4809 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4810 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4811 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4812 		    tcp->tcp_conn_req_cnt_q0,
4813 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4814 	}
4815 
4816 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4817 
4818 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4819 	CONN_INC_REF(eager->tcp_connp);
4820 
4821 	/* Mark the IRE created for this SYN request temporary */
4822 	tcp_ip_ire_mark_advice(eager);
4823 	squeue_fill(eager->tcp_connp->conn_sqp, mp,
4824 	    tcp_clean_death_wrapper, eager->tcp_connp, SQTAG_TCP_DROP_Q0);
4825 
4826 	return (B_TRUE);
4827 }
4828 
4829 int
4830 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4831     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4832 {
4833 	tcp_t 		*ltcp = lconnp->conn_tcp;
4834 	tcp_t		*tcp = connp->conn_tcp;
4835 	mblk_t		*tpi_mp;
4836 	ipha_t		*ipha;
4837 	ip6_t		*ip6h;
4838 	sin6_t 		sin6;
4839 	in6_addr_t 	v6dst;
4840 	int		err;
4841 	int		ifindex = 0;
4842 	cred_t		*cr;
4843 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4844 
4845 	if (ipvers == IPV4_VERSION) {
4846 		ipha = (ipha_t *)mp->b_rptr;
4847 
4848 		connp->conn_send = ip_output;
4849 		connp->conn_recv = tcp_input;
4850 
4851 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4852 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4853 
4854 		sin6 = sin6_null;
4855 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4856 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4857 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4858 		sin6.sin6_family = AF_INET6;
4859 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4860 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4861 		if (tcp->tcp_recvdstaddr) {
4862 			sin6_t	sin6d;
4863 
4864 			sin6d = sin6_null;
4865 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4866 			    &sin6d.sin6_addr);
4867 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4868 			sin6d.sin6_family = AF_INET;
4869 			tpi_mp = mi_tpi_extconn_ind(NULL,
4870 			    (char *)&sin6d, sizeof (sin6_t),
4871 			    (char *)&tcp,
4872 			    (t_scalar_t)sizeof (intptr_t),
4873 			    (char *)&sin6d, sizeof (sin6_t),
4874 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4875 		} else {
4876 			tpi_mp = mi_tpi_conn_ind(NULL,
4877 			    (char *)&sin6, sizeof (sin6_t),
4878 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4879 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4880 		}
4881 	} else {
4882 		ip6h = (ip6_t *)mp->b_rptr;
4883 
4884 		connp->conn_send = ip_output_v6;
4885 		connp->conn_recv = tcp_input;
4886 
4887 		connp->conn_srcv6 = ip6h->ip6_dst;
4888 		connp->conn_remv6 = ip6h->ip6_src;
4889 
4890 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4891 		ifindex = (int)DB_CKSUMSTUFF(mp);
4892 		DB_CKSUMSTUFF(mp) = 0;
4893 
4894 		sin6 = sin6_null;
4895 		sin6.sin6_addr = ip6h->ip6_src;
4896 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4897 		sin6.sin6_family = AF_INET6;
4898 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4899 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4900 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4901 
4902 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4903 			/* Pass up the scope_id of remote addr */
4904 			sin6.sin6_scope_id = ifindex;
4905 		} else {
4906 			sin6.sin6_scope_id = 0;
4907 		}
4908 		if (tcp->tcp_recvdstaddr) {
4909 			sin6_t	sin6d;
4910 
4911 			sin6d = sin6_null;
4912 			sin6.sin6_addr = ip6h->ip6_dst;
4913 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4914 			sin6d.sin6_family = AF_INET;
4915 			tpi_mp = mi_tpi_extconn_ind(NULL,
4916 			    (char *)&sin6d, sizeof (sin6_t),
4917 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4918 			    (char *)&sin6d, sizeof (sin6_t),
4919 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4920 		} else {
4921 			tpi_mp = mi_tpi_conn_ind(NULL,
4922 			    (char *)&sin6, sizeof (sin6_t),
4923 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4924 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4925 		}
4926 	}
4927 
4928 	if (tpi_mp == NULL)
4929 		return (ENOMEM);
4930 
4931 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4932 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4933 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4934 	connp->conn_fully_bound = B_FALSE;
4935 
4936 	/* Inherit information from the "parent" */
4937 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4938 	tcp->tcp_family = ltcp->tcp_family;
4939 	tcp->tcp_wq = ltcp->tcp_wq;
4940 	tcp->tcp_rq = ltcp->tcp_rq;
4941 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4942 	tcp->tcp_detached = B_TRUE;
4943 	if ((err = tcp_init_values(tcp)) != 0) {
4944 		freemsg(tpi_mp);
4945 		return (err);
4946 	}
4947 
4948 	if (ipvers == IPV4_VERSION) {
4949 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4950 			freemsg(tpi_mp);
4951 			return (err);
4952 		}
4953 		ASSERT(tcp->tcp_ipha != NULL);
4954 	} else {
4955 		/* ifindex must be already set */
4956 		ASSERT(ifindex != 0);
4957 
4958 		if (ltcp->tcp_bound_if != 0) {
4959 			/*
4960 			 * Set newtcp's bound_if equal to
4961 			 * listener's value. If ifindex is
4962 			 * not the same as ltcp->tcp_bound_if,
4963 			 * it must be a packet for the ipmp group
4964 			 * of interfaces
4965 			 */
4966 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4967 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4968 			tcp->tcp_bound_if = ifindex;
4969 		}
4970 
4971 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4972 		tcp->tcp_recvifindex = 0;
4973 		tcp->tcp_recvhops = 0xffffffffU;
4974 		ASSERT(tcp->tcp_ip6h != NULL);
4975 	}
4976 
4977 	tcp->tcp_lport = ltcp->tcp_lport;
4978 
4979 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4980 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4981 			/*
4982 			 * Listener had options of some sort; eager inherits.
4983 			 * Free up the eager template and allocate one
4984 			 * of the right size.
4985 			 */
4986 			if (tcp->tcp_hdr_grown) {
4987 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4988 			} else {
4989 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4990 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4991 			}
4992 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4993 			    KM_NOSLEEP);
4994 			if (tcp->tcp_iphc == NULL) {
4995 				tcp->tcp_iphc_len = 0;
4996 				freemsg(tpi_mp);
4997 				return (ENOMEM);
4998 			}
4999 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
5000 			tcp->tcp_hdr_grown = B_TRUE;
5001 		}
5002 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5003 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5004 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5005 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
5006 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
5007 
5008 		/*
5009 		 * Copy the IP+TCP header template from listener to eager
5010 		 */
5011 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5012 		if (tcp->tcp_ipversion == IPV6_VERSION) {
5013 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
5014 			    IPPROTO_RAW) {
5015 				tcp->tcp_ip6h =
5016 				    (ip6_t *)(tcp->tcp_iphc +
5017 				    sizeof (ip6i_t));
5018 			} else {
5019 				tcp->tcp_ip6h =
5020 				    (ip6_t *)(tcp->tcp_iphc);
5021 			}
5022 			tcp->tcp_ipha = NULL;
5023 		} else {
5024 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5025 			tcp->tcp_ip6h = NULL;
5026 		}
5027 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5028 		    tcp->tcp_ip_hdr_len);
5029 	} else {
5030 		/*
5031 		 * only valid case when ipversion of listener and
5032 		 * eager differ is when listener is IPv6 and
5033 		 * eager is IPv4.
5034 		 * Eager header template has been initialized to the
5035 		 * maximum v4 header sizes, which includes space for
5036 		 * TCP and IP options.
5037 		 */
5038 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5039 		    (tcp->tcp_ipversion == IPV4_VERSION));
5040 		ASSERT(tcp->tcp_iphc_len >=
5041 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5042 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5043 		/* copy IP header fields individually */
5044 		tcp->tcp_ipha->ipha_ttl =
5045 		    ltcp->tcp_ip6h->ip6_hops;
5046 		bcopy(ltcp->tcp_tcph->th_lport,
5047 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5048 	}
5049 
5050 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5051 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5052 	    sizeof (in_port_t));
5053 
5054 	if (ltcp->tcp_lport == 0) {
5055 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5056 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5057 		    sizeof (in_port_t));
5058 	}
5059 
5060 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5061 		ASSERT(ipha != NULL);
5062 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5063 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5064 
5065 		/* Source routing option copyover (reverse it) */
5066 		if (tcps->tcps_rev_src_routes)
5067 			tcp_opt_reverse(tcp, ipha);
5068 	} else {
5069 		ASSERT(ip6h != NULL);
5070 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5071 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5072 	}
5073 
5074 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5075 	ASSERT(!tcp->tcp_tconnind_started);
5076 	/*
5077 	 * If the SYN contains a credential, it's a loopback packet; attach
5078 	 * the credential to the TPI message.
5079 	 */
5080 	if ((cr = DB_CRED(idmp)) != NULL) {
5081 		mblk_setcred(tpi_mp, cr);
5082 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5083 	}
5084 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5085 
5086 	/* Inherit the listener's SSL protection state */
5087 
5088 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5089 		kssl_hold_ent(tcp->tcp_kssl_ent);
5090 		tcp->tcp_kssl_pending = B_TRUE;
5091 	}
5092 
5093 	return (0);
5094 }
5095 
5096 
5097 int
5098 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5099     tcph_t *tcph, mblk_t *idmp)
5100 {
5101 	tcp_t 		*ltcp = lconnp->conn_tcp;
5102 	tcp_t		*tcp = connp->conn_tcp;
5103 	sin_t		sin;
5104 	mblk_t		*tpi_mp = NULL;
5105 	int		err;
5106 	cred_t		*cr;
5107 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5108 
5109 	sin = sin_null;
5110 	sin.sin_addr.s_addr = ipha->ipha_src;
5111 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5112 	sin.sin_family = AF_INET;
5113 	if (ltcp->tcp_recvdstaddr) {
5114 		sin_t	sind;
5115 
5116 		sind = sin_null;
5117 		sind.sin_addr.s_addr = ipha->ipha_dst;
5118 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5119 		sind.sin_family = AF_INET;
5120 		tpi_mp = mi_tpi_extconn_ind(NULL,
5121 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5122 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5123 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5124 	} else {
5125 		tpi_mp = mi_tpi_conn_ind(NULL,
5126 		    (char *)&sin, sizeof (sin_t),
5127 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5128 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5129 	}
5130 
5131 	if (tpi_mp == NULL) {
5132 		return (ENOMEM);
5133 	}
5134 
5135 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5136 	connp->conn_send = ip_output;
5137 	connp->conn_recv = tcp_input;
5138 	connp->conn_fully_bound = B_FALSE;
5139 
5140 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5141 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5142 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5143 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5144 
5145 	/* Inherit information from the "parent" */
5146 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5147 	tcp->tcp_family = ltcp->tcp_family;
5148 	tcp->tcp_wq = ltcp->tcp_wq;
5149 	tcp->tcp_rq = ltcp->tcp_rq;
5150 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
5151 	tcp->tcp_detached = B_TRUE;
5152 	if ((err = tcp_init_values(tcp)) != 0) {
5153 		freemsg(tpi_mp);
5154 		return (err);
5155 	}
5156 
5157 	/*
5158 	 * Let's make sure that eager tcp template has enough space to
5159 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5160 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5161 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5162 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5163 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5164 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5165 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5166 	 */
5167 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5168 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5169 
5170 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5171 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5172 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5173 	tcp->tcp_ttl = ltcp->tcp_ttl;
5174 	tcp->tcp_tos = ltcp->tcp_tos;
5175 
5176 	/* Copy the IP+TCP header template from listener to eager */
5177 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5178 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5179 	tcp->tcp_ip6h = NULL;
5180 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5181 	    tcp->tcp_ip_hdr_len);
5182 
5183 	/* Initialize the IP addresses and Ports */
5184 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5185 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5186 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5187 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5188 
5189 	/* Source routing option copyover (reverse it) */
5190 	if (tcps->tcps_rev_src_routes)
5191 		tcp_opt_reverse(tcp, ipha);
5192 
5193 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5194 	ASSERT(!tcp->tcp_tconnind_started);
5195 
5196 	/*
5197 	 * If the SYN contains a credential, it's a loopback packet; attach
5198 	 * the credential to the TPI message.
5199 	 */
5200 	if ((cr = DB_CRED(idmp)) != NULL) {
5201 		mblk_setcred(tpi_mp, cr);
5202 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5203 	}
5204 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5205 
5206 	/* Inherit the listener's SSL protection state */
5207 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5208 		kssl_hold_ent(tcp->tcp_kssl_ent);
5209 		tcp->tcp_kssl_pending = B_TRUE;
5210 	}
5211 
5212 	return (0);
5213 }
5214 
5215 /*
5216  * sets up conn for ipsec.
5217  * if the first mblk is M_CTL it is consumed and mpp is updated.
5218  * in case of error mpp is freed.
5219  */
5220 conn_t *
5221 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5222 {
5223 	conn_t 		*connp = tcp->tcp_connp;
5224 	conn_t 		*econnp;
5225 	squeue_t 	*new_sqp;
5226 	mblk_t 		*first_mp = *mpp;
5227 	mblk_t		*mp = *mpp;
5228 	boolean_t	mctl_present = B_FALSE;
5229 	uint_t		ipvers;
5230 
5231 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
5232 	if (econnp == NULL) {
5233 		freemsg(first_mp);
5234 		return (NULL);
5235 	}
5236 	if (DB_TYPE(mp) == M_CTL) {
5237 		if (mp->b_cont == NULL ||
5238 		    mp->b_cont->b_datap->db_type != M_DATA) {
5239 			freemsg(first_mp);
5240 			return (NULL);
5241 		}
5242 		mp = mp->b_cont;
5243 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5244 			freemsg(first_mp);
5245 			return (NULL);
5246 		}
5247 
5248 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5249 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5250 		mctl_present = B_TRUE;
5251 	} else {
5252 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5253 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5254 	}
5255 
5256 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5257 	DB_CKSUMSTART(mp) = 0;
5258 
5259 	ASSERT(OK_32PTR(mp->b_rptr));
5260 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5261 	if (ipvers == IPV4_VERSION) {
5262 		uint16_t  	*up;
5263 		uint32_t	ports;
5264 		ipha_t		*ipha;
5265 
5266 		ipha = (ipha_t *)mp->b_rptr;
5267 		up = (uint16_t *)((uchar_t *)ipha +
5268 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5269 		ports = *(uint32_t *)up;
5270 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5271 		    ipha->ipha_dst, ipha->ipha_src, ports);
5272 	} else {
5273 		uint16_t  	*up;
5274 		uint32_t	ports;
5275 		uint16_t	ip_hdr_len;
5276 		uint8_t		*nexthdrp;
5277 		ip6_t 		*ip6h;
5278 		tcph_t		*tcph;
5279 
5280 		ip6h = (ip6_t *)mp->b_rptr;
5281 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5282 			ip_hdr_len = IPV6_HDR_LEN;
5283 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5284 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5285 			CONN_DEC_REF(econnp);
5286 			freemsg(first_mp);
5287 			return (NULL);
5288 		}
5289 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5290 		up = (uint16_t *)tcph->th_lport;
5291 		ports = *(uint32_t *)up;
5292 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5293 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5294 	}
5295 
5296 	/*
5297 	 * The caller already ensured that there is a sqp present.
5298 	 */
5299 	econnp->conn_sqp = new_sqp;
5300 
5301 	if (connp->conn_policy != NULL) {
5302 		ipsec_in_t *ii;
5303 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5304 		ASSERT(ii->ipsec_in_policy == NULL);
5305 		IPPH_REFHOLD(connp->conn_policy);
5306 		ii->ipsec_in_policy = connp->conn_policy;
5307 
5308 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5309 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5310 			CONN_DEC_REF(econnp);
5311 			freemsg(first_mp);
5312 			return (NULL);
5313 		}
5314 	}
5315 
5316 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5317 		CONN_DEC_REF(econnp);
5318 		freemsg(first_mp);
5319 		return (NULL);
5320 	}
5321 
5322 	/*
5323 	 * If we know we have some policy, pass the "IPSEC"
5324 	 * options size TCP uses this adjust the MSS.
5325 	 */
5326 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5327 	if (mctl_present) {
5328 		freeb(first_mp);
5329 		*mpp = mp;
5330 	}
5331 
5332 	return (econnp);
5333 }
5334 
5335 /*
5336  * tcp_get_conn/tcp_free_conn
5337  *
5338  * tcp_get_conn is used to get a clean tcp connection structure.
5339  * It tries to reuse the connections put on the freelist by the
5340  * time_wait_collector failing which it goes to kmem_cache. This
5341  * way has two benefits compared to just allocating from and
5342  * freeing to kmem_cache.
5343  * 1) The time_wait_collector can free (which includes the cleanup)
5344  * outside the squeue. So when the interrupt comes, we have a clean
5345  * connection sitting in the freelist. Obviously, this buys us
5346  * performance.
5347  *
5348  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5349  * has multiple disadvantages - tying up the squeue during alloc, and the
5350  * fact that IPSec policy initialization has to happen here which
5351  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5352  * But allocating the conn/tcp in IP land is also not the best since
5353  * we can't check the 'q' and 'q0' which are protected by squeue and
5354  * blindly allocate memory which might have to be freed here if we are
5355  * not allowed to accept the connection. By using the freelist and
5356  * putting the conn/tcp back in freelist, we don't pay a penalty for
5357  * allocating memory without checking 'q/q0' and freeing it if we can't
5358  * accept the connection.
5359  *
5360  * Care should be taken to put the conn back in the same squeue's freelist
5361  * from which it was allocated. Best results are obtained if conn is
5362  * allocated from listener's squeue and freed to the same. Time wait
5363  * collector will free up the freelist is the connection ends up sitting
5364  * there for too long.
5365  */
5366 void *
5367 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5368 {
5369 	tcp_t			*tcp = NULL;
5370 	conn_t			*connp = NULL;
5371 	squeue_t		*sqp = (squeue_t *)arg;
5372 	tcp_squeue_priv_t 	*tcp_time_wait;
5373 	netstack_t		*ns;
5374 
5375 	tcp_time_wait =
5376 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5377 
5378 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5379 	tcp = tcp_time_wait->tcp_free_list;
5380 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5381 	if (tcp != NULL) {
5382 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5383 		tcp_time_wait->tcp_free_list_cnt--;
5384 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5385 		tcp->tcp_time_wait_next = NULL;
5386 		connp = tcp->tcp_connp;
5387 		connp->conn_flags |= IPCL_REUSED;
5388 
5389 		ASSERT(tcp->tcp_tcps == NULL);
5390 		ASSERT(connp->conn_netstack == NULL);
5391 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5392 		ns = tcps->tcps_netstack;
5393 		netstack_hold(ns);
5394 		connp->conn_netstack = ns;
5395 		tcp->tcp_tcps = tcps;
5396 		TCPS_REFHOLD(tcps);
5397 		ipcl_globalhash_insert(connp);
5398 		return ((void *)connp);
5399 	}
5400 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5401 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5402 	    tcps->tcps_netstack)) == NULL)
5403 		return (NULL);
5404 	tcp = connp->conn_tcp;
5405 	/*
5406 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5407 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5408 	 */
5409 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5410 		ipcl_conn_destroy(connp);
5411 		return (NULL);
5412 	}
5413 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5414 	tcp->tcp_tcps = tcps;
5415 	TCPS_REFHOLD(tcps);
5416 
5417 	return ((void *)connp);
5418 }
5419 
5420 /*
5421  * Update the cached label for the given tcp_t.  This should be called once per
5422  * connection, and before any packets are sent or tcp_process_options is
5423  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5424  */
5425 static boolean_t
5426 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5427 {
5428 	conn_t *connp = tcp->tcp_connp;
5429 
5430 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5431 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5432 		int added;
5433 
5434 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5435 		    connp->conn_mac_exempt,
5436 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5437 			return (B_FALSE);
5438 
5439 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5440 		if (added == -1)
5441 			return (B_FALSE);
5442 		tcp->tcp_hdr_len += added;
5443 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5444 		tcp->tcp_ip_hdr_len += added;
5445 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5446 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5447 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5448 			    tcp->tcp_hdr_len);
5449 			if (added == -1)
5450 				return (B_FALSE);
5451 			tcp->tcp_hdr_len += added;
5452 			tcp->tcp_tcph = (tcph_t *)
5453 			    ((uchar_t *)tcp->tcp_tcph + added);
5454 			tcp->tcp_ip_hdr_len += added;
5455 		}
5456 	} else {
5457 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5458 
5459 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5460 		    connp->conn_mac_exempt,
5461 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5462 			return (B_FALSE);
5463 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5464 		    &tcp->tcp_label_len, optbuf) != 0)
5465 			return (B_FALSE);
5466 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5467 			return (B_FALSE);
5468 	}
5469 
5470 	connp->conn_ulp_labeled = 1;
5471 
5472 	return (B_TRUE);
5473 }
5474 
5475 /* BEGIN CSTYLED */
5476 /*
5477  *
5478  * The sockfs ACCEPT path:
5479  * =======================
5480  *
5481  * The eager is now established in its own perimeter as soon as SYN is
5482  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5483  * completes the accept processing on the acceptor STREAM. The sending
5484  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5485  * listener but a TLI/XTI listener completes the accept processing
5486  * on the listener perimeter.
5487  *
5488  * Common control flow for 3 way handshake:
5489  * ----------------------------------------
5490  *
5491  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5492  *					-> tcp_conn_request()
5493  *
5494  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5495  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5496  *
5497  * Sockfs ACCEPT Path:
5498  * -------------------
5499  *
5500  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5501  * as STREAM entry point)
5502  *
5503  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5504  *
5505  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5506  * association (we are not behind eager's squeue but sockfs is protecting us
5507  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5508  * is changed to point at tcp_wput().
5509  *
5510  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5511  * listener (done on listener's perimeter).
5512  *
5513  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5514  * accept.
5515  *
5516  * TLI/XTI client ACCEPT path:
5517  * ---------------------------
5518  *
5519  * soaccept() sends T_CONN_RES on the listener STREAM.
5520  *
5521  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5522  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5523  *
5524  * Locks:
5525  * ======
5526  *
5527  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5528  * and listeners->tcp_eager_next_q.
5529  *
5530  * Referencing:
5531  * ============
5532  *
5533  * 1) We start out in tcp_conn_request by eager placing a ref on
5534  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5535  *
5536  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5537  * doing so we place a ref on the eager. This ref is finally dropped at the
5538  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5539  * reference is dropped by the squeue framework.
5540  *
5541  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5542  *
5543  * The reference must be released by the same entity that added the reference
5544  * In the above scheme, the eager is the entity that adds and releases the
5545  * references. Note that tcp_accept_finish executes in the squeue of the eager
5546  * (albeit after it is attached to the acceptor stream). Though 1. executes
5547  * in the listener's squeue, the eager is nascent at this point and the
5548  * reference can be considered to have been added on behalf of the eager.
5549  *
5550  * Eager getting a Reset or listener closing:
5551  * ==========================================
5552  *
5553  * Once the listener and eager are linked, the listener never does the unlink.
5554  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5555  * a message on all eager perimeter. The eager then does the unlink, clears
5556  * any pointers to the listener's queue and drops the reference to the
5557  * listener. The listener waits in tcp_close outside the squeue until its
5558  * refcount has dropped to 1. This ensures that the listener has waited for
5559  * all eagers to clear their association with the listener.
5560  *
5561  * Similarly, if eager decides to go away, it can unlink itself and close.
5562  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5563  * the reference to eager is still valid because of the extra ref we put
5564  * in tcp_send_conn_ind.
5565  *
5566  * Listener can always locate the eager under the protection
5567  * of the listener->tcp_eager_lock, and then do a refhold
5568  * on the eager during the accept processing.
5569  *
5570  * The acceptor stream accesses the eager in the accept processing
5571  * based on the ref placed on eager before sending T_conn_ind.
5572  * The only entity that can negate this refhold is a listener close
5573  * which is mutually exclusive with an active acceptor stream.
5574  *
5575  * Eager's reference on the listener
5576  * ===================================
5577  *
5578  * If the accept happens (even on a closed eager) the eager drops its
5579  * reference on the listener at the start of tcp_accept_finish. If the
5580  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5581  * the reference is dropped in tcp_closei_local. If the listener closes,
5582  * the reference is dropped in tcp_eager_kill. In all cases the reference
5583  * is dropped while executing in the eager's context (squeue).
5584  */
5585 /* END CSTYLED */
5586 
5587 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5588 
5589 /*
5590  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5591  * tcp_rput_data will not see any SYN packets.
5592  */
5593 /* ARGSUSED */
5594 void
5595 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5596 {
5597 	tcph_t		*tcph;
5598 	uint32_t	seg_seq;
5599 	tcp_t		*eager;
5600 	uint_t		ipvers;
5601 	ipha_t		*ipha;
5602 	ip6_t		*ip6h;
5603 	int		err;
5604 	conn_t		*econnp = NULL;
5605 	squeue_t	*new_sqp;
5606 	mblk_t		*mp1;
5607 	uint_t 		ip_hdr_len;
5608 	conn_t		*connp = (conn_t *)arg;
5609 	tcp_t		*tcp = connp->conn_tcp;
5610 	cred_t		*credp;
5611 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5612 	ip_stack_t	*ipst;
5613 
5614 	if (tcp->tcp_state != TCPS_LISTEN)
5615 		goto error2;
5616 
5617 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5618 
5619 	mutex_enter(&tcp->tcp_eager_lock);
5620 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5621 		mutex_exit(&tcp->tcp_eager_lock);
5622 		TCP_STAT(tcps, tcp_listendrop);
5623 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5624 		if (tcp->tcp_debug) {
5625 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5626 			    "tcp_conn_request: listen backlog (max=%d) "
5627 			    "overflow (%d pending) on %s",
5628 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5629 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5630 		}
5631 		goto error2;
5632 	}
5633 
5634 	if (tcp->tcp_conn_req_cnt_q0 >=
5635 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5636 		/*
5637 		 * Q0 is full. Drop a pending half-open req from the queue
5638 		 * to make room for the new SYN req. Also mark the time we
5639 		 * drop a SYN.
5640 		 *
5641 		 * A more aggressive defense against SYN attack will
5642 		 * be to set the "tcp_syn_defense" flag now.
5643 		 */
5644 		TCP_STAT(tcps, tcp_listendropq0);
5645 		tcp->tcp_last_rcv_lbolt = lbolt64;
5646 		if (!tcp_drop_q0(tcp)) {
5647 			mutex_exit(&tcp->tcp_eager_lock);
5648 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5649 			if (tcp->tcp_debug) {
5650 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5651 				    "tcp_conn_request: listen half-open queue "
5652 				    "(max=%d) full (%d pending) on %s",
5653 				    tcps->tcps_conn_req_max_q0,
5654 				    tcp->tcp_conn_req_cnt_q0,
5655 				    tcp_display(tcp, NULL,
5656 				    DISP_PORT_ONLY));
5657 			}
5658 			goto error2;
5659 		}
5660 	}
5661 	mutex_exit(&tcp->tcp_eager_lock);
5662 
5663 	/*
5664 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5665 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5666 	 * link local address.  If IPSec is enabled, db_struioflag has
5667 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5668 	 * otherwise an error case if neither of them is set.
5669 	 */
5670 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5671 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5672 		DB_CKSUMSTART(mp) = 0;
5673 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5674 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5675 		if (econnp == NULL)
5676 			goto error2;
5677 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5678 		econnp->conn_sqp = new_sqp;
5679 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5680 		/*
5681 		 * mp is updated in tcp_get_ipsec_conn().
5682 		 */
5683 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5684 		if (econnp == NULL) {
5685 			/*
5686 			 * mp freed by tcp_get_ipsec_conn.
5687 			 */
5688 			return;
5689 		}
5690 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5691 	} else {
5692 		goto error2;
5693 	}
5694 
5695 	ASSERT(DB_TYPE(mp) == M_DATA);
5696 
5697 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5698 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5699 	ASSERT(OK_32PTR(mp->b_rptr));
5700 	if (ipvers == IPV4_VERSION) {
5701 		ipha = (ipha_t *)mp->b_rptr;
5702 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5703 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5704 	} else {
5705 		ip6h = (ip6_t *)mp->b_rptr;
5706 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5707 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5708 	}
5709 
5710 	if (tcp->tcp_family == AF_INET) {
5711 		ASSERT(ipvers == IPV4_VERSION);
5712 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5713 	} else {
5714 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5715 	}
5716 
5717 	if (err)
5718 		goto error3;
5719 
5720 	eager = econnp->conn_tcp;
5721 
5722 	/*
5723 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5724 	 * will always have that to send up.  Otherwise, we need to do
5725 	 * special handling in case the allocation fails at that time.
5726 	 */
5727 	ASSERT(eager->tcp_ordrel_mp == NULL);
5728 	if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5729 		goto error3;
5730 
5731 	/* Inherit various TCP parameters from the listener */
5732 	eager->tcp_naglim = tcp->tcp_naglim;
5733 	eager->tcp_first_timer_threshold =
5734 	    tcp->tcp_first_timer_threshold;
5735 	eager->tcp_second_timer_threshold =
5736 	    tcp->tcp_second_timer_threshold;
5737 
5738 	eager->tcp_first_ctimer_threshold =
5739 	    tcp->tcp_first_ctimer_threshold;
5740 	eager->tcp_second_ctimer_threshold =
5741 	    tcp->tcp_second_ctimer_threshold;
5742 
5743 	/*
5744 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5745 	 * If it does not, the eager's receive window will be set to the
5746 	 * listener's receive window later in this function.
5747 	 */
5748 	eager->tcp_rwnd = 0;
5749 
5750 	/*
5751 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5752 	 * calling tcp_process_options() where tcp_mss_set() is called
5753 	 * to set the initial cwnd.
5754 	 */
5755 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5756 
5757 	/*
5758 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5759 	 * zone id before the accept is completed in tcp_wput_accept().
5760 	 */
5761 	econnp->conn_zoneid = connp->conn_zoneid;
5762 	econnp->conn_allzones = connp->conn_allzones;
5763 
5764 	/* Copy nexthop information from listener to eager */
5765 	if (connp->conn_nexthop_set) {
5766 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5767 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5768 	}
5769 
5770 	/*
5771 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5772 	 * eager is accepted
5773 	 */
5774 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5775 	crhold(credp);
5776 
5777 	/*
5778 	 * If the caller has the process-wide flag set, then default to MAC
5779 	 * exempt mode.  This allows read-down to unlabeled hosts.
5780 	 */
5781 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5782 		econnp->conn_mac_exempt = B_TRUE;
5783 
5784 	if (is_system_labeled()) {
5785 		cred_t *cr;
5786 
5787 		if (connp->conn_mlp_type != mlptSingle) {
5788 			cr = econnp->conn_peercred = DB_CRED(mp);
5789 			if (cr != NULL)
5790 				crhold(cr);
5791 			else
5792 				cr = econnp->conn_cred;
5793 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5794 			    econnp, cred_t *, cr)
5795 		} else {
5796 			cr = econnp->conn_cred;
5797 			DTRACE_PROBE2(syn_accept, conn_t *,
5798 			    econnp, cred_t *, cr)
5799 		}
5800 
5801 		if (!tcp_update_label(eager, cr)) {
5802 			DTRACE_PROBE3(
5803 			    tx__ip__log__error__connrequest__tcp,
5804 			    char *, "eager connp(1) label on SYN mp(2) failed",
5805 			    conn_t *, econnp, mblk_t *, mp);
5806 			goto error3;
5807 		}
5808 	}
5809 
5810 	eager->tcp_hard_binding = B_TRUE;
5811 
5812 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5813 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5814 
5815 	CL_INET_CONNECT(eager);
5816 
5817 	/*
5818 	 * No need to check for multicast destination since ip will only pass
5819 	 * up multicasts to those that have expressed interest
5820 	 * TODO: what about rejecting broadcasts?
5821 	 * Also check that source is not a multicast or broadcast address.
5822 	 */
5823 	eager->tcp_state = TCPS_SYN_RCVD;
5824 
5825 
5826 	/*
5827 	 * There should be no ire in the mp as we are being called after
5828 	 * receiving the SYN.
5829 	 */
5830 	ASSERT(tcp_ire_mp(mp) == NULL);
5831 
5832 	/*
5833 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5834 	 */
5835 
5836 	if (tcp_adapt_ire(eager, NULL) == 0) {
5837 		/* Undo the bind_hash_insert */
5838 		tcp_bind_hash_remove(eager);
5839 		goto error3;
5840 	}
5841 
5842 	/* Process all TCP options. */
5843 	tcp_process_options(eager, tcph);
5844 
5845 	/* Is the other end ECN capable? */
5846 	if (tcps->tcps_ecn_permitted >= 1 &&
5847 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5848 		eager->tcp_ecn_ok = B_TRUE;
5849 	}
5850 
5851 	/*
5852 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5853 	 * window size changed via SO_RCVBUF option.  First round up the
5854 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5855 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5856 	 * setting.
5857 	 *
5858 	 * Note if there is a rpipe metric associated with the remote host,
5859 	 * we should not inherit receive window size from listener.
5860 	 */
5861 	eager->tcp_rwnd = MSS_ROUNDUP(
5862 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5863 	    eager->tcp_rwnd), eager->tcp_mss);
5864 	if (eager->tcp_snd_ws_ok)
5865 		tcp_set_ws_value(eager);
5866 	/*
5867 	 * Note that this is the only place tcp_rwnd_set() is called for
5868 	 * accepting a connection.  We need to call it here instead of
5869 	 * after the 3-way handshake because we need to tell the other
5870 	 * side our rwnd in the SYN-ACK segment.
5871 	 */
5872 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5873 
5874 	/*
5875 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5876 	 * via soaccept()->soinheritoptions() which essentially applies
5877 	 * all the listener options to the new STREAM. The options that we
5878 	 * need to take care of are:
5879 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5880 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5881 	 * SO_SNDBUF, SO_RCVBUF.
5882 	 *
5883 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5884 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5885 	 *		tcp_maxpsz_set() gets called later from
5886 	 *		tcp_accept_finish(), the option takes effect.
5887 	 *
5888 	 */
5889 	/* Set the TCP options */
5890 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5891 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5892 	eager->tcp_oobinline = tcp->tcp_oobinline;
5893 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5894 	eager->tcp_broadcast = tcp->tcp_broadcast;
5895 	eager->tcp_useloopback = tcp->tcp_useloopback;
5896 	eager->tcp_dontroute = tcp->tcp_dontroute;
5897 	eager->tcp_linger = tcp->tcp_linger;
5898 	eager->tcp_lingertime = tcp->tcp_lingertime;
5899 	if (tcp->tcp_ka_enabled)
5900 		eager->tcp_ka_enabled = 1;
5901 
5902 	/* Set the IP options */
5903 	econnp->conn_broadcast = connp->conn_broadcast;
5904 	econnp->conn_loopback = connp->conn_loopback;
5905 	econnp->conn_dontroute = connp->conn_dontroute;
5906 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5907 
5908 	/* Put a ref on the listener for the eager. */
5909 	CONN_INC_REF(connp);
5910 	mutex_enter(&tcp->tcp_eager_lock);
5911 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5912 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5913 	tcp->tcp_eager_next_q0 = eager;
5914 	eager->tcp_eager_prev_q0 = tcp;
5915 
5916 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5917 	eager->tcp_listener = tcp;
5918 	eager->tcp_saved_listener = tcp;
5919 
5920 	/*
5921 	 * Tag this detached tcp vector for later retrieval
5922 	 * by our listener client in tcp_accept().
5923 	 */
5924 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5925 	tcp->tcp_conn_req_cnt_q0++;
5926 	if (++tcp->tcp_conn_req_seqnum == -1) {
5927 		/*
5928 		 * -1 is "special" and defined in TPI as something
5929 		 * that should never be used in T_CONN_IND
5930 		 */
5931 		++tcp->tcp_conn_req_seqnum;
5932 	}
5933 	mutex_exit(&tcp->tcp_eager_lock);
5934 
5935 	if (tcp->tcp_syn_defense) {
5936 		/* Don't drop the SYN that comes from a good IP source */
5937 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5938 		if (addr_cache != NULL && eager->tcp_remote ==
5939 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5940 			eager->tcp_dontdrop = B_TRUE;
5941 		}
5942 	}
5943 
5944 	/*
5945 	 * We need to insert the eager in its own perimeter but as soon
5946 	 * as we do that, we expose the eager to the classifier and
5947 	 * should not touch any field outside the eager's perimeter.
5948 	 * So do all the work necessary before inserting the eager
5949 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5950 	 * will succeed but undo everything if it fails.
5951 	 */
5952 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5953 	eager->tcp_irs = seg_seq;
5954 	eager->tcp_rack = seg_seq;
5955 	eager->tcp_rnxt = seg_seq + 1;
5956 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5957 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5958 	eager->tcp_state = TCPS_SYN_RCVD;
5959 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5960 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5961 	if (mp1 == NULL) {
5962 		/*
5963 		 * Increment the ref count as we are going to
5964 		 * enqueueing an mp in squeue
5965 		 */
5966 		CONN_INC_REF(econnp);
5967 		goto error;
5968 	}
5969 	DB_CPID(mp1) = tcp->tcp_cpid;
5970 	eager->tcp_cpid = tcp->tcp_cpid;
5971 	eager->tcp_open_time = lbolt64;
5972 
5973 	/*
5974 	 * We need to start the rto timer. In normal case, we start
5975 	 * the timer after sending the packet on the wire (or at
5976 	 * least believing that packet was sent by waiting for
5977 	 * CALL_IP_WPUT() to return). Since this is the first packet
5978 	 * being sent on the wire for the eager, our initial tcp_rto
5979 	 * is at least tcp_rexmit_interval_min which is a fairly
5980 	 * large value to allow the algorithm to adjust slowly to large
5981 	 * fluctuations of RTT during first few transmissions.
5982 	 *
5983 	 * Starting the timer first and then sending the packet in this
5984 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5985 	 * is of the order of several 100ms and starting the timer
5986 	 * first and then sending the packet will result in difference
5987 	 * of few micro seconds.
5988 	 *
5989 	 * Without this optimization, we are forced to hold the fanout
5990 	 * lock across the ipcl_bind_insert() and sending the packet
5991 	 * so that we don't race against an incoming packet (maybe RST)
5992 	 * for this eager.
5993 	 *
5994 	 * It is necessary to acquire an extra reference on the eager
5995 	 * at this point and hold it until after tcp_send_data() to
5996 	 * ensure against an eager close race.
5997 	 */
5998 
5999 	CONN_INC_REF(eager->tcp_connp);
6000 
6001 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
6002 
6003 	/*
6004 	 * Insert the eager in its own perimeter now. We are ready to deal
6005 	 * with any packets on eager.
6006 	 */
6007 	if (eager->tcp_ipversion == IPV4_VERSION) {
6008 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
6009 			goto error;
6010 		}
6011 	} else {
6012 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
6013 			goto error;
6014 		}
6015 	}
6016 
6017 	/* mark conn as fully-bound */
6018 	econnp->conn_fully_bound = B_TRUE;
6019 
6020 	/* Send the SYN-ACK */
6021 	tcp_send_data(eager, eager->tcp_wq, mp1);
6022 	CONN_DEC_REF(eager->tcp_connp);
6023 	freemsg(mp);
6024 
6025 	return;
6026 error:
6027 	freemsg(mp1);
6028 	eager->tcp_closemp_used = B_TRUE;
6029 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6030 	squeue_fill(econnp->conn_sqp, &eager->tcp_closemp, tcp_eager_kill,
6031 	    econnp, SQTAG_TCP_CONN_REQ_2);
6032 
6033 	/*
6034 	 * If a connection already exists, send the mp to that connections so
6035 	 * that it can be appropriately dealt with.
6036 	 */
6037 	ipst = tcps->tcps_netstack->netstack_ip;
6038 
6039 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
6040 		if (!IPCL_IS_CONNECTED(econnp)) {
6041 			/*
6042 			 * Something bad happened. ipcl_conn_insert()
6043 			 * failed because a connection already existed
6044 			 * in connected hash but we can't find it
6045 			 * anymore (someone blew it away). Just
6046 			 * free this message and hopefully remote
6047 			 * will retransmit at which time the SYN can be
6048 			 * treated as a new connection or dealth with
6049 			 * a TH_RST if a connection already exists.
6050 			 */
6051 			CONN_DEC_REF(econnp);
6052 			freemsg(mp);
6053 		} else {
6054 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6055 			    econnp, SQTAG_TCP_CONN_REQ_1);
6056 		}
6057 	} else {
6058 		/* Nobody wants this packet */
6059 		freemsg(mp);
6060 	}
6061 	return;
6062 error3:
6063 	CONN_DEC_REF(econnp);
6064 error2:
6065 	freemsg(mp);
6066 }
6067 
6068 /*
6069  * In an ideal case of vertical partition in NUMA architecture, its
6070  * beneficial to have the listener and all the incoming connections
6071  * tied to the same squeue. The other constraint is that incoming
6072  * connections should be tied to the squeue attached to interrupted
6073  * CPU for obvious locality reason so this leaves the listener to
6074  * be tied to the same squeue. Our only problem is that when listener
6075  * is binding, the CPU that will get interrupted by the NIC whose
6076  * IP address the listener is binding to is not even known. So
6077  * the code below allows us to change that binding at the time the
6078  * CPU is interrupted by virtue of incoming connection's squeue.
6079  *
6080  * This is usefull only in case of a listener bound to a specific IP
6081  * address. For other kind of listeners, they get bound the
6082  * very first time and there is no attempt to rebind them.
6083  */
6084 void
6085 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6086 {
6087 	conn_t		*connp = (conn_t *)arg;
6088 	squeue_t	*sqp = (squeue_t *)arg2;
6089 	squeue_t	*new_sqp;
6090 	uint32_t	conn_flags;
6091 
6092 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6093 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
6094 	} else {
6095 		goto done;
6096 	}
6097 
6098 	if (connp->conn_fanout == NULL)
6099 		goto done;
6100 
6101 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6102 		mutex_enter(&connp->conn_fanout->connf_lock);
6103 		mutex_enter(&connp->conn_lock);
6104 		/*
6105 		 * No one from read or write side can access us now
6106 		 * except for already queued packets on this squeue.
6107 		 * But since we haven't changed the squeue yet, they
6108 		 * can't execute. If they are processed after we have
6109 		 * changed the squeue, they are sent back to the
6110 		 * correct squeue down below.
6111 		 * But a listner close can race with processing of
6112 		 * incoming SYN. If incoming SYN processing changes
6113 		 * the squeue then the listener close which is waiting
6114 		 * to enter the squeue would operate on the wrong
6115 		 * squeue. Hence we don't change the squeue here unless
6116 		 * the refcount is exactly the minimum refcount. The
6117 		 * minimum refcount of 4 is counted as - 1 each for
6118 		 * TCP and IP, 1 for being in the classifier hash, and
6119 		 * 1 for the mblk being processed.
6120 		 */
6121 
6122 		if (connp->conn_ref != 4 ||
6123 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
6124 			mutex_exit(&connp->conn_lock);
6125 			mutex_exit(&connp->conn_fanout->connf_lock);
6126 			goto done;
6127 		}
6128 		if (connp->conn_sqp != new_sqp) {
6129 			while (connp->conn_sqp != new_sqp)
6130 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6131 		}
6132 
6133 		do {
6134 			conn_flags = connp->conn_flags;
6135 			conn_flags |= IPCL_FULLY_BOUND;
6136 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6137 			    conn_flags);
6138 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6139 
6140 		mutex_exit(&connp->conn_fanout->connf_lock);
6141 		mutex_exit(&connp->conn_lock);
6142 	}
6143 
6144 done:
6145 	if (connp->conn_sqp != sqp) {
6146 		CONN_INC_REF(connp);
6147 		squeue_fill(connp->conn_sqp, mp,
6148 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6149 	} else {
6150 		tcp_conn_request(connp, mp, sqp);
6151 	}
6152 }
6153 
6154 /*
6155  * Successful connect request processing begins when our client passes
6156  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6157  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6158  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6159  *   upstream <- tcp_rput()                <- IP
6160  * After various error checks are completed, tcp_connect() lays
6161  * the target address and port into the composite header template,
6162  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6163  * request followed by an IRE request, and passes the three mblk message
6164  * down to IP looking like this:
6165  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6166  * Processing continues in tcp_rput() when we receive the following message:
6167  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6168  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6169  * to fire off the connection request, and then passes the T_OK_ACK mblk
6170  * upstream that we filled in below.  There are, of course, numerous
6171  * error conditions along the way which truncate the processing described
6172  * above.
6173  */
6174 static void
6175 tcp_connect(tcp_t *tcp, mblk_t *mp)
6176 {
6177 	sin_t		*sin;
6178 	sin6_t		*sin6;
6179 	queue_t		*q = tcp->tcp_wq;
6180 	struct T_conn_req	*tcr;
6181 	ipaddr_t	*dstaddrp;
6182 	in_port_t	dstport;
6183 	uint_t		srcid;
6184 
6185 	tcr = (struct T_conn_req *)mp->b_rptr;
6186 
6187 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6188 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6189 		tcp_err_ack(tcp, mp, TPROTO, 0);
6190 		return;
6191 	}
6192 
6193 	/*
6194 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
6195 	 * will always have that to send up.  Otherwise, we need to do
6196 	 * special handling in case the allocation fails at that time.
6197 	 */
6198 	ASSERT(tcp->tcp_ordrel_mp == NULL);
6199 	if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
6200 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6201 		return;
6202 	}
6203 
6204 	/*
6205 	 * Determine packet type based on type of address passed in
6206 	 * the request should contain an IPv4 or IPv6 address.
6207 	 * Make sure that address family matches the type of
6208 	 * family of the the address passed down
6209 	 */
6210 	switch (tcr->DEST_length) {
6211 	default:
6212 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6213 		return;
6214 
6215 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6216 		/*
6217 		 * XXX: The check for valid DEST_length was not there
6218 		 * in earlier releases and some buggy
6219 		 * TLI apps (e.g Sybase) got away with not feeding
6220 		 * in sin_zero part of address.
6221 		 * We allow that bug to keep those buggy apps humming.
6222 		 * Test suites require the check on DEST_length.
6223 		 * We construct a new mblk with valid DEST_length
6224 		 * free the original so the rest of the code does
6225 		 * not have to keep track of this special shorter
6226 		 * length address case.
6227 		 */
6228 		mblk_t *nmp;
6229 		struct T_conn_req *ntcr;
6230 		sin_t *nsin;
6231 
6232 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6233 		    tcr->OPT_length, BPRI_HI);
6234 		if (nmp == NULL) {
6235 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6236 			return;
6237 		}
6238 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6239 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6240 		ntcr->PRIM_type = T_CONN_REQ;
6241 		ntcr->DEST_length = sizeof (sin_t);
6242 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6243 
6244 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6245 		*nsin = sin_null;
6246 		/* Get pointer to shorter address to copy from original mp */
6247 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6248 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6249 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6250 			freemsg(nmp);
6251 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6252 			return;
6253 		}
6254 		nsin->sin_family = sin->sin_family;
6255 		nsin->sin_port = sin->sin_port;
6256 		nsin->sin_addr = sin->sin_addr;
6257 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6258 		nmp->b_wptr = (uchar_t *)&nsin[1];
6259 		if (tcr->OPT_length != 0) {
6260 			ntcr->OPT_length = tcr->OPT_length;
6261 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6262 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6263 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6264 			    tcr->OPT_length);
6265 			nmp->b_wptr += tcr->OPT_length;
6266 		}
6267 		freemsg(mp);	/* original mp freed */
6268 		mp = nmp;	/* re-initialize original variables */
6269 		tcr = ntcr;
6270 	}
6271 	/* FALLTHRU */
6272 
6273 	case sizeof (sin_t):
6274 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6275 		    sizeof (sin_t));
6276 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6277 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6278 			return;
6279 		}
6280 		if (tcp->tcp_family != AF_INET ||
6281 		    sin->sin_family != AF_INET) {
6282 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6283 			return;
6284 		}
6285 		if (sin->sin_port == 0) {
6286 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6287 			return;
6288 		}
6289 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6290 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6291 			return;
6292 		}
6293 
6294 		break;
6295 
6296 	case sizeof (sin6_t):
6297 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6298 		    sizeof (sin6_t));
6299 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6300 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6301 			return;
6302 		}
6303 		if (tcp->tcp_family != AF_INET6 ||
6304 		    sin6->sin6_family != AF_INET6) {
6305 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6306 			return;
6307 		}
6308 		if (sin6->sin6_port == 0) {
6309 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6310 			return;
6311 		}
6312 		break;
6313 	}
6314 	/*
6315 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6316 	 * should key on their sequence number and cut them loose.
6317 	 */
6318 
6319 	/*
6320 	 * If options passed in, feed it for verification and handling
6321 	 */
6322 	if (tcr->OPT_length != 0) {
6323 		mblk_t	*ok_mp;
6324 		mblk_t	*discon_mp;
6325 		mblk_t  *conn_opts_mp;
6326 		int t_error, sys_error, do_disconnect;
6327 
6328 		conn_opts_mp = NULL;
6329 
6330 		if (tcp_conprim_opt_process(tcp, mp,
6331 		    &do_disconnect, &t_error, &sys_error) < 0) {
6332 			if (do_disconnect) {
6333 				ASSERT(t_error == 0 && sys_error == 0);
6334 				discon_mp = mi_tpi_discon_ind(NULL,
6335 				    ECONNREFUSED, 0);
6336 				if (!discon_mp) {
6337 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6338 					    TSYSERR, ENOMEM);
6339 					return;
6340 				}
6341 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6342 				if (!ok_mp) {
6343 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6344 					    TSYSERR, ENOMEM);
6345 					return;
6346 				}
6347 				qreply(q, ok_mp);
6348 				qreply(q, discon_mp); /* no flush! */
6349 			} else {
6350 				ASSERT(t_error != 0);
6351 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6352 				    sys_error);
6353 			}
6354 			return;
6355 		}
6356 		/*
6357 		 * Success in setting options, the mp option buffer represented
6358 		 * by OPT_length/offset has been potentially modified and
6359 		 * contains results of option processing. We copy it in
6360 		 * another mp to save it for potentially influencing returning
6361 		 * it in T_CONN_CONN.
6362 		 */
6363 		if (tcr->OPT_length != 0) { /* there are resulting options */
6364 			conn_opts_mp = copyb(mp);
6365 			if (!conn_opts_mp) {
6366 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6367 				    TSYSERR, ENOMEM);
6368 				return;
6369 			}
6370 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6371 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6372 			/*
6373 			 * Note:
6374 			 * These resulting option negotiation can include any
6375 			 * end-to-end negotiation options but there no such
6376 			 * thing (yet?) in our TCP/IP.
6377 			 */
6378 		}
6379 	}
6380 
6381 	/*
6382 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6383 	 * make sure that the template IP header in the tcp structure is an
6384 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6385 	 * need to this before we call tcp_bindi() so that the port lookup
6386 	 * code will look for ports in the correct port space (IPv4 and
6387 	 * IPv6 have separate port spaces).
6388 	 */
6389 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6390 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6391 		int err = 0;
6392 
6393 		err = tcp_header_init_ipv4(tcp);
6394 		if (err != 0) {
6395 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6396 			goto connect_failed;
6397 		}
6398 		if (tcp->tcp_lport != 0)
6399 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6400 	}
6401 
6402 	if (tcp->tcp_issocket) {
6403 		/*
6404 		 * TCP is _D_SODIRECT and sockfs is directly above so save
6405 		 * the shared sonode sodirect_t pointer (if any) to enable
6406 		 * TCP sodirect.
6407 		 */
6408 		tcp->tcp_sodirect = SOD_QTOSODP(tcp->tcp_rq);
6409 	}
6410 
6411 	switch (tcp->tcp_state) {
6412 	case TCPS_IDLE:
6413 		/*
6414 		 * We support quick connect, refer to comments in
6415 		 * tcp_connect_*()
6416 		 */
6417 		/* FALLTHRU */
6418 	case TCPS_BOUND:
6419 	case TCPS_LISTEN:
6420 		if (tcp->tcp_family == AF_INET6) {
6421 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6422 				tcp_connect_ipv6(tcp, mp,
6423 				    &sin6->sin6_addr,
6424 				    sin6->sin6_port, sin6->sin6_flowinfo,
6425 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6426 				return;
6427 			}
6428 			/*
6429 			 * Destination adress is mapped IPv6 address.
6430 			 * Source bound address should be unspecified or
6431 			 * IPv6 mapped address as well.
6432 			 */
6433 			if (!IN6_IS_ADDR_UNSPECIFIED(
6434 			    &tcp->tcp_bound_source_v6) &&
6435 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6436 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6437 				    EADDRNOTAVAIL);
6438 				break;
6439 			}
6440 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6441 			dstport = sin6->sin6_port;
6442 			srcid = sin6->__sin6_src_id;
6443 		} else {
6444 			dstaddrp = &sin->sin_addr.s_addr;
6445 			dstport = sin->sin_port;
6446 			srcid = 0;
6447 		}
6448 
6449 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6450 		return;
6451 	default:
6452 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6453 		break;
6454 	}
6455 	/*
6456 	 * Note: Code below is the "failure" case
6457 	 */
6458 	/* return error ack and blow away saved option results if any */
6459 connect_failed:
6460 	if (mp != NULL)
6461 		putnext(tcp->tcp_rq, mp);
6462 	else {
6463 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6464 		    TSYSERR, ENOMEM);
6465 	}
6466 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6467 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6468 }
6469 
6470 /*
6471  * Handle connect to IPv4 destinations, including connections for AF_INET6
6472  * sockets connecting to IPv4 mapped IPv6 destinations.
6473  */
6474 static void
6475 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6476     uint_t srcid)
6477 {
6478 	tcph_t	*tcph;
6479 	mblk_t	*mp1;
6480 	ipaddr_t dstaddr = *dstaddrp;
6481 	int32_t	oldstate;
6482 	uint16_t lport;
6483 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6484 
6485 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6486 
6487 	/* Check for attempt to connect to INADDR_ANY */
6488 	if (dstaddr == INADDR_ANY)  {
6489 		/*
6490 		 * SunOS 4.x and 4.3 BSD allow an application
6491 		 * to connect a TCP socket to INADDR_ANY.
6492 		 * When they do this, the kernel picks the
6493 		 * address of one interface and uses it
6494 		 * instead.  The kernel usually ends up
6495 		 * picking the address of the loopback
6496 		 * interface.  This is an undocumented feature.
6497 		 * However, we provide the same thing here
6498 		 * in order to have source and binary
6499 		 * compatibility with SunOS 4.x.
6500 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6501 		 * generate the T_CONN_CON.
6502 		 */
6503 		dstaddr = htonl(INADDR_LOOPBACK);
6504 		*dstaddrp = dstaddr;
6505 	}
6506 
6507 	/* Handle __sin6_src_id if socket not bound to an IP address */
6508 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6509 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6510 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6511 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6512 		    tcp->tcp_ipha->ipha_src);
6513 	}
6514 
6515 	/*
6516 	 * Don't let an endpoint connect to itself.  Note that
6517 	 * the test here does not catch the case where the
6518 	 * source IP addr was left unspecified by the user. In
6519 	 * this case, the source addr is set in tcp_adapt_ire()
6520 	 * using the reply to the T_BIND message that we send
6521 	 * down to IP here and the check is repeated in tcp_rput_other.
6522 	 */
6523 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6524 	    dstport == tcp->tcp_lport) {
6525 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6526 		goto failed;
6527 	}
6528 
6529 	tcp->tcp_ipha->ipha_dst = dstaddr;
6530 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6531 
6532 	/*
6533 	 * Massage a source route if any putting the first hop
6534 	 * in iph_dst. Compute a starting value for the checksum which
6535 	 * takes into account that the original iph_dst should be
6536 	 * included in the checksum but that ip will include the
6537 	 * first hop in the source route in the tcp checksum.
6538 	 */
6539 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6540 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6541 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6542 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6543 	if ((int)tcp->tcp_sum < 0)
6544 		tcp->tcp_sum--;
6545 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6546 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6547 	    (tcp->tcp_sum >> 16));
6548 	tcph = tcp->tcp_tcph;
6549 	*(uint16_t *)tcph->th_fport = dstport;
6550 	tcp->tcp_fport = dstport;
6551 
6552 	oldstate = tcp->tcp_state;
6553 	/*
6554 	 * At this point the remote destination address and remote port fields
6555 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6556 	 * have to see which state tcp was in so we can take apropriate action.
6557 	 */
6558 	if (oldstate == TCPS_IDLE) {
6559 		/*
6560 		 * We support a quick connect capability here, allowing
6561 		 * clients to transition directly from IDLE to SYN_SENT
6562 		 * tcp_bindi will pick an unused port, insert the connection
6563 		 * in the bind hash and transition to BOUND state.
6564 		 */
6565 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6566 		    tcp, B_TRUE);
6567 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6568 		    B_FALSE, B_FALSE);
6569 		if (lport == 0) {
6570 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6571 			goto failed;
6572 		}
6573 	}
6574 	tcp->tcp_state = TCPS_SYN_SENT;
6575 
6576 	/*
6577 	 * TODO: allow data with connect requests
6578 	 * by unlinking M_DATA trailers here and
6579 	 * linking them in behind the T_OK_ACK mblk.
6580 	 * The tcp_rput() bind ack handler would then
6581 	 * feed them to tcp_wput_data() rather than call
6582 	 * tcp_timer().
6583 	 */
6584 	mp = mi_tpi_ok_ack_alloc(mp);
6585 	if (!mp) {
6586 		tcp->tcp_state = oldstate;
6587 		goto failed;
6588 	}
6589 	if (tcp->tcp_family == AF_INET) {
6590 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6591 		    sizeof (ipa_conn_t));
6592 	} else {
6593 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6594 		    sizeof (ipa6_conn_t));
6595 	}
6596 	if (mp1) {
6597 		/*
6598 		 * We need to make sure that the conn_recv is set to a non-null
6599 		 * value before we insert the conn_t into the classifier table.
6600 		 * This is to avoid a race with an incoming packet which does
6601 		 * an ipcl_classify().
6602 		 */
6603 		tcp->tcp_connp->conn_recv = tcp_input;
6604 
6605 		/* Hang onto the T_OK_ACK for later. */
6606 		linkb(mp1, mp);
6607 		mblk_setcred(mp1, tcp->tcp_cred);
6608 		if (tcp->tcp_family == AF_INET)
6609 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6610 		else {
6611 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6612 			    &tcp->tcp_sticky_ipp);
6613 		}
6614 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6615 		tcp->tcp_active_open = 1;
6616 		/*
6617 		 * If the bind cannot complete immediately
6618 		 * IP will arrange to call tcp_rput_other
6619 		 * when the bind completes.
6620 		 */
6621 		if (mp1 != NULL)
6622 			tcp_rput_other(tcp, mp1);
6623 		return;
6624 	}
6625 	/* Error case */
6626 	tcp->tcp_state = oldstate;
6627 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6628 
6629 failed:
6630 	/* return error ack and blow away saved option results if any */
6631 	if (mp != NULL)
6632 		putnext(tcp->tcp_rq, mp);
6633 	else {
6634 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6635 		    TSYSERR, ENOMEM);
6636 	}
6637 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6638 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6639 
6640 }
6641 
6642 /*
6643  * Handle connect to IPv6 destinations.
6644  */
6645 static void
6646 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6647     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6648 {
6649 	tcph_t	*tcph;
6650 	mblk_t	*mp1;
6651 	ip6_rthdr_t *rth;
6652 	int32_t  oldstate;
6653 	uint16_t lport;
6654 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6655 
6656 	ASSERT(tcp->tcp_family == AF_INET6);
6657 
6658 	/*
6659 	 * If we're here, it means that the destination address is a native
6660 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6661 	 * reason why it might not be IPv6 is if the socket was bound to an
6662 	 * IPv4-mapped IPv6 address.
6663 	 */
6664 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6665 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6666 		goto failed;
6667 	}
6668 
6669 	/*
6670 	 * Interpret a zero destination to mean loopback.
6671 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6672 	 * generate the T_CONN_CON.
6673 	 */
6674 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6675 		*dstaddrp = ipv6_loopback;
6676 	}
6677 
6678 	/* Handle __sin6_src_id if socket not bound to an IP address */
6679 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6680 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6681 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6682 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6683 	}
6684 
6685 	/*
6686 	 * Take care of the scope_id now and add ip6i_t
6687 	 * if ip6i_t is not already allocated through TCP
6688 	 * sticky options. At this point tcp_ip6h does not
6689 	 * have dst info, thus use dstaddrp.
6690 	 */
6691 	if (scope_id != 0 &&
6692 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6693 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6694 		ip6i_t  *ip6i;
6695 
6696 		ipp->ipp_ifindex = scope_id;
6697 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6698 
6699 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6700 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6701 			/* Already allocated */
6702 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6703 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6704 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6705 		} else {
6706 			int reterr;
6707 
6708 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6709 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6710 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6711 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6712 			if (reterr != 0)
6713 				goto failed;
6714 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6715 		}
6716 	}
6717 
6718 	/*
6719 	 * Don't let an endpoint connect to itself.  Note that
6720 	 * the test here does not catch the case where the
6721 	 * source IP addr was left unspecified by the user. In
6722 	 * this case, the source addr is set in tcp_adapt_ire()
6723 	 * using the reply to the T_BIND message that we send
6724 	 * down to IP here and the check is repeated in tcp_rput_other.
6725 	 */
6726 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6727 	    (dstport == tcp->tcp_lport)) {
6728 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6729 		goto failed;
6730 	}
6731 
6732 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6733 	tcp->tcp_remote_v6 = *dstaddrp;
6734 	tcp->tcp_ip6h->ip6_vcf =
6735 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6736 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6737 
6738 
6739 	/*
6740 	 * Massage a routing header (if present) putting the first hop
6741 	 * in ip6_dst. Compute a starting value for the checksum which
6742 	 * takes into account that the original ip6_dst should be
6743 	 * included in the checksum but that ip will include the
6744 	 * first hop in the source route in the tcp checksum.
6745 	 */
6746 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6747 	if (rth != NULL) {
6748 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6749 		    tcps->tcps_netstack);
6750 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6751 		    (tcp->tcp_sum >> 16));
6752 	} else {
6753 		tcp->tcp_sum = 0;
6754 	}
6755 
6756 	tcph = tcp->tcp_tcph;
6757 	*(uint16_t *)tcph->th_fport = dstport;
6758 	tcp->tcp_fport = dstport;
6759 
6760 	oldstate = tcp->tcp_state;
6761 	/*
6762 	 * At this point the remote destination address and remote port fields
6763 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6764 	 * have to see which state tcp was in so we can take apropriate action.
6765 	 */
6766 	if (oldstate == TCPS_IDLE) {
6767 		/*
6768 		 * We support a quick connect capability here, allowing
6769 		 * clients to transition directly from IDLE to SYN_SENT
6770 		 * tcp_bindi will pick an unused port, insert the connection
6771 		 * in the bind hash and transition to BOUND state.
6772 		 */
6773 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6774 		    tcp, B_TRUE);
6775 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6776 		    B_FALSE, B_FALSE);
6777 		if (lport == 0) {
6778 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6779 			goto failed;
6780 		}
6781 	}
6782 	tcp->tcp_state = TCPS_SYN_SENT;
6783 	/*
6784 	 * TODO: allow data with connect requests
6785 	 * by unlinking M_DATA trailers here and
6786 	 * linking them in behind the T_OK_ACK mblk.
6787 	 * The tcp_rput() bind ack handler would then
6788 	 * feed them to tcp_wput_data() rather than call
6789 	 * tcp_timer().
6790 	 */
6791 	mp = mi_tpi_ok_ack_alloc(mp);
6792 	if (!mp) {
6793 		tcp->tcp_state = oldstate;
6794 		goto failed;
6795 	}
6796 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6797 	if (mp1) {
6798 		/*
6799 		 * We need to make sure that the conn_recv is set to a non-null
6800 		 * value before we insert the conn_t into the classifier table.
6801 		 * This is to avoid a race with an incoming packet which does
6802 		 * an ipcl_classify().
6803 		 */
6804 		tcp->tcp_connp->conn_recv = tcp_input;
6805 
6806 		/* Hang onto the T_OK_ACK for later. */
6807 		linkb(mp1, mp);
6808 		mblk_setcred(mp1, tcp->tcp_cred);
6809 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6810 		    &tcp->tcp_sticky_ipp);
6811 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6812 		tcp->tcp_active_open = 1;
6813 		/* ip_bind_v6() may return ACK or ERROR */
6814 		if (mp1 != NULL)
6815 			tcp_rput_other(tcp, mp1);
6816 		return;
6817 	}
6818 	/* Error case */
6819 	tcp->tcp_state = oldstate;
6820 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6821 
6822 failed:
6823 	/* return error ack and blow away saved option results if any */
6824 	if (mp != NULL)
6825 		putnext(tcp->tcp_rq, mp);
6826 	else {
6827 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6828 		    TSYSERR, ENOMEM);
6829 	}
6830 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6831 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6832 }
6833 
6834 /*
6835  * We need a stream q for detached closing tcp connections
6836  * to use.  Our client hereby indicates that this q is the
6837  * one to use.
6838  */
6839 static void
6840 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6841 {
6842 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6843 	queue_t	*q = tcp->tcp_wq;
6844 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6845 
6846 #ifdef NS_DEBUG
6847 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6848 	    tcps->tcps_netstack->netstack_stackid);
6849 #endif
6850 	mp->b_datap->db_type = M_IOCACK;
6851 	iocp->ioc_count = 0;
6852 	mutex_enter(&tcps->tcps_g_q_lock);
6853 	if (tcps->tcps_g_q != NULL) {
6854 		mutex_exit(&tcps->tcps_g_q_lock);
6855 		iocp->ioc_error = EALREADY;
6856 	} else {
6857 		mblk_t *mp1;
6858 
6859 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6860 		if (mp1 == NULL) {
6861 			mutex_exit(&tcps->tcps_g_q_lock);
6862 			iocp->ioc_error = ENOMEM;
6863 		} else {
6864 			tcps->tcps_g_q = tcp->tcp_rq;
6865 			mutex_exit(&tcps->tcps_g_q_lock);
6866 			iocp->ioc_error = 0;
6867 			iocp->ioc_rval = 0;
6868 			/*
6869 			 * We are passing tcp_sticky_ipp as NULL
6870 			 * as it is not useful for tcp_default queue
6871 			 *
6872 			 * Set conn_recv just in case.
6873 			 */
6874 			tcp->tcp_connp->conn_recv = tcp_conn_request;
6875 
6876 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6877 			if (mp1 != NULL)
6878 				tcp_rput_other(tcp, mp1);
6879 		}
6880 	}
6881 	qreply(q, mp);
6882 }
6883 
6884 /*
6885  * Our client hereby directs us to reject the connection request
6886  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6887  * of sending the appropriate RST, not an ICMP error.
6888  */
6889 static void
6890 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6891 {
6892 	tcp_t	*ltcp = NULL;
6893 	t_scalar_t seqnum;
6894 	conn_t	*connp;
6895 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6896 
6897 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6898 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6899 		tcp_err_ack(tcp, mp, TPROTO, 0);
6900 		return;
6901 	}
6902 
6903 	/*
6904 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6905 	 * when the stream is in BOUND state. Do not send a reset,
6906 	 * since the destination IP address is not valid, and it can
6907 	 * be the initialized value of all zeros (broadcast address).
6908 	 *
6909 	 * If TCP has sent down a bind request to IP and has not
6910 	 * received the reply, reject the request.  Otherwise, TCP
6911 	 * will be confused.
6912 	 */
6913 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6914 		if (tcp->tcp_debug) {
6915 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6916 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6917 		}
6918 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6919 		return;
6920 	}
6921 
6922 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6923 
6924 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6925 
6926 		/*
6927 		 * According to TPI, for non-listeners, ignore seqnum
6928 		 * and disconnect.
6929 		 * Following interpretation of -1 seqnum is historical
6930 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6931 		 * a valid seqnum should not be -1).
6932 		 *
6933 		 *	-1 means disconnect everything
6934 		 *	regardless even on a listener.
6935 		 */
6936 
6937 		int old_state = tcp->tcp_state;
6938 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6939 
6940 		/*
6941 		 * The connection can't be on the tcp_time_wait_head list
6942 		 * since it is not detached.
6943 		 */
6944 		ASSERT(tcp->tcp_time_wait_next == NULL);
6945 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6946 		ASSERT(tcp->tcp_time_wait_expire == 0);
6947 		ltcp = NULL;
6948 		/*
6949 		 * If it used to be a listener, check to make sure no one else
6950 		 * has taken the port before switching back to LISTEN state.
6951 		 */
6952 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6953 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6954 			    tcp->tcp_ipha->ipha_src,
6955 			    tcp->tcp_connp->conn_zoneid, ipst);
6956 			if (connp != NULL)
6957 				ltcp = connp->conn_tcp;
6958 		} else {
6959 			/* Allow tcp_bound_if listeners? */
6960 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6961 			    &tcp->tcp_ip6h->ip6_src, 0,
6962 			    tcp->tcp_connp->conn_zoneid, ipst);
6963 			if (connp != NULL)
6964 				ltcp = connp->conn_tcp;
6965 		}
6966 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6967 			tcp->tcp_state = TCPS_LISTEN;
6968 		} else if (old_state > TCPS_BOUND) {
6969 			tcp->tcp_conn_req_max = 0;
6970 			tcp->tcp_state = TCPS_BOUND;
6971 		}
6972 		if (ltcp != NULL)
6973 			CONN_DEC_REF(ltcp->tcp_connp);
6974 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6975 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6976 		} else if (old_state == TCPS_ESTABLISHED ||
6977 		    old_state == TCPS_CLOSE_WAIT) {
6978 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6979 		}
6980 
6981 		if (tcp->tcp_fused)
6982 			tcp_unfuse(tcp);
6983 
6984 		mutex_enter(&tcp->tcp_eager_lock);
6985 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6986 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6987 			tcp_eager_cleanup(tcp, 0);
6988 		}
6989 		mutex_exit(&tcp->tcp_eager_lock);
6990 
6991 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6992 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6993 
6994 		tcp_reinit(tcp);
6995 
6996 		if (old_state >= TCPS_ESTABLISHED) {
6997 			/* Send M_FLUSH according to TPI */
6998 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6999 		}
7000 		mp = mi_tpi_ok_ack_alloc(mp);
7001 		if (mp)
7002 			putnext(tcp->tcp_rq, mp);
7003 		return;
7004 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
7005 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
7006 		return;
7007 	}
7008 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
7009 		/* Send M_FLUSH according to TPI */
7010 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7011 	}
7012 	mp = mi_tpi_ok_ack_alloc(mp);
7013 	if (mp)
7014 		putnext(tcp->tcp_rq, mp);
7015 }
7016 
7017 /*
7018  * Diagnostic routine used to return a string associated with the tcp state.
7019  * Note that if the caller does not supply a buffer, it will use an internal
7020  * static string.  This means that if multiple threads call this function at
7021  * the same time, output can be corrupted...  Note also that this function
7022  * does not check the size of the supplied buffer.  The caller has to make
7023  * sure that it is big enough.
7024  */
7025 static char *
7026 tcp_display(tcp_t *tcp, char *sup_buf, char format)
7027 {
7028 	char		buf1[30];
7029 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
7030 	char		*buf;
7031 	char		*cp;
7032 	in6_addr_t	local, remote;
7033 	char		local_addrbuf[INET6_ADDRSTRLEN];
7034 	char		remote_addrbuf[INET6_ADDRSTRLEN];
7035 
7036 	if (sup_buf != NULL)
7037 		buf = sup_buf;
7038 	else
7039 		buf = priv_buf;
7040 
7041 	if (tcp == NULL)
7042 		return ("NULL_TCP");
7043 	switch (tcp->tcp_state) {
7044 	case TCPS_CLOSED:
7045 		cp = "TCP_CLOSED";
7046 		break;
7047 	case TCPS_IDLE:
7048 		cp = "TCP_IDLE";
7049 		break;
7050 	case TCPS_BOUND:
7051 		cp = "TCP_BOUND";
7052 		break;
7053 	case TCPS_LISTEN:
7054 		cp = "TCP_LISTEN";
7055 		break;
7056 	case TCPS_SYN_SENT:
7057 		cp = "TCP_SYN_SENT";
7058 		break;
7059 	case TCPS_SYN_RCVD:
7060 		cp = "TCP_SYN_RCVD";
7061 		break;
7062 	case TCPS_ESTABLISHED:
7063 		cp = "TCP_ESTABLISHED";
7064 		break;
7065 	case TCPS_CLOSE_WAIT:
7066 		cp = "TCP_CLOSE_WAIT";
7067 		break;
7068 	case TCPS_FIN_WAIT_1:
7069 		cp = "TCP_FIN_WAIT_1";
7070 		break;
7071 	case TCPS_CLOSING:
7072 		cp = "TCP_CLOSING";
7073 		break;
7074 	case TCPS_LAST_ACK:
7075 		cp = "TCP_LAST_ACK";
7076 		break;
7077 	case TCPS_FIN_WAIT_2:
7078 		cp = "TCP_FIN_WAIT_2";
7079 		break;
7080 	case TCPS_TIME_WAIT:
7081 		cp = "TCP_TIME_WAIT";
7082 		break;
7083 	default:
7084 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7085 		cp = buf1;
7086 		break;
7087 	}
7088 	switch (format) {
7089 	case DISP_ADDR_AND_PORT:
7090 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7091 			/*
7092 			 * Note that we use the remote address in the tcp_b
7093 			 * structure.  This means that it will print out
7094 			 * the real destination address, not the next hop's
7095 			 * address if source routing is used.
7096 			 */
7097 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7098 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7099 
7100 		} else {
7101 			local = tcp->tcp_ip_src_v6;
7102 			remote = tcp->tcp_remote_v6;
7103 		}
7104 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7105 		    sizeof (local_addrbuf));
7106 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7107 		    sizeof (remote_addrbuf));
7108 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7109 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7110 		    ntohs(tcp->tcp_fport), cp);
7111 		break;
7112 	case DISP_PORT_ONLY:
7113 	default:
7114 		(void) mi_sprintf(buf, "[%u, %u] %s",
7115 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7116 		break;
7117 	}
7118 
7119 	return (buf);
7120 }
7121 
7122 /*
7123  * Called via squeue to get on to eager's perimeter. It sends a
7124  * TH_RST if eager is in the fanout table. The listener wants the
7125  * eager to disappear either by means of tcp_eager_blowoff() or
7126  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
7127  * called (via squeue) if the eager cannot be inserted in the
7128  * fanout table in tcp_conn_request().
7129  */
7130 /* ARGSUSED */
7131 void
7132 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7133 {
7134 	conn_t	*econnp = (conn_t *)arg;
7135 	tcp_t	*eager = econnp->conn_tcp;
7136 	tcp_t	*listener = eager->tcp_listener;
7137 	tcp_stack_t	*tcps = eager->tcp_tcps;
7138 
7139 	/*
7140 	 * We could be called because listener is closing. Since
7141 	 * the eager is using listener's queue's, its not safe.
7142 	 * Better use the default queue just to send the TH_RST
7143 	 * out.
7144 	 */
7145 	ASSERT(tcps->tcps_g_q != NULL);
7146 	eager->tcp_rq = tcps->tcps_g_q;
7147 	eager->tcp_wq = WR(tcps->tcps_g_q);
7148 
7149 	/*
7150 	 * An eager's conn_fanout will be NULL if it's a duplicate
7151 	 * for an existing 4-tuples in the conn fanout table.
7152 	 * We don't want to send an RST out in such case.
7153 	 */
7154 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
7155 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7156 		    eager, eager->tcp_snxt, 0, TH_RST);
7157 	}
7158 
7159 	/* We are here because listener wants this eager gone */
7160 	if (listener != NULL) {
7161 		mutex_enter(&listener->tcp_eager_lock);
7162 		tcp_eager_unlink(eager);
7163 		if (eager->tcp_tconnind_started) {
7164 			/*
7165 			 * The eager has sent a conn_ind up to the
7166 			 * listener but listener decides to close
7167 			 * instead. We need to drop the extra ref
7168 			 * placed on eager in tcp_rput_data() before
7169 			 * sending the conn_ind to listener.
7170 			 */
7171 			CONN_DEC_REF(econnp);
7172 		}
7173 		mutex_exit(&listener->tcp_eager_lock);
7174 		CONN_DEC_REF(listener->tcp_connp);
7175 	}
7176 
7177 	if (eager->tcp_state > TCPS_BOUND)
7178 		tcp_close_detached(eager);
7179 }
7180 
7181 /*
7182  * Reset any eager connection hanging off this listener marked
7183  * with 'seqnum' and then reclaim it's resources.
7184  */
7185 static boolean_t
7186 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7187 {
7188 	tcp_t	*eager;
7189 	mblk_t 	*mp;
7190 	tcp_stack_t	*tcps = listener->tcp_tcps;
7191 
7192 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
7193 	eager = listener;
7194 	mutex_enter(&listener->tcp_eager_lock);
7195 	do {
7196 		eager = eager->tcp_eager_next_q;
7197 		if (eager == NULL) {
7198 			mutex_exit(&listener->tcp_eager_lock);
7199 			return (B_FALSE);
7200 		}
7201 	} while (eager->tcp_conn_req_seqnum != seqnum);
7202 
7203 	if (eager->tcp_closemp_used) {
7204 		mutex_exit(&listener->tcp_eager_lock);
7205 		return (B_TRUE);
7206 	}
7207 	eager->tcp_closemp_used = B_TRUE;
7208 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7209 	CONN_INC_REF(eager->tcp_connp);
7210 	mutex_exit(&listener->tcp_eager_lock);
7211 	mp = &eager->tcp_closemp;
7212 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7213 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7214 	return (B_TRUE);
7215 }
7216 
7217 /*
7218  * Reset any eager connection hanging off this listener
7219  * and then reclaim it's resources.
7220  */
7221 static void
7222 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7223 {
7224 	tcp_t	*eager;
7225 	mblk_t	*mp;
7226 	tcp_stack_t	*tcps = listener->tcp_tcps;
7227 
7228 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7229 
7230 	if (!q0_only) {
7231 		/* First cleanup q */
7232 		TCP_STAT(tcps, tcp_eager_blowoff_q);
7233 		eager = listener->tcp_eager_next_q;
7234 		while (eager != NULL) {
7235 			if (!eager->tcp_closemp_used) {
7236 				eager->tcp_closemp_used = B_TRUE;
7237 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7238 				CONN_INC_REF(eager->tcp_connp);
7239 				mp = &eager->tcp_closemp;
7240 				squeue_fill(eager->tcp_connp->conn_sqp, mp,
7241 				    tcp_eager_kill, eager->tcp_connp,
7242 				    SQTAG_TCP_EAGER_CLEANUP);
7243 			}
7244 			eager = eager->tcp_eager_next_q;
7245 		}
7246 	}
7247 	/* Then cleanup q0 */
7248 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
7249 	eager = listener->tcp_eager_next_q0;
7250 	while (eager != listener) {
7251 		if (!eager->tcp_closemp_used) {
7252 			eager->tcp_closemp_used = B_TRUE;
7253 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7254 			CONN_INC_REF(eager->tcp_connp);
7255 			mp = &eager->tcp_closemp;
7256 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7257 			    tcp_eager_kill, eager->tcp_connp,
7258 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
7259 		}
7260 		eager = eager->tcp_eager_next_q0;
7261 	}
7262 }
7263 
7264 /*
7265  * If we are an eager connection hanging off a listener that hasn't
7266  * formally accepted the connection yet, get off his list and blow off
7267  * any data that we have accumulated.
7268  */
7269 static void
7270 tcp_eager_unlink(tcp_t *tcp)
7271 {
7272 	tcp_t	*listener = tcp->tcp_listener;
7273 
7274 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7275 	ASSERT(listener != NULL);
7276 	if (tcp->tcp_eager_next_q0 != NULL) {
7277 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7278 
7279 		/* Remove the eager tcp from q0 */
7280 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7281 		    tcp->tcp_eager_prev_q0;
7282 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7283 		    tcp->tcp_eager_next_q0;
7284 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7285 		listener->tcp_conn_req_cnt_q0--;
7286 
7287 		tcp->tcp_eager_next_q0 = NULL;
7288 		tcp->tcp_eager_prev_q0 = NULL;
7289 
7290 		/*
7291 		 * Take the eager out, if it is in the list of droppable
7292 		 * eagers.
7293 		 */
7294 		MAKE_UNDROPPABLE(tcp);
7295 
7296 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7297 			/* we have timed out before */
7298 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7299 			listener->tcp_syn_rcvd_timeout--;
7300 		}
7301 	} else {
7302 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7303 		tcp_t	*prev = NULL;
7304 
7305 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7306 			if (tcpp[0] == tcp) {
7307 				if (listener->tcp_eager_last_q == tcp) {
7308 					/*
7309 					 * If we are unlinking the last
7310 					 * element on the list, adjust
7311 					 * tail pointer. Set tail pointer
7312 					 * to nil when list is empty.
7313 					 */
7314 					ASSERT(tcp->tcp_eager_next_q == NULL);
7315 					if (listener->tcp_eager_last_q ==
7316 					    listener->tcp_eager_next_q) {
7317 						listener->tcp_eager_last_q =
7318 						    NULL;
7319 					} else {
7320 						/*
7321 						 * We won't get here if there
7322 						 * is only one eager in the
7323 						 * list.
7324 						 */
7325 						ASSERT(prev != NULL);
7326 						listener->tcp_eager_last_q =
7327 						    prev;
7328 					}
7329 				}
7330 				tcpp[0] = tcp->tcp_eager_next_q;
7331 				tcp->tcp_eager_next_q = NULL;
7332 				tcp->tcp_eager_last_q = NULL;
7333 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7334 				listener->tcp_conn_req_cnt_q--;
7335 				break;
7336 			}
7337 			prev = tcpp[0];
7338 		}
7339 	}
7340 	tcp->tcp_listener = NULL;
7341 }
7342 
7343 /* Shorthand to generate and send TPI error acks to our client */
7344 static void
7345 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7346 {
7347 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7348 		putnext(tcp->tcp_rq, mp);
7349 }
7350 
7351 /* Shorthand to generate and send TPI error acks to our client */
7352 static void
7353 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7354     int t_error, int sys_error)
7355 {
7356 	struct T_error_ack	*teackp;
7357 
7358 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7359 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7360 		teackp = (struct T_error_ack *)mp->b_rptr;
7361 		teackp->ERROR_prim = primitive;
7362 		teackp->TLI_error = t_error;
7363 		teackp->UNIX_error = sys_error;
7364 		putnext(tcp->tcp_rq, mp);
7365 	}
7366 }
7367 
7368 /*
7369  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7370  * but instead the code relies on:
7371  * - the fact that the address of the array and its size never changes
7372  * - the atomic assignment of the elements of the array
7373  */
7374 /* ARGSUSED */
7375 static int
7376 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7377 {
7378 	int i;
7379 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7380 
7381 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7382 		if (tcps->tcps_g_epriv_ports[i] != 0)
7383 			(void) mi_mpprintf(mp, "%d ",
7384 			    tcps->tcps_g_epriv_ports[i]);
7385 	}
7386 	return (0);
7387 }
7388 
7389 /*
7390  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7391  * threads from changing it at the same time.
7392  */
7393 /* ARGSUSED */
7394 static int
7395 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7396     cred_t *cr)
7397 {
7398 	long	new_value;
7399 	int	i;
7400 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7401 
7402 	/*
7403 	 * Fail the request if the new value does not lie within the
7404 	 * port number limits.
7405 	 */
7406 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7407 	    new_value <= 0 || new_value >= 65536) {
7408 		return (EINVAL);
7409 	}
7410 
7411 	mutex_enter(&tcps->tcps_epriv_port_lock);
7412 	/* Check if the value is already in the list */
7413 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7414 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7415 			mutex_exit(&tcps->tcps_epriv_port_lock);
7416 			return (EEXIST);
7417 		}
7418 	}
7419 	/* Find an empty slot */
7420 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7421 		if (tcps->tcps_g_epriv_ports[i] == 0)
7422 			break;
7423 	}
7424 	if (i == tcps->tcps_g_num_epriv_ports) {
7425 		mutex_exit(&tcps->tcps_epriv_port_lock);
7426 		return (EOVERFLOW);
7427 	}
7428 	/* Set the new value */
7429 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7430 	mutex_exit(&tcps->tcps_epriv_port_lock);
7431 	return (0);
7432 }
7433 
7434 /*
7435  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7436  * threads from changing it at the same time.
7437  */
7438 /* ARGSUSED */
7439 static int
7440 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7441     cred_t *cr)
7442 {
7443 	long	new_value;
7444 	int	i;
7445 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7446 
7447 	/*
7448 	 * Fail the request if the new value does not lie within the
7449 	 * port number limits.
7450 	 */
7451 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7452 	    new_value >= 65536) {
7453 		return (EINVAL);
7454 	}
7455 
7456 	mutex_enter(&tcps->tcps_epriv_port_lock);
7457 	/* Check that the value is already in the list */
7458 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7459 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7460 			break;
7461 	}
7462 	if (i == tcps->tcps_g_num_epriv_ports) {
7463 		mutex_exit(&tcps->tcps_epriv_port_lock);
7464 		return (ESRCH);
7465 	}
7466 	/* Clear the value */
7467 	tcps->tcps_g_epriv_ports[i] = 0;
7468 	mutex_exit(&tcps->tcps_epriv_port_lock);
7469 	return (0);
7470 }
7471 
7472 /* Return the TPI/TLI equivalent of our current tcp_state */
7473 static int
7474 tcp_tpistate(tcp_t *tcp)
7475 {
7476 	switch (tcp->tcp_state) {
7477 	case TCPS_IDLE:
7478 		return (TS_UNBND);
7479 	case TCPS_LISTEN:
7480 		/*
7481 		 * Return whether there are outstanding T_CONN_IND waiting
7482 		 * for the matching T_CONN_RES. Therefore don't count q0.
7483 		 */
7484 		if (tcp->tcp_conn_req_cnt_q > 0)
7485 			return (TS_WRES_CIND);
7486 		else
7487 			return (TS_IDLE);
7488 	case TCPS_BOUND:
7489 		return (TS_IDLE);
7490 	case TCPS_SYN_SENT:
7491 		return (TS_WCON_CREQ);
7492 	case TCPS_SYN_RCVD:
7493 		/*
7494 		 * Note: assumption: this has to the active open SYN_RCVD.
7495 		 * The passive instance is detached in SYN_RCVD stage of
7496 		 * incoming connection processing so we cannot get request
7497 		 * for T_info_ack on it.
7498 		 */
7499 		return (TS_WACK_CRES);
7500 	case TCPS_ESTABLISHED:
7501 		return (TS_DATA_XFER);
7502 	case TCPS_CLOSE_WAIT:
7503 		return (TS_WREQ_ORDREL);
7504 	case TCPS_FIN_WAIT_1:
7505 		return (TS_WIND_ORDREL);
7506 	case TCPS_FIN_WAIT_2:
7507 		return (TS_WIND_ORDREL);
7508 
7509 	case TCPS_CLOSING:
7510 	case TCPS_LAST_ACK:
7511 	case TCPS_TIME_WAIT:
7512 	case TCPS_CLOSED:
7513 		/*
7514 		 * Following TS_WACK_DREQ7 is a rendition of "not
7515 		 * yet TS_IDLE" TPI state. There is no best match to any
7516 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7517 		 * choose a value chosen that will map to TLI/XTI level
7518 		 * state of TSTATECHNG (state is process of changing) which
7519 		 * captures what this dummy state represents.
7520 		 */
7521 		return (TS_WACK_DREQ7);
7522 	default:
7523 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7524 		    tcp->tcp_state, tcp_display(tcp, NULL,
7525 		    DISP_PORT_ONLY));
7526 		return (TS_UNBND);
7527 	}
7528 }
7529 
7530 static void
7531 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7532 {
7533 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7534 
7535 	if (tcp->tcp_family == AF_INET6)
7536 		*tia = tcp_g_t_info_ack_v6;
7537 	else
7538 		*tia = tcp_g_t_info_ack;
7539 	tia->CURRENT_state = tcp_tpistate(tcp);
7540 	tia->OPT_size = tcp_max_optsize;
7541 	if (tcp->tcp_mss == 0) {
7542 		/* Not yet set - tcp_open does not set mss */
7543 		if (tcp->tcp_ipversion == IPV4_VERSION)
7544 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7545 		else
7546 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7547 	} else {
7548 		tia->TIDU_size = tcp->tcp_mss;
7549 	}
7550 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7551 }
7552 
7553 /*
7554  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7555  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7556  * tcp_g_t_info_ack.  The current state of the stream is copied from
7557  * tcp_state.
7558  */
7559 static void
7560 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7561 {
7562 	t_uscalar_t		cap_bits1;
7563 	struct T_capability_ack	*tcap;
7564 
7565 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7566 		freemsg(mp);
7567 		return;
7568 	}
7569 
7570 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7571 
7572 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7573 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7574 	if (mp == NULL)
7575 		return;
7576 
7577 	tcap = (struct T_capability_ack *)mp->b_rptr;
7578 	tcap->CAP_bits1 = 0;
7579 
7580 	if (cap_bits1 & TC1_INFO) {
7581 		tcp_copy_info(&tcap->INFO_ack, tcp);
7582 		tcap->CAP_bits1 |= TC1_INFO;
7583 	}
7584 
7585 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7586 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7587 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7588 	}
7589 
7590 	putnext(tcp->tcp_rq, mp);
7591 }
7592 
7593 /*
7594  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7595  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7596  * The current state of the stream is copied from tcp_state.
7597  */
7598 static void
7599 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7600 {
7601 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7602 	    T_INFO_ACK);
7603 	if (!mp) {
7604 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7605 		return;
7606 	}
7607 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7608 	putnext(tcp->tcp_rq, mp);
7609 }
7610 
7611 /* Respond to the TPI addr request */
7612 static void
7613 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7614 {
7615 	sin_t	*sin;
7616 	mblk_t	*ackmp;
7617 	struct T_addr_ack *taa;
7618 
7619 	/* Make it large enough for worst case */
7620 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7621 	    2 * sizeof (sin6_t), 1);
7622 	if (ackmp == NULL) {
7623 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7624 		return;
7625 	}
7626 
7627 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7628 		tcp_addr_req_ipv6(tcp, ackmp);
7629 		return;
7630 	}
7631 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7632 
7633 	bzero(taa, sizeof (struct T_addr_ack));
7634 	ackmp->b_wptr = (uchar_t *)&taa[1];
7635 
7636 	taa->PRIM_type = T_ADDR_ACK;
7637 	ackmp->b_datap->db_type = M_PCPROTO;
7638 
7639 	/*
7640 	 * Note: Following code assumes 32 bit alignment of basic
7641 	 * data structures like sin_t and struct T_addr_ack.
7642 	 */
7643 	if (tcp->tcp_state >= TCPS_BOUND) {
7644 		/*
7645 		 * Fill in local address
7646 		 */
7647 		taa->LOCADDR_length = sizeof (sin_t);
7648 		taa->LOCADDR_offset = sizeof (*taa);
7649 
7650 		sin = (sin_t *)&taa[1];
7651 
7652 		/* Fill zeroes and then intialize non-zero fields */
7653 		*sin = sin_null;
7654 
7655 		sin->sin_family = AF_INET;
7656 
7657 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7658 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7659 
7660 		ackmp->b_wptr = (uchar_t *)&sin[1];
7661 
7662 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7663 			/*
7664 			 * Fill in Remote address
7665 			 */
7666 			taa->REMADDR_length = sizeof (sin_t);
7667 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7668 			    taa->LOCADDR_length);
7669 
7670 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7671 			*sin = sin_null;
7672 			sin->sin_family = AF_INET;
7673 			sin->sin_addr.s_addr = tcp->tcp_remote;
7674 			sin->sin_port = tcp->tcp_fport;
7675 
7676 			ackmp->b_wptr = (uchar_t *)&sin[1];
7677 		}
7678 	}
7679 	putnext(tcp->tcp_rq, ackmp);
7680 }
7681 
7682 /* Assumes that tcp_addr_req gets enough space and alignment */
7683 static void
7684 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7685 {
7686 	sin6_t	*sin6;
7687 	struct T_addr_ack *taa;
7688 
7689 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7690 	ASSERT(OK_32PTR(ackmp->b_rptr));
7691 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7692 	    2 * sizeof (sin6_t));
7693 
7694 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7695 
7696 	bzero(taa, sizeof (struct T_addr_ack));
7697 	ackmp->b_wptr = (uchar_t *)&taa[1];
7698 
7699 	taa->PRIM_type = T_ADDR_ACK;
7700 	ackmp->b_datap->db_type = M_PCPROTO;
7701 
7702 	/*
7703 	 * Note: Following code assumes 32 bit alignment of basic
7704 	 * data structures like sin6_t and struct T_addr_ack.
7705 	 */
7706 	if (tcp->tcp_state >= TCPS_BOUND) {
7707 		/*
7708 		 * Fill in local address
7709 		 */
7710 		taa->LOCADDR_length = sizeof (sin6_t);
7711 		taa->LOCADDR_offset = sizeof (*taa);
7712 
7713 		sin6 = (sin6_t *)&taa[1];
7714 		*sin6 = sin6_null;
7715 
7716 		sin6->sin6_family = AF_INET6;
7717 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7718 		sin6->sin6_port = tcp->tcp_lport;
7719 
7720 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7721 
7722 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7723 			/*
7724 			 * Fill in Remote address
7725 			 */
7726 			taa->REMADDR_length = sizeof (sin6_t);
7727 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7728 			    taa->LOCADDR_length);
7729 
7730 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7731 			*sin6 = sin6_null;
7732 			sin6->sin6_family = AF_INET6;
7733 			sin6->sin6_flowinfo =
7734 			    tcp->tcp_ip6h->ip6_vcf &
7735 			    ~IPV6_VERS_AND_FLOW_MASK;
7736 			sin6->sin6_addr = tcp->tcp_remote_v6;
7737 			sin6->sin6_port = tcp->tcp_fport;
7738 
7739 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7740 		}
7741 	}
7742 	putnext(tcp->tcp_rq, ackmp);
7743 }
7744 
7745 /*
7746  * Handle reinitialization of a tcp structure.
7747  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7748  */
7749 static void
7750 tcp_reinit(tcp_t *tcp)
7751 {
7752 	mblk_t	*mp;
7753 	int 	err;
7754 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7755 
7756 	TCP_STAT(tcps, tcp_reinit_calls);
7757 
7758 	/* tcp_reinit should never be called for detached tcp_t's */
7759 	ASSERT(tcp->tcp_listener == NULL);
7760 	ASSERT((tcp->tcp_family == AF_INET &&
7761 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7762 	    (tcp->tcp_family == AF_INET6 &&
7763 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7764 	    tcp->tcp_ipversion == IPV6_VERSION)));
7765 
7766 	/* Cancel outstanding timers */
7767 	tcp_timers_stop(tcp);
7768 
7769 	/*
7770 	 * Reset everything in the state vector, after updating global
7771 	 * MIB data from instance counters.
7772 	 */
7773 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7774 	tcp->tcp_ibsegs = 0;
7775 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7776 	tcp->tcp_obsegs = 0;
7777 
7778 	tcp_close_mpp(&tcp->tcp_xmit_head);
7779 	if (tcp->tcp_snd_zcopy_aware)
7780 		tcp_zcopy_notify(tcp);
7781 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7782 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7783 	mutex_enter(&tcp->tcp_non_sq_lock);
7784 	if (tcp->tcp_flow_stopped &&
7785 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7786 		tcp_clrqfull(tcp);
7787 	}
7788 	mutex_exit(&tcp->tcp_non_sq_lock);
7789 	tcp_close_mpp(&tcp->tcp_reass_head);
7790 	tcp->tcp_reass_tail = NULL;
7791 	if (tcp->tcp_rcv_list != NULL) {
7792 		/* Free b_next chain */
7793 		tcp_close_mpp(&tcp->tcp_rcv_list);
7794 		tcp->tcp_rcv_last_head = NULL;
7795 		tcp->tcp_rcv_last_tail = NULL;
7796 		tcp->tcp_rcv_cnt = 0;
7797 	}
7798 	tcp->tcp_rcv_last_tail = NULL;
7799 
7800 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7801 		freemsg(mp);
7802 		tcp->tcp_urp_mp = NULL;
7803 	}
7804 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7805 		freemsg(mp);
7806 		tcp->tcp_urp_mark_mp = NULL;
7807 	}
7808 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7809 		freeb(tcp->tcp_fused_sigurg_mp);
7810 		tcp->tcp_fused_sigurg_mp = NULL;
7811 	}
7812 	if (tcp->tcp_ordrel_mp != NULL) {
7813 		freeb(tcp->tcp_ordrel_mp);
7814 		tcp->tcp_ordrel_mp = NULL;
7815 	}
7816 
7817 	/*
7818 	 * Following is a union with two members which are
7819 	 * identical types and size so the following cleanup
7820 	 * is enough.
7821 	 */
7822 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7823 
7824 	CL_INET_DISCONNECT(tcp);
7825 
7826 	/*
7827 	 * The connection can't be on the tcp_time_wait_head list
7828 	 * since it is not detached.
7829 	 */
7830 	ASSERT(tcp->tcp_time_wait_next == NULL);
7831 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7832 	ASSERT(tcp->tcp_time_wait_expire == 0);
7833 
7834 	if (tcp->tcp_kssl_pending) {
7835 		tcp->tcp_kssl_pending = B_FALSE;
7836 
7837 		/* Don't reset if the initialized by bind. */
7838 		if (tcp->tcp_kssl_ent != NULL) {
7839 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7840 			    KSSL_NO_PROXY);
7841 		}
7842 	}
7843 	if (tcp->tcp_kssl_ctx != NULL) {
7844 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7845 		tcp->tcp_kssl_ctx = NULL;
7846 	}
7847 
7848 	/*
7849 	 * Reset/preserve other values
7850 	 */
7851 	tcp_reinit_values(tcp);
7852 	ipcl_hash_remove(tcp->tcp_connp);
7853 	conn_delete_ire(tcp->tcp_connp, NULL);
7854 	tcp_ipsec_cleanup(tcp);
7855 
7856 	if (tcp->tcp_conn_req_max != 0) {
7857 		/*
7858 		 * This is the case when a TLI program uses the same
7859 		 * transport end point to accept a connection.  This
7860 		 * makes the TCP both a listener and acceptor.  When
7861 		 * this connection is closed, we need to set the state
7862 		 * back to TCPS_LISTEN.  Make sure that the eager list
7863 		 * is reinitialized.
7864 		 *
7865 		 * Note that this stream is still bound to the four
7866 		 * tuples of the previous connection in IP.  If a new
7867 		 * SYN with different foreign address comes in, IP will
7868 		 * not find it and will send it to the global queue.  In
7869 		 * the global queue, TCP will do a tcp_lookup_listener()
7870 		 * to find this stream.  This works because this stream
7871 		 * is only removed from connected hash.
7872 		 *
7873 		 */
7874 		tcp->tcp_state = TCPS_LISTEN;
7875 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7876 		tcp->tcp_eager_next_drop_q0 = tcp;
7877 		tcp->tcp_eager_prev_drop_q0 = tcp;
7878 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7879 		if (tcp->tcp_family == AF_INET6) {
7880 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7881 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7882 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7883 		} else {
7884 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7885 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7886 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7887 		}
7888 	} else {
7889 		tcp->tcp_state = TCPS_BOUND;
7890 	}
7891 
7892 	/*
7893 	 * Initialize to default values
7894 	 * Can't fail since enough header template space already allocated
7895 	 * at open().
7896 	 */
7897 	err = tcp_init_values(tcp);
7898 	ASSERT(err == 0);
7899 	/* Restore state in tcp_tcph */
7900 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7901 	if (tcp->tcp_ipversion == IPV4_VERSION)
7902 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7903 	else
7904 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7905 	/*
7906 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7907 	 * since the lookup funcs can only lookup on tcp_t
7908 	 */
7909 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7910 
7911 	ASSERT(tcp->tcp_ptpbhn != NULL);
7912 	tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7913 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7914 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7915 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7916 }
7917 
7918 /*
7919  * Force values to zero that need be zero.
7920  * Do not touch values asociated with the BOUND or LISTEN state
7921  * since the connection will end up in that state after the reinit.
7922  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7923  * structure!
7924  */
7925 static void
7926 tcp_reinit_values(tcp)
7927 	tcp_t *tcp;
7928 {
7929 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7930 
7931 #ifndef	lint
7932 #define	DONTCARE(x)
7933 #define	PRESERVE(x)
7934 #else
7935 #define	DONTCARE(x)	((x) = (x))
7936 #define	PRESERVE(x)	((x) = (x))
7937 #endif	/* lint */
7938 
7939 	PRESERVE(tcp->tcp_bind_hash);
7940 	PRESERVE(tcp->tcp_ptpbhn);
7941 	PRESERVE(tcp->tcp_acceptor_hash);
7942 	PRESERVE(tcp->tcp_ptpahn);
7943 
7944 	/* Should be ASSERT NULL on these with new code! */
7945 	ASSERT(tcp->tcp_time_wait_next == NULL);
7946 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7947 	ASSERT(tcp->tcp_time_wait_expire == 0);
7948 	PRESERVE(tcp->tcp_state);
7949 	PRESERVE(tcp->tcp_rq);
7950 	PRESERVE(tcp->tcp_wq);
7951 
7952 	ASSERT(tcp->tcp_xmit_head == NULL);
7953 	ASSERT(tcp->tcp_xmit_last == NULL);
7954 	ASSERT(tcp->tcp_unsent == 0);
7955 	ASSERT(tcp->tcp_xmit_tail == NULL);
7956 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7957 
7958 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7959 	tcp->tcp_suna = 0;			/* Displayed in mib */
7960 	tcp->tcp_swnd = 0;
7961 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7962 
7963 	ASSERT(tcp->tcp_ibsegs == 0);
7964 	ASSERT(tcp->tcp_obsegs == 0);
7965 
7966 	if (tcp->tcp_iphc != NULL) {
7967 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7968 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7969 	}
7970 
7971 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7972 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7973 	DONTCARE(tcp->tcp_ipha);
7974 	DONTCARE(tcp->tcp_ip6h);
7975 	DONTCARE(tcp->tcp_ip_hdr_len);
7976 	DONTCARE(tcp->tcp_tcph);
7977 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7978 	tcp->tcp_valid_bits = 0;
7979 
7980 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7981 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7982 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7983 	tcp->tcp_last_rcv_lbolt = 0;
7984 
7985 	tcp->tcp_init_cwnd = 0;
7986 
7987 	tcp->tcp_urp_last_valid = 0;
7988 	tcp->tcp_hard_binding = 0;
7989 	tcp->tcp_hard_bound = 0;
7990 	PRESERVE(tcp->tcp_cred);
7991 	PRESERVE(tcp->tcp_cpid);
7992 	PRESERVE(tcp->tcp_open_time);
7993 	PRESERVE(tcp->tcp_exclbind);
7994 
7995 	tcp->tcp_fin_acked = 0;
7996 	tcp->tcp_fin_rcvd = 0;
7997 	tcp->tcp_fin_sent = 0;
7998 	tcp->tcp_ordrel_done = 0;
7999 
8000 	tcp->tcp_debug = 0;
8001 	tcp->tcp_dontroute = 0;
8002 	tcp->tcp_broadcast = 0;
8003 
8004 	tcp->tcp_useloopback = 0;
8005 	tcp->tcp_reuseaddr = 0;
8006 	tcp->tcp_oobinline = 0;
8007 	tcp->tcp_dgram_errind = 0;
8008 
8009 	tcp->tcp_detached = 0;
8010 	tcp->tcp_bind_pending = 0;
8011 	tcp->tcp_unbind_pending = 0;
8012 
8013 	tcp->tcp_snd_ws_ok = B_FALSE;
8014 	tcp->tcp_snd_ts_ok = B_FALSE;
8015 	tcp->tcp_linger = 0;
8016 	tcp->tcp_ka_enabled = 0;
8017 	tcp->tcp_zero_win_probe = 0;
8018 
8019 	tcp->tcp_loopback = 0;
8020 	tcp->tcp_refuse = 0;
8021 	tcp->tcp_localnet = 0;
8022 	tcp->tcp_syn_defense = 0;
8023 	tcp->tcp_set_timer = 0;
8024 
8025 	tcp->tcp_active_open = 0;
8026 	tcp->tcp_rexmit = B_FALSE;
8027 	tcp->tcp_xmit_zc_clean = B_FALSE;
8028 
8029 	tcp->tcp_snd_sack_ok = B_FALSE;
8030 	PRESERVE(tcp->tcp_recvdstaddr);
8031 	tcp->tcp_hwcksum = B_FALSE;
8032 
8033 	tcp->tcp_ire_ill_check_done = B_FALSE;
8034 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
8035 
8036 	tcp->tcp_mdt = B_FALSE;
8037 	tcp->tcp_mdt_hdr_head = 0;
8038 	tcp->tcp_mdt_hdr_tail = 0;
8039 
8040 	tcp->tcp_conn_def_q0 = 0;
8041 	tcp->tcp_ip_forward_progress = B_FALSE;
8042 	tcp->tcp_anon_priv_bind = 0;
8043 	tcp->tcp_ecn_ok = B_FALSE;
8044 
8045 	tcp->tcp_cwr = B_FALSE;
8046 	tcp->tcp_ecn_echo_on = B_FALSE;
8047 
8048 	if (tcp->tcp_sack_info != NULL) {
8049 		if (tcp->tcp_notsack_list != NULL) {
8050 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
8051 		}
8052 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
8053 		tcp->tcp_sack_info = NULL;
8054 	}
8055 
8056 	tcp->tcp_rcv_ws = 0;
8057 	tcp->tcp_snd_ws = 0;
8058 	tcp->tcp_ts_recent = 0;
8059 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
8060 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
8061 	tcp->tcp_if_mtu = 0;
8062 
8063 	ASSERT(tcp->tcp_reass_head == NULL);
8064 	ASSERT(tcp->tcp_reass_tail == NULL);
8065 
8066 	tcp->tcp_cwnd_cnt = 0;
8067 
8068 	ASSERT(tcp->tcp_rcv_list == NULL);
8069 	ASSERT(tcp->tcp_rcv_last_head == NULL);
8070 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
8071 	ASSERT(tcp->tcp_rcv_cnt == 0);
8072 
8073 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8074 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8075 	tcp->tcp_csuna = 0;
8076 
8077 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8078 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8079 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8080 	tcp->tcp_rtt_update = 0;
8081 
8082 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8083 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8084 
8085 	tcp->tcp_rack = 0;			/* Displayed in mib */
8086 	tcp->tcp_rack_cnt = 0;
8087 	tcp->tcp_rack_cur_max = 0;
8088 	tcp->tcp_rack_abs_max = 0;
8089 
8090 	tcp->tcp_max_swnd = 0;
8091 
8092 	ASSERT(tcp->tcp_listener == NULL);
8093 
8094 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8095 
8096 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8097 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8098 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8099 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8100 
8101 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8102 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8103 	PRESERVE(tcp->tcp_conn_req_max);
8104 	PRESERVE(tcp->tcp_conn_req_seqnum);
8105 
8106 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8107 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8108 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8109 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8110 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8111 
8112 	tcp->tcp_lingertime = 0;
8113 
8114 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8115 	ASSERT(tcp->tcp_urp_mp == NULL);
8116 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8117 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8118 
8119 	ASSERT(tcp->tcp_eager_next_q == NULL);
8120 	ASSERT(tcp->tcp_eager_last_q == NULL);
8121 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8122 	    tcp->tcp_eager_prev_q0 == NULL) ||
8123 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8124 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8125 
8126 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
8127 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
8128 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
8129 
8130 	tcp->tcp_client_errno = 0;
8131 
8132 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8133 
8134 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8135 
8136 	PRESERVE(tcp->tcp_bound_source_v6);
8137 	tcp->tcp_last_sent_len = 0;
8138 	tcp->tcp_dupack_cnt = 0;
8139 
8140 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8141 	PRESERVE(tcp->tcp_lport);
8142 
8143 	PRESERVE(tcp->tcp_acceptor_lockp);
8144 
8145 	ASSERT(tcp->tcp_ordrel_mp == NULL);
8146 	PRESERVE(tcp->tcp_acceptor_id);
8147 	DONTCARE(tcp->tcp_ipsec_overhead);
8148 
8149 	PRESERVE(tcp->tcp_family);
8150 	if (tcp->tcp_family == AF_INET6) {
8151 		tcp->tcp_ipversion = IPV6_VERSION;
8152 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
8153 	} else {
8154 		tcp->tcp_ipversion = IPV4_VERSION;
8155 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
8156 	}
8157 
8158 	tcp->tcp_bound_if = 0;
8159 	tcp->tcp_ipv6_recvancillary = 0;
8160 	tcp->tcp_recvifindex = 0;
8161 	tcp->tcp_recvhops = 0;
8162 	tcp->tcp_closed = 0;
8163 	tcp->tcp_cleandeathtag = 0;
8164 	if (tcp->tcp_hopopts != NULL) {
8165 		mi_free(tcp->tcp_hopopts);
8166 		tcp->tcp_hopopts = NULL;
8167 		tcp->tcp_hopoptslen = 0;
8168 	}
8169 	ASSERT(tcp->tcp_hopoptslen == 0);
8170 	if (tcp->tcp_dstopts != NULL) {
8171 		mi_free(tcp->tcp_dstopts);
8172 		tcp->tcp_dstopts = NULL;
8173 		tcp->tcp_dstoptslen = 0;
8174 	}
8175 	ASSERT(tcp->tcp_dstoptslen == 0);
8176 	if (tcp->tcp_rtdstopts != NULL) {
8177 		mi_free(tcp->tcp_rtdstopts);
8178 		tcp->tcp_rtdstopts = NULL;
8179 		tcp->tcp_rtdstoptslen = 0;
8180 	}
8181 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8182 	if (tcp->tcp_rthdr != NULL) {
8183 		mi_free(tcp->tcp_rthdr);
8184 		tcp->tcp_rthdr = NULL;
8185 		tcp->tcp_rthdrlen = 0;
8186 	}
8187 	ASSERT(tcp->tcp_rthdrlen == 0);
8188 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8189 
8190 	/* Reset fusion-related fields */
8191 	tcp->tcp_fused = B_FALSE;
8192 	tcp->tcp_unfusable = B_FALSE;
8193 	tcp->tcp_fused_sigurg = B_FALSE;
8194 	tcp->tcp_direct_sockfs = B_FALSE;
8195 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8196 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8197 	tcp->tcp_loopback_peer = NULL;
8198 	tcp->tcp_fuse_rcv_hiwater = 0;
8199 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8200 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8201 
8202 	tcp->tcp_lso = B_FALSE;
8203 
8204 	tcp->tcp_in_ack_unsent = 0;
8205 	tcp->tcp_cork = B_FALSE;
8206 	tcp->tcp_tconnind_started = B_FALSE;
8207 
8208 	PRESERVE(tcp->tcp_squeue_bytes);
8209 
8210 	ASSERT(tcp->tcp_kssl_ctx == NULL);
8211 	ASSERT(!tcp->tcp_kssl_pending);
8212 	PRESERVE(tcp->tcp_kssl_ent);
8213 
8214 	/* Sodirect */
8215 	tcp->tcp_sodirect = NULL;
8216 
8217 	tcp->tcp_closemp_used = B_FALSE;
8218 
8219 	PRESERVE(tcp->tcp_rsrv_mp);
8220 	PRESERVE(tcp->tcp_rsrv_mp_lock);
8221 
8222 #ifdef DEBUG
8223 	DONTCARE(tcp->tcmp_stk[0]);
8224 #endif
8225 
8226 
8227 #undef	DONTCARE
8228 #undef	PRESERVE
8229 }
8230 
8231 /*
8232  * Allocate necessary resources and initialize state vector.
8233  * Guaranteed not to fail so that when an error is returned,
8234  * the caller doesn't need to do any additional cleanup.
8235  */
8236 int
8237 tcp_init(tcp_t *tcp, queue_t *q)
8238 {
8239 	int	err;
8240 
8241 	tcp->tcp_rq = q;
8242 	tcp->tcp_wq = WR(q);
8243 	tcp->tcp_state = TCPS_IDLE;
8244 	if ((err = tcp_init_values(tcp)) != 0)
8245 		tcp_timers_stop(tcp);
8246 	return (err);
8247 }
8248 
8249 static int
8250 tcp_init_values(tcp_t *tcp)
8251 {
8252 	int	err;
8253 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8254 
8255 	ASSERT((tcp->tcp_family == AF_INET &&
8256 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8257 	    (tcp->tcp_family == AF_INET6 &&
8258 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8259 	    tcp->tcp_ipversion == IPV6_VERSION)));
8260 
8261 	/*
8262 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8263 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8264 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8265 	 * during first few transmissions of a connection as seen in slow
8266 	 * links.
8267 	 */
8268 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
8269 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
8270 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8271 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8272 	    tcps->tcps_conn_grace_period;
8273 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
8274 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
8275 	tcp->tcp_timer_backoff = 0;
8276 	tcp->tcp_ms_we_have_waited = 0;
8277 	tcp->tcp_last_recv_time = lbolt;
8278 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
8279 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8280 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8281 
8282 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
8283 
8284 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
8285 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
8286 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
8287 	/*
8288 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8289 	 * passive open.
8290 	 */
8291 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
8292 
8293 	tcp->tcp_naglim = tcps->tcps_naglim_def;
8294 
8295 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8296 
8297 	tcp->tcp_mdt_hdr_head = 0;
8298 	tcp->tcp_mdt_hdr_tail = 0;
8299 
8300 	/* Reset fusion-related fields */
8301 	tcp->tcp_fused = B_FALSE;
8302 	tcp->tcp_unfusable = B_FALSE;
8303 	tcp->tcp_fused_sigurg = B_FALSE;
8304 	tcp->tcp_direct_sockfs = B_FALSE;
8305 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8306 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8307 	tcp->tcp_loopback_peer = NULL;
8308 	tcp->tcp_fuse_rcv_hiwater = 0;
8309 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8310 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8311 
8312 	/* Sodirect */
8313 	tcp->tcp_sodirect = NULL;
8314 
8315 	/* Initialize the header template */
8316 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8317 		err = tcp_header_init_ipv4(tcp);
8318 	} else {
8319 		err = tcp_header_init_ipv6(tcp);
8320 	}
8321 	if (err)
8322 		return (err);
8323 
8324 	/*
8325 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8326 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8327 	 */
8328 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8329 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8330 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8331 
8332 	tcp->tcp_cork = B_FALSE;
8333 	/*
8334 	 * Init the tcp_debug option.  This value determines whether TCP
8335 	 * calls strlog() to print out debug messages.  Doing this
8336 	 * initialization here means that this value is not inherited thru
8337 	 * tcp_reinit().
8338 	 */
8339 	tcp->tcp_debug = tcps->tcps_dbg;
8340 
8341 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8342 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8343 
8344 	return (0);
8345 }
8346 
8347 /*
8348  * Initialize the IPv4 header. Loses any record of any IP options.
8349  */
8350 static int
8351 tcp_header_init_ipv4(tcp_t *tcp)
8352 {
8353 	tcph_t		*tcph;
8354 	uint32_t	sum;
8355 	conn_t		*connp;
8356 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8357 
8358 	/*
8359 	 * This is a simple initialization. If there's
8360 	 * already a template, it should never be too small,
8361 	 * so reuse it.  Otherwise, allocate space for the new one.
8362 	 */
8363 	if (tcp->tcp_iphc == NULL) {
8364 		ASSERT(tcp->tcp_iphc_len == 0);
8365 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8366 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8367 		if (tcp->tcp_iphc == NULL) {
8368 			tcp->tcp_iphc_len = 0;
8369 			return (ENOMEM);
8370 		}
8371 	}
8372 
8373 	/* options are gone; may need a new label */
8374 	connp = tcp->tcp_connp;
8375 	connp->conn_mlp_type = mlptSingle;
8376 	connp->conn_ulp_labeled = !is_system_labeled();
8377 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8378 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8379 	tcp->tcp_ip6h = NULL;
8380 	tcp->tcp_ipversion = IPV4_VERSION;
8381 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8382 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8383 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8384 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8385 	tcp->tcp_ipha->ipha_version_and_hdr_length
8386 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8387 	tcp->tcp_ipha->ipha_ident = 0;
8388 
8389 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8390 	tcp->tcp_tos = 0;
8391 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8392 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8393 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8394 
8395 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8396 	tcp->tcp_tcph = tcph;
8397 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8398 	/*
8399 	 * IP wants our header length in the checksum field to
8400 	 * allow it to perform a single pseudo-header+checksum
8401 	 * calculation on behalf of TCP.
8402 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8403 	 */
8404 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8405 	sum = (sum >> 16) + (sum & 0xFFFF);
8406 	U16_TO_ABE16(sum, tcph->th_sum);
8407 	return (0);
8408 }
8409 
8410 /*
8411  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8412  */
8413 static int
8414 tcp_header_init_ipv6(tcp_t *tcp)
8415 {
8416 	tcph_t	*tcph;
8417 	uint32_t	sum;
8418 	conn_t	*connp;
8419 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8420 
8421 	/*
8422 	 * This is a simple initialization. If there's
8423 	 * already a template, it should never be too small,
8424 	 * so reuse it. Otherwise, allocate space for the new one.
8425 	 * Ensure that there is enough space to "downgrade" the tcp_t
8426 	 * to an IPv4 tcp_t. This requires having space for a full load
8427 	 * of IPv4 options, as well as a full load of TCP options
8428 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8429 	 * than a v6 header and a TCP header with a full load of TCP options
8430 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8431 	 * We want to avoid reallocation in the "downgraded" case when
8432 	 * processing outbound IPv4 options.
8433 	 */
8434 	if (tcp->tcp_iphc == NULL) {
8435 		ASSERT(tcp->tcp_iphc_len == 0);
8436 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8437 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8438 		if (tcp->tcp_iphc == NULL) {
8439 			tcp->tcp_iphc_len = 0;
8440 			return (ENOMEM);
8441 		}
8442 	}
8443 
8444 	/* options are gone; may need a new label */
8445 	connp = tcp->tcp_connp;
8446 	connp->conn_mlp_type = mlptSingle;
8447 	connp->conn_ulp_labeled = !is_system_labeled();
8448 
8449 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8450 	tcp->tcp_ipversion = IPV6_VERSION;
8451 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8452 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8453 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8454 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8455 	tcp->tcp_ipha = NULL;
8456 
8457 	/* Initialize the header template */
8458 
8459 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8460 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8461 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8462 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8463 
8464 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8465 	tcp->tcp_tcph = tcph;
8466 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8467 	/*
8468 	 * IP wants our header length in the checksum field to
8469 	 * allow it to perform a single psuedo-header+checksum
8470 	 * calculation on behalf of TCP.
8471 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8472 	 */
8473 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8474 	sum = (sum >> 16) + (sum & 0xFFFF);
8475 	U16_TO_ABE16(sum, tcph->th_sum);
8476 	return (0);
8477 }
8478 
8479 /* At minimum we need 8 bytes in the TCP header for the lookup */
8480 #define	ICMP_MIN_TCP_HDR	8
8481 
8482 /*
8483  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8484  * passed up by IP. The message is always received on the correct tcp_t.
8485  * Assumes that IP has pulled up everything up to and including the ICMP header.
8486  */
8487 void
8488 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8489 {
8490 	icmph_t *icmph;
8491 	ipha_t	*ipha;
8492 	int	iph_hdr_length;
8493 	tcph_t	*tcph;
8494 	boolean_t ipsec_mctl = B_FALSE;
8495 	boolean_t secure;
8496 	mblk_t *first_mp = mp;
8497 	uint32_t new_mss;
8498 	uint32_t ratio;
8499 	size_t mp_size = MBLKL(mp);
8500 	uint32_t seg_seq;
8501 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8502 
8503 	/* Assume IP provides aligned packets - otherwise toss */
8504 	if (!OK_32PTR(mp->b_rptr)) {
8505 		freemsg(mp);
8506 		return;
8507 	}
8508 
8509 	/*
8510 	 * Since ICMP errors are normal data marked with M_CTL when sent
8511 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8512 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8513 	 */
8514 	if ((mp_size == sizeof (ipsec_info_t)) &&
8515 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8516 		ASSERT(mp->b_cont != NULL);
8517 		mp = mp->b_cont;
8518 		/* IP should have done this */
8519 		ASSERT(OK_32PTR(mp->b_rptr));
8520 		mp_size = MBLKL(mp);
8521 		ipsec_mctl = B_TRUE;
8522 	}
8523 
8524 	/*
8525 	 * Verify that we have a complete outer IP header. If not, drop it.
8526 	 */
8527 	if (mp_size < sizeof (ipha_t)) {
8528 noticmpv4:
8529 		freemsg(first_mp);
8530 		return;
8531 	}
8532 
8533 	ipha = (ipha_t *)mp->b_rptr;
8534 	/*
8535 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8536 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8537 	 */
8538 	switch (IPH_HDR_VERSION(ipha)) {
8539 	case IPV6_VERSION:
8540 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8541 		return;
8542 	case IPV4_VERSION:
8543 		break;
8544 	default:
8545 		goto noticmpv4;
8546 	}
8547 
8548 	/* Skip past the outer IP and ICMP headers */
8549 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8550 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8551 	/*
8552 	 * If we don't have the correct outer IP header length or if the ULP
8553 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8554 	 * send it upstream.
8555 	 */
8556 	if (iph_hdr_length < sizeof (ipha_t) ||
8557 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8558 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8559 		goto noticmpv4;
8560 	}
8561 	ipha = (ipha_t *)&icmph[1];
8562 
8563 	/* Skip past the inner IP and find the ULP header */
8564 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8565 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8566 	/*
8567 	 * If we don't have the correct inner IP header length or if the ULP
8568 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8569 	 * bytes of TCP header, drop it.
8570 	 */
8571 	if (iph_hdr_length < sizeof (ipha_t) ||
8572 	    ipha->ipha_protocol != IPPROTO_TCP ||
8573 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8574 		goto noticmpv4;
8575 	}
8576 
8577 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8578 		if (ipsec_mctl) {
8579 			secure = ipsec_in_is_secure(first_mp);
8580 		} else {
8581 			secure = B_FALSE;
8582 		}
8583 		if (secure) {
8584 			/*
8585 			 * If we are willing to accept this in clear
8586 			 * we don't have to verify policy.
8587 			 */
8588 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8589 				if (!tcp_check_policy(tcp, first_mp,
8590 				    ipha, NULL, secure, ipsec_mctl)) {
8591 					/*
8592 					 * tcp_check_policy called
8593 					 * ip_drop_packet() on failure.
8594 					 */
8595 					return;
8596 				}
8597 			}
8598 		}
8599 	} else if (ipsec_mctl) {
8600 		/*
8601 		 * This is a hard_bound connection. IP has already
8602 		 * verified policy. We don't have to do it again.
8603 		 */
8604 		freeb(first_mp);
8605 		first_mp = mp;
8606 		ipsec_mctl = B_FALSE;
8607 	}
8608 
8609 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8610 	/*
8611 	 * TCP SHOULD check that the TCP sequence number contained in
8612 	 * payload of the ICMP error message is within the range
8613 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8614 	 */
8615 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8616 		/*
8617 		 * If the ICMP message is bogus, should we kill the
8618 		 * connection, or should we just drop the bogus ICMP
8619 		 * message? It would probably make more sense to just
8620 		 * drop the message so that if this one managed to get
8621 		 * in, the real connection should not suffer.
8622 		 */
8623 		goto noticmpv4;
8624 	}
8625 
8626 	switch (icmph->icmph_type) {
8627 	case ICMP_DEST_UNREACHABLE:
8628 		switch (icmph->icmph_code) {
8629 		case ICMP_FRAGMENTATION_NEEDED:
8630 			/*
8631 			 * Reduce the MSS based on the new MTU.  This will
8632 			 * eliminate any fragmentation locally.
8633 			 * N.B.  There may well be some funny side-effects on
8634 			 * the local send policy and the remote receive policy.
8635 			 * Pending further research, we provide
8636 			 * tcp_ignore_path_mtu just in case this proves
8637 			 * disastrous somewhere.
8638 			 *
8639 			 * After updating the MSS, retransmit part of the
8640 			 * dropped segment using the new mss by calling
8641 			 * tcp_wput_data().  Need to adjust all those
8642 			 * params to make sure tcp_wput_data() work properly.
8643 			 */
8644 			if (tcps->tcps_ignore_path_mtu)
8645 				break;
8646 
8647 			/*
8648 			 * Decrease the MSS by time stamp options
8649 			 * IP options and IPSEC options. tcp_hdr_len
8650 			 * includes time stamp option and IP option
8651 			 * length.
8652 			 */
8653 
8654 			new_mss = ntohs(icmph->icmph_du_mtu) -
8655 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8656 
8657 			/*
8658 			 * Only update the MSS if the new one is
8659 			 * smaller than the previous one.  This is
8660 			 * to avoid problems when getting multiple
8661 			 * ICMP errors for the same MTU.
8662 			 */
8663 			if (new_mss >= tcp->tcp_mss)
8664 				break;
8665 
8666 			/*
8667 			 * Stop doing PMTU if new_mss is less than 68
8668 			 * or less than tcp_mss_min.
8669 			 * The value 68 comes from rfc 1191.
8670 			 */
8671 			if (new_mss < MAX(68, tcps->tcps_mss_min))
8672 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8673 				    0;
8674 
8675 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8676 			ASSERT(ratio >= 1);
8677 			tcp_mss_set(tcp, new_mss, B_TRUE);
8678 
8679 			/*
8680 			 * Make sure we have something to
8681 			 * send.
8682 			 */
8683 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8684 			    (tcp->tcp_xmit_head != NULL)) {
8685 				/*
8686 				 * Shrink tcp_cwnd in
8687 				 * proportion to the old MSS/new MSS.
8688 				 */
8689 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8690 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8691 				    (tcp->tcp_unsent == 0)) {
8692 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8693 				} else {
8694 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8695 				}
8696 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8697 				tcp->tcp_rexmit = B_TRUE;
8698 				tcp->tcp_dupack_cnt = 0;
8699 				tcp->tcp_snd_burst = TCP_CWND_SS;
8700 				tcp_ss_rexmit(tcp);
8701 			}
8702 			break;
8703 		case ICMP_PORT_UNREACHABLE:
8704 		case ICMP_PROTOCOL_UNREACHABLE:
8705 			switch (tcp->tcp_state) {
8706 			case TCPS_SYN_SENT:
8707 			case TCPS_SYN_RCVD:
8708 				/*
8709 				 * ICMP can snipe away incipient
8710 				 * TCP connections as long as
8711 				 * seq number is same as initial
8712 				 * send seq number.
8713 				 */
8714 				if (seg_seq == tcp->tcp_iss) {
8715 					(void) tcp_clean_death(tcp,
8716 					    ECONNREFUSED, 6);
8717 				}
8718 				break;
8719 			}
8720 			break;
8721 		case ICMP_HOST_UNREACHABLE:
8722 		case ICMP_NET_UNREACHABLE:
8723 			/* Record the error in case we finally time out. */
8724 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8725 				tcp->tcp_client_errno = EHOSTUNREACH;
8726 			else
8727 				tcp->tcp_client_errno = ENETUNREACH;
8728 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8729 				if (tcp->tcp_listener != NULL &&
8730 				    tcp->tcp_listener->tcp_syn_defense) {
8731 					/*
8732 					 * Ditch the half-open connection if we
8733 					 * suspect a SYN attack is under way.
8734 					 */
8735 					tcp_ip_ire_mark_advice(tcp);
8736 					(void) tcp_clean_death(tcp,
8737 					    tcp->tcp_client_errno, 7);
8738 				}
8739 			}
8740 			break;
8741 		default:
8742 			break;
8743 		}
8744 		break;
8745 	case ICMP_SOURCE_QUENCH: {
8746 		/*
8747 		 * use a global boolean to control
8748 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8749 		 * The default is false.
8750 		 */
8751 		if (tcp_icmp_source_quench) {
8752 			/*
8753 			 * Reduce the sending rate as if we got a
8754 			 * retransmit timeout
8755 			 */
8756 			uint32_t npkt;
8757 
8758 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8759 			    tcp->tcp_mss;
8760 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8761 			tcp->tcp_cwnd = tcp->tcp_mss;
8762 			tcp->tcp_cwnd_cnt = 0;
8763 		}
8764 		break;
8765 	}
8766 	}
8767 	freemsg(first_mp);
8768 }
8769 
8770 /*
8771  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8772  * error messages passed up by IP.
8773  * Assumes that IP has pulled up all the extension headers as well
8774  * as the ICMPv6 header.
8775  */
8776 static void
8777 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8778 {
8779 	icmp6_t *icmp6;
8780 	ip6_t	*ip6h;
8781 	uint16_t	iph_hdr_length;
8782 	tcpha_t	*tcpha;
8783 	uint8_t	*nexthdrp;
8784 	uint32_t new_mss;
8785 	uint32_t ratio;
8786 	boolean_t secure;
8787 	mblk_t *first_mp = mp;
8788 	size_t mp_size;
8789 	uint32_t seg_seq;
8790 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8791 
8792 	/*
8793 	 * The caller has determined if this is an IPSEC_IN packet and
8794 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8795 	 */
8796 	if (ipsec_mctl)
8797 		mp = mp->b_cont;
8798 
8799 	mp_size = MBLKL(mp);
8800 
8801 	/*
8802 	 * Verify that we have a complete IP header. If not, send it upstream.
8803 	 */
8804 	if (mp_size < sizeof (ip6_t)) {
8805 noticmpv6:
8806 		freemsg(first_mp);
8807 		return;
8808 	}
8809 
8810 	/*
8811 	 * Verify this is an ICMPV6 packet, else send it upstream.
8812 	 */
8813 	ip6h = (ip6_t *)mp->b_rptr;
8814 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8815 		iph_hdr_length = IPV6_HDR_LEN;
8816 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8817 	    &nexthdrp) ||
8818 	    *nexthdrp != IPPROTO_ICMPV6) {
8819 		goto noticmpv6;
8820 	}
8821 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8822 	ip6h = (ip6_t *)&icmp6[1];
8823 	/*
8824 	 * Verify if we have a complete ICMP and inner IP header.
8825 	 */
8826 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8827 		goto noticmpv6;
8828 
8829 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8830 		goto noticmpv6;
8831 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8832 	/*
8833 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8834 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8835 	 * packet.
8836 	 */
8837 	if ((*nexthdrp != IPPROTO_TCP) ||
8838 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8839 		goto noticmpv6;
8840 	}
8841 
8842 	/*
8843 	 * ICMP errors come on the right queue or come on
8844 	 * listener/global queue for detached connections and
8845 	 * get switched to the right queue. If it comes on the
8846 	 * right queue, policy check has already been done by IP
8847 	 * and thus free the first_mp without verifying the policy.
8848 	 * If it has come for a non-hard bound connection, we need
8849 	 * to verify policy as IP may not have done it.
8850 	 */
8851 	if (!tcp->tcp_hard_bound) {
8852 		if (ipsec_mctl) {
8853 			secure = ipsec_in_is_secure(first_mp);
8854 		} else {
8855 			secure = B_FALSE;
8856 		}
8857 		if (secure) {
8858 			/*
8859 			 * If we are willing to accept this in clear
8860 			 * we don't have to verify policy.
8861 			 */
8862 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8863 				if (!tcp_check_policy(tcp, first_mp,
8864 				    NULL, ip6h, secure, ipsec_mctl)) {
8865 					/*
8866 					 * tcp_check_policy called
8867 					 * ip_drop_packet() on failure.
8868 					 */
8869 					return;
8870 				}
8871 			}
8872 		}
8873 	} else if (ipsec_mctl) {
8874 		/*
8875 		 * This is a hard_bound connection. IP has already
8876 		 * verified policy. We don't have to do it again.
8877 		 */
8878 		freeb(first_mp);
8879 		first_mp = mp;
8880 		ipsec_mctl = B_FALSE;
8881 	}
8882 
8883 	seg_seq = ntohl(tcpha->tha_seq);
8884 	/*
8885 	 * TCP SHOULD check that the TCP sequence number contained in
8886 	 * payload of the ICMP error message is within the range
8887 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8888 	 */
8889 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8890 		/*
8891 		 * If the ICMP message is bogus, should we kill the
8892 		 * connection, or should we just drop the bogus ICMP
8893 		 * message? It would probably make more sense to just
8894 		 * drop the message so that if this one managed to get
8895 		 * in, the real connection should not suffer.
8896 		 */
8897 		goto noticmpv6;
8898 	}
8899 
8900 	switch (icmp6->icmp6_type) {
8901 	case ICMP6_PACKET_TOO_BIG:
8902 		/*
8903 		 * Reduce the MSS based on the new MTU.  This will
8904 		 * eliminate any fragmentation locally.
8905 		 * N.B.  There may well be some funny side-effects on
8906 		 * the local send policy and the remote receive policy.
8907 		 * Pending further research, we provide
8908 		 * tcp_ignore_path_mtu just in case this proves
8909 		 * disastrous somewhere.
8910 		 *
8911 		 * After updating the MSS, retransmit part of the
8912 		 * dropped segment using the new mss by calling
8913 		 * tcp_wput_data().  Need to adjust all those
8914 		 * params to make sure tcp_wput_data() work properly.
8915 		 */
8916 		if (tcps->tcps_ignore_path_mtu)
8917 			break;
8918 
8919 		/*
8920 		 * Decrease the MSS by time stamp options
8921 		 * IP options and IPSEC options. tcp_hdr_len
8922 		 * includes time stamp option and IP option
8923 		 * length.
8924 		 */
8925 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8926 		    tcp->tcp_ipsec_overhead;
8927 
8928 		/*
8929 		 * Only update the MSS if the new one is
8930 		 * smaller than the previous one.  This is
8931 		 * to avoid problems when getting multiple
8932 		 * ICMP errors for the same MTU.
8933 		 */
8934 		if (new_mss >= tcp->tcp_mss)
8935 			break;
8936 
8937 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8938 		ASSERT(ratio >= 1);
8939 		tcp_mss_set(tcp, new_mss, B_TRUE);
8940 
8941 		/*
8942 		 * Make sure we have something to
8943 		 * send.
8944 		 */
8945 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8946 		    (tcp->tcp_xmit_head != NULL)) {
8947 			/*
8948 			 * Shrink tcp_cwnd in
8949 			 * proportion to the old MSS/new MSS.
8950 			 */
8951 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8952 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8953 			    (tcp->tcp_unsent == 0)) {
8954 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8955 			} else {
8956 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8957 			}
8958 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8959 			tcp->tcp_rexmit = B_TRUE;
8960 			tcp->tcp_dupack_cnt = 0;
8961 			tcp->tcp_snd_burst = TCP_CWND_SS;
8962 			tcp_ss_rexmit(tcp);
8963 		}
8964 		break;
8965 
8966 	case ICMP6_DST_UNREACH:
8967 		switch (icmp6->icmp6_code) {
8968 		case ICMP6_DST_UNREACH_NOPORT:
8969 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8970 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8971 			    (seg_seq == tcp->tcp_iss)) {
8972 				(void) tcp_clean_death(tcp,
8973 				    ECONNREFUSED, 8);
8974 			}
8975 			break;
8976 
8977 		case ICMP6_DST_UNREACH_ADMIN:
8978 		case ICMP6_DST_UNREACH_NOROUTE:
8979 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8980 		case ICMP6_DST_UNREACH_ADDR:
8981 			/* Record the error in case we finally time out. */
8982 			tcp->tcp_client_errno = EHOSTUNREACH;
8983 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8984 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8985 			    (seg_seq == tcp->tcp_iss)) {
8986 				if (tcp->tcp_listener != NULL &&
8987 				    tcp->tcp_listener->tcp_syn_defense) {
8988 					/*
8989 					 * Ditch the half-open connection if we
8990 					 * suspect a SYN attack is under way.
8991 					 */
8992 					tcp_ip_ire_mark_advice(tcp);
8993 					(void) tcp_clean_death(tcp,
8994 					    tcp->tcp_client_errno, 9);
8995 				}
8996 			}
8997 
8998 
8999 			break;
9000 		default:
9001 			break;
9002 		}
9003 		break;
9004 
9005 	case ICMP6_PARAM_PROB:
9006 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
9007 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
9008 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
9009 		    (uchar_t *)nexthdrp) {
9010 			if (tcp->tcp_state == TCPS_SYN_SENT ||
9011 			    tcp->tcp_state == TCPS_SYN_RCVD) {
9012 				(void) tcp_clean_death(tcp,
9013 				    ECONNREFUSED, 10);
9014 			}
9015 			break;
9016 		}
9017 		break;
9018 
9019 	case ICMP6_TIME_EXCEEDED:
9020 	default:
9021 		break;
9022 	}
9023 	freemsg(first_mp);
9024 }
9025 
9026 /*
9027  * IP recognizes seven kinds of bind requests:
9028  *
9029  * - A zero-length address binds only to the protocol number.
9030  *
9031  * - A 4-byte address is treated as a request to
9032  * validate that the address is a valid local IPv4
9033  * address, appropriate for an application to bind to.
9034  * IP does the verification, but does not make any note
9035  * of the address at this time.
9036  *
9037  * - A 16-byte address contains is treated as a request
9038  * to validate a local IPv6 address, as the 4-byte
9039  * address case above.
9040  *
9041  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
9042  * use it for the inbound fanout of packets.
9043  *
9044  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
9045  * use it for the inbound fanout of packets.
9046  *
9047  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
9048  * information consisting of local and remote addresses
9049  * and ports.  In this case, the addresses are both
9050  * validated as appropriate for this operation, and, if
9051  * so, the information is retained for use in the
9052  * inbound fanout.
9053  *
9054  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
9055  * fanout information, like the 12-byte case above.
9056  *
9057  * IP will also fill in the IRE request mblk with information
9058  * regarding our peer.  In all cases, we notify IP of our protocol
9059  * type by appending a single protocol byte to the bind request.
9060  */
9061 static mblk_t *
9062 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
9063 {
9064 	char	*cp;
9065 	mblk_t	*mp;
9066 	struct T_bind_req *tbr;
9067 	ipa_conn_t	*ac;
9068 	ipa6_conn_t	*ac6;
9069 	sin_t		*sin;
9070 	sin6_t		*sin6;
9071 
9072 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9073 	ASSERT((tcp->tcp_family == AF_INET &&
9074 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9075 	    (tcp->tcp_family == AF_INET6 &&
9076 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9077 	    tcp->tcp_ipversion == IPV6_VERSION)));
9078 
9079 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9080 	if (!mp)
9081 		return (mp);
9082 	mp->b_datap->db_type = M_PROTO;
9083 	tbr = (struct T_bind_req *)mp->b_rptr;
9084 	tbr->PRIM_type = bind_prim;
9085 	tbr->ADDR_offset = sizeof (*tbr);
9086 	tbr->CONIND_number = 0;
9087 	tbr->ADDR_length = addr_length;
9088 	cp = (char *)&tbr[1];
9089 	switch (addr_length) {
9090 	case sizeof (ipa_conn_t):
9091 		ASSERT(tcp->tcp_family == AF_INET);
9092 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9093 
9094 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9095 		if (mp->b_cont == NULL) {
9096 			freemsg(mp);
9097 			return (NULL);
9098 		}
9099 		mp->b_cont->b_wptr += sizeof (ire_t);
9100 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9101 
9102 		/* cp known to be 32 bit aligned */
9103 		ac = (ipa_conn_t *)cp;
9104 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9105 		ac->ac_faddr = tcp->tcp_remote;
9106 		ac->ac_fport = tcp->tcp_fport;
9107 		ac->ac_lport = tcp->tcp_lport;
9108 		tcp->tcp_hard_binding = 1;
9109 		break;
9110 
9111 	case sizeof (ipa6_conn_t):
9112 		ASSERT(tcp->tcp_family == AF_INET6);
9113 
9114 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9115 		if (mp->b_cont == NULL) {
9116 			freemsg(mp);
9117 			return (NULL);
9118 		}
9119 		mp->b_cont->b_wptr += sizeof (ire_t);
9120 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9121 
9122 		/* cp known to be 32 bit aligned */
9123 		ac6 = (ipa6_conn_t *)cp;
9124 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9125 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9126 			    &ac6->ac6_laddr);
9127 		} else {
9128 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9129 		}
9130 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9131 		ac6->ac6_fport = tcp->tcp_fport;
9132 		ac6->ac6_lport = tcp->tcp_lport;
9133 		tcp->tcp_hard_binding = 1;
9134 		break;
9135 
9136 	case sizeof (sin_t):
9137 		/*
9138 		 * NOTE: IPV6_ADDR_LEN also has same size.
9139 		 * Use family to discriminate.
9140 		 */
9141 		if (tcp->tcp_family == AF_INET) {
9142 			sin = (sin_t *)cp;
9143 
9144 			*sin = sin_null;
9145 			sin->sin_family = AF_INET;
9146 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9147 			sin->sin_port = tcp->tcp_lport;
9148 			break;
9149 		} else {
9150 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9151 		}
9152 		break;
9153 
9154 	case sizeof (sin6_t):
9155 		ASSERT(tcp->tcp_family == AF_INET6);
9156 		sin6 = (sin6_t *)cp;
9157 
9158 		*sin6 = sin6_null;
9159 		sin6->sin6_family = AF_INET6;
9160 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9161 		sin6->sin6_port = tcp->tcp_lport;
9162 		break;
9163 
9164 	case IP_ADDR_LEN:
9165 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9166 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9167 		break;
9168 
9169 	}
9170 	/* Add protocol number to end */
9171 	cp[addr_length] = (char)IPPROTO_TCP;
9172 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9173 	return (mp);
9174 }
9175 
9176 /*
9177  * Notify IP that we are having trouble with this connection.  IP should
9178  * blow the IRE away and start over.
9179  */
9180 static void
9181 tcp_ip_notify(tcp_t *tcp)
9182 {
9183 	struct iocblk	*iocp;
9184 	ipid_t	*ipid;
9185 	mblk_t	*mp;
9186 
9187 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9188 	if (tcp->tcp_ipversion == IPV6_VERSION)
9189 		return;
9190 
9191 	mp = mkiocb(IP_IOCTL);
9192 	if (mp == NULL)
9193 		return;
9194 
9195 	iocp = (struct iocblk *)mp->b_rptr;
9196 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9197 
9198 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9199 	if (!mp->b_cont) {
9200 		freeb(mp);
9201 		return;
9202 	}
9203 
9204 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9205 	mp->b_cont->b_wptr += iocp->ioc_count;
9206 	bzero(ipid, sizeof (*ipid));
9207 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9208 	ipid->ipid_ire_type = IRE_CACHE;
9209 	ipid->ipid_addr_offset = sizeof (ipid_t);
9210 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9211 	/*
9212 	 * Note: in the case of source routing we want to blow away the
9213 	 * route to the first source route hop.
9214 	 */
9215 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9216 	    sizeof (tcp->tcp_ipha->ipha_dst));
9217 
9218 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9219 }
9220 
9221 /* Unlink and return any mblk that looks like it contains an ire */
9222 static mblk_t *
9223 tcp_ire_mp(mblk_t *mp)
9224 {
9225 	mblk_t	*prev_mp;
9226 
9227 	for (;;) {
9228 		prev_mp = mp;
9229 		mp = mp->b_cont;
9230 		if (mp == NULL)
9231 			break;
9232 		switch (DB_TYPE(mp)) {
9233 		case IRE_DB_TYPE:
9234 		case IRE_DB_REQ_TYPE:
9235 			if (prev_mp != NULL)
9236 				prev_mp->b_cont = mp->b_cont;
9237 			mp->b_cont = NULL;
9238 			return (mp);
9239 		default:
9240 			break;
9241 		}
9242 	}
9243 	return (mp);
9244 }
9245 
9246 /*
9247  * Timer callback routine for keepalive probe.  We do a fake resend of
9248  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9249  * check to see if we have heard anything from the other end for the last
9250  * RTO period.  If we have, set the timer to expire for another
9251  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9252  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9253  * the timeout if we have not heard from the other side.  If for more than
9254  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9255  * kill the connection unless the keepalive abort threshold is 0.  In
9256  * that case, we will probe "forever."
9257  */
9258 static void
9259 tcp_keepalive_killer(void *arg)
9260 {
9261 	mblk_t	*mp;
9262 	conn_t	*connp = (conn_t *)arg;
9263 	tcp_t  	*tcp = connp->conn_tcp;
9264 	int32_t	firetime;
9265 	int32_t	idletime;
9266 	int32_t	ka_intrvl;
9267 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9268 
9269 	tcp->tcp_ka_tid = 0;
9270 
9271 	if (tcp->tcp_fused)
9272 		return;
9273 
9274 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
9275 	ka_intrvl = tcp->tcp_ka_interval;
9276 
9277 	/*
9278 	 * Keepalive probe should only be sent if the application has not
9279 	 * done a close on the connection.
9280 	 */
9281 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9282 		return;
9283 	}
9284 	/* Timer fired too early, restart it. */
9285 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9286 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9287 		    MSEC_TO_TICK(ka_intrvl));
9288 		return;
9289 	}
9290 
9291 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9292 	/*
9293 	 * If we have not heard from the other side for a long
9294 	 * time, kill the connection unless the keepalive abort
9295 	 * threshold is 0.  In that case, we will probe "forever."
9296 	 */
9297 	if (tcp->tcp_ka_abort_thres != 0 &&
9298 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9299 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
9300 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9301 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9302 		return;
9303 	}
9304 
9305 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9306 	    idletime >= ka_intrvl) {
9307 		/* Fake resend of last ACKed byte. */
9308 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9309 
9310 		if (mp1 != NULL) {
9311 			*mp1->b_wptr++ = '\0';
9312 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9313 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9314 			freeb(mp1);
9315 			/*
9316 			 * if allocation failed, fall through to start the
9317 			 * timer back.
9318 			 */
9319 			if (mp != NULL) {
9320 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9321 				BUMP_MIB(&tcps->tcps_mib,
9322 				    tcpTimKeepaliveProbe);
9323 				if (tcp->tcp_ka_last_intrvl != 0) {
9324 					int max;
9325 					/*
9326 					 * We should probe again at least
9327 					 * in ka_intrvl, but not more than
9328 					 * tcp_rexmit_interval_max.
9329 					 */
9330 					max = tcps->tcps_rexmit_interval_max;
9331 					firetime = MIN(ka_intrvl - 1,
9332 					    tcp->tcp_ka_last_intrvl << 1);
9333 					if (firetime > max)
9334 						firetime = max;
9335 				} else {
9336 					firetime = tcp->tcp_rto;
9337 				}
9338 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9339 				    tcp_keepalive_killer,
9340 				    MSEC_TO_TICK(firetime));
9341 				tcp->tcp_ka_last_intrvl = firetime;
9342 				return;
9343 			}
9344 		}
9345 	} else {
9346 		tcp->tcp_ka_last_intrvl = 0;
9347 	}
9348 
9349 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9350 	if ((firetime = ka_intrvl - idletime) < 0) {
9351 		firetime = ka_intrvl;
9352 	}
9353 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9354 	    MSEC_TO_TICK(firetime));
9355 }
9356 
9357 int
9358 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9359 {
9360 	queue_t	*q = tcp->tcp_rq;
9361 	int32_t	mss = tcp->tcp_mss;
9362 	int	maxpsz;
9363 
9364 	if (TCP_IS_DETACHED(tcp))
9365 		return (mss);
9366 
9367 	if (tcp->tcp_fused) {
9368 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9369 		mss = INFPSZ;
9370 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
9371 		/*
9372 		 * Set the sd_qn_maxpsz according to the socket send buffer
9373 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9374 		 * instruct the stream head to copyin user data into contiguous
9375 		 * kernel-allocated buffers without breaking it up into smaller
9376 		 * chunks.  We round up the buffer size to the nearest SMSS.
9377 		 */
9378 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9379 		if (tcp->tcp_kssl_ctx == NULL)
9380 			mss = INFPSZ;
9381 		else
9382 			mss = SSL3_MAX_RECORD_LEN;
9383 	} else {
9384 		/*
9385 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9386 		 * (and a multiple of the mss).  This instructs the stream
9387 		 * head to break down larger than SMSS writes into SMSS-
9388 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9389 		 */
9390 		maxpsz = tcp->tcp_maxpsz * mss;
9391 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9392 			maxpsz = tcp->tcp_xmit_hiwater/2;
9393 			/* Round up to nearest mss */
9394 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9395 		}
9396 	}
9397 	(void) setmaxps(q, maxpsz);
9398 	tcp->tcp_wq->q_maxpsz = maxpsz;
9399 
9400 	if (set_maxblk)
9401 		(void) mi_set_sth_maxblk(q, mss);
9402 
9403 	return (mss);
9404 }
9405 
9406 /*
9407  * Extract option values from a tcp header.  We put any found values into the
9408  * tcpopt struct and return a bitmask saying which options were found.
9409  */
9410 static int
9411 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9412 {
9413 	uchar_t		*endp;
9414 	int		len;
9415 	uint32_t	mss;
9416 	uchar_t		*up = (uchar_t *)tcph;
9417 	int		found = 0;
9418 	int32_t		sack_len;
9419 	tcp_seq		sack_begin, sack_end;
9420 	tcp_t		*tcp;
9421 
9422 	endp = up + TCP_HDR_LENGTH(tcph);
9423 	up += TCP_MIN_HEADER_LENGTH;
9424 	while (up < endp) {
9425 		len = endp - up;
9426 		switch (*up) {
9427 		case TCPOPT_EOL:
9428 			break;
9429 
9430 		case TCPOPT_NOP:
9431 			up++;
9432 			continue;
9433 
9434 		case TCPOPT_MAXSEG:
9435 			if (len < TCPOPT_MAXSEG_LEN ||
9436 			    up[1] != TCPOPT_MAXSEG_LEN)
9437 				break;
9438 
9439 			mss = BE16_TO_U16(up+2);
9440 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9441 			tcpopt->tcp_opt_mss = mss;
9442 			found |= TCP_OPT_MSS_PRESENT;
9443 
9444 			up += TCPOPT_MAXSEG_LEN;
9445 			continue;
9446 
9447 		case TCPOPT_WSCALE:
9448 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9449 				break;
9450 
9451 			if (up[2] > TCP_MAX_WINSHIFT)
9452 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9453 			else
9454 				tcpopt->tcp_opt_wscale = up[2];
9455 			found |= TCP_OPT_WSCALE_PRESENT;
9456 
9457 			up += TCPOPT_WS_LEN;
9458 			continue;
9459 
9460 		case TCPOPT_SACK_PERMITTED:
9461 			if (len < TCPOPT_SACK_OK_LEN ||
9462 			    up[1] != TCPOPT_SACK_OK_LEN)
9463 				break;
9464 			found |= TCP_OPT_SACK_OK_PRESENT;
9465 			up += TCPOPT_SACK_OK_LEN;
9466 			continue;
9467 
9468 		case TCPOPT_SACK:
9469 			if (len <= 2 || up[1] <= 2 || len < up[1])
9470 				break;
9471 
9472 			/* If TCP is not interested in SACK blks... */
9473 			if ((tcp = tcpopt->tcp) == NULL) {
9474 				up += up[1];
9475 				continue;
9476 			}
9477 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9478 			up += TCPOPT_HEADER_LEN;
9479 
9480 			/*
9481 			 * If the list is empty, allocate one and assume
9482 			 * nothing is sack'ed.
9483 			 */
9484 			ASSERT(tcp->tcp_sack_info != NULL);
9485 			if (tcp->tcp_notsack_list == NULL) {
9486 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9487 				    tcp->tcp_suna, tcp->tcp_snxt,
9488 				    &(tcp->tcp_num_notsack_blk),
9489 				    &(tcp->tcp_cnt_notsack_list));
9490 
9491 				/*
9492 				 * Make sure tcp_notsack_list is not NULL.
9493 				 * This happens when kmem_alloc(KM_NOSLEEP)
9494 				 * returns NULL.
9495 				 */
9496 				if (tcp->tcp_notsack_list == NULL) {
9497 					up += sack_len;
9498 					continue;
9499 				}
9500 				tcp->tcp_fack = tcp->tcp_suna;
9501 			}
9502 
9503 			while (sack_len > 0) {
9504 				if (up + 8 > endp) {
9505 					up = endp;
9506 					break;
9507 				}
9508 				sack_begin = BE32_TO_U32(up);
9509 				up += 4;
9510 				sack_end = BE32_TO_U32(up);
9511 				up += 4;
9512 				sack_len -= 8;
9513 				/*
9514 				 * Bounds checking.  Make sure the SACK
9515 				 * info is within tcp_suna and tcp_snxt.
9516 				 * If this SACK blk is out of bound, ignore
9517 				 * it but continue to parse the following
9518 				 * blks.
9519 				 */
9520 				if (SEQ_LEQ(sack_end, sack_begin) ||
9521 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9522 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9523 					continue;
9524 				}
9525 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9526 				    sack_begin, sack_end,
9527 				    &(tcp->tcp_num_notsack_blk),
9528 				    &(tcp->tcp_cnt_notsack_list));
9529 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9530 					tcp->tcp_fack = sack_end;
9531 				}
9532 			}
9533 			found |= TCP_OPT_SACK_PRESENT;
9534 			continue;
9535 
9536 		case TCPOPT_TSTAMP:
9537 			if (len < TCPOPT_TSTAMP_LEN ||
9538 			    up[1] != TCPOPT_TSTAMP_LEN)
9539 				break;
9540 
9541 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9542 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9543 
9544 			found |= TCP_OPT_TSTAMP_PRESENT;
9545 
9546 			up += TCPOPT_TSTAMP_LEN;
9547 			continue;
9548 
9549 		default:
9550 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9551 				break;
9552 			up += up[1];
9553 			continue;
9554 		}
9555 		break;
9556 	}
9557 	return (found);
9558 }
9559 
9560 /*
9561  * Set the mss associated with a particular tcp based on its current value,
9562  * and a new one passed in. Observe minimums and maximums, and reset
9563  * other state variables that we want to view as multiples of mss.
9564  *
9565  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9566  * highwater marks etc. need to be initialized or adjusted.
9567  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9568  *    packet arrives.
9569  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9570  *    ICMP6_PACKET_TOO_BIG arrives.
9571  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9572  *    to increase the MSS to use the extra bytes available.
9573  *
9574  * Callers except tcp_paws_check() ensure that they only reduce mss.
9575  */
9576 static void
9577 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9578 {
9579 	uint32_t	mss_max;
9580 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9581 
9582 	if (tcp->tcp_ipversion == IPV4_VERSION)
9583 		mss_max = tcps->tcps_mss_max_ipv4;
9584 	else
9585 		mss_max = tcps->tcps_mss_max_ipv6;
9586 
9587 	if (mss < tcps->tcps_mss_min)
9588 		mss = tcps->tcps_mss_min;
9589 	if (mss > mss_max)
9590 		mss = mss_max;
9591 	/*
9592 	 * Unless naglim has been set by our client to
9593 	 * a non-mss value, force naglim to track mss.
9594 	 * This can help to aggregate small writes.
9595 	 */
9596 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9597 		tcp->tcp_naglim = mss;
9598 	/*
9599 	 * TCP should be able to buffer at least 4 MSS data for obvious
9600 	 * performance reason.
9601 	 */
9602 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9603 		tcp->tcp_xmit_hiwater = mss << 2;
9604 
9605 	if (do_ss) {
9606 		/*
9607 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9608 		 * changing due to a reduction in MTU, presumably as a
9609 		 * result of a new path component, reset cwnd to its
9610 		 * "initial" value, as a multiple of the new mss.
9611 		 */
9612 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9613 	} else {
9614 		/*
9615 		 * Called by tcp_paws_check(), the mss increased
9616 		 * marginally to allow use of space previously taken
9617 		 * by the timestamp option. It would be inappropriate
9618 		 * to apply slow start or tcp_init_cwnd values to
9619 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9620 		 */
9621 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9622 		tcp->tcp_cwnd_cnt = 0;
9623 	}
9624 	tcp->tcp_mss = mss;
9625 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9626 }
9627 
9628 /* For /dev/tcp aka AF_INET open */
9629 static int
9630 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9631 {
9632 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9633 }
9634 
9635 /* For /dev/tcp6 aka AF_INET6 open */
9636 static int
9637 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9638 {
9639 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9640 }
9641 
9642 static int
9643 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9644     boolean_t isv6)
9645 {
9646 	tcp_t		*tcp = NULL;
9647 	conn_t		*connp;
9648 	int		err;
9649 	vmem_t		*minor_arena = NULL;
9650 	dev_t		conn_dev;
9651 	zoneid_t	zoneid;
9652 	tcp_stack_t	*tcps = NULL;
9653 
9654 	if (q->q_ptr != NULL)
9655 		return (0);
9656 
9657 	if (sflag == MODOPEN)
9658 		return (EINVAL);
9659 
9660 	if (!(flag & SO_ACCEPTOR)) {
9661 		/*
9662 		 * Special case for install: miniroot needs to be able to
9663 		 * access files via NFS as though it were always in the
9664 		 * global zone.
9665 		 */
9666 		if (credp == kcred && nfs_global_client_only != 0) {
9667 			zoneid = GLOBAL_ZONEID;
9668 			tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9669 			    netstack_tcp;
9670 			ASSERT(tcps != NULL);
9671 		} else {
9672 			netstack_t *ns;
9673 
9674 			ns = netstack_find_by_cred(credp);
9675 			ASSERT(ns != NULL);
9676 			tcps = ns->netstack_tcp;
9677 			ASSERT(tcps != NULL);
9678 
9679 			/*
9680 			 * For exclusive stacks we set the zoneid to zero
9681 			 * to make TCP operate as if in the global zone.
9682 			 */
9683 			if (tcps->tcps_netstack->netstack_stackid !=
9684 			    GLOBAL_NETSTACKID)
9685 				zoneid = GLOBAL_ZONEID;
9686 			else
9687 				zoneid = crgetzoneid(credp);
9688 		}
9689 		/*
9690 		 * For stackid zero this is done from strplumb.c, but
9691 		 * non-zero stackids are handled here.
9692 		 */
9693 		if (tcps->tcps_g_q == NULL &&
9694 		    tcps->tcps_netstack->netstack_stackid !=
9695 		    GLOBAL_NETSTACKID) {
9696 			tcp_g_q_setup(tcps);
9697 		}
9698 	}
9699 
9700 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9701 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9702 		minor_arena = ip_minor_arena_la;
9703 	} else {
9704 		/*
9705 		 * Either minor numbers in the large arena were exhausted
9706 		 * or a non socket application is doing the open.
9707 		 * Try to allocate from the small arena.
9708 		 */
9709 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9710 			if (tcps != NULL)
9711 				netstack_rele(tcps->tcps_netstack);
9712 			return (EBUSY);
9713 		}
9714 		minor_arena = ip_minor_arena_sa;
9715 	}
9716 	ASSERT(minor_arena != NULL);
9717 
9718 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9719 
9720 	if (flag & SO_ACCEPTOR) {
9721 		/* No netstack_find_by_cred, hence no netstack_rele needed */
9722 		ASSERT(tcps == NULL);
9723 		q->q_qinfo = &tcp_acceptor_rinit;
9724 		/*
9725 		 * the conn_dev and minor_arena will be subsequently used by
9726 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9727 		 * minor device number for this connection from the q_ptr.
9728 		 */
9729 		RD(q)->q_ptr = (void *)conn_dev;
9730 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9731 		WR(q)->q_ptr = (void *)minor_arena;
9732 		qprocson(q);
9733 		return (0);
9734 	}
9735 
9736 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9737 	/*
9738 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9739 	 * so we drop it by one.
9740 	 */
9741 	netstack_rele(tcps->tcps_netstack);
9742 	if (connp == NULL) {
9743 		inet_minor_free(minor_arena, conn_dev);
9744 		q->q_ptr = NULL;
9745 		return (ENOSR);
9746 	}
9747 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9748 	tcp = connp->conn_tcp;
9749 
9750 	q->q_ptr = WR(q)->q_ptr = connp;
9751 	if (isv6) {
9752 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9753 		connp->conn_send = ip_output_v6;
9754 		connp->conn_af_isv6 = B_TRUE;
9755 		connp->conn_pkt_isv6 = B_TRUE;
9756 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9757 		tcp->tcp_ipversion = IPV6_VERSION;
9758 		tcp->tcp_family = AF_INET6;
9759 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9760 	} else {
9761 		connp->conn_flags |= IPCL_TCP4;
9762 		connp->conn_send = ip_output;
9763 		connp->conn_af_isv6 = B_FALSE;
9764 		connp->conn_pkt_isv6 = B_FALSE;
9765 		tcp->tcp_ipversion = IPV4_VERSION;
9766 		tcp->tcp_family = AF_INET;
9767 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9768 	}
9769 
9770 	/*
9771 	 * TCP keeps a copy of cred for cache locality reasons but
9772 	 * we put a reference only once. If connp->conn_cred
9773 	 * becomes invalid, tcp_cred should also be set to NULL.
9774 	 */
9775 	tcp->tcp_cred = connp->conn_cred = credp;
9776 	crhold(connp->conn_cred);
9777 	tcp->tcp_cpid = curproc->p_pid;
9778 	tcp->tcp_open_time = lbolt64;
9779 	connp->conn_zoneid = zoneid;
9780 	connp->conn_mlp_type = mlptSingle;
9781 	connp->conn_ulp_labeled = !is_system_labeled();
9782 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9783 	ASSERT(tcp->tcp_tcps == tcps);
9784 
9785 	/*
9786 	 * If the caller has the process-wide flag set, then default to MAC
9787 	 * exempt mode.  This allows read-down to unlabeled hosts.
9788 	 */
9789 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9790 		connp->conn_mac_exempt = B_TRUE;
9791 
9792 	connp->conn_dev = conn_dev;
9793 	connp->conn_minor_arena = minor_arena;
9794 
9795 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9796 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9797 
9798 	if (flag & SO_SOCKSTR) {
9799 		/*
9800 		 * No need to insert a socket in tcp acceptor hash.
9801 		 * If it was a socket acceptor stream, we dealt with
9802 		 * it above. A socket listener can never accept a
9803 		 * connection and doesn't need acceptor_id.
9804 		 */
9805 		connp->conn_flags |= IPCL_SOCKET;
9806 		tcp->tcp_issocket = 1;
9807 		WR(q)->q_qinfo = &tcp_sock_winit;
9808 	} else {
9809 #ifdef	_ILP32
9810 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9811 #else
9812 		tcp->tcp_acceptor_id = conn_dev;
9813 #endif	/* _ILP32 */
9814 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9815 	}
9816 
9817 	err = tcp_init(tcp, q);
9818 	if (err != 0) {
9819 		inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
9820 		tcp_acceptor_hash_remove(tcp);
9821 		CONN_DEC_REF(connp);
9822 		q->q_ptr = WR(q)->q_ptr = NULL;
9823 		return (err);
9824 	}
9825 
9826 	RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9827 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9828 
9829 	/* Non-zero default values */
9830 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9831 	/*
9832 	 * Put the ref for TCP. Ref for IP was already put
9833 	 * by ipcl_conn_create. Also Make the conn_t globally
9834 	 * visible to walkers
9835 	 */
9836 	mutex_enter(&connp->conn_lock);
9837 	CONN_INC_REF_LOCKED(connp);
9838 	ASSERT(connp->conn_ref == 2);
9839 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9840 	mutex_exit(&connp->conn_lock);
9841 
9842 	qprocson(q);
9843 	return (0);
9844 }
9845 
9846 /*
9847  * Some TCP options can be "set" by requesting them in the option
9848  * buffer. This is needed for XTI feature test though we do not
9849  * allow it in general. We interpret that this mechanism is more
9850  * applicable to OSI protocols and need not be allowed in general.
9851  * This routine filters out options for which it is not allowed (most)
9852  * and lets through those (few) for which it is. [ The XTI interface
9853  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9854  * ever implemented will have to be allowed here ].
9855  */
9856 static boolean_t
9857 tcp_allow_connopt_set(int level, int name)
9858 {
9859 
9860 	switch (level) {
9861 	case IPPROTO_TCP:
9862 		switch (name) {
9863 		case TCP_NODELAY:
9864 			return (B_TRUE);
9865 		default:
9866 			return (B_FALSE);
9867 		}
9868 		/*NOTREACHED*/
9869 	default:
9870 		return (B_FALSE);
9871 	}
9872 	/*NOTREACHED*/
9873 }
9874 
9875 /*
9876  * This routine gets default values of certain options whose default
9877  * values are maintained by protocol specific code
9878  */
9879 /* ARGSUSED */
9880 int
9881 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9882 {
9883 	int32_t	*i1 = (int32_t *)ptr;
9884 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9885 
9886 	switch (level) {
9887 	case IPPROTO_TCP:
9888 		switch (name) {
9889 		case TCP_NOTIFY_THRESHOLD:
9890 			*i1 = tcps->tcps_ip_notify_interval;
9891 			break;
9892 		case TCP_ABORT_THRESHOLD:
9893 			*i1 = tcps->tcps_ip_abort_interval;
9894 			break;
9895 		case TCP_CONN_NOTIFY_THRESHOLD:
9896 			*i1 = tcps->tcps_ip_notify_cinterval;
9897 			break;
9898 		case TCP_CONN_ABORT_THRESHOLD:
9899 			*i1 = tcps->tcps_ip_abort_cinterval;
9900 			break;
9901 		default:
9902 			return (-1);
9903 		}
9904 		break;
9905 	case IPPROTO_IP:
9906 		switch (name) {
9907 		case IP_TTL:
9908 			*i1 = tcps->tcps_ipv4_ttl;
9909 			break;
9910 		default:
9911 			return (-1);
9912 		}
9913 		break;
9914 	case IPPROTO_IPV6:
9915 		switch (name) {
9916 		case IPV6_UNICAST_HOPS:
9917 			*i1 = tcps->tcps_ipv6_hoplimit;
9918 			break;
9919 		default:
9920 			return (-1);
9921 		}
9922 		break;
9923 	default:
9924 		return (-1);
9925 	}
9926 	return (sizeof (int));
9927 }
9928 
9929 
9930 /*
9931  * TCP routine to get the values of options.
9932  */
9933 int
9934 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9935 {
9936 	int		*i1 = (int *)ptr;
9937 	conn_t		*connp = Q_TO_CONN(q);
9938 	tcp_t		*tcp = connp->conn_tcp;
9939 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9940 
9941 	switch (level) {
9942 	case SOL_SOCKET:
9943 		switch (name) {
9944 		case SO_LINGER:	{
9945 			struct linger *lgr = (struct linger *)ptr;
9946 
9947 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9948 			lgr->l_linger = tcp->tcp_lingertime;
9949 			}
9950 			return (sizeof (struct linger));
9951 		case SO_DEBUG:
9952 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9953 			break;
9954 		case SO_KEEPALIVE:
9955 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9956 			break;
9957 		case SO_DONTROUTE:
9958 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9959 			break;
9960 		case SO_USELOOPBACK:
9961 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9962 			break;
9963 		case SO_BROADCAST:
9964 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9965 			break;
9966 		case SO_REUSEADDR:
9967 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9968 			break;
9969 		case SO_OOBINLINE:
9970 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9971 			break;
9972 		case SO_DGRAM_ERRIND:
9973 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9974 			break;
9975 		case SO_TYPE:
9976 			*i1 = SOCK_STREAM;
9977 			break;
9978 		case SO_SNDBUF:
9979 			*i1 = tcp->tcp_xmit_hiwater;
9980 			break;
9981 		case SO_RCVBUF:
9982 			*i1 = RD(q)->q_hiwat;
9983 			break;
9984 		case SO_SND_COPYAVOID:
9985 			*i1 = tcp->tcp_snd_zcopy_on ?
9986 			    SO_SND_COPYAVOID : 0;
9987 			break;
9988 		case SO_ALLZONES:
9989 			*i1 = connp->conn_allzones ? 1 : 0;
9990 			break;
9991 		case SO_ANON_MLP:
9992 			*i1 = connp->conn_anon_mlp;
9993 			break;
9994 		case SO_MAC_EXEMPT:
9995 			*i1 = connp->conn_mac_exempt;
9996 			break;
9997 		case SO_EXCLBIND:
9998 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9999 			break;
10000 		case SO_PROTOTYPE:
10001 			*i1 = IPPROTO_TCP;
10002 			break;
10003 		case SO_DOMAIN:
10004 			*i1 = tcp->tcp_family;
10005 			break;
10006 		default:
10007 			return (-1);
10008 		}
10009 		break;
10010 	case IPPROTO_TCP:
10011 		switch (name) {
10012 		case TCP_NODELAY:
10013 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
10014 			break;
10015 		case TCP_MAXSEG:
10016 			*i1 = tcp->tcp_mss;
10017 			break;
10018 		case TCP_NOTIFY_THRESHOLD:
10019 			*i1 = (int)tcp->tcp_first_timer_threshold;
10020 			break;
10021 		case TCP_ABORT_THRESHOLD:
10022 			*i1 = tcp->tcp_second_timer_threshold;
10023 			break;
10024 		case TCP_CONN_NOTIFY_THRESHOLD:
10025 			*i1 = tcp->tcp_first_ctimer_threshold;
10026 			break;
10027 		case TCP_CONN_ABORT_THRESHOLD:
10028 			*i1 = tcp->tcp_second_ctimer_threshold;
10029 			break;
10030 		case TCP_RECVDSTADDR:
10031 			*i1 = tcp->tcp_recvdstaddr;
10032 			break;
10033 		case TCP_ANONPRIVBIND:
10034 			*i1 = tcp->tcp_anon_priv_bind;
10035 			break;
10036 		case TCP_EXCLBIND:
10037 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
10038 			break;
10039 		case TCP_INIT_CWND:
10040 			*i1 = tcp->tcp_init_cwnd;
10041 			break;
10042 		case TCP_KEEPALIVE_THRESHOLD:
10043 			*i1 = tcp->tcp_ka_interval;
10044 			break;
10045 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10046 			*i1 = tcp->tcp_ka_abort_thres;
10047 			break;
10048 		case TCP_CORK:
10049 			*i1 = tcp->tcp_cork;
10050 			break;
10051 		default:
10052 			return (-1);
10053 		}
10054 		break;
10055 	case IPPROTO_IP:
10056 		if (tcp->tcp_family != AF_INET)
10057 			return (-1);
10058 		switch (name) {
10059 		case IP_OPTIONS:
10060 		case T_IP_OPTIONS: {
10061 			/*
10062 			 * This is compatible with BSD in that in only return
10063 			 * the reverse source route with the final destination
10064 			 * as the last entry. The first 4 bytes of the option
10065 			 * will contain the final destination.
10066 			 */
10067 			int	opt_len;
10068 
10069 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
10070 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
10071 			ASSERT(opt_len >= 0);
10072 			/* Caller ensures enough space */
10073 			if (opt_len > 0) {
10074 				/*
10075 				 * TODO: Do we have to handle getsockopt on an
10076 				 * initiator as well?
10077 				 */
10078 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
10079 			}
10080 			return (0);
10081 			}
10082 		case IP_TOS:
10083 		case T_IP_TOS:
10084 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10085 			break;
10086 		case IP_TTL:
10087 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10088 			break;
10089 		case IP_NEXTHOP:
10090 			/* Handled at IP level */
10091 			return (-EINVAL);
10092 		default:
10093 			return (-1);
10094 		}
10095 		break;
10096 	case IPPROTO_IPV6:
10097 		/*
10098 		 * IPPROTO_IPV6 options are only supported for sockets
10099 		 * that are using IPv6 on the wire.
10100 		 */
10101 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10102 			return (-1);
10103 		}
10104 		switch (name) {
10105 		case IPV6_UNICAST_HOPS:
10106 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10107 			break;	/* goto sizeof (int) option return */
10108 		case IPV6_BOUND_IF:
10109 			/* Zero if not set */
10110 			*i1 = tcp->tcp_bound_if;
10111 			break;	/* goto sizeof (int) option return */
10112 		case IPV6_RECVPKTINFO:
10113 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10114 				*i1 = 1;
10115 			else
10116 				*i1 = 0;
10117 			break;	/* goto sizeof (int) option return */
10118 		case IPV6_RECVTCLASS:
10119 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10120 				*i1 = 1;
10121 			else
10122 				*i1 = 0;
10123 			break;	/* goto sizeof (int) option return */
10124 		case IPV6_RECVHOPLIMIT:
10125 			if (tcp->tcp_ipv6_recvancillary &
10126 			    TCP_IPV6_RECVHOPLIMIT)
10127 				*i1 = 1;
10128 			else
10129 				*i1 = 0;
10130 			break;	/* goto sizeof (int) option return */
10131 		case IPV6_RECVHOPOPTS:
10132 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10133 				*i1 = 1;
10134 			else
10135 				*i1 = 0;
10136 			break;	/* goto sizeof (int) option return */
10137 		case IPV6_RECVDSTOPTS:
10138 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10139 				*i1 = 1;
10140 			else
10141 				*i1 = 0;
10142 			break;	/* goto sizeof (int) option return */
10143 		case _OLD_IPV6_RECVDSTOPTS:
10144 			if (tcp->tcp_ipv6_recvancillary &
10145 			    TCP_OLD_IPV6_RECVDSTOPTS)
10146 				*i1 = 1;
10147 			else
10148 				*i1 = 0;
10149 			break;	/* goto sizeof (int) option return */
10150 		case IPV6_RECVRTHDR:
10151 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10152 				*i1 = 1;
10153 			else
10154 				*i1 = 0;
10155 			break;	/* goto sizeof (int) option return */
10156 		case IPV6_RECVRTHDRDSTOPTS:
10157 			if (tcp->tcp_ipv6_recvancillary &
10158 			    TCP_IPV6_RECVRTDSTOPTS)
10159 				*i1 = 1;
10160 			else
10161 				*i1 = 0;
10162 			break;	/* goto sizeof (int) option return */
10163 		case IPV6_PKTINFO: {
10164 			/* XXX assumes that caller has room for max size! */
10165 			struct in6_pktinfo *pkti;
10166 
10167 			pkti = (struct in6_pktinfo *)ptr;
10168 			if (ipp->ipp_fields & IPPF_IFINDEX)
10169 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10170 			else
10171 				pkti->ipi6_ifindex = 0;
10172 			if (ipp->ipp_fields & IPPF_ADDR)
10173 				pkti->ipi6_addr = ipp->ipp_addr;
10174 			else
10175 				pkti->ipi6_addr = ipv6_all_zeros;
10176 			return (sizeof (struct in6_pktinfo));
10177 		}
10178 		case IPV6_TCLASS:
10179 			if (ipp->ipp_fields & IPPF_TCLASS)
10180 				*i1 = ipp->ipp_tclass;
10181 			else
10182 				*i1 = IPV6_FLOW_TCLASS(
10183 				    IPV6_DEFAULT_VERS_AND_FLOW);
10184 			break;	/* goto sizeof (int) option return */
10185 		case IPV6_NEXTHOP: {
10186 			sin6_t *sin6 = (sin6_t *)ptr;
10187 
10188 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10189 				return (0);
10190 			*sin6 = sin6_null;
10191 			sin6->sin6_family = AF_INET6;
10192 			sin6->sin6_addr = ipp->ipp_nexthop;
10193 			return (sizeof (sin6_t));
10194 		}
10195 		case IPV6_HOPOPTS:
10196 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10197 				return (0);
10198 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
10199 				return (0);
10200 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
10201 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
10202 			if (tcp->tcp_label_len > 0) {
10203 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
10204 				ptr[1] = (ipp->ipp_hopoptslen -
10205 				    tcp->tcp_label_len + 7) / 8 - 1;
10206 			}
10207 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
10208 		case IPV6_RTHDRDSTOPTS:
10209 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10210 				return (0);
10211 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10212 			return (ipp->ipp_rtdstoptslen);
10213 		case IPV6_RTHDR:
10214 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10215 				return (0);
10216 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10217 			return (ipp->ipp_rthdrlen);
10218 		case IPV6_DSTOPTS:
10219 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10220 				return (0);
10221 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10222 			return (ipp->ipp_dstoptslen);
10223 		case IPV6_SRC_PREFERENCES:
10224 			return (ip6_get_src_preferences(connp,
10225 			    (uint32_t *)ptr));
10226 		case IPV6_PATHMTU: {
10227 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10228 
10229 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10230 				return (-1);
10231 
10232 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10233 			    connp->conn_fport, mtuinfo,
10234 			    connp->conn_netstack));
10235 		}
10236 		default:
10237 			return (-1);
10238 		}
10239 		break;
10240 	default:
10241 		return (-1);
10242 	}
10243 	return (sizeof (int));
10244 }
10245 
10246 /*
10247  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10248  * Parameters are assumed to be verified by the caller.
10249  */
10250 /* ARGSUSED */
10251 int
10252 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10253     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10254     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10255 {
10256 	conn_t	*connp = Q_TO_CONN(q);
10257 	tcp_t	*tcp = connp->conn_tcp;
10258 	int	*i1 = (int *)invalp;
10259 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10260 	boolean_t checkonly;
10261 	int	reterr;
10262 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
10263 
10264 	switch (optset_context) {
10265 	case SETFN_OPTCOM_CHECKONLY:
10266 		checkonly = B_TRUE;
10267 		/*
10268 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10269 		 * inlen != 0 implies value supplied and
10270 		 * 	we have to "pretend" to set it.
10271 		 * inlen == 0 implies that there is no
10272 		 * 	value part in T_CHECK request and just validation
10273 		 * done elsewhere should be enough, we just return here.
10274 		 */
10275 		if (inlen == 0) {
10276 			*outlenp = 0;
10277 			return (0);
10278 		}
10279 		break;
10280 	case SETFN_OPTCOM_NEGOTIATE:
10281 		checkonly = B_FALSE;
10282 		break;
10283 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10284 	case SETFN_CONN_NEGOTIATE:
10285 		checkonly = B_FALSE;
10286 		/*
10287 		 * Negotiating local and "association-related" options
10288 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10289 		 * primitives is allowed by XTI, but we choose
10290 		 * to not implement this style negotiation for Internet
10291 		 * protocols (We interpret it is a must for OSI world but
10292 		 * optional for Internet protocols) for all options.
10293 		 * [ Will do only for the few options that enable test
10294 		 * suites that our XTI implementation of this feature
10295 		 * works for transports that do allow it ]
10296 		 */
10297 		if (!tcp_allow_connopt_set(level, name)) {
10298 			*outlenp = 0;
10299 			return (EINVAL);
10300 		}
10301 		break;
10302 	default:
10303 		/*
10304 		 * We should never get here
10305 		 */
10306 		*outlenp = 0;
10307 		return (EINVAL);
10308 	}
10309 
10310 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10311 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10312 
10313 	/*
10314 	 * For TCP, we should have no ancillary data sent down
10315 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10316 	 * has to be zero.
10317 	 */
10318 	ASSERT(thisdg_attrs == NULL);
10319 
10320 	/*
10321 	 * For fixed length options, no sanity check
10322 	 * of passed in length is done. It is assumed *_optcom_req()
10323 	 * routines do the right thing.
10324 	 */
10325 
10326 	switch (level) {
10327 	case SOL_SOCKET:
10328 		switch (name) {
10329 		case SO_LINGER: {
10330 			struct linger *lgr = (struct linger *)invalp;
10331 
10332 			if (!checkonly) {
10333 				if (lgr->l_onoff) {
10334 					tcp->tcp_linger = 1;
10335 					tcp->tcp_lingertime = lgr->l_linger;
10336 				} else {
10337 					tcp->tcp_linger = 0;
10338 					tcp->tcp_lingertime = 0;
10339 				}
10340 				/* struct copy */
10341 				*(struct linger *)outvalp = *lgr;
10342 			} else {
10343 				if (!lgr->l_onoff) {
10344 					((struct linger *)
10345 					    outvalp)->l_onoff = 0;
10346 					((struct linger *)
10347 					    outvalp)->l_linger = 0;
10348 				} else {
10349 					/* struct copy */
10350 					*(struct linger *)outvalp = *lgr;
10351 				}
10352 			}
10353 			*outlenp = sizeof (struct linger);
10354 			return (0);
10355 		}
10356 		case SO_DEBUG:
10357 			if (!checkonly)
10358 				tcp->tcp_debug = onoff;
10359 			break;
10360 		case SO_KEEPALIVE:
10361 			if (checkonly) {
10362 				/* T_CHECK case */
10363 				break;
10364 			}
10365 
10366 			if (!onoff) {
10367 				if (tcp->tcp_ka_enabled) {
10368 					if (tcp->tcp_ka_tid != 0) {
10369 						(void) TCP_TIMER_CANCEL(tcp,
10370 						    tcp->tcp_ka_tid);
10371 						tcp->tcp_ka_tid = 0;
10372 					}
10373 					tcp->tcp_ka_enabled = 0;
10374 				}
10375 				break;
10376 			}
10377 			if (!tcp->tcp_ka_enabled) {
10378 				/* Crank up the keepalive timer */
10379 				tcp->tcp_ka_last_intrvl = 0;
10380 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10381 				    tcp_keepalive_killer,
10382 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10383 				tcp->tcp_ka_enabled = 1;
10384 			}
10385 			break;
10386 		case SO_DONTROUTE:
10387 			/*
10388 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10389 			 * only of interest to IP.  We track them here only so
10390 			 * that we can report their current value.
10391 			 */
10392 			if (!checkonly) {
10393 				tcp->tcp_dontroute = onoff;
10394 				tcp->tcp_connp->conn_dontroute = onoff;
10395 			}
10396 			break;
10397 		case SO_USELOOPBACK:
10398 			if (!checkonly) {
10399 				tcp->tcp_useloopback = onoff;
10400 				tcp->tcp_connp->conn_loopback = onoff;
10401 			}
10402 			break;
10403 		case SO_BROADCAST:
10404 			if (!checkonly) {
10405 				tcp->tcp_broadcast = onoff;
10406 				tcp->tcp_connp->conn_broadcast = onoff;
10407 			}
10408 			break;
10409 		case SO_REUSEADDR:
10410 			if (!checkonly) {
10411 				tcp->tcp_reuseaddr = onoff;
10412 				tcp->tcp_connp->conn_reuseaddr = onoff;
10413 			}
10414 			break;
10415 		case SO_OOBINLINE:
10416 			if (!checkonly)
10417 				tcp->tcp_oobinline = onoff;
10418 			break;
10419 		case SO_DGRAM_ERRIND:
10420 			if (!checkonly)
10421 				tcp->tcp_dgram_errind = onoff;
10422 			break;
10423 		case SO_SNDBUF: {
10424 			if (*i1 > tcps->tcps_max_buf) {
10425 				*outlenp = 0;
10426 				return (ENOBUFS);
10427 			}
10428 			if (checkonly)
10429 				break;
10430 
10431 			tcp->tcp_xmit_hiwater = *i1;
10432 			if (tcps->tcps_snd_lowat_fraction != 0)
10433 				tcp->tcp_xmit_lowater =
10434 				    tcp->tcp_xmit_hiwater /
10435 				    tcps->tcps_snd_lowat_fraction;
10436 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10437 			/*
10438 			 * If we are flow-controlled, recheck the condition.
10439 			 * There are apps that increase SO_SNDBUF size when
10440 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10441 			 * control condition to be lifted right away.
10442 			 */
10443 			mutex_enter(&tcp->tcp_non_sq_lock);
10444 			if (tcp->tcp_flow_stopped &&
10445 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10446 				tcp_clrqfull(tcp);
10447 			}
10448 			mutex_exit(&tcp->tcp_non_sq_lock);
10449 			break;
10450 		}
10451 		case SO_RCVBUF:
10452 			if (*i1 > tcps->tcps_max_buf) {
10453 				*outlenp = 0;
10454 				return (ENOBUFS);
10455 			}
10456 			/* Silently ignore zero */
10457 			if (!checkonly && *i1 != 0) {
10458 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10459 				(void) tcp_rwnd_set(tcp, *i1);
10460 			}
10461 			/*
10462 			 * XXX should we return the rwnd here
10463 			 * and tcp_opt_get ?
10464 			 */
10465 			break;
10466 		case SO_SND_COPYAVOID:
10467 			if (!checkonly) {
10468 				/* we only allow enable at most once for now */
10469 				if (tcp->tcp_loopback ||
10470 				    (tcp->tcp_kssl_ctx != NULL) ||
10471 				    (!tcp->tcp_snd_zcopy_aware &&
10472 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10473 					*outlenp = 0;
10474 					return (EOPNOTSUPP);
10475 				}
10476 				tcp->tcp_snd_zcopy_aware = 1;
10477 			}
10478 			break;
10479 		case SO_ALLZONES:
10480 			/* Pass option along to IP level for handling */
10481 			return (-EINVAL);
10482 		case SO_ANON_MLP:
10483 			/* Pass option along to IP level for handling */
10484 			return (-EINVAL);
10485 		case SO_MAC_EXEMPT:
10486 			/* Pass option along to IP level for handling */
10487 			return (-EINVAL);
10488 		case SO_EXCLBIND:
10489 			if (!checkonly)
10490 				tcp->tcp_exclbind = onoff;
10491 			break;
10492 		default:
10493 			*outlenp = 0;
10494 			return (EINVAL);
10495 		}
10496 		break;
10497 	case IPPROTO_TCP:
10498 		switch (name) {
10499 		case TCP_NODELAY:
10500 			if (!checkonly)
10501 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10502 			break;
10503 		case TCP_NOTIFY_THRESHOLD:
10504 			if (!checkonly)
10505 				tcp->tcp_first_timer_threshold = *i1;
10506 			break;
10507 		case TCP_ABORT_THRESHOLD:
10508 			if (!checkonly)
10509 				tcp->tcp_second_timer_threshold = *i1;
10510 			break;
10511 		case TCP_CONN_NOTIFY_THRESHOLD:
10512 			if (!checkonly)
10513 				tcp->tcp_first_ctimer_threshold = *i1;
10514 			break;
10515 		case TCP_CONN_ABORT_THRESHOLD:
10516 			if (!checkonly)
10517 				tcp->tcp_second_ctimer_threshold = *i1;
10518 			break;
10519 		case TCP_RECVDSTADDR:
10520 			if (tcp->tcp_state > TCPS_LISTEN)
10521 				return (EOPNOTSUPP);
10522 			if (!checkonly)
10523 				tcp->tcp_recvdstaddr = onoff;
10524 			break;
10525 		case TCP_ANONPRIVBIND:
10526 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10527 			    IPPROTO_TCP)) != 0) {
10528 				*outlenp = 0;
10529 				return (reterr);
10530 			}
10531 			if (!checkonly) {
10532 				tcp->tcp_anon_priv_bind = onoff;
10533 			}
10534 			break;
10535 		case TCP_EXCLBIND:
10536 			if (!checkonly)
10537 				tcp->tcp_exclbind = onoff;
10538 			break;	/* goto sizeof (int) option return */
10539 		case TCP_INIT_CWND: {
10540 			uint32_t init_cwnd = *((uint32_t *)invalp);
10541 
10542 			if (checkonly)
10543 				break;
10544 
10545 			/*
10546 			 * Only allow socket with network configuration
10547 			 * privilege to set the initial cwnd to be larger
10548 			 * than allowed by RFC 3390.
10549 			 */
10550 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10551 				tcp->tcp_init_cwnd = init_cwnd;
10552 				break;
10553 			}
10554 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10555 				*outlenp = 0;
10556 				return (reterr);
10557 			}
10558 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10559 				*outlenp = 0;
10560 				return (EINVAL);
10561 			}
10562 			tcp->tcp_init_cwnd = init_cwnd;
10563 			break;
10564 		}
10565 		case TCP_KEEPALIVE_THRESHOLD:
10566 			if (checkonly)
10567 				break;
10568 
10569 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10570 			    *i1 > tcps->tcps_keepalive_interval_high) {
10571 				*outlenp = 0;
10572 				return (EINVAL);
10573 			}
10574 			if (*i1 != tcp->tcp_ka_interval) {
10575 				tcp->tcp_ka_interval = *i1;
10576 				/*
10577 				 * Check if we need to restart the
10578 				 * keepalive timer.
10579 				 */
10580 				if (tcp->tcp_ka_tid != 0) {
10581 					ASSERT(tcp->tcp_ka_enabled);
10582 					(void) TCP_TIMER_CANCEL(tcp,
10583 					    tcp->tcp_ka_tid);
10584 					tcp->tcp_ka_last_intrvl = 0;
10585 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10586 					    tcp_keepalive_killer,
10587 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10588 				}
10589 			}
10590 			break;
10591 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10592 			if (!checkonly) {
10593 				if (*i1 <
10594 				    tcps->tcps_keepalive_abort_interval_low ||
10595 				    *i1 >
10596 				    tcps->tcps_keepalive_abort_interval_high) {
10597 					*outlenp = 0;
10598 					return (EINVAL);
10599 				}
10600 				tcp->tcp_ka_abort_thres = *i1;
10601 			}
10602 			break;
10603 		case TCP_CORK:
10604 			if (!checkonly) {
10605 				/*
10606 				 * if tcp->tcp_cork was set and is now
10607 				 * being unset, we have to make sure that
10608 				 * the remaining data gets sent out. Also
10609 				 * unset tcp->tcp_cork so that tcp_wput_data()
10610 				 * can send data even if it is less than mss
10611 				 */
10612 				if (tcp->tcp_cork && onoff == 0 &&
10613 				    tcp->tcp_unsent > 0) {
10614 					tcp->tcp_cork = B_FALSE;
10615 					tcp_wput_data(tcp, NULL, B_FALSE);
10616 				}
10617 				tcp->tcp_cork = onoff;
10618 			}
10619 			break;
10620 		default:
10621 			*outlenp = 0;
10622 			return (EINVAL);
10623 		}
10624 		break;
10625 	case IPPROTO_IP:
10626 		if (tcp->tcp_family != AF_INET) {
10627 			*outlenp = 0;
10628 			return (ENOPROTOOPT);
10629 		}
10630 		switch (name) {
10631 		case IP_OPTIONS:
10632 		case T_IP_OPTIONS:
10633 			reterr = tcp_opt_set_header(tcp, checkonly,
10634 			    invalp, inlen);
10635 			if (reterr) {
10636 				*outlenp = 0;
10637 				return (reterr);
10638 			}
10639 			/* OK return - copy input buffer into output buffer */
10640 			if (invalp != outvalp) {
10641 				/* don't trust bcopy for identical src/dst */
10642 				bcopy(invalp, outvalp, inlen);
10643 			}
10644 			*outlenp = inlen;
10645 			return (0);
10646 		case IP_TOS:
10647 		case T_IP_TOS:
10648 			if (!checkonly) {
10649 				tcp->tcp_ipha->ipha_type_of_service =
10650 				    (uchar_t)*i1;
10651 				tcp->tcp_tos = (uchar_t)*i1;
10652 			}
10653 			break;
10654 		case IP_TTL:
10655 			if (!checkonly) {
10656 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10657 				tcp->tcp_ttl = (uchar_t)*i1;
10658 			}
10659 			break;
10660 		case IP_BOUND_IF:
10661 		case IP_NEXTHOP:
10662 			/* Handled at the IP level */
10663 			return (-EINVAL);
10664 		case IP_SEC_OPT:
10665 			/*
10666 			 * We should not allow policy setting after
10667 			 * we start listening for connections.
10668 			 */
10669 			if (tcp->tcp_state == TCPS_LISTEN) {
10670 				return (EINVAL);
10671 			} else {
10672 				/* Handled at the IP level */
10673 				return (-EINVAL);
10674 			}
10675 		default:
10676 			*outlenp = 0;
10677 			return (EINVAL);
10678 		}
10679 		break;
10680 	case IPPROTO_IPV6: {
10681 		ip6_pkt_t		*ipp;
10682 
10683 		/*
10684 		 * IPPROTO_IPV6 options are only supported for sockets
10685 		 * that are using IPv6 on the wire.
10686 		 */
10687 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10688 			*outlenp = 0;
10689 			return (ENOPROTOOPT);
10690 		}
10691 		/*
10692 		 * Only sticky options; no ancillary data
10693 		 */
10694 		ASSERT(thisdg_attrs == NULL);
10695 		ipp = &tcp->tcp_sticky_ipp;
10696 
10697 		switch (name) {
10698 		case IPV6_UNICAST_HOPS:
10699 			/* -1 means use default */
10700 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10701 				*outlenp = 0;
10702 				return (EINVAL);
10703 			}
10704 			if (!checkonly) {
10705 				if (*i1 == -1) {
10706 					tcp->tcp_ip6h->ip6_hops =
10707 					    ipp->ipp_unicast_hops =
10708 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10709 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10710 					/* Pass modified value to IP. */
10711 					*i1 = tcp->tcp_ip6h->ip6_hops;
10712 				} else {
10713 					tcp->tcp_ip6h->ip6_hops =
10714 					    ipp->ipp_unicast_hops =
10715 					    (uint8_t)*i1;
10716 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10717 				}
10718 				reterr = tcp_build_hdrs(q, tcp);
10719 				if (reterr != 0)
10720 					return (reterr);
10721 			}
10722 			break;
10723 		case IPV6_BOUND_IF:
10724 			if (!checkonly) {
10725 				int error = 0;
10726 
10727 				tcp->tcp_bound_if = *i1;
10728 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10729 				    B_TRUE, checkonly, level, name, mblk);
10730 				if (error != 0) {
10731 					*outlenp = 0;
10732 					return (error);
10733 				}
10734 			}
10735 			break;
10736 		/*
10737 		 * Set boolean switches for ancillary data delivery
10738 		 */
10739 		case IPV6_RECVPKTINFO:
10740 			if (!checkonly) {
10741 				if (onoff)
10742 					tcp->tcp_ipv6_recvancillary |=
10743 					    TCP_IPV6_RECVPKTINFO;
10744 				else
10745 					tcp->tcp_ipv6_recvancillary &=
10746 					    ~TCP_IPV6_RECVPKTINFO;
10747 				/* Force it to be sent up with the next msg */
10748 				tcp->tcp_recvifindex = 0;
10749 			}
10750 			break;
10751 		case IPV6_RECVTCLASS:
10752 			if (!checkonly) {
10753 				if (onoff)
10754 					tcp->tcp_ipv6_recvancillary |=
10755 					    TCP_IPV6_RECVTCLASS;
10756 				else
10757 					tcp->tcp_ipv6_recvancillary &=
10758 					    ~TCP_IPV6_RECVTCLASS;
10759 			}
10760 			break;
10761 		case IPV6_RECVHOPLIMIT:
10762 			if (!checkonly) {
10763 				if (onoff)
10764 					tcp->tcp_ipv6_recvancillary |=
10765 					    TCP_IPV6_RECVHOPLIMIT;
10766 				else
10767 					tcp->tcp_ipv6_recvancillary &=
10768 					    ~TCP_IPV6_RECVHOPLIMIT;
10769 				/* Force it to be sent up with the next msg */
10770 				tcp->tcp_recvhops = 0xffffffffU;
10771 			}
10772 			break;
10773 		case IPV6_RECVHOPOPTS:
10774 			if (!checkonly) {
10775 				if (onoff)
10776 					tcp->tcp_ipv6_recvancillary |=
10777 					    TCP_IPV6_RECVHOPOPTS;
10778 				else
10779 					tcp->tcp_ipv6_recvancillary &=
10780 					    ~TCP_IPV6_RECVHOPOPTS;
10781 			}
10782 			break;
10783 		case IPV6_RECVDSTOPTS:
10784 			if (!checkonly) {
10785 				if (onoff)
10786 					tcp->tcp_ipv6_recvancillary |=
10787 					    TCP_IPV6_RECVDSTOPTS;
10788 				else
10789 					tcp->tcp_ipv6_recvancillary &=
10790 					    ~TCP_IPV6_RECVDSTOPTS;
10791 			}
10792 			break;
10793 		case _OLD_IPV6_RECVDSTOPTS:
10794 			if (!checkonly) {
10795 				if (onoff)
10796 					tcp->tcp_ipv6_recvancillary |=
10797 					    TCP_OLD_IPV6_RECVDSTOPTS;
10798 				else
10799 					tcp->tcp_ipv6_recvancillary &=
10800 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10801 			}
10802 			break;
10803 		case IPV6_RECVRTHDR:
10804 			if (!checkonly) {
10805 				if (onoff)
10806 					tcp->tcp_ipv6_recvancillary |=
10807 					    TCP_IPV6_RECVRTHDR;
10808 				else
10809 					tcp->tcp_ipv6_recvancillary &=
10810 					    ~TCP_IPV6_RECVRTHDR;
10811 			}
10812 			break;
10813 		case IPV6_RECVRTHDRDSTOPTS:
10814 			if (!checkonly) {
10815 				if (onoff)
10816 					tcp->tcp_ipv6_recvancillary |=
10817 					    TCP_IPV6_RECVRTDSTOPTS;
10818 				else
10819 					tcp->tcp_ipv6_recvancillary &=
10820 					    ~TCP_IPV6_RECVRTDSTOPTS;
10821 			}
10822 			break;
10823 		case IPV6_PKTINFO:
10824 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10825 				return (EINVAL);
10826 			if (checkonly)
10827 				break;
10828 
10829 			if (inlen == 0) {
10830 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10831 			} else {
10832 				struct in6_pktinfo *pkti;
10833 
10834 				pkti = (struct in6_pktinfo *)invalp;
10835 				/*
10836 				 * RFC 3542 states that ipi6_addr must be
10837 				 * the unspecified address when setting the
10838 				 * IPV6_PKTINFO sticky socket option on a
10839 				 * TCP socket.
10840 				 */
10841 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10842 					return (EINVAL);
10843 				/*
10844 				 * ip6_set_pktinfo() validates the source
10845 				 * address and interface index.
10846 				 */
10847 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10848 				    pkti, mblk);
10849 				if (reterr != 0)
10850 					return (reterr);
10851 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10852 				ipp->ipp_addr = pkti->ipi6_addr;
10853 				if (ipp->ipp_ifindex != 0)
10854 					ipp->ipp_fields |= IPPF_IFINDEX;
10855 				else
10856 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10857 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10858 					ipp->ipp_fields |= IPPF_ADDR;
10859 				else
10860 					ipp->ipp_fields &= ~IPPF_ADDR;
10861 			}
10862 			reterr = tcp_build_hdrs(q, tcp);
10863 			if (reterr != 0)
10864 				return (reterr);
10865 			break;
10866 		case IPV6_TCLASS:
10867 			if (inlen != 0 && inlen != sizeof (int))
10868 				return (EINVAL);
10869 			if (checkonly)
10870 				break;
10871 
10872 			if (inlen == 0) {
10873 				ipp->ipp_fields &= ~IPPF_TCLASS;
10874 			} else {
10875 				if (*i1 > 255 || *i1 < -1)
10876 					return (EINVAL);
10877 				if (*i1 == -1) {
10878 					ipp->ipp_tclass = 0;
10879 					*i1 = 0;
10880 				} else {
10881 					ipp->ipp_tclass = *i1;
10882 				}
10883 				ipp->ipp_fields |= IPPF_TCLASS;
10884 			}
10885 			reterr = tcp_build_hdrs(q, tcp);
10886 			if (reterr != 0)
10887 				return (reterr);
10888 			break;
10889 		case IPV6_NEXTHOP:
10890 			/*
10891 			 * IP will verify that the nexthop is reachable
10892 			 * and fail for sticky options.
10893 			 */
10894 			if (inlen != 0 && inlen != sizeof (sin6_t))
10895 				return (EINVAL);
10896 			if (checkonly)
10897 				break;
10898 
10899 			if (inlen == 0) {
10900 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10901 			} else {
10902 				sin6_t *sin6 = (sin6_t *)invalp;
10903 
10904 				if (sin6->sin6_family != AF_INET6)
10905 					return (EAFNOSUPPORT);
10906 				if (IN6_IS_ADDR_V4MAPPED(
10907 				    &sin6->sin6_addr))
10908 					return (EADDRNOTAVAIL);
10909 				ipp->ipp_nexthop = sin6->sin6_addr;
10910 				if (!IN6_IS_ADDR_UNSPECIFIED(
10911 				    &ipp->ipp_nexthop))
10912 					ipp->ipp_fields |= IPPF_NEXTHOP;
10913 				else
10914 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10915 			}
10916 			reterr = tcp_build_hdrs(q, tcp);
10917 			if (reterr != 0)
10918 				return (reterr);
10919 			break;
10920 		case IPV6_HOPOPTS: {
10921 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10922 
10923 			/*
10924 			 * Sanity checks - minimum size, size a multiple of
10925 			 * eight bytes, and matching size passed in.
10926 			 */
10927 			if (inlen != 0 &&
10928 			    inlen != (8 * (hopts->ip6h_len + 1)))
10929 				return (EINVAL);
10930 
10931 			if (checkonly)
10932 				break;
10933 
10934 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10935 			    (uchar_t **)&ipp->ipp_hopopts,
10936 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10937 			if (reterr != 0)
10938 				return (reterr);
10939 			if (ipp->ipp_hopoptslen == 0)
10940 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10941 			else
10942 				ipp->ipp_fields |= IPPF_HOPOPTS;
10943 			reterr = tcp_build_hdrs(q, tcp);
10944 			if (reterr != 0)
10945 				return (reterr);
10946 			break;
10947 		}
10948 		case IPV6_RTHDRDSTOPTS: {
10949 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10950 
10951 			/*
10952 			 * Sanity checks - minimum size, size a multiple of
10953 			 * eight bytes, and matching size passed in.
10954 			 */
10955 			if (inlen != 0 &&
10956 			    inlen != (8 * (dopts->ip6d_len + 1)))
10957 				return (EINVAL);
10958 
10959 			if (checkonly)
10960 				break;
10961 
10962 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10963 			    (uchar_t **)&ipp->ipp_rtdstopts,
10964 			    &ipp->ipp_rtdstoptslen, 0);
10965 			if (reterr != 0)
10966 				return (reterr);
10967 			if (ipp->ipp_rtdstoptslen == 0)
10968 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10969 			else
10970 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10971 			reterr = tcp_build_hdrs(q, tcp);
10972 			if (reterr != 0)
10973 				return (reterr);
10974 			break;
10975 		}
10976 		case IPV6_DSTOPTS: {
10977 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10978 
10979 			/*
10980 			 * Sanity checks - minimum size, size a multiple of
10981 			 * eight bytes, and matching size passed in.
10982 			 */
10983 			if (inlen != 0 &&
10984 			    inlen != (8 * (dopts->ip6d_len + 1)))
10985 				return (EINVAL);
10986 
10987 			if (checkonly)
10988 				break;
10989 
10990 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10991 			    (uchar_t **)&ipp->ipp_dstopts,
10992 			    &ipp->ipp_dstoptslen, 0);
10993 			if (reterr != 0)
10994 				return (reterr);
10995 			if (ipp->ipp_dstoptslen == 0)
10996 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10997 			else
10998 				ipp->ipp_fields |= IPPF_DSTOPTS;
10999 			reterr = tcp_build_hdrs(q, tcp);
11000 			if (reterr != 0)
11001 				return (reterr);
11002 			break;
11003 		}
11004 		case IPV6_RTHDR: {
11005 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
11006 
11007 			/*
11008 			 * Sanity checks - minimum size, size a multiple of
11009 			 * eight bytes, and matching size passed in.
11010 			 */
11011 			if (inlen != 0 &&
11012 			    inlen != (8 * (rt->ip6r_len + 1)))
11013 				return (EINVAL);
11014 
11015 			if (checkonly)
11016 				break;
11017 
11018 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
11019 			    (uchar_t **)&ipp->ipp_rthdr,
11020 			    &ipp->ipp_rthdrlen, 0);
11021 			if (reterr != 0)
11022 				return (reterr);
11023 			if (ipp->ipp_rthdrlen == 0)
11024 				ipp->ipp_fields &= ~IPPF_RTHDR;
11025 			else
11026 				ipp->ipp_fields |= IPPF_RTHDR;
11027 			reterr = tcp_build_hdrs(q, tcp);
11028 			if (reterr != 0)
11029 				return (reterr);
11030 			break;
11031 		}
11032 		case IPV6_V6ONLY:
11033 			if (!checkonly)
11034 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
11035 			break;
11036 		case IPV6_USE_MIN_MTU:
11037 			if (inlen != sizeof (int))
11038 				return (EINVAL);
11039 
11040 			if (*i1 < -1 || *i1 > 1)
11041 				return (EINVAL);
11042 
11043 			if (checkonly)
11044 				break;
11045 
11046 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
11047 			ipp->ipp_use_min_mtu = *i1;
11048 			break;
11049 		case IPV6_BOUND_PIF:
11050 			/* Handled at the IP level */
11051 			return (-EINVAL);
11052 		case IPV6_SEC_OPT:
11053 			/*
11054 			 * We should not allow policy setting after
11055 			 * we start listening for connections.
11056 			 */
11057 			if (tcp->tcp_state == TCPS_LISTEN) {
11058 				return (EINVAL);
11059 			} else {
11060 				/* Handled at the IP level */
11061 				return (-EINVAL);
11062 			}
11063 		case IPV6_SRC_PREFERENCES:
11064 			if (inlen != sizeof (uint32_t))
11065 				return (EINVAL);
11066 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
11067 			    *(uint32_t *)invalp);
11068 			if (reterr != 0) {
11069 				*outlenp = 0;
11070 				return (reterr);
11071 			}
11072 			break;
11073 		default:
11074 			*outlenp = 0;
11075 			return (EINVAL);
11076 		}
11077 		break;
11078 	}		/* end IPPROTO_IPV6 */
11079 	default:
11080 		*outlenp = 0;
11081 		return (EINVAL);
11082 	}
11083 	/*
11084 	 * Common case of OK return with outval same as inval
11085 	 */
11086 	if (invalp != outvalp) {
11087 		/* don't trust bcopy for identical src/dst */
11088 		(void) bcopy(invalp, outvalp, inlen);
11089 	}
11090 	*outlenp = inlen;
11091 	return (0);
11092 }
11093 
11094 /*
11095  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11096  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11097  * headers, and the maximum size tcp header (to avoid reallocation
11098  * on the fly for additional tcp options).
11099  * Returns failure if can't allocate memory.
11100  */
11101 static int
11102 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11103 {
11104 	char	*hdrs;
11105 	uint_t	hdrs_len;
11106 	ip6i_t	*ip6i;
11107 	char	buf[TCP_MAX_HDR_LENGTH];
11108 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11109 	in6_addr_t src, dst;
11110 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11111 
11112 	/*
11113 	 * save the existing tcp header and source/dest IP addresses
11114 	 */
11115 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11116 	src = tcp->tcp_ip6h->ip6_src;
11117 	dst = tcp->tcp_ip6h->ip6_dst;
11118 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11119 	ASSERT(hdrs_len != 0);
11120 	if (hdrs_len > tcp->tcp_iphc_len) {
11121 		/* Need to reallocate */
11122 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11123 		if (hdrs == NULL)
11124 			return (ENOMEM);
11125 		if (tcp->tcp_iphc != NULL) {
11126 			if (tcp->tcp_hdr_grown) {
11127 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11128 			} else {
11129 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11130 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11131 			}
11132 			tcp->tcp_iphc_len = 0;
11133 		}
11134 		ASSERT(tcp->tcp_iphc_len == 0);
11135 		tcp->tcp_iphc = hdrs;
11136 		tcp->tcp_iphc_len = hdrs_len;
11137 		tcp->tcp_hdr_grown = B_TRUE;
11138 	}
11139 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11140 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11141 
11142 	/* Set header fields not in ipp */
11143 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11144 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11145 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11146 	} else {
11147 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11148 	}
11149 	/*
11150 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11151 	 *
11152 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11153 	 */
11154 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11155 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11156 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11157 
11158 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11159 
11160 	tcp->tcp_ip6h->ip6_src = src;
11161 	tcp->tcp_ip6h->ip6_dst = dst;
11162 
11163 	/*
11164 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11165 	 * the default value for TCP.
11166 	 */
11167 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11168 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
11169 
11170 	/*
11171 	 * If we're setting extension headers after a connection
11172 	 * has been established, and if we have a routing header
11173 	 * among the extension headers, call ip_massage_options_v6 to
11174 	 * manipulate the routing header/ip6_dst set the checksum
11175 	 * difference in the tcp header template.
11176 	 * (This happens in tcp_connect_ipv6 if the routing header
11177 	 * is set prior to the connect.)
11178 	 * Set the tcp_sum to zero first in case we've cleared a
11179 	 * routing header or don't have one at all.
11180 	 */
11181 	tcp->tcp_sum = 0;
11182 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11183 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11184 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11185 		    (uint8_t *)tcp->tcp_tcph);
11186 		if (rth != NULL) {
11187 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11188 			    rth, tcps->tcps_netstack);
11189 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11190 			    (tcp->tcp_sum >> 16));
11191 		}
11192 	}
11193 
11194 	/* Try to get everything in a single mblk */
11195 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcps->tcps_wroff_xtra);
11196 	return (0);
11197 }
11198 
11199 /*
11200  * Transfer any source route option from ipha to buf/dst in reversed form.
11201  */
11202 static int
11203 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11204 {
11205 	ipoptp_t	opts;
11206 	uchar_t		*opt;
11207 	uint8_t		optval;
11208 	uint8_t		optlen;
11209 	uint32_t	len = 0;
11210 
11211 	for (optval = ipoptp_first(&opts, ipha);
11212 	    optval != IPOPT_EOL;
11213 	    optval = ipoptp_next(&opts)) {
11214 		opt = opts.ipoptp_cur;
11215 		optlen = opts.ipoptp_len;
11216 		switch (optval) {
11217 			int	off1, off2;
11218 		case IPOPT_SSRR:
11219 		case IPOPT_LSRR:
11220 
11221 			/* Reverse source route */
11222 			/*
11223 			 * First entry should be the next to last one in the
11224 			 * current source route (the last entry is our
11225 			 * address.)
11226 			 * The last entry should be the final destination.
11227 			 */
11228 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11229 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11230 			off1 = IPOPT_MINOFF_SR - 1;
11231 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11232 			if (off2 < 0) {
11233 				/* No entries in source route */
11234 				break;
11235 			}
11236 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11237 			/*
11238 			 * Note: use src since ipha has not had its src
11239 			 * and dst reversed (it is in the state it was
11240 			 * received.
11241 			 */
11242 			bcopy(&ipha->ipha_src, buf + off2,
11243 			    IP_ADDR_LEN);
11244 			off2 -= IP_ADDR_LEN;
11245 
11246 			while (off2 > 0) {
11247 				bcopy(opt + off2, buf + off1,
11248 				    IP_ADDR_LEN);
11249 				off1 += IP_ADDR_LEN;
11250 				off2 -= IP_ADDR_LEN;
11251 			}
11252 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11253 			buf += optlen;
11254 			len += optlen;
11255 			break;
11256 		}
11257 	}
11258 done:
11259 	/* Pad the resulting options */
11260 	while (len & 0x3) {
11261 		*buf++ = IPOPT_EOL;
11262 		len++;
11263 	}
11264 	return (len);
11265 }
11266 
11267 
11268 /*
11269  * Extract and revert a source route from ipha (if any)
11270  * and then update the relevant fields in both tcp_t and the standard header.
11271  */
11272 static void
11273 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11274 {
11275 	char	buf[TCP_MAX_HDR_LENGTH];
11276 	uint_t	tcph_len;
11277 	int	len;
11278 
11279 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11280 	len = IPH_HDR_LENGTH(ipha);
11281 	if (len == IP_SIMPLE_HDR_LENGTH)
11282 		/* Nothing to do */
11283 		return;
11284 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11285 	    (len & 0x3))
11286 		return;
11287 
11288 	tcph_len = tcp->tcp_tcp_hdr_len;
11289 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11290 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11291 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11292 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11293 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11294 	len += IP_SIMPLE_HDR_LENGTH;
11295 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11296 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11297 	if ((int)tcp->tcp_sum < 0)
11298 		tcp->tcp_sum--;
11299 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11300 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11301 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11302 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11303 	tcp->tcp_ip_hdr_len = len;
11304 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11305 	    (IP_VERSION << 4) | (len >> 2);
11306 	len += tcph_len;
11307 	tcp->tcp_hdr_len = len;
11308 }
11309 
11310 /*
11311  * Copy the standard header into its new location,
11312  * lay in the new options and then update the relevant
11313  * fields in both tcp_t and the standard header.
11314  */
11315 static int
11316 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11317 {
11318 	uint_t	tcph_len;
11319 	uint8_t	*ip_optp;
11320 	tcph_t	*new_tcph;
11321 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11322 
11323 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11324 		return (EINVAL);
11325 
11326 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11327 		return (EINVAL);
11328 
11329 	if (checkonly) {
11330 		/*
11331 		 * do not really set, just pretend to - T_CHECK
11332 		 */
11333 		return (0);
11334 	}
11335 
11336 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11337 	if (tcp->tcp_label_len > 0) {
11338 		int padlen;
11339 		uint8_t opt;
11340 
11341 		/* convert list termination to no-ops */
11342 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11343 		ip_optp += ip_optp[IPOPT_OLEN];
11344 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11345 		while (--padlen >= 0)
11346 			*ip_optp++ = opt;
11347 	}
11348 	tcph_len = tcp->tcp_tcp_hdr_len;
11349 	new_tcph = (tcph_t *)(ip_optp + len);
11350 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11351 	tcp->tcp_tcph = new_tcph;
11352 	bcopy(ptr, ip_optp, len);
11353 
11354 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11355 
11356 	tcp->tcp_ip_hdr_len = len;
11357 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11358 	    (IP_VERSION << 4) | (len >> 2);
11359 	tcp->tcp_hdr_len = len + tcph_len;
11360 	if (!TCP_IS_DETACHED(tcp)) {
11361 		/* Always allocate room for all options. */
11362 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11363 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11364 	}
11365 	return (0);
11366 }
11367 
11368 /* Get callback routine passed to nd_load by tcp_param_register */
11369 /* ARGSUSED */
11370 static int
11371 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11372 {
11373 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11374 
11375 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11376 	return (0);
11377 }
11378 
11379 /*
11380  * Walk through the param array specified registering each element with the
11381  * named dispatch handler.
11382  */
11383 static boolean_t
11384 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11385 {
11386 	for (; cnt-- > 0; tcppa++) {
11387 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11388 			if (!nd_load(ndp, tcppa->tcp_param_name,
11389 			    tcp_param_get, tcp_param_set,
11390 			    (caddr_t)tcppa)) {
11391 				nd_free(ndp);
11392 				return (B_FALSE);
11393 			}
11394 		}
11395 	}
11396 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11397 	    KM_SLEEP);
11398 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11399 	    sizeof (tcpparam_t));
11400 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11401 	    tcp_param_get, tcp_param_set_aligned,
11402 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11403 		nd_free(ndp);
11404 		return (B_FALSE);
11405 	}
11406 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11407 	    KM_SLEEP);
11408 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11409 	    sizeof (tcpparam_t));
11410 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11411 	    tcp_param_get, tcp_param_set_aligned,
11412 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11413 		nd_free(ndp);
11414 		return (B_FALSE);
11415 	}
11416 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11417 	    KM_SLEEP);
11418 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11419 	    sizeof (tcpparam_t));
11420 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11421 	    tcp_param_get, tcp_param_set_aligned,
11422 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11423 		nd_free(ndp);
11424 		return (B_FALSE);
11425 	}
11426 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11427 	    KM_SLEEP);
11428 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11429 	    sizeof (tcpparam_t));
11430 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11431 	    tcp_param_get, tcp_param_set_aligned,
11432 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11433 		nd_free(ndp);
11434 		return (B_FALSE);
11435 	}
11436 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11437 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11438 		nd_free(ndp);
11439 		return (B_FALSE);
11440 	}
11441 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11442 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11443 		nd_free(ndp);
11444 		return (B_FALSE);
11445 	}
11446 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11447 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11448 		nd_free(ndp);
11449 		return (B_FALSE);
11450 	}
11451 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11452 	    NULL)) {
11453 		nd_free(ndp);
11454 		return (B_FALSE);
11455 	}
11456 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11457 	    NULL, NULL)) {
11458 		nd_free(ndp);
11459 		return (B_FALSE);
11460 	}
11461 	if (!nd_load(ndp, "tcp_listen_hash",
11462 	    tcp_listen_hash_report, NULL, NULL)) {
11463 		nd_free(ndp);
11464 		return (B_FALSE);
11465 	}
11466 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11467 	    NULL, NULL)) {
11468 		nd_free(ndp);
11469 		return (B_FALSE);
11470 	}
11471 	if (!nd_load(ndp, "tcp_acceptor_hash",
11472 	    tcp_acceptor_hash_report, NULL, NULL)) {
11473 		nd_free(ndp);
11474 		return (B_FALSE);
11475 	}
11476 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11477 	    tcp_1948_phrase_set, NULL)) {
11478 		nd_free(ndp);
11479 		return (B_FALSE);
11480 	}
11481 	/*
11482 	 * Dummy ndd variables - only to convey obsolescence information
11483 	 * through printing of their name (no get or set routines)
11484 	 * XXX Remove in future releases ?
11485 	 */
11486 	if (!nd_load(ndp,
11487 	    "tcp_close_wait_interval(obsoleted - "
11488 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11489 		nd_free(ndp);
11490 		return (B_FALSE);
11491 	}
11492 	return (B_TRUE);
11493 }
11494 
11495 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11496 /* ARGSUSED */
11497 static int
11498 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11499     cred_t *cr)
11500 {
11501 	long new_value;
11502 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11503 
11504 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11505 	    new_value < tcppa->tcp_param_min ||
11506 	    new_value > tcppa->tcp_param_max) {
11507 		return (EINVAL);
11508 	}
11509 	/*
11510 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11511 	 * round it up.  For future 64 bit requirement, we actually make it
11512 	 * a multiple of 8.
11513 	 */
11514 	if (new_value & 0x7) {
11515 		new_value = (new_value & ~0x7) + 0x8;
11516 	}
11517 	tcppa->tcp_param_val = new_value;
11518 	return (0);
11519 }
11520 
11521 /* Set callback routine passed to nd_load by tcp_param_register */
11522 /* ARGSUSED */
11523 static int
11524 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11525 {
11526 	long	new_value;
11527 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11528 
11529 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11530 	    new_value < tcppa->tcp_param_min ||
11531 	    new_value > tcppa->tcp_param_max) {
11532 		return (EINVAL);
11533 	}
11534 	tcppa->tcp_param_val = new_value;
11535 	return (0);
11536 }
11537 
11538 /*
11539  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11540  * is filled, return as much as we can.  The message passed in may be
11541  * multi-part, chained using b_cont.  "start" is the starting sequence
11542  * number for this piece.
11543  */
11544 static mblk_t *
11545 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11546 {
11547 	uint32_t	end;
11548 	mblk_t		*mp1;
11549 	mblk_t		*mp2;
11550 	mblk_t		*next_mp;
11551 	uint32_t	u1;
11552 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11553 
11554 	/* Walk through all the new pieces. */
11555 	do {
11556 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11557 		    (uintptr_t)INT_MAX);
11558 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11559 		next_mp = mp->b_cont;
11560 		if (start == end) {
11561 			/* Empty.  Blast it. */
11562 			freeb(mp);
11563 			continue;
11564 		}
11565 		mp->b_cont = NULL;
11566 		TCP_REASS_SET_SEQ(mp, start);
11567 		TCP_REASS_SET_END(mp, end);
11568 		mp1 = tcp->tcp_reass_tail;
11569 		if (!mp1) {
11570 			tcp->tcp_reass_tail = mp;
11571 			tcp->tcp_reass_head = mp;
11572 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11573 			UPDATE_MIB(&tcps->tcps_mib,
11574 			    tcpInDataUnorderBytes, end - start);
11575 			continue;
11576 		}
11577 		/* New stuff completely beyond tail? */
11578 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11579 			/* Link it on end. */
11580 			mp1->b_cont = mp;
11581 			tcp->tcp_reass_tail = mp;
11582 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11583 			UPDATE_MIB(&tcps->tcps_mib,
11584 			    tcpInDataUnorderBytes, end - start);
11585 			continue;
11586 		}
11587 		mp1 = tcp->tcp_reass_head;
11588 		u1 = TCP_REASS_SEQ(mp1);
11589 		/* New stuff at the front? */
11590 		if (SEQ_LT(start, u1)) {
11591 			/* Yes... Check for overlap. */
11592 			mp->b_cont = mp1;
11593 			tcp->tcp_reass_head = mp;
11594 			tcp_reass_elim_overlap(tcp, mp);
11595 			continue;
11596 		}
11597 		/*
11598 		 * The new piece fits somewhere between the head and tail.
11599 		 * We find our slot, where mp1 precedes us and mp2 trails.
11600 		 */
11601 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11602 			u1 = TCP_REASS_SEQ(mp2);
11603 			if (SEQ_LEQ(start, u1))
11604 				break;
11605 		}
11606 		/* Link ourselves in */
11607 		mp->b_cont = mp2;
11608 		mp1->b_cont = mp;
11609 
11610 		/* Trim overlap with following mblk(s) first */
11611 		tcp_reass_elim_overlap(tcp, mp);
11612 
11613 		/* Trim overlap with preceding mblk */
11614 		tcp_reass_elim_overlap(tcp, mp1);
11615 
11616 	} while (start = end, mp = next_mp);
11617 	mp1 = tcp->tcp_reass_head;
11618 	/* Anything ready to go? */
11619 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11620 		return (NULL);
11621 	/* Eat what we can off the queue */
11622 	for (;;) {
11623 		mp = mp1->b_cont;
11624 		end = TCP_REASS_END(mp1);
11625 		TCP_REASS_SET_SEQ(mp1, 0);
11626 		TCP_REASS_SET_END(mp1, 0);
11627 		if (!mp) {
11628 			tcp->tcp_reass_tail = NULL;
11629 			break;
11630 		}
11631 		if (end != TCP_REASS_SEQ(mp)) {
11632 			mp1->b_cont = NULL;
11633 			break;
11634 		}
11635 		mp1 = mp;
11636 	}
11637 	mp1 = tcp->tcp_reass_head;
11638 	tcp->tcp_reass_head = mp;
11639 	return (mp1);
11640 }
11641 
11642 /* Eliminate any overlap that mp may have over later mblks */
11643 static void
11644 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11645 {
11646 	uint32_t	end;
11647 	mblk_t		*mp1;
11648 	uint32_t	u1;
11649 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11650 
11651 	end = TCP_REASS_END(mp);
11652 	while ((mp1 = mp->b_cont) != NULL) {
11653 		u1 = TCP_REASS_SEQ(mp1);
11654 		if (!SEQ_GT(end, u1))
11655 			break;
11656 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11657 			mp->b_wptr -= end - u1;
11658 			TCP_REASS_SET_END(mp, u1);
11659 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11660 			UPDATE_MIB(&tcps->tcps_mib,
11661 			    tcpInDataPartDupBytes, end - u1);
11662 			break;
11663 		}
11664 		mp->b_cont = mp1->b_cont;
11665 		TCP_REASS_SET_SEQ(mp1, 0);
11666 		TCP_REASS_SET_END(mp1, 0);
11667 		freeb(mp1);
11668 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11669 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11670 	}
11671 	if (!mp1)
11672 		tcp->tcp_reass_tail = mp;
11673 }
11674 
11675 /*
11676  * Send up all messages queued on tcp_rcv_list.
11677  */
11678 static uint_t
11679 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11680 {
11681 	mblk_t *mp;
11682 	uint_t ret = 0;
11683 	uint_t thwin;
11684 #ifdef DEBUG
11685 	uint_t cnt = 0;
11686 #endif
11687 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11688 
11689 	/* Can't drain on an eager connection */
11690 	if (tcp->tcp_listener != NULL)
11691 		return (ret);
11692 
11693 	/* Can't be sodirect enabled */
11694 	ASSERT(SOD_NOT_ENABLED(tcp));
11695 
11696 	/* No need for the push timer now. */
11697 	if (tcp->tcp_push_tid != 0) {
11698 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11699 		tcp->tcp_push_tid = 0;
11700 	}
11701 
11702 	/*
11703 	 * Handle two cases here: we are currently fused or we were
11704 	 * previously fused and have some urgent data to be delivered
11705 	 * upstream.  The latter happens because we either ran out of
11706 	 * memory or were detached and therefore sending the SIGURG was
11707 	 * deferred until this point.  In either case we pass control
11708 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11709 	 * some work.
11710 	 */
11711 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11712 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11713 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11714 		    &tcp->tcp_fused_sigurg_mp))
11715 			return (ret);
11716 	}
11717 
11718 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11719 		tcp->tcp_rcv_list = mp->b_next;
11720 		mp->b_next = NULL;
11721 #ifdef DEBUG
11722 		cnt += msgdsize(mp);
11723 #endif
11724 		/* Does this need SSL processing first? */
11725 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11726 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11727 			    mblk_t *, mp);
11728 			tcp_kssl_input(tcp, mp);
11729 			continue;
11730 		}
11731 		putnext(q, mp);
11732 	}
11733 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11734 	tcp->tcp_rcv_last_head = NULL;
11735 	tcp->tcp_rcv_last_tail = NULL;
11736 	tcp->tcp_rcv_cnt = 0;
11737 
11738 	/* Learn the latest rwnd information that we sent to the other side. */
11739 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11740 	    << tcp->tcp_rcv_ws;
11741 	/* This is peer's calculated send window (our receive window). */
11742 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11743 	/*
11744 	 * Increase the receive window to max.  But we need to do receiver
11745 	 * SWS avoidance.  This means that we need to check the increase of
11746 	 * of receive window is at least 1 MSS.
11747 	 */
11748 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11749 		/*
11750 		 * If the window that the other side knows is less than max
11751 		 * deferred acks segments, send an update immediately.
11752 		 */
11753 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11754 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11755 			ret = TH_ACK_NEEDED;
11756 		}
11757 		tcp->tcp_rwnd = q->q_hiwat;
11758 	}
11759 	return (ret);
11760 }
11761 
11762 /*
11763  * Queue data on tcp_rcv_list which is a b_next chain.
11764  * tcp_rcv_last_head/tail is the last element of this chain.
11765  * Each element of the chain is a b_cont chain.
11766  *
11767  * M_DATA messages are added to the current element.
11768  * Other messages are added as new (b_next) elements.
11769  */
11770 void
11771 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11772 {
11773 	ASSERT(seg_len == msgdsize(mp));
11774 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11775 
11776 	if (tcp->tcp_rcv_list == NULL) {
11777 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11778 		tcp->tcp_rcv_list = mp;
11779 		tcp->tcp_rcv_last_head = mp;
11780 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11781 		tcp->tcp_rcv_last_tail->b_cont = mp;
11782 	} else {
11783 		tcp->tcp_rcv_last_head->b_next = mp;
11784 		tcp->tcp_rcv_last_head = mp;
11785 	}
11786 
11787 	while (mp->b_cont)
11788 		mp = mp->b_cont;
11789 
11790 	tcp->tcp_rcv_last_tail = mp;
11791 	tcp->tcp_rcv_cnt += seg_len;
11792 	tcp->tcp_rwnd -= seg_len;
11793 }
11794 
11795 /*
11796  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11797  * above, in addition when uioa is enabled schedule an asynchronous uio
11798  * prior to enqueuing. They implement the combinhed semantics of the
11799  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11800  * canputnext(), i.e. flow-control with backenable.
11801  *
11802  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11803  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11804  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11805  *
11806  * Must be called with sodp->sod_lockp held and will return with the lock
11807  * released.
11808  */
11809 static uint_t
11810 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11811 {
11812 	queue_t		*q = tcp->tcp_rq;
11813 	uint_t		thwin;
11814 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11815 	uint_t		ret = 0;
11816 
11817 	/* Can't be an eager connection */
11818 	ASSERT(tcp->tcp_listener == NULL);
11819 
11820 	/* Caller must have lock held */
11821 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11822 
11823 	/* Sodirect mode so must not be a tcp_rcv_list */
11824 	ASSERT(tcp->tcp_rcv_list == NULL);
11825 
11826 	if (SOD_QFULL(sodp)) {
11827 		/* Q is full, mark Q for need backenable */
11828 		SOD_QSETBE(sodp);
11829 	}
11830 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11831 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11832 	    << tcp->tcp_rcv_ws;
11833 	/* This is peer's calculated send window (our available rwnd). */
11834 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11835 	/*
11836 	 * Increase the receive window to max.  But we need to do receiver
11837 	 * SWS avoidance.  This means that we need to check the increase of
11838 	 * of receive window is at least 1 MSS.
11839 	 */
11840 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11841 		/*
11842 		 * If the window that the other side knows is less than max
11843 		 * deferred acks segments, send an update immediately.
11844 		 */
11845 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11846 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11847 			ret = TH_ACK_NEEDED;
11848 		}
11849 		tcp->tcp_rwnd = q->q_hiwat;
11850 	}
11851 
11852 	if (!SOD_QEMPTY(sodp)) {
11853 		/* Wakeup to socket */
11854 		sodp->sod_state &= SOD_WAKE_CLR;
11855 		sodp->sod_state |= SOD_WAKE_DONE;
11856 		(sodp->sod_wakeup)(sodp);
11857 		/* wakeup() does the mutex_ext() */
11858 	} else {
11859 		/* Q is empty, no need to wake */
11860 		sodp->sod_state &= SOD_WAKE_CLR;
11861 		sodp->sod_state |= SOD_WAKE_NOT;
11862 		mutex_exit(sodp->sod_lockp);
11863 	}
11864 
11865 	/* No need for the push timer now. */
11866 	if (tcp->tcp_push_tid != 0) {
11867 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11868 		tcp->tcp_push_tid = 0;
11869 	}
11870 
11871 	return (ret);
11872 }
11873 
11874 /*
11875  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11876  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11877  * to the user-land buffer and flag the mblk_t as such.
11878  *
11879  * Also, handle tcp_rwnd.
11880  */
11881 uint_t
11882 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11883 {
11884 	uioa_t		*uioap = &sodp->sod_uioa;
11885 	boolean_t	qfull;
11886 	uint_t		thwin;
11887 
11888 	/* Can't be an eager connection */
11889 	ASSERT(tcp->tcp_listener == NULL);
11890 
11891 	/* Caller must have lock held */
11892 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11893 
11894 	/* Sodirect mode so must not be a tcp_rcv_list */
11895 	ASSERT(tcp->tcp_rcv_list == NULL);
11896 
11897 	/* Passed in segment length must be equal to mblk_t chain data size */
11898 	ASSERT(seg_len == msgdsize(mp));
11899 
11900 	if (DB_TYPE(mp) != M_DATA) {
11901 		/* Only process M_DATA mblk_t's */
11902 		goto enq;
11903 	}
11904 	if (uioap->uioa_state & UIOA_ENABLED) {
11905 		/* Uioa is enabled */
11906 		mblk_t		*mp1 = mp;
11907 		mblk_t		*lmp = NULL;
11908 
11909 		if (seg_len > uioap->uio_resid) {
11910 			/*
11911 			 * There isn't enough uio space for the mblk_t chain
11912 			 * so disable uioa such that this and any additional
11913 			 * mblk_t data is handled by the socket and schedule
11914 			 * the socket for wakeup to finish this uioa.
11915 			 */
11916 			uioap->uioa_state &= UIOA_CLR;
11917 			uioap->uioa_state |= UIOA_FINI;
11918 			if (sodp->sod_state & SOD_WAKE_NOT) {
11919 				sodp->sod_state &= SOD_WAKE_CLR;
11920 				sodp->sod_state |= SOD_WAKE_NEED;
11921 			}
11922 			goto enq;
11923 		}
11924 		do {
11925 			uint32_t	len = MBLKL(mp1);
11926 
11927 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11928 				/* Scheduled, mark dblk_t as such */
11929 				DB_FLAGS(mp1) |= DBLK_UIOA;
11930 			} else {
11931 				/* Error, turn off async processing */
11932 				uioap->uioa_state &= UIOA_CLR;
11933 				uioap->uioa_state |= UIOA_FINI;
11934 				break;
11935 			}
11936 			lmp = mp1;
11937 		} while ((mp1 = mp1->b_cont) != NULL);
11938 
11939 		if (mp1 != NULL || uioap->uio_resid == 0) {
11940 			/*
11941 			 * Not all mblk_t(s) uioamoved (error) or all uio
11942 			 * space has been consumed so schedule the socket
11943 			 * for wakeup to finish this uio.
11944 			 */
11945 			sodp->sod_state &= SOD_WAKE_CLR;
11946 			sodp->sod_state |= SOD_WAKE_NEED;
11947 
11948 			/* Break the mblk chain if neccessary. */
11949 			if (mp1 != NULL && lmp != NULL) {
11950 				mp->b_next = mp1;
11951 				lmp->b_cont = NULL;
11952 			}
11953 		}
11954 	} else if (uioap->uioa_state & UIOA_FINI) {
11955 		/*
11956 		 * Post UIO_ENABLED waiting for socket to finish processing
11957 		 * so just enqueue and update tcp_rwnd.
11958 		 */
11959 		if (SOD_QFULL(sodp))
11960 			tcp->tcp_rwnd -= seg_len;
11961 	} else if (sodp->sod_want > 0) {
11962 		/*
11963 		 * Uioa isn't enabled but sodirect has a pending read().
11964 		 */
11965 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11966 			if (sodp->sod_state & SOD_WAKE_NOT) {
11967 				/* Schedule socket for wakeup */
11968 				sodp->sod_state &= SOD_WAKE_CLR;
11969 				sodp->sod_state |= SOD_WAKE_NEED;
11970 			}
11971 			tcp->tcp_rwnd -= seg_len;
11972 		}
11973 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11974 		/*
11975 		 * No pending sodirect read() so used the default
11976 		 * TCP push logic to guess that a push is needed.
11977 		 */
11978 		if (sodp->sod_state & SOD_WAKE_NOT) {
11979 			/* Schedule socket for wakeup */
11980 			sodp->sod_state &= SOD_WAKE_CLR;
11981 			sodp->sod_state |= SOD_WAKE_NEED;
11982 		}
11983 		tcp->tcp_rwnd -= seg_len;
11984 	} else {
11985 		/* Just update tcp_rwnd */
11986 		tcp->tcp_rwnd -= seg_len;
11987 	}
11988 enq:
11989 	qfull = SOD_QFULL(sodp);
11990 
11991 	(sodp->sod_enqueue)(sodp, mp);
11992 
11993 	if (! qfull && SOD_QFULL(sodp)) {
11994 		/* Wasn't QFULL, now QFULL, need back-enable */
11995 		SOD_QSETBE(sodp);
11996 	}
11997 
11998 	/*
11999 	 * Check to see if remote avail swnd < mss due to delayed ACK,
12000 	 * first get advertised rwnd.
12001 	 */
12002 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
12003 	/* Minus delayed ACK count */
12004 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
12005 	if (thwin < tcp->tcp_mss) {
12006 		/* Remote avail swnd < mss, need ACK now */
12007 		return (TH_ACK_NEEDED);
12008 	}
12009 
12010 	return (0);
12011 }
12012 
12013 /*
12014  * DEFAULT TCP ENTRY POINT via squeue on READ side.
12015  *
12016  * This is the default entry function into TCP on the read side. TCP is
12017  * always entered via squeue i.e. using squeue's for mutual exclusion.
12018  * When classifier does a lookup to find the tcp, it also puts a reference
12019  * on the conn structure associated so the tcp is guaranteed to exist
12020  * when we come here. We still need to check the state because it might
12021  * as well has been closed. The squeue processing function i.e. squeue_enter,
12022  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
12023  * CONN_DEC_REF.
12024  *
12025  * Apart from the default entry point, IP also sends packets directly to
12026  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
12027  * connections.
12028  */
12029 void
12030 tcp_input(void *arg, mblk_t *mp, void *arg2)
12031 {
12032 	conn_t	*connp = (conn_t *)arg;
12033 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
12034 
12035 	/* arg2 is the sqp */
12036 	ASSERT(arg2 != NULL);
12037 	ASSERT(mp != NULL);
12038 
12039 	/*
12040 	 * Don't accept any input on a closed tcp as this TCP logically does
12041 	 * not exist on the system. Don't proceed further with this TCP.
12042 	 * For eg. this packet could trigger another close of this tcp
12043 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
12044 	 * tcp_clean_death / tcp_closei_local must be called at most once
12045 	 * on a TCP. In this case we need to refeed the packet into the
12046 	 * classifier and figure out where the packet should go. Need to
12047 	 * preserve the recv_ill somehow. Until we figure that out, for
12048 	 * now just drop the packet if we can't classify the packet.
12049 	 */
12050 	if (tcp->tcp_state == TCPS_CLOSED ||
12051 	    tcp->tcp_state == TCPS_BOUND) {
12052 		conn_t	*new_connp;
12053 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
12054 
12055 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
12056 		if (new_connp != NULL) {
12057 			tcp_reinput(new_connp, mp, arg2);
12058 			return;
12059 		}
12060 		/* We failed to classify. For now just drop the packet */
12061 		freemsg(mp);
12062 		return;
12063 	}
12064 
12065 	if (DB_TYPE(mp) == M_DATA)
12066 		tcp_rput_data(connp, mp, arg2);
12067 	else
12068 		tcp_rput_common(tcp, mp);
12069 }
12070 
12071 /*
12072  * The read side put procedure.
12073  * The packets passed up by ip are assume to be aligned according to
12074  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
12075  */
12076 static void
12077 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
12078 {
12079 	/*
12080 	 * tcp_rput_data() does not expect M_CTL except for the case
12081 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
12082 	 * type. Need to make sure that any other M_CTLs don't make
12083 	 * it to tcp_rput_data since it is not expecting any and doesn't
12084 	 * check for it.
12085 	 */
12086 	if (DB_TYPE(mp) == M_CTL) {
12087 		switch (*(uint32_t *)(mp->b_rptr)) {
12088 		case TCP_IOC_ABORT_CONN:
12089 			/*
12090 			 * Handle connection abort request.
12091 			 */
12092 			tcp_ioctl_abort_handler(tcp, mp);
12093 			return;
12094 		case IPSEC_IN:
12095 			/*
12096 			 * Only secure icmp arrive in TCP and they
12097 			 * don't go through data path.
12098 			 */
12099 			tcp_icmp_error(tcp, mp);
12100 			return;
12101 		case IN_PKTINFO:
12102 			/*
12103 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
12104 			 * sockets that are receiving IPv4 traffic. tcp
12105 			 */
12106 			ASSERT(tcp->tcp_family == AF_INET6);
12107 			ASSERT(tcp->tcp_ipv6_recvancillary &
12108 			    TCP_IPV6_RECVPKTINFO);
12109 			tcp_rput_data(tcp->tcp_connp, mp,
12110 			    tcp->tcp_connp->conn_sqp);
12111 			return;
12112 		case MDT_IOC_INFO_UPDATE:
12113 			/*
12114 			 * Handle Multidata information update; the
12115 			 * following routine will free the message.
12116 			 */
12117 			if (tcp->tcp_connp->conn_mdt_ok) {
12118 				tcp_mdt_update(tcp,
12119 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
12120 				    B_FALSE);
12121 			}
12122 			freemsg(mp);
12123 			return;
12124 		case LSO_IOC_INFO_UPDATE:
12125 			/*
12126 			 * Handle LSO information update; the following
12127 			 * routine will free the message.
12128 			 */
12129 			if (tcp->tcp_connp->conn_lso_ok) {
12130 				tcp_lso_update(tcp,
12131 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
12132 			}
12133 			freemsg(mp);
12134 			return;
12135 		default:
12136 			/*
12137 			 * tcp_icmp_err() will process the M_CTL packets.
12138 			 * Non-ICMP packets, if any, will be discarded in
12139 			 * tcp_icmp_err(). We will process the ICMP packet
12140 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
12141 			 * incoming ICMP packet may result in changing
12142 			 * the tcp_mss, which we would need if we have
12143 			 * packets to retransmit.
12144 			 */
12145 			tcp_icmp_error(tcp, mp);
12146 			return;
12147 		}
12148 	}
12149 
12150 	/* No point processing the message if tcp is already closed */
12151 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
12152 		freemsg(mp);
12153 		return;
12154 	}
12155 
12156 	tcp_rput_other(tcp, mp);
12157 }
12158 
12159 
12160 /* The minimum of smoothed mean deviation in RTO calculation. */
12161 #define	TCP_SD_MIN	400
12162 
12163 /*
12164  * Set RTO for this connection.  The formula is from Jacobson and Karels'
12165  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
12166  * are the same as those in Appendix A.2 of that paper.
12167  *
12168  * m = new measurement
12169  * sa = smoothed RTT average (8 * average estimates).
12170  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
12171  */
12172 static void
12173 tcp_set_rto(tcp_t *tcp, clock_t rtt)
12174 {
12175 	long m = TICK_TO_MSEC(rtt);
12176 	clock_t sa = tcp->tcp_rtt_sa;
12177 	clock_t sv = tcp->tcp_rtt_sd;
12178 	clock_t rto;
12179 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12180 
12181 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
12182 	tcp->tcp_rtt_update++;
12183 
12184 	/* tcp_rtt_sa is not 0 means this is a new sample. */
12185 	if (sa != 0) {
12186 		/*
12187 		 * Update average estimator:
12188 		 *	new rtt = 7/8 old rtt + 1/8 Error
12189 		 */
12190 
12191 		/* m is now Error in estimate. */
12192 		m -= sa >> 3;
12193 		if ((sa += m) <= 0) {
12194 			/*
12195 			 * Don't allow the smoothed average to be negative.
12196 			 * We use 0 to denote reinitialization of the
12197 			 * variables.
12198 			 */
12199 			sa = 1;
12200 		}
12201 
12202 		/*
12203 		 * Update deviation estimator:
12204 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
12205 		 */
12206 		if (m < 0)
12207 			m = -m;
12208 		m -= sv >> 2;
12209 		sv += m;
12210 	} else {
12211 		/*
12212 		 * This follows BSD's implementation.  So the reinitialized
12213 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12214 		 * link is bandwidth dominated, doubling the window size
12215 		 * during slow start means doubling the RTT.  We want to be
12216 		 * more conservative when we reinitialize our estimates.  3
12217 		 * is just a convenient number.
12218 		 */
12219 		sa = m << 3;
12220 		sv = m << 1;
12221 	}
12222 	if (sv < TCP_SD_MIN) {
12223 		/*
12224 		 * We do not know that if sa captures the delay ACK
12225 		 * effect as in a long train of segments, a receiver
12226 		 * does not delay its ACKs.  So set the minimum of sv
12227 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12228 		 * of BSD DATO.  That means the minimum of mean
12229 		 * deviation is 100 ms.
12230 		 *
12231 		 */
12232 		sv = TCP_SD_MIN;
12233 	}
12234 	tcp->tcp_rtt_sa = sa;
12235 	tcp->tcp_rtt_sd = sv;
12236 	/*
12237 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12238 	 *
12239 	 * Add tcp_rexmit_interval extra in case of extreme environment
12240 	 * where the algorithm fails to work.  The default value of
12241 	 * tcp_rexmit_interval_extra should be 0.
12242 	 *
12243 	 * As we use a finer grained clock than BSD and update
12244 	 * RTO for every ACKs, add in another .25 of RTT to the
12245 	 * deviation of RTO to accomodate burstiness of 1/4 of
12246 	 * window size.
12247 	 */
12248 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12249 
12250 	if (rto > tcps->tcps_rexmit_interval_max) {
12251 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12252 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12253 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12254 	} else {
12255 		tcp->tcp_rto = rto;
12256 	}
12257 
12258 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12259 	tcp->tcp_timer_backoff = 0;
12260 }
12261 
12262 /*
12263  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12264  * send queue which starts at the given seq. no.
12265  *
12266  * Parameters:
12267  *	tcp_t *tcp: the tcp instance pointer.
12268  *	uint32_t seq: the starting seq. no of the requested segment.
12269  *	int32_t *off: after the execution, *off will be the offset to
12270  *		the returned mblk which points to the requested seq no.
12271  *		It is the caller's responsibility to send in a non-null off.
12272  *
12273  * Return:
12274  *	A mblk_t pointer pointing to the requested segment in send queue.
12275  */
12276 static mblk_t *
12277 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12278 {
12279 	int32_t	cnt;
12280 	mblk_t	*mp;
12281 
12282 	/* Defensive coding.  Make sure we don't send incorrect data. */
12283 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12284 		return (NULL);
12285 
12286 	cnt = seq - tcp->tcp_suna;
12287 	mp = tcp->tcp_xmit_head;
12288 	while (cnt > 0 && mp != NULL) {
12289 		cnt -= mp->b_wptr - mp->b_rptr;
12290 		if (cnt < 0) {
12291 			cnt += mp->b_wptr - mp->b_rptr;
12292 			break;
12293 		}
12294 		mp = mp->b_cont;
12295 	}
12296 	ASSERT(mp != NULL);
12297 	*off = cnt;
12298 	return (mp);
12299 }
12300 
12301 /*
12302  * This function handles all retransmissions if SACK is enabled for this
12303  * connection.  First it calculates how many segments can be retransmitted
12304  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12305  * segments.  A segment is eligible if sack_cnt for that segment is greater
12306  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12307  * all eligible segments, it checks to see if TCP can send some new segments
12308  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12309  *
12310  * Parameters:
12311  *	tcp_t *tcp: the tcp structure of the connection.
12312  *	uint_t *flags: in return, appropriate value will be set for
12313  *	tcp_rput_data().
12314  */
12315 static void
12316 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12317 {
12318 	notsack_blk_t	*notsack_blk;
12319 	int32_t		usable_swnd;
12320 	int32_t		mss;
12321 	uint32_t	seg_len;
12322 	mblk_t		*xmit_mp;
12323 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12324 
12325 	ASSERT(tcp->tcp_sack_info != NULL);
12326 	ASSERT(tcp->tcp_notsack_list != NULL);
12327 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12328 
12329 	/* Defensive coding in case there is a bug... */
12330 	if (tcp->tcp_notsack_list == NULL) {
12331 		return;
12332 	}
12333 	notsack_blk = tcp->tcp_notsack_list;
12334 	mss = tcp->tcp_mss;
12335 
12336 	/*
12337 	 * Limit the num of outstanding data in the network to be
12338 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12339 	 */
12340 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12341 
12342 	/* At least retransmit 1 MSS of data. */
12343 	if (usable_swnd <= 0) {
12344 		usable_swnd = mss;
12345 	}
12346 
12347 	/* Make sure no new RTT samples will be taken. */
12348 	tcp->tcp_csuna = tcp->tcp_snxt;
12349 
12350 	notsack_blk = tcp->tcp_notsack_list;
12351 	while (usable_swnd > 0) {
12352 		mblk_t		*snxt_mp, *tmp_mp;
12353 		tcp_seq		begin = tcp->tcp_sack_snxt;
12354 		tcp_seq		end;
12355 		int32_t		off;
12356 
12357 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12358 			if (SEQ_GT(notsack_blk->end, begin) &&
12359 			    (notsack_blk->sack_cnt >=
12360 			    tcps->tcps_dupack_fast_retransmit)) {
12361 				end = notsack_blk->end;
12362 				if (SEQ_LT(begin, notsack_blk->begin)) {
12363 					begin = notsack_blk->begin;
12364 				}
12365 				break;
12366 			}
12367 		}
12368 		/*
12369 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12370 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12371 		 * set to tcp_cwnd_ssthresh.
12372 		 */
12373 		if (notsack_blk == NULL) {
12374 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12375 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12376 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12377 				ASSERT(tcp->tcp_cwnd > 0);
12378 				return;
12379 			} else {
12380 				usable_swnd = usable_swnd / mss;
12381 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12382 				    MAX(usable_swnd * mss, mss);
12383 				*flags |= TH_XMIT_NEEDED;
12384 				return;
12385 			}
12386 		}
12387 
12388 		/*
12389 		 * Note that we may send more than usable_swnd allows here
12390 		 * because of round off, but no more than 1 MSS of data.
12391 		 */
12392 		seg_len = end - begin;
12393 		if (seg_len > mss)
12394 			seg_len = mss;
12395 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12396 		ASSERT(snxt_mp != NULL);
12397 		/* This should not happen.  Defensive coding again... */
12398 		if (snxt_mp == NULL) {
12399 			return;
12400 		}
12401 
12402 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12403 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12404 		if (xmit_mp == NULL)
12405 			return;
12406 
12407 		usable_swnd -= seg_len;
12408 		tcp->tcp_pipe += seg_len;
12409 		tcp->tcp_sack_snxt = begin + seg_len;
12410 
12411 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12412 
12413 		/*
12414 		 * Update the send timestamp to avoid false retransmission.
12415 		 */
12416 		snxt_mp->b_prev = (mblk_t *)lbolt;
12417 
12418 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12419 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12420 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12421 		/*
12422 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12423 		 * This happens when new data sent during fast recovery is
12424 		 * also lost.  If TCP retransmits those new data, it needs
12425 		 * to extend SACK recover phase to avoid starting another
12426 		 * fast retransmit/recovery unnecessarily.
12427 		 */
12428 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12429 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12430 		}
12431 	}
12432 }
12433 
12434 /*
12435  * This function handles policy checking at TCP level for non-hard_bound/
12436  * detached connections.
12437  */
12438 static boolean_t
12439 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12440     boolean_t secure, boolean_t mctl_present)
12441 {
12442 	ipsec_latch_t *ipl = NULL;
12443 	ipsec_action_t *act = NULL;
12444 	mblk_t *data_mp;
12445 	ipsec_in_t *ii;
12446 	const char *reason;
12447 	kstat_named_t *counter;
12448 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12449 	ipsec_stack_t	*ipss;
12450 	ip_stack_t	*ipst;
12451 
12452 	ASSERT(mctl_present || !secure);
12453 
12454 	ASSERT((ipha == NULL && ip6h != NULL) ||
12455 	    (ip6h == NULL && ipha != NULL));
12456 
12457 	/*
12458 	 * We don't necessarily have an ipsec_in_act action to verify
12459 	 * policy because of assymetrical policy where we have only
12460 	 * outbound policy and no inbound policy (possible with global
12461 	 * policy).
12462 	 */
12463 	if (!secure) {
12464 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12465 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12466 			return (B_TRUE);
12467 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12468 		    "tcp_check_policy", ipha, ip6h, secure,
12469 		    tcps->tcps_netstack);
12470 		ipss = tcps->tcps_netstack->netstack_ipsec;
12471 
12472 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12473 		    DROPPER(ipss, ipds_tcp_clear),
12474 		    &tcps->tcps_dropper);
12475 		return (B_FALSE);
12476 	}
12477 
12478 	/*
12479 	 * We have a secure packet.
12480 	 */
12481 	if (act == NULL) {
12482 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12483 		    "tcp_check_policy", ipha, ip6h, secure,
12484 		    tcps->tcps_netstack);
12485 		ipss = tcps->tcps_netstack->netstack_ipsec;
12486 
12487 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12488 		    DROPPER(ipss, ipds_tcp_secure),
12489 		    &tcps->tcps_dropper);
12490 		return (B_FALSE);
12491 	}
12492 
12493 	/*
12494 	 * XXX This whole routine is currently incorrect.  ipl should
12495 	 * be set to the latch pointer, but is currently not set, so
12496 	 * we initialize it to NULL to avoid picking up random garbage.
12497 	 */
12498 	if (ipl == NULL)
12499 		return (B_TRUE);
12500 
12501 	data_mp = first_mp->b_cont;
12502 
12503 	ii = (ipsec_in_t *)first_mp->b_rptr;
12504 
12505 	ipst = tcps->tcps_netstack->netstack_ip;
12506 
12507 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12508 	    &counter, tcp->tcp_connp)) {
12509 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12510 		return (B_TRUE);
12511 	}
12512 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12513 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12514 	    reason);
12515 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12516 
12517 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12518 	    &tcps->tcps_dropper);
12519 	return (B_FALSE);
12520 }
12521 
12522 /*
12523  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12524  * retransmission after a timeout.
12525  *
12526  * To limit the number of duplicate segments, we limit the number of segment
12527  * to be sent in one time to tcp_snd_burst, the burst variable.
12528  */
12529 static void
12530 tcp_ss_rexmit(tcp_t *tcp)
12531 {
12532 	uint32_t	snxt;
12533 	uint32_t	smax;
12534 	int32_t		win;
12535 	int32_t		mss;
12536 	int32_t		off;
12537 	int32_t		burst = tcp->tcp_snd_burst;
12538 	mblk_t		*snxt_mp;
12539 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12540 
12541 	/*
12542 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12543 	 * all unack'ed segments.
12544 	 */
12545 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12546 		smax = tcp->tcp_rexmit_max;
12547 		snxt = tcp->tcp_rexmit_nxt;
12548 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12549 			snxt = tcp->tcp_suna;
12550 		}
12551 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12552 		win -= snxt - tcp->tcp_suna;
12553 		mss = tcp->tcp_mss;
12554 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12555 
12556 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12557 		    (burst > 0) && (snxt_mp != NULL)) {
12558 			mblk_t	*xmit_mp;
12559 			mblk_t	*old_snxt_mp = snxt_mp;
12560 			uint32_t cnt = mss;
12561 
12562 			if (win < cnt) {
12563 				cnt = win;
12564 			}
12565 			if (SEQ_GT(snxt + cnt, smax)) {
12566 				cnt = smax - snxt;
12567 			}
12568 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12569 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12570 			if (xmit_mp == NULL)
12571 				return;
12572 
12573 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12574 
12575 			snxt += cnt;
12576 			win -= cnt;
12577 			/*
12578 			 * Update the send timestamp to avoid false
12579 			 * retransmission.
12580 			 */
12581 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12582 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12583 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12584 
12585 			tcp->tcp_rexmit_nxt = snxt;
12586 			burst--;
12587 		}
12588 		/*
12589 		 * If we have transmitted all we have at the time
12590 		 * we started the retranmission, we can leave
12591 		 * the rest of the job to tcp_wput_data().  But we
12592 		 * need to check the send window first.  If the
12593 		 * win is not 0, go on with tcp_wput_data().
12594 		 */
12595 		if (SEQ_LT(snxt, smax) || win == 0) {
12596 			return;
12597 		}
12598 	}
12599 	/* Only call tcp_wput_data() if there is data to be sent. */
12600 	if (tcp->tcp_unsent) {
12601 		tcp_wput_data(tcp, NULL, B_FALSE);
12602 	}
12603 }
12604 
12605 /*
12606  * Process all TCP option in SYN segment.  Note that this function should
12607  * be called after tcp_adapt_ire() is called so that the necessary info
12608  * from IRE is already set in the tcp structure.
12609  *
12610  * This function sets up the correct tcp_mss value according to the
12611  * MSS option value and our header size.  It also sets up the window scale
12612  * and timestamp values, and initialize SACK info blocks.  But it does not
12613  * change receive window size after setting the tcp_mss value.  The caller
12614  * should do the appropriate change.
12615  */
12616 void
12617 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12618 {
12619 	int options;
12620 	tcp_opt_t tcpopt;
12621 	uint32_t mss_max;
12622 	char *tmp_tcph;
12623 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12624 
12625 	tcpopt.tcp = NULL;
12626 	options = tcp_parse_options(tcph, &tcpopt);
12627 
12628 	/*
12629 	 * Process MSS option.  Note that MSS option value does not account
12630 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12631 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12632 	 * IPv6.
12633 	 */
12634 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12635 		if (tcp->tcp_ipversion == IPV4_VERSION)
12636 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12637 		else
12638 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12639 	} else {
12640 		if (tcp->tcp_ipversion == IPV4_VERSION)
12641 			mss_max = tcps->tcps_mss_max_ipv4;
12642 		else
12643 			mss_max = tcps->tcps_mss_max_ipv6;
12644 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12645 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12646 		else if (tcpopt.tcp_opt_mss > mss_max)
12647 			tcpopt.tcp_opt_mss = mss_max;
12648 	}
12649 
12650 	/* Process Window Scale option. */
12651 	if (options & TCP_OPT_WSCALE_PRESENT) {
12652 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12653 		tcp->tcp_snd_ws_ok = B_TRUE;
12654 	} else {
12655 		tcp->tcp_snd_ws = B_FALSE;
12656 		tcp->tcp_snd_ws_ok = B_FALSE;
12657 		tcp->tcp_rcv_ws = B_FALSE;
12658 	}
12659 
12660 	/* Process Timestamp option. */
12661 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12662 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12663 		tmp_tcph = (char *)tcp->tcp_tcph;
12664 
12665 		tcp->tcp_snd_ts_ok = B_TRUE;
12666 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12667 		tcp->tcp_last_rcv_lbolt = lbolt64;
12668 		ASSERT(OK_32PTR(tmp_tcph));
12669 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12670 
12671 		/* Fill in our template header with basic timestamp option. */
12672 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12673 		tmp_tcph[0] = TCPOPT_NOP;
12674 		tmp_tcph[1] = TCPOPT_NOP;
12675 		tmp_tcph[2] = TCPOPT_TSTAMP;
12676 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12677 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12678 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12679 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12680 	} else {
12681 		tcp->tcp_snd_ts_ok = B_FALSE;
12682 	}
12683 
12684 	/*
12685 	 * Process SACK options.  If SACK is enabled for this connection,
12686 	 * then allocate the SACK info structure.  Note the following ways
12687 	 * when tcp_snd_sack_ok is set to true.
12688 	 *
12689 	 * For active connection: in tcp_adapt_ire() called in
12690 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12691 	 * is checked.
12692 	 *
12693 	 * For passive connection: in tcp_adapt_ire() called in
12694 	 * tcp_accept_comm().
12695 	 *
12696 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12697 	 * That check makes sure that if we did not send a SACK OK option,
12698 	 * we will not enable SACK for this connection even though the other
12699 	 * side sends us SACK OK option.  For active connection, the SACK
12700 	 * info structure has already been allocated.  So we need to free
12701 	 * it if SACK is disabled.
12702 	 */
12703 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12704 	    (tcp->tcp_snd_sack_ok ||
12705 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12706 		/* This should be true only in the passive case. */
12707 		if (tcp->tcp_sack_info == NULL) {
12708 			ASSERT(TCP_IS_DETACHED(tcp));
12709 			tcp->tcp_sack_info =
12710 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12711 		}
12712 		if (tcp->tcp_sack_info == NULL) {
12713 			tcp->tcp_snd_sack_ok = B_FALSE;
12714 		} else {
12715 			tcp->tcp_snd_sack_ok = B_TRUE;
12716 			if (tcp->tcp_snd_ts_ok) {
12717 				tcp->tcp_max_sack_blk = 3;
12718 			} else {
12719 				tcp->tcp_max_sack_blk = 4;
12720 			}
12721 		}
12722 	} else {
12723 		/*
12724 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12725 		 * no SACK info will be used for this
12726 		 * connection.  This assumes that SACK usage
12727 		 * permission is negotiated.  This may need
12728 		 * to be changed once this is clarified.
12729 		 */
12730 		if (tcp->tcp_sack_info != NULL) {
12731 			ASSERT(tcp->tcp_notsack_list == NULL);
12732 			kmem_cache_free(tcp_sack_info_cache,
12733 			    tcp->tcp_sack_info);
12734 			tcp->tcp_sack_info = NULL;
12735 		}
12736 		tcp->tcp_snd_sack_ok = B_FALSE;
12737 	}
12738 
12739 	/*
12740 	 * Now we know the exact TCP/IP header length, subtract
12741 	 * that from tcp_mss to get our side's MSS.
12742 	 */
12743 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12744 	/*
12745 	 * Here we assume that the other side's header size will be equal to
12746 	 * our header size.  We calculate the real MSS accordingly.  Need to
12747 	 * take into additional stuffs IPsec puts in.
12748 	 *
12749 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12750 	 */
12751 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12752 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12753 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12754 
12755 	/*
12756 	 * Set MSS to the smaller one of both ends of the connection.
12757 	 * We should not have called tcp_mss_set() before, but our
12758 	 * side of the MSS should have been set to a proper value
12759 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12760 	 * STREAM head parameters properly.
12761 	 *
12762 	 * If we have a larger-than-16-bit window but the other side
12763 	 * didn't want to do window scale, tcp_rwnd_set() will take
12764 	 * care of that.
12765 	 */
12766 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12767 }
12768 
12769 /*
12770  * Sends the T_CONN_IND to the listener. The caller calls this
12771  * functions via squeue to get inside the listener's perimeter
12772  * once the 3 way hand shake is done a T_CONN_IND needs to be
12773  * sent. As an optimization, the caller can call this directly
12774  * if listener's perimeter is same as eager's.
12775  */
12776 /* ARGSUSED */
12777 void
12778 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12779 {
12780 	conn_t			*lconnp = (conn_t *)arg;
12781 	tcp_t			*listener = lconnp->conn_tcp;
12782 	tcp_t			*tcp;
12783 	struct T_conn_ind	*conn_ind;
12784 	ipaddr_t 		*addr_cache;
12785 	boolean_t		need_send_conn_ind = B_FALSE;
12786 	tcp_stack_t		*tcps = listener->tcp_tcps;
12787 
12788 	/* retrieve the eager */
12789 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12790 	ASSERT(conn_ind->OPT_offset != 0 &&
12791 	    conn_ind->OPT_length == sizeof (intptr_t));
12792 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12793 	    conn_ind->OPT_length);
12794 
12795 	/*
12796 	 * TLI/XTI applications will get confused by
12797 	 * sending eager as an option since it violates
12798 	 * the option semantics. So remove the eager as
12799 	 * option since TLI/XTI app doesn't need it anyway.
12800 	 */
12801 	if (!TCP_IS_SOCKET(listener)) {
12802 		conn_ind->OPT_length = 0;
12803 		conn_ind->OPT_offset = 0;
12804 	}
12805 	if (listener->tcp_state == TCPS_CLOSED ||
12806 	    TCP_IS_DETACHED(listener)) {
12807 		/*
12808 		 * If listener has closed, it would have caused a
12809 		 * a cleanup/blowoff to happen for the eager. We
12810 		 * just need to return.
12811 		 */
12812 		freemsg(mp);
12813 		return;
12814 	}
12815 
12816 
12817 	/*
12818 	 * if the conn_req_q is full defer passing up the
12819 	 * T_CONN_IND until space is availabe after t_accept()
12820 	 * processing
12821 	 */
12822 	mutex_enter(&listener->tcp_eager_lock);
12823 
12824 	/*
12825 	 * Take the eager out, if it is in the list of droppable eagers
12826 	 * as we are here because the 3W handshake is over.
12827 	 */
12828 	MAKE_UNDROPPABLE(tcp);
12829 
12830 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12831 		tcp_t *tail;
12832 
12833 		/*
12834 		 * The eager already has an extra ref put in tcp_rput_data
12835 		 * so that it stays till accept comes back even though it
12836 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12837 		 */
12838 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12839 		listener->tcp_conn_req_cnt_q0--;
12840 		listener->tcp_conn_req_cnt_q++;
12841 
12842 		/* Move from SYN_RCVD to ESTABLISHED list  */
12843 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12844 		    tcp->tcp_eager_prev_q0;
12845 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12846 		    tcp->tcp_eager_next_q0;
12847 		tcp->tcp_eager_prev_q0 = NULL;
12848 		tcp->tcp_eager_next_q0 = NULL;
12849 
12850 		/*
12851 		 * Insert at end of the queue because sockfs
12852 		 * sends down T_CONN_RES in chronological
12853 		 * order. Leaving the older conn indications
12854 		 * at front of the queue helps reducing search
12855 		 * time.
12856 		 */
12857 		tail = listener->tcp_eager_last_q;
12858 		if (tail != NULL)
12859 			tail->tcp_eager_next_q = tcp;
12860 		else
12861 			listener->tcp_eager_next_q = tcp;
12862 		listener->tcp_eager_last_q = tcp;
12863 		tcp->tcp_eager_next_q = NULL;
12864 		/*
12865 		 * Delay sending up the T_conn_ind until we are
12866 		 * done with the eager. Once we have have sent up
12867 		 * the T_conn_ind, the accept can potentially complete
12868 		 * any time and release the refhold we have on the eager.
12869 		 */
12870 		need_send_conn_ind = B_TRUE;
12871 	} else {
12872 		/*
12873 		 * Defer connection on q0 and set deferred
12874 		 * connection bit true
12875 		 */
12876 		tcp->tcp_conn_def_q0 = B_TRUE;
12877 
12878 		/* take tcp out of q0 ... */
12879 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12880 		    tcp->tcp_eager_next_q0;
12881 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12882 		    tcp->tcp_eager_prev_q0;
12883 
12884 		/* ... and place it at the end of q0 */
12885 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12886 		tcp->tcp_eager_next_q0 = listener;
12887 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12888 		listener->tcp_eager_prev_q0 = tcp;
12889 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12890 	}
12891 
12892 	/* we have timed out before */
12893 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12894 		tcp->tcp_syn_rcvd_timeout = 0;
12895 		listener->tcp_syn_rcvd_timeout--;
12896 		if (listener->tcp_syn_defense &&
12897 		    listener->tcp_syn_rcvd_timeout <=
12898 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12899 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12900 		    listener->tcp_last_rcv_lbolt)) {
12901 			/*
12902 			 * Turn off the defense mode if we
12903 			 * believe the SYN attack is over.
12904 			 */
12905 			listener->tcp_syn_defense = B_FALSE;
12906 			if (listener->tcp_ip_addr_cache) {
12907 				kmem_free((void *)listener->tcp_ip_addr_cache,
12908 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12909 				listener->tcp_ip_addr_cache = NULL;
12910 			}
12911 		}
12912 	}
12913 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12914 	if (addr_cache != NULL) {
12915 		/*
12916 		 * We have finished a 3-way handshake with this
12917 		 * remote host. This proves the IP addr is good.
12918 		 * Cache it!
12919 		 */
12920 		addr_cache[IP_ADDR_CACHE_HASH(
12921 		    tcp->tcp_remote)] = tcp->tcp_remote;
12922 	}
12923 	mutex_exit(&listener->tcp_eager_lock);
12924 	if (need_send_conn_ind)
12925 		putnext(listener->tcp_rq, mp);
12926 }
12927 
12928 mblk_t *
12929 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12930     uint_t *ifindexp, ip6_pkt_t *ippp)
12931 {
12932 	ip_pktinfo_t	*pinfo;
12933 	ip6_t		*ip6h;
12934 	uchar_t		*rptr;
12935 	mblk_t		*first_mp = mp;
12936 	boolean_t	mctl_present = B_FALSE;
12937 	uint_t 		ifindex = 0;
12938 	ip6_pkt_t	ipp;
12939 	uint_t		ipvers;
12940 	uint_t		ip_hdr_len;
12941 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12942 
12943 	rptr = mp->b_rptr;
12944 	ASSERT(OK_32PTR(rptr));
12945 	ASSERT(tcp != NULL);
12946 	ipp.ipp_fields = 0;
12947 
12948 	switch DB_TYPE(mp) {
12949 	case M_CTL:
12950 		mp = mp->b_cont;
12951 		if (mp == NULL) {
12952 			freemsg(first_mp);
12953 			return (NULL);
12954 		}
12955 		if (DB_TYPE(mp) != M_DATA) {
12956 			freemsg(first_mp);
12957 			return (NULL);
12958 		}
12959 		mctl_present = B_TRUE;
12960 		break;
12961 	case M_DATA:
12962 		break;
12963 	default:
12964 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12965 		freemsg(mp);
12966 		return (NULL);
12967 	}
12968 	ipvers = IPH_HDR_VERSION(rptr);
12969 	if (ipvers == IPV4_VERSION) {
12970 		if (tcp == NULL) {
12971 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12972 			goto done;
12973 		}
12974 
12975 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12976 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12977 
12978 		/*
12979 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12980 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12981 		 */
12982 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12983 		    mctl_present) {
12984 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12985 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12986 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12987 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12988 				ipp.ipp_fields |= IPPF_IFINDEX;
12989 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12990 				ifindex = pinfo->ip_pkt_ifindex;
12991 			}
12992 			freeb(first_mp);
12993 			mctl_present = B_FALSE;
12994 		}
12995 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12996 	} else {
12997 		ip6h = (ip6_t *)rptr;
12998 
12999 		ASSERT(ipvers == IPV6_VERSION);
13000 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
13001 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
13002 		ipp.ipp_hoplimit = ip6h->ip6_hops;
13003 
13004 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
13005 			uint8_t	nexthdrp;
13006 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13007 
13008 			/* Look for ifindex information */
13009 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
13010 				ip6i_t *ip6i = (ip6i_t *)ip6h;
13011 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
13012 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13013 					freemsg(first_mp);
13014 					return (NULL);
13015 				}
13016 
13017 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
13018 					ASSERT(ip6i->ip6i_ifindex != 0);
13019 					ipp.ipp_fields |= IPPF_IFINDEX;
13020 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
13021 					ifindex = ip6i->ip6i_ifindex;
13022 				}
13023 				rptr = (uchar_t *)&ip6i[1];
13024 				mp->b_rptr = rptr;
13025 				if (rptr == mp->b_wptr) {
13026 					mblk_t *mp1;
13027 					mp1 = mp->b_cont;
13028 					freeb(mp);
13029 					mp = mp1;
13030 					rptr = mp->b_rptr;
13031 				}
13032 				if (MBLKL(mp) < IPV6_HDR_LEN +
13033 				    sizeof (tcph_t)) {
13034 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13035 					freemsg(first_mp);
13036 					return (NULL);
13037 				}
13038 				ip6h = (ip6_t *)rptr;
13039 			}
13040 
13041 			/*
13042 			 * Find any potentially interesting extension headers
13043 			 * as well as the length of the IPv6 + extension
13044 			 * headers.
13045 			 */
13046 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
13047 			/* Verify if this is a TCP packet */
13048 			if (nexthdrp != IPPROTO_TCP) {
13049 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13050 				freemsg(first_mp);
13051 				return (NULL);
13052 			}
13053 		} else {
13054 			ip_hdr_len = IPV6_HDR_LEN;
13055 		}
13056 	}
13057 
13058 done:
13059 	if (ipversp != NULL)
13060 		*ipversp = ipvers;
13061 	if (ip_hdr_lenp != NULL)
13062 		*ip_hdr_lenp = ip_hdr_len;
13063 	if (ippp != NULL)
13064 		*ippp = ipp;
13065 	if (ifindexp != NULL)
13066 		*ifindexp = ifindex;
13067 	if (mctl_present) {
13068 		freeb(first_mp);
13069 	}
13070 	return (mp);
13071 }
13072 
13073 /*
13074  * Handle M_DATA messages from IP. Its called directly from IP via
13075  * squeue for AF_INET type sockets fast path. No M_CTL are expected
13076  * in this path.
13077  *
13078  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
13079  * v4 and v6), we are called through tcp_input() and a M_CTL can
13080  * be present for options but tcp_find_pktinfo() deals with it. We
13081  * only expect M_DATA packets after tcp_find_pktinfo() is done.
13082  *
13083  * The first argument is always the connp/tcp to which the mp belongs.
13084  * There are no exceptions to this rule. The caller has already put
13085  * a reference on this connp/tcp and once tcp_rput_data() returns,
13086  * the squeue will do the refrele.
13087  *
13088  * The TH_SYN for the listener directly go to tcp_conn_request via
13089  * squeue.
13090  *
13091  * sqp: NULL = recursive, sqp != NULL means called from squeue
13092  */
13093 void
13094 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
13095 {
13096 	int32_t		bytes_acked;
13097 	int32_t		gap;
13098 	mblk_t		*mp1;
13099 	uint_t		flags;
13100 	uint32_t	new_swnd = 0;
13101 	uchar_t		*iphdr;
13102 	uchar_t		*rptr;
13103 	int32_t		rgap;
13104 	uint32_t	seg_ack;
13105 	int		seg_len;
13106 	uint_t		ip_hdr_len;
13107 	uint32_t	seg_seq;
13108 	tcph_t		*tcph;
13109 	int		urp;
13110 	tcp_opt_t	tcpopt;
13111 	uint_t		ipvers;
13112 	ip6_pkt_t	ipp;
13113 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
13114 	uint32_t	cwnd;
13115 	uint32_t	add;
13116 	int		npkt;
13117 	int		mss;
13118 	conn_t		*connp = (conn_t *)arg;
13119 	squeue_t	*sqp = (squeue_t *)arg2;
13120 	tcp_t		*tcp = connp->conn_tcp;
13121 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13122 
13123 	/*
13124 	 * RST from fused tcp loopback peer should trigger an unfuse.
13125 	 */
13126 	if (tcp->tcp_fused) {
13127 		TCP_STAT(tcps, tcp_fusion_aborted);
13128 		tcp_unfuse(tcp);
13129 	}
13130 
13131 	iphdr = mp->b_rptr;
13132 	rptr = mp->b_rptr;
13133 	ASSERT(OK_32PTR(rptr));
13134 
13135 	/*
13136 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
13137 	 * processing here. For rest call tcp_find_pktinfo to fill up the
13138 	 * necessary information.
13139 	 */
13140 	if (IPCL_IS_TCP4(connp)) {
13141 		ipvers = IPV4_VERSION;
13142 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13143 	} else {
13144 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
13145 		    NULL, &ipp);
13146 		if (mp == NULL) {
13147 			TCP_STAT(tcps, tcp_rput_v6_error);
13148 			return;
13149 		}
13150 		iphdr = mp->b_rptr;
13151 		rptr = mp->b_rptr;
13152 	}
13153 	ASSERT(DB_TYPE(mp) == M_DATA);
13154 
13155 	tcph = (tcph_t *)&rptr[ip_hdr_len];
13156 	seg_seq = ABE32_TO_U32(tcph->th_seq);
13157 	seg_ack = ABE32_TO_U32(tcph->th_ack);
13158 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
13159 	seg_len = (int)(mp->b_wptr - rptr) -
13160 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
13161 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
13162 		do {
13163 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13164 			    (uintptr_t)INT_MAX);
13165 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
13166 		} while ((mp1 = mp1->b_cont) != NULL &&
13167 		    mp1->b_datap->db_type == M_DATA);
13168 	}
13169 
13170 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
13171 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
13172 		    seg_len, tcph);
13173 		return;
13174 	}
13175 
13176 	if (sqp != NULL) {
13177 		/*
13178 		 * This is the correct place to update tcp_last_recv_time. Note
13179 		 * that it is also updated for tcp structure that belongs to
13180 		 * global and listener queues which do not really need updating.
13181 		 * But that should not cause any harm.  And it is updated for
13182 		 * all kinds of incoming segments, not only for data segments.
13183 		 */
13184 		tcp->tcp_last_recv_time = lbolt;
13185 	}
13186 
13187 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13188 
13189 	BUMP_LOCAL(tcp->tcp_ibsegs);
13190 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13191 
13192 	if ((flags & TH_URG) && sqp != NULL) {
13193 		/*
13194 		 * TCP can't handle urgent pointers that arrive before
13195 		 * the connection has been accept()ed since it can't
13196 		 * buffer OOB data.  Discard segment if this happens.
13197 		 *
13198 		 * We can't just rely on a non-null tcp_listener to indicate
13199 		 * that the accept() has completed since unlinking of the
13200 		 * eager and completion of the accept are not atomic.
13201 		 * tcp_detached, when it is not set (B_FALSE) indicates
13202 		 * that the accept() has completed.
13203 		 *
13204 		 * Nor can it reassemble urgent pointers, so discard
13205 		 * if it's not the next segment expected.
13206 		 *
13207 		 * Otherwise, collapse chain into one mblk (discard if
13208 		 * that fails).  This makes sure the headers, retransmitted
13209 		 * data, and new data all are in the same mblk.
13210 		 */
13211 		ASSERT(mp != NULL);
13212 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13213 			freemsg(mp);
13214 			return;
13215 		}
13216 		/* Update pointers into message */
13217 		iphdr = rptr = mp->b_rptr;
13218 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13219 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13220 			/*
13221 			 * Since we can't handle any data with this urgent
13222 			 * pointer that is out of sequence, we expunge
13223 			 * the data.  This allows us to still register
13224 			 * the urgent mark and generate the M_PCSIG,
13225 			 * which we can do.
13226 			 */
13227 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13228 			seg_len = 0;
13229 		}
13230 	}
13231 
13232 	switch (tcp->tcp_state) {
13233 	case TCPS_SYN_SENT:
13234 		if (flags & TH_ACK) {
13235 			/*
13236 			 * Note that our stack cannot send data before a
13237 			 * connection is established, therefore the
13238 			 * following check is valid.  Otherwise, it has
13239 			 * to be changed.
13240 			 */
13241 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13242 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13243 				freemsg(mp);
13244 				if (flags & TH_RST)
13245 					return;
13246 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13247 				    tcp, seg_ack, 0, TH_RST);
13248 				return;
13249 			}
13250 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13251 		}
13252 		if (flags & TH_RST) {
13253 			freemsg(mp);
13254 			if (flags & TH_ACK)
13255 				(void) tcp_clean_death(tcp,
13256 				    ECONNREFUSED, 13);
13257 			return;
13258 		}
13259 		if (!(flags & TH_SYN)) {
13260 			freemsg(mp);
13261 			return;
13262 		}
13263 
13264 		/* Process all TCP options. */
13265 		tcp_process_options(tcp, tcph);
13266 		/*
13267 		 * The following changes our rwnd to be a multiple of the
13268 		 * MIN(peer MSS, our MSS) for performance reason.
13269 		 */
13270 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
13271 		    tcp->tcp_mss));
13272 
13273 		/* Is the other end ECN capable? */
13274 		if (tcp->tcp_ecn_ok) {
13275 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13276 				tcp->tcp_ecn_ok = B_FALSE;
13277 			}
13278 		}
13279 		/*
13280 		 * Clear ECN flags because it may interfere with later
13281 		 * processing.
13282 		 */
13283 		flags &= ~(TH_ECE|TH_CWR);
13284 
13285 		tcp->tcp_irs = seg_seq;
13286 		tcp->tcp_rack = seg_seq;
13287 		tcp->tcp_rnxt = seg_seq + 1;
13288 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13289 		if (!TCP_IS_DETACHED(tcp)) {
13290 			/* Allocate room for SACK options if needed. */
13291 			if (tcp->tcp_snd_sack_ok) {
13292 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13293 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13294 				    (tcp->tcp_loopback ? 0 :
13295 				    tcps->tcps_wroff_xtra));
13296 			} else {
13297 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13298 				    tcp->tcp_hdr_len +
13299 				    (tcp->tcp_loopback ? 0 :
13300 				    tcps->tcps_wroff_xtra));
13301 			}
13302 		}
13303 		if (flags & TH_ACK) {
13304 			/*
13305 			 * If we can't get the confirmation upstream, pretend
13306 			 * we didn't even see this one.
13307 			 *
13308 			 * XXX: how can we pretend we didn't see it if we
13309 			 * have updated rnxt et. al.
13310 			 *
13311 			 * For loopback we defer sending up the T_CONN_CON
13312 			 * until after some checks below.
13313 			 */
13314 			mp1 = NULL;
13315 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13316 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13317 				freemsg(mp);
13318 				return;
13319 			}
13320 			/* SYN was acked - making progress */
13321 			if (tcp->tcp_ipversion == IPV6_VERSION)
13322 				tcp->tcp_ip_forward_progress = B_TRUE;
13323 
13324 			/* One for the SYN */
13325 			tcp->tcp_suna = tcp->tcp_iss + 1;
13326 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13327 			tcp->tcp_state = TCPS_ESTABLISHED;
13328 
13329 			/*
13330 			 * If SYN was retransmitted, need to reset all
13331 			 * retransmission info.  This is because this
13332 			 * segment will be treated as a dup ACK.
13333 			 */
13334 			if (tcp->tcp_rexmit) {
13335 				tcp->tcp_rexmit = B_FALSE;
13336 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13337 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13338 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13339 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13340 				tcp->tcp_ms_we_have_waited = 0;
13341 
13342 				/*
13343 				 * Set tcp_cwnd back to 1 MSS, per
13344 				 * recommendation from
13345 				 * draft-floyd-incr-init-win-01.txt,
13346 				 * Increasing TCP's Initial Window.
13347 				 */
13348 				tcp->tcp_cwnd = tcp->tcp_mss;
13349 			}
13350 
13351 			tcp->tcp_swl1 = seg_seq;
13352 			tcp->tcp_swl2 = seg_ack;
13353 
13354 			new_swnd = BE16_TO_U16(tcph->th_win);
13355 			tcp->tcp_swnd = new_swnd;
13356 			if (new_swnd > tcp->tcp_max_swnd)
13357 				tcp->tcp_max_swnd = new_swnd;
13358 
13359 			/*
13360 			 * Always send the three-way handshake ack immediately
13361 			 * in order to make the connection complete as soon as
13362 			 * possible on the accepting host.
13363 			 */
13364 			flags |= TH_ACK_NEEDED;
13365 
13366 			/*
13367 			 * Special case for loopback.  At this point we have
13368 			 * received SYN-ACK from the remote endpoint.  In
13369 			 * order to ensure that both endpoints reach the
13370 			 * fused state prior to any data exchange, the final
13371 			 * ACK needs to be sent before we indicate T_CONN_CON
13372 			 * to the module upstream.
13373 			 */
13374 			if (tcp->tcp_loopback) {
13375 				mblk_t *ack_mp;
13376 
13377 				ASSERT(!tcp->tcp_unfusable);
13378 				ASSERT(mp1 != NULL);
13379 				/*
13380 				 * For loopback, we always get a pure SYN-ACK
13381 				 * and only need to send back the final ACK
13382 				 * with no data (this is because the other
13383 				 * tcp is ours and we don't do T/TCP).  This
13384 				 * final ACK triggers the passive side to
13385 				 * perform fusion in ESTABLISHED state.
13386 				 */
13387 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13388 					if (tcp->tcp_ack_tid != 0) {
13389 						(void) TCP_TIMER_CANCEL(tcp,
13390 						    tcp->tcp_ack_tid);
13391 						tcp->tcp_ack_tid = 0;
13392 					}
13393 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13394 					BUMP_LOCAL(tcp->tcp_obsegs);
13395 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13396 
13397 					/* Send up T_CONN_CON */
13398 					putnext(tcp->tcp_rq, mp1);
13399 
13400 					freemsg(mp);
13401 					return;
13402 				}
13403 				/*
13404 				 * Forget fusion; we need to handle more
13405 				 * complex cases below.  Send the deferred
13406 				 * T_CONN_CON message upstream and proceed
13407 				 * as usual.  Mark this tcp as not capable
13408 				 * of fusion.
13409 				 */
13410 				TCP_STAT(tcps, tcp_fusion_unfusable);
13411 				tcp->tcp_unfusable = B_TRUE;
13412 				putnext(tcp->tcp_rq, mp1);
13413 			}
13414 
13415 			/*
13416 			 * Check to see if there is data to be sent.  If
13417 			 * yes, set the transmit flag.  Then check to see
13418 			 * if received data processing needs to be done.
13419 			 * If not, go straight to xmit_check.  This short
13420 			 * cut is OK as we don't support T/TCP.
13421 			 */
13422 			if (tcp->tcp_unsent)
13423 				flags |= TH_XMIT_NEEDED;
13424 
13425 			if (seg_len == 0 && !(flags & TH_URG)) {
13426 				freemsg(mp);
13427 				goto xmit_check;
13428 			}
13429 
13430 			flags &= ~TH_SYN;
13431 			seg_seq++;
13432 			break;
13433 		}
13434 		tcp->tcp_state = TCPS_SYN_RCVD;
13435 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13436 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13437 		if (mp1) {
13438 			DB_CPID(mp1) = tcp->tcp_cpid;
13439 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13440 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13441 		}
13442 		freemsg(mp);
13443 		return;
13444 	case TCPS_SYN_RCVD:
13445 		if (flags & TH_ACK) {
13446 			/*
13447 			 * In this state, a SYN|ACK packet is either bogus
13448 			 * because the other side must be ACKing our SYN which
13449 			 * indicates it has seen the ACK for their SYN and
13450 			 * shouldn't retransmit it or we're crossing SYNs
13451 			 * on active open.
13452 			 */
13453 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13454 				freemsg(mp);
13455 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13456 				    tcp, seg_ack, 0, TH_RST);
13457 				return;
13458 			}
13459 			/*
13460 			 * NOTE: RFC 793 pg. 72 says this should be
13461 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13462 			 * but that would mean we have an ack that ignored
13463 			 * our SYN.
13464 			 */
13465 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13466 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13467 				freemsg(mp);
13468 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13469 				    tcp, seg_ack, 0, TH_RST);
13470 				return;
13471 			}
13472 		}
13473 		break;
13474 	case TCPS_LISTEN:
13475 		/*
13476 		 * Only a TLI listener can come through this path when a
13477 		 * acceptor is going back to be a listener and a packet
13478 		 * for the acceptor hits the classifier. For a socket
13479 		 * listener, this can never happen because a listener
13480 		 * can never accept connection on itself and hence a
13481 		 * socket acceptor can not go back to being a listener.
13482 		 */
13483 		ASSERT(!TCP_IS_SOCKET(tcp));
13484 		/*FALLTHRU*/
13485 	case TCPS_CLOSED:
13486 	case TCPS_BOUND: {
13487 		conn_t	*new_connp;
13488 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13489 
13490 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13491 		if (new_connp != NULL) {
13492 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13493 			return;
13494 		}
13495 		/* We failed to classify. For now just drop the packet */
13496 		freemsg(mp);
13497 		return;
13498 	}
13499 	case TCPS_IDLE:
13500 		/*
13501 		 * Handle the case where the tcp_clean_death() has happened
13502 		 * on a connection (application hasn't closed yet) but a packet
13503 		 * was already queued on squeue before tcp_clean_death()
13504 		 * was processed. Calling tcp_clean_death() twice on same
13505 		 * connection can result in weird behaviour.
13506 		 */
13507 		freemsg(mp);
13508 		return;
13509 	default:
13510 		break;
13511 	}
13512 
13513 	/*
13514 	 * Already on the correct queue/perimeter.
13515 	 * If this is a detached connection and not an eager
13516 	 * connection hanging off a listener then new data
13517 	 * (past the FIN) will cause a reset.
13518 	 * We do a special check here where it
13519 	 * is out of the main line, rather than check
13520 	 * if we are detached every time we see new
13521 	 * data down below.
13522 	 */
13523 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13524 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13525 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13526 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13527 
13528 		freemsg(mp);
13529 		/*
13530 		 * This could be an SSL closure alert. We're detached so just
13531 		 * acknowledge it this last time.
13532 		 */
13533 		if (tcp->tcp_kssl_ctx != NULL) {
13534 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13535 			tcp->tcp_kssl_ctx = NULL;
13536 
13537 			tcp->tcp_rnxt += seg_len;
13538 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13539 			flags |= TH_ACK_NEEDED;
13540 			goto ack_check;
13541 		}
13542 
13543 		tcp_xmit_ctl("new data when detached", tcp,
13544 		    tcp->tcp_snxt, 0, TH_RST);
13545 		(void) tcp_clean_death(tcp, EPROTO, 12);
13546 		return;
13547 	}
13548 
13549 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13550 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13551 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13552 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13553 
13554 	if (tcp->tcp_snd_ts_ok) {
13555 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13556 			/*
13557 			 * This segment is not acceptable.
13558 			 * Drop it and send back an ACK.
13559 			 */
13560 			freemsg(mp);
13561 			flags |= TH_ACK_NEEDED;
13562 			goto ack_check;
13563 		}
13564 	} else if (tcp->tcp_snd_sack_ok) {
13565 		ASSERT(tcp->tcp_sack_info != NULL);
13566 		tcpopt.tcp = tcp;
13567 		/*
13568 		 * SACK info in already updated in tcp_parse_options.  Ignore
13569 		 * all other TCP options...
13570 		 */
13571 		(void) tcp_parse_options(tcph, &tcpopt);
13572 	}
13573 try_again:;
13574 	mss = tcp->tcp_mss;
13575 	gap = seg_seq - tcp->tcp_rnxt;
13576 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13577 	/*
13578 	 * gap is the amount of sequence space between what we expect to see
13579 	 * and what we got for seg_seq.  A positive value for gap means
13580 	 * something got lost.  A negative value means we got some old stuff.
13581 	 */
13582 	if (gap < 0) {
13583 		/* Old stuff present.  Is the SYN in there? */
13584 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13585 		    (seg_len != 0)) {
13586 			flags &= ~TH_SYN;
13587 			seg_seq++;
13588 			urp--;
13589 			/* Recompute the gaps after noting the SYN. */
13590 			goto try_again;
13591 		}
13592 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13593 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13594 		    (seg_len > -gap ? -gap : seg_len));
13595 		/* Remove the old stuff from seg_len. */
13596 		seg_len += gap;
13597 		/*
13598 		 * Anything left?
13599 		 * Make sure to check for unack'd FIN when rest of data
13600 		 * has been previously ack'd.
13601 		 */
13602 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13603 			/*
13604 			 * Resets are only valid if they lie within our offered
13605 			 * window.  If the RST bit is set, we just ignore this
13606 			 * segment.
13607 			 */
13608 			if (flags & TH_RST) {
13609 				freemsg(mp);
13610 				return;
13611 			}
13612 
13613 			/*
13614 			 * The arriving of dup data packets indicate that we
13615 			 * may have postponed an ack for too long, or the other
13616 			 * side's RTT estimate is out of shape. Start acking
13617 			 * more often.
13618 			 */
13619 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13620 			    tcp->tcp_rack_cnt >= 1 &&
13621 			    tcp->tcp_rack_abs_max > 2) {
13622 				tcp->tcp_rack_abs_max--;
13623 			}
13624 			tcp->tcp_rack_cur_max = 1;
13625 
13626 			/*
13627 			 * This segment is "unacceptable".  None of its
13628 			 * sequence space lies within our advertized window.
13629 			 *
13630 			 * Adjust seg_len to the original value for tracing.
13631 			 */
13632 			seg_len -= gap;
13633 			if (tcp->tcp_debug) {
13634 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13635 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13636 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13637 				    "seg_len %d, rnxt %u, snxt %u, %s",
13638 				    gap, rgap, flags, seg_seq, seg_ack,
13639 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13640 				    tcp_display(tcp, NULL,
13641 				    DISP_ADDR_AND_PORT));
13642 			}
13643 
13644 			/*
13645 			 * Arrange to send an ACK in response to the
13646 			 * unacceptable segment per RFC 793 page 69. There
13647 			 * is only one small difference between ours and the
13648 			 * acceptability test in the RFC - we accept ACK-only
13649 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13650 			 * will be generated.
13651 			 *
13652 			 * Note that we have to ACK an ACK-only packet at least
13653 			 * for stacks that send 0-length keep-alives with
13654 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13655 			 * section 4.2.3.6. As long as we don't ever generate
13656 			 * an unacceptable packet in response to an incoming
13657 			 * packet that is unacceptable, it should not cause
13658 			 * "ACK wars".
13659 			 */
13660 			flags |=  TH_ACK_NEEDED;
13661 
13662 			/*
13663 			 * Continue processing this segment in order to use the
13664 			 * ACK information it contains, but skip all other
13665 			 * sequence-number processing.	Processing the ACK
13666 			 * information is necessary in order to
13667 			 * re-synchronize connections that may have lost
13668 			 * synchronization.
13669 			 *
13670 			 * We clear seg_len and flag fields related to
13671 			 * sequence number processing as they are not
13672 			 * to be trusted for an unacceptable segment.
13673 			 */
13674 			seg_len = 0;
13675 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13676 			goto process_ack;
13677 		}
13678 
13679 		/* Fix seg_seq, and chew the gap off the front. */
13680 		seg_seq = tcp->tcp_rnxt;
13681 		urp += gap;
13682 		do {
13683 			mblk_t	*mp2;
13684 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13685 			    (uintptr_t)UINT_MAX);
13686 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13687 			if (gap > 0) {
13688 				mp->b_rptr = mp->b_wptr - gap;
13689 				break;
13690 			}
13691 			mp2 = mp;
13692 			mp = mp->b_cont;
13693 			freeb(mp2);
13694 		} while (gap < 0);
13695 		/*
13696 		 * If the urgent data has already been acknowledged, we
13697 		 * should ignore TH_URG below
13698 		 */
13699 		if (urp < 0)
13700 			flags &= ~TH_URG;
13701 	}
13702 	/*
13703 	 * rgap is the amount of stuff received out of window.  A negative
13704 	 * value is the amount out of window.
13705 	 */
13706 	if (rgap < 0) {
13707 		mblk_t	*mp2;
13708 
13709 		if (tcp->tcp_rwnd == 0) {
13710 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13711 		} else {
13712 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13713 			UPDATE_MIB(&tcps->tcps_mib,
13714 			    tcpInDataPastWinBytes, -rgap);
13715 		}
13716 
13717 		/*
13718 		 * seg_len does not include the FIN, so if more than
13719 		 * just the FIN is out of window, we act like we don't
13720 		 * see it.  (If just the FIN is out of window, rgap
13721 		 * will be zero and we will go ahead and acknowledge
13722 		 * the FIN.)
13723 		 */
13724 		flags &= ~TH_FIN;
13725 
13726 		/* Fix seg_len and make sure there is something left. */
13727 		seg_len += rgap;
13728 		if (seg_len <= 0) {
13729 			/*
13730 			 * Resets are only valid if they lie within our offered
13731 			 * window.  If the RST bit is set, we just ignore this
13732 			 * segment.
13733 			 */
13734 			if (flags & TH_RST) {
13735 				freemsg(mp);
13736 				return;
13737 			}
13738 
13739 			/* Per RFC 793, we need to send back an ACK. */
13740 			flags |= TH_ACK_NEEDED;
13741 
13742 			/*
13743 			 * Send SIGURG as soon as possible i.e. even
13744 			 * if the TH_URG was delivered in a window probe
13745 			 * packet (which will be unacceptable).
13746 			 *
13747 			 * We generate a signal if none has been generated
13748 			 * for this connection or if this is a new urgent
13749 			 * byte. Also send a zero-length "unmarked" message
13750 			 * to inform SIOCATMARK that this is not the mark.
13751 			 *
13752 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13753 			 * is sent up. This plus the check for old data
13754 			 * (gap >= 0) handles the wraparound of the sequence
13755 			 * number space without having to always track the
13756 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13757 			 * this max in its rcv_up variable).
13758 			 *
13759 			 * This prevents duplicate SIGURGS due to a "late"
13760 			 * zero-window probe when the T_EXDATA_IND has already
13761 			 * been sent up.
13762 			 */
13763 			if ((flags & TH_URG) &&
13764 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13765 			    tcp->tcp_urp_last))) {
13766 				mp1 = allocb(0, BPRI_MED);
13767 				if (mp1 == NULL) {
13768 					freemsg(mp);
13769 					return;
13770 				}
13771 				if (!TCP_IS_DETACHED(tcp) &&
13772 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13773 				    SIGURG)) {
13774 					/* Try again on the rexmit. */
13775 					freemsg(mp1);
13776 					freemsg(mp);
13777 					return;
13778 				}
13779 				/*
13780 				 * If the next byte would be the mark
13781 				 * then mark with MARKNEXT else mark
13782 				 * with NOTMARKNEXT.
13783 				 */
13784 				if (gap == 0 && urp == 0)
13785 					mp1->b_flag |= MSGMARKNEXT;
13786 				else
13787 					mp1->b_flag |= MSGNOTMARKNEXT;
13788 				freemsg(tcp->tcp_urp_mark_mp);
13789 				tcp->tcp_urp_mark_mp = mp1;
13790 				flags |= TH_SEND_URP_MARK;
13791 				tcp->tcp_urp_last_valid = B_TRUE;
13792 				tcp->tcp_urp_last = urp + seg_seq;
13793 			}
13794 			/*
13795 			 * If this is a zero window probe, continue to
13796 			 * process the ACK part.  But we need to set seg_len
13797 			 * to 0 to avoid data processing.  Otherwise just
13798 			 * drop the segment and send back an ACK.
13799 			 */
13800 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13801 				flags &= ~(TH_SYN | TH_URG);
13802 				seg_len = 0;
13803 				goto process_ack;
13804 			} else {
13805 				freemsg(mp);
13806 				goto ack_check;
13807 			}
13808 		}
13809 		/* Pitch out of window stuff off the end. */
13810 		rgap = seg_len;
13811 		mp2 = mp;
13812 		do {
13813 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13814 			    (uintptr_t)INT_MAX);
13815 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13816 			if (rgap < 0) {
13817 				mp2->b_wptr += rgap;
13818 				if ((mp1 = mp2->b_cont) != NULL) {
13819 					mp2->b_cont = NULL;
13820 					freemsg(mp1);
13821 				}
13822 				break;
13823 			}
13824 		} while ((mp2 = mp2->b_cont) != NULL);
13825 	}
13826 ok:;
13827 	/*
13828 	 * TCP should check ECN info for segments inside the window only.
13829 	 * Therefore the check should be done here.
13830 	 */
13831 	if (tcp->tcp_ecn_ok) {
13832 		if (flags & TH_CWR) {
13833 			tcp->tcp_ecn_echo_on = B_FALSE;
13834 		}
13835 		/*
13836 		 * Note that both ECN_CE and CWR can be set in the
13837 		 * same segment.  In this case, we once again turn
13838 		 * on ECN_ECHO.
13839 		 */
13840 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13841 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13842 
13843 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13844 				tcp->tcp_ecn_echo_on = B_TRUE;
13845 			}
13846 		} else {
13847 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13848 
13849 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13850 			    htonl(IPH_ECN_CE << 20)) {
13851 				tcp->tcp_ecn_echo_on = B_TRUE;
13852 			}
13853 		}
13854 	}
13855 
13856 	/*
13857 	 * Check whether we can update tcp_ts_recent.  This test is
13858 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13859 	 * Extensions for High Performance: An Update", Internet Draft.
13860 	 */
13861 	if (tcp->tcp_snd_ts_ok &&
13862 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13863 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13864 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13865 		tcp->tcp_last_rcv_lbolt = lbolt64;
13866 	}
13867 
13868 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13869 		/*
13870 		 * FIN in an out of order segment.  We record this in
13871 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13872 		 * Clear the FIN so that any check on FIN flag will fail.
13873 		 * Remember that FIN also counts in the sequence number
13874 		 * space.  So we need to ack out of order FIN only segments.
13875 		 */
13876 		if (flags & TH_FIN) {
13877 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13878 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13879 			flags &= ~TH_FIN;
13880 			flags |= TH_ACK_NEEDED;
13881 		}
13882 		if (seg_len > 0) {
13883 			/* Fill in the SACK blk list. */
13884 			if (tcp->tcp_snd_sack_ok) {
13885 				ASSERT(tcp->tcp_sack_info != NULL);
13886 				tcp_sack_insert(tcp->tcp_sack_list,
13887 				    seg_seq, seg_seq + seg_len,
13888 				    &(tcp->tcp_num_sack_blk));
13889 			}
13890 
13891 			/*
13892 			 * Attempt reassembly and see if we have something
13893 			 * ready to go.
13894 			 */
13895 			mp = tcp_reass(tcp, mp, seg_seq);
13896 			/* Always ack out of order packets */
13897 			flags |= TH_ACK_NEEDED | TH_PUSH;
13898 			if (mp) {
13899 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13900 				    (uintptr_t)INT_MAX);
13901 				seg_len = mp->b_cont ? msgdsize(mp) :
13902 				    (int)(mp->b_wptr - mp->b_rptr);
13903 				seg_seq = tcp->tcp_rnxt;
13904 				/*
13905 				 * A gap is filled and the seq num and len
13906 				 * of the gap match that of a previously
13907 				 * received FIN, put the FIN flag back in.
13908 				 */
13909 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13910 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13911 					flags |= TH_FIN;
13912 					tcp->tcp_valid_bits &=
13913 					    ~TCP_OFO_FIN_VALID;
13914 				}
13915 			} else {
13916 				/*
13917 				 * Keep going even with NULL mp.
13918 				 * There may be a useful ACK or something else
13919 				 * we don't want to miss.
13920 				 *
13921 				 * But TCP should not perform fast retransmit
13922 				 * because of the ack number.  TCP uses
13923 				 * seg_len == 0 to determine if it is a pure
13924 				 * ACK.  And this is not a pure ACK.
13925 				 */
13926 				seg_len = 0;
13927 				ofo_seg = B_TRUE;
13928 			}
13929 		}
13930 	} else if (seg_len > 0) {
13931 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13932 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13933 		/*
13934 		 * If an out of order FIN was received before, and the seq
13935 		 * num and len of the new segment match that of the FIN,
13936 		 * put the FIN flag back in.
13937 		 */
13938 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13939 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13940 			flags |= TH_FIN;
13941 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13942 		}
13943 	}
13944 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13945 	if (flags & TH_RST) {
13946 		freemsg(mp);
13947 		switch (tcp->tcp_state) {
13948 		case TCPS_SYN_RCVD:
13949 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13950 			break;
13951 		case TCPS_ESTABLISHED:
13952 		case TCPS_FIN_WAIT_1:
13953 		case TCPS_FIN_WAIT_2:
13954 		case TCPS_CLOSE_WAIT:
13955 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13956 			break;
13957 		case TCPS_CLOSING:
13958 		case TCPS_LAST_ACK:
13959 			(void) tcp_clean_death(tcp, 0, 16);
13960 			break;
13961 		default:
13962 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13963 			(void) tcp_clean_death(tcp, ENXIO, 17);
13964 			break;
13965 		}
13966 		return;
13967 	}
13968 	if (flags & TH_SYN) {
13969 		/*
13970 		 * See RFC 793, Page 71
13971 		 *
13972 		 * The seq number must be in the window as it should
13973 		 * be "fixed" above.  If it is outside window, it should
13974 		 * be already rejected.  Note that we allow seg_seq to be
13975 		 * rnxt + rwnd because we want to accept 0 window probe.
13976 		 */
13977 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13978 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13979 		freemsg(mp);
13980 		/*
13981 		 * If the ACK flag is not set, just use our snxt as the
13982 		 * seq number of the RST segment.
13983 		 */
13984 		if (!(flags & TH_ACK)) {
13985 			seg_ack = tcp->tcp_snxt;
13986 		}
13987 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13988 		    TH_RST|TH_ACK);
13989 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13990 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13991 		return;
13992 	}
13993 	/*
13994 	 * urp could be -1 when the urp field in the packet is 0
13995 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13996 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13997 	 */
13998 	if (flags & TH_URG && urp >= 0) {
13999 		if (!tcp->tcp_urp_last_valid ||
14000 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
14001 			/*
14002 			 * If we haven't generated the signal yet for this
14003 			 * urgent pointer value, do it now.  Also, send up a
14004 			 * zero-length M_DATA indicating whether or not this is
14005 			 * the mark. The latter is not needed when a
14006 			 * T_EXDATA_IND is sent up. However, if there are
14007 			 * allocation failures this code relies on the sender
14008 			 * retransmitting and the socket code for determining
14009 			 * the mark should not block waiting for the peer to
14010 			 * transmit. Thus, for simplicity we always send up the
14011 			 * mark indication.
14012 			 */
14013 			mp1 = allocb(0, BPRI_MED);
14014 			if (mp1 == NULL) {
14015 				freemsg(mp);
14016 				return;
14017 			}
14018 			if (!TCP_IS_DETACHED(tcp) &&
14019 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
14020 				/* Try again on the rexmit. */
14021 				freemsg(mp1);
14022 				freemsg(mp);
14023 				return;
14024 			}
14025 			/*
14026 			 * Mark with NOTMARKNEXT for now.
14027 			 * The code below will change this to MARKNEXT
14028 			 * if we are at the mark.
14029 			 *
14030 			 * If there are allocation failures (e.g. in dupmsg
14031 			 * below) the next time tcp_rput_data sees the urgent
14032 			 * segment it will send up the MSG*MARKNEXT message.
14033 			 */
14034 			mp1->b_flag |= MSGNOTMARKNEXT;
14035 			freemsg(tcp->tcp_urp_mark_mp);
14036 			tcp->tcp_urp_mark_mp = mp1;
14037 			flags |= TH_SEND_URP_MARK;
14038 #ifdef DEBUG
14039 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14040 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
14041 			    "last %x, %s",
14042 			    seg_seq, urp, tcp->tcp_urp_last,
14043 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14044 #endif /* DEBUG */
14045 			tcp->tcp_urp_last_valid = B_TRUE;
14046 			tcp->tcp_urp_last = urp + seg_seq;
14047 		} else if (tcp->tcp_urp_mark_mp != NULL) {
14048 			/*
14049 			 * An allocation failure prevented the previous
14050 			 * tcp_rput_data from sending up the allocated
14051 			 * MSG*MARKNEXT message - send it up this time
14052 			 * around.
14053 			 */
14054 			flags |= TH_SEND_URP_MARK;
14055 		}
14056 
14057 		/*
14058 		 * If the urgent byte is in this segment, make sure that it is
14059 		 * all by itself.  This makes it much easier to deal with the
14060 		 * possibility of an allocation failure on the T_exdata_ind.
14061 		 * Note that seg_len is the number of bytes in the segment, and
14062 		 * urp is the offset into the segment of the urgent byte.
14063 		 * urp < seg_len means that the urgent byte is in this segment.
14064 		 */
14065 		if (urp < seg_len) {
14066 			if (seg_len != 1) {
14067 				uint32_t  tmp_rnxt;
14068 				/*
14069 				 * Break it up and feed it back in.
14070 				 * Re-attach the IP header.
14071 				 */
14072 				mp->b_rptr = iphdr;
14073 				if (urp > 0) {
14074 					/*
14075 					 * There is stuff before the urgent
14076 					 * byte.
14077 					 */
14078 					mp1 = dupmsg(mp);
14079 					if (!mp1) {
14080 						/*
14081 						 * Trim from urgent byte on.
14082 						 * The rest will come back.
14083 						 */
14084 						(void) adjmsg(mp,
14085 						    urp - seg_len);
14086 						tcp_rput_data(connp,
14087 						    mp, NULL);
14088 						return;
14089 					}
14090 					(void) adjmsg(mp1, urp - seg_len);
14091 					/* Feed this piece back in. */
14092 					tmp_rnxt = tcp->tcp_rnxt;
14093 					tcp_rput_data(connp, mp1, NULL);
14094 					/*
14095 					 * If the data passed back in was not
14096 					 * processed (ie: bad ACK) sending
14097 					 * the remainder back in will cause a
14098 					 * loop. In this case, drop the
14099 					 * packet and let the sender try
14100 					 * sending a good packet.
14101 					 */
14102 					if (tmp_rnxt == tcp->tcp_rnxt) {
14103 						freemsg(mp);
14104 						return;
14105 					}
14106 				}
14107 				if (urp != seg_len - 1) {
14108 					uint32_t  tmp_rnxt;
14109 					/*
14110 					 * There is stuff after the urgent
14111 					 * byte.
14112 					 */
14113 					mp1 = dupmsg(mp);
14114 					if (!mp1) {
14115 						/*
14116 						 * Trim everything beyond the
14117 						 * urgent byte.  The rest will
14118 						 * come back.
14119 						 */
14120 						(void) adjmsg(mp,
14121 						    urp + 1 - seg_len);
14122 						tcp_rput_data(connp,
14123 						    mp, NULL);
14124 						return;
14125 					}
14126 					(void) adjmsg(mp1, urp + 1 - seg_len);
14127 					tmp_rnxt = tcp->tcp_rnxt;
14128 					tcp_rput_data(connp, mp1, NULL);
14129 					/*
14130 					 * If the data passed back in was not
14131 					 * processed (ie: bad ACK) sending
14132 					 * the remainder back in will cause a
14133 					 * loop. In this case, drop the
14134 					 * packet and let the sender try
14135 					 * sending a good packet.
14136 					 */
14137 					if (tmp_rnxt == tcp->tcp_rnxt) {
14138 						freemsg(mp);
14139 						return;
14140 					}
14141 				}
14142 				tcp_rput_data(connp, mp, NULL);
14143 				return;
14144 			}
14145 			/*
14146 			 * This segment contains only the urgent byte.  We
14147 			 * have to allocate the T_exdata_ind, if we can.
14148 			 */
14149 			if (!tcp->tcp_urp_mp) {
14150 				struct T_exdata_ind *tei;
14151 				mp1 = allocb(sizeof (struct T_exdata_ind),
14152 				    BPRI_MED);
14153 				if (!mp1) {
14154 					/*
14155 					 * Sigh... It'll be back.
14156 					 * Generate any MSG*MARK message now.
14157 					 */
14158 					freemsg(mp);
14159 					seg_len = 0;
14160 					if (flags & TH_SEND_URP_MARK) {
14161 
14162 
14163 						ASSERT(tcp->tcp_urp_mark_mp);
14164 						tcp->tcp_urp_mark_mp->b_flag &=
14165 						    ~MSGNOTMARKNEXT;
14166 						tcp->tcp_urp_mark_mp->b_flag |=
14167 						    MSGMARKNEXT;
14168 					}
14169 					goto ack_check;
14170 				}
14171 				mp1->b_datap->db_type = M_PROTO;
14172 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14173 				tei->PRIM_type = T_EXDATA_IND;
14174 				tei->MORE_flag = 0;
14175 				mp1->b_wptr = (uchar_t *)&tei[1];
14176 				tcp->tcp_urp_mp = mp1;
14177 #ifdef DEBUG
14178 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14179 				    "tcp_rput: allocated exdata_ind %s",
14180 				    tcp_display(tcp, NULL,
14181 				    DISP_PORT_ONLY));
14182 #endif /* DEBUG */
14183 				/*
14184 				 * There is no need to send a separate MSG*MARK
14185 				 * message since the T_EXDATA_IND will be sent
14186 				 * now.
14187 				 */
14188 				flags &= ~TH_SEND_URP_MARK;
14189 				freemsg(tcp->tcp_urp_mark_mp);
14190 				tcp->tcp_urp_mark_mp = NULL;
14191 			}
14192 			/*
14193 			 * Now we are all set.  On the next putnext upstream,
14194 			 * tcp_urp_mp will be non-NULL and will get prepended
14195 			 * to what has to be this piece containing the urgent
14196 			 * byte.  If for any reason we abort this segment below,
14197 			 * if it comes back, we will have this ready, or it
14198 			 * will get blown off in close.
14199 			 */
14200 		} else if (urp == seg_len) {
14201 			/*
14202 			 * The urgent byte is the next byte after this sequence
14203 			 * number. If there is data it is marked with
14204 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14205 			 * since it is not needed. Otherwise, if the code
14206 			 * above just allocated a zero-length tcp_urp_mark_mp
14207 			 * message, that message is tagged with MSGMARKNEXT.
14208 			 * Sending up these MSGMARKNEXT messages makes
14209 			 * SIOCATMARK work correctly even though
14210 			 * the T_EXDATA_IND will not be sent up until the
14211 			 * urgent byte arrives.
14212 			 */
14213 			if (seg_len != 0) {
14214 				flags |= TH_MARKNEXT_NEEDED;
14215 				freemsg(tcp->tcp_urp_mark_mp);
14216 				tcp->tcp_urp_mark_mp = NULL;
14217 				flags &= ~TH_SEND_URP_MARK;
14218 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14219 				flags |= TH_SEND_URP_MARK;
14220 				tcp->tcp_urp_mark_mp->b_flag &=
14221 				    ~MSGNOTMARKNEXT;
14222 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14223 			}
14224 #ifdef DEBUG
14225 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14226 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14227 			    seg_len, flags,
14228 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14229 #endif /* DEBUG */
14230 		} else {
14231 			/* Data left until we hit mark */
14232 #ifdef DEBUG
14233 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14234 			    "tcp_rput: URP %d bytes left, %s",
14235 			    urp - seg_len, tcp_display(tcp, NULL,
14236 			    DISP_PORT_ONLY));
14237 #endif /* DEBUG */
14238 		}
14239 	}
14240 
14241 process_ack:
14242 	if (!(flags & TH_ACK)) {
14243 		freemsg(mp);
14244 		goto xmit_check;
14245 	}
14246 	}
14247 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14248 
14249 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14250 		tcp->tcp_ip_forward_progress = B_TRUE;
14251 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14252 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14253 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14254 			/* 3-way handshake complete - pass up the T_CONN_IND */
14255 			tcp_t	*listener = tcp->tcp_listener;
14256 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14257 
14258 			tcp->tcp_tconnind_started = B_TRUE;
14259 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14260 			/*
14261 			 * We are here means eager is fine but it can
14262 			 * get a TH_RST at any point between now and till
14263 			 * accept completes and disappear. We need to
14264 			 * ensure that reference to eager is valid after
14265 			 * we get out of eager's perimeter. So we do
14266 			 * an extra refhold.
14267 			 */
14268 			CONN_INC_REF(connp);
14269 
14270 			/*
14271 			 * The listener also exists because of the refhold
14272 			 * done in tcp_conn_request. Its possible that it
14273 			 * might have closed. We will check that once we
14274 			 * get inside listeners context.
14275 			 */
14276 			CONN_INC_REF(listener->tcp_connp);
14277 			if (listener->tcp_connp->conn_sqp ==
14278 			    connp->conn_sqp) {
14279 				tcp_send_conn_ind(listener->tcp_connp, mp,
14280 				    listener->tcp_connp->conn_sqp);
14281 				CONN_DEC_REF(listener->tcp_connp);
14282 			} else if (!tcp->tcp_loopback) {
14283 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14284 				    tcp_send_conn_ind,
14285 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14286 			} else {
14287 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14288 				    tcp_send_conn_ind, listener->tcp_connp,
14289 				    SQTAG_TCP_CONN_IND);
14290 			}
14291 		}
14292 
14293 		if (tcp->tcp_active_open) {
14294 			/*
14295 			 * We are seeing the final ack in the three way
14296 			 * hand shake of a active open'ed connection
14297 			 * so we must send up a T_CONN_CON
14298 			 */
14299 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14300 				freemsg(mp);
14301 				return;
14302 			}
14303 			/*
14304 			 * Don't fuse the loopback endpoints for
14305 			 * simultaneous active opens.
14306 			 */
14307 			if (tcp->tcp_loopback) {
14308 				TCP_STAT(tcps, tcp_fusion_unfusable);
14309 				tcp->tcp_unfusable = B_TRUE;
14310 			}
14311 		}
14312 
14313 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14314 		bytes_acked--;
14315 		/* SYN was acked - making progress */
14316 		if (tcp->tcp_ipversion == IPV6_VERSION)
14317 			tcp->tcp_ip_forward_progress = B_TRUE;
14318 
14319 		/*
14320 		 * If SYN was retransmitted, need to reset all
14321 		 * retransmission info as this segment will be
14322 		 * treated as a dup ACK.
14323 		 */
14324 		if (tcp->tcp_rexmit) {
14325 			tcp->tcp_rexmit = B_FALSE;
14326 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14327 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14328 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14329 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14330 			tcp->tcp_ms_we_have_waited = 0;
14331 			tcp->tcp_cwnd = mss;
14332 		}
14333 
14334 		/*
14335 		 * We set the send window to zero here.
14336 		 * This is needed if there is data to be
14337 		 * processed already on the queue.
14338 		 * Later (at swnd_update label), the
14339 		 * "new_swnd > tcp_swnd" condition is satisfied
14340 		 * the XMIT_NEEDED flag is set in the current
14341 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14342 		 * called if there is already data on queue in
14343 		 * this state.
14344 		 */
14345 		tcp->tcp_swnd = 0;
14346 
14347 		if (new_swnd > tcp->tcp_max_swnd)
14348 			tcp->tcp_max_swnd = new_swnd;
14349 		tcp->tcp_swl1 = seg_seq;
14350 		tcp->tcp_swl2 = seg_ack;
14351 		tcp->tcp_state = TCPS_ESTABLISHED;
14352 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14353 
14354 		/* Fuse when both sides are in ESTABLISHED state */
14355 		if (tcp->tcp_loopback && do_tcp_fusion)
14356 			tcp_fuse(tcp, iphdr, tcph);
14357 
14358 	}
14359 	/* This code follows 4.4BSD-Lite2 mostly. */
14360 	if (bytes_acked < 0)
14361 		goto est;
14362 
14363 	/*
14364 	 * If TCP is ECN capable and the congestion experience bit is
14365 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14366 	 * done once per window (or more loosely, per RTT).
14367 	 */
14368 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14369 		tcp->tcp_cwr = B_FALSE;
14370 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14371 		if (!tcp->tcp_cwr) {
14372 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14373 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14374 			tcp->tcp_cwnd = npkt * mss;
14375 			/*
14376 			 * If the cwnd is 0, use the timer to clock out
14377 			 * new segments.  This is required by the ECN spec.
14378 			 */
14379 			if (npkt == 0) {
14380 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14381 				/*
14382 				 * This makes sure that when the ACK comes
14383 				 * back, we will increase tcp_cwnd by 1 MSS.
14384 				 */
14385 				tcp->tcp_cwnd_cnt = 0;
14386 			}
14387 			tcp->tcp_cwr = B_TRUE;
14388 			/*
14389 			 * This marks the end of the current window of in
14390 			 * flight data.  That is why we don't use
14391 			 * tcp_suna + tcp_swnd.  Only data in flight can
14392 			 * provide ECN info.
14393 			 */
14394 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14395 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14396 		}
14397 	}
14398 
14399 	mp1 = tcp->tcp_xmit_head;
14400 	if (bytes_acked == 0) {
14401 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14402 			int dupack_cnt;
14403 
14404 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14405 			/*
14406 			 * Fast retransmit.  When we have seen exactly three
14407 			 * identical ACKs while we have unacked data
14408 			 * outstanding we take it as a hint that our peer
14409 			 * dropped something.
14410 			 *
14411 			 * If TCP is retransmitting, don't do fast retransmit.
14412 			 */
14413 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14414 			    ! tcp->tcp_rexmit) {
14415 				/* Do Limited Transmit */
14416 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14417 				    tcps->tcps_dupack_fast_retransmit) {
14418 					/*
14419 					 * RFC 3042
14420 					 *
14421 					 * What we need to do is temporarily
14422 					 * increase tcp_cwnd so that new
14423 					 * data can be sent if it is allowed
14424 					 * by the receive window (tcp_rwnd).
14425 					 * tcp_wput_data() will take care of
14426 					 * the rest.
14427 					 *
14428 					 * If the connection is SACK capable,
14429 					 * only do limited xmit when there
14430 					 * is SACK info.
14431 					 *
14432 					 * Note how tcp_cwnd is incremented.
14433 					 * The first dup ACK will increase
14434 					 * it by 1 MSS.  The second dup ACK
14435 					 * will increase it by 2 MSS.  This
14436 					 * means that only 1 new segment will
14437 					 * be sent for each dup ACK.
14438 					 */
14439 					if (tcp->tcp_unsent > 0 &&
14440 					    (!tcp->tcp_snd_sack_ok ||
14441 					    (tcp->tcp_snd_sack_ok &&
14442 					    tcp->tcp_notsack_list != NULL))) {
14443 						tcp->tcp_cwnd += mss <<
14444 						    (tcp->tcp_dupack_cnt - 1);
14445 						flags |= TH_LIMIT_XMIT;
14446 					}
14447 				} else if (dupack_cnt ==
14448 				    tcps->tcps_dupack_fast_retransmit) {
14449 
14450 				/*
14451 				 * If we have reduced tcp_ssthresh
14452 				 * because of ECN, do not reduce it again
14453 				 * unless it is already one window of data
14454 				 * away.  After one window of data, tcp_cwr
14455 				 * should then be cleared.  Note that
14456 				 * for non ECN capable connection, tcp_cwr
14457 				 * should always be false.
14458 				 *
14459 				 * Adjust cwnd since the duplicate
14460 				 * ack indicates that a packet was
14461 				 * dropped (due to congestion.)
14462 				 */
14463 				if (!tcp->tcp_cwr) {
14464 					npkt = ((tcp->tcp_snxt -
14465 					    tcp->tcp_suna) >> 1) / mss;
14466 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14467 					    mss;
14468 					tcp->tcp_cwnd = (npkt +
14469 					    tcp->tcp_dupack_cnt) * mss;
14470 				}
14471 				if (tcp->tcp_ecn_ok) {
14472 					tcp->tcp_cwr = B_TRUE;
14473 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14474 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14475 				}
14476 
14477 				/*
14478 				 * We do Hoe's algorithm.  Refer to her
14479 				 * paper "Improving the Start-up Behavior
14480 				 * of a Congestion Control Scheme for TCP,"
14481 				 * appeared in SIGCOMM'96.
14482 				 *
14483 				 * Save highest seq no we have sent so far.
14484 				 * Be careful about the invisible FIN byte.
14485 				 */
14486 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14487 				    (tcp->tcp_unsent == 0)) {
14488 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14489 				} else {
14490 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14491 				}
14492 
14493 				/*
14494 				 * Do not allow bursty traffic during.
14495 				 * fast recovery.  Refer to Fall and Floyd's
14496 				 * paper "Simulation-based Comparisons of
14497 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14498 				 * This is a best current practise.
14499 				 */
14500 				tcp->tcp_snd_burst = TCP_CWND_SS;
14501 
14502 				/*
14503 				 * For SACK:
14504 				 * Calculate tcp_pipe, which is the
14505 				 * estimated number of bytes in
14506 				 * network.
14507 				 *
14508 				 * tcp_fack is the highest sack'ed seq num
14509 				 * TCP has received.
14510 				 *
14511 				 * tcp_pipe is explained in the above quoted
14512 				 * Fall and Floyd's paper.  tcp_fack is
14513 				 * explained in Mathis and Mahdavi's
14514 				 * "Forward Acknowledgment: Refining TCP
14515 				 * Congestion Control" in SIGCOMM '96.
14516 				 */
14517 				if (tcp->tcp_snd_sack_ok) {
14518 					ASSERT(tcp->tcp_sack_info != NULL);
14519 					if (tcp->tcp_notsack_list != NULL) {
14520 						tcp->tcp_pipe = tcp->tcp_snxt -
14521 						    tcp->tcp_fack;
14522 						tcp->tcp_sack_snxt = seg_ack;
14523 						flags |= TH_NEED_SACK_REXMIT;
14524 					} else {
14525 						/*
14526 						 * Always initialize tcp_pipe
14527 						 * even though we don't have
14528 						 * any SACK info.  If later
14529 						 * we get SACK info and
14530 						 * tcp_pipe is not initialized,
14531 						 * funny things will happen.
14532 						 */
14533 						tcp->tcp_pipe =
14534 						    tcp->tcp_cwnd_ssthresh;
14535 					}
14536 				} else {
14537 					flags |= TH_REXMIT_NEEDED;
14538 				} /* tcp_snd_sack_ok */
14539 
14540 				} else {
14541 					/*
14542 					 * Here we perform congestion
14543 					 * avoidance, but NOT slow start.
14544 					 * This is known as the Fast
14545 					 * Recovery Algorithm.
14546 					 */
14547 					if (tcp->tcp_snd_sack_ok &&
14548 					    tcp->tcp_notsack_list != NULL) {
14549 						flags |= TH_NEED_SACK_REXMIT;
14550 						tcp->tcp_pipe -= mss;
14551 						if (tcp->tcp_pipe < 0)
14552 							tcp->tcp_pipe = 0;
14553 					} else {
14554 					/*
14555 					 * We know that one more packet has
14556 					 * left the pipe thus we can update
14557 					 * cwnd.
14558 					 */
14559 					cwnd = tcp->tcp_cwnd + mss;
14560 					if (cwnd > tcp->tcp_cwnd_max)
14561 						cwnd = tcp->tcp_cwnd_max;
14562 					tcp->tcp_cwnd = cwnd;
14563 					if (tcp->tcp_unsent > 0)
14564 						flags |= TH_XMIT_NEEDED;
14565 					}
14566 				}
14567 			}
14568 		} else if (tcp->tcp_zero_win_probe) {
14569 			/*
14570 			 * If the window has opened, need to arrange
14571 			 * to send additional data.
14572 			 */
14573 			if (new_swnd != 0) {
14574 				/* tcp_suna != tcp_snxt */
14575 				/* Packet contains a window update */
14576 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14577 				tcp->tcp_zero_win_probe = 0;
14578 				tcp->tcp_timer_backoff = 0;
14579 				tcp->tcp_ms_we_have_waited = 0;
14580 
14581 				/*
14582 				 * Transmit starting with tcp_suna since
14583 				 * the one byte probe is not ack'ed.
14584 				 * If TCP has sent more than one identical
14585 				 * probe, tcp_rexmit will be set.  That means
14586 				 * tcp_ss_rexmit() will send out the one
14587 				 * byte along with new data.  Otherwise,
14588 				 * fake the retransmission.
14589 				 */
14590 				flags |= TH_XMIT_NEEDED;
14591 				if (!tcp->tcp_rexmit) {
14592 					tcp->tcp_rexmit = B_TRUE;
14593 					tcp->tcp_dupack_cnt = 0;
14594 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14595 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14596 				}
14597 			}
14598 		}
14599 		goto swnd_update;
14600 	}
14601 
14602 	/*
14603 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14604 	 * If the ACK value acks something that we have not yet sent, it might
14605 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14606 	 * other side.
14607 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14608 	 * state is handled above, so we can always just drop the segment and
14609 	 * send an ACK here.
14610 	 *
14611 	 * Should we send ACKs in response to ACK only segments?
14612 	 */
14613 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14614 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14615 		/* drop the received segment */
14616 		freemsg(mp);
14617 
14618 		/*
14619 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14620 		 * greater than 0, check if the number of such
14621 		 * bogus ACks is greater than that count.  If yes,
14622 		 * don't send back any ACK.  This prevents TCP from
14623 		 * getting into an ACK storm if somehow an attacker
14624 		 * successfully spoofs an acceptable segment to our
14625 		 * peer.
14626 		 */
14627 		if (tcp_drop_ack_unsent_cnt > 0 &&
14628 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14629 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14630 			return;
14631 		}
14632 		mp = tcp_ack_mp(tcp);
14633 		if (mp != NULL) {
14634 			BUMP_LOCAL(tcp->tcp_obsegs);
14635 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14636 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14637 		}
14638 		return;
14639 	}
14640 
14641 	/*
14642 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14643 	 * blocks that are covered by this ACK.
14644 	 */
14645 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14646 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14647 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14648 	}
14649 
14650 	/*
14651 	 * If we got an ACK after fast retransmit, check to see
14652 	 * if it is a partial ACK.  If it is not and the congestion
14653 	 * window was inflated to account for the other side's
14654 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14655 	 */
14656 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14657 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14658 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14659 			tcp->tcp_dupack_cnt = 0;
14660 			/*
14661 			 * Restore the orig tcp_cwnd_ssthresh after
14662 			 * fast retransmit phase.
14663 			 */
14664 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14665 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14666 			}
14667 			tcp->tcp_rexmit_max = seg_ack;
14668 			tcp->tcp_cwnd_cnt = 0;
14669 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14670 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14671 
14672 			/*
14673 			 * Remove all notsack info to avoid confusion with
14674 			 * the next fast retrasnmit/recovery phase.
14675 			 */
14676 			if (tcp->tcp_snd_sack_ok &&
14677 			    tcp->tcp_notsack_list != NULL) {
14678 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14679 			}
14680 		} else {
14681 			if (tcp->tcp_snd_sack_ok &&
14682 			    tcp->tcp_notsack_list != NULL) {
14683 				flags |= TH_NEED_SACK_REXMIT;
14684 				tcp->tcp_pipe -= mss;
14685 				if (tcp->tcp_pipe < 0)
14686 					tcp->tcp_pipe = 0;
14687 			} else {
14688 				/*
14689 				 * Hoe's algorithm:
14690 				 *
14691 				 * Retransmit the unack'ed segment and
14692 				 * restart fast recovery.  Note that we
14693 				 * need to scale back tcp_cwnd to the
14694 				 * original value when we started fast
14695 				 * recovery.  This is to prevent overly
14696 				 * aggressive behaviour in sending new
14697 				 * segments.
14698 				 */
14699 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14700 				    tcps->tcps_dupack_fast_retransmit * mss;
14701 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14702 				flags |= TH_REXMIT_NEEDED;
14703 			}
14704 		}
14705 	} else {
14706 		tcp->tcp_dupack_cnt = 0;
14707 		if (tcp->tcp_rexmit) {
14708 			/*
14709 			 * TCP is retranmitting.  If the ACK ack's all
14710 			 * outstanding data, update tcp_rexmit_max and
14711 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14712 			 * to the correct value.
14713 			 *
14714 			 * Note that SEQ_LEQ() is used.  This is to avoid
14715 			 * unnecessary fast retransmit caused by dup ACKs
14716 			 * received when TCP does slow start retransmission
14717 			 * after a time out.  During this phase, TCP may
14718 			 * send out segments which are already received.
14719 			 * This causes dup ACKs to be sent back.
14720 			 */
14721 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14722 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14723 					tcp->tcp_rexmit_nxt = seg_ack;
14724 				}
14725 				if (seg_ack != tcp->tcp_rexmit_max) {
14726 					flags |= TH_XMIT_NEEDED;
14727 				}
14728 			} else {
14729 				tcp->tcp_rexmit = B_FALSE;
14730 				tcp->tcp_xmit_zc_clean = B_FALSE;
14731 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14732 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14733 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14734 			}
14735 			tcp->tcp_ms_we_have_waited = 0;
14736 		}
14737 	}
14738 
14739 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14740 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14741 	tcp->tcp_suna = seg_ack;
14742 	if (tcp->tcp_zero_win_probe != 0) {
14743 		tcp->tcp_zero_win_probe = 0;
14744 		tcp->tcp_timer_backoff = 0;
14745 	}
14746 
14747 	/*
14748 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14749 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14750 	 * will not reach here.
14751 	 */
14752 	if (mp1 == NULL) {
14753 		goto fin_acked;
14754 	}
14755 
14756 	/*
14757 	 * Update the congestion window.
14758 	 *
14759 	 * If TCP is not ECN capable or TCP is ECN capable but the
14760 	 * congestion experience bit is not set, increase the tcp_cwnd as
14761 	 * usual.
14762 	 */
14763 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14764 		cwnd = tcp->tcp_cwnd;
14765 		add = mss;
14766 
14767 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14768 			/*
14769 			 * This is to prevent an increase of less than 1 MSS of
14770 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14771 			 * may send out tinygrams in order to preserve mblk
14772 			 * boundaries.
14773 			 *
14774 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14775 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14776 			 * increased by 1 MSS for every RTTs.
14777 			 */
14778 			if (tcp->tcp_cwnd_cnt <= 0) {
14779 				tcp->tcp_cwnd_cnt = cwnd + add;
14780 			} else {
14781 				tcp->tcp_cwnd_cnt -= add;
14782 				add = 0;
14783 			}
14784 		}
14785 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14786 	}
14787 
14788 	/* See if the latest urgent data has been acknowledged */
14789 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14790 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14791 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14792 
14793 	/* Can we update the RTT estimates? */
14794 	if (tcp->tcp_snd_ts_ok) {
14795 		/* Ignore zero timestamp echo-reply. */
14796 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14797 			tcp_set_rto(tcp, (int32_t)lbolt -
14798 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14799 		}
14800 
14801 		/* If needed, restart the timer. */
14802 		if (tcp->tcp_set_timer == 1) {
14803 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14804 			tcp->tcp_set_timer = 0;
14805 		}
14806 		/*
14807 		 * Update tcp_csuna in case the other side stops sending
14808 		 * us timestamps.
14809 		 */
14810 		tcp->tcp_csuna = tcp->tcp_snxt;
14811 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14812 		/*
14813 		 * An ACK sequence we haven't seen before, so get the RTT
14814 		 * and update the RTO. But first check if the timestamp is
14815 		 * valid to use.
14816 		 */
14817 		if ((mp1->b_next != NULL) &&
14818 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14819 			tcp_set_rto(tcp, (int32_t)lbolt -
14820 			    (int32_t)(intptr_t)mp1->b_prev);
14821 		else
14822 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14823 
14824 		/* Remeber the last sequence to be ACKed */
14825 		tcp->tcp_csuna = seg_ack;
14826 		if (tcp->tcp_set_timer == 1) {
14827 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14828 			tcp->tcp_set_timer = 0;
14829 		}
14830 	} else {
14831 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14832 	}
14833 
14834 	/* Eat acknowledged bytes off the xmit queue. */
14835 	for (;;) {
14836 		mblk_t	*mp2;
14837 		uchar_t	*wptr;
14838 
14839 		wptr = mp1->b_wptr;
14840 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14841 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14842 		if (bytes_acked < 0) {
14843 			mp1->b_rptr = wptr + bytes_acked;
14844 			/*
14845 			 * Set a new timestamp if all the bytes timed by the
14846 			 * old timestamp have been ack'ed.
14847 			 */
14848 			if (SEQ_GT(seg_ack,
14849 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14850 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14851 				mp1->b_next = NULL;
14852 			}
14853 			break;
14854 		}
14855 		mp1->b_next = NULL;
14856 		mp1->b_prev = NULL;
14857 		mp2 = mp1;
14858 		mp1 = mp1->b_cont;
14859 
14860 		/*
14861 		 * This notification is required for some zero-copy
14862 		 * clients to maintain a copy semantic. After the data
14863 		 * is ack'ed, client is safe to modify or reuse the buffer.
14864 		 */
14865 		if (tcp->tcp_snd_zcopy_aware &&
14866 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14867 			tcp_zcopy_notify(tcp);
14868 		freeb(mp2);
14869 		if (bytes_acked == 0) {
14870 			if (mp1 == NULL) {
14871 				/* Everything is ack'ed, clear the tail. */
14872 				tcp->tcp_xmit_tail = NULL;
14873 				/*
14874 				 * Cancel the timer unless we are still
14875 				 * waiting for an ACK for the FIN packet.
14876 				 */
14877 				if (tcp->tcp_timer_tid != 0 &&
14878 				    tcp->tcp_snxt == tcp->tcp_suna) {
14879 					(void) TCP_TIMER_CANCEL(tcp,
14880 					    tcp->tcp_timer_tid);
14881 					tcp->tcp_timer_tid = 0;
14882 				}
14883 				goto pre_swnd_update;
14884 			}
14885 			if (mp2 != tcp->tcp_xmit_tail)
14886 				break;
14887 			tcp->tcp_xmit_tail = mp1;
14888 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14889 			    (uintptr_t)INT_MAX);
14890 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14891 			    mp1->b_rptr);
14892 			break;
14893 		}
14894 		if (mp1 == NULL) {
14895 			/*
14896 			 * More was acked but there is nothing more
14897 			 * outstanding.  This means that the FIN was
14898 			 * just acked or that we're talking to a clown.
14899 			 */
14900 fin_acked:
14901 			ASSERT(tcp->tcp_fin_sent);
14902 			tcp->tcp_xmit_tail = NULL;
14903 			if (tcp->tcp_fin_sent) {
14904 				/* FIN was acked - making progress */
14905 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14906 				    !tcp->tcp_fin_acked)
14907 					tcp->tcp_ip_forward_progress = B_TRUE;
14908 				tcp->tcp_fin_acked = B_TRUE;
14909 				if (tcp->tcp_linger_tid != 0 &&
14910 				    TCP_TIMER_CANCEL(tcp,
14911 				    tcp->tcp_linger_tid) >= 0) {
14912 					tcp_stop_lingering(tcp);
14913 					freemsg(mp);
14914 					mp = NULL;
14915 				}
14916 			} else {
14917 				/*
14918 				 * We should never get here because
14919 				 * we have already checked that the
14920 				 * number of bytes ack'ed should be
14921 				 * smaller than or equal to what we
14922 				 * have sent so far (it is the
14923 				 * acceptability check of the ACK).
14924 				 * We can only get here if the send
14925 				 * queue is corrupted.
14926 				 *
14927 				 * Terminate the connection and
14928 				 * panic the system.  It is better
14929 				 * for us to panic instead of
14930 				 * continuing to avoid other disaster.
14931 				 */
14932 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14933 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14934 				panic("Memory corruption "
14935 				    "detected for connection %s.",
14936 				    tcp_display(tcp, NULL,
14937 				    DISP_ADDR_AND_PORT));
14938 				/*NOTREACHED*/
14939 			}
14940 			goto pre_swnd_update;
14941 		}
14942 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14943 	}
14944 	if (tcp->tcp_unsent) {
14945 		flags |= TH_XMIT_NEEDED;
14946 	}
14947 pre_swnd_update:
14948 	tcp->tcp_xmit_head = mp1;
14949 swnd_update:
14950 	/*
14951 	 * The following check is different from most other implementations.
14952 	 * For bi-directional transfer, when segments are dropped, the
14953 	 * "normal" check will not accept a window update in those
14954 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14955 	 * segments which are outside receiver's window.  As TCP accepts
14956 	 * the ack in those retransmitted segments, if the window update in
14957 	 * the same segment is not accepted, TCP will incorrectly calculates
14958 	 * that it can send more segments.  This can create a deadlock
14959 	 * with the receiver if its window becomes zero.
14960 	 */
14961 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14962 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14963 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14964 		/*
14965 		 * The criteria for update is:
14966 		 *
14967 		 * 1. the segment acknowledges some data.  Or
14968 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14969 		 * 3. the segment is not old and the advertised window is
14970 		 * larger than the previous advertised window.
14971 		 */
14972 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14973 			flags |= TH_XMIT_NEEDED;
14974 		tcp->tcp_swnd = new_swnd;
14975 		if (new_swnd > tcp->tcp_max_swnd)
14976 			tcp->tcp_max_swnd = new_swnd;
14977 		tcp->tcp_swl1 = seg_seq;
14978 		tcp->tcp_swl2 = seg_ack;
14979 	}
14980 est:
14981 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14982 
14983 		switch (tcp->tcp_state) {
14984 		case TCPS_FIN_WAIT_1:
14985 			if (tcp->tcp_fin_acked) {
14986 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14987 				/*
14988 				 * We implement the non-standard BSD/SunOS
14989 				 * FIN_WAIT_2 flushing algorithm.
14990 				 * If there is no user attached to this
14991 				 * TCP endpoint, then this TCP struct
14992 				 * could hang around forever in FIN_WAIT_2
14993 				 * state if the peer forgets to send us
14994 				 * a FIN.  To prevent this, we wait only
14995 				 * 2*MSL (a convenient time value) for
14996 				 * the FIN to arrive.  If it doesn't show up,
14997 				 * we flush the TCP endpoint.  This algorithm,
14998 				 * though a violation of RFC-793, has worked
14999 				 * for over 10 years in BSD systems.
15000 				 * Note: SunOS 4.x waits 675 seconds before
15001 				 * flushing the FIN_WAIT_2 connection.
15002 				 */
15003 				TCP_TIMER_RESTART(tcp,
15004 				    tcps->tcps_fin_wait_2_flush_interval);
15005 			}
15006 			break;
15007 		case TCPS_FIN_WAIT_2:
15008 			break;	/* Shutdown hook? */
15009 		case TCPS_LAST_ACK:
15010 			freemsg(mp);
15011 			if (tcp->tcp_fin_acked) {
15012 				(void) tcp_clean_death(tcp, 0, 19);
15013 				return;
15014 			}
15015 			goto xmit_check;
15016 		case TCPS_CLOSING:
15017 			if (tcp->tcp_fin_acked) {
15018 				tcp->tcp_state = TCPS_TIME_WAIT;
15019 				/*
15020 				 * Unconditionally clear the exclusive binding
15021 				 * bit so this TIME-WAIT connection won't
15022 				 * interfere with new ones.
15023 				 */
15024 				tcp->tcp_exclbind = 0;
15025 				if (!TCP_IS_DETACHED(tcp)) {
15026 					TCP_TIMER_RESTART(tcp,
15027 					    tcps->tcps_time_wait_interval);
15028 				} else {
15029 					tcp_time_wait_append(tcp);
15030 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15031 				}
15032 			}
15033 			/*FALLTHRU*/
15034 		case TCPS_CLOSE_WAIT:
15035 			freemsg(mp);
15036 			goto xmit_check;
15037 		default:
15038 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
15039 			break;
15040 		}
15041 	}
15042 	if (flags & TH_FIN) {
15043 		/* Make sure we ack the fin */
15044 		flags |= TH_ACK_NEEDED;
15045 		if (!tcp->tcp_fin_rcvd) {
15046 			tcp->tcp_fin_rcvd = B_TRUE;
15047 			tcp->tcp_rnxt++;
15048 			tcph = tcp->tcp_tcph;
15049 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15050 
15051 			/*
15052 			 * Generate the ordrel_ind at the end unless we
15053 			 * are an eager guy.
15054 			 * In the eager case tcp_rsrv will do this when run
15055 			 * after tcp_accept is done.
15056 			 */
15057 			if (tcp->tcp_listener == NULL &&
15058 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
15059 				flags |= TH_ORDREL_NEEDED;
15060 			switch (tcp->tcp_state) {
15061 			case TCPS_SYN_RCVD:
15062 			case TCPS_ESTABLISHED:
15063 				tcp->tcp_state = TCPS_CLOSE_WAIT;
15064 				/* Keepalive? */
15065 				break;
15066 			case TCPS_FIN_WAIT_1:
15067 				if (!tcp->tcp_fin_acked) {
15068 					tcp->tcp_state = TCPS_CLOSING;
15069 					break;
15070 				}
15071 				/* FALLTHRU */
15072 			case TCPS_FIN_WAIT_2:
15073 				tcp->tcp_state = TCPS_TIME_WAIT;
15074 				/*
15075 				 * Unconditionally clear the exclusive binding
15076 				 * bit so this TIME-WAIT connection won't
15077 				 * interfere with new ones.
15078 				 */
15079 				tcp->tcp_exclbind = 0;
15080 				if (!TCP_IS_DETACHED(tcp)) {
15081 					TCP_TIMER_RESTART(tcp,
15082 					    tcps->tcps_time_wait_interval);
15083 				} else {
15084 					tcp_time_wait_append(tcp);
15085 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15086 				}
15087 				if (seg_len) {
15088 					/*
15089 					 * implies data piggybacked on FIN.
15090 					 * break to handle data.
15091 					 */
15092 					break;
15093 				}
15094 				freemsg(mp);
15095 				goto ack_check;
15096 			}
15097 		}
15098 	}
15099 	if (mp == NULL)
15100 		goto xmit_check;
15101 	if (seg_len == 0) {
15102 		freemsg(mp);
15103 		goto xmit_check;
15104 	}
15105 	if (mp->b_rptr == mp->b_wptr) {
15106 		/*
15107 		 * The header has been consumed, so we remove the
15108 		 * zero-length mblk here.
15109 		 */
15110 		mp1 = mp;
15111 		mp = mp->b_cont;
15112 		freeb(mp1);
15113 	}
15114 	tcph = tcp->tcp_tcph;
15115 	tcp->tcp_rack_cnt++;
15116 	{
15117 		uint32_t cur_max;
15118 
15119 		cur_max = tcp->tcp_rack_cur_max;
15120 		if (tcp->tcp_rack_cnt >= cur_max) {
15121 			/*
15122 			 * We have more unacked data than we should - send
15123 			 * an ACK now.
15124 			 */
15125 			flags |= TH_ACK_NEEDED;
15126 			cur_max++;
15127 			if (cur_max > tcp->tcp_rack_abs_max)
15128 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15129 			else
15130 				tcp->tcp_rack_cur_max = cur_max;
15131 		} else if (TCP_IS_DETACHED(tcp)) {
15132 			/* We don't have an ACK timer for detached TCP. */
15133 			flags |= TH_ACK_NEEDED;
15134 		} else if (seg_len < mss) {
15135 			/*
15136 			 * If we get a segment that is less than an mss, and we
15137 			 * already have unacknowledged data, and the amount
15138 			 * unacknowledged is not a multiple of mss, then we
15139 			 * better generate an ACK now.  Otherwise, this may be
15140 			 * the tail piece of a transaction, and we would rather
15141 			 * wait for the response.
15142 			 */
15143 			uint32_t udif;
15144 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15145 			    (uintptr_t)INT_MAX);
15146 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15147 			if (udif && (udif % mss))
15148 				flags |= TH_ACK_NEEDED;
15149 			else
15150 				flags |= TH_ACK_TIMER_NEEDED;
15151 		} else {
15152 			/* Start delayed ack timer */
15153 			flags |= TH_ACK_TIMER_NEEDED;
15154 		}
15155 	}
15156 	tcp->tcp_rnxt += seg_len;
15157 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15158 
15159 	/* Update SACK list */
15160 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15161 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15162 		    &(tcp->tcp_num_sack_blk));
15163 	}
15164 
15165 	if (tcp->tcp_urp_mp) {
15166 		tcp->tcp_urp_mp->b_cont = mp;
15167 		mp = tcp->tcp_urp_mp;
15168 		tcp->tcp_urp_mp = NULL;
15169 		/* Ready for a new signal. */
15170 		tcp->tcp_urp_last_valid = B_FALSE;
15171 #ifdef DEBUG
15172 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15173 		    "tcp_rput: sending exdata_ind %s",
15174 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15175 #endif /* DEBUG */
15176 	}
15177 
15178 	/*
15179 	 * Check for ancillary data changes compared to last segment.
15180 	 */
15181 	if (tcp->tcp_ipv6_recvancillary != 0) {
15182 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15183 		ASSERT(mp != NULL);
15184 	}
15185 
15186 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15187 		/*
15188 		 * Side queue inbound data until the accept happens.
15189 		 * tcp_accept/tcp_rput drains this when the accept happens.
15190 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15191 		 * T_EXDATA_IND) it is queued on b_next.
15192 		 * XXX Make urgent data use this. Requires:
15193 		 *	Removing tcp_listener check for TH_URG
15194 		 *	Making M_PCPROTO and MARK messages skip the eager case
15195 		 */
15196 
15197 		if (tcp->tcp_kssl_pending) {
15198 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15199 			    mblk_t *, mp);
15200 			tcp_kssl_input(tcp, mp);
15201 		} else {
15202 			tcp_rcv_enqueue(tcp, mp, seg_len);
15203 		}
15204 	} else {
15205 		sodirect_t	*sodp = tcp->tcp_sodirect;
15206 
15207 		/*
15208 		 * If an sodirect connection and an enabled sodirect_t then
15209 		 * sodp will be set to point to the tcp_t/sonode_t shared
15210 		 * sodirect_t and the sodirect_t's lock will be held.
15211 		 */
15212 		if (sodp != NULL) {
15213 			mutex_enter(sodp->sod_lockp);
15214 			if (!(sodp->sod_state & SOD_ENABLED) ||
15215 			    (tcp->tcp_kssl_ctx != NULL &&
15216 			    DB_TYPE(mp) == M_DATA)) {
15217 				mutex_exit(sodp->sod_lockp);
15218 				sodp = NULL;
15219 			}
15220 		}
15221 		if (mp->b_datap->db_type != M_DATA ||
15222 		    (flags & TH_MARKNEXT_NEEDED)) {
15223 			if (sodp != NULL) {
15224 				if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15225 					sodp->sod_uioa.uioa_state &= UIOA_CLR;
15226 					sodp->sod_uioa.uioa_state |= UIOA_FINI;
15227 				}
15228 				if (!SOD_QEMPTY(sodp) &&
15229 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15230 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15231 					/* sod_wakeup() did the mutex_exit() */
15232 				} else {
15233 					mutex_exit(sodp->sod_lockp);
15234 				}
15235 			} else if (tcp->tcp_rcv_list != NULL) {
15236 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15237 			}
15238 			ASSERT(tcp->tcp_rcv_list == NULL ||
15239 			    tcp->tcp_fused_sigurg);
15240 
15241 			if (flags & TH_MARKNEXT_NEEDED) {
15242 #ifdef DEBUG
15243 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15244 				    "tcp_rput: sending MSGMARKNEXT %s",
15245 				    tcp_display(tcp, NULL,
15246 				    DISP_PORT_ONLY));
15247 #endif /* DEBUG */
15248 				mp->b_flag |= MSGMARKNEXT;
15249 				flags &= ~TH_MARKNEXT_NEEDED;
15250 			}
15251 
15252 			/* Does this need SSL processing first? */
15253 			if ((tcp->tcp_kssl_ctx != NULL) &&
15254 			    (DB_TYPE(mp) == M_DATA)) {
15255 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15256 				    mblk_t *, mp);
15257 				tcp_kssl_input(tcp, mp);
15258 			} else {
15259 				putnext(tcp->tcp_rq, mp);
15260 				if (!canputnext(tcp->tcp_rq))
15261 					tcp->tcp_rwnd -= seg_len;
15262 			}
15263 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15264 		    (DB_TYPE(mp) == M_DATA)) {
15265 			/* Do SSL processing first */
15266 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2,
15267 			    mblk_t *, mp);
15268 			tcp_kssl_input(tcp, mp);
15269 		} else if (sodp != NULL) {
15270 			/*
15271 			 * Sodirect so all mblk_t's are queued on the
15272 			 * socket directly, check for wakeup of blocked
15273 			 * reader (if any), and last if flow-controled.
15274 			 */
15275 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15276 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15277 			    (flags & (TH_PUSH|TH_FIN))) {
15278 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15279 				/* sod_wakeup() did the mutex_exit() */
15280 			} else {
15281 				if (SOD_QFULL(sodp)) {
15282 					/* Q is full, need backenable */
15283 					SOD_QSETBE(sodp);
15284 				}
15285 				mutex_exit(sodp->sod_lockp);
15286 			}
15287 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15288 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
15289 			if (tcp->tcp_rcv_list != NULL) {
15290 				/*
15291 				 * Enqueue the new segment first and then
15292 				 * call tcp_rcv_drain() to send all data
15293 				 * up.  The other way to do this is to
15294 				 * send all queued data up and then call
15295 				 * putnext() to send the new segment up.
15296 				 * This way can remove the else part later
15297 				 * on.
15298 				 *
15299 				 * We don't this to avoid one more call to
15300 				 * canputnext() as tcp_rcv_drain() needs to
15301 				 * call canputnext().
15302 				 */
15303 				tcp_rcv_enqueue(tcp, mp, seg_len);
15304 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15305 			} else {
15306 				putnext(tcp->tcp_rq, mp);
15307 				if (!canputnext(tcp->tcp_rq))
15308 					tcp->tcp_rwnd -= seg_len;
15309 			}
15310 		} else {
15311 			/*
15312 			 * Enqueue all packets when processing an mblk
15313 			 * from the co queue and also enqueue normal packets.
15314 			 */
15315 			tcp_rcv_enqueue(tcp, mp, seg_len);
15316 		}
15317 		/*
15318 		 * Make sure the timer is running if we have data waiting
15319 		 * for a push bit. This provides resiliency against
15320 		 * implementations that do not correctly generate push bits.
15321 		 *
15322 		 * Note, for sodirect if Q isn't empty and there's not a
15323 		 * pending wakeup then we need a timer. Also note that sodp
15324 		 * is assumed to be still valid after exit()ing the sod_lockp
15325 		 * above and while the SOD state can change it can only change
15326 		 * such that the Q is empty now even though data was added
15327 		 * above.
15328 		 */
15329 		if (((sodp != NULL && !SOD_QEMPTY(sodp) &&
15330 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15331 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15332 		    tcp->tcp_push_tid == 0) {
15333 			/*
15334 			 * The connection may be closed at this point, so don't
15335 			 * do anything for a detached tcp.
15336 			 */
15337 			if (!TCP_IS_DETACHED(tcp))
15338 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15339 				    tcp_push_timer,
15340 				    MSEC_TO_TICK(
15341 				    tcps->tcps_push_timer_interval));
15342 		}
15343 	}
15344 
15345 xmit_check:
15346 	/* Is there anything left to do? */
15347 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15348 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15349 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15350 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15351 		goto done;
15352 
15353 	/* Any transmit work to do and a non-zero window? */
15354 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15355 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15356 		if (flags & TH_REXMIT_NEEDED) {
15357 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15358 
15359 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15360 			if (snd_size > mss)
15361 				snd_size = mss;
15362 			if (snd_size > tcp->tcp_swnd)
15363 				snd_size = tcp->tcp_swnd;
15364 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15365 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15366 			    B_TRUE);
15367 
15368 			if (mp1 != NULL) {
15369 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15370 				tcp->tcp_csuna = tcp->tcp_snxt;
15371 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15372 				UPDATE_MIB(&tcps->tcps_mib,
15373 				    tcpRetransBytes, snd_size);
15374 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15375 			}
15376 		}
15377 		if (flags & TH_NEED_SACK_REXMIT) {
15378 			tcp_sack_rxmit(tcp, &flags);
15379 		}
15380 		/*
15381 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15382 		 * out new segment.  Note that tcp_rexmit should not be
15383 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15384 		 */
15385 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15386 			if (!tcp->tcp_rexmit) {
15387 				tcp_wput_data(tcp, NULL, B_FALSE);
15388 			} else {
15389 				tcp_ss_rexmit(tcp);
15390 			}
15391 		}
15392 		/*
15393 		 * Adjust tcp_cwnd back to normal value after sending
15394 		 * new data segments.
15395 		 */
15396 		if (flags & TH_LIMIT_XMIT) {
15397 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15398 			/*
15399 			 * This will restart the timer.  Restarting the
15400 			 * timer is used to avoid a timeout before the
15401 			 * limited transmitted segment's ACK gets back.
15402 			 */
15403 			if (tcp->tcp_xmit_head != NULL)
15404 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15405 		}
15406 
15407 		/* Anything more to do? */
15408 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15409 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15410 			goto done;
15411 	}
15412 ack_check:
15413 	if (flags & TH_SEND_URP_MARK) {
15414 		ASSERT(tcp->tcp_urp_mark_mp);
15415 		/*
15416 		 * Send up any queued data and then send the mark message
15417 		 */
15418 		sodirect_t *sodp;
15419 
15420 		SOD_PTR_ENTER(tcp, sodp);
15421 
15422 		mp1 = tcp->tcp_urp_mark_mp;
15423 		tcp->tcp_urp_mark_mp = NULL;
15424 		if (sodp != NULL) {
15425 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15426 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15427 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15428 			}
15429 			ASSERT(tcp->tcp_rcv_list == NULL);
15430 
15431 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15432 			/* sod_wakeup() does the mutex_exit() */
15433 		} else if (tcp->tcp_rcv_list != NULL) {
15434 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15435 
15436 			ASSERT(tcp->tcp_rcv_list == NULL ||
15437 			    tcp->tcp_fused_sigurg);
15438 
15439 		}
15440 		putnext(tcp->tcp_rq, mp1);
15441 #ifdef DEBUG
15442 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15443 		    "tcp_rput: sending zero-length %s %s",
15444 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15445 		    "MSGNOTMARKNEXT"),
15446 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15447 #endif /* DEBUG */
15448 		flags &= ~TH_SEND_URP_MARK;
15449 	}
15450 	if (flags & TH_ACK_NEEDED) {
15451 		/*
15452 		 * Time to send an ack for some reason.
15453 		 */
15454 		mp1 = tcp_ack_mp(tcp);
15455 
15456 		if (mp1 != NULL) {
15457 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15458 			BUMP_LOCAL(tcp->tcp_obsegs);
15459 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15460 		}
15461 		if (tcp->tcp_ack_tid != 0) {
15462 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15463 			tcp->tcp_ack_tid = 0;
15464 		}
15465 	}
15466 	if (flags & TH_ACK_TIMER_NEEDED) {
15467 		/*
15468 		 * Arrange for deferred ACK or push wait timeout.
15469 		 * Start timer if it is not already running.
15470 		 */
15471 		if (tcp->tcp_ack_tid == 0) {
15472 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15473 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15474 			    (clock_t)tcps->tcps_local_dack_interval :
15475 			    (clock_t)tcps->tcps_deferred_ack_interval));
15476 		}
15477 	}
15478 	if (flags & TH_ORDREL_NEEDED) {
15479 		/*
15480 		 * Send up the ordrel_ind unless we are an eager guy.
15481 		 * In the eager case tcp_rsrv will do this when run
15482 		 * after tcp_accept is done.
15483 		 */
15484 		sodirect_t *sodp;
15485 
15486 		ASSERT(tcp->tcp_listener == NULL);
15487 
15488 		SOD_PTR_ENTER(tcp, sodp);
15489 		if (sodp != NULL) {
15490 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15491 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15492 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15493 			}
15494 			/* No more sodirect */
15495 			tcp->tcp_sodirect = NULL;
15496 			if (!SOD_QEMPTY(sodp)) {
15497 				/* Mblk(s) to process, notify */
15498 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15499 				/* sod_wakeup() does the mutex_exit() */
15500 			} else {
15501 				/* Nothing to process */
15502 				mutex_exit(sodp->sod_lockp);
15503 			}
15504 		} else if (tcp->tcp_rcv_list != NULL) {
15505 			/*
15506 			 * Push any mblk(s) enqueued from co processing.
15507 			 */
15508 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15509 
15510 			ASSERT(tcp->tcp_rcv_list == NULL ||
15511 			    tcp->tcp_fused_sigurg);
15512 		}
15513 
15514 		mp1 = tcp->tcp_ordrel_mp;
15515 		tcp->tcp_ordrel_mp = NULL;
15516 		tcp->tcp_ordrel_done = B_TRUE;
15517 		putnext(tcp->tcp_rq, mp1);
15518 	}
15519 done:
15520 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15521 }
15522 
15523 /*
15524  * This function does PAWS protection check. Returns B_TRUE if the
15525  * segment passes the PAWS test, else returns B_FALSE.
15526  */
15527 boolean_t
15528 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15529 {
15530 	uint8_t	flags;
15531 	int	options;
15532 	uint8_t *up;
15533 
15534 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15535 	/*
15536 	 * If timestamp option is aligned nicely, get values inline,
15537 	 * otherwise call general routine to parse.  Only do that
15538 	 * if timestamp is the only option.
15539 	 */
15540 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15541 	    TCPOPT_REAL_TS_LEN &&
15542 	    OK_32PTR((up = ((uint8_t *)tcph) +
15543 	    TCP_MIN_HEADER_LENGTH)) &&
15544 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15545 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15546 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15547 
15548 		options = TCP_OPT_TSTAMP_PRESENT;
15549 	} else {
15550 		if (tcp->tcp_snd_sack_ok) {
15551 			tcpoptp->tcp = tcp;
15552 		} else {
15553 			tcpoptp->tcp = NULL;
15554 		}
15555 		options = tcp_parse_options(tcph, tcpoptp);
15556 	}
15557 
15558 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15559 		/*
15560 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15561 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15562 		 */
15563 		if ((flags & TH_RST) == 0 &&
15564 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15565 		    tcp->tcp_ts_recent)) {
15566 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15567 			    PAWS_TIMEOUT)) {
15568 				/* This segment is not acceptable. */
15569 				return (B_FALSE);
15570 			} else {
15571 				/*
15572 				 * Connection has been idle for
15573 				 * too long.  Reset the timestamp
15574 				 * and assume the segment is valid.
15575 				 */
15576 				tcp->tcp_ts_recent =
15577 				    tcpoptp->tcp_opt_ts_val;
15578 			}
15579 		}
15580 	} else {
15581 		/*
15582 		 * If we don't get a timestamp on every packet, we
15583 		 * figure we can't really trust 'em, so we stop sending
15584 		 * and parsing them.
15585 		 */
15586 		tcp->tcp_snd_ts_ok = B_FALSE;
15587 
15588 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15589 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15590 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15591 		/*
15592 		 * Adjust the tcp_mss accordingly. We also need to
15593 		 * adjust tcp_cwnd here in accordance with the new mss.
15594 		 * But we avoid doing a slow start here so as to not
15595 		 * to lose on the transfer rate built up so far.
15596 		 */
15597 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15598 		if (tcp->tcp_snd_sack_ok) {
15599 			ASSERT(tcp->tcp_sack_info != NULL);
15600 			tcp->tcp_max_sack_blk = 4;
15601 		}
15602 	}
15603 	return (B_TRUE);
15604 }
15605 
15606 /*
15607  * Attach ancillary data to a received TCP segments for the
15608  * ancillary pieces requested by the application that are
15609  * different than they were in the previous data segment.
15610  *
15611  * Save the "current" values once memory allocation is ok so that
15612  * when memory allocation fails we can just wait for the next data segment.
15613  */
15614 static mblk_t *
15615 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15616 {
15617 	struct T_optdata_ind *todi;
15618 	int optlen;
15619 	uchar_t *optptr;
15620 	struct T_opthdr *toh;
15621 	uint_t addflag;	/* Which pieces to add */
15622 	mblk_t *mp1;
15623 
15624 	optlen = 0;
15625 	addflag = 0;
15626 	/* If app asked for pktinfo and the index has changed ... */
15627 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15628 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15629 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15630 		optlen += sizeof (struct T_opthdr) +
15631 		    sizeof (struct in6_pktinfo);
15632 		addflag |= TCP_IPV6_RECVPKTINFO;
15633 	}
15634 	/* If app asked for hoplimit and it has changed ... */
15635 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15636 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15637 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15638 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15639 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15640 	}
15641 	/* If app asked for tclass and it has changed ... */
15642 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15643 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15644 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15645 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15646 		addflag |= TCP_IPV6_RECVTCLASS;
15647 	}
15648 	/*
15649 	 * If app asked for hopbyhop headers and it has changed ...
15650 	 * For security labels, note that (1) security labels can't change on
15651 	 * a connected socket at all, (2) we're connected to at most one peer,
15652 	 * (3) if anything changes, then it must be some other extra option.
15653 	 */
15654 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15655 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15656 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15657 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15658 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15659 		    tcp->tcp_label_len;
15660 		addflag |= TCP_IPV6_RECVHOPOPTS;
15661 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15662 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15663 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15664 			return (mp);
15665 	}
15666 	/* If app asked for dst headers before routing headers ... */
15667 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15668 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15669 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15670 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15671 		optlen += sizeof (struct T_opthdr) +
15672 		    ipp->ipp_rtdstoptslen;
15673 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15674 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15675 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15676 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15677 			return (mp);
15678 	}
15679 	/* If app asked for routing headers and it has changed ... */
15680 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15681 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15682 	    (ipp->ipp_fields & IPPF_RTHDR),
15683 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15684 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15685 		addflag |= TCP_IPV6_RECVRTHDR;
15686 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15687 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15688 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15689 			return (mp);
15690 	}
15691 	/* If app asked for dest headers and it has changed ... */
15692 	if ((tcp->tcp_ipv6_recvancillary &
15693 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15694 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15695 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15696 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15697 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15698 		addflag |= TCP_IPV6_RECVDSTOPTS;
15699 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15700 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15701 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15702 			return (mp);
15703 	}
15704 
15705 	if (optlen == 0) {
15706 		/* Nothing to add */
15707 		return (mp);
15708 	}
15709 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15710 	if (mp1 == NULL) {
15711 		/*
15712 		 * Defer sending ancillary data until the next TCP segment
15713 		 * arrives.
15714 		 */
15715 		return (mp);
15716 	}
15717 	mp1->b_cont = mp;
15718 	mp = mp1;
15719 	mp->b_wptr += sizeof (*todi) + optlen;
15720 	mp->b_datap->db_type = M_PROTO;
15721 	todi = (struct T_optdata_ind *)mp->b_rptr;
15722 	todi->PRIM_type = T_OPTDATA_IND;
15723 	todi->DATA_flag = 1;	/* MORE data */
15724 	todi->OPT_length = optlen;
15725 	todi->OPT_offset = sizeof (*todi);
15726 	optptr = (uchar_t *)&todi[1];
15727 	/*
15728 	 * If app asked for pktinfo and the index has changed ...
15729 	 * Note that the local address never changes for the connection.
15730 	 */
15731 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15732 		struct in6_pktinfo *pkti;
15733 
15734 		toh = (struct T_opthdr *)optptr;
15735 		toh->level = IPPROTO_IPV6;
15736 		toh->name = IPV6_PKTINFO;
15737 		toh->len = sizeof (*toh) + sizeof (*pkti);
15738 		toh->status = 0;
15739 		optptr += sizeof (*toh);
15740 		pkti = (struct in6_pktinfo *)optptr;
15741 		if (tcp->tcp_ipversion == IPV6_VERSION)
15742 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15743 		else
15744 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15745 			    &pkti->ipi6_addr);
15746 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15747 		optptr += sizeof (*pkti);
15748 		ASSERT(OK_32PTR(optptr));
15749 		/* Save as "last" value */
15750 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15751 	}
15752 	/* If app asked for hoplimit and it has changed ... */
15753 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15754 		toh = (struct T_opthdr *)optptr;
15755 		toh->level = IPPROTO_IPV6;
15756 		toh->name = IPV6_HOPLIMIT;
15757 		toh->len = sizeof (*toh) + sizeof (uint_t);
15758 		toh->status = 0;
15759 		optptr += sizeof (*toh);
15760 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15761 		optptr += sizeof (uint_t);
15762 		ASSERT(OK_32PTR(optptr));
15763 		/* Save as "last" value */
15764 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15765 	}
15766 	/* If app asked for tclass and it has changed ... */
15767 	if (addflag & TCP_IPV6_RECVTCLASS) {
15768 		toh = (struct T_opthdr *)optptr;
15769 		toh->level = IPPROTO_IPV6;
15770 		toh->name = IPV6_TCLASS;
15771 		toh->len = sizeof (*toh) + sizeof (uint_t);
15772 		toh->status = 0;
15773 		optptr += sizeof (*toh);
15774 		*(uint_t *)optptr = ipp->ipp_tclass;
15775 		optptr += sizeof (uint_t);
15776 		ASSERT(OK_32PTR(optptr));
15777 		/* Save as "last" value */
15778 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15779 	}
15780 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15781 		toh = (struct T_opthdr *)optptr;
15782 		toh->level = IPPROTO_IPV6;
15783 		toh->name = IPV6_HOPOPTS;
15784 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15785 		    tcp->tcp_label_len;
15786 		toh->status = 0;
15787 		optptr += sizeof (*toh);
15788 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15789 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15790 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15791 		ASSERT(OK_32PTR(optptr));
15792 		/* Save as last value */
15793 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15794 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15795 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15796 	}
15797 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15798 		toh = (struct T_opthdr *)optptr;
15799 		toh->level = IPPROTO_IPV6;
15800 		toh->name = IPV6_RTHDRDSTOPTS;
15801 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15802 		toh->status = 0;
15803 		optptr += sizeof (*toh);
15804 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15805 		optptr += ipp->ipp_rtdstoptslen;
15806 		ASSERT(OK_32PTR(optptr));
15807 		/* Save as last value */
15808 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15809 		    &tcp->tcp_rtdstoptslen,
15810 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15811 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15812 	}
15813 	if (addflag & TCP_IPV6_RECVRTHDR) {
15814 		toh = (struct T_opthdr *)optptr;
15815 		toh->level = IPPROTO_IPV6;
15816 		toh->name = IPV6_RTHDR;
15817 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15818 		toh->status = 0;
15819 		optptr += sizeof (*toh);
15820 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15821 		optptr += ipp->ipp_rthdrlen;
15822 		ASSERT(OK_32PTR(optptr));
15823 		/* Save as last value */
15824 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15825 		    (ipp->ipp_fields & IPPF_RTHDR),
15826 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15827 	}
15828 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15829 		toh = (struct T_opthdr *)optptr;
15830 		toh->level = IPPROTO_IPV6;
15831 		toh->name = IPV6_DSTOPTS;
15832 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15833 		toh->status = 0;
15834 		optptr += sizeof (*toh);
15835 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15836 		optptr += ipp->ipp_dstoptslen;
15837 		ASSERT(OK_32PTR(optptr));
15838 		/* Save as last value */
15839 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15840 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15841 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15842 	}
15843 	ASSERT(optptr == mp->b_wptr);
15844 	return (mp);
15845 }
15846 
15847 
15848 /*
15849  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15850  * or a "bad" IRE detected by tcp_adapt_ire.
15851  * We can't tell if the failure was due to the laddr or the faddr
15852  * thus we clear out all addresses and ports.
15853  */
15854 static void
15855 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15856 {
15857 	queue_t	*q = tcp->tcp_rq;
15858 	tcph_t	*tcph;
15859 	struct T_error_ack *tea;
15860 	conn_t	*connp = tcp->tcp_connp;
15861 
15862 
15863 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15864 
15865 	if (mp->b_cont) {
15866 		freemsg(mp->b_cont);
15867 		mp->b_cont = NULL;
15868 	}
15869 	tea = (struct T_error_ack *)mp->b_rptr;
15870 	switch (tea->PRIM_type) {
15871 	case T_BIND_ACK:
15872 		/*
15873 		 * Need to unbind with classifier since we were just told that
15874 		 * our bind succeeded.
15875 		 */
15876 		tcp->tcp_hard_bound = B_FALSE;
15877 		tcp->tcp_hard_binding = B_FALSE;
15878 
15879 		ipcl_hash_remove(connp);
15880 		/* Reuse the mblk if possible */
15881 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15882 		    sizeof (*tea));
15883 		mp->b_rptr = mp->b_datap->db_base;
15884 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15885 		tea = (struct T_error_ack *)mp->b_rptr;
15886 		tea->PRIM_type = T_ERROR_ACK;
15887 		tea->TLI_error = TSYSERR;
15888 		tea->UNIX_error = error;
15889 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15890 			tea->ERROR_prim = T_CONN_REQ;
15891 		} else {
15892 			tea->ERROR_prim = O_T_BIND_REQ;
15893 		}
15894 		break;
15895 
15896 	case T_ERROR_ACK:
15897 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15898 			tea->ERROR_prim = T_CONN_REQ;
15899 		break;
15900 	default:
15901 		panic("tcp_bind_failed: unexpected TPI type");
15902 		/*NOTREACHED*/
15903 	}
15904 
15905 	tcp->tcp_state = TCPS_IDLE;
15906 	if (tcp->tcp_ipversion == IPV4_VERSION)
15907 		tcp->tcp_ipha->ipha_src = 0;
15908 	else
15909 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15910 	/*
15911 	 * Copy of the src addr. in tcp_t is needed since
15912 	 * the lookup funcs. can only look at tcp_t
15913 	 */
15914 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15915 
15916 	tcph = tcp->tcp_tcph;
15917 	tcph->th_lport[0] = 0;
15918 	tcph->th_lport[1] = 0;
15919 	tcp_bind_hash_remove(tcp);
15920 	bzero(&connp->u_port, sizeof (connp->u_port));
15921 	/* blow away saved option results if any */
15922 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15923 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15924 
15925 	conn_delete_ire(tcp->tcp_connp, NULL);
15926 	putnext(q, mp);
15927 }
15928 
15929 /*
15930  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15931  * messages.
15932  */
15933 void
15934 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15935 {
15936 	mblk_t	*mp1;
15937 	uchar_t	*rptr = mp->b_rptr;
15938 	queue_t	*q = tcp->tcp_rq;
15939 	struct T_error_ack *tea;
15940 	uint32_t mss;
15941 	mblk_t *syn_mp;
15942 	mblk_t *mdti;
15943 	mblk_t *lsoi;
15944 	int	retval;
15945 	mblk_t *ire_mp;
15946 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15947 
15948 	switch (mp->b_datap->db_type) {
15949 	case M_PROTO:
15950 	case M_PCPROTO:
15951 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15952 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15953 			break;
15954 		tea = (struct T_error_ack *)rptr;
15955 		switch (tea->PRIM_type) {
15956 		case T_BIND_ACK:
15957 			/*
15958 			 * Adapt Multidata information, if any.  The
15959 			 * following tcp_mdt_update routine will free
15960 			 * the message.
15961 			 */
15962 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15963 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15964 				    b_rptr)->mdt_capab, B_TRUE);
15965 				freemsg(mdti);
15966 			}
15967 
15968 			/*
15969 			 * Check to update LSO information with tcp, and
15970 			 * tcp_lso_update routine will free the message.
15971 			 */
15972 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
15973 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
15974 				    b_rptr)->lso_capab);
15975 				freemsg(lsoi);
15976 			}
15977 
15978 			/* Get the IRE, if we had requested for it */
15979 			ire_mp = tcp_ire_mp(mp);
15980 
15981 			if (tcp->tcp_hard_binding) {
15982 				tcp->tcp_hard_binding = B_FALSE;
15983 				tcp->tcp_hard_bound = B_TRUE;
15984 				CL_INET_CONNECT(tcp);
15985 			} else {
15986 				if (ire_mp != NULL)
15987 					freeb(ire_mp);
15988 				goto after_syn_sent;
15989 			}
15990 
15991 			retval = tcp_adapt_ire(tcp, ire_mp);
15992 			if (ire_mp != NULL)
15993 				freeb(ire_mp);
15994 			if (retval == 0) {
15995 				tcp_bind_failed(tcp, mp,
15996 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15997 				    ENETUNREACH : EADDRNOTAVAIL));
15998 				return;
15999 			}
16000 			/*
16001 			 * Don't let an endpoint connect to itself.
16002 			 * Also checked in tcp_connect() but that
16003 			 * check can't handle the case when the
16004 			 * local IP address is INADDR_ANY.
16005 			 */
16006 			if (tcp->tcp_ipversion == IPV4_VERSION) {
16007 				if ((tcp->tcp_ipha->ipha_dst ==
16008 				    tcp->tcp_ipha->ipha_src) &&
16009 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16010 				    tcp->tcp_tcph->th_fport))) {
16011 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16012 					return;
16013 				}
16014 			} else {
16015 				if (IN6_ARE_ADDR_EQUAL(
16016 				    &tcp->tcp_ip6h->ip6_dst,
16017 				    &tcp->tcp_ip6h->ip6_src) &&
16018 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16019 				    tcp->tcp_tcph->th_fport))) {
16020 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16021 					return;
16022 				}
16023 			}
16024 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
16025 			/*
16026 			 * This should not be possible!  Just for
16027 			 * defensive coding...
16028 			 */
16029 			if (tcp->tcp_state != TCPS_SYN_SENT)
16030 				goto after_syn_sent;
16031 
16032 			if (is_system_labeled() &&
16033 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
16034 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
16035 				return;
16036 			}
16037 
16038 			ASSERT(q == tcp->tcp_rq);
16039 			/*
16040 			 * tcp_adapt_ire() does not adjust
16041 			 * for TCP/IP header length.
16042 			 */
16043 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
16044 
16045 			/*
16046 			 * Just make sure our rwnd is at
16047 			 * least tcp_recv_hiwat_mss * MSS
16048 			 * large, and round up to the nearest
16049 			 * MSS.
16050 			 *
16051 			 * We do the round up here because
16052 			 * we need to get the interface
16053 			 * MTU first before we can do the
16054 			 * round up.
16055 			 */
16056 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
16057 			    tcps->tcps_recv_hiwat_minmss * mss);
16058 			q->q_hiwat = tcp->tcp_rwnd;
16059 			tcp_set_ws_value(tcp);
16060 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
16061 			    tcp->tcp_tcph->th_win);
16062 			if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
16063 				tcp->tcp_snd_ws_ok = B_TRUE;
16064 
16065 			/*
16066 			 * Set tcp_snd_ts_ok to true
16067 			 * so that tcp_xmit_mp will
16068 			 * include the timestamp
16069 			 * option in the SYN segment.
16070 			 */
16071 			if (tcps->tcps_tstamp_always ||
16072 			    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
16073 				tcp->tcp_snd_ts_ok = B_TRUE;
16074 			}
16075 
16076 			/*
16077 			 * tcp_snd_sack_ok can be set in
16078 			 * tcp_adapt_ire() if the sack metric
16079 			 * is set.  So check it here also.
16080 			 */
16081 			if (tcps->tcps_sack_permitted == 2 ||
16082 			    tcp->tcp_snd_sack_ok) {
16083 				if (tcp->tcp_sack_info == NULL) {
16084 					tcp->tcp_sack_info =
16085 					    kmem_cache_alloc(
16086 					    tcp_sack_info_cache,
16087 					    KM_SLEEP);
16088 				}
16089 				tcp->tcp_snd_sack_ok = B_TRUE;
16090 			}
16091 
16092 			/*
16093 			 * Should we use ECN?  Note that the current
16094 			 * default value (SunOS 5.9) of tcp_ecn_permitted
16095 			 * is 1.  The reason for doing this is that there
16096 			 * are equipments out there that will drop ECN
16097 			 * enabled IP packets.  Setting it to 1 avoids
16098 			 * compatibility problems.
16099 			 */
16100 			if (tcps->tcps_ecn_permitted == 2)
16101 				tcp->tcp_ecn_ok = B_TRUE;
16102 
16103 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16104 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
16105 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
16106 			if (syn_mp) {
16107 				cred_t *cr;
16108 				pid_t pid;
16109 
16110 				/*
16111 				 * Obtain the credential from the
16112 				 * thread calling connect(); the credential
16113 				 * lives on in the second mblk which
16114 				 * originated from T_CONN_REQ and is echoed
16115 				 * with the T_BIND_ACK from ip.  If none
16116 				 * can be found, default to the creator
16117 				 * of the socket.
16118 				 */
16119 				if (mp->b_cont == NULL ||
16120 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
16121 					cr = tcp->tcp_cred;
16122 					pid = tcp->tcp_cpid;
16123 				} else {
16124 					pid = DB_CPID(mp->b_cont);
16125 				}
16126 				mblk_setcred(syn_mp, cr);
16127 				DB_CPID(syn_mp) = pid;
16128 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
16129 			}
16130 		after_syn_sent:
16131 			/*
16132 			 * A trailer mblk indicates a waiting client upstream.
16133 			 * We complete here the processing begun in
16134 			 * either tcp_bind() or tcp_connect() by passing
16135 			 * upstream the reply message they supplied.
16136 			 */
16137 			mp1 = mp;
16138 			mp = mp->b_cont;
16139 			freeb(mp1);
16140 			if (mp)
16141 				break;
16142 			return;
16143 		case T_ERROR_ACK:
16144 			if (tcp->tcp_debug) {
16145 				(void) strlog(TCP_MOD_ID, 0, 1,
16146 				    SL_TRACE|SL_ERROR,
16147 				    "tcp_rput_other: case T_ERROR_ACK, "
16148 				    "ERROR_prim == %d",
16149 				    tea->ERROR_prim);
16150 			}
16151 			switch (tea->ERROR_prim) {
16152 			case O_T_BIND_REQ:
16153 			case T_BIND_REQ:
16154 				tcp_bind_failed(tcp, mp,
16155 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
16156 				    ENETUNREACH : EADDRNOTAVAIL));
16157 				return;
16158 			case T_UNBIND_REQ:
16159 				tcp->tcp_hard_binding = B_FALSE;
16160 				tcp->tcp_hard_bound = B_FALSE;
16161 				if (mp->b_cont) {
16162 					freemsg(mp->b_cont);
16163 					mp->b_cont = NULL;
16164 				}
16165 				if (tcp->tcp_unbind_pending)
16166 					tcp->tcp_unbind_pending = 0;
16167 				else {
16168 					/* From tcp_ip_unbind() - free */
16169 					freemsg(mp);
16170 					return;
16171 				}
16172 				break;
16173 			case T_SVR4_OPTMGMT_REQ:
16174 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
16175 					/* T_OPTMGMT_REQ generated by TCP */
16176 					printf("T_SVR4_OPTMGMT_REQ failed "
16177 					    "%d/%d - dropped (cnt %d)\n",
16178 					    tea->TLI_error, tea->UNIX_error,
16179 					    tcp->tcp_drop_opt_ack_cnt);
16180 					freemsg(mp);
16181 					tcp->tcp_drop_opt_ack_cnt--;
16182 					return;
16183 				}
16184 				break;
16185 			}
16186 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
16187 			    tcp->tcp_drop_opt_ack_cnt > 0) {
16188 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
16189 				    "- dropped (cnt %d)\n",
16190 				    tea->TLI_error, tea->UNIX_error,
16191 				    tcp->tcp_drop_opt_ack_cnt);
16192 				freemsg(mp);
16193 				tcp->tcp_drop_opt_ack_cnt--;
16194 				return;
16195 			}
16196 			break;
16197 		case T_OPTMGMT_ACK:
16198 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
16199 				/* T_OPTMGMT_REQ generated by TCP */
16200 				freemsg(mp);
16201 				tcp->tcp_drop_opt_ack_cnt--;
16202 				return;
16203 			}
16204 			break;
16205 		default:
16206 			break;
16207 		}
16208 		break;
16209 	case M_FLUSH:
16210 		if (*rptr & FLUSHR)
16211 			flushq(q, FLUSHDATA);
16212 		break;
16213 	default:
16214 		/* M_CTL will be directly sent to tcp_icmp_error() */
16215 		ASSERT(DB_TYPE(mp) != M_CTL);
16216 		break;
16217 	}
16218 	/*
16219 	 * Make sure we set this bit before sending the ACK for
16220 	 * bind. Otherwise accept could possibly run and free
16221 	 * this tcp struct.
16222 	 */
16223 	putnext(q, mp);
16224 }
16225 
16226 /* ARGSUSED */
16227 static void
16228 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
16229 {
16230 	conn_t	*connp = (conn_t *)arg;
16231 	tcp_t	*tcp = connp->conn_tcp;
16232 	queue_t	*q = tcp->tcp_rq;
16233 	uint_t	thwin;
16234 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16235 	sodirect_t	*sodp;
16236 	boolean_t	fc;
16237 
16238 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
16239 	tcp->tcp_rsrv_mp = mp;
16240 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
16241 
16242 	TCP_STAT(tcps, tcp_rsrv_calls);
16243 
16244 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
16245 		return;
16246 	}
16247 
16248 	if (tcp->tcp_fused) {
16249 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16250 
16251 		ASSERT(tcp->tcp_fused);
16252 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
16253 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
16254 		ASSERT(!TCP_IS_DETACHED(tcp));
16255 		ASSERT(tcp->tcp_connp->conn_sqp ==
16256 		    peer_tcp->tcp_connp->conn_sqp);
16257 
16258 		/*
16259 		 * Normally we would not get backenabled in synchronous
16260 		 * streams mode, but in case this happens, we need to plug
16261 		 * synchronous streams during our drain to prevent a race
16262 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
16263 		 */
16264 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
16265 		if (tcp->tcp_rcv_list != NULL)
16266 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
16267 
16268 		if (peer_tcp > tcp) {
16269 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16270 			mutex_enter(&tcp->tcp_non_sq_lock);
16271 		} else {
16272 			mutex_enter(&tcp->tcp_non_sq_lock);
16273 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16274 		}
16275 
16276 		if (peer_tcp->tcp_flow_stopped &&
16277 		    (TCP_UNSENT_BYTES(peer_tcp) <=
16278 		    peer_tcp->tcp_xmit_lowater)) {
16279 			tcp_clrqfull(peer_tcp);
16280 		}
16281 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
16282 		mutex_exit(&tcp->tcp_non_sq_lock);
16283 
16284 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
16285 		TCP_STAT(tcps, tcp_fusion_backenabled);
16286 		return;
16287 	}
16288 
16289 	SOD_PTR_ENTER(tcp, sodp);
16290 	if (sodp != NULL) {
16291 		/* An sodirect connection */
16292 		if (SOD_QFULL(sodp)) {
16293 			/* Flow-controlled, need another back-enable */
16294 			fc = B_TRUE;
16295 			SOD_QSETBE(sodp);
16296 		} else {
16297 			/* Not flow-controlled */
16298 			fc = B_FALSE;
16299 		}
16300 		mutex_exit(sodp->sod_lockp);
16301 	} else if (canputnext(q)) {
16302 		/* STREAMS, not flow-controlled */
16303 		fc = B_FALSE;
16304 	} else {
16305 		/* STREAMS, flow-controlled */
16306 		fc = B_TRUE;
16307 	}
16308 	if (!fc) {
16309 		/* Not flow-controlled, open rwnd */
16310 		tcp->tcp_rwnd = q->q_hiwat;
16311 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16312 		    << tcp->tcp_rcv_ws;
16313 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16314 		/*
16315 		 * Send back a window update immediately if TCP is above
16316 		 * ESTABLISHED state and the increase of the rcv window
16317 		 * that the other side knows is at least 1 MSS after flow
16318 		 * control is lifted.
16319 		 */
16320 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16321 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16322 			tcp_xmit_ctl(NULL, tcp,
16323 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16324 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16325 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
16326 		}
16327 	}
16328 }
16329 
16330 /*
16331  * The read side service routine is called mostly when we get back-enabled as a
16332  * result of flow control relief.  Since we don't actually queue anything in
16333  * TCP, we have no data to send out of here.  What we do is clear the receive
16334  * window, and send out a window update.
16335  */
16336 static void
16337 tcp_rsrv(queue_t *q)
16338 {
16339 	conn_t		*connp = Q_TO_CONN(q);
16340 	tcp_t		*tcp = connp->conn_tcp;
16341 	mblk_t		*mp;
16342 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16343 
16344 	/* No code does a putq on the read side */
16345 	ASSERT(q->q_first == NULL);
16346 
16347 	/* Nothing to do for the default queue */
16348 	if (q == tcps->tcps_g_q) {
16349 		return;
16350 	}
16351 
16352 	/*
16353 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
16354 	 * been run.  So just return.
16355 	 */
16356 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
16357 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
16358 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
16359 		return;
16360 	}
16361 	tcp->tcp_rsrv_mp = NULL;
16362 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
16363 
16364 	CONN_INC_REF(connp);
16365 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16366 	    SQTAG_TCP_RSRV);
16367 }
16368 
16369 /*
16370  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16371  * We do not allow the receive window to shrink.  After setting rwnd,
16372  * set the flow control hiwat of the stream.
16373  *
16374  * This function is called in 2 cases:
16375  *
16376  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16377  *    connection (passive open) and in tcp_rput_data() for active connect.
16378  *    This is called after tcp_mss_set() when the desired MSS value is known.
16379  *    This makes sure that our window size is a mutiple of the other side's
16380  *    MSS.
16381  * 2) Handling SO_RCVBUF option.
16382  *
16383  * It is ASSUMED that the requested size is a multiple of the current MSS.
16384  *
16385  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16386  * user requests so.
16387  */
16388 static int
16389 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16390 {
16391 	uint32_t	mss = tcp->tcp_mss;
16392 	uint32_t	old_max_rwnd;
16393 	uint32_t	max_transmittable_rwnd;
16394 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16395 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16396 
16397 	if (tcp->tcp_fused) {
16398 		size_t sth_hiwat;
16399 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16400 
16401 		ASSERT(peer_tcp != NULL);
16402 		/*
16403 		 * Record the stream head's high water mark for
16404 		 * this endpoint; this is used for flow-control
16405 		 * purposes in tcp_fuse_output().
16406 		 */
16407 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16408 		if (!tcp_detached)
16409 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
16410 
16411 		/*
16412 		 * In the fusion case, the maxpsz stream head value of
16413 		 * our peer is set according to its send buffer size
16414 		 * and our receive buffer size; since the latter may
16415 		 * have changed we need to update the peer's maxpsz.
16416 		 */
16417 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16418 		return (rwnd);
16419 	}
16420 
16421 	if (tcp_detached)
16422 		old_max_rwnd = tcp->tcp_rwnd;
16423 	else
16424 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16425 
16426 	/*
16427 	 * Insist on a receive window that is at least
16428 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16429 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16430 	 * and delayed acknowledgement.
16431 	 */
16432 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16433 
16434 	/*
16435 	 * If window size info has already been exchanged, TCP should not
16436 	 * shrink the window.  Shrinking window is doable if done carefully.
16437 	 * We may add that support later.  But so far there is not a real
16438 	 * need to do that.
16439 	 */
16440 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16441 		/* MSS may have changed, do a round up again. */
16442 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16443 	}
16444 
16445 	/*
16446 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16447 	 * can be applied even before the window scale option is decided.
16448 	 */
16449 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16450 	if (rwnd > max_transmittable_rwnd) {
16451 		rwnd = max_transmittable_rwnd -
16452 		    (max_transmittable_rwnd % mss);
16453 		if (rwnd < mss)
16454 			rwnd = max_transmittable_rwnd;
16455 		/*
16456 		 * If we're over the limit we may have to back down tcp_rwnd.
16457 		 * The increment below won't work for us. So we set all three
16458 		 * here and the increment below will have no effect.
16459 		 */
16460 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16461 	}
16462 	if (tcp->tcp_localnet) {
16463 		tcp->tcp_rack_abs_max =
16464 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16465 	} else {
16466 		/*
16467 		 * For a remote host on a different subnet (through a router),
16468 		 * we ack every other packet to be conforming to RFC1122.
16469 		 * tcp_deferred_acks_max is default to 2.
16470 		 */
16471 		tcp->tcp_rack_abs_max =
16472 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16473 	}
16474 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16475 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16476 	else
16477 		tcp->tcp_rack_cur_max = 0;
16478 	/*
16479 	 * Increment the current rwnd by the amount the maximum grew (we
16480 	 * can not overwrite it since we might be in the middle of a
16481 	 * connection.)
16482 	 */
16483 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16484 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16485 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16486 		tcp->tcp_cwnd_max = rwnd;
16487 
16488 	if (tcp_detached)
16489 		return (rwnd);
16490 	/*
16491 	 * We set the maximum receive window into rq->q_hiwat.
16492 	 * This is not actually used for flow control.
16493 	 */
16494 	tcp->tcp_rq->q_hiwat = rwnd;
16495 	/*
16496 	 * Set the Stream head high water mark. This doesn't have to be
16497 	 * here, since we are simply using default values, but we would
16498 	 * prefer to choose these values algorithmically, with a likely
16499 	 * relationship to rwnd.
16500 	 */
16501 	(void) mi_set_sth_hiwat(tcp->tcp_rq,
16502 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16503 	return (rwnd);
16504 }
16505 
16506 /*
16507  * Return SNMP stuff in buffer in mpdata.
16508  */
16509 mblk_t *
16510 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16511 {
16512 	mblk_t			*mpdata;
16513 	mblk_t			*mp_conn_ctl = NULL;
16514 	mblk_t			*mp_conn_tail;
16515 	mblk_t			*mp_attr_ctl = NULL;
16516 	mblk_t			*mp_attr_tail;
16517 	mblk_t			*mp6_conn_ctl = NULL;
16518 	mblk_t			*mp6_conn_tail;
16519 	mblk_t			*mp6_attr_ctl = NULL;
16520 	mblk_t			*mp6_attr_tail;
16521 	struct opthdr		*optp;
16522 	mib2_tcpConnEntry_t	tce;
16523 	mib2_tcp6ConnEntry_t	tce6;
16524 	mib2_transportMLPEntry_t mlp;
16525 	connf_t			*connfp;
16526 	int			i;
16527 	boolean_t 		ispriv;
16528 	zoneid_t 		zoneid;
16529 	int			v4_conn_idx;
16530 	int			v6_conn_idx;
16531 	conn_t			*connp = Q_TO_CONN(q);
16532 	tcp_stack_t		*tcps;
16533 	ip_stack_t		*ipst;
16534 	mblk_t			*mp2ctl;
16535 
16536 	/*
16537 	 * make a copy of the original message
16538 	 */
16539 	mp2ctl = copymsg(mpctl);
16540 
16541 	if (mpctl == NULL ||
16542 	    (mpdata = mpctl->b_cont) == NULL ||
16543 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16544 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16545 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16546 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16547 		freemsg(mp_conn_ctl);
16548 		freemsg(mp_attr_ctl);
16549 		freemsg(mp6_conn_ctl);
16550 		freemsg(mp6_attr_ctl);
16551 		freemsg(mpctl);
16552 		freemsg(mp2ctl);
16553 		return (NULL);
16554 	}
16555 
16556 	ipst = connp->conn_netstack->netstack_ip;
16557 	tcps = connp->conn_netstack->netstack_tcp;
16558 
16559 	/* build table of connections -- need count in fixed part */
16560 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16561 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16562 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16563 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16564 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16565 
16566 	ispriv =
16567 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16568 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16569 
16570 	v4_conn_idx = v6_conn_idx = 0;
16571 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16572 
16573 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16574 		ipst = tcps->tcps_netstack->netstack_ip;
16575 
16576 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16577 
16578 		connp = NULL;
16579 
16580 		while ((connp =
16581 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16582 			tcp_t *tcp;
16583 			boolean_t needattr;
16584 
16585 			if (connp->conn_zoneid != zoneid)
16586 				continue;	/* not in this zone */
16587 
16588 			tcp = connp->conn_tcp;
16589 			UPDATE_MIB(&tcps->tcps_mib,
16590 			    tcpHCInSegs, tcp->tcp_ibsegs);
16591 			tcp->tcp_ibsegs = 0;
16592 			UPDATE_MIB(&tcps->tcps_mib,
16593 			    tcpHCOutSegs, tcp->tcp_obsegs);
16594 			tcp->tcp_obsegs = 0;
16595 
16596 			tce6.tcp6ConnState = tce.tcpConnState =
16597 			    tcp_snmp_state(tcp);
16598 			if (tce.tcpConnState == MIB2_TCP_established ||
16599 			    tce.tcpConnState == MIB2_TCP_closeWait)
16600 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16601 
16602 			needattr = B_FALSE;
16603 			bzero(&mlp, sizeof (mlp));
16604 			if (connp->conn_mlp_type != mlptSingle) {
16605 				if (connp->conn_mlp_type == mlptShared ||
16606 				    connp->conn_mlp_type == mlptBoth)
16607 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16608 				if (connp->conn_mlp_type == mlptPrivate ||
16609 				    connp->conn_mlp_type == mlptBoth)
16610 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16611 				needattr = B_TRUE;
16612 			}
16613 			if (connp->conn_peercred != NULL) {
16614 				ts_label_t *tsl;
16615 
16616 				tsl = crgetlabel(connp->conn_peercred);
16617 				mlp.tme_doi = label2doi(tsl);
16618 				mlp.tme_label = *label2bslabel(tsl);
16619 				needattr = B_TRUE;
16620 			}
16621 
16622 			/* Create a message to report on IPv6 entries */
16623 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16624 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16625 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16626 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16627 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16628 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16629 			/* Don't want just anybody seeing these... */
16630 			if (ispriv) {
16631 				tce6.tcp6ConnEntryInfo.ce_snxt =
16632 				    tcp->tcp_snxt;
16633 				tce6.tcp6ConnEntryInfo.ce_suna =
16634 				    tcp->tcp_suna;
16635 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16636 				    tcp->tcp_rnxt;
16637 				tce6.tcp6ConnEntryInfo.ce_rack =
16638 				    tcp->tcp_rack;
16639 			} else {
16640 				/*
16641 				 * Netstat, unfortunately, uses this to
16642 				 * get send/receive queue sizes.  How to fix?
16643 				 * Why not compute the difference only?
16644 				 */
16645 				tce6.tcp6ConnEntryInfo.ce_snxt =
16646 				    tcp->tcp_snxt - tcp->tcp_suna;
16647 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16648 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16649 				    tcp->tcp_rnxt - tcp->tcp_rack;
16650 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16651 			}
16652 
16653 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16654 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16655 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16656 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16657 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16658 
16659 			tce6.tcp6ConnCreationProcess =
16660 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16661 			    tcp->tcp_cpid;
16662 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16663 
16664 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16665 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16666 
16667 			mlp.tme_connidx = v6_conn_idx++;
16668 			if (needattr)
16669 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16670 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16671 			}
16672 			/*
16673 			 * Create an IPv4 table entry for IPv4 entries and also
16674 			 * for IPv6 entries which are bound to in6addr_any
16675 			 * but don't have IPV6_V6ONLY set.
16676 			 * (i.e. anything an IPv4 peer could connect to)
16677 			 */
16678 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16679 			    (tcp->tcp_state <= TCPS_LISTEN &&
16680 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16681 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16682 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16683 					tce.tcpConnRemAddress = INADDR_ANY;
16684 					tce.tcpConnLocalAddress = INADDR_ANY;
16685 				} else {
16686 					tce.tcpConnRemAddress =
16687 					    tcp->tcp_remote;
16688 					tce.tcpConnLocalAddress =
16689 					    tcp->tcp_ip_src;
16690 				}
16691 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16692 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16693 				/* Don't want just anybody seeing these... */
16694 				if (ispriv) {
16695 					tce.tcpConnEntryInfo.ce_snxt =
16696 					    tcp->tcp_snxt;
16697 					tce.tcpConnEntryInfo.ce_suna =
16698 					    tcp->tcp_suna;
16699 					tce.tcpConnEntryInfo.ce_rnxt =
16700 					    tcp->tcp_rnxt;
16701 					tce.tcpConnEntryInfo.ce_rack =
16702 					    tcp->tcp_rack;
16703 				} else {
16704 					/*
16705 					 * Netstat, unfortunately, uses this to
16706 					 * get send/receive queue sizes.  How
16707 					 * to fix?
16708 					 * Why not compute the difference only?
16709 					 */
16710 					tce.tcpConnEntryInfo.ce_snxt =
16711 					    tcp->tcp_snxt - tcp->tcp_suna;
16712 					tce.tcpConnEntryInfo.ce_suna = 0;
16713 					tce.tcpConnEntryInfo.ce_rnxt =
16714 					    tcp->tcp_rnxt - tcp->tcp_rack;
16715 					tce.tcpConnEntryInfo.ce_rack = 0;
16716 				}
16717 
16718 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16719 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16720 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16721 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16722 				tce.tcpConnEntryInfo.ce_state =
16723 				    tcp->tcp_state;
16724 
16725 				tce.tcpConnCreationProcess =
16726 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16727 				    tcp->tcp_cpid;
16728 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16729 
16730 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16731 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16732 
16733 				mlp.tme_connidx = v4_conn_idx++;
16734 				if (needattr)
16735 					(void) snmp_append_data2(
16736 					    mp_attr_ctl->b_cont,
16737 					    &mp_attr_tail, (char *)&mlp,
16738 					    sizeof (mlp));
16739 			}
16740 		}
16741 	}
16742 
16743 	/* fixed length structure for IPv4 and IPv6 counters */
16744 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16745 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16746 	    sizeof (mib2_tcp6ConnEntry_t));
16747 	/* synchronize 32- and 64-bit counters */
16748 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16749 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16750 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16751 	optp->level = MIB2_TCP;
16752 	optp->name = 0;
16753 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16754 	    sizeof (tcps->tcps_mib));
16755 	optp->len = msgdsize(mpdata);
16756 	qreply(q, mpctl);
16757 
16758 	/* table of connections... */
16759 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16760 	    sizeof (struct T_optmgmt_ack)];
16761 	optp->level = MIB2_TCP;
16762 	optp->name = MIB2_TCP_CONN;
16763 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16764 	qreply(q, mp_conn_ctl);
16765 
16766 	/* table of MLP attributes... */
16767 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16768 	    sizeof (struct T_optmgmt_ack)];
16769 	optp->level = MIB2_TCP;
16770 	optp->name = EXPER_XPORT_MLP;
16771 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16772 	if (optp->len == 0)
16773 		freemsg(mp_attr_ctl);
16774 	else
16775 		qreply(q, mp_attr_ctl);
16776 
16777 	/* table of IPv6 connections... */
16778 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16779 	    sizeof (struct T_optmgmt_ack)];
16780 	optp->level = MIB2_TCP6;
16781 	optp->name = MIB2_TCP6_CONN;
16782 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16783 	qreply(q, mp6_conn_ctl);
16784 
16785 	/* table of IPv6 MLP attributes... */
16786 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16787 	    sizeof (struct T_optmgmt_ack)];
16788 	optp->level = MIB2_TCP6;
16789 	optp->name = EXPER_XPORT_MLP;
16790 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16791 	if (optp->len == 0)
16792 		freemsg(mp6_attr_ctl);
16793 	else
16794 		qreply(q, mp6_attr_ctl);
16795 	return (mp2ctl);
16796 }
16797 
16798 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16799 /* ARGSUSED */
16800 int
16801 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16802 {
16803 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16804 
16805 	switch (level) {
16806 	case MIB2_TCP:
16807 		switch (name) {
16808 		case 13:
16809 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16810 				return (0);
16811 			/* TODO: delete entry defined by tce */
16812 			return (1);
16813 		default:
16814 			return (0);
16815 		}
16816 	default:
16817 		return (1);
16818 	}
16819 }
16820 
16821 /* Translate TCP state to MIB2 TCP state. */
16822 static int
16823 tcp_snmp_state(tcp_t *tcp)
16824 {
16825 	if (tcp == NULL)
16826 		return (0);
16827 
16828 	switch (tcp->tcp_state) {
16829 	case TCPS_CLOSED:
16830 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16831 	case TCPS_BOUND:
16832 		return (MIB2_TCP_closed);
16833 	case TCPS_LISTEN:
16834 		return (MIB2_TCP_listen);
16835 	case TCPS_SYN_SENT:
16836 		return (MIB2_TCP_synSent);
16837 	case TCPS_SYN_RCVD:
16838 		return (MIB2_TCP_synReceived);
16839 	case TCPS_ESTABLISHED:
16840 		return (MIB2_TCP_established);
16841 	case TCPS_CLOSE_WAIT:
16842 		return (MIB2_TCP_closeWait);
16843 	case TCPS_FIN_WAIT_1:
16844 		return (MIB2_TCP_finWait1);
16845 	case TCPS_CLOSING:
16846 		return (MIB2_TCP_closing);
16847 	case TCPS_LAST_ACK:
16848 		return (MIB2_TCP_lastAck);
16849 	case TCPS_FIN_WAIT_2:
16850 		return (MIB2_TCP_finWait2);
16851 	case TCPS_TIME_WAIT:
16852 		return (MIB2_TCP_timeWait);
16853 	default:
16854 		return (0);
16855 	}
16856 }
16857 
16858 static char tcp_report_header[] =
16859 	"TCP     " MI_COL_HDRPAD_STR
16860 	"zone dest            snxt     suna     "
16861 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16862 	"recent   [lport,fport] state";
16863 
16864 /*
16865  * TCP status report triggered via the Named Dispatch mechanism.
16866  */
16867 /* ARGSUSED */
16868 static void
16869 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16870     cred_t *cr)
16871 {
16872 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16873 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16874 	char cflag;
16875 	in6_addr_t	v6dst;
16876 	char buf[80];
16877 	uint_t print_len, buf_len;
16878 
16879 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16880 	if (buf_len <= 0)
16881 		return;
16882 
16883 	if (hashval >= 0)
16884 		(void) sprintf(hash, "%03d ", hashval);
16885 	else
16886 		hash[0] = '\0';
16887 
16888 	/*
16889 	 * Note that we use the remote address in the tcp_b  structure.
16890 	 * This means that it will print out the real destination address,
16891 	 * not the next hop's address if source routing is used.  This
16892 	 * avoid the confusion on the output because user may not
16893 	 * know that source routing is used for a connection.
16894 	 */
16895 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16896 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16897 	} else {
16898 		v6dst = tcp->tcp_remote_v6;
16899 	}
16900 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16901 	/*
16902 	 * the ispriv checks are so that normal users cannot determine
16903 	 * sequence number information using NDD.
16904 	 */
16905 
16906 	if (TCP_IS_DETACHED(tcp))
16907 		cflag = '*';
16908 	else
16909 		cflag = ' ';
16910 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16911 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16912 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16913 	    hash,
16914 	    (void *)tcp,
16915 	    tcp->tcp_connp->conn_zoneid,
16916 	    addrbuf,
16917 	    (ispriv) ? tcp->tcp_snxt : 0,
16918 	    (ispriv) ? tcp->tcp_suna : 0,
16919 	    tcp->tcp_swnd,
16920 	    (ispriv) ? tcp->tcp_rnxt : 0,
16921 	    (ispriv) ? tcp->tcp_rack : 0,
16922 	    tcp->tcp_rwnd,
16923 	    tcp->tcp_rto,
16924 	    tcp->tcp_mss,
16925 	    tcp->tcp_snd_ws_ok,
16926 	    tcp->tcp_snd_ws,
16927 	    tcp->tcp_rcv_ws,
16928 	    tcp->tcp_snd_ts_ok,
16929 	    tcp->tcp_ts_recent,
16930 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16931 	if (print_len < buf_len) {
16932 		((mblk_t *)mp)->b_wptr += print_len;
16933 	} else {
16934 		((mblk_t *)mp)->b_wptr += buf_len;
16935 	}
16936 }
16937 
16938 /*
16939  * TCP status report (for listeners only) triggered via the Named Dispatch
16940  * mechanism.
16941  */
16942 /* ARGSUSED */
16943 static void
16944 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16945 {
16946 	char addrbuf[INET6_ADDRSTRLEN];
16947 	in6_addr_t	v6dst;
16948 	uint_t print_len, buf_len;
16949 
16950 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16951 	if (buf_len <= 0)
16952 		return;
16953 
16954 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16955 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16956 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16957 	} else {
16958 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16959 		    addrbuf, sizeof (addrbuf));
16960 	}
16961 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16962 	    "%03d "
16963 	    MI_COL_PTRFMT_STR
16964 	    "%d %s %05u %08u %d/%d/%d%c\n",
16965 	    hashval, (void *)tcp,
16966 	    tcp->tcp_connp->conn_zoneid,
16967 	    addrbuf,
16968 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16969 	    tcp->tcp_conn_req_seqnum,
16970 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16971 	    tcp->tcp_conn_req_max,
16972 	    tcp->tcp_syn_defense ? '*' : ' ');
16973 	if (print_len < buf_len) {
16974 		((mblk_t *)mp)->b_wptr += print_len;
16975 	} else {
16976 		((mblk_t *)mp)->b_wptr += buf_len;
16977 	}
16978 }
16979 
16980 /* TCP status report triggered via the Named Dispatch mechanism. */
16981 /* ARGSUSED */
16982 static int
16983 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16984 {
16985 	tcp_t	*tcp;
16986 	int	i;
16987 	conn_t	*connp;
16988 	connf_t	*connfp;
16989 	zoneid_t zoneid;
16990 	tcp_stack_t *tcps;
16991 	ip_stack_t *ipst;
16992 
16993 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16994 	tcps = Q_TO_TCP(q)->tcp_tcps;
16995 
16996 	/*
16997 	 * Because of the ndd constraint, at most we can have 64K buffer
16998 	 * to put in all TCP info.  So to be more efficient, just
16999 	 * allocate a 64K buffer here, assuming we need that large buffer.
17000 	 * This may be a problem as any user can read tcp_status.  Therefore
17001 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
17002 	 * This should be OK as normal users should not do this too often.
17003 	 */
17004 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17005 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17006 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17007 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17008 			return (0);
17009 		}
17010 	}
17011 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17012 		/* The following may work even if we cannot get a large buf. */
17013 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17014 		return (0);
17015 	}
17016 
17017 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
17018 
17019 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
17020 
17021 		ipst = tcps->tcps_netstack->netstack_ip;
17022 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
17023 
17024 		connp = NULL;
17025 
17026 		while ((connp =
17027 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17028 			tcp = connp->conn_tcp;
17029 			if (zoneid != GLOBAL_ZONEID &&
17030 			    zoneid != connp->conn_zoneid)
17031 				continue;
17032 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
17033 			    cr);
17034 		}
17035 
17036 	}
17037 
17038 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17039 	return (0);
17040 }
17041 
17042 /* TCP status report triggered via the Named Dispatch mechanism. */
17043 /* ARGSUSED */
17044 static int
17045 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17046 {
17047 	tf_t	*tbf;
17048 	tcp_t	*tcp;
17049 	int	i;
17050 	zoneid_t zoneid;
17051 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17052 
17053 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17054 
17055 	/* Refer to comments in tcp_status_report(). */
17056 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17057 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17058 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17059 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17060 			return (0);
17061 		}
17062 	}
17063 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17064 		/* The following may work even if we cannot get a large buf. */
17065 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17066 		return (0);
17067 	}
17068 
17069 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17070 
17071 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
17072 		tbf = &tcps->tcps_bind_fanout[i];
17073 		mutex_enter(&tbf->tf_lock);
17074 		for (tcp = tbf->tf_tcp; tcp != NULL;
17075 		    tcp = tcp->tcp_bind_hash) {
17076 			if (zoneid != GLOBAL_ZONEID &&
17077 			    zoneid != tcp->tcp_connp->conn_zoneid)
17078 				continue;
17079 			CONN_INC_REF(tcp->tcp_connp);
17080 			tcp_report_item(mp->b_cont, tcp, i,
17081 			    Q_TO_TCP(q), cr);
17082 			CONN_DEC_REF(tcp->tcp_connp);
17083 		}
17084 		mutex_exit(&tbf->tf_lock);
17085 	}
17086 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17087 	return (0);
17088 }
17089 
17090 /* TCP status report triggered via the Named Dispatch mechanism. */
17091 /* ARGSUSED */
17092 static int
17093 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17094 {
17095 	connf_t	*connfp;
17096 	conn_t	*connp;
17097 	tcp_t	*tcp;
17098 	int	i;
17099 	zoneid_t zoneid;
17100 	tcp_stack_t *tcps;
17101 	ip_stack_t	*ipst;
17102 
17103 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17104 	tcps = Q_TO_TCP(q)->tcp_tcps;
17105 
17106 	/* Refer to comments in tcp_status_report(). */
17107 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17108 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17109 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17110 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17111 			return (0);
17112 		}
17113 	}
17114 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17115 		/* The following may work even if we cannot get a large buf. */
17116 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17117 		return (0);
17118 	}
17119 
17120 	(void) mi_mpprintf(mp,
17121 	    "    TCP    " MI_COL_HDRPAD_STR
17122 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
17123 
17124 	ipst = tcps->tcps_netstack->netstack_ip;
17125 
17126 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
17127 		connfp = &ipst->ips_ipcl_bind_fanout[i];
17128 		connp = NULL;
17129 		while ((connp =
17130 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17131 			tcp = connp->conn_tcp;
17132 			if (zoneid != GLOBAL_ZONEID &&
17133 			    zoneid != connp->conn_zoneid)
17134 				continue;
17135 			tcp_report_listener(mp->b_cont, tcp, i);
17136 		}
17137 	}
17138 
17139 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17140 	return (0);
17141 }
17142 
17143 /* TCP status report triggered via the Named Dispatch mechanism. */
17144 /* ARGSUSED */
17145 static int
17146 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17147 {
17148 	connf_t	*connfp;
17149 	conn_t	*connp;
17150 	tcp_t	*tcp;
17151 	int	i;
17152 	zoneid_t zoneid;
17153 	tcp_stack_t *tcps;
17154 	ip_stack_t *ipst;
17155 
17156 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17157 	tcps = Q_TO_TCP(q)->tcp_tcps;
17158 	ipst = tcps->tcps_netstack->netstack_ip;
17159 
17160 	/* Refer to comments in tcp_status_report(). */
17161 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17162 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17163 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17164 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17165 			return (0);
17166 		}
17167 	}
17168 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17169 		/* The following may work even if we cannot get a large buf. */
17170 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17171 		return (0);
17172 	}
17173 
17174 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
17175 	    ipst->ips_ipcl_conn_fanout_size);
17176 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17177 
17178 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
17179 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
17180 		connp = NULL;
17181 		while ((connp =
17182 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17183 			tcp = connp->conn_tcp;
17184 			if (zoneid != GLOBAL_ZONEID &&
17185 			    zoneid != connp->conn_zoneid)
17186 				continue;
17187 			tcp_report_item(mp->b_cont, tcp, i,
17188 			    Q_TO_TCP(q), cr);
17189 		}
17190 	}
17191 
17192 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17193 	return (0);
17194 }
17195 
17196 /* TCP status report triggered via the Named Dispatch mechanism. */
17197 /* ARGSUSED */
17198 static int
17199 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17200 {
17201 	tf_t	*tf;
17202 	tcp_t	*tcp;
17203 	int	i;
17204 	zoneid_t zoneid;
17205 	tcp_stack_t	*tcps;
17206 
17207 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17208 	tcps = Q_TO_TCP(q)->tcp_tcps;
17209 
17210 	/* Refer to comments in tcp_status_report(). */
17211 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17212 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17213 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17214 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17215 			return (0);
17216 		}
17217 	}
17218 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17219 		/* The following may work even if we cannot get a large buf. */
17220 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17221 		return (0);
17222 	}
17223 
17224 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17225 
17226 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
17227 		tf = &tcps->tcps_acceptor_fanout[i];
17228 		mutex_enter(&tf->tf_lock);
17229 		for (tcp = tf->tf_tcp; tcp != NULL;
17230 		    tcp = tcp->tcp_acceptor_hash) {
17231 			if (zoneid != GLOBAL_ZONEID &&
17232 			    zoneid != tcp->tcp_connp->conn_zoneid)
17233 				continue;
17234 			tcp_report_item(mp->b_cont, tcp, i,
17235 			    Q_TO_TCP(q), cr);
17236 		}
17237 		mutex_exit(&tf->tf_lock);
17238 	}
17239 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17240 	return (0);
17241 }
17242 
17243 /*
17244  * tcp_timer is the timer service routine.  It handles the retransmission,
17245  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
17246  * from the state of the tcp instance what kind of action needs to be done
17247  * at the time it is called.
17248  */
17249 static void
17250 tcp_timer(void *arg)
17251 {
17252 	mblk_t		*mp;
17253 	clock_t		first_threshold;
17254 	clock_t		second_threshold;
17255 	clock_t		ms;
17256 	uint32_t	mss;
17257 	conn_t		*connp = (conn_t *)arg;
17258 	tcp_t		*tcp = connp->conn_tcp;
17259 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17260 
17261 	tcp->tcp_timer_tid = 0;
17262 
17263 	if (tcp->tcp_fused)
17264 		return;
17265 
17266 	first_threshold =  tcp->tcp_first_timer_threshold;
17267 	second_threshold = tcp->tcp_second_timer_threshold;
17268 	switch (tcp->tcp_state) {
17269 	case TCPS_IDLE:
17270 	case TCPS_BOUND:
17271 	case TCPS_LISTEN:
17272 		return;
17273 	case TCPS_SYN_RCVD: {
17274 		tcp_t	*listener = tcp->tcp_listener;
17275 
17276 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
17277 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
17278 			/* it's our first timeout */
17279 			tcp->tcp_syn_rcvd_timeout = 1;
17280 			mutex_enter(&listener->tcp_eager_lock);
17281 			listener->tcp_syn_rcvd_timeout++;
17282 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
17283 				/*
17284 				 * Make this eager available for drop if we
17285 				 * need to drop one to accomodate a new
17286 				 * incoming SYN request.
17287 				 */
17288 				MAKE_DROPPABLE(listener, tcp);
17289 			}
17290 			if (!listener->tcp_syn_defense &&
17291 			    (listener->tcp_syn_rcvd_timeout >
17292 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
17293 			    (tcps->tcps_conn_req_max_q0 > 200)) {
17294 				/* We may be under attack. Put on a defense. */
17295 				listener->tcp_syn_defense = B_TRUE;
17296 				cmn_err(CE_WARN, "High TCP connect timeout "
17297 				    "rate! System (port %d) may be under a "
17298 				    "SYN flood attack!",
17299 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
17300 
17301 				listener->tcp_ip_addr_cache = kmem_zalloc(
17302 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
17303 				    KM_NOSLEEP);
17304 			}
17305 			mutex_exit(&listener->tcp_eager_lock);
17306 		} else if (listener != NULL) {
17307 			mutex_enter(&listener->tcp_eager_lock);
17308 			tcp->tcp_syn_rcvd_timeout++;
17309 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17310 			    !tcp->tcp_closemp_used) {
17311 				/*
17312 				 * This is our second timeout. Put the tcp in
17313 				 * the list of droppable eagers to allow it to
17314 				 * be dropped, if needed. We don't check
17315 				 * whether tcp_dontdrop is set or not to
17316 				 * protect ourselve from a SYN attack where a
17317 				 * remote host can spoof itself as one of the
17318 				 * good IP source and continue to hold
17319 				 * resources too long.
17320 				 */
17321 				MAKE_DROPPABLE(listener, tcp);
17322 			}
17323 			mutex_exit(&listener->tcp_eager_lock);
17324 		}
17325 	}
17326 		/* FALLTHRU */
17327 	case TCPS_SYN_SENT:
17328 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17329 		second_threshold = tcp->tcp_second_ctimer_threshold;
17330 		break;
17331 	case TCPS_ESTABLISHED:
17332 	case TCPS_FIN_WAIT_1:
17333 	case TCPS_CLOSING:
17334 	case TCPS_CLOSE_WAIT:
17335 	case TCPS_LAST_ACK:
17336 		/* If we have data to rexmit */
17337 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17338 			clock_t	time_to_wait;
17339 
17340 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17341 			if (!tcp->tcp_xmit_head)
17342 				break;
17343 			time_to_wait = lbolt -
17344 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17345 			time_to_wait = tcp->tcp_rto -
17346 			    TICK_TO_MSEC(time_to_wait);
17347 			/*
17348 			 * If the timer fires too early, 1 clock tick earlier,
17349 			 * restart the timer.
17350 			 */
17351 			if (time_to_wait > msec_per_tick) {
17352 				TCP_STAT(tcps, tcp_timer_fire_early);
17353 				TCP_TIMER_RESTART(tcp, time_to_wait);
17354 				return;
17355 			}
17356 			/*
17357 			 * When we probe zero windows, we force the swnd open.
17358 			 * If our peer acks with a closed window swnd will be
17359 			 * set to zero by tcp_rput(). As long as we are
17360 			 * receiving acks tcp_rput will
17361 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17362 			 * first and second interval actions.  NOTE: the timer
17363 			 * interval is allowed to continue its exponential
17364 			 * backoff.
17365 			 */
17366 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17367 				if (tcp->tcp_debug) {
17368 					(void) strlog(TCP_MOD_ID, 0, 1,
17369 					    SL_TRACE, "tcp_timer: zero win");
17370 				}
17371 			} else {
17372 				/*
17373 				 * After retransmission, we need to do
17374 				 * slow start.  Set the ssthresh to one
17375 				 * half of current effective window and
17376 				 * cwnd to one MSS.  Also reset
17377 				 * tcp_cwnd_cnt.
17378 				 *
17379 				 * Note that if tcp_ssthresh is reduced because
17380 				 * of ECN, do not reduce it again unless it is
17381 				 * already one window of data away (tcp_cwr
17382 				 * should then be cleared) or this is a
17383 				 * timeout for a retransmitted segment.
17384 				 */
17385 				uint32_t npkt;
17386 
17387 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17388 					npkt = ((tcp->tcp_timer_backoff ?
17389 					    tcp->tcp_cwnd_ssthresh :
17390 					    tcp->tcp_snxt -
17391 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17392 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17393 					    tcp->tcp_mss;
17394 				}
17395 				tcp->tcp_cwnd = tcp->tcp_mss;
17396 				tcp->tcp_cwnd_cnt = 0;
17397 				if (tcp->tcp_ecn_ok) {
17398 					tcp->tcp_cwr = B_TRUE;
17399 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17400 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17401 				}
17402 			}
17403 			break;
17404 		}
17405 		/*
17406 		 * We have something to send yet we cannot send.  The
17407 		 * reason can be:
17408 		 *
17409 		 * 1. Zero send window: we need to do zero window probe.
17410 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17411 		 * segments.
17412 		 * 3. SWS avoidance: receiver may have shrunk window,
17413 		 * reset our knowledge.
17414 		 *
17415 		 * Note that condition 2 can happen with either 1 or
17416 		 * 3.  But 1 and 3 are exclusive.
17417 		 */
17418 		if (tcp->tcp_unsent != 0) {
17419 			if (tcp->tcp_cwnd == 0) {
17420 				/*
17421 				 * Set tcp_cwnd to 1 MSS so that a
17422 				 * new segment can be sent out.  We
17423 				 * are "clocking out" new data when
17424 				 * the network is really congested.
17425 				 */
17426 				ASSERT(tcp->tcp_ecn_ok);
17427 				tcp->tcp_cwnd = tcp->tcp_mss;
17428 			}
17429 			if (tcp->tcp_swnd == 0) {
17430 				/* Extend window for zero window probe */
17431 				tcp->tcp_swnd++;
17432 				tcp->tcp_zero_win_probe = B_TRUE;
17433 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17434 			} else {
17435 				/*
17436 				 * Handle timeout from sender SWS avoidance.
17437 				 * Reset our knowledge of the max send window
17438 				 * since the receiver might have reduced its
17439 				 * receive buffer.  Avoid setting tcp_max_swnd
17440 				 * to one since that will essentially disable
17441 				 * the SWS checks.
17442 				 *
17443 				 * Note that since we don't have a SWS
17444 				 * state variable, if the timeout is set
17445 				 * for ECN but not for SWS, this
17446 				 * code will also be executed.  This is
17447 				 * fine as tcp_max_swnd is updated
17448 				 * constantly and it will not affect
17449 				 * anything.
17450 				 */
17451 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17452 			}
17453 			tcp_wput_data(tcp, NULL, B_FALSE);
17454 			return;
17455 		}
17456 		/* Is there a FIN that needs to be to re retransmitted? */
17457 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17458 		    !tcp->tcp_fin_acked)
17459 			break;
17460 		/* Nothing to do, return without restarting timer. */
17461 		TCP_STAT(tcps, tcp_timer_fire_miss);
17462 		return;
17463 	case TCPS_FIN_WAIT_2:
17464 		/*
17465 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17466 		 * We waited some time for for peer's FIN, but it hasn't
17467 		 * arrived.  We flush the connection now to avoid
17468 		 * case where the peer has rebooted.
17469 		 */
17470 		if (TCP_IS_DETACHED(tcp)) {
17471 			(void) tcp_clean_death(tcp, 0, 23);
17472 		} else {
17473 			TCP_TIMER_RESTART(tcp,
17474 			    tcps->tcps_fin_wait_2_flush_interval);
17475 		}
17476 		return;
17477 	case TCPS_TIME_WAIT:
17478 		(void) tcp_clean_death(tcp, 0, 24);
17479 		return;
17480 	default:
17481 		if (tcp->tcp_debug) {
17482 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17483 			    "tcp_timer: strange state (%d) %s",
17484 			    tcp->tcp_state, tcp_display(tcp, NULL,
17485 			    DISP_PORT_ONLY));
17486 		}
17487 		return;
17488 	}
17489 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17490 		/*
17491 		 * For zero window probe, we need to send indefinitely,
17492 		 * unless we have not heard from the other side for some
17493 		 * time...
17494 		 */
17495 		if ((tcp->tcp_zero_win_probe == 0) ||
17496 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17497 		    second_threshold)) {
17498 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17499 			/*
17500 			 * If TCP is in SYN_RCVD state, send back a
17501 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17502 			 * should be zero in TCPS_SYN_RCVD state.
17503 			 */
17504 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17505 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17506 				    "in SYN_RCVD",
17507 				    tcp, tcp->tcp_snxt,
17508 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17509 			}
17510 			(void) tcp_clean_death(tcp,
17511 			    tcp->tcp_client_errno ?
17512 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17513 			return;
17514 		} else {
17515 			/*
17516 			 * Set tcp_ms_we_have_waited to second_threshold
17517 			 * so that in next timeout, we will do the above
17518 			 * check (lbolt - tcp_last_recv_time).  This is
17519 			 * also to avoid overflow.
17520 			 *
17521 			 * We don't need to decrement tcp_timer_backoff
17522 			 * to avoid overflow because it will be decremented
17523 			 * later if new timeout value is greater than
17524 			 * tcp_rexmit_interval_max.  In the case when
17525 			 * tcp_rexmit_interval_max is greater than
17526 			 * second_threshold, it means that we will wait
17527 			 * longer than second_threshold to send the next
17528 			 * window probe.
17529 			 */
17530 			tcp->tcp_ms_we_have_waited = second_threshold;
17531 		}
17532 	} else if (ms > first_threshold) {
17533 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17534 		    tcp->tcp_xmit_head != NULL) {
17535 			tcp->tcp_xmit_head =
17536 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17537 		}
17538 		/*
17539 		 * We have been retransmitting for too long...  The RTT
17540 		 * we calculated is probably incorrect.  Reinitialize it.
17541 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17542 		 * tcp_rtt_update so that we won't accidentally cache a
17543 		 * bad value.  But only do this if this is not a zero
17544 		 * window probe.
17545 		 */
17546 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17547 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17548 			    (tcp->tcp_rtt_sa >> 5);
17549 			tcp->tcp_rtt_sa = 0;
17550 			tcp_ip_notify(tcp);
17551 			tcp->tcp_rtt_update = 0;
17552 		}
17553 	}
17554 	tcp->tcp_timer_backoff++;
17555 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17556 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17557 	    tcps->tcps_rexmit_interval_min) {
17558 		/*
17559 		 * This means the original RTO is tcp_rexmit_interval_min.
17560 		 * So we will use tcp_rexmit_interval_min as the RTO value
17561 		 * and do the backoff.
17562 		 */
17563 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17564 	} else {
17565 		ms <<= tcp->tcp_timer_backoff;
17566 	}
17567 	if (ms > tcps->tcps_rexmit_interval_max) {
17568 		ms = tcps->tcps_rexmit_interval_max;
17569 		/*
17570 		 * ms is at max, decrement tcp_timer_backoff to avoid
17571 		 * overflow.
17572 		 */
17573 		tcp->tcp_timer_backoff--;
17574 	}
17575 	tcp->tcp_ms_we_have_waited += ms;
17576 	if (tcp->tcp_zero_win_probe == 0) {
17577 		tcp->tcp_rto = ms;
17578 	}
17579 	TCP_TIMER_RESTART(tcp, ms);
17580 	/*
17581 	 * This is after a timeout and tcp_rto is backed off.  Set
17582 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17583 	 * restart the timer with a correct value.
17584 	 */
17585 	tcp->tcp_set_timer = 1;
17586 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17587 	if (mss > tcp->tcp_mss)
17588 		mss = tcp->tcp_mss;
17589 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17590 		mss = tcp->tcp_swnd;
17591 
17592 	if ((mp = tcp->tcp_xmit_head) != NULL)
17593 		mp->b_prev = (mblk_t *)lbolt;
17594 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17595 	    B_TRUE);
17596 
17597 	/*
17598 	 * When slow start after retransmission begins, start with
17599 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17600 	 * start phase.  tcp_snd_burst controls how many segments
17601 	 * can be sent because of an ack.
17602 	 */
17603 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17604 	tcp->tcp_snd_burst = TCP_CWND_SS;
17605 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17606 	    (tcp->tcp_unsent == 0)) {
17607 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17608 	} else {
17609 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17610 	}
17611 	tcp->tcp_rexmit = B_TRUE;
17612 	tcp->tcp_dupack_cnt = 0;
17613 
17614 	/*
17615 	 * Remove all rexmit SACK blk to start from fresh.
17616 	 */
17617 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17618 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17619 		tcp->tcp_num_notsack_blk = 0;
17620 		tcp->tcp_cnt_notsack_list = 0;
17621 	}
17622 	if (mp == NULL) {
17623 		return;
17624 	}
17625 	/* Attach credentials to retransmitted initial SYNs. */
17626 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17627 		mblk_setcred(mp, tcp->tcp_cred);
17628 		DB_CPID(mp) = tcp->tcp_cpid;
17629 	}
17630 
17631 	tcp->tcp_csuna = tcp->tcp_snxt;
17632 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17633 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17634 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17635 
17636 }
17637 
17638 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17639 static void
17640 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17641 {
17642 	conn_t	*connp;
17643 
17644 	switch (tcp->tcp_state) {
17645 	case TCPS_BOUND:
17646 	case TCPS_LISTEN:
17647 		break;
17648 	default:
17649 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17650 		return;
17651 	}
17652 
17653 	/*
17654 	 * Need to clean up all the eagers since after the unbind, segments
17655 	 * will no longer be delivered to this listener stream.
17656 	 */
17657 	mutex_enter(&tcp->tcp_eager_lock);
17658 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17659 		tcp_eager_cleanup(tcp, 0);
17660 	}
17661 	mutex_exit(&tcp->tcp_eager_lock);
17662 
17663 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17664 		tcp->tcp_ipha->ipha_src = 0;
17665 	} else {
17666 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17667 	}
17668 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17669 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17670 	tcp_bind_hash_remove(tcp);
17671 	tcp->tcp_state = TCPS_IDLE;
17672 	tcp->tcp_mdt = B_FALSE;
17673 	/* Send M_FLUSH according to TPI */
17674 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17675 	connp = tcp->tcp_connp;
17676 	connp->conn_mdt_ok = B_FALSE;
17677 	ipcl_hash_remove(connp);
17678 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17679 	mp = mi_tpi_ok_ack_alloc(mp);
17680 	putnext(tcp->tcp_rq, mp);
17681 }
17682 
17683 /*
17684  * Don't let port fall into the privileged range.
17685  * Since the extra privileged ports can be arbitrary we also
17686  * ensure that we exclude those from consideration.
17687  * tcp_g_epriv_ports is not sorted thus we loop over it until
17688  * there are no changes.
17689  *
17690  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17691  * but instead the code relies on:
17692  * - the fact that the address of the array and its size never changes
17693  * - the atomic assignment of the elements of the array
17694  *
17695  * Returns 0 if there are no more ports available.
17696  *
17697  * TS note: skip multilevel ports.
17698  */
17699 static in_port_t
17700 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17701 {
17702 	int i;
17703 	boolean_t restart = B_FALSE;
17704 	tcp_stack_t *tcps = tcp->tcp_tcps;
17705 
17706 	if (random && tcp_random_anon_port != 0) {
17707 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17708 		    sizeof (in_port_t));
17709 		/*
17710 		 * Unless changed by a sys admin, the smallest anon port
17711 		 * is 32768 and the largest anon port is 65535.  It is
17712 		 * very likely (50%) for the random port to be smaller
17713 		 * than the smallest anon port.  When that happens,
17714 		 * add port % (anon port range) to the smallest anon
17715 		 * port to get the random port.  It should fall into the
17716 		 * valid anon port range.
17717 		 */
17718 		if (port < tcps->tcps_smallest_anon_port) {
17719 			port = tcps->tcps_smallest_anon_port +
17720 			    port % (tcps->tcps_largest_anon_port -
17721 			    tcps->tcps_smallest_anon_port);
17722 		}
17723 	}
17724 
17725 retry:
17726 	if (port < tcps->tcps_smallest_anon_port)
17727 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17728 
17729 	if (port > tcps->tcps_largest_anon_port) {
17730 		if (restart)
17731 			return (0);
17732 		restart = B_TRUE;
17733 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17734 	}
17735 
17736 	if (port < tcps->tcps_smallest_nonpriv_port)
17737 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17738 
17739 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17740 		if (port == tcps->tcps_g_epriv_ports[i]) {
17741 			port++;
17742 			/*
17743 			 * Make sure whether the port is in the
17744 			 * valid range.
17745 			 */
17746 			goto retry;
17747 		}
17748 	}
17749 	if (is_system_labeled() &&
17750 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17751 	    IPPROTO_TCP, B_TRUE)) != 0) {
17752 		port = i;
17753 		goto retry;
17754 	}
17755 	return (port);
17756 }
17757 
17758 /*
17759  * Return the next anonymous port in the privileged port range for
17760  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17761  * downwards.  This is the same behavior as documented in the userland
17762  * library call rresvport(3N).
17763  *
17764  * TS note: skip multilevel ports.
17765  */
17766 static in_port_t
17767 tcp_get_next_priv_port(const tcp_t *tcp)
17768 {
17769 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17770 	in_port_t nextport;
17771 	boolean_t restart = B_FALSE;
17772 	tcp_stack_t *tcps = tcp->tcp_tcps;
17773 retry:
17774 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17775 	    next_priv_port >= IPPORT_RESERVED) {
17776 		next_priv_port = IPPORT_RESERVED - 1;
17777 		if (restart)
17778 			return (0);
17779 		restart = B_TRUE;
17780 	}
17781 	if (is_system_labeled() &&
17782 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17783 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17784 		next_priv_port = nextport;
17785 		goto retry;
17786 	}
17787 	return (next_priv_port--);
17788 }
17789 
17790 /* The write side r/w procedure. */
17791 
17792 #if CCS_STATS
17793 struct {
17794 	struct {
17795 		int64_t count, bytes;
17796 	} tot, hit;
17797 } wrw_stats;
17798 #endif
17799 
17800 /*
17801  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17802  * messages.
17803  */
17804 /* ARGSUSED */
17805 static void
17806 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17807 {
17808 	conn_t	*connp = (conn_t *)arg;
17809 	tcp_t	*tcp = connp->conn_tcp;
17810 	queue_t	*q = tcp->tcp_wq;
17811 
17812 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17813 	/*
17814 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17815 	 * Once the close starts, streamhead and sockfs will not let any data
17816 	 * packets come down (close ensures that there are no threads using the
17817 	 * queue and no new threads will come down) but since qprocsoff()
17818 	 * hasn't happened yet, a M_FLUSH or some non data message might
17819 	 * get reflected back (in response to our own FLUSHRW) and get
17820 	 * processed after tcp_close() is done. The conn would still be valid
17821 	 * because a ref would have added but we need to check the state
17822 	 * before actually processing the packet.
17823 	 */
17824 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17825 		freemsg(mp);
17826 		return;
17827 	}
17828 
17829 	switch (DB_TYPE(mp)) {
17830 	case M_IOCDATA:
17831 		tcp_wput_iocdata(tcp, mp);
17832 		break;
17833 	case M_FLUSH:
17834 		tcp_wput_flush(tcp, mp);
17835 		break;
17836 	default:
17837 		CALL_IP_WPUT(connp, q, mp);
17838 		break;
17839 	}
17840 }
17841 
17842 /*
17843  * The TCP fast path write put procedure.
17844  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17845  */
17846 /* ARGSUSED */
17847 void
17848 tcp_output(void *arg, mblk_t *mp, void *arg2)
17849 {
17850 	int		len;
17851 	int		hdrlen;
17852 	int		plen;
17853 	mblk_t		*mp1;
17854 	uchar_t		*rptr;
17855 	uint32_t	snxt;
17856 	tcph_t		*tcph;
17857 	struct datab	*db;
17858 	uint32_t	suna;
17859 	uint32_t	mss;
17860 	ipaddr_t	*dst;
17861 	ipaddr_t	*src;
17862 	uint32_t	sum;
17863 	int		usable;
17864 	conn_t		*connp = (conn_t *)arg;
17865 	tcp_t		*tcp = connp->conn_tcp;
17866 	uint32_t	msize;
17867 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17868 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17869 
17870 	/*
17871 	 * Try and ASSERT the minimum possible references on the
17872 	 * conn early enough. Since we are executing on write side,
17873 	 * the connection is obviously not detached and that means
17874 	 * there is a ref each for TCP and IP. Since we are behind
17875 	 * the squeue, the minimum references needed are 3. If the
17876 	 * conn is in classifier hash list, there should be an
17877 	 * extra ref for that (we check both the possibilities).
17878 	 */
17879 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17880 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17881 
17882 	ASSERT(DB_TYPE(mp) == M_DATA);
17883 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17884 
17885 	mutex_enter(&tcp->tcp_non_sq_lock);
17886 	tcp->tcp_squeue_bytes -= msize;
17887 	mutex_exit(&tcp->tcp_non_sq_lock);
17888 
17889 	/* Check to see if this connection wants to be re-fused. */
17890 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17891 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17892 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17893 			    &tcp->tcp_saved_tcph);
17894 		} else {
17895 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17896 			    &tcp->tcp_saved_tcph);
17897 		}
17898 	}
17899 	/* Bypass tcp protocol for fused tcp loopback */
17900 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17901 		return;
17902 
17903 	mss = tcp->tcp_mss;
17904 	if (tcp->tcp_xmit_zc_clean)
17905 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17906 
17907 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17908 	len = (int)(mp->b_wptr - mp->b_rptr);
17909 
17910 	/*
17911 	 * Criteria for fast path:
17912 	 *
17913 	 *   1. no unsent data
17914 	 *   2. single mblk in request
17915 	 *   3. connection established
17916 	 *   4. data in mblk
17917 	 *   5. len <= mss
17918 	 *   6. no tcp_valid bits
17919 	 */
17920 	if ((tcp->tcp_unsent != 0) ||
17921 	    (tcp->tcp_cork) ||
17922 	    (mp->b_cont != NULL) ||
17923 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17924 	    (len == 0) ||
17925 	    (len > mss) ||
17926 	    (tcp->tcp_valid_bits != 0)) {
17927 		tcp_wput_data(tcp, mp, B_FALSE);
17928 		return;
17929 	}
17930 
17931 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17932 	ASSERT(tcp->tcp_fin_sent == 0);
17933 
17934 	/* queue new packet onto retransmission queue */
17935 	if (tcp->tcp_xmit_head == NULL) {
17936 		tcp->tcp_xmit_head = mp;
17937 	} else {
17938 		tcp->tcp_xmit_last->b_cont = mp;
17939 	}
17940 	tcp->tcp_xmit_last = mp;
17941 	tcp->tcp_xmit_tail = mp;
17942 
17943 	/* find out how much we can send */
17944 	/* BEGIN CSTYLED */
17945 	/*
17946 	 *    un-acked           usable
17947 	 *  |--------------|-----------------|
17948 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17949 	 */
17950 	/* END CSTYLED */
17951 
17952 	/* start sending from tcp_snxt */
17953 	snxt = tcp->tcp_snxt;
17954 
17955 	/*
17956 	 * Check to see if this connection has been idled for some
17957 	 * time and no ACK is expected.  If it is, we need to slow
17958 	 * start again to get back the connection's "self-clock" as
17959 	 * described in VJ's paper.
17960 	 *
17961 	 * Refer to the comment in tcp_mss_set() for the calculation
17962 	 * of tcp_cwnd after idle.
17963 	 */
17964 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17965 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17966 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17967 	}
17968 
17969 	usable = tcp->tcp_swnd;		/* tcp window size */
17970 	if (usable > tcp->tcp_cwnd)
17971 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17972 	usable -= snxt;		/* subtract stuff already sent */
17973 	suna = tcp->tcp_suna;
17974 	usable += suna;
17975 	/* usable can be < 0 if the congestion window is smaller */
17976 	if (len > usable) {
17977 		/* Can't send complete M_DATA in one shot */
17978 		goto slow;
17979 	}
17980 
17981 	mutex_enter(&tcp->tcp_non_sq_lock);
17982 	if (tcp->tcp_flow_stopped &&
17983 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17984 		tcp_clrqfull(tcp);
17985 	}
17986 	mutex_exit(&tcp->tcp_non_sq_lock);
17987 
17988 	/*
17989 	 * determine if anything to send (Nagle).
17990 	 *
17991 	 *   1. len < tcp_mss (i.e. small)
17992 	 *   2. unacknowledged data present
17993 	 *   3. len < nagle limit
17994 	 *   4. last packet sent < nagle limit (previous packet sent)
17995 	 */
17996 	if ((len < mss) && (snxt != suna) &&
17997 	    (len < (int)tcp->tcp_naglim) &&
17998 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17999 		/*
18000 		 * This was the first unsent packet and normally
18001 		 * mss < xmit_hiwater so there is no need to worry
18002 		 * about flow control. The next packet will go
18003 		 * through the flow control check in tcp_wput_data().
18004 		 */
18005 		/* leftover work from above */
18006 		tcp->tcp_unsent = len;
18007 		tcp->tcp_xmit_tail_unsent = len;
18008 
18009 		return;
18010 	}
18011 
18012 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
18013 
18014 	if (snxt == suna) {
18015 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18016 	}
18017 
18018 	/* we have always sent something */
18019 	tcp->tcp_rack_cnt = 0;
18020 
18021 	tcp->tcp_snxt = snxt + len;
18022 	tcp->tcp_rack = tcp->tcp_rnxt;
18023 
18024 	if ((mp1 = dupb(mp)) == 0)
18025 		goto no_memory;
18026 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
18027 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
18028 
18029 	/* adjust tcp header information */
18030 	tcph = tcp->tcp_tcph;
18031 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
18032 
18033 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
18034 	sum = (sum >> 16) + (sum & 0xFFFF);
18035 	U16_TO_ABE16(sum, tcph->th_sum);
18036 
18037 	U32_TO_ABE32(snxt, tcph->th_seq);
18038 
18039 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
18040 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
18041 	BUMP_LOCAL(tcp->tcp_obsegs);
18042 
18043 	/* Update the latest receive window size in TCP header. */
18044 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18045 	    tcph->th_win);
18046 
18047 	tcp->tcp_last_sent_len = (ushort_t)len;
18048 
18049 	plen = len + tcp->tcp_hdr_len;
18050 
18051 	if (tcp->tcp_ipversion == IPV4_VERSION) {
18052 		tcp->tcp_ipha->ipha_length = htons(plen);
18053 	} else {
18054 		tcp->tcp_ip6h->ip6_plen = htons(plen -
18055 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
18056 	}
18057 
18058 	/* see if we need to allocate a mblk for the headers */
18059 	hdrlen = tcp->tcp_hdr_len;
18060 	rptr = mp1->b_rptr - hdrlen;
18061 	db = mp1->b_datap;
18062 	if ((db->db_ref != 2) || rptr < db->db_base ||
18063 	    (!OK_32PTR(rptr))) {
18064 		/* NOTE: we assume allocb returns an OK_32PTR */
18065 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
18066 		    tcps->tcps_wroff_xtra, BPRI_MED);
18067 		if (!mp) {
18068 			freemsg(mp1);
18069 			goto no_memory;
18070 		}
18071 		mp->b_cont = mp1;
18072 		mp1 = mp;
18073 		/* Leave room for Link Level header */
18074 		/* hdrlen = tcp->tcp_hdr_len; */
18075 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
18076 		mp1->b_wptr = &rptr[hdrlen];
18077 	}
18078 	mp1->b_rptr = rptr;
18079 
18080 	/* Fill in the timestamp option. */
18081 	if (tcp->tcp_snd_ts_ok) {
18082 		U32_TO_BE32((uint32_t)lbolt,
18083 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
18084 		U32_TO_BE32(tcp->tcp_ts_recent,
18085 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
18086 	} else {
18087 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18088 	}
18089 
18090 	/* copy header into outgoing packet */
18091 	dst = (ipaddr_t *)rptr;
18092 	src = (ipaddr_t *)tcp->tcp_iphc;
18093 	dst[0] = src[0];
18094 	dst[1] = src[1];
18095 	dst[2] = src[2];
18096 	dst[3] = src[3];
18097 	dst[4] = src[4];
18098 	dst[5] = src[5];
18099 	dst[6] = src[6];
18100 	dst[7] = src[7];
18101 	dst[8] = src[8];
18102 	dst[9] = src[9];
18103 	if (hdrlen -= 40) {
18104 		hdrlen >>= 2;
18105 		dst += 10;
18106 		src += 10;
18107 		do {
18108 			*dst++ = *src++;
18109 		} while (--hdrlen);
18110 	}
18111 
18112 	/*
18113 	 * Set the ECN info in the TCP header.  Note that this
18114 	 * is not the template header.
18115 	 */
18116 	if (tcp->tcp_ecn_ok) {
18117 		SET_ECT(tcp, rptr);
18118 
18119 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18120 		if (tcp->tcp_ecn_echo_on)
18121 			tcph->th_flags[0] |= TH_ECE;
18122 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18123 			tcph->th_flags[0] |= TH_CWR;
18124 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18125 		}
18126 	}
18127 
18128 	if (tcp->tcp_ip_forward_progress) {
18129 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
18130 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
18131 		tcp->tcp_ip_forward_progress = B_FALSE;
18132 	}
18133 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
18134 	return;
18135 
18136 	/*
18137 	 * If we ran out of memory, we pretend to have sent the packet
18138 	 * and that it was lost on the wire.
18139 	 */
18140 no_memory:
18141 	return;
18142 
18143 slow:
18144 	/* leftover work from above */
18145 	tcp->tcp_unsent = len;
18146 	tcp->tcp_xmit_tail_unsent = len;
18147 	tcp_wput_data(tcp, NULL, B_FALSE);
18148 }
18149 
18150 /*
18151  * The function called through squeue to get behind eager's perimeter to
18152  * finish the accept processing.
18153  */
18154 /* ARGSUSED */
18155 void
18156 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
18157 {
18158 	conn_t			*connp = (conn_t *)arg;
18159 	tcp_t			*tcp = connp->conn_tcp;
18160 	queue_t			*q = tcp->tcp_rq;
18161 	mblk_t			*mp1;
18162 	mblk_t			*stropt_mp = mp;
18163 	struct  stroptions	*stropt;
18164 	uint_t			thwin;
18165 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18166 
18167 	/*
18168 	 * Drop the eager's ref on the listener, that was placed when
18169 	 * this eager began life in tcp_conn_request.
18170 	 */
18171 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
18172 
18173 	tcp->tcp_detached = B_FALSE;
18174 
18175 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
18176 		/*
18177 		 * Someone blewoff the eager before we could finish
18178 		 * the accept.
18179 		 *
18180 		 * The only reason eager exists it because we put in
18181 		 * a ref on it when conn ind went up. We need to send
18182 		 * a disconnect indication up while the last reference
18183 		 * on the eager will be dropped by the squeue when we
18184 		 * return.
18185 		 */
18186 		ASSERT(tcp->tcp_listener == NULL);
18187 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
18188 			struct	T_discon_ind	*tdi;
18189 
18190 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
18191 			/*
18192 			 * Let us reuse the incoming mblk to avoid memory
18193 			 * allocation failure problems. We know that the
18194 			 * size of the incoming mblk i.e. stroptions is greater
18195 			 * than sizeof T_discon_ind. So the reallocb below
18196 			 * can't fail.
18197 			 */
18198 			freemsg(mp->b_cont);
18199 			mp->b_cont = NULL;
18200 			ASSERT(DB_REF(mp) == 1);
18201 			mp = reallocb(mp, sizeof (struct T_discon_ind),
18202 			    B_FALSE);
18203 			ASSERT(mp != NULL);
18204 			DB_TYPE(mp) = M_PROTO;
18205 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
18206 			tdi = (struct T_discon_ind *)mp->b_rptr;
18207 			if (tcp->tcp_issocket) {
18208 				tdi->DISCON_reason = ECONNREFUSED;
18209 				tdi->SEQ_number = 0;
18210 			} else {
18211 				tdi->DISCON_reason = ENOPROTOOPT;
18212 				tdi->SEQ_number =
18213 				    tcp->tcp_conn_req_seqnum;
18214 			}
18215 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
18216 			putnext(q, mp);
18217 		} else {
18218 			freemsg(mp);
18219 		}
18220 		if (tcp->tcp_hard_binding) {
18221 			tcp->tcp_hard_binding = B_FALSE;
18222 			tcp->tcp_hard_bound = B_TRUE;
18223 		}
18224 		return;
18225 	}
18226 
18227 	mp1 = stropt_mp->b_cont;
18228 	stropt_mp->b_cont = NULL;
18229 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
18230 	stropt = (struct stroptions *)stropt_mp->b_rptr;
18231 
18232 	while (mp1 != NULL) {
18233 		mp = mp1;
18234 		mp1 = mp1->b_cont;
18235 		mp->b_cont = NULL;
18236 		tcp->tcp_drop_opt_ack_cnt++;
18237 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
18238 	}
18239 	mp = NULL;
18240 
18241 	/*
18242 	 * For a loopback connection with tcp_direct_sockfs on, note that
18243 	 * we don't have to protect tcp_rcv_list yet because synchronous
18244 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
18245 	 * possibly race with us.
18246 	 */
18247 
18248 	/*
18249 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
18250 	 * properly.  This is the first time we know of the acceptor'
18251 	 * queue.  So we do it here.
18252 	 */
18253 	if (tcp->tcp_rcv_list == NULL) {
18254 		/*
18255 		 * Recv queue is empty, tcp_rwnd should not have changed.
18256 		 * That means it should be equal to the listener's tcp_rwnd.
18257 		 */
18258 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
18259 	} else {
18260 #ifdef DEBUG
18261 		uint_t cnt = 0;
18262 
18263 		mp1 = tcp->tcp_rcv_list;
18264 		while ((mp = mp1) != NULL) {
18265 			mp1 = mp->b_next;
18266 			cnt += msgdsize(mp);
18267 		}
18268 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
18269 #endif
18270 		/* There is some data, add them back to get the max. */
18271 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18272 	}
18273 	/*
18274 	 * This is the first time we run on the correct
18275 	 * queue after tcp_accept. So fix all the q parameters
18276 	 * here.
18277 	 */
18278 	stropt->so_flags = SO_HIWAT | SO_MAXBLK | SO_WROFF;
18279 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
18280 
18281 	/*
18282 	 * Record the stream head's high water mark for this endpoint;
18283 	 * this is used for flow-control purposes.
18284 	 */
18285 	stropt->so_hiwat = tcp->tcp_fused ?
18286 	    tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat) :
18287 	    MAX(q->q_hiwat, tcps->tcps_sth_rcv_hiwat);
18288 
18289 	/*
18290 	 * Determine what write offset value to use depending on SACK and
18291 	 * whether the endpoint is fused or not.
18292 	 */
18293 	if (tcp->tcp_fused) {
18294 		ASSERT(tcp->tcp_loopback);
18295 		ASSERT(tcp->tcp_loopback_peer != NULL);
18296 		/*
18297 		 * For fused tcp loopback, set the stream head's write
18298 		 * offset value to zero since we won't be needing any room
18299 		 * for TCP/IP headers.  This would also improve performance
18300 		 * since it would reduce the amount of work done by kmem.
18301 		 * Non-fused tcp loopback case is handled separately below.
18302 		 */
18303 		stropt->so_wroff = 0;
18304 		/*
18305 		 * Update the peer's transmit parameters according to
18306 		 * our recently calculated high water mark value.
18307 		 */
18308 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18309 	} else if (tcp->tcp_snd_sack_ok) {
18310 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18311 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18312 	} else {
18313 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18314 		    tcps->tcps_wroff_xtra);
18315 	}
18316 
18317 	/*
18318 	 * If this is endpoint is handling SSL, then reserve extra
18319 	 * offset and space at the end.
18320 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18321 	 * overriding the previous setting. The extra cost of signing and
18322 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18323 	 * instead of a single contiguous one by the stream head
18324 	 * largely outweighs the statistical reduction of ACKs, when
18325 	 * applicable. The peer will also save on decryption and verification
18326 	 * costs.
18327 	 */
18328 	if (tcp->tcp_kssl_ctx != NULL) {
18329 		stropt->so_wroff += SSL3_WROFFSET;
18330 
18331 		stropt->so_flags |= SO_TAIL;
18332 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
18333 
18334 		stropt->so_flags |= SO_COPYOPT;
18335 		stropt->so_copyopt = ZCVMUNSAFE;
18336 
18337 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
18338 	}
18339 
18340 	/* Send the options up */
18341 	putnext(q, stropt_mp);
18342 
18343 	/*
18344 	 * Pass up any data and/or a fin that has been received.
18345 	 *
18346 	 * Adjust receive window in case it had decreased
18347 	 * (because there is data <=> tcp_rcv_list != NULL)
18348 	 * while the connection was detached. Note that
18349 	 * in case the eager was flow-controlled, w/o this
18350 	 * code, the rwnd may never open up again!
18351 	 */
18352 	if (tcp->tcp_rcv_list != NULL) {
18353 		/* We drain directly in case of fused tcp loopback */
18354 		sodirect_t *sodp;
18355 
18356 		if (!tcp->tcp_fused && canputnext(q)) {
18357 			tcp->tcp_rwnd = q->q_hiwat;
18358 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
18359 			    << tcp->tcp_rcv_ws;
18360 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
18361 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18362 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
18363 				tcp_xmit_ctl(NULL,
18364 				    tcp, (tcp->tcp_swnd == 0) ?
18365 				    tcp->tcp_suna : tcp->tcp_snxt,
18366 				    tcp->tcp_rnxt, TH_ACK);
18367 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
18368 			}
18369 
18370 		}
18371 
18372 		SOD_PTR_ENTER(tcp, sodp);
18373 		if (sodp != NULL) {
18374 			/* Sodirect, move from rcv_list */
18375 			ASSERT(!tcp->tcp_fused);
18376 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18377 				tcp->tcp_rcv_list = mp->b_next;
18378 				mp->b_next = NULL;
18379 				(void) tcp_rcv_sod_enqueue(tcp, sodp, mp,
18380 				    msgdsize(mp));
18381 			}
18382 			tcp->tcp_rcv_last_head = NULL;
18383 			tcp->tcp_rcv_last_tail = NULL;
18384 			tcp->tcp_rcv_cnt = 0;
18385 			(void) tcp_rcv_sod_wakeup(tcp, sodp);
18386 			/* sod_wakeup() did the mutex_exit() */
18387 		} else {
18388 			/* Not sodirect, drain */
18389 			(void) tcp_rcv_drain(q, tcp);
18390 		}
18391 
18392 		/*
18393 		 * For fused tcp loopback, back-enable peer endpoint
18394 		 * if it's currently flow-controlled.
18395 		 */
18396 		if (tcp->tcp_fused) {
18397 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18398 
18399 			ASSERT(peer_tcp != NULL);
18400 			ASSERT(peer_tcp->tcp_fused);
18401 			/*
18402 			 * In order to change the peer's tcp_flow_stopped,
18403 			 * we need to take locks for both end points. The
18404 			 * highest address is taken first.
18405 			 */
18406 			if (peer_tcp > tcp) {
18407 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18408 				mutex_enter(&tcp->tcp_non_sq_lock);
18409 			} else {
18410 				mutex_enter(&tcp->tcp_non_sq_lock);
18411 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18412 			}
18413 			if (peer_tcp->tcp_flow_stopped) {
18414 				tcp_clrqfull(peer_tcp);
18415 				TCP_STAT(tcps, tcp_fusion_backenabled);
18416 			}
18417 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18418 			mutex_exit(&tcp->tcp_non_sq_lock);
18419 		}
18420 	}
18421 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18422 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18423 		mp = tcp->tcp_ordrel_mp;
18424 		tcp->tcp_ordrel_mp = NULL;
18425 		tcp->tcp_ordrel_done = B_TRUE;
18426 		putnext(q, mp);
18427 	}
18428 	if (tcp->tcp_hard_binding) {
18429 		tcp->tcp_hard_binding = B_FALSE;
18430 		tcp->tcp_hard_bound = B_TRUE;
18431 	}
18432 
18433 	/* We can enable synchronous streams now */
18434 	if (tcp->tcp_fused) {
18435 		tcp_fuse_syncstr_enable_pair(tcp);
18436 	}
18437 
18438 	if (tcp->tcp_ka_enabled) {
18439 		tcp->tcp_ka_last_intrvl = 0;
18440 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18441 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18442 	}
18443 
18444 	/*
18445 	 * At this point, eager is fully established and will
18446 	 * have the following references -
18447 	 *
18448 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18449 	 * 1 reference for the squeue which will be dropped by the squeue as
18450 	 *	soon as this function returns.
18451 	 * There will be 1 additonal reference for being in classifier
18452 	 *	hash list provided something bad hasn't happened.
18453 	 */
18454 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18455 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18456 }
18457 
18458 /*
18459  * The function called through squeue to get behind listener's perimeter to
18460  * send a deffered conn_ind.
18461  */
18462 /* ARGSUSED */
18463 void
18464 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18465 {
18466 	conn_t	*connp = (conn_t *)arg;
18467 	tcp_t *listener = connp->conn_tcp;
18468 
18469 	if (listener->tcp_state == TCPS_CLOSED ||
18470 	    TCP_IS_DETACHED(listener)) {
18471 		/*
18472 		 * If listener has closed, it would have caused a
18473 		 * a cleanup/blowoff to happen for the eager.
18474 		 */
18475 		tcp_t *tcp;
18476 		struct T_conn_ind	*conn_ind;
18477 
18478 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18479 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18480 		    conn_ind->OPT_length);
18481 		/*
18482 		 * We need to drop the ref on eager that was put
18483 		 * tcp_rput_data() before trying to send the conn_ind
18484 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18485 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18486 		 * listener is closed so we drop the ref.
18487 		 */
18488 		CONN_DEC_REF(tcp->tcp_connp);
18489 		freemsg(mp);
18490 		return;
18491 	}
18492 	putnext(listener->tcp_rq, mp);
18493 }
18494 
18495 
18496 /*
18497  * This is the STREAMS entry point for T_CONN_RES coming down on
18498  * Acceptor STREAM when  sockfs listener does accept processing.
18499  * Read the block comment on top of tcp_conn_request().
18500  */
18501 void
18502 tcp_wput_accept(queue_t *q, mblk_t *mp)
18503 {
18504 	queue_t *rq = RD(q);
18505 	struct T_conn_res *conn_res;
18506 	tcp_t *eager;
18507 	tcp_t *listener;
18508 	struct T_ok_ack *ok;
18509 	t_scalar_t PRIM_type;
18510 	mblk_t *opt_mp;
18511 	conn_t *econnp;
18512 
18513 	ASSERT(DB_TYPE(mp) == M_PROTO);
18514 
18515 	conn_res = (struct T_conn_res *)mp->b_rptr;
18516 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18517 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18518 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18519 		if (mp != NULL)
18520 			putnext(rq, mp);
18521 		return;
18522 	}
18523 	switch (conn_res->PRIM_type) {
18524 	case O_T_CONN_RES:
18525 	case T_CONN_RES:
18526 		/*
18527 		 * We pass up an err ack if allocb fails. This will
18528 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18529 		 * tcp_eager_blowoff to be called. sockfs will then call
18530 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18531 		 * we need to do the allocb up here because we have to
18532 		 * make sure rq->q_qinfo->qi_qclose still points to the
18533 		 * correct function (tcpclose_accept) in case allocb
18534 		 * fails.
18535 		 */
18536 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18537 		if (opt_mp == NULL) {
18538 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18539 			if (mp != NULL)
18540 				putnext(rq, mp);
18541 			return;
18542 		}
18543 
18544 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18545 		    &eager, conn_res->OPT_length);
18546 		PRIM_type = conn_res->PRIM_type;
18547 		mp->b_datap->db_type = M_PCPROTO;
18548 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18549 		ok = (struct T_ok_ack *)mp->b_rptr;
18550 		ok->PRIM_type = T_OK_ACK;
18551 		ok->CORRECT_prim = PRIM_type;
18552 		econnp = eager->tcp_connp;
18553 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18554 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18555 		eager->tcp_rq = rq;
18556 		eager->tcp_wq = q;
18557 		rq->q_ptr = econnp;
18558 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18559 		q->q_ptr = econnp;
18560 		q->q_qinfo = &tcp_winit;
18561 		listener = eager->tcp_listener;
18562 		eager->tcp_issocket = B_TRUE;
18563 
18564 		/*
18565 		 * TCP is _D_SODIRECT and sockfs is directly above so
18566 		 * save shared sodirect_t pointer (if any).
18567 		 *
18568 		 * If tcp_fused and sodirect enabled disable it.
18569 		 */
18570 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18571 		if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18572 			/* Fused, disable sodirect */
18573 			mutex_enter(eager->tcp_sodirect->sod_lockp);
18574 			SOD_DISABLE(eager->tcp_sodirect);
18575 			mutex_exit(eager->tcp_sodirect->sod_lockp);
18576 			eager->tcp_sodirect = NULL;
18577 		}
18578 
18579 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18580 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18581 		ASSERT(econnp->conn_netstack ==
18582 		    listener->tcp_connp->conn_netstack);
18583 		ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18584 
18585 		/* Put the ref for IP */
18586 		CONN_INC_REF(econnp);
18587 
18588 		/*
18589 		 * We should have minimum of 3 references on the conn
18590 		 * at this point. One each for TCP and IP and one for
18591 		 * the T_conn_ind that was sent up when the 3-way handshake
18592 		 * completed. In the normal case we would also have another
18593 		 * reference (making a total of 4) for the conn being in the
18594 		 * classifier hash list. However the eager could have received
18595 		 * an RST subsequently and tcp_closei_local could have removed
18596 		 * the eager from the classifier hash list, hence we can't
18597 		 * assert that reference.
18598 		 */
18599 		ASSERT(econnp->conn_ref >= 3);
18600 
18601 		/*
18602 		 * Send the new local address also up to sockfs. There
18603 		 * should already be enough space in the mp that came
18604 		 * down from soaccept().
18605 		 */
18606 		if (eager->tcp_family == AF_INET) {
18607 			sin_t *sin;
18608 
18609 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18610 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18611 			sin = (sin_t *)mp->b_wptr;
18612 			mp->b_wptr += sizeof (sin_t);
18613 			sin->sin_family = AF_INET;
18614 			sin->sin_port = eager->tcp_lport;
18615 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18616 		} else {
18617 			sin6_t *sin6;
18618 
18619 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18620 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18621 			sin6 = (sin6_t *)mp->b_wptr;
18622 			mp->b_wptr += sizeof (sin6_t);
18623 			sin6->sin6_family = AF_INET6;
18624 			sin6->sin6_port = eager->tcp_lport;
18625 			if (eager->tcp_ipversion == IPV4_VERSION) {
18626 				sin6->sin6_flowinfo = 0;
18627 				IN6_IPADDR_TO_V4MAPPED(
18628 				    eager->tcp_ipha->ipha_src,
18629 				    &sin6->sin6_addr);
18630 			} else {
18631 				ASSERT(eager->tcp_ip6h != NULL);
18632 				sin6->sin6_flowinfo =
18633 				    eager->tcp_ip6h->ip6_vcf &
18634 				    ~IPV6_VERS_AND_FLOW_MASK;
18635 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18636 			}
18637 			sin6->sin6_scope_id = 0;
18638 			sin6->__sin6_src_id = 0;
18639 		}
18640 
18641 		putnext(rq, mp);
18642 
18643 		opt_mp->b_datap->db_type = M_SETOPTS;
18644 		opt_mp->b_wptr += sizeof (struct stroptions);
18645 
18646 		/*
18647 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18648 		 * from listener to acceptor. The message is chained on the
18649 		 * bind_mp which tcp_rput_other will send down to IP.
18650 		 */
18651 		if (listener->tcp_bound_if != 0) {
18652 			/* allocate optmgmt req */
18653 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18654 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18655 			    sizeof (int));
18656 			if (mp != NULL)
18657 				linkb(opt_mp, mp);
18658 		}
18659 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18660 			uint_t on = 1;
18661 
18662 			/* allocate optmgmt req */
18663 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18664 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18665 			if (mp != NULL)
18666 				linkb(opt_mp, mp);
18667 		}
18668 
18669 
18670 		mutex_enter(&listener->tcp_eager_lock);
18671 
18672 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18673 
18674 			tcp_t *tail;
18675 			tcp_t *tcp;
18676 			mblk_t *mp1;
18677 
18678 			tcp = listener->tcp_eager_prev_q0;
18679 			/*
18680 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18681 			 * deferred T_conn_ind queue. We need to get to the head
18682 			 * of the queue in order to send up T_conn_ind the same
18683 			 * order as how the 3WHS is completed.
18684 			 */
18685 			while (tcp != listener) {
18686 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18687 				    !tcp->tcp_kssl_pending)
18688 					break;
18689 				else
18690 					tcp = tcp->tcp_eager_prev_q0;
18691 			}
18692 			/* None of the pending eagers can be sent up now */
18693 			if (tcp == listener)
18694 				goto no_more_eagers;
18695 
18696 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18697 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18698 			/* Move from q0 to q */
18699 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18700 			listener->tcp_conn_req_cnt_q0--;
18701 			listener->tcp_conn_req_cnt_q++;
18702 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18703 			    tcp->tcp_eager_prev_q0;
18704 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18705 			    tcp->tcp_eager_next_q0;
18706 			tcp->tcp_eager_prev_q0 = NULL;
18707 			tcp->tcp_eager_next_q0 = NULL;
18708 			tcp->tcp_conn_def_q0 = B_FALSE;
18709 
18710 			/* Make sure the tcp isn't in the list of droppables */
18711 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18712 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18713 
18714 			/*
18715 			 * Insert at end of the queue because sockfs sends
18716 			 * down T_CONN_RES in chronological order. Leaving
18717 			 * the older conn indications at front of the queue
18718 			 * helps reducing search time.
18719 			 */
18720 			tail = listener->tcp_eager_last_q;
18721 			if (tail != NULL) {
18722 				tail->tcp_eager_next_q = tcp;
18723 			} else {
18724 				listener->tcp_eager_next_q = tcp;
18725 			}
18726 			listener->tcp_eager_last_q = tcp;
18727 			tcp->tcp_eager_next_q = NULL;
18728 
18729 			/* Need to get inside the listener perimeter */
18730 			CONN_INC_REF(listener->tcp_connp);
18731 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18732 			    tcp_send_pending, listener->tcp_connp,
18733 			    SQTAG_TCP_SEND_PENDING);
18734 		}
18735 no_more_eagers:
18736 		tcp_eager_unlink(eager);
18737 		mutex_exit(&listener->tcp_eager_lock);
18738 
18739 		/*
18740 		 * At this point, the eager is detached from the listener
18741 		 * but we still have an extra refs on eager (apart from the
18742 		 * usual tcp references). The ref was placed in tcp_rput_data
18743 		 * before sending the conn_ind in tcp_send_conn_ind.
18744 		 * The ref will be dropped in tcp_accept_finish().
18745 		 */
18746 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18747 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18748 		return;
18749 	default:
18750 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18751 		if (mp != NULL)
18752 			putnext(rq, mp);
18753 		return;
18754 	}
18755 }
18756 
18757 static int
18758 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18759 {
18760 	sin_t *sin = (sin_t *)sa;
18761 	sin6_t *sin6 = (sin6_t *)sa;
18762 
18763 	switch (tcp->tcp_family) {
18764 	case AF_INET:
18765 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18766 
18767 		if (*salenp < sizeof (sin_t))
18768 			return (EINVAL);
18769 
18770 		*sin = sin_null;
18771 		sin->sin_family = AF_INET;
18772 		sin->sin_port = tcp->tcp_lport;
18773 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18774 		break;
18775 
18776 	case AF_INET6:
18777 		if (*salenp < sizeof (sin6_t))
18778 			return (EINVAL);
18779 
18780 		*sin6 = sin6_null;
18781 		sin6->sin6_family = AF_INET6;
18782 		sin6->sin6_port = tcp->tcp_lport;
18783 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18784 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18785 			    &sin6->sin6_addr);
18786 		} else {
18787 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18788 		}
18789 		break;
18790 	}
18791 
18792 	return (0);
18793 }
18794 
18795 static int
18796 tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18797 {
18798 	sin_t *sin = (sin_t *)sa;
18799 	sin6_t *sin6 = (sin6_t *)sa;
18800 
18801 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18802 		return (ENOTCONN);
18803 
18804 	switch (tcp->tcp_family) {
18805 	case AF_INET:
18806 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18807 
18808 		if (*salenp < sizeof (sin_t))
18809 			return (EINVAL);
18810 
18811 		*sin = sin_null;
18812 		sin->sin_family = AF_INET;
18813 		sin->sin_port = tcp->tcp_fport;
18814 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18815 		    sin->sin_addr.s_addr);
18816 		break;
18817 
18818 	case AF_INET6:
18819 		if (*salenp < sizeof (sin6_t))
18820 			return (EINVAL);
18821 
18822 		*sin6 = sin6_null;
18823 		sin6->sin6_family = AF_INET6;
18824 		sin6->sin6_port = tcp->tcp_fport;
18825 		sin6->sin6_addr = tcp->tcp_remote_v6;
18826 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18827 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18828 			    ~IPV6_VERS_AND_FLOW_MASK;
18829 		}
18830 		break;
18831 	}
18832 
18833 	return (0);
18834 }
18835 
18836 /*
18837  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18838  */
18839 static void
18840 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18841 {
18842 	void	*data;
18843 	mblk_t	*datamp = mp->b_cont;
18844 	tcp_t	*tcp = Q_TO_TCP(q);
18845 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18846 
18847 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18848 		cmdp->cb_error = EPROTO;
18849 		qreply(q, mp);
18850 		return;
18851 	}
18852 
18853 	data = datamp->b_rptr;
18854 
18855 	switch (cmdp->cb_cmd) {
18856 	case TI_GETPEERNAME:
18857 		cmdp->cb_error = tcp_getpeername(tcp, data, &cmdp->cb_len);
18858 		break;
18859 	case TI_GETMYNAME:
18860 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
18861 		break;
18862 	default:
18863 		cmdp->cb_error = EINVAL;
18864 		break;
18865 	}
18866 
18867 	qreply(q, mp);
18868 }
18869 
18870 void
18871 tcp_wput(queue_t *q, mblk_t *mp)
18872 {
18873 	conn_t	*connp = Q_TO_CONN(q);
18874 	tcp_t	*tcp;
18875 	void (*output_proc)();
18876 	t_scalar_t type;
18877 	uchar_t *rptr;
18878 	struct iocblk	*iocp;
18879 	uint32_t	msize;
18880 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18881 
18882 	ASSERT(connp->conn_ref >= 2);
18883 
18884 	switch (DB_TYPE(mp)) {
18885 	case M_DATA:
18886 		tcp = connp->conn_tcp;
18887 		ASSERT(tcp != NULL);
18888 
18889 		msize = msgdsize(mp);
18890 
18891 		mutex_enter(&tcp->tcp_non_sq_lock);
18892 		tcp->tcp_squeue_bytes += msize;
18893 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18894 			tcp_setqfull(tcp);
18895 		}
18896 		mutex_exit(&tcp->tcp_non_sq_lock);
18897 
18898 		CONN_INC_REF(connp);
18899 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18900 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18901 		return;
18902 
18903 	case M_CMD:
18904 		tcp_wput_cmdblk(q, mp);
18905 		return;
18906 
18907 	case M_PROTO:
18908 	case M_PCPROTO:
18909 		/*
18910 		 * if it is a snmp message, don't get behind the squeue
18911 		 */
18912 		tcp = connp->conn_tcp;
18913 		rptr = mp->b_rptr;
18914 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18915 			type = ((union T_primitives *)rptr)->type;
18916 		} else {
18917 			if (tcp->tcp_debug) {
18918 				(void) strlog(TCP_MOD_ID, 0, 1,
18919 				    SL_ERROR|SL_TRACE,
18920 				    "tcp_wput_proto, dropping one...");
18921 			}
18922 			freemsg(mp);
18923 			return;
18924 		}
18925 		if (type == T_SVR4_OPTMGMT_REQ) {
18926 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18927 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18928 			    cr)) {
18929 				/*
18930 				 * This was a SNMP request
18931 				 */
18932 				return;
18933 			} else {
18934 				output_proc = tcp_wput_proto;
18935 			}
18936 		} else {
18937 			output_proc = tcp_wput_proto;
18938 		}
18939 		break;
18940 	case M_IOCTL:
18941 		/*
18942 		 * Most ioctls can be processed right away without going via
18943 		 * squeues - process them right here. Those that do require
18944 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18945 		 * are processed by tcp_wput_ioctl().
18946 		 */
18947 		iocp = (struct iocblk *)mp->b_rptr;
18948 		tcp = connp->conn_tcp;
18949 
18950 		switch (iocp->ioc_cmd) {
18951 		case TCP_IOC_ABORT_CONN:
18952 			tcp_ioctl_abort_conn(q, mp);
18953 			return;
18954 		case TI_GETPEERNAME:
18955 		case TI_GETMYNAME:
18956 			mi_copyin(q, mp, NULL,
18957 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18958 			return;
18959 		case ND_SET:
18960 			/* nd_getset does the necessary checks */
18961 		case ND_GET:
18962 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18963 				CALL_IP_WPUT(connp, q, mp);
18964 				return;
18965 			}
18966 			qreply(q, mp);
18967 			return;
18968 		case TCP_IOC_DEFAULT_Q:
18969 			/*
18970 			 * Wants to be the default wq. Check the credentials
18971 			 * first, the rest is executed via squeue.
18972 			 */
18973 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18974 				iocp->ioc_error = EPERM;
18975 				iocp->ioc_count = 0;
18976 				mp->b_datap->db_type = M_IOCACK;
18977 				qreply(q, mp);
18978 				return;
18979 			}
18980 			output_proc = tcp_wput_ioctl;
18981 			break;
18982 		default:
18983 			output_proc = tcp_wput_ioctl;
18984 			break;
18985 		}
18986 		break;
18987 	default:
18988 		output_proc = tcp_wput_nondata;
18989 		break;
18990 	}
18991 
18992 	CONN_INC_REF(connp);
18993 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18994 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
18995 }
18996 
18997 /*
18998  * Initial STREAMS write side put() procedure for sockets. It tries to
18999  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
19000  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
19001  * are handled by tcp_wput() as usual.
19002  *
19003  * All further messages will also be handled by tcp_wput() because we cannot
19004  * be sure that the above short cut is safe later.
19005  */
19006 static void
19007 tcp_wput_sock(queue_t *wq, mblk_t *mp)
19008 {
19009 	conn_t			*connp = Q_TO_CONN(wq);
19010 	tcp_t			*tcp = connp->conn_tcp;
19011 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
19012 
19013 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
19014 	wq->q_qinfo = &tcp_winit;
19015 
19016 	ASSERT(IPCL_IS_TCP(connp));
19017 	ASSERT(TCP_IS_SOCKET(tcp));
19018 
19019 	if (DB_TYPE(mp) == M_PCPROTO &&
19020 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
19021 	    car->PRIM_type == T_CAPABILITY_REQ) {
19022 		tcp_capability_req(tcp, mp);
19023 		return;
19024 	}
19025 
19026 	tcp_wput(wq, mp);
19027 }
19028 
19029 static boolean_t
19030 tcp_zcopy_check(tcp_t *tcp)
19031 {
19032 	conn_t	*connp = tcp->tcp_connp;
19033 	ire_t	*ire;
19034 	boolean_t	zc_enabled = B_FALSE;
19035 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19036 
19037 	if (do_tcpzcopy == 2)
19038 		zc_enabled = B_TRUE;
19039 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
19040 	    IPCL_IS_CONNECTED(connp) &&
19041 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
19042 	    connp->conn_dontroute == 0 &&
19043 	    !connp->conn_nexthop_set &&
19044 	    connp->conn_outgoing_ill == NULL &&
19045 	    connp->conn_nofailover_ill == NULL &&
19046 	    do_tcpzcopy == 1) {
19047 		/*
19048 		 * the checks above  closely resemble the fast path checks
19049 		 * in tcp_send_data().
19050 		 */
19051 		mutex_enter(&connp->conn_lock);
19052 		ire = connp->conn_ire_cache;
19053 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19054 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19055 			IRE_REFHOLD(ire);
19056 			if (ire->ire_stq != NULL) {
19057 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
19058 
19059 				zc_enabled = ill && (ill->ill_capabilities &
19060 				    ILL_CAPAB_ZEROCOPY) &&
19061 				    (ill->ill_zerocopy_capab->
19062 				    ill_zerocopy_flags != 0);
19063 			}
19064 			IRE_REFRELE(ire);
19065 		}
19066 		mutex_exit(&connp->conn_lock);
19067 	}
19068 	tcp->tcp_snd_zcopy_on = zc_enabled;
19069 	if (!TCP_IS_DETACHED(tcp)) {
19070 		if (zc_enabled) {
19071 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
19072 			TCP_STAT(tcps, tcp_zcopy_on);
19073 		} else {
19074 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19075 			TCP_STAT(tcps, tcp_zcopy_off);
19076 		}
19077 	}
19078 	return (zc_enabled);
19079 }
19080 
19081 static mblk_t *
19082 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
19083 {
19084 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19085 
19086 	if (do_tcpzcopy == 2)
19087 		return (bp);
19088 	else if (tcp->tcp_snd_zcopy_on) {
19089 		tcp->tcp_snd_zcopy_on = B_FALSE;
19090 		if (!TCP_IS_DETACHED(tcp)) {
19091 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19092 			TCP_STAT(tcps, tcp_zcopy_disable);
19093 		}
19094 	}
19095 	return (tcp_zcopy_backoff(tcp, bp, 0));
19096 }
19097 
19098 /*
19099  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
19100  * the original desballoca'ed segmapped mblk.
19101  */
19102 static mblk_t *
19103 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
19104 {
19105 	mblk_t *head, *tail, *nbp;
19106 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19107 
19108 	if (IS_VMLOANED_MBLK(bp)) {
19109 		TCP_STAT(tcps, tcp_zcopy_backoff);
19110 		if ((head = copyb(bp)) == NULL) {
19111 			/* fail to backoff; leave it for the next backoff */
19112 			tcp->tcp_xmit_zc_clean = B_FALSE;
19113 			return (bp);
19114 		}
19115 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19116 			if (fix_xmitlist)
19117 				tcp_zcopy_notify(tcp);
19118 			else
19119 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19120 		}
19121 		nbp = bp->b_cont;
19122 		if (fix_xmitlist) {
19123 			head->b_prev = bp->b_prev;
19124 			head->b_next = bp->b_next;
19125 			if (tcp->tcp_xmit_tail == bp)
19126 				tcp->tcp_xmit_tail = head;
19127 		}
19128 		bp->b_next = NULL;
19129 		bp->b_prev = NULL;
19130 		freeb(bp);
19131 	} else {
19132 		head = bp;
19133 		nbp = bp->b_cont;
19134 	}
19135 	tail = head;
19136 	while (nbp) {
19137 		if (IS_VMLOANED_MBLK(nbp)) {
19138 			TCP_STAT(tcps, tcp_zcopy_backoff);
19139 			if ((tail->b_cont = copyb(nbp)) == NULL) {
19140 				tcp->tcp_xmit_zc_clean = B_FALSE;
19141 				tail->b_cont = nbp;
19142 				return (head);
19143 			}
19144 			tail = tail->b_cont;
19145 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19146 				if (fix_xmitlist)
19147 					tcp_zcopy_notify(tcp);
19148 				else
19149 					tail->b_datap->db_struioflag |=
19150 					    STRUIO_ZCNOTIFY;
19151 			}
19152 			bp = nbp;
19153 			nbp = nbp->b_cont;
19154 			if (fix_xmitlist) {
19155 				tail->b_prev = bp->b_prev;
19156 				tail->b_next = bp->b_next;
19157 				if (tcp->tcp_xmit_tail == bp)
19158 					tcp->tcp_xmit_tail = tail;
19159 			}
19160 			bp->b_next = NULL;
19161 			bp->b_prev = NULL;
19162 			freeb(bp);
19163 		} else {
19164 			tail->b_cont = nbp;
19165 			tail = nbp;
19166 			nbp = nbp->b_cont;
19167 		}
19168 	}
19169 	if (fix_xmitlist) {
19170 		tcp->tcp_xmit_last = tail;
19171 		tcp->tcp_xmit_zc_clean = B_TRUE;
19172 	}
19173 	return (head);
19174 }
19175 
19176 static void
19177 tcp_zcopy_notify(tcp_t *tcp)
19178 {
19179 	struct stdata	*stp;
19180 
19181 	if (tcp->tcp_detached)
19182 		return;
19183 	stp = STREAM(tcp->tcp_rq);
19184 	mutex_enter(&stp->sd_lock);
19185 	stp->sd_flag |= STZCNOTIFY;
19186 	cv_broadcast(&stp->sd_zcopy_wait);
19187 	mutex_exit(&stp->sd_lock);
19188 }
19189 
19190 static boolean_t
19191 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19192 {
19193 	ire_t	*ire;
19194 	conn_t	*connp = tcp->tcp_connp;
19195 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19196 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19197 
19198 	mutex_enter(&connp->conn_lock);
19199 	ire = connp->conn_ire_cache;
19200 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19201 
19202 	if ((ire != NULL) &&
19203 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19204 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19205 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19206 		IRE_REFHOLD(ire);
19207 		mutex_exit(&connp->conn_lock);
19208 	} else {
19209 		boolean_t cached = B_FALSE;
19210 		ts_label_t *tsl;
19211 
19212 		/* force a recheck later on */
19213 		tcp->tcp_ire_ill_check_done = B_FALSE;
19214 
19215 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19216 		connp->conn_ire_cache = NULL;
19217 		mutex_exit(&connp->conn_lock);
19218 
19219 		if (ire != NULL)
19220 			IRE_REFRELE_NOTR(ire);
19221 
19222 		tsl = crgetlabel(CONN_CRED(connp));
19223 		ire = (dst ?
19224 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19225 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19226 		    connp->conn_zoneid, tsl, ipst));
19227 
19228 		if (ire == NULL) {
19229 			TCP_STAT(tcps, tcp_ire_null);
19230 			return (B_FALSE);
19231 		}
19232 
19233 		IRE_REFHOLD_NOTR(ire);
19234 
19235 		mutex_enter(&connp->conn_lock);
19236 		if (CONN_CACHE_IRE(connp)) {
19237 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19238 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19239 				TCP_CHECK_IREINFO(tcp, ire);
19240 				connp->conn_ire_cache = ire;
19241 				cached = B_TRUE;
19242 			}
19243 			rw_exit(&ire->ire_bucket->irb_lock);
19244 		}
19245 		mutex_exit(&connp->conn_lock);
19246 
19247 		/*
19248 		 * We can continue to use the ire but since it was
19249 		 * not cached, we should drop the extra reference.
19250 		 */
19251 		if (!cached)
19252 			IRE_REFRELE_NOTR(ire);
19253 
19254 		/*
19255 		 * Rampart note: no need to select a new label here, since
19256 		 * labels are not allowed to change during the life of a TCP
19257 		 * connection.
19258 		 */
19259 	}
19260 
19261 	*irep = ire;
19262 
19263 	return (B_TRUE);
19264 }
19265 
19266 /*
19267  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19268  *
19269  * 0 = success;
19270  * 1 = failed to find ire and ill.
19271  */
19272 static boolean_t
19273 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19274 {
19275 	ipha_t		*ipha;
19276 	ipaddr_t	dst;
19277 	ire_t		*ire;
19278 	ill_t		*ill;
19279 	conn_t		*connp = tcp->tcp_connp;
19280 	mblk_t		*ire_fp_mp;
19281 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19282 
19283 	if (mp != NULL)
19284 		ipha = (ipha_t *)mp->b_rptr;
19285 	else
19286 		ipha = tcp->tcp_ipha;
19287 	dst = ipha->ipha_dst;
19288 
19289 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19290 		return (B_FALSE);
19291 
19292 	if ((ire->ire_flags & RTF_MULTIRT) ||
19293 	    (ire->ire_stq == NULL) ||
19294 	    (ire->ire_nce == NULL) ||
19295 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19296 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19297 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19298 		TCP_STAT(tcps, tcp_ip_ire_send);
19299 		IRE_REFRELE(ire);
19300 		return (B_FALSE);
19301 	}
19302 
19303 	ill = ire_to_ill(ire);
19304 	if (connp->conn_outgoing_ill != NULL) {
19305 		ill_t *conn_outgoing_ill = NULL;
19306 		/*
19307 		 * Choose a good ill in the group to send the packets on.
19308 		 */
19309 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
19310 		ill = ire_to_ill(ire);
19311 	}
19312 	ASSERT(ill != NULL);
19313 
19314 	if (!tcp->tcp_ire_ill_check_done) {
19315 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19316 		tcp->tcp_ire_ill_check_done = B_TRUE;
19317 	}
19318 
19319 	*irep = ire;
19320 	*illp = ill;
19321 
19322 	return (B_TRUE);
19323 }
19324 
19325 static void
19326 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19327 {
19328 	ipha_t		*ipha;
19329 	ipaddr_t	src;
19330 	ipaddr_t	dst;
19331 	uint32_t	cksum;
19332 	ire_t		*ire;
19333 	uint16_t	*up;
19334 	ill_t		*ill;
19335 	conn_t		*connp = tcp->tcp_connp;
19336 	uint32_t	hcksum_txflags = 0;
19337 	mblk_t		*ire_fp_mp;
19338 	uint_t		ire_fp_mp_len;
19339 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19340 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19341 
19342 	ASSERT(DB_TYPE(mp) == M_DATA);
19343 
19344 	if (DB_CRED(mp) == NULL)
19345 		mblk_setcred(mp, CONN_CRED(connp));
19346 
19347 	ipha = (ipha_t *)mp->b_rptr;
19348 	src = ipha->ipha_src;
19349 	dst = ipha->ipha_dst;
19350 
19351 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19352 
19353 	/*
19354 	 * Drop off fast path for IPv6 and also if options are present or
19355 	 * we need to resolve a TS label.
19356 	 */
19357 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19358 	    !IPCL_IS_CONNECTED(connp) ||
19359 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19360 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19361 	    !connp->conn_ulp_labeled ||
19362 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19363 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19364 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19365 		if (tcp->tcp_snd_zcopy_aware)
19366 			mp = tcp_zcopy_disable(tcp, mp);
19367 		TCP_STAT(tcps, tcp_ip_send);
19368 		CALL_IP_WPUT(connp, q, mp);
19369 		return;
19370 	}
19371 
19372 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19373 		if (tcp->tcp_snd_zcopy_aware)
19374 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19375 		CALL_IP_WPUT(connp, q, mp);
19376 		return;
19377 	}
19378 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19379 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19380 
19381 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19382 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19383 #ifndef _BIG_ENDIAN
19384 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19385 #endif
19386 
19387 	/*
19388 	 * Check to see if we need to re-enable LSO/MDT for this connection
19389 	 * because it was previously disabled due to changes in the ill;
19390 	 * note that by doing it here, this re-enabling only applies when
19391 	 * the packet is not dispatched through CALL_IP_WPUT().
19392 	 *
19393 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19394 	 * case, since that's how we ended up here.  For IPv6, we do the
19395 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19396 	 */
19397 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19398 		/*
19399 		 * Restore LSO for this connection, so that next time around
19400 		 * it is eligible to go through tcp_lsosend() path again.
19401 		 */
19402 		TCP_STAT(tcps, tcp_lso_enabled);
19403 		tcp->tcp_lso = B_TRUE;
19404 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19405 		    "interface %s\n", (void *)connp, ill->ill_name));
19406 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19407 		/*
19408 		 * Restore MDT for this connection, so that next time around
19409 		 * it is eligible to go through tcp_multisend() path again.
19410 		 */
19411 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19412 		tcp->tcp_mdt = B_TRUE;
19413 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19414 		    "interface %s\n", (void *)connp, ill->ill_name));
19415 	}
19416 
19417 	if (tcp->tcp_snd_zcopy_aware) {
19418 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19419 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19420 			mp = tcp_zcopy_disable(tcp, mp);
19421 		/*
19422 		 * we shouldn't need to reset ipha as the mp containing
19423 		 * ipha should never be a zero-copy mp.
19424 		 */
19425 	}
19426 
19427 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19428 		ASSERT(ill->ill_hcksum_capab != NULL);
19429 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19430 	}
19431 
19432 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19433 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19434 
19435 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19436 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19437 
19438 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19439 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19440 
19441 	/* Software checksum? */
19442 	if (DB_CKSUMFLAGS(mp) == 0) {
19443 		TCP_STAT(tcps, tcp_out_sw_cksum);
19444 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19445 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19446 	}
19447 
19448 	ipha->ipha_fragment_offset_and_flags |=
19449 	    (uint32_t)htons(ire->ire_frag_flag);
19450 
19451 	/* Calculate IP header checksum if hardware isn't capable */
19452 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19453 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19454 		    ((uint16_t *)ipha)[4]);
19455 	}
19456 
19457 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19458 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19459 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19460 
19461 	UPDATE_OB_PKT_COUNT(ire);
19462 	ire->ire_last_used_time = lbolt;
19463 
19464 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19465 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19466 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19467 	    ntohs(ipha->ipha_length));
19468 
19469 	if (ILL_DLS_CAPABLE(ill)) {
19470 		/*
19471 		 * Send the packet directly to DLD, where it may be queued
19472 		 * depending on the availability of transmit resources at
19473 		 * the media layer.
19474 		 */
19475 		IP_DLS_ILL_TX(ill, ipha, mp, ipst, ire_fp_mp_len);
19476 	} else {
19477 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
19478 		DTRACE_PROBE4(ip4__physical__out__start,
19479 		    ill_t *, NULL, ill_t *, out_ill,
19480 		    ipha_t *, ipha, mblk_t *, mp);
19481 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
19482 		    ipst->ips_ipv4firewall_physical_out,
19483 		    NULL, out_ill, ipha, mp, mp, 0, ipst);
19484 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19485 
19486 		if (mp != NULL) {
19487 			if (ipst->ips_ipobs_enabled) {
19488 				ipobs_hook(mp, IPOBS_HOOK_OUTBOUND,
19489 				    IP_REAL_ZONEID(connp->conn_zoneid, ipst),
19490 				    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len,
19491 				    ipst);
19492 			}
19493 			DTRACE_IP_FASTPATH(mp, ipha, out_ill, ipha, NULL);
19494 			putnext(ire->ire_stq, mp);
19495 		}
19496 	}
19497 	IRE_REFRELE(ire);
19498 }
19499 
19500 /*
19501  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19502  * if the receiver shrinks the window, i.e. moves the right window to the
19503  * left, the we should not send new data, but should retransmit normally the
19504  * old unacked data between suna and suna + swnd. We might has sent data
19505  * that is now outside the new window, pretend that we didn't send  it.
19506  */
19507 static void
19508 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19509 {
19510 	uint32_t	snxt = tcp->tcp_snxt;
19511 	mblk_t		*xmit_tail;
19512 	int32_t		offset;
19513 
19514 	ASSERT(shrunk_count > 0);
19515 
19516 	/* Pretend we didn't send the data outside the window */
19517 	snxt -= shrunk_count;
19518 
19519 	/* Get the mblk and the offset in it per the shrunk window */
19520 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19521 
19522 	ASSERT(xmit_tail != NULL);
19523 
19524 	/* Reset all the values per the now shrunk window */
19525 	tcp->tcp_snxt = snxt;
19526 	tcp->tcp_xmit_tail = xmit_tail;
19527 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19528 	    offset;
19529 	tcp->tcp_unsent += shrunk_count;
19530 
19531 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19532 		/*
19533 		 * Make sure the timer is running so that we will probe a zero
19534 		 * window.
19535 		 */
19536 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19537 }
19538 
19539 
19540 /*
19541  * The TCP normal data output path.
19542  * NOTE: the logic of the fast path is duplicated from this function.
19543  */
19544 static void
19545 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19546 {
19547 	int		len;
19548 	mblk_t		*local_time;
19549 	mblk_t		*mp1;
19550 	uint32_t	snxt;
19551 	int		tail_unsent;
19552 	int		tcpstate;
19553 	int		usable = 0;
19554 	mblk_t		*xmit_tail;
19555 	queue_t		*q = tcp->tcp_wq;
19556 	int32_t		mss;
19557 	int32_t		num_sack_blk = 0;
19558 	int32_t		tcp_hdr_len;
19559 	int32_t		tcp_tcp_hdr_len;
19560 	int		mdt_thres;
19561 	int		rc;
19562 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19563 	ip_stack_t	*ipst;
19564 
19565 	tcpstate = tcp->tcp_state;
19566 	if (mp == NULL) {
19567 		/*
19568 		 * tcp_wput_data() with NULL mp should only be called when
19569 		 * there is unsent data.
19570 		 */
19571 		ASSERT(tcp->tcp_unsent > 0);
19572 		/* Really tacky... but we need this for detached closes. */
19573 		len = tcp->tcp_unsent;
19574 		goto data_null;
19575 	}
19576 
19577 #if CCS_STATS
19578 	wrw_stats.tot.count++;
19579 	wrw_stats.tot.bytes += msgdsize(mp);
19580 #endif
19581 	ASSERT(mp->b_datap->db_type == M_DATA);
19582 	/*
19583 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19584 	 * or before a connection attempt has begun.
19585 	 */
19586 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19587 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19588 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19589 #ifdef DEBUG
19590 			cmn_err(CE_WARN,
19591 			    "tcp_wput_data: data after ordrel, %s",
19592 			    tcp_display(tcp, NULL,
19593 			    DISP_ADDR_AND_PORT));
19594 #else
19595 			if (tcp->tcp_debug) {
19596 				(void) strlog(TCP_MOD_ID, 0, 1,
19597 				    SL_TRACE|SL_ERROR,
19598 				    "tcp_wput_data: data after ordrel, %s\n",
19599 				    tcp_display(tcp, NULL,
19600 				    DISP_ADDR_AND_PORT));
19601 			}
19602 #endif /* DEBUG */
19603 		}
19604 		if (tcp->tcp_snd_zcopy_aware &&
19605 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19606 			tcp_zcopy_notify(tcp);
19607 		freemsg(mp);
19608 		mutex_enter(&tcp->tcp_non_sq_lock);
19609 		if (tcp->tcp_flow_stopped &&
19610 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19611 			tcp_clrqfull(tcp);
19612 		}
19613 		mutex_exit(&tcp->tcp_non_sq_lock);
19614 		return;
19615 	}
19616 
19617 	/* Strip empties */
19618 	for (;;) {
19619 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19620 		    (uintptr_t)INT_MAX);
19621 		len = (int)(mp->b_wptr - mp->b_rptr);
19622 		if (len > 0)
19623 			break;
19624 		mp1 = mp;
19625 		mp = mp->b_cont;
19626 		freeb(mp1);
19627 		if (!mp) {
19628 			return;
19629 		}
19630 	}
19631 
19632 	/* If we are the first on the list ... */
19633 	if (tcp->tcp_xmit_head == NULL) {
19634 		tcp->tcp_xmit_head = mp;
19635 		tcp->tcp_xmit_tail = mp;
19636 		tcp->tcp_xmit_tail_unsent = len;
19637 	} else {
19638 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19639 		struct datab *dp;
19640 
19641 		mp1 = tcp->tcp_xmit_last;
19642 		if (len < tcp_tx_pull_len &&
19643 		    (dp = mp1->b_datap)->db_ref == 1 &&
19644 		    dp->db_lim - mp1->b_wptr >= len) {
19645 			ASSERT(len > 0);
19646 			ASSERT(!mp1->b_cont);
19647 			if (len == 1) {
19648 				*mp1->b_wptr++ = *mp->b_rptr;
19649 			} else {
19650 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19651 				mp1->b_wptr += len;
19652 			}
19653 			if (mp1 == tcp->tcp_xmit_tail)
19654 				tcp->tcp_xmit_tail_unsent += len;
19655 			mp1->b_cont = mp->b_cont;
19656 			if (tcp->tcp_snd_zcopy_aware &&
19657 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19658 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19659 			freeb(mp);
19660 			mp = mp1;
19661 		} else {
19662 			tcp->tcp_xmit_last->b_cont = mp;
19663 		}
19664 		len += tcp->tcp_unsent;
19665 	}
19666 
19667 	/* Tack on however many more positive length mblks we have */
19668 	if ((mp1 = mp->b_cont) != NULL) {
19669 		do {
19670 			int tlen;
19671 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19672 			    (uintptr_t)INT_MAX);
19673 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19674 			if (tlen <= 0) {
19675 				mp->b_cont = mp1->b_cont;
19676 				freeb(mp1);
19677 			} else {
19678 				len += tlen;
19679 				mp = mp1;
19680 			}
19681 		} while ((mp1 = mp->b_cont) != NULL);
19682 	}
19683 	tcp->tcp_xmit_last = mp;
19684 	tcp->tcp_unsent = len;
19685 
19686 	if (urgent)
19687 		usable = 1;
19688 
19689 data_null:
19690 	snxt = tcp->tcp_snxt;
19691 	xmit_tail = tcp->tcp_xmit_tail;
19692 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19693 
19694 	/*
19695 	 * Note that tcp_mss has been adjusted to take into account the
19696 	 * timestamp option if applicable.  Because SACK options do not
19697 	 * appear in every TCP segments and they are of variable lengths,
19698 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19699 	 * the actual segment length when we need to send a segment which
19700 	 * includes SACK options.
19701 	 */
19702 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19703 		int32_t	opt_len;
19704 
19705 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19706 		    tcp->tcp_num_sack_blk);
19707 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19708 		    2 + TCPOPT_HEADER_LEN;
19709 		mss = tcp->tcp_mss - opt_len;
19710 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19711 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19712 	} else {
19713 		mss = tcp->tcp_mss;
19714 		tcp_hdr_len = tcp->tcp_hdr_len;
19715 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19716 	}
19717 
19718 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19719 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19720 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19721 	}
19722 	if (tcpstate == TCPS_SYN_RCVD) {
19723 		/*
19724 		 * The three-way connection establishment handshake is not
19725 		 * complete yet. We want to queue the data for transmission
19726 		 * after entering ESTABLISHED state (RFC793). A jump to
19727 		 * "done" label effectively leaves data on the queue.
19728 		 */
19729 		goto done;
19730 	} else {
19731 		int usable_r;
19732 
19733 		/*
19734 		 * In the special case when cwnd is zero, which can only
19735 		 * happen if the connection is ECN capable, return now.
19736 		 * New segments is sent using tcp_timer().  The timer
19737 		 * is set in tcp_rput_data().
19738 		 */
19739 		if (tcp->tcp_cwnd == 0) {
19740 			/*
19741 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19742 			 * finished.
19743 			 */
19744 			ASSERT(tcp->tcp_ecn_ok ||
19745 			    tcp->tcp_state < TCPS_ESTABLISHED);
19746 			return;
19747 		}
19748 
19749 		/* NOTE: trouble if xmitting while SYN not acked? */
19750 		usable_r = snxt - tcp->tcp_suna;
19751 		usable_r = tcp->tcp_swnd - usable_r;
19752 
19753 		/*
19754 		 * Check if the receiver has shrunk the window.  If
19755 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19756 		 * cannot be set as there is unsent data, so FIN cannot
19757 		 * be sent out.  Otherwise, we need to take into account
19758 		 * of FIN as it consumes an "invisible" sequence number.
19759 		 */
19760 		ASSERT(tcp->tcp_fin_sent == 0);
19761 		if (usable_r < 0) {
19762 			/*
19763 			 * The receiver has shrunk the window and we have sent
19764 			 * -usable_r date beyond the window, re-adjust.
19765 			 *
19766 			 * If TCP window scaling is enabled, there can be
19767 			 * round down error as the advertised receive window
19768 			 * is actually right shifted n bits.  This means that
19769 			 * the lower n bits info is wiped out.  It will look
19770 			 * like the window is shrunk.  Do a check here to
19771 			 * see if the shrunk amount is actually within the
19772 			 * error in window calculation.  If it is, just
19773 			 * return.  Note that this check is inside the
19774 			 * shrunk window check.  This makes sure that even
19775 			 * though tcp_process_shrunk_swnd() is not called,
19776 			 * we will stop further processing.
19777 			 */
19778 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19779 				tcp_process_shrunk_swnd(tcp, -usable_r);
19780 			}
19781 			return;
19782 		}
19783 
19784 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19785 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19786 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19787 
19788 		/* usable = MIN(usable, unsent) */
19789 		if (usable_r > len)
19790 			usable_r = len;
19791 
19792 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19793 		if (usable_r > 0) {
19794 			usable = usable_r;
19795 		} else {
19796 			/* Bypass all other unnecessary processing. */
19797 			goto done;
19798 		}
19799 	}
19800 
19801 	local_time = (mblk_t *)lbolt;
19802 
19803 	/*
19804 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19805 	 * BSD.  This is more in line with the true intent of Nagle.
19806 	 *
19807 	 * The conditions are:
19808 	 * 1. The amount of unsent data (or amount of data which can be
19809 	 *    sent, whichever is smaller) is less than Nagle limit.
19810 	 * 2. The last sent size is also less than Nagle limit.
19811 	 * 3. There is unack'ed data.
19812 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19813 	 *    Nagle algorithm.  This reduces the probability that urgent
19814 	 *    bytes get "merged" together.
19815 	 * 5. The app has not closed the connection.  This eliminates the
19816 	 *    wait time of the receiving side waiting for the last piece of
19817 	 *    (small) data.
19818 	 *
19819 	 * If all are satisified, exit without sending anything.  Note
19820 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19821 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19822 	 * 4095).
19823 	 */
19824 	if (usable < (int)tcp->tcp_naglim &&
19825 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19826 	    snxt != tcp->tcp_suna &&
19827 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19828 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19829 		goto done;
19830 	}
19831 
19832 	if (tcp->tcp_cork) {
19833 		/*
19834 		 * if the tcp->tcp_cork option is set, then we have to force
19835 		 * TCP not to send partial segment (smaller than MSS bytes).
19836 		 * We are calculating the usable now based on full mss and
19837 		 * will save the rest of remaining data for later.
19838 		 */
19839 		if (usable < mss)
19840 			goto done;
19841 		usable = (usable / mss) * mss;
19842 	}
19843 
19844 	/* Update the latest receive window size in TCP header. */
19845 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19846 	    tcp->tcp_tcph->th_win);
19847 
19848 	/*
19849 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19850 	 *
19851 	 * 1. Simple TCP/IP{v4,v6} (no options).
19852 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19853 	 * 3. If the TCP connection is in ESTABLISHED state.
19854 	 * 4. The TCP is not detached.
19855 	 *
19856 	 * If any of the above conditions have changed during the
19857 	 * connection, stop using LSO/MDT and restore the stream head
19858 	 * parameters accordingly.
19859 	 */
19860 	ipst = tcps->tcps_netstack->netstack_ip;
19861 
19862 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19863 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19864 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19865 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19866 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19867 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19868 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19869 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19870 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19871 		if (tcp->tcp_lso) {
19872 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19873 			tcp->tcp_lso = B_FALSE;
19874 		} else {
19875 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19876 			tcp->tcp_mdt = B_FALSE;
19877 		}
19878 
19879 		/* Anything other than detached is considered pathological */
19880 		if (!TCP_IS_DETACHED(tcp)) {
19881 			if (tcp->tcp_lso)
19882 				TCP_STAT(tcps, tcp_lso_disabled);
19883 			else
19884 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19885 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19886 		}
19887 	}
19888 
19889 	/* Use MDT if sendable amount is greater than the threshold */
19890 	if (tcp->tcp_mdt &&
19891 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19892 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19893 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19894 	    (tcp->tcp_valid_bits == 0 ||
19895 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19896 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19897 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19898 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19899 		    local_time, mdt_thres);
19900 	} else {
19901 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19902 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19903 		    local_time, INT_MAX);
19904 	}
19905 
19906 	/* Pretend that all we were trying to send really got sent */
19907 	if (rc < 0 && tail_unsent < 0) {
19908 		do {
19909 			xmit_tail = xmit_tail->b_cont;
19910 			xmit_tail->b_prev = local_time;
19911 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19912 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19913 			tail_unsent += (int)(xmit_tail->b_wptr -
19914 			    xmit_tail->b_rptr);
19915 		} while (tail_unsent < 0);
19916 	}
19917 done:;
19918 	tcp->tcp_xmit_tail = xmit_tail;
19919 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19920 	len = tcp->tcp_snxt - snxt;
19921 	if (len) {
19922 		/*
19923 		 * If new data was sent, need to update the notsack
19924 		 * list, which is, afterall, data blocks that have
19925 		 * not been sack'ed by the receiver.  New data is
19926 		 * not sack'ed.
19927 		 */
19928 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19929 			/* len is a negative value. */
19930 			tcp->tcp_pipe -= len;
19931 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19932 			    tcp->tcp_snxt, snxt,
19933 			    &(tcp->tcp_num_notsack_blk),
19934 			    &(tcp->tcp_cnt_notsack_list));
19935 		}
19936 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19937 		tcp->tcp_rack = tcp->tcp_rnxt;
19938 		tcp->tcp_rack_cnt = 0;
19939 		if ((snxt + len) == tcp->tcp_suna) {
19940 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19941 		}
19942 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19943 		/*
19944 		 * Didn't send anything. Make sure the timer is running
19945 		 * so that we will probe a zero window.
19946 		 */
19947 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19948 	}
19949 	/* Note that len is the amount we just sent but with a negative sign */
19950 	tcp->tcp_unsent += len;
19951 	mutex_enter(&tcp->tcp_non_sq_lock);
19952 	if (tcp->tcp_flow_stopped) {
19953 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19954 			tcp_clrqfull(tcp);
19955 		}
19956 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19957 		tcp_setqfull(tcp);
19958 	}
19959 	mutex_exit(&tcp->tcp_non_sq_lock);
19960 }
19961 
19962 /*
19963  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19964  * outgoing TCP header with the template header, as well as other
19965  * options such as time-stamp, ECN and/or SACK.
19966  */
19967 static void
19968 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19969 {
19970 	tcph_t *tcp_tmpl, *tcp_h;
19971 	uint32_t *dst, *src;
19972 	int hdrlen;
19973 
19974 	ASSERT(OK_32PTR(rptr));
19975 
19976 	/* Template header */
19977 	tcp_tmpl = tcp->tcp_tcph;
19978 
19979 	/* Header of outgoing packet */
19980 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19981 
19982 	/* dst and src are opaque 32-bit fields, used for copying */
19983 	dst = (uint32_t *)rptr;
19984 	src = (uint32_t *)tcp->tcp_iphc;
19985 	hdrlen = tcp->tcp_hdr_len;
19986 
19987 	/* Fill time-stamp option if needed */
19988 	if (tcp->tcp_snd_ts_ok) {
19989 		U32_TO_BE32((uint32_t)now,
19990 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19991 		U32_TO_BE32(tcp->tcp_ts_recent,
19992 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19993 	} else {
19994 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19995 	}
19996 
19997 	/*
19998 	 * Copy the template header; is this really more efficient than
19999 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
20000 	 * but perhaps not for other scenarios.
20001 	 */
20002 	dst[0] = src[0];
20003 	dst[1] = src[1];
20004 	dst[2] = src[2];
20005 	dst[3] = src[3];
20006 	dst[4] = src[4];
20007 	dst[5] = src[5];
20008 	dst[6] = src[6];
20009 	dst[7] = src[7];
20010 	dst[8] = src[8];
20011 	dst[9] = src[9];
20012 	if (hdrlen -= 40) {
20013 		hdrlen >>= 2;
20014 		dst += 10;
20015 		src += 10;
20016 		do {
20017 			*dst++ = *src++;
20018 		} while (--hdrlen);
20019 	}
20020 
20021 	/*
20022 	 * Set the ECN info in the TCP header if it is not a zero
20023 	 * window probe.  Zero window probe is only sent in
20024 	 * tcp_wput_data() and tcp_timer().
20025 	 */
20026 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
20027 		SET_ECT(tcp, rptr);
20028 
20029 		if (tcp->tcp_ecn_echo_on)
20030 			tcp_h->th_flags[0] |= TH_ECE;
20031 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
20032 			tcp_h->th_flags[0] |= TH_CWR;
20033 			tcp->tcp_ecn_cwr_sent = B_TRUE;
20034 		}
20035 	}
20036 
20037 	/* Fill in SACK options */
20038 	if (num_sack_blk > 0) {
20039 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
20040 		sack_blk_t *tmp;
20041 		int32_t	i;
20042 
20043 		wptr[0] = TCPOPT_NOP;
20044 		wptr[1] = TCPOPT_NOP;
20045 		wptr[2] = TCPOPT_SACK;
20046 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
20047 		    sizeof (sack_blk_t);
20048 		wptr += TCPOPT_REAL_SACK_LEN;
20049 
20050 		tmp = tcp->tcp_sack_list;
20051 		for (i = 0; i < num_sack_blk; i++) {
20052 			U32_TO_BE32(tmp[i].begin, wptr);
20053 			wptr += sizeof (tcp_seq);
20054 			U32_TO_BE32(tmp[i].end, wptr);
20055 			wptr += sizeof (tcp_seq);
20056 		}
20057 		tcp_h->th_offset_and_rsrvd[0] +=
20058 		    ((num_sack_blk * 2 + 1) << 4);
20059 	}
20060 }
20061 
20062 /*
20063  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
20064  * the destination address and SAP attribute, and if necessary, the
20065  * hardware checksum offload attribute to a Multidata message.
20066  */
20067 static int
20068 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
20069     const uint32_t start, const uint32_t stuff, const uint32_t end,
20070     const uint32_t flags, tcp_stack_t *tcps)
20071 {
20072 	/* Add global destination address & SAP attribute */
20073 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
20074 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
20075 		    "destination address+SAP\n"));
20076 
20077 		if (dlmp != NULL)
20078 			TCP_STAT(tcps, tcp_mdt_allocfail);
20079 		return (-1);
20080 	}
20081 
20082 	/* Add global hwcksum attribute */
20083 	if (hwcksum &&
20084 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
20085 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
20086 		    "checksum attribute\n"));
20087 
20088 		TCP_STAT(tcps, tcp_mdt_allocfail);
20089 		return (-1);
20090 	}
20091 
20092 	return (0);
20093 }
20094 
20095 /*
20096  * Smaller and private version of pdescinfo_t used specifically for TCP,
20097  * which allows for only two payload spans per packet.
20098  */
20099 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
20100 
20101 /*
20102  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
20103  * scheme, and returns one the following:
20104  *
20105  * -1 = failed allocation.
20106  *  0 = success; burst count reached, or usable send window is too small,
20107  *      and that we'd rather wait until later before sending again.
20108  */
20109 static int
20110 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20111     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20112     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20113     const int mdt_thres)
20114 {
20115 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
20116 	multidata_t	*mmd;
20117 	uint_t		obsegs, obbytes, hdr_frag_sz;
20118 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
20119 	int		num_burst_seg, max_pld;
20120 	pdesc_t		*pkt;
20121 	tcp_pdescinfo_t	tcp_pkt_info;
20122 	pdescinfo_t	*pkt_info;
20123 	int		pbuf_idx, pbuf_idx_nxt;
20124 	int		seg_len, len, spill, af;
20125 	boolean_t	add_buffer, zcopy, clusterwide;
20126 	boolean_t	rconfirm = B_FALSE;
20127 	boolean_t	done = B_FALSE;
20128 	uint32_t	cksum;
20129 	uint32_t	hwcksum_flags;
20130 	ire_t		*ire = NULL;
20131 	ill_t		*ill;
20132 	ipha_t		*ipha;
20133 	ip6_t		*ip6h;
20134 	ipaddr_t	src, dst;
20135 	ill_zerocopy_capab_t *zc_cap = NULL;
20136 	uint16_t	*up;
20137 	int		err;
20138 	conn_t		*connp;
20139 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20140 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
20141 	int		usable_mmd, tail_unsent_mmd;
20142 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
20143 	mblk_t		*xmit_tail_mmd;
20144 
20145 #ifdef	_BIG_ENDIAN
20146 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20147 #else
20148 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20149 #endif
20150 
20151 #define	PREP_NEW_MULTIDATA() {			\
20152 	mmd = NULL;				\
20153 	md_mp = md_hbuf = NULL;			\
20154 	cur_hdr_off = 0;			\
20155 	max_pld = tcp->tcp_mdt_max_pld;		\
20156 	pbuf_idx = pbuf_idx_nxt = -1;		\
20157 	add_buffer = B_TRUE;			\
20158 	zcopy = B_FALSE;			\
20159 }
20160 
20161 #define	PREP_NEW_PBUF() {			\
20162 	md_pbuf = md_pbuf_nxt = NULL;		\
20163 	pbuf_idx = pbuf_idx_nxt = -1;		\
20164 	cur_pld_off = 0;			\
20165 	first_snxt = *snxt;			\
20166 	ASSERT(*tail_unsent > 0);		\
20167 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20168 }
20169 
20170 	ASSERT(mdt_thres >= mss);
20171 	ASSERT(*usable > 0 && *usable > mdt_thres);
20172 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20173 	ASSERT(!TCP_IS_DETACHED(tcp));
20174 	ASSERT(tcp->tcp_valid_bits == 0 ||
20175 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20176 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20177 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20178 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20179 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20180 
20181 	connp = tcp->tcp_connp;
20182 	ASSERT(connp != NULL);
20183 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20184 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20185 
20186 	usable_mmd = tail_unsent_mmd = 0;
20187 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20188 	xmit_tail_mmd = NULL;
20189 	/*
20190 	 * Note that tcp will only declare at most 2 payload spans per
20191 	 * packet, which is much lower than the maximum allowable number
20192 	 * of packet spans per Multidata.  For this reason, we use the
20193 	 * privately declared and smaller descriptor info structure, in
20194 	 * order to save some stack space.
20195 	 */
20196 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20197 
20198 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20199 	if (af == AF_INET) {
20200 		dst = tcp->tcp_ipha->ipha_dst;
20201 		src = tcp->tcp_ipha->ipha_src;
20202 		ASSERT(!CLASSD(dst));
20203 	}
20204 	ASSERT(af == AF_INET ||
20205 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20206 
20207 	obsegs = obbytes = 0;
20208 	num_burst_seg = tcp->tcp_snd_burst;
20209 	md_mp_head = NULL;
20210 	PREP_NEW_MULTIDATA();
20211 
20212 	/*
20213 	 * Before we go on further, make sure there is an IRE that we can
20214 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20215 	 * in proceeding any further, and we should just hand everything
20216 	 * off to the legacy path.
20217 	 */
20218 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20219 		goto legacy_send_no_md;
20220 
20221 	ASSERT(ire != NULL);
20222 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20223 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20224 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20225 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20226 	/*
20227 	 * If we do support loopback for MDT (which requires modifications
20228 	 * to the receiving paths), the following assertions should go away,
20229 	 * and we would be sending the Multidata to loopback conn later on.
20230 	 */
20231 	ASSERT(!IRE_IS_LOCAL(ire));
20232 	ASSERT(ire->ire_stq != NULL);
20233 
20234 	ill = ire_to_ill(ire);
20235 	ASSERT(ill != NULL);
20236 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20237 
20238 	if (!tcp->tcp_ire_ill_check_done) {
20239 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20240 		tcp->tcp_ire_ill_check_done = B_TRUE;
20241 	}
20242 
20243 	/*
20244 	 * If the underlying interface conditions have changed, or if the
20245 	 * new interface does not support MDT, go back to legacy path.
20246 	 */
20247 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20248 		/* don't go through this path anymore for this connection */
20249 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20250 		tcp->tcp_mdt = B_FALSE;
20251 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20252 		    "interface %s\n", (void *)connp, ill->ill_name));
20253 		/* IRE will be released prior to returning */
20254 		goto legacy_send_no_md;
20255 	}
20256 
20257 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20258 		zc_cap = ill->ill_zerocopy_capab;
20259 
20260 	/*
20261 	 * Check if we can take tcp fast-path. Note that "incomplete"
20262 	 * ire's (where the link-layer for next hop is not resolved
20263 	 * or where the fast-path header in nce_fp_mp is not available
20264 	 * yet) are sent down the legacy (slow) path.
20265 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20266 	 */
20267 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20268 		/* IRE will be released prior to returning */
20269 		goto legacy_send_no_md;
20270 	}
20271 
20272 	/* go to legacy path if interface doesn't support zerocopy */
20273 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20274 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20275 		/* IRE will be released prior to returning */
20276 		goto legacy_send_no_md;
20277 	}
20278 
20279 	/* does the interface support hardware checksum offload? */
20280 	hwcksum_flags = 0;
20281 	if (ILL_HCKSUM_CAPABLE(ill) &&
20282 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20283 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20284 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20285 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20286 		    HCKSUM_IPHDRCKSUM)
20287 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20288 
20289 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20290 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20291 			hwcksum_flags |= HCK_FULLCKSUM;
20292 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20293 		    HCKSUM_INET_PARTIAL)
20294 			hwcksum_flags |= HCK_PARTIALCKSUM;
20295 	}
20296 
20297 	/*
20298 	 * Each header fragment consists of the leading extra space,
20299 	 * followed by the TCP/IP header, and the trailing extra space.
20300 	 * We make sure that each header fragment begins on a 32-bit
20301 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20302 	 * aligned in tcp_mdt_update).
20303 	 */
20304 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20305 	    tcp->tcp_mdt_hdr_tail), 4);
20306 
20307 	/* are we starting from the beginning of data block? */
20308 	if (*tail_unsent == 0) {
20309 		*xmit_tail = (*xmit_tail)->b_cont;
20310 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20311 		*tail_unsent = (int)MBLKL(*xmit_tail);
20312 	}
20313 
20314 	/*
20315 	 * Here we create one or more Multidata messages, each made up of
20316 	 * one header buffer and up to N payload buffers.  This entire
20317 	 * operation is done within two loops:
20318 	 *
20319 	 * The outer loop mostly deals with creating the Multidata message,
20320 	 * as well as the header buffer that gets added to it.  It also
20321 	 * links the Multidata messages together such that all of them can
20322 	 * be sent down to the lower layer in a single putnext call; this
20323 	 * linking behavior depends on the tcp_mdt_chain tunable.
20324 	 *
20325 	 * The inner loop takes an existing Multidata message, and adds
20326 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20327 	 * packetizes those buffers by filling up the corresponding header
20328 	 * buffer fragments with the proper IP and TCP headers, and by
20329 	 * describing the layout of each packet in the packet descriptors
20330 	 * that get added to the Multidata.
20331 	 */
20332 	do {
20333 		/*
20334 		 * If usable send window is too small, or data blocks in
20335 		 * transmit list are smaller than our threshold (i.e. app
20336 		 * performs large writes followed by small ones), we hand
20337 		 * off the control over to the legacy path.  Note that we'll
20338 		 * get back the control once it encounters a large block.
20339 		 */
20340 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20341 		    (*xmit_tail)->b_cont != NULL &&
20342 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20343 			/* send down what we've got so far */
20344 			if (md_mp_head != NULL) {
20345 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20346 				    obsegs, obbytes, &rconfirm);
20347 			}
20348 			/*
20349 			 * Pass control over to tcp_send(), but tell it to
20350 			 * return to us once a large-size transmission is
20351 			 * possible.
20352 			 */
20353 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20354 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20355 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20356 			    tail_unsent, xmit_tail, local_time,
20357 			    mdt_thres)) <= 0) {
20358 				/* burst count reached, or alloc failed */
20359 				IRE_REFRELE(ire);
20360 				return (err);
20361 			}
20362 
20363 			/* tcp_send() may have sent everything, so check */
20364 			if (*usable <= 0) {
20365 				IRE_REFRELE(ire);
20366 				return (0);
20367 			}
20368 
20369 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20370 			/*
20371 			 * We may have delivered the Multidata, so make sure
20372 			 * to re-initialize before the next round.
20373 			 */
20374 			md_mp_head = NULL;
20375 			obsegs = obbytes = 0;
20376 			num_burst_seg = tcp->tcp_snd_burst;
20377 			PREP_NEW_MULTIDATA();
20378 
20379 			/* are we starting from the beginning of data block? */
20380 			if (*tail_unsent == 0) {
20381 				*xmit_tail = (*xmit_tail)->b_cont;
20382 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20383 				    (uintptr_t)INT_MAX);
20384 				*tail_unsent = (int)MBLKL(*xmit_tail);
20385 			}
20386 		}
20387 		/*
20388 		 * Record current values for parameters we may need to pass
20389 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20390 		 * each iteration of the outer loop (each multidata message
20391 		 * creation). If we have a failure in the inner loop, we send
20392 		 * any complete multidata messages we have before reverting
20393 		 * to using the traditional non-md path.
20394 		 */
20395 		snxt_mmd = *snxt;
20396 		usable_mmd = *usable;
20397 		xmit_tail_mmd = *xmit_tail;
20398 		tail_unsent_mmd = *tail_unsent;
20399 		obsegs_mmd = obsegs;
20400 		obbytes_mmd = obbytes;
20401 
20402 		/*
20403 		 * max_pld limits the number of mblks in tcp's transmit
20404 		 * queue that can be added to a Multidata message.  Once
20405 		 * this counter reaches zero, no more additional mblks
20406 		 * can be added to it.  What happens afterwards depends
20407 		 * on whether or not we are set to chain the Multidata
20408 		 * messages.  If we are to link them together, reset
20409 		 * max_pld to its original value (tcp_mdt_max_pld) and
20410 		 * prepare to create a new Multidata message which will
20411 		 * get linked to md_mp_head.  Else, leave it alone and
20412 		 * let the inner loop break on its own.
20413 		 */
20414 		if (tcp_mdt_chain && max_pld == 0)
20415 			PREP_NEW_MULTIDATA();
20416 
20417 		/* adding a payload buffer; re-initialize values */
20418 		if (add_buffer)
20419 			PREP_NEW_PBUF();
20420 
20421 		/*
20422 		 * If we don't have a Multidata, either because we just
20423 		 * (re)entered this outer loop, or after we branched off
20424 		 * to tcp_send above, setup the Multidata and header
20425 		 * buffer to be used.
20426 		 */
20427 		if (md_mp == NULL) {
20428 			int md_hbuflen;
20429 			uint32_t start, stuff;
20430 
20431 			/*
20432 			 * Calculate Multidata header buffer size large enough
20433 			 * to hold all of the headers that can possibly be
20434 			 * sent at this moment.  We'd rather over-estimate
20435 			 * the size than running out of space; this is okay
20436 			 * since this buffer is small anyway.
20437 			 */
20438 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20439 
20440 			/*
20441 			 * Start and stuff offset for partial hardware
20442 			 * checksum offload; these are currently for IPv4.
20443 			 * For full checksum offload, they are set to zero.
20444 			 */
20445 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20446 				if (af == AF_INET) {
20447 					start = IP_SIMPLE_HDR_LENGTH;
20448 					stuff = IP_SIMPLE_HDR_LENGTH +
20449 					    TCP_CHECKSUM_OFFSET;
20450 				} else {
20451 					start = IPV6_HDR_LEN;
20452 					stuff = IPV6_HDR_LEN +
20453 					    TCP_CHECKSUM_OFFSET;
20454 				}
20455 			} else {
20456 				start = stuff = 0;
20457 			}
20458 
20459 			/*
20460 			 * Create the header buffer, Multidata, as well as
20461 			 * any necessary attributes (destination address,
20462 			 * SAP and hardware checksum offload) that should
20463 			 * be associated with the Multidata message.
20464 			 */
20465 			ASSERT(cur_hdr_off == 0);
20466 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20467 			    ((md_hbuf->b_wptr += md_hbuflen),
20468 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20469 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20470 			    /* fastpath mblk */
20471 			    ire->ire_nce->nce_res_mp,
20472 			    /* hardware checksum enabled */
20473 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20474 			    /* hardware checksum offsets */
20475 			    start, stuff, 0,
20476 			    /* hardware checksum flag */
20477 			    hwcksum_flags, tcps) != 0)) {
20478 legacy_send:
20479 				/*
20480 				 * We arrive here from a failure within the
20481 				 * inner (packetizer) loop or we fail one of
20482 				 * the conditionals above. We restore the
20483 				 * previously checkpointed values for:
20484 				 *    xmit_tail
20485 				 *    usable
20486 				 *    tail_unsent
20487 				 *    snxt
20488 				 *    obbytes
20489 				 *    obsegs
20490 				 * We should then be able to dispatch any
20491 				 * complete multidata before reverting to the
20492 				 * traditional path with consistent parameters
20493 				 * (the inner loop updates these as it
20494 				 * iterates).
20495 				 */
20496 				*xmit_tail = xmit_tail_mmd;
20497 				*usable = usable_mmd;
20498 				*tail_unsent = tail_unsent_mmd;
20499 				*snxt = snxt_mmd;
20500 				obbytes = obbytes_mmd;
20501 				obsegs = obsegs_mmd;
20502 				if (md_mp != NULL) {
20503 					/* Unlink message from the chain */
20504 					if (md_mp_head != NULL) {
20505 						err = (intptr_t)rmvb(md_mp_head,
20506 						    md_mp);
20507 						/*
20508 						 * We can't assert that rmvb
20509 						 * did not return -1, since we
20510 						 * may get here before linkb
20511 						 * happens.  We do, however,
20512 						 * check if we just removed the
20513 						 * only element in the list.
20514 						 */
20515 						if (err == 0)
20516 							md_mp_head = NULL;
20517 					}
20518 					/* md_hbuf gets freed automatically */
20519 					TCP_STAT(tcps, tcp_mdt_discarded);
20520 					freeb(md_mp);
20521 				} else {
20522 					/* Either allocb or mmd_alloc failed */
20523 					TCP_STAT(tcps, tcp_mdt_allocfail);
20524 					if (md_hbuf != NULL)
20525 						freeb(md_hbuf);
20526 				}
20527 
20528 				/* send down what we've got so far */
20529 				if (md_mp_head != NULL) {
20530 					tcp_multisend_data(tcp, ire, ill,
20531 					    md_mp_head, obsegs, obbytes,
20532 					    &rconfirm);
20533 				}
20534 legacy_send_no_md:
20535 				if (ire != NULL)
20536 					IRE_REFRELE(ire);
20537 				/*
20538 				 * Too bad; let the legacy path handle this.
20539 				 * We specify INT_MAX for the threshold, since
20540 				 * we gave up with the Multidata processings
20541 				 * and let the old path have it all.
20542 				 */
20543 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20544 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20545 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20546 				    snxt, tail_unsent, xmit_tail, local_time,
20547 				    INT_MAX));
20548 			}
20549 
20550 			/* link to any existing ones, if applicable */
20551 			TCP_STAT(tcps, tcp_mdt_allocd);
20552 			if (md_mp_head == NULL) {
20553 				md_mp_head = md_mp;
20554 			} else if (tcp_mdt_chain) {
20555 				TCP_STAT(tcps, tcp_mdt_linked);
20556 				linkb(md_mp_head, md_mp);
20557 			}
20558 		}
20559 
20560 		ASSERT(md_mp_head != NULL);
20561 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20562 		ASSERT(md_mp != NULL && mmd != NULL);
20563 		ASSERT(md_hbuf != NULL);
20564 
20565 		/*
20566 		 * Packetize the transmittable portion of the data block;
20567 		 * each data block is essentially added to the Multidata
20568 		 * as a payload buffer.  We also deal with adding more
20569 		 * than one payload buffers, which happens when the remaining
20570 		 * packetized portion of the current payload buffer is less
20571 		 * than MSS, while the next data block in transmit queue
20572 		 * has enough data to make up for one.  This "spillover"
20573 		 * case essentially creates a split-packet, where portions
20574 		 * of the packet's payload fragments may span across two
20575 		 * virtually discontiguous address blocks.
20576 		 */
20577 		seg_len = mss;
20578 		do {
20579 			len = seg_len;
20580 
20581 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20582 			ipha = NULL;
20583 			ip6h = NULL;
20584 
20585 			ASSERT(len > 0);
20586 			ASSERT(max_pld >= 0);
20587 			ASSERT(!add_buffer || cur_pld_off == 0);
20588 
20589 			/*
20590 			 * First time around for this payload buffer; note
20591 			 * in the case of a spillover, the following has
20592 			 * been done prior to adding the split-packet
20593 			 * descriptor to Multidata, and we don't want to
20594 			 * repeat the process.
20595 			 */
20596 			if (add_buffer) {
20597 				ASSERT(mmd != NULL);
20598 				ASSERT(md_pbuf == NULL);
20599 				ASSERT(md_pbuf_nxt == NULL);
20600 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20601 
20602 				/*
20603 				 * Have we reached the limit?  We'd get to
20604 				 * this case when we're not chaining the
20605 				 * Multidata messages together, and since
20606 				 * we're done, terminate this loop.
20607 				 */
20608 				if (max_pld == 0)
20609 					break; /* done */
20610 
20611 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20612 					TCP_STAT(tcps, tcp_mdt_allocfail);
20613 					goto legacy_send; /* out_of_mem */
20614 				}
20615 
20616 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20617 				    zc_cap != NULL) {
20618 					if (!ip_md_zcopy_attr(mmd, NULL,
20619 					    zc_cap->ill_zerocopy_flags)) {
20620 						freeb(md_pbuf);
20621 						TCP_STAT(tcps,
20622 						    tcp_mdt_allocfail);
20623 						/* out_of_mem */
20624 						goto legacy_send;
20625 					}
20626 					zcopy = B_TRUE;
20627 				}
20628 
20629 				md_pbuf->b_rptr += base_pld_off;
20630 
20631 				/*
20632 				 * Add a payload buffer to the Multidata; this
20633 				 * operation must not fail, or otherwise our
20634 				 * logic in this routine is broken.  There
20635 				 * is no memory allocation done by the
20636 				 * routine, so any returned failure simply
20637 				 * tells us that we've done something wrong.
20638 				 *
20639 				 * A failure tells us that either we're adding
20640 				 * the same payload buffer more than once, or
20641 				 * we're trying to add more buffers than
20642 				 * allowed (max_pld calculation is wrong).
20643 				 * None of the above cases should happen, and
20644 				 * we panic because either there's horrible
20645 				 * heap corruption, and/or programming mistake.
20646 				 */
20647 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20648 				if (pbuf_idx < 0) {
20649 					cmn_err(CE_PANIC, "tcp_multisend: "
20650 					    "payload buffer logic error "
20651 					    "detected for tcp %p mmd %p "
20652 					    "pbuf %p (%d)\n",
20653 					    (void *)tcp, (void *)mmd,
20654 					    (void *)md_pbuf, pbuf_idx);
20655 				}
20656 
20657 				ASSERT(max_pld > 0);
20658 				--max_pld;
20659 				add_buffer = B_FALSE;
20660 			}
20661 
20662 			ASSERT(md_mp_head != NULL);
20663 			ASSERT(md_pbuf != NULL);
20664 			ASSERT(md_pbuf_nxt == NULL);
20665 			ASSERT(pbuf_idx != -1);
20666 			ASSERT(pbuf_idx_nxt == -1);
20667 			ASSERT(*usable > 0);
20668 
20669 			/*
20670 			 * We spillover to the next payload buffer only
20671 			 * if all of the following is true:
20672 			 *
20673 			 *   1. There is not enough data on the current
20674 			 *	payload buffer to make up `len',
20675 			 *   2. We are allowed to send `len',
20676 			 *   3. The next payload buffer length is large
20677 			 *	enough to accomodate `spill'.
20678 			 */
20679 			if ((spill = len - *tail_unsent) > 0 &&
20680 			    *usable >= len &&
20681 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20682 			    max_pld > 0) {
20683 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20684 				if (md_pbuf_nxt == NULL) {
20685 					TCP_STAT(tcps, tcp_mdt_allocfail);
20686 					goto legacy_send; /* out_of_mem */
20687 				}
20688 
20689 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20690 				    zc_cap != NULL) {
20691 					if (!ip_md_zcopy_attr(mmd, NULL,
20692 					    zc_cap->ill_zerocopy_flags)) {
20693 						freeb(md_pbuf_nxt);
20694 						TCP_STAT(tcps,
20695 						    tcp_mdt_allocfail);
20696 						/* out_of_mem */
20697 						goto legacy_send;
20698 					}
20699 					zcopy = B_TRUE;
20700 				}
20701 
20702 				/*
20703 				 * See comments above on the first call to
20704 				 * mmd_addpldbuf for explanation on the panic.
20705 				 */
20706 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20707 				if (pbuf_idx_nxt < 0) {
20708 					panic("tcp_multisend: "
20709 					    "next payload buffer logic error "
20710 					    "detected for tcp %p mmd %p "
20711 					    "pbuf %p (%d)\n",
20712 					    (void *)tcp, (void *)mmd,
20713 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20714 				}
20715 
20716 				ASSERT(max_pld > 0);
20717 				--max_pld;
20718 			} else if (spill > 0) {
20719 				/*
20720 				 * If there's a spillover, but the following
20721 				 * xmit_tail couldn't give us enough octets
20722 				 * to reach "len", then stop the current
20723 				 * Multidata creation and let the legacy
20724 				 * tcp_send() path take over.  We don't want
20725 				 * to send the tiny segment as part of this
20726 				 * Multidata for performance reasons; instead,
20727 				 * we let the legacy path deal with grouping
20728 				 * it with the subsequent small mblks.
20729 				 */
20730 				if (*usable >= len &&
20731 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20732 					max_pld = 0;
20733 					break;	/* done */
20734 				}
20735 
20736 				/*
20737 				 * We can't spillover, and we are near
20738 				 * the end of the current payload buffer,
20739 				 * so send what's left.
20740 				 */
20741 				ASSERT(*tail_unsent > 0);
20742 				len = *tail_unsent;
20743 			}
20744 
20745 			/* tail_unsent is negated if there is a spillover */
20746 			*tail_unsent -= len;
20747 			*usable -= len;
20748 			ASSERT(*usable >= 0);
20749 
20750 			if (*usable < mss)
20751 				seg_len = *usable;
20752 			/*
20753 			 * Sender SWS avoidance; see comments in tcp_send();
20754 			 * everything else is the same, except that we only
20755 			 * do this here if there is no more data to be sent
20756 			 * following the current xmit_tail.  We don't check
20757 			 * for 1-byte urgent data because we shouldn't get
20758 			 * here if TCP_URG_VALID is set.
20759 			 */
20760 			if (*usable > 0 && *usable < mss &&
20761 			    ((md_pbuf_nxt == NULL &&
20762 			    (*xmit_tail)->b_cont == NULL) ||
20763 			    (md_pbuf_nxt != NULL &&
20764 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20765 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20766 			    (tcp->tcp_unsent -
20767 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20768 			    !tcp->tcp_zero_win_probe) {
20769 				if ((*snxt + len) == tcp->tcp_snxt &&
20770 				    (*snxt + len) == tcp->tcp_suna) {
20771 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20772 				}
20773 				done = B_TRUE;
20774 			}
20775 
20776 			/*
20777 			 * Prime pump for IP's checksumming on our behalf;
20778 			 * include the adjustment for a source route if any.
20779 			 * Do this only for software/partial hardware checksum
20780 			 * offload, as this field gets zeroed out later for
20781 			 * the full hardware checksum offload case.
20782 			 */
20783 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20784 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20785 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20786 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20787 			}
20788 
20789 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20790 			*snxt += len;
20791 
20792 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20793 			/*
20794 			 * We set the PUSH bit only if TCP has no more buffered
20795 			 * data to be transmitted (or if sender SWS avoidance
20796 			 * takes place), as opposed to setting it for every
20797 			 * last packet in the burst.
20798 			 */
20799 			if (done ||
20800 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20801 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20802 
20803 			/*
20804 			 * Set FIN bit if this is our last segment; snxt
20805 			 * already includes its length, and it will not
20806 			 * be adjusted after this point.
20807 			 */
20808 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20809 			    *snxt == tcp->tcp_fss) {
20810 				if (!tcp->tcp_fin_acked) {
20811 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20812 					BUMP_MIB(&tcps->tcps_mib,
20813 					    tcpOutControl);
20814 				}
20815 				if (!tcp->tcp_fin_sent) {
20816 					tcp->tcp_fin_sent = B_TRUE;
20817 					/*
20818 					 * tcp state must be ESTABLISHED
20819 					 * in order for us to get here in
20820 					 * the first place.
20821 					 */
20822 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20823 
20824 					/*
20825 					 * Upon returning from this routine,
20826 					 * tcp_wput_data() will set tcp_snxt
20827 					 * to be equal to snxt + tcp_fin_sent.
20828 					 * This is essentially the same as
20829 					 * setting it to tcp_fss + 1.
20830 					 */
20831 				}
20832 			}
20833 
20834 			tcp->tcp_last_sent_len = (ushort_t)len;
20835 
20836 			len += tcp_hdr_len;
20837 			if (tcp->tcp_ipversion == IPV4_VERSION)
20838 				tcp->tcp_ipha->ipha_length = htons(len);
20839 			else
20840 				tcp->tcp_ip6h->ip6_plen = htons(len -
20841 				    ((char *)&tcp->tcp_ip6h[1] -
20842 				    tcp->tcp_iphc));
20843 
20844 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20845 
20846 			/* setup header fragment */
20847 			PDESC_HDR_ADD(pkt_info,
20848 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20849 			    tcp->tcp_mdt_hdr_head,		/* head room */
20850 			    tcp_hdr_len,			/* len */
20851 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20852 
20853 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20854 			    hdr_frag_sz);
20855 			ASSERT(MBLKIN(md_hbuf,
20856 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20857 			    PDESC_HDRSIZE(pkt_info)));
20858 
20859 			/* setup first payload fragment */
20860 			PDESC_PLD_INIT(pkt_info);
20861 			PDESC_PLD_SPAN_ADD(pkt_info,
20862 			    pbuf_idx,				/* index */
20863 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20864 			    tcp->tcp_last_sent_len);		/* len */
20865 
20866 			/* create a split-packet in case of a spillover */
20867 			if (md_pbuf_nxt != NULL) {
20868 				ASSERT(spill > 0);
20869 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20870 				ASSERT(!add_buffer);
20871 
20872 				md_pbuf = md_pbuf_nxt;
20873 				md_pbuf_nxt = NULL;
20874 				pbuf_idx = pbuf_idx_nxt;
20875 				pbuf_idx_nxt = -1;
20876 				cur_pld_off = spill;
20877 
20878 				/* trim out first payload fragment */
20879 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20880 
20881 				/* setup second payload fragment */
20882 				PDESC_PLD_SPAN_ADD(pkt_info,
20883 				    pbuf_idx,			/* index */
20884 				    md_pbuf->b_rptr,		/* start */
20885 				    spill);			/* len */
20886 
20887 				if ((*xmit_tail)->b_next == NULL) {
20888 					/*
20889 					 * Store the lbolt used for RTT
20890 					 * estimation. We can only record one
20891 					 * timestamp per mblk so we do it when
20892 					 * we reach the end of the payload
20893 					 * buffer.  Also we only take a new
20894 					 * timestamp sample when the previous
20895 					 * timed data from the same mblk has
20896 					 * been ack'ed.
20897 					 */
20898 					(*xmit_tail)->b_prev = local_time;
20899 					(*xmit_tail)->b_next =
20900 					    (mblk_t *)(uintptr_t)first_snxt;
20901 				}
20902 
20903 				first_snxt = *snxt - spill;
20904 
20905 				/*
20906 				 * Advance xmit_tail; usable could be 0 by
20907 				 * the time we got here, but we made sure
20908 				 * above that we would only spillover to
20909 				 * the next data block if usable includes
20910 				 * the spilled-over amount prior to the
20911 				 * subtraction.  Therefore, we are sure
20912 				 * that xmit_tail->b_cont can't be NULL.
20913 				 */
20914 				ASSERT((*xmit_tail)->b_cont != NULL);
20915 				*xmit_tail = (*xmit_tail)->b_cont;
20916 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20917 				    (uintptr_t)INT_MAX);
20918 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20919 			} else {
20920 				cur_pld_off += tcp->tcp_last_sent_len;
20921 			}
20922 
20923 			/*
20924 			 * Fill in the header using the template header, and
20925 			 * add options such as time-stamp, ECN and/or SACK,
20926 			 * as needed.
20927 			 */
20928 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20929 			    (clock_t)local_time, num_sack_blk);
20930 
20931 			/* take care of some IP header businesses */
20932 			if (af == AF_INET) {
20933 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20934 
20935 				ASSERT(OK_32PTR((uchar_t *)ipha));
20936 				ASSERT(PDESC_HDRL(pkt_info) >=
20937 				    IP_SIMPLE_HDR_LENGTH);
20938 				ASSERT(ipha->ipha_version_and_hdr_length ==
20939 				    IP_SIMPLE_HDR_VERSION);
20940 
20941 				/*
20942 				 * Assign ident value for current packet; see
20943 				 * related comments in ip_wput_ire() about the
20944 				 * contract private interface with clustering
20945 				 * group.
20946 				 */
20947 				clusterwide = B_FALSE;
20948 				if (cl_inet_ipident != NULL) {
20949 					ASSERT(cl_inet_isclusterwide != NULL);
20950 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20951 					    AF_INET,
20952 					    (uint8_t *)(uintptr_t)src)) {
20953 						ipha->ipha_ident =
20954 						    (*cl_inet_ipident)
20955 						    (IPPROTO_IP, AF_INET,
20956 						    (uint8_t *)(uintptr_t)src,
20957 						    (uint8_t *)(uintptr_t)dst);
20958 						clusterwide = B_TRUE;
20959 					}
20960 				}
20961 
20962 				if (!clusterwide) {
20963 					ipha->ipha_ident = (uint16_t)
20964 					    atomic_add_32_nv(
20965 						&ire->ire_ident, 1);
20966 				}
20967 #ifndef _BIG_ENDIAN
20968 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20969 				    (ipha->ipha_ident >> 8);
20970 #endif
20971 			} else {
20972 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20973 
20974 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20975 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20976 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20977 				ASSERT(PDESC_HDRL(pkt_info) >=
20978 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20979 				    TCP_CHECKSUM_SIZE));
20980 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20981 
20982 				if (tcp->tcp_ip_forward_progress) {
20983 					rconfirm = B_TRUE;
20984 					tcp->tcp_ip_forward_progress = B_FALSE;
20985 				}
20986 			}
20987 
20988 			/* at least one payload span, and at most two */
20989 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20990 
20991 			/* add the packet descriptor to Multidata */
20992 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20993 			    KM_NOSLEEP)) == NULL) {
20994 				/*
20995 				 * Any failure other than ENOMEM indicates
20996 				 * that we have passed in invalid pkt_info
20997 				 * or parameters to mmd_addpdesc, which must
20998 				 * not happen.
20999 				 *
21000 				 * EINVAL is a result of failure on boundary
21001 				 * checks against the pkt_info contents.  It
21002 				 * should not happen, and we panic because
21003 				 * either there's horrible heap corruption,
21004 				 * and/or programming mistake.
21005 				 */
21006 				if (err != ENOMEM) {
21007 					cmn_err(CE_PANIC, "tcp_multisend: "
21008 					    "pdesc logic error detected for "
21009 					    "tcp %p mmd %p pinfo %p (%d)\n",
21010 					    (void *)tcp, (void *)mmd,
21011 					    (void *)pkt_info, err);
21012 				}
21013 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
21014 				goto legacy_send; /* out_of_mem */
21015 			}
21016 			ASSERT(pkt != NULL);
21017 
21018 			/* calculate IP header and TCP checksums */
21019 			if (af == AF_INET) {
21020 				/* calculate pseudo-header checksum */
21021 				cksum = (dst >> 16) + (dst & 0xFFFF) +
21022 				    (src >> 16) + (src & 0xFFFF);
21023 
21024 				/* offset for TCP header checksum */
21025 				up = IPH_TCPH_CHECKSUMP(ipha,
21026 				    IP_SIMPLE_HDR_LENGTH);
21027 			} else {
21028 				up = (uint16_t *)&ip6h->ip6_src;
21029 
21030 				/* calculate pseudo-header checksum */
21031 				cksum = up[0] + up[1] + up[2] + up[3] +
21032 				    up[4] + up[5] + up[6] + up[7] +
21033 				    up[8] + up[9] + up[10] + up[11] +
21034 				    up[12] + up[13] + up[14] + up[15];
21035 
21036 				/* Fold the initial sum */
21037 				cksum = (cksum & 0xffff) + (cksum >> 16);
21038 
21039 				up = (uint16_t *)(((uchar_t *)ip6h) +
21040 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
21041 			}
21042 
21043 			if (hwcksum_flags & HCK_FULLCKSUM) {
21044 				/* clear checksum field for hardware */
21045 				*up = 0;
21046 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
21047 				uint32_t sum;
21048 
21049 				/* pseudo-header checksumming */
21050 				sum = *up + cksum + IP_TCP_CSUM_COMP;
21051 				sum = (sum & 0xFFFF) + (sum >> 16);
21052 				*up = (sum & 0xFFFF) + (sum >> 16);
21053 			} else {
21054 				/* software checksumming */
21055 				TCP_STAT(tcps, tcp_out_sw_cksum);
21056 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
21057 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
21058 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
21059 				    cksum + IP_TCP_CSUM_COMP);
21060 				if (*up == 0)
21061 					*up = 0xFFFF;
21062 			}
21063 
21064 			/* IPv4 header checksum */
21065 			if (af == AF_INET) {
21066 				ipha->ipha_fragment_offset_and_flags |=
21067 				    (uint32_t)htons(ire->ire_frag_flag);
21068 
21069 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
21070 					ipha->ipha_hdr_checksum = 0;
21071 				} else {
21072 					IP_HDR_CKSUM(ipha, cksum,
21073 					    ((uint32_t *)ipha)[0],
21074 					    ((uint16_t *)ipha)[4]);
21075 				}
21076 			}
21077 
21078 			if (af == AF_INET &&
21079 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
21080 			    af == AF_INET6 &&
21081 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
21082 				mblk_t	*mp, *mp1;
21083 				uchar_t	*hdr_rptr, *hdr_wptr;
21084 				uchar_t	*pld_rptr, *pld_wptr;
21085 
21086 				/*
21087 				 * We reconstruct a pseudo packet for the hooks
21088 				 * framework using mmd_transform_link().
21089 				 * If it is a split packet we pullup the
21090 				 * payload. FW_HOOKS expects a pkt comprising
21091 				 * of two mblks: a header and the payload.
21092 				 */
21093 				if ((mp = mmd_transform_link(pkt)) == NULL) {
21094 					TCP_STAT(tcps, tcp_mdt_allocfail);
21095 					goto legacy_send;
21096 				}
21097 
21098 				if (pkt_info->pld_cnt > 1) {
21099 					/* split payload, more than one pld */
21100 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
21101 					    NULL) {
21102 						freemsg(mp);
21103 						TCP_STAT(tcps,
21104 						    tcp_mdt_allocfail);
21105 						goto legacy_send;
21106 					}
21107 					freemsg(mp->b_cont);
21108 					mp->b_cont = mp1;
21109 				} else {
21110 					mp1 = mp->b_cont;
21111 				}
21112 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
21113 
21114 				/*
21115 				 * Remember the message offsets. This is so we
21116 				 * can detect changes when we return from the
21117 				 * FW_HOOKS callbacks.
21118 				 */
21119 				hdr_rptr = mp->b_rptr;
21120 				hdr_wptr = mp->b_wptr;
21121 				pld_rptr = mp->b_cont->b_rptr;
21122 				pld_wptr = mp->b_cont->b_wptr;
21123 
21124 				if (af == AF_INET) {
21125 					DTRACE_PROBE4(
21126 					    ip4__physical__out__start,
21127 					    ill_t *, NULL,
21128 					    ill_t *, ill,
21129 					    ipha_t *, ipha,
21130 					    mblk_t *, mp);
21131 					FW_HOOKS(
21132 					    ipst->ips_ip4_physical_out_event,
21133 					    ipst->ips_ipv4firewall_physical_out,
21134 					    NULL, ill, ipha, mp, mp, 0, ipst);
21135 					DTRACE_PROBE1(
21136 					    ip4__physical__out__end,
21137 					    mblk_t *, mp);
21138 				} else {
21139 					DTRACE_PROBE4(
21140 					    ip6__physical__out_start,
21141 					    ill_t *, NULL,
21142 					    ill_t *, ill,
21143 					    ip6_t *, ip6h,
21144 					    mblk_t *, mp);
21145 					FW_HOOKS6(
21146 					    ipst->ips_ip6_physical_out_event,
21147 					    ipst->ips_ipv6firewall_physical_out,
21148 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21149 					DTRACE_PROBE1(
21150 					    ip6__physical__out__end,
21151 					    mblk_t *, mp);
21152 				}
21153 
21154 				if (mp == NULL ||
21155 				    (mp1 = mp->b_cont) == NULL ||
21156 				    mp->b_rptr != hdr_rptr ||
21157 				    mp->b_wptr != hdr_wptr ||
21158 				    mp1->b_rptr != pld_rptr ||
21159 				    mp1->b_wptr != pld_wptr ||
21160 				    mp1->b_cont != NULL) {
21161 					/*
21162 					 * We abandon multidata processing and
21163 					 * return to the normal path, either
21164 					 * when a packet is blocked, or when
21165 					 * the boundaries of header buffer or
21166 					 * payload buffer have been changed by
21167 					 * FW_HOOKS[6].
21168 					 */
21169 					if (mp != NULL)
21170 						freemsg(mp);
21171 					goto legacy_send;
21172 				}
21173 				/* Finished with the pseudo packet */
21174 				freemsg(mp);
21175 			}
21176 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21177 			    ill, ipha, ip6h);
21178 			/* advance header offset */
21179 			cur_hdr_off += hdr_frag_sz;
21180 
21181 			obbytes += tcp->tcp_last_sent_len;
21182 			++obsegs;
21183 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21184 		    *tail_unsent > 0);
21185 
21186 		if ((*xmit_tail)->b_next == NULL) {
21187 			/*
21188 			 * Store the lbolt used for RTT estimation. We can only
21189 			 * record one timestamp per mblk so we do it when we
21190 			 * reach the end of the payload buffer. Also we only
21191 			 * take a new timestamp sample when the previous timed
21192 			 * data from the same mblk has been ack'ed.
21193 			 */
21194 			(*xmit_tail)->b_prev = local_time;
21195 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21196 		}
21197 
21198 		ASSERT(*tail_unsent >= 0);
21199 		if (*tail_unsent > 0) {
21200 			/*
21201 			 * We got here because we broke out of the above
21202 			 * loop due to of one of the following cases:
21203 			 *
21204 			 *   1. len < adjusted MSS (i.e. small),
21205 			 *   2. Sender SWS avoidance,
21206 			 *   3. max_pld is zero.
21207 			 *
21208 			 * We are done for this Multidata, so trim our
21209 			 * last payload buffer (if any) accordingly.
21210 			 */
21211 			if (md_pbuf != NULL)
21212 				md_pbuf->b_wptr -= *tail_unsent;
21213 		} else if (*usable > 0) {
21214 			*xmit_tail = (*xmit_tail)->b_cont;
21215 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21216 			    (uintptr_t)INT_MAX);
21217 			*tail_unsent = (int)MBLKL(*xmit_tail);
21218 			add_buffer = B_TRUE;
21219 		}
21220 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21221 	    (tcp_mdt_chain || max_pld > 0));
21222 
21223 	if (md_mp_head != NULL) {
21224 		/* send everything down */
21225 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21226 		    &rconfirm);
21227 	}
21228 
21229 #undef PREP_NEW_MULTIDATA
21230 #undef PREP_NEW_PBUF
21231 #undef IPVER
21232 
21233 	IRE_REFRELE(ire);
21234 	return (0);
21235 }
21236 
21237 /*
21238  * A wrapper function for sending one or more Multidata messages down to
21239  * the module below ip; this routine does not release the reference of the
21240  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21241  */
21242 static void
21243 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21244     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21245 {
21246 	uint64_t delta;
21247 	nce_t *nce;
21248 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21249 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21250 
21251 	ASSERT(ire != NULL && ill != NULL);
21252 	ASSERT(ire->ire_stq != NULL);
21253 	ASSERT(md_mp_head != NULL);
21254 	ASSERT(rconfirm != NULL);
21255 
21256 	/* adjust MIBs and IRE timestamp */
21257 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21258 	tcp->tcp_obsegs += obsegs;
21259 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21260 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21261 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21262 
21263 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21264 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21265 	} else {
21266 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21267 	}
21268 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21269 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21270 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21271 
21272 	ire->ire_ob_pkt_count += obsegs;
21273 	if (ire->ire_ipif != NULL)
21274 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21275 	ire->ire_last_used_time = lbolt;
21276 
21277 	if (ipst->ips_ipobs_enabled) {
21278 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21279 		pdesc_t *dl_pkt;
21280 		pdescinfo_t pinfo;
21281 		mblk_t *nmp;
21282 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21283 
21284 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21285 		    (dl_pkt != NULL);
21286 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21287 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21288 				continue;
21289 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21290 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21291 			freemsg(nmp);
21292 		}
21293 	}
21294 
21295 	/* send it down */
21296 	if (ILL_DLS_CAPABLE(ill)) {
21297 		ill_dls_capab_t *ill_dls = ill->ill_dls_capab;
21298 		ill_dls->ill_tx(ill_dls->ill_tx_handle, md_mp_head);
21299 	} else {
21300 		putnext(ire->ire_stq, md_mp_head);
21301 	}
21302 
21303 	/* we're done for TCP/IPv4 */
21304 	if (tcp->tcp_ipversion == IPV4_VERSION)
21305 		return;
21306 
21307 	nce = ire->ire_nce;
21308 
21309 	ASSERT(nce != NULL);
21310 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21311 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21312 
21313 	/* reachability confirmation? */
21314 	if (*rconfirm) {
21315 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21316 		if (nce->nce_state != ND_REACHABLE) {
21317 			mutex_enter(&nce->nce_lock);
21318 			nce->nce_state = ND_REACHABLE;
21319 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21320 			mutex_exit(&nce->nce_lock);
21321 			(void) untimeout(nce->nce_timeout_id);
21322 			if (ip_debug > 2) {
21323 				/* ip1dbg */
21324 				pr_addr_dbg("tcp_multisend_data: state "
21325 				    "for %s changed to REACHABLE\n",
21326 				    AF_INET6, &ire->ire_addr_v6);
21327 			}
21328 		}
21329 		/* reset transport reachability confirmation */
21330 		*rconfirm = B_FALSE;
21331 	}
21332 
21333 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21334 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21335 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21336 
21337 	if (delta > (uint64_t)ill->ill_reachable_time) {
21338 		mutex_enter(&nce->nce_lock);
21339 		switch (nce->nce_state) {
21340 		case ND_REACHABLE:
21341 		case ND_STALE:
21342 			/*
21343 			 * ND_REACHABLE is identical to ND_STALE in this
21344 			 * specific case. If reachable time has expired for
21345 			 * this neighbor (delta is greater than reachable
21346 			 * time), conceptually, the neighbor cache is no
21347 			 * longer in REACHABLE state, but already in STALE
21348 			 * state.  So the correct transition here is to
21349 			 * ND_DELAY.
21350 			 */
21351 			nce->nce_state = ND_DELAY;
21352 			mutex_exit(&nce->nce_lock);
21353 			NDP_RESTART_TIMER(nce,
21354 			    ipst->ips_delay_first_probe_time);
21355 			if (ip_debug > 3) {
21356 				/* ip2dbg */
21357 				pr_addr_dbg("tcp_multisend_data: state "
21358 				    "for %s changed to DELAY\n",
21359 				    AF_INET6, &ire->ire_addr_v6);
21360 			}
21361 			break;
21362 		case ND_DELAY:
21363 		case ND_PROBE:
21364 			mutex_exit(&nce->nce_lock);
21365 			/* Timers have already started */
21366 			break;
21367 		case ND_UNREACHABLE:
21368 			/*
21369 			 * ndp timer has detected that this nce is
21370 			 * unreachable and initiated deleting this nce
21371 			 * and all its associated IREs. This is a race
21372 			 * where we found the ire before it was deleted
21373 			 * and have just sent out a packet using this
21374 			 * unreachable nce.
21375 			 */
21376 			mutex_exit(&nce->nce_lock);
21377 			break;
21378 		default:
21379 			ASSERT(0);
21380 		}
21381 	}
21382 }
21383 
21384 /*
21385  * Derived from tcp_send_data().
21386  */
21387 static void
21388 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21389     int num_lso_seg)
21390 {
21391 	ipha_t		*ipha;
21392 	mblk_t		*ire_fp_mp;
21393 	uint_t		ire_fp_mp_len;
21394 	uint32_t	hcksum_txflags = 0;
21395 	ipaddr_t	src;
21396 	ipaddr_t	dst;
21397 	uint32_t	cksum;
21398 	uint16_t	*up;
21399 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21400 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21401 
21402 	ASSERT(DB_TYPE(mp) == M_DATA);
21403 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21404 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21405 	ASSERT(tcp->tcp_connp != NULL);
21406 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21407 
21408 	ipha = (ipha_t *)mp->b_rptr;
21409 	src = ipha->ipha_src;
21410 	dst = ipha->ipha_dst;
21411 
21412 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21413 
21414 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21415 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21416 	    num_lso_seg);
21417 #ifndef _BIG_ENDIAN
21418 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21419 #endif
21420 	if (tcp->tcp_snd_zcopy_aware) {
21421 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21422 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21423 			mp = tcp_zcopy_disable(tcp, mp);
21424 	}
21425 
21426 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21427 		ASSERT(ill->ill_hcksum_capab != NULL);
21428 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21429 	}
21430 
21431 	/*
21432 	 * Since the TCP checksum should be recalculated by h/w, we can just
21433 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21434 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21435 	 * The partial pseudo-header excludes TCP length, that was calculated
21436 	 * in tcp_send(), so to zero *up before further processing.
21437 	 */
21438 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21439 
21440 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21441 	*up = 0;
21442 
21443 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21444 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21445 
21446 	/*
21447 	 * Append LSO flag to DB_LSOFLAGS(mp) and set the mss to DB_LSOMSS(mp).
21448 	 */
21449 	DB_LSOFLAGS(mp) |= HW_LSO;
21450 	DB_LSOMSS(mp) = mss;
21451 
21452 	ipha->ipha_fragment_offset_and_flags |=
21453 	    (uint32_t)htons(ire->ire_frag_flag);
21454 
21455 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21456 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21457 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21458 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21459 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21460 
21461 	UPDATE_OB_PKT_COUNT(ire);
21462 	ire->ire_last_used_time = lbolt;
21463 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21464 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21465 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21466 	    ntohs(ipha->ipha_length));
21467 
21468 	if (ILL_DLS_CAPABLE(ill)) {
21469 		/*
21470 		 * Send the packet directly to DLD, where it may be queued
21471 		 * depending on the availability of transmit resources at
21472 		 * the media layer.
21473 		 */
21474 		IP_DLS_ILL_TX(ill, ipha, mp, ipst, ire_fp_mp_len);
21475 	} else {
21476 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
21477 		DTRACE_PROBE4(ip4__physical__out__start,
21478 		    ill_t *, NULL, ill_t *, out_ill,
21479 		    ipha_t *, ipha, mblk_t *, mp);
21480 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
21481 		    ipst->ips_ipv4firewall_physical_out,
21482 		    NULL, out_ill, ipha, mp, mp, 0, ipst);
21483 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21484 
21485 		if (mp != NULL) {
21486 			if (ipst->ips_ipobs_enabled) {
21487 				zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21488 
21489 				ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21490 				    ALL_ZONES, ill, tcp->tcp_ipversion,
21491 				    ire_fp_mp_len, ipst);
21492 			}
21493 			DTRACE_IP_FASTPATH(mp, ipha, out_ill, ipha, NULL);
21494 			putnext(ire->ire_stq, mp);
21495 		}
21496 	}
21497 }
21498 
21499 /*
21500  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21501  * scheme, and returns one of the following:
21502  *
21503  * -1 = failed allocation.
21504  *  0 = success; burst count reached, or usable send window is too small,
21505  *      and that we'd rather wait until later before sending again.
21506  *  1 = success; we are called from tcp_multisend(), and both usable send
21507  *      window and tail_unsent are greater than the MDT threshold, and thus
21508  *      Multidata Transmit should be used instead.
21509  */
21510 static int
21511 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21512     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21513     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21514     const int mdt_thres)
21515 {
21516 	int num_burst_seg = tcp->tcp_snd_burst;
21517 	ire_t		*ire = NULL;
21518 	ill_t		*ill = NULL;
21519 	mblk_t		*ire_fp_mp = NULL;
21520 	uint_t		ire_fp_mp_len = 0;
21521 	int		num_lso_seg = 1;
21522 	uint_t		lso_usable;
21523 	boolean_t	do_lso_send = B_FALSE;
21524 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21525 
21526 	/*
21527 	 * Check LSO capability before any further work. And the similar check
21528 	 * need to be done in for(;;) loop.
21529 	 * LSO will be deployed when therer is more than one mss of available
21530 	 * data and a burst transmission is allowed.
21531 	 */
21532 	if (tcp->tcp_lso &&
21533 	    (tcp->tcp_valid_bits == 0 ||
21534 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21535 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21536 		/*
21537 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21538 		 */
21539 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21540 			/*
21541 			 * Enable LSO with this transmission.
21542 			 * Since IRE has been hold in
21543 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21544 			 * should be called before return.
21545 			 */
21546 			do_lso_send = B_TRUE;
21547 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21548 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21549 			/* Round up to multiple of 4 */
21550 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21551 		} else {
21552 			do_lso_send = B_FALSE;
21553 			ill = NULL;
21554 		}
21555 	}
21556 
21557 	for (;;) {
21558 		struct datab	*db;
21559 		tcph_t		*tcph;
21560 		uint32_t	sum;
21561 		mblk_t		*mp, *mp1;
21562 		uchar_t		*rptr;
21563 		int		len;
21564 
21565 		/*
21566 		 * If we're called by tcp_multisend(), and the amount of
21567 		 * sendable data as well as the size of current xmit_tail
21568 		 * is beyond the MDT threshold, return to the caller and
21569 		 * let the large data transmit be done using MDT.
21570 		 */
21571 		if (*usable > 0 && *usable > mdt_thres &&
21572 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21573 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21574 			ASSERT(tcp->tcp_mdt);
21575 			return (1);	/* success; do large send */
21576 		}
21577 
21578 		if (num_burst_seg == 0)
21579 			break;		/* success; burst count reached */
21580 
21581 		/*
21582 		 * Calculate the maximum payload length we can send in *one*
21583 		 * time.
21584 		 */
21585 		if (do_lso_send) {
21586 			/*
21587 			 * Check whether need to do LSO any more.
21588 			 */
21589 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21590 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21591 				lso_usable = MIN(lso_usable,
21592 				    num_burst_seg * mss);
21593 
21594 				num_lso_seg = lso_usable / mss;
21595 				if (lso_usable % mss) {
21596 					num_lso_seg++;
21597 					tcp->tcp_last_sent_len = (ushort_t)
21598 					    (lso_usable % mss);
21599 				} else {
21600 					tcp->tcp_last_sent_len = (ushort_t)mss;
21601 				}
21602 			} else {
21603 				do_lso_send = B_FALSE;
21604 				num_lso_seg = 1;
21605 				lso_usable = mss;
21606 			}
21607 		}
21608 
21609 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21610 
21611 		/*
21612 		 * Adjust num_burst_seg here.
21613 		 */
21614 		num_burst_seg -= num_lso_seg;
21615 
21616 		len = mss;
21617 		if (len > *usable) {
21618 			ASSERT(do_lso_send == B_FALSE);
21619 
21620 			len = *usable;
21621 			if (len <= 0) {
21622 				/* Terminate the loop */
21623 				break;	/* success; too small */
21624 			}
21625 			/*
21626 			 * Sender silly-window avoidance.
21627 			 * Ignore this if we are going to send a
21628 			 * zero window probe out.
21629 			 *
21630 			 * TODO: force data into microscopic window?
21631 			 *	==> (!pushed || (unsent > usable))
21632 			 */
21633 			if (len < (tcp->tcp_max_swnd >> 1) &&
21634 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21635 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21636 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21637 				/*
21638 				 * If the retransmit timer is not running
21639 				 * we start it so that we will retransmit
21640 				 * in the case when the the receiver has
21641 				 * decremented the window.
21642 				 */
21643 				if (*snxt == tcp->tcp_snxt &&
21644 				    *snxt == tcp->tcp_suna) {
21645 					/*
21646 					 * We are not supposed to send
21647 					 * anything.  So let's wait a little
21648 					 * bit longer before breaking SWS
21649 					 * avoidance.
21650 					 *
21651 					 * What should the value be?
21652 					 * Suggestion: MAX(init rexmit time,
21653 					 * tcp->tcp_rto)
21654 					 */
21655 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21656 				}
21657 				break;	/* success; too small */
21658 			}
21659 		}
21660 
21661 		tcph = tcp->tcp_tcph;
21662 
21663 		/*
21664 		 * The reason to adjust len here is that we need to set flags
21665 		 * and calculate checksum.
21666 		 */
21667 		if (do_lso_send)
21668 			len = lso_usable;
21669 
21670 		*usable -= len; /* Approximate - can be adjusted later */
21671 		if (*usable > 0)
21672 			tcph->th_flags[0] = TH_ACK;
21673 		else
21674 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21675 
21676 		/*
21677 		 * Prime pump for IP's checksumming on our behalf
21678 		 * Include the adjustment for a source route if any.
21679 		 */
21680 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21681 		sum = (sum >> 16) + (sum & 0xFFFF);
21682 		U16_TO_ABE16(sum, tcph->th_sum);
21683 
21684 		U32_TO_ABE32(*snxt, tcph->th_seq);
21685 
21686 		/*
21687 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21688 		 * set.  For the case when TCP_FSS_VALID is the only valid
21689 		 * bit (normal active close), branch off only when we think
21690 		 * that the FIN flag needs to be set.  Note for this case,
21691 		 * that (snxt + len) may not reflect the actual seg_len,
21692 		 * as len may be further reduced in tcp_xmit_mp().  If len
21693 		 * gets modified, we will end up here again.
21694 		 */
21695 		if (tcp->tcp_valid_bits != 0 &&
21696 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21697 		    ((*snxt + len) == tcp->tcp_fss))) {
21698 			uchar_t		*prev_rptr;
21699 			uint32_t	prev_snxt = tcp->tcp_snxt;
21700 
21701 			if (*tail_unsent == 0) {
21702 				ASSERT((*xmit_tail)->b_cont != NULL);
21703 				*xmit_tail = (*xmit_tail)->b_cont;
21704 				prev_rptr = (*xmit_tail)->b_rptr;
21705 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21706 				    (*xmit_tail)->b_rptr);
21707 			} else {
21708 				prev_rptr = (*xmit_tail)->b_rptr;
21709 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21710 				    *tail_unsent;
21711 			}
21712 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21713 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21714 			/* Restore tcp_snxt so we get amount sent right. */
21715 			tcp->tcp_snxt = prev_snxt;
21716 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21717 				/*
21718 				 * If the previous timestamp is still in use,
21719 				 * don't stomp on it.
21720 				 */
21721 				if ((*xmit_tail)->b_next == NULL) {
21722 					(*xmit_tail)->b_prev = local_time;
21723 					(*xmit_tail)->b_next =
21724 					    (mblk_t *)(uintptr_t)(*snxt);
21725 				}
21726 			} else
21727 				(*xmit_tail)->b_rptr = prev_rptr;
21728 
21729 			if (mp == NULL) {
21730 				if (ire != NULL)
21731 					IRE_REFRELE(ire);
21732 				return (-1);
21733 			}
21734 			mp1 = mp->b_cont;
21735 
21736 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21737 				tcp->tcp_last_sent_len = (ushort_t)len;
21738 			while (mp1->b_cont) {
21739 				*xmit_tail = (*xmit_tail)->b_cont;
21740 				(*xmit_tail)->b_prev = local_time;
21741 				(*xmit_tail)->b_next =
21742 				    (mblk_t *)(uintptr_t)(*snxt);
21743 				mp1 = mp1->b_cont;
21744 			}
21745 			*snxt += len;
21746 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21747 			BUMP_LOCAL(tcp->tcp_obsegs);
21748 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21749 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21750 			tcp_send_data(tcp, q, mp);
21751 			continue;
21752 		}
21753 
21754 		*snxt += len;	/* Adjust later if we don't send all of len */
21755 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21756 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21757 
21758 		if (*tail_unsent) {
21759 			/* Are the bytes above us in flight? */
21760 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21761 			if (rptr != (*xmit_tail)->b_rptr) {
21762 				*tail_unsent -= len;
21763 				if (len <= mss) /* LSO is unusable */
21764 					tcp->tcp_last_sent_len = (ushort_t)len;
21765 				len += tcp_hdr_len;
21766 				if (tcp->tcp_ipversion == IPV4_VERSION)
21767 					tcp->tcp_ipha->ipha_length = htons(len);
21768 				else
21769 					tcp->tcp_ip6h->ip6_plen =
21770 					    htons(len -
21771 					    ((char *)&tcp->tcp_ip6h[1] -
21772 					    tcp->tcp_iphc));
21773 				mp = dupb(*xmit_tail);
21774 				if (mp == NULL) {
21775 					if (ire != NULL)
21776 						IRE_REFRELE(ire);
21777 					return (-1);	/* out_of_mem */
21778 				}
21779 				mp->b_rptr = rptr;
21780 				/*
21781 				 * If the old timestamp is no longer in use,
21782 				 * sample a new timestamp now.
21783 				 */
21784 				if ((*xmit_tail)->b_next == NULL) {
21785 					(*xmit_tail)->b_prev = local_time;
21786 					(*xmit_tail)->b_next =
21787 					    (mblk_t *)(uintptr_t)(*snxt-len);
21788 				}
21789 				goto must_alloc;
21790 			}
21791 		} else {
21792 			*xmit_tail = (*xmit_tail)->b_cont;
21793 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21794 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21795 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21796 			    (*xmit_tail)->b_rptr);
21797 		}
21798 
21799 		(*xmit_tail)->b_prev = local_time;
21800 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21801 
21802 		*tail_unsent -= len;
21803 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21804 			tcp->tcp_last_sent_len = (ushort_t)len;
21805 
21806 		len += tcp_hdr_len;
21807 		if (tcp->tcp_ipversion == IPV4_VERSION)
21808 			tcp->tcp_ipha->ipha_length = htons(len);
21809 		else
21810 			tcp->tcp_ip6h->ip6_plen = htons(len -
21811 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21812 
21813 		mp = dupb(*xmit_tail);
21814 		if (mp == NULL) {
21815 			if (ire != NULL)
21816 				IRE_REFRELE(ire);
21817 			return (-1);	/* out_of_mem */
21818 		}
21819 
21820 		len = tcp_hdr_len;
21821 		/*
21822 		 * There are four reasons to allocate a new hdr mblk:
21823 		 *  1) The bytes above us are in use by another packet
21824 		 *  2) We don't have good alignment
21825 		 *  3) The mblk is being shared
21826 		 *  4) We don't have enough room for a header
21827 		 */
21828 		rptr = mp->b_rptr - len;
21829 		if (!OK_32PTR(rptr) ||
21830 		    ((db = mp->b_datap), db->db_ref != 2) ||
21831 		    rptr < db->db_base + ire_fp_mp_len) {
21832 			/* NOTE: we assume allocb returns an OK_32PTR */
21833 
21834 		must_alloc:;
21835 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21836 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21837 			if (mp1 == NULL) {
21838 				freemsg(mp);
21839 				if (ire != NULL)
21840 					IRE_REFRELE(ire);
21841 				return (-1);	/* out_of_mem */
21842 			}
21843 			mp1->b_cont = mp;
21844 			mp = mp1;
21845 			/* Leave room for Link Level header */
21846 			len = tcp_hdr_len;
21847 			rptr =
21848 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21849 			mp->b_wptr = &rptr[len];
21850 		}
21851 
21852 		/*
21853 		 * Fill in the header using the template header, and add
21854 		 * options such as time-stamp, ECN and/or SACK, as needed.
21855 		 */
21856 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21857 
21858 		mp->b_rptr = rptr;
21859 
21860 		if (*tail_unsent) {
21861 			int spill = *tail_unsent;
21862 
21863 			mp1 = mp->b_cont;
21864 			if (mp1 == NULL)
21865 				mp1 = mp;
21866 
21867 			/*
21868 			 * If we're a little short, tack on more mblks until
21869 			 * there is no more spillover.
21870 			 */
21871 			while (spill < 0) {
21872 				mblk_t *nmp;
21873 				int nmpsz;
21874 
21875 				nmp = (*xmit_tail)->b_cont;
21876 				nmpsz = MBLKL(nmp);
21877 
21878 				/*
21879 				 * Excess data in mblk; can we split it?
21880 				 * If MDT is enabled for the connection,
21881 				 * keep on splitting as this is a transient
21882 				 * send path.
21883 				 */
21884 				if (!do_lso_send && !tcp->tcp_mdt &&
21885 				    (spill + nmpsz > 0)) {
21886 					/*
21887 					 * Don't split if stream head was
21888 					 * told to break up larger writes
21889 					 * into smaller ones.
21890 					 */
21891 					if (tcp->tcp_maxpsz > 0)
21892 						break;
21893 
21894 					/*
21895 					 * Next mblk is less than SMSS/2
21896 					 * rounded up to nearest 64-byte;
21897 					 * let it get sent as part of the
21898 					 * next segment.
21899 					 */
21900 					if (tcp->tcp_localnet &&
21901 					    !tcp->tcp_cork &&
21902 					    (nmpsz < roundup((mss >> 1), 64)))
21903 						break;
21904 				}
21905 
21906 				*xmit_tail = nmp;
21907 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21908 				/* Stash for rtt use later */
21909 				(*xmit_tail)->b_prev = local_time;
21910 				(*xmit_tail)->b_next =
21911 				    (mblk_t *)(uintptr_t)(*snxt - len);
21912 				mp1->b_cont = dupb(*xmit_tail);
21913 				mp1 = mp1->b_cont;
21914 
21915 				spill += nmpsz;
21916 				if (mp1 == NULL) {
21917 					*tail_unsent = spill;
21918 					freemsg(mp);
21919 					if (ire != NULL)
21920 						IRE_REFRELE(ire);
21921 					return (-1);	/* out_of_mem */
21922 				}
21923 			}
21924 
21925 			/* Trim back any surplus on the last mblk */
21926 			if (spill >= 0) {
21927 				mp1->b_wptr -= spill;
21928 				*tail_unsent = spill;
21929 			} else {
21930 				/*
21931 				 * We did not send everything we could in
21932 				 * order to remain within the b_cont limit.
21933 				 */
21934 				*usable -= spill;
21935 				*snxt += spill;
21936 				tcp->tcp_last_sent_len += spill;
21937 				UPDATE_MIB(&tcps->tcps_mib,
21938 				    tcpOutDataBytes, spill);
21939 				/*
21940 				 * Adjust the checksum
21941 				 */
21942 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21943 				sum += spill;
21944 				sum = (sum >> 16) + (sum & 0xFFFF);
21945 				U16_TO_ABE16(sum, tcph->th_sum);
21946 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21947 					sum = ntohs(
21948 					    ((ipha_t *)rptr)->ipha_length) +
21949 					    spill;
21950 					((ipha_t *)rptr)->ipha_length =
21951 					    htons(sum);
21952 				} else {
21953 					sum = ntohs(
21954 					    ((ip6_t *)rptr)->ip6_plen) +
21955 					    spill;
21956 					((ip6_t *)rptr)->ip6_plen =
21957 					    htons(sum);
21958 				}
21959 				*tail_unsent = 0;
21960 			}
21961 		}
21962 		if (tcp->tcp_ip_forward_progress) {
21963 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21964 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21965 			tcp->tcp_ip_forward_progress = B_FALSE;
21966 		}
21967 
21968 		if (do_lso_send) {
21969 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21970 			    num_lso_seg);
21971 			tcp->tcp_obsegs += num_lso_seg;
21972 
21973 			TCP_STAT(tcps, tcp_lso_times);
21974 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21975 		} else {
21976 			tcp_send_data(tcp, q, mp);
21977 			BUMP_LOCAL(tcp->tcp_obsegs);
21978 		}
21979 	}
21980 
21981 	if (ire != NULL)
21982 		IRE_REFRELE(ire);
21983 	return (0);
21984 }
21985 
21986 /* Unlink and return any mblk that looks like it contains a MDT info */
21987 static mblk_t *
21988 tcp_mdt_info_mp(mblk_t *mp)
21989 {
21990 	mblk_t	*prev_mp;
21991 
21992 	for (;;) {
21993 		prev_mp = mp;
21994 		/* no more to process? */
21995 		if ((mp = mp->b_cont) == NULL)
21996 			break;
21997 
21998 		switch (DB_TYPE(mp)) {
21999 		case M_CTL:
22000 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
22001 				continue;
22002 			ASSERT(prev_mp != NULL);
22003 			prev_mp->b_cont = mp->b_cont;
22004 			mp->b_cont = NULL;
22005 			return (mp);
22006 		default:
22007 			break;
22008 		}
22009 	}
22010 	return (mp);
22011 }
22012 
22013 /* MDT info update routine, called when IP notifies us about MDT */
22014 static void
22015 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
22016 {
22017 	boolean_t prev_state;
22018 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22019 
22020 	/*
22021 	 * IP is telling us to abort MDT on this connection?  We know
22022 	 * this because the capability is only turned off when IP
22023 	 * encounters some pathological cases, e.g. link-layer change
22024 	 * where the new driver doesn't support MDT, or in situation
22025 	 * where MDT usage on the link-layer has been switched off.
22026 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
22027 	 * if the link-layer doesn't support MDT, and if it does, it
22028 	 * will indicate that the feature is to be turned on.
22029 	 */
22030 	prev_state = tcp->tcp_mdt;
22031 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
22032 	if (!tcp->tcp_mdt && !first) {
22033 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
22034 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
22035 		    (void *)tcp->tcp_connp));
22036 	}
22037 
22038 	/*
22039 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
22040 	 * so disable MDT otherwise.  The checks are done here
22041 	 * and in tcp_wput_data().
22042 	 */
22043 	if (tcp->tcp_mdt &&
22044 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22045 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22046 	    (tcp->tcp_ipversion == IPV6_VERSION &&
22047 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
22048 		tcp->tcp_mdt = B_FALSE;
22049 
22050 	if (tcp->tcp_mdt) {
22051 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
22052 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
22053 			    "version (%d), expected version is %d",
22054 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
22055 			tcp->tcp_mdt = B_FALSE;
22056 			return;
22057 		}
22058 
22059 		/*
22060 		 * We need the driver to be able to handle at least three
22061 		 * spans per packet in order for tcp MDT to be utilized.
22062 		 * The first is for the header portion, while the rest are
22063 		 * needed to handle a packet that straddles across two
22064 		 * virtually non-contiguous buffers; a typical tcp packet
22065 		 * therefore consists of only two spans.  Note that we take
22066 		 * a zero as "don't care".
22067 		 */
22068 		if (mdt_capab->ill_mdt_span_limit > 0 &&
22069 		    mdt_capab->ill_mdt_span_limit < 3) {
22070 			tcp->tcp_mdt = B_FALSE;
22071 			return;
22072 		}
22073 
22074 		/* a zero means driver wants default value */
22075 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
22076 		    tcps->tcps_mdt_max_pbufs);
22077 		if (tcp->tcp_mdt_max_pld == 0)
22078 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
22079 
22080 		/* ensure 32-bit alignment */
22081 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
22082 		    mdt_capab->ill_mdt_hdr_head), 4);
22083 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
22084 		    mdt_capab->ill_mdt_hdr_tail), 4);
22085 
22086 		if (!first && !prev_state) {
22087 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
22088 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
22089 			    (void *)tcp->tcp_connp));
22090 		}
22091 	}
22092 }
22093 
22094 /* Unlink and return any mblk that looks like it contains a LSO info */
22095 static mblk_t *
22096 tcp_lso_info_mp(mblk_t *mp)
22097 {
22098 	mblk_t	*prev_mp;
22099 
22100 	for (;;) {
22101 		prev_mp = mp;
22102 		/* no more to process? */
22103 		if ((mp = mp->b_cont) == NULL)
22104 			break;
22105 
22106 		switch (DB_TYPE(mp)) {
22107 		case M_CTL:
22108 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
22109 				continue;
22110 			ASSERT(prev_mp != NULL);
22111 			prev_mp->b_cont = mp->b_cont;
22112 			mp->b_cont = NULL;
22113 			return (mp);
22114 		default:
22115 			break;
22116 		}
22117 	}
22118 
22119 	return (mp);
22120 }
22121 
22122 /* LSO info update routine, called when IP notifies us about LSO */
22123 static void
22124 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
22125 {
22126 	tcp_stack_t *tcps = tcp->tcp_tcps;
22127 
22128 	/*
22129 	 * IP is telling us to abort LSO on this connection?  We know
22130 	 * this because the capability is only turned off when IP
22131 	 * encounters some pathological cases, e.g. link-layer change
22132 	 * where the new NIC/driver doesn't support LSO, or in situation
22133 	 * where LSO usage on the link-layer has been switched off.
22134 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
22135 	 * if the link-layer doesn't support LSO, and if it does, it
22136 	 * will indicate that the feature is to be turned on.
22137 	 */
22138 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
22139 	TCP_STAT(tcps, tcp_lso_enabled);
22140 
22141 	/*
22142 	 * We currently only support LSO on simple TCP/IPv4,
22143 	 * so disable LSO otherwise.  The checks are done here
22144 	 * and in tcp_wput_data().
22145 	 */
22146 	if (tcp->tcp_lso &&
22147 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22148 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22149 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
22150 		tcp->tcp_lso = B_FALSE;
22151 		TCP_STAT(tcps, tcp_lso_disabled);
22152 	} else {
22153 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
22154 		    lso_capab->ill_lso_max);
22155 	}
22156 }
22157 
22158 static void
22159 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22160 {
22161 	conn_t *connp = tcp->tcp_connp;
22162 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22163 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22164 
22165 	ASSERT(ire != NULL);
22166 
22167 	/*
22168 	 * We may be in the fastpath here, and although we essentially do
22169 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22170 	 * we try to keep things as brief as possible.  After all, these
22171 	 * are only best-effort checks, and we do more thorough ones prior
22172 	 * to calling tcp_send()/tcp_multisend().
22173 	 */
22174 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22175 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22176 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22177 	    !(ire->ire_flags & RTF_MULTIRT) &&
22178 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22179 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22180 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22181 			/* Cache the result */
22182 			connp->conn_lso_ok = B_TRUE;
22183 
22184 			ASSERT(ill->ill_lso_capab != NULL);
22185 			if (!ill->ill_lso_capab->ill_lso_on) {
22186 				ill->ill_lso_capab->ill_lso_on = 1;
22187 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22188 				    "LSO for interface %s\n", (void *)connp,
22189 				    ill->ill_name));
22190 			}
22191 			tcp_lso_update(tcp, ill->ill_lso_capab);
22192 		} else if (ipst->ips_ip_multidata_outbound &&
22193 		    ILL_MDT_CAPABLE(ill)) {
22194 			/* Cache the result */
22195 			connp->conn_mdt_ok = B_TRUE;
22196 
22197 			ASSERT(ill->ill_mdt_capab != NULL);
22198 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22199 				ill->ill_mdt_capab->ill_mdt_on = 1;
22200 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22201 				    "MDT for interface %s\n", (void *)connp,
22202 				    ill->ill_name));
22203 			}
22204 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22205 		}
22206 	}
22207 
22208 	/*
22209 	 * The goal is to reduce the number of generated tcp segments by
22210 	 * setting the maxpsz multiplier to 0; this will have an affect on
22211 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22212 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22213 	 * of outbound segments and incoming ACKs, thus allowing for better
22214 	 * network and system performance.  In contrast the legacy behavior
22215 	 * may result in sending less than SMSS size, because the last mblk
22216 	 * for some packets may have more data than needed to make up SMSS,
22217 	 * and the legacy code refused to "split" it.
22218 	 *
22219 	 * We apply the new behavior on following situations:
22220 	 *
22221 	 *   1) Loopback connections,
22222 	 *   2) Connections in which the remote peer is not on local subnet,
22223 	 *   3) Local subnet connections over the bge interface (see below).
22224 	 *
22225 	 * Ideally, we would like this behavior to apply for interfaces other
22226 	 * than bge.  However, doing so would negatively impact drivers which
22227 	 * perform dynamic mapping and unmapping of DMA resources, which are
22228 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22229 	 * packet will be generated by tcp).  The bge driver does not suffer
22230 	 * from this, as it copies the mblks into pre-mapped buffers, and
22231 	 * therefore does not require more I/O resources than before.
22232 	 *
22233 	 * Otherwise, this behavior is present on all network interfaces when
22234 	 * the destination endpoint is non-local, since reducing the number
22235 	 * of packets in general is good for the network.
22236 	 *
22237 	 * TODO We need to remove this hard-coded conditional for bge once
22238 	 *	a better "self-tuning" mechanism, or a way to comprehend
22239 	 *	the driver transmit strategy is devised.  Until the solution
22240 	 *	is found and well understood, we live with this hack.
22241 	 */
22242 	if (!tcp_static_maxpsz &&
22243 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22244 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22245 		/* override the default value */
22246 		tcp->tcp_maxpsz = 0;
22247 
22248 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22249 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22250 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22251 	}
22252 
22253 	/* set the stream head parameters accordingly */
22254 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22255 }
22256 
22257 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22258 static void
22259 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22260 {
22261 	uchar_t	fval = *mp->b_rptr;
22262 	mblk_t	*tail;
22263 	queue_t	*q = tcp->tcp_wq;
22264 
22265 	/* TODO: How should flush interact with urgent data? */
22266 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22267 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22268 		/*
22269 		 * Flush only data that has not yet been put on the wire.  If
22270 		 * we flush data that we have already transmitted, life, as we
22271 		 * know it, may come to an end.
22272 		 */
22273 		tail = tcp->tcp_xmit_tail;
22274 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22275 		tcp->tcp_xmit_tail_unsent = 0;
22276 		tcp->tcp_unsent = 0;
22277 		if (tail->b_wptr != tail->b_rptr)
22278 			tail = tail->b_cont;
22279 		if (tail) {
22280 			mblk_t **excess = &tcp->tcp_xmit_head;
22281 			for (;;) {
22282 				mblk_t *mp1 = *excess;
22283 				if (mp1 == tail)
22284 					break;
22285 				tcp->tcp_xmit_tail = mp1;
22286 				tcp->tcp_xmit_last = mp1;
22287 				excess = &mp1->b_cont;
22288 			}
22289 			*excess = NULL;
22290 			tcp_close_mpp(&tail);
22291 			if (tcp->tcp_snd_zcopy_aware)
22292 				tcp_zcopy_notify(tcp);
22293 		}
22294 		/*
22295 		 * We have no unsent data, so unsent must be less than
22296 		 * tcp_xmit_lowater, so re-enable flow.
22297 		 */
22298 		mutex_enter(&tcp->tcp_non_sq_lock);
22299 		if (tcp->tcp_flow_stopped) {
22300 			tcp_clrqfull(tcp);
22301 		}
22302 		mutex_exit(&tcp->tcp_non_sq_lock);
22303 	}
22304 	/*
22305 	 * TODO: you can't just flush these, you have to increase rwnd for one
22306 	 * thing.  For another, how should urgent data interact?
22307 	 */
22308 	if (fval & FLUSHR) {
22309 		*mp->b_rptr = fval & ~FLUSHW;
22310 		/* XXX */
22311 		qreply(q, mp);
22312 		return;
22313 	}
22314 	freemsg(mp);
22315 }
22316 
22317 /*
22318  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22319  * messages.
22320  */
22321 static void
22322 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22323 {
22324 	mblk_t	*mp1;
22325 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22326 	STRUCT_HANDLE(strbuf, sb);
22327 	queue_t *q = tcp->tcp_wq;
22328 	int	error;
22329 	uint_t	addrlen;
22330 
22331 	/* Make sure it is one of ours. */
22332 	switch (iocp->ioc_cmd) {
22333 	case TI_GETMYNAME:
22334 	case TI_GETPEERNAME:
22335 		break;
22336 	default:
22337 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22338 		return;
22339 	}
22340 	switch (mi_copy_state(q, mp, &mp1)) {
22341 	case -1:
22342 		return;
22343 	case MI_COPY_CASE(MI_COPY_IN, 1):
22344 		break;
22345 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22346 		/* Copy out the strbuf. */
22347 		mi_copyout(q, mp);
22348 		return;
22349 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22350 		/* All done. */
22351 		mi_copy_done(q, mp, 0);
22352 		return;
22353 	default:
22354 		mi_copy_done(q, mp, EPROTO);
22355 		return;
22356 	}
22357 	/* Check alignment of the strbuf */
22358 	if (!OK_32PTR(mp1->b_rptr)) {
22359 		mi_copy_done(q, mp, EINVAL);
22360 		return;
22361 	}
22362 
22363 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22364 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22365 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22366 		mi_copy_done(q, mp, EINVAL);
22367 		return;
22368 	}
22369 
22370 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22371 	if (mp1 == NULL)
22372 		return;
22373 
22374 	switch (iocp->ioc_cmd) {
22375 	case TI_GETMYNAME:
22376 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22377 		break;
22378 	case TI_GETPEERNAME:
22379 		error = tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22380 		break;
22381 	}
22382 
22383 	if (error != 0) {
22384 		mi_copy_done(q, mp, error);
22385 	} else {
22386 		mp1->b_wptr += addrlen;
22387 		STRUCT_FSET(sb, len, addrlen);
22388 
22389 		/* Copy out the address */
22390 		mi_copyout(q, mp);
22391 	}
22392 }
22393 
22394 /*
22395  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22396  * messages.
22397  */
22398 /* ARGSUSED */
22399 static void
22400 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22401 {
22402 	conn_t 	*connp = (conn_t *)arg;
22403 	tcp_t	*tcp = connp->conn_tcp;
22404 	queue_t	*q = tcp->tcp_wq;
22405 	struct iocblk	*iocp;
22406 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22407 
22408 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22409 	/*
22410 	 * Try and ASSERT the minimum possible references on the
22411 	 * conn early enough. Since we are executing on write side,
22412 	 * the connection is obviously not detached and that means
22413 	 * there is a ref each for TCP and IP. Since we are behind
22414 	 * the squeue, the minimum references needed are 3. If the
22415 	 * conn is in classifier hash list, there should be an
22416 	 * extra ref for that (we check both the possibilities).
22417 	 */
22418 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22419 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22420 
22421 	iocp = (struct iocblk *)mp->b_rptr;
22422 	switch (iocp->ioc_cmd) {
22423 	case TCP_IOC_DEFAULT_Q:
22424 		/* Wants to be the default wq. */
22425 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22426 			iocp->ioc_error = EPERM;
22427 			iocp->ioc_count = 0;
22428 			mp->b_datap->db_type = M_IOCACK;
22429 			qreply(q, mp);
22430 			return;
22431 		}
22432 		tcp_def_q_set(tcp, mp);
22433 		return;
22434 	case _SIOCSOCKFALLBACK:
22435 		/*
22436 		 * Either sockmod is about to be popped and the socket
22437 		 * would now be treated as a plain stream, or a module
22438 		 * is about to be pushed so we could no longer use read-
22439 		 * side synchronous streams for fused loopback tcp.
22440 		 * Drain any queued data and disable direct sockfs
22441 		 * interface from now on.
22442 		 */
22443 		if (!tcp->tcp_issocket) {
22444 			DB_TYPE(mp) = M_IOCNAK;
22445 			iocp->ioc_error = EINVAL;
22446 		} else {
22447 #ifdef	_ILP32
22448 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
22449 #else
22450 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22451 #endif
22452 			/*
22453 			 * Insert this socket into the acceptor hash.
22454 			 * We might need it for T_CONN_RES message
22455 			 */
22456 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22457 
22458 			if (tcp->tcp_fused) {
22459 				/*
22460 				 * This is a fused loopback tcp; disable
22461 				 * read-side synchronous streams interface
22462 				 * and drain any queued data.  It is okay
22463 				 * to do this for non-synchronous streams
22464 				 * fused tcp as well.
22465 				 */
22466 				tcp_fuse_disable_pair(tcp, B_FALSE);
22467 			}
22468 			tcp->tcp_issocket = B_FALSE;
22469 			tcp->tcp_sodirect = NULL;
22470 			TCP_STAT(tcps, tcp_sock_fallback);
22471 
22472 			DB_TYPE(mp) = M_IOCACK;
22473 			iocp->ioc_error = 0;
22474 		}
22475 		iocp->ioc_count = 0;
22476 		iocp->ioc_rval = 0;
22477 		qreply(q, mp);
22478 		return;
22479 	}
22480 	CALL_IP_WPUT(connp, q, mp);
22481 }
22482 
22483 /*
22484  * This routine is called by tcp_wput() to handle all TPI requests.
22485  */
22486 /* ARGSUSED */
22487 static void
22488 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22489 {
22490 	conn_t 	*connp = (conn_t *)arg;
22491 	tcp_t	*tcp = connp->conn_tcp;
22492 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22493 	uchar_t *rptr;
22494 	t_scalar_t type;
22495 	int len;
22496 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22497 
22498 	/*
22499 	 * Try and ASSERT the minimum possible references on the
22500 	 * conn early enough. Since we are executing on write side,
22501 	 * the connection is obviously not detached and that means
22502 	 * there is a ref each for TCP and IP. Since we are behind
22503 	 * the squeue, the minimum references needed are 3. If the
22504 	 * conn is in classifier hash list, there should be an
22505 	 * extra ref for that (we check both the possibilities).
22506 	 */
22507 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22508 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22509 
22510 	rptr = mp->b_rptr;
22511 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22512 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22513 		type = ((union T_primitives *)rptr)->type;
22514 		if (type == T_EXDATA_REQ) {
22515 			uint32_t msize = msgdsize(mp->b_cont);
22516 
22517 			len = msize - 1;
22518 			if (len < 0) {
22519 				freemsg(mp);
22520 				return;
22521 			}
22522 			/*
22523 			 * Try to force urgent data out on the wire.
22524 			 * Even if we have unsent data this will
22525 			 * at least send the urgent flag.
22526 			 * XXX does not handle more flag correctly.
22527 			 */
22528 			len += tcp->tcp_unsent;
22529 			len += tcp->tcp_snxt;
22530 			tcp->tcp_urg = len;
22531 			tcp->tcp_valid_bits |= TCP_URG_VALID;
22532 
22533 			/* Bypass tcp protocol for fused tcp loopback */
22534 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
22535 				return;
22536 		} else if (type != T_DATA_REQ) {
22537 			goto non_urgent_data;
22538 		}
22539 		/* TODO: options, flags, ... from user */
22540 		/* Set length to zero for reclamation below */
22541 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22542 		freeb(mp);
22543 		return;
22544 	} else {
22545 		if (tcp->tcp_debug) {
22546 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22547 			    "tcp_wput_proto, dropping one...");
22548 		}
22549 		freemsg(mp);
22550 		return;
22551 	}
22552 
22553 non_urgent_data:
22554 
22555 	switch ((int)tprim->type) {
22556 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22557 		/*
22558 		 * save the kssl_ent_t from the next block, and convert this
22559 		 * back to a normal bind_req.
22560 		 */
22561 		if (mp->b_cont != NULL) {
22562 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22563 
22564 			if (tcp->tcp_kssl_ent != NULL) {
22565 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22566 				    KSSL_NO_PROXY);
22567 				tcp->tcp_kssl_ent = NULL;
22568 			}
22569 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22570 			    sizeof (kssl_ent_t));
22571 			kssl_hold_ent(tcp->tcp_kssl_ent);
22572 			freemsg(mp->b_cont);
22573 			mp->b_cont = NULL;
22574 		}
22575 		tprim->type = T_BIND_REQ;
22576 
22577 	/* FALLTHROUGH */
22578 	case O_T_BIND_REQ:	/* bind request */
22579 	case T_BIND_REQ:	/* new semantics bind request */
22580 		tcp_bind(tcp, mp);
22581 		break;
22582 	case T_UNBIND_REQ:	/* unbind request */
22583 		tcp_unbind(tcp, mp);
22584 		break;
22585 	case O_T_CONN_RES:	/* old connection response XXX */
22586 	case T_CONN_RES:	/* connection response */
22587 		tcp_accept(tcp, mp);
22588 		break;
22589 	case T_CONN_REQ:	/* connection request */
22590 		tcp_connect(tcp, mp);
22591 		break;
22592 	case T_DISCON_REQ:	/* disconnect request */
22593 		tcp_disconnect(tcp, mp);
22594 		break;
22595 	case T_CAPABILITY_REQ:
22596 		tcp_capability_req(tcp, mp);	/* capability request */
22597 		break;
22598 	case T_INFO_REQ:	/* information request */
22599 		tcp_info_req(tcp, mp);
22600 		break;
22601 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22602 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22603 		    &tcp_opt_obj, B_TRUE);
22604 		break;
22605 	case T_OPTMGMT_REQ:
22606 		/*
22607 		 * Note:  no support for snmpcom_req() through new
22608 		 * T_OPTMGMT_REQ. See comments in ip.c
22609 		 */
22610 		/* Only IP is allowed to return meaningful value */
22611 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22612 		    B_TRUE);
22613 		break;
22614 
22615 	case T_UNITDATA_REQ:	/* unitdata request */
22616 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22617 		break;
22618 	case T_ORDREL_REQ:	/* orderly release req */
22619 		freemsg(mp);
22620 
22621 		if (tcp->tcp_fused)
22622 			tcp_unfuse(tcp);
22623 
22624 		if (tcp_xmit_end(tcp) != 0) {
22625 			/*
22626 			 * We were crossing FINs and got a reset from
22627 			 * the other side. Just ignore it.
22628 			 */
22629 			if (tcp->tcp_debug) {
22630 				(void) strlog(TCP_MOD_ID, 0, 1,
22631 				    SL_ERROR|SL_TRACE,
22632 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22633 				    "state %s",
22634 				    tcp_display(tcp, NULL,
22635 				    DISP_ADDR_AND_PORT));
22636 			}
22637 		}
22638 		break;
22639 	case T_ADDR_REQ:
22640 		tcp_addr_req(tcp, mp);
22641 		break;
22642 	default:
22643 		if (tcp->tcp_debug) {
22644 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22645 			    "tcp_wput_proto, bogus TPI msg, type %d",
22646 			    tprim->type);
22647 		}
22648 		/*
22649 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22650 		 * to recover.
22651 		 */
22652 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22653 		break;
22654 	}
22655 }
22656 
22657 /*
22658  * The TCP write service routine should never be called...
22659  */
22660 /* ARGSUSED */
22661 static void
22662 tcp_wsrv(queue_t *q)
22663 {
22664 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22665 
22666 	TCP_STAT(tcps, tcp_wsrv_called);
22667 }
22668 
22669 /* Non overlapping byte exchanger */
22670 static void
22671 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22672 {
22673 	uchar_t	uch;
22674 
22675 	while (len-- > 0) {
22676 		uch = a[len];
22677 		a[len] = b[len];
22678 		b[len] = uch;
22679 	}
22680 }
22681 
22682 /*
22683  * Send out a control packet on the tcp connection specified.  This routine
22684  * is typically called where we need a simple ACK or RST generated.
22685  */
22686 static void
22687 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22688 {
22689 	uchar_t		*rptr;
22690 	tcph_t		*tcph;
22691 	ipha_t		*ipha = NULL;
22692 	ip6_t		*ip6h = NULL;
22693 	uint32_t	sum;
22694 	int		tcp_hdr_len;
22695 	int		tcp_ip_hdr_len;
22696 	mblk_t		*mp;
22697 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22698 
22699 	/*
22700 	 * Save sum for use in source route later.
22701 	 */
22702 	ASSERT(tcp != NULL);
22703 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22704 	tcp_hdr_len = tcp->tcp_hdr_len;
22705 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22706 
22707 	/* If a text string is passed in with the request, pass it to strlog. */
22708 	if (str != NULL && tcp->tcp_debug) {
22709 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22710 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22711 		    str, seq, ack, ctl);
22712 	}
22713 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22714 	    BPRI_MED);
22715 	if (mp == NULL) {
22716 		return;
22717 	}
22718 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22719 	mp->b_rptr = rptr;
22720 	mp->b_wptr = &rptr[tcp_hdr_len];
22721 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22722 
22723 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22724 		ipha = (ipha_t *)rptr;
22725 		ipha->ipha_length = htons(tcp_hdr_len);
22726 	} else {
22727 		ip6h = (ip6_t *)rptr;
22728 		ASSERT(tcp != NULL);
22729 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22730 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22731 	}
22732 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22733 	tcph->th_flags[0] = (uint8_t)ctl;
22734 	if (ctl & TH_RST) {
22735 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22736 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22737 		/*
22738 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22739 		 */
22740 		if (tcp->tcp_snd_ts_ok &&
22741 		    tcp->tcp_state > TCPS_SYN_SENT) {
22742 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22743 			*(mp->b_wptr) = TCPOPT_EOL;
22744 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22745 				ipha->ipha_length = htons(tcp_hdr_len -
22746 				    TCPOPT_REAL_TS_LEN);
22747 			} else {
22748 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22749 				    TCPOPT_REAL_TS_LEN);
22750 			}
22751 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22752 			sum -= TCPOPT_REAL_TS_LEN;
22753 		}
22754 	}
22755 	if (ctl & TH_ACK) {
22756 		if (tcp->tcp_snd_ts_ok) {
22757 			U32_TO_BE32(lbolt,
22758 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22759 			U32_TO_BE32(tcp->tcp_ts_recent,
22760 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22761 		}
22762 
22763 		/* Update the latest receive window size in TCP header. */
22764 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22765 		    tcph->th_win);
22766 		tcp->tcp_rack = ack;
22767 		tcp->tcp_rack_cnt = 0;
22768 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22769 	}
22770 	BUMP_LOCAL(tcp->tcp_obsegs);
22771 	U32_TO_BE32(seq, tcph->th_seq);
22772 	U32_TO_BE32(ack, tcph->th_ack);
22773 	/*
22774 	 * Include the adjustment for a source route if any.
22775 	 */
22776 	sum = (sum >> 16) + (sum & 0xFFFF);
22777 	U16_TO_BE16(sum, tcph->th_sum);
22778 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22779 }
22780 
22781 /*
22782  * If this routine returns B_TRUE, TCP can generate a RST in response
22783  * to a segment.  If it returns B_FALSE, TCP should not respond.
22784  */
22785 static boolean_t
22786 tcp_send_rst_chk(tcp_stack_t *tcps)
22787 {
22788 	clock_t	now;
22789 
22790 	/*
22791 	 * TCP needs to protect itself from generating too many RSTs.
22792 	 * This can be a DoS attack by sending us random segments
22793 	 * soliciting RSTs.
22794 	 *
22795 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22796 	 * in each 1 second interval.  In this way, TCP still generate
22797 	 * RSTs in normal cases but when under attack, the impact is
22798 	 * limited.
22799 	 */
22800 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22801 		now = lbolt;
22802 		/* lbolt can wrap around. */
22803 		if ((tcps->tcps_last_rst_intrvl > now) ||
22804 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22805 		    1*SECONDS)) {
22806 			tcps->tcps_last_rst_intrvl = now;
22807 			tcps->tcps_rst_cnt = 1;
22808 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22809 			return (B_FALSE);
22810 		}
22811 	}
22812 	return (B_TRUE);
22813 }
22814 
22815 /*
22816  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22817  */
22818 static void
22819 tcp_ip_ire_mark_advice(tcp_t *tcp)
22820 {
22821 	mblk_t *mp;
22822 	ipic_t *ipic;
22823 
22824 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22825 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22826 		    &ipic);
22827 	} else {
22828 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22829 		    &ipic);
22830 	}
22831 	if (mp == NULL)
22832 		return;
22833 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22834 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22835 }
22836 
22837 /*
22838  * Return an IP advice ioctl mblk and set ipic to be the pointer
22839  * to the advice structure.
22840  */
22841 static mblk_t *
22842 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22843 {
22844 	struct iocblk *ioc;
22845 	mblk_t *mp, *mp1;
22846 
22847 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22848 	if (mp == NULL)
22849 		return (NULL);
22850 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22851 	*ipic = (ipic_t *)mp->b_rptr;
22852 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22853 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22854 
22855 	bcopy(addr, *ipic + 1, addr_len);
22856 
22857 	(*ipic)->ipic_addr_length = addr_len;
22858 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22859 
22860 	mp1 = mkiocb(IP_IOCTL);
22861 	if (mp1 == NULL) {
22862 		freemsg(mp);
22863 		return (NULL);
22864 	}
22865 	mp1->b_cont = mp;
22866 	ioc = (struct iocblk *)mp1->b_rptr;
22867 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22868 
22869 	return (mp1);
22870 }
22871 
22872 /*
22873  * Generate a reset based on an inbound packet, connp is set by caller
22874  * when RST is in response to an unexpected inbound packet for which
22875  * there is active tcp state in the system.
22876  *
22877  * IPSEC NOTE : Try to send the reply with the same protection as it came
22878  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22879  * the packet will go out at the same level of protection as it came in by
22880  * converting the IPSEC_IN to IPSEC_OUT.
22881  */
22882 static void
22883 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22884     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22885     tcp_stack_t *tcps, conn_t *connp)
22886 {
22887 	ipha_t		*ipha = NULL;
22888 	ip6_t		*ip6h = NULL;
22889 	ushort_t	len;
22890 	tcph_t		*tcph;
22891 	int		i;
22892 	mblk_t		*ipsec_mp;
22893 	boolean_t	mctl_present;
22894 	ipic_t		*ipic;
22895 	ipaddr_t	v4addr;
22896 	in6_addr_t	v6addr;
22897 	int		addr_len;
22898 	void		*addr;
22899 	queue_t		*q = tcps->tcps_g_q;
22900 	tcp_t		*tcp;
22901 	cred_t		*cr;
22902 	mblk_t		*nmp;
22903 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22904 
22905 	if (tcps->tcps_g_q == NULL) {
22906 		/*
22907 		 * For non-zero stackids the default queue isn't created
22908 		 * until the first open, thus there can be a need to send
22909 		 * a reset before then. But we can't do that, hence we just
22910 		 * drop the packet. Later during boot, when the default queue
22911 		 * has been setup, a retransmitted packet from the peer
22912 		 * will result in a reset.
22913 		 */
22914 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22915 		    GLOBAL_NETSTACKID);
22916 		freemsg(mp);
22917 		return;
22918 	}
22919 
22920 	if (connp != NULL)
22921 		tcp = connp->conn_tcp;
22922 	else
22923 		tcp = Q_TO_TCP(q);
22924 
22925 	if (!tcp_send_rst_chk(tcps)) {
22926 		tcps->tcps_rst_unsent++;
22927 		freemsg(mp);
22928 		return;
22929 	}
22930 
22931 	if (mp->b_datap->db_type == M_CTL) {
22932 		ipsec_mp = mp;
22933 		mp = mp->b_cont;
22934 		mctl_present = B_TRUE;
22935 	} else {
22936 		ipsec_mp = mp;
22937 		mctl_present = B_FALSE;
22938 	}
22939 
22940 	if (str && q && tcps->tcps_dbg) {
22941 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22942 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22943 		    "flags 0x%x",
22944 		    str, seq, ack, ctl);
22945 	}
22946 	if (mp->b_datap->db_ref != 1) {
22947 		mblk_t *mp1 = copyb(mp);
22948 		freemsg(mp);
22949 		mp = mp1;
22950 		if (!mp) {
22951 			if (mctl_present)
22952 				freeb(ipsec_mp);
22953 			return;
22954 		} else {
22955 			if (mctl_present) {
22956 				ipsec_mp->b_cont = mp;
22957 			} else {
22958 				ipsec_mp = mp;
22959 			}
22960 		}
22961 	} else if (mp->b_cont) {
22962 		freemsg(mp->b_cont);
22963 		mp->b_cont = NULL;
22964 	}
22965 	/*
22966 	 * We skip reversing source route here.
22967 	 * (for now we replace all IP options with EOL)
22968 	 */
22969 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22970 		ipha = (ipha_t *)mp->b_rptr;
22971 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22972 			mp->b_rptr[i] = IPOPT_EOL;
22973 		/*
22974 		 * Make sure that src address isn't flagrantly invalid.
22975 		 * Not all broadcast address checking for the src address
22976 		 * is possible, since we don't know the netmask of the src
22977 		 * addr.  No check for destination address is done, since
22978 		 * IP will not pass up a packet with a broadcast dest
22979 		 * address to TCP.  Similar checks are done below for IPv6.
22980 		 */
22981 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22982 		    CLASSD(ipha->ipha_src)) {
22983 			freemsg(ipsec_mp);
22984 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22985 			return;
22986 		}
22987 	} else {
22988 		ip6h = (ip6_t *)mp->b_rptr;
22989 
22990 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22991 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22992 			freemsg(ipsec_mp);
22993 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22994 			return;
22995 		}
22996 
22997 		/* Remove any extension headers assuming partial overlay */
22998 		if (ip_hdr_len > IPV6_HDR_LEN) {
22999 			uint8_t *to;
23000 
23001 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
23002 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
23003 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
23004 			ip_hdr_len = IPV6_HDR_LEN;
23005 			ip6h = (ip6_t *)mp->b_rptr;
23006 			ip6h->ip6_nxt = IPPROTO_TCP;
23007 		}
23008 	}
23009 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
23010 	if (tcph->th_flags[0] & TH_RST) {
23011 		freemsg(ipsec_mp);
23012 		return;
23013 	}
23014 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
23015 	len = ip_hdr_len + sizeof (tcph_t);
23016 	mp->b_wptr = &mp->b_rptr[len];
23017 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23018 		ipha->ipha_length = htons(len);
23019 		/* Swap addresses */
23020 		v4addr = ipha->ipha_src;
23021 		ipha->ipha_src = ipha->ipha_dst;
23022 		ipha->ipha_dst = v4addr;
23023 		ipha->ipha_ident = 0;
23024 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
23025 		addr_len = IP_ADDR_LEN;
23026 		addr = &v4addr;
23027 	} else {
23028 		/* No ip6i_t in this case */
23029 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
23030 		/* Swap addresses */
23031 		v6addr = ip6h->ip6_src;
23032 		ip6h->ip6_src = ip6h->ip6_dst;
23033 		ip6h->ip6_dst = v6addr;
23034 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
23035 		addr_len = IPV6_ADDR_LEN;
23036 		addr = &v6addr;
23037 	}
23038 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
23039 	U32_TO_BE32(ack, tcph->th_ack);
23040 	U32_TO_BE32(seq, tcph->th_seq);
23041 	U16_TO_BE16(0, tcph->th_win);
23042 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
23043 	tcph->th_flags[0] = (uint8_t)ctl;
23044 	if (ctl & TH_RST) {
23045 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
23046 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23047 	}
23048 
23049 	/* IP trusts us to set up labels when required. */
23050 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
23051 	    crgetlabel(cr) != NULL) {
23052 		int err;
23053 
23054 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
23055 			err = tsol_check_label(cr, &mp,
23056 			    tcp->tcp_connp->conn_mac_exempt,
23057 			    tcps->tcps_netstack->netstack_ip);
23058 		else
23059 			err = tsol_check_label_v6(cr, &mp,
23060 			    tcp->tcp_connp->conn_mac_exempt,
23061 			    tcps->tcps_netstack->netstack_ip);
23062 		if (mctl_present)
23063 			ipsec_mp->b_cont = mp;
23064 		else
23065 			ipsec_mp = mp;
23066 		if (err != 0) {
23067 			freemsg(ipsec_mp);
23068 			return;
23069 		}
23070 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23071 			ipha = (ipha_t *)mp->b_rptr;
23072 		} else {
23073 			ip6h = (ip6_t *)mp->b_rptr;
23074 		}
23075 	}
23076 
23077 	if (mctl_present) {
23078 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23079 
23080 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23081 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
23082 			return;
23083 		}
23084 	}
23085 	if (zoneid == ALL_ZONES)
23086 		zoneid = GLOBAL_ZONEID;
23087 
23088 	/* Add the zoneid so ip_output routes it properly */
23089 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
23090 		freemsg(ipsec_mp);
23091 		return;
23092 	}
23093 	ipsec_mp = nmp;
23094 
23095 	/*
23096 	 * NOTE:  one might consider tracing a TCP packet here, but
23097 	 * this function has no active TCP state and no tcp structure
23098 	 * that has a trace buffer.  If we traced here, we would have
23099 	 * to keep a local trace buffer in tcp_record_trace().
23100 	 *
23101 	 * TSol note: The mblk that contains the incoming packet was
23102 	 * reused by tcp_xmit_listener_reset, so it already contains
23103 	 * the right credentials and we don't need to call mblk_setcred.
23104 	 * Also the conn's cred is not right since it is associated
23105 	 * with tcps_g_q.
23106 	 */
23107 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
23108 
23109 	/*
23110 	 * Tell IP to mark the IRE used for this destination temporary.
23111 	 * This way, we can limit our exposure to DoS attack because IP
23112 	 * creates an IRE for each destination.  If there are too many,
23113 	 * the time to do any routing lookup will be extremely long.  And
23114 	 * the lookup can be in interrupt context.
23115 	 *
23116 	 * Note that in normal circumstances, this marking should not
23117 	 * affect anything.  It would be nice if only 1 message is
23118 	 * needed to inform IP that the IRE created for this RST should
23119 	 * not be added to the cache table.  But there is currently
23120 	 * not such communication mechanism between TCP and IP.  So
23121 	 * the best we can do now is to send the advice ioctl to IP
23122 	 * to mark the IRE temporary.
23123 	 */
23124 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
23125 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
23126 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23127 	}
23128 }
23129 
23130 /*
23131  * Initiate closedown sequence on an active connection.  (May be called as
23132  * writer.)  Return value zero for OK return, non-zero for error return.
23133  */
23134 static int
23135 tcp_xmit_end(tcp_t *tcp)
23136 {
23137 	ipic_t	*ipic;
23138 	mblk_t	*mp;
23139 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23140 
23141 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
23142 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
23143 		/*
23144 		 * Invalid state, only states TCPS_SYN_RCVD,
23145 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
23146 		 */
23147 		return (-1);
23148 	}
23149 
23150 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
23151 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
23152 	/*
23153 	 * If there is nothing more unsent, send the FIN now.
23154 	 * Otherwise, it will go out with the last segment.
23155 	 */
23156 	if (tcp->tcp_unsent == 0) {
23157 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
23158 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
23159 
23160 		if (mp) {
23161 			tcp_send_data(tcp, tcp->tcp_wq, mp);
23162 		} else {
23163 			/*
23164 			 * Couldn't allocate msg.  Pretend we got it out.
23165 			 * Wait for rexmit timeout.
23166 			 */
23167 			tcp->tcp_snxt = tcp->tcp_fss + 1;
23168 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23169 		}
23170 
23171 		/*
23172 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23173 		 * changed.
23174 		 */
23175 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23176 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23177 		}
23178 	} else {
23179 		/*
23180 		 * If tcp->tcp_cork is set, then the data will not get sent,
23181 		 * so we have to check that and unset it first.
23182 		 */
23183 		if (tcp->tcp_cork)
23184 			tcp->tcp_cork = B_FALSE;
23185 		tcp_wput_data(tcp, NULL, B_FALSE);
23186 	}
23187 
23188 	/*
23189 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23190 	 * is 0, don't update the cache.
23191 	 */
23192 	if (tcps->tcps_rtt_updates == 0 ||
23193 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23194 		return (0);
23195 
23196 	/*
23197 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23198 	 * different from the destination.
23199 	 */
23200 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23201 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23202 			return (0);
23203 		}
23204 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23205 		    &ipic);
23206 	} else {
23207 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23208 		    &tcp->tcp_ip6h->ip6_dst))) {
23209 			return (0);
23210 		}
23211 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23212 		    &ipic);
23213 	}
23214 
23215 	/* Record route attributes in the IRE for use by future connections. */
23216 	if (mp == NULL)
23217 		return (0);
23218 
23219 	/*
23220 	 * We do not have a good algorithm to update ssthresh at this time.
23221 	 * So don't do any update.
23222 	 */
23223 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23224 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23225 
23226 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23227 	return (0);
23228 }
23229 
23230 /*
23231  * Generate a "no listener here" RST in response to an "unknown" segment.
23232  * connp is set by caller when RST is in response to an unexpected
23233  * inbound packet for which there is active tcp state in the system.
23234  * Note that we are reusing the incoming mp to construct the outgoing RST.
23235  */
23236 void
23237 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23238     tcp_stack_t *tcps, conn_t *connp)
23239 {
23240 	uchar_t		*rptr;
23241 	uint32_t	seg_len;
23242 	tcph_t		*tcph;
23243 	uint32_t	seg_seq;
23244 	uint32_t	seg_ack;
23245 	uint_t		flags;
23246 	mblk_t		*ipsec_mp;
23247 	ipha_t 		*ipha;
23248 	ip6_t 		*ip6h;
23249 	boolean_t	mctl_present = B_FALSE;
23250 	boolean_t	check = B_TRUE;
23251 	boolean_t	policy_present;
23252 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23253 
23254 	TCP_STAT(tcps, tcp_no_listener);
23255 
23256 	ipsec_mp = mp;
23257 
23258 	if (mp->b_datap->db_type == M_CTL) {
23259 		ipsec_in_t *ii;
23260 
23261 		mctl_present = B_TRUE;
23262 		mp = mp->b_cont;
23263 
23264 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23265 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23266 		if (ii->ipsec_in_dont_check) {
23267 			check = B_FALSE;
23268 			if (!ii->ipsec_in_secure) {
23269 				freeb(ipsec_mp);
23270 				mctl_present = B_FALSE;
23271 				ipsec_mp = mp;
23272 			}
23273 		}
23274 	}
23275 
23276 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23277 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23278 		ipha = (ipha_t *)mp->b_rptr;
23279 		ip6h = NULL;
23280 	} else {
23281 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23282 		ipha = NULL;
23283 		ip6h = (ip6_t *)mp->b_rptr;
23284 	}
23285 
23286 	if (check && policy_present) {
23287 		/*
23288 		 * The conn_t parameter is NULL because we already know
23289 		 * nobody's home.
23290 		 */
23291 		ipsec_mp = ipsec_check_global_policy(
23292 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23293 		    tcps->tcps_netstack);
23294 		if (ipsec_mp == NULL)
23295 			return;
23296 	}
23297 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23298 		DTRACE_PROBE2(
23299 		    tx__ip__log__error__nolistener__tcp,
23300 		    char *, "Could not reply with RST to mp(1)",
23301 		    mblk_t *, mp);
23302 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23303 		freemsg(ipsec_mp);
23304 		return;
23305 	}
23306 
23307 	rptr = mp->b_rptr;
23308 
23309 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23310 	seg_seq = BE32_TO_U32(tcph->th_seq);
23311 	seg_ack = BE32_TO_U32(tcph->th_ack);
23312 	flags = tcph->th_flags[0];
23313 
23314 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23315 	if (flags & TH_RST) {
23316 		freemsg(ipsec_mp);
23317 	} else if (flags & TH_ACK) {
23318 		tcp_xmit_early_reset("no tcp, reset",
23319 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23320 		    connp);
23321 	} else {
23322 		if (flags & TH_SYN) {
23323 			seg_len++;
23324 		} else {
23325 			/*
23326 			 * Here we violate the RFC.  Note that a normal
23327 			 * TCP will never send a segment without the ACK
23328 			 * flag, except for RST or SYN segment.  This
23329 			 * segment is neither.  Just drop it on the
23330 			 * floor.
23331 			 */
23332 			freemsg(ipsec_mp);
23333 			tcps->tcps_rst_unsent++;
23334 			return;
23335 		}
23336 
23337 		tcp_xmit_early_reset("no tcp, reset/ack",
23338 		    ipsec_mp, 0, seg_seq + seg_len,
23339 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23340 	}
23341 }
23342 
23343 /*
23344  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23345  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23346  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23347  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23348  * otherwise it will dup partial mblks.)
23349  * Otherwise, an appropriate ACK packet will be generated.  This
23350  * routine is not usually called to send new data for the first time.  It
23351  * is mostly called out of the timer for retransmits, and to generate ACKs.
23352  *
23353  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23354  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23355  * of the original mblk chain will be returned in *offset and *end_mp.
23356  */
23357 mblk_t *
23358 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23359     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23360     boolean_t rexmit)
23361 {
23362 	int	data_length;
23363 	int32_t	off = 0;
23364 	uint_t	flags;
23365 	mblk_t	*mp1;
23366 	mblk_t	*mp2;
23367 	uchar_t	*rptr;
23368 	tcph_t	*tcph;
23369 	int32_t	num_sack_blk = 0;
23370 	int32_t	sack_opt_len = 0;
23371 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23372 
23373 	/* Allocate for our maximum TCP header + link-level */
23374 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23375 	    tcps->tcps_wroff_xtra, BPRI_MED);
23376 	if (!mp1)
23377 		return (NULL);
23378 	data_length = 0;
23379 
23380 	/*
23381 	 * Note that tcp_mss has been adjusted to take into account the
23382 	 * timestamp option if applicable.  Because SACK options do not
23383 	 * appear in every TCP segments and they are of variable lengths,
23384 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23385 	 * the actual segment length when we need to send a segment which
23386 	 * includes SACK options.
23387 	 */
23388 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23389 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23390 		    tcp->tcp_num_sack_blk);
23391 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23392 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23393 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23394 			max_to_send -= sack_opt_len;
23395 	}
23396 
23397 	if (offset != NULL) {
23398 		off = *offset;
23399 		/* We use offset as an indicator that end_mp is not NULL. */
23400 		*end_mp = NULL;
23401 	}
23402 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23403 		/* This could be faster with cooperation from downstream */
23404 		if (mp2 != mp1 && !sendall &&
23405 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23406 		    max_to_send)
23407 			/*
23408 			 * Don't send the next mblk since the whole mblk
23409 			 * does not fit.
23410 			 */
23411 			break;
23412 		mp2->b_cont = dupb(mp);
23413 		mp2 = mp2->b_cont;
23414 		if (!mp2) {
23415 			freemsg(mp1);
23416 			return (NULL);
23417 		}
23418 		mp2->b_rptr += off;
23419 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23420 		    (uintptr_t)INT_MAX);
23421 
23422 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23423 		if (data_length > max_to_send) {
23424 			mp2->b_wptr -= data_length - max_to_send;
23425 			data_length = max_to_send;
23426 			off = mp2->b_wptr - mp->b_rptr;
23427 			break;
23428 		} else {
23429 			off = 0;
23430 		}
23431 	}
23432 	if (offset != NULL) {
23433 		*offset = off;
23434 		*end_mp = mp;
23435 	}
23436 	if (seg_len != NULL) {
23437 		*seg_len = data_length;
23438 	}
23439 
23440 	/* Update the latest receive window size in TCP header. */
23441 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23442 	    tcp->tcp_tcph->th_win);
23443 
23444 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23445 	mp1->b_rptr = rptr;
23446 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23447 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23448 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23449 	U32_TO_ABE32(seq, tcph->th_seq);
23450 
23451 	/*
23452 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23453 	 * that this function was called from tcp_wput_data. Thus, when called
23454 	 * to retransmit data the setting of the PUSH bit may appear some
23455 	 * what random in that it might get set when it should not. This
23456 	 * should not pose any performance issues.
23457 	 */
23458 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23459 	    tcp->tcp_unsent == data_length)) {
23460 		flags = TH_ACK | TH_PUSH;
23461 	} else {
23462 		flags = TH_ACK;
23463 	}
23464 
23465 	if (tcp->tcp_ecn_ok) {
23466 		if (tcp->tcp_ecn_echo_on)
23467 			flags |= TH_ECE;
23468 
23469 		/*
23470 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23471 		 * There is no TCP flow control for non-data segments, and
23472 		 * only data segment is transmitted reliably.
23473 		 */
23474 		if (data_length > 0 && !rexmit) {
23475 			SET_ECT(tcp, rptr);
23476 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23477 				flags |= TH_CWR;
23478 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23479 			}
23480 		}
23481 	}
23482 
23483 	if (tcp->tcp_valid_bits) {
23484 		uint32_t u1;
23485 
23486 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23487 		    seq == tcp->tcp_iss) {
23488 			uchar_t	*wptr;
23489 
23490 			/*
23491 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23492 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23493 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23494 			 * our SYN is not ack'ed but the app closes this
23495 			 * TCP connection.
23496 			 */
23497 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23498 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23499 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23500 
23501 			/*
23502 			 * Tack on the MSS option.  It is always needed
23503 			 * for both active and passive open.
23504 			 *
23505 			 * MSS option value should be interface MTU - MIN
23506 			 * TCP/IP header according to RFC 793 as it means
23507 			 * the maximum segment size TCP can receive.  But
23508 			 * to get around some broken middle boxes/end hosts
23509 			 * out there, we allow the option value to be the
23510 			 * same as the MSS option size on the peer side.
23511 			 * In this way, the other side will not send
23512 			 * anything larger than they can receive.
23513 			 *
23514 			 * Note that for SYN_SENT state, the ndd param
23515 			 * tcp_use_smss_as_mss_opt has no effect as we
23516 			 * don't know the peer's MSS option value. So
23517 			 * the only case we need to take care of is in
23518 			 * SYN_RCVD state, which is done later.
23519 			 */
23520 			wptr = mp1->b_wptr;
23521 			wptr[0] = TCPOPT_MAXSEG;
23522 			wptr[1] = TCPOPT_MAXSEG_LEN;
23523 			wptr += 2;
23524 			u1 = tcp->tcp_if_mtu -
23525 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23526 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23527 			    TCP_MIN_HEADER_LENGTH;
23528 			U16_TO_BE16(u1, wptr);
23529 			mp1->b_wptr = wptr + 2;
23530 			/* Update the offset to cover the additional word */
23531 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23532 
23533 			/*
23534 			 * Note that the following way of filling in
23535 			 * TCP options are not optimal.  Some NOPs can
23536 			 * be saved.  But there is no need at this time
23537 			 * to optimize it.  When it is needed, we will
23538 			 * do it.
23539 			 */
23540 			switch (tcp->tcp_state) {
23541 			case TCPS_SYN_SENT:
23542 				flags = TH_SYN;
23543 
23544 				if (tcp->tcp_snd_ts_ok) {
23545 					uint32_t llbolt = (uint32_t)lbolt;
23546 
23547 					wptr = mp1->b_wptr;
23548 					wptr[0] = TCPOPT_NOP;
23549 					wptr[1] = TCPOPT_NOP;
23550 					wptr[2] = TCPOPT_TSTAMP;
23551 					wptr[3] = TCPOPT_TSTAMP_LEN;
23552 					wptr += 4;
23553 					U32_TO_BE32(llbolt, wptr);
23554 					wptr += 4;
23555 					ASSERT(tcp->tcp_ts_recent == 0);
23556 					U32_TO_BE32(0L, wptr);
23557 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23558 					tcph->th_offset_and_rsrvd[0] +=
23559 					    (3 << 4);
23560 				}
23561 
23562 				/*
23563 				 * Set up all the bits to tell other side
23564 				 * we are ECN capable.
23565 				 */
23566 				if (tcp->tcp_ecn_ok) {
23567 					flags |= (TH_ECE | TH_CWR);
23568 				}
23569 				break;
23570 			case TCPS_SYN_RCVD:
23571 				flags |= TH_SYN;
23572 
23573 				/*
23574 				 * Reset the MSS option value to be SMSS
23575 				 * We should probably add back the bytes
23576 				 * for timestamp option and IPsec.  We
23577 				 * don't do that as this is a workaround
23578 				 * for broken middle boxes/end hosts, it
23579 				 * is better for us to be more cautious.
23580 				 * They may not take these things into
23581 				 * account in their SMSS calculation.  Thus
23582 				 * the peer's calculated SMSS may be smaller
23583 				 * than what it can be.  This should be OK.
23584 				 */
23585 				if (tcps->tcps_use_smss_as_mss_opt) {
23586 					u1 = tcp->tcp_mss;
23587 					U16_TO_BE16(u1, wptr);
23588 				}
23589 
23590 				/*
23591 				 * If the other side is ECN capable, reply
23592 				 * that we are also ECN capable.
23593 				 */
23594 				if (tcp->tcp_ecn_ok)
23595 					flags |= TH_ECE;
23596 				break;
23597 			default:
23598 				/*
23599 				 * The above ASSERT() makes sure that this
23600 				 * must be FIN-WAIT-1 state.  Our SYN has
23601 				 * not been ack'ed so retransmit it.
23602 				 */
23603 				flags |= TH_SYN;
23604 				break;
23605 			}
23606 
23607 			if (tcp->tcp_snd_ws_ok) {
23608 				wptr = mp1->b_wptr;
23609 				wptr[0] =  TCPOPT_NOP;
23610 				wptr[1] =  TCPOPT_WSCALE;
23611 				wptr[2] =  TCPOPT_WS_LEN;
23612 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23613 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23614 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23615 			}
23616 
23617 			if (tcp->tcp_snd_sack_ok) {
23618 				wptr = mp1->b_wptr;
23619 				wptr[0] = TCPOPT_NOP;
23620 				wptr[1] = TCPOPT_NOP;
23621 				wptr[2] = TCPOPT_SACK_PERMITTED;
23622 				wptr[3] = TCPOPT_SACK_OK_LEN;
23623 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23624 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23625 			}
23626 
23627 			/* allocb() of adequate mblk assures space */
23628 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23629 			    (uintptr_t)INT_MAX);
23630 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23631 			/*
23632 			 * Get IP set to checksum on our behalf
23633 			 * Include the adjustment for a source route if any.
23634 			 */
23635 			u1 += tcp->tcp_sum;
23636 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23637 			U16_TO_BE16(u1, tcph->th_sum);
23638 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23639 		}
23640 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23641 		    (seq + data_length) == tcp->tcp_fss) {
23642 			if (!tcp->tcp_fin_acked) {
23643 				flags |= TH_FIN;
23644 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23645 			}
23646 			if (!tcp->tcp_fin_sent) {
23647 				tcp->tcp_fin_sent = B_TRUE;
23648 				switch (tcp->tcp_state) {
23649 				case TCPS_SYN_RCVD:
23650 				case TCPS_ESTABLISHED:
23651 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23652 					break;
23653 				case TCPS_CLOSE_WAIT:
23654 					tcp->tcp_state = TCPS_LAST_ACK;
23655 					break;
23656 				}
23657 				if (tcp->tcp_suna == tcp->tcp_snxt)
23658 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23659 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23660 			}
23661 		}
23662 		/*
23663 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23664 		 * is smaller than seq, u1 will become a very huge value.
23665 		 * So the comparison will fail.  Also note that tcp_urp
23666 		 * should be positive, see RFC 793 page 17.
23667 		 */
23668 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23669 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23670 		    u1 < (uint32_t)(64 * 1024)) {
23671 			flags |= TH_URG;
23672 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23673 			U32_TO_ABE16(u1, tcph->th_urp);
23674 		}
23675 	}
23676 	tcph->th_flags[0] = (uchar_t)flags;
23677 	tcp->tcp_rack = tcp->tcp_rnxt;
23678 	tcp->tcp_rack_cnt = 0;
23679 
23680 	if (tcp->tcp_snd_ts_ok) {
23681 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23682 			uint32_t llbolt = (uint32_t)lbolt;
23683 
23684 			U32_TO_BE32(llbolt,
23685 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23686 			U32_TO_BE32(tcp->tcp_ts_recent,
23687 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23688 		}
23689 	}
23690 
23691 	if (num_sack_blk > 0) {
23692 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23693 		sack_blk_t *tmp;
23694 		int32_t	i;
23695 
23696 		wptr[0] = TCPOPT_NOP;
23697 		wptr[1] = TCPOPT_NOP;
23698 		wptr[2] = TCPOPT_SACK;
23699 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23700 		    sizeof (sack_blk_t);
23701 		wptr += TCPOPT_REAL_SACK_LEN;
23702 
23703 		tmp = tcp->tcp_sack_list;
23704 		for (i = 0; i < num_sack_blk; i++) {
23705 			U32_TO_BE32(tmp[i].begin, wptr);
23706 			wptr += sizeof (tcp_seq);
23707 			U32_TO_BE32(tmp[i].end, wptr);
23708 			wptr += sizeof (tcp_seq);
23709 		}
23710 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23711 	}
23712 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23713 	data_length += (int)(mp1->b_wptr - rptr);
23714 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23715 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23716 	} else {
23717 		ip6_t *ip6 = (ip6_t *)(rptr +
23718 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23719 		    sizeof (ip6i_t) : 0));
23720 
23721 		ip6->ip6_plen = htons(data_length -
23722 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23723 	}
23724 
23725 	/*
23726 	 * Prime pump for IP
23727 	 * Include the adjustment for a source route if any.
23728 	 */
23729 	data_length -= tcp->tcp_ip_hdr_len;
23730 	data_length += tcp->tcp_sum;
23731 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23732 	U16_TO_ABE16(data_length, tcph->th_sum);
23733 	if (tcp->tcp_ip_forward_progress) {
23734 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23735 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23736 		tcp->tcp_ip_forward_progress = B_FALSE;
23737 	}
23738 	return (mp1);
23739 }
23740 
23741 /* This function handles the push timeout. */
23742 void
23743 tcp_push_timer(void *arg)
23744 {
23745 	conn_t	*connp = (conn_t *)arg;
23746 	tcp_t *tcp = connp->conn_tcp;
23747 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23748 	uint_t		flags;
23749 	sodirect_t	*sodp;
23750 
23751 	TCP_DBGSTAT(tcps, tcp_push_timer_cnt);
23752 
23753 	ASSERT(tcp->tcp_listener == NULL);
23754 
23755 	/*
23756 	 * We need to plug synchronous streams during our drain to prevent
23757 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23758 	 */
23759 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23760 	tcp->tcp_push_tid = 0;
23761 
23762 	SOD_PTR_ENTER(tcp, sodp);
23763 	if (sodp != NULL) {
23764 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23765 		/* sod_wakeup() does the mutex_exit() */
23766 	} else if (tcp->tcp_rcv_list != NULL) {
23767 		flags = tcp_rcv_drain(tcp->tcp_rq, tcp);
23768 	}
23769 	if (flags == TH_ACK_NEEDED)
23770 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23771 
23772 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23773 }
23774 
23775 /*
23776  * This function handles delayed ACK timeout.
23777  */
23778 static void
23779 tcp_ack_timer(void *arg)
23780 {
23781 	conn_t	*connp = (conn_t *)arg;
23782 	tcp_t *tcp = connp->conn_tcp;
23783 	mblk_t *mp;
23784 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23785 
23786 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23787 
23788 	tcp->tcp_ack_tid = 0;
23789 
23790 	if (tcp->tcp_fused)
23791 		return;
23792 
23793 	/*
23794 	 * Do not send ACK if there is no outstanding unack'ed data.
23795 	 */
23796 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23797 		return;
23798 	}
23799 
23800 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23801 		/*
23802 		 * Make sure we don't allow deferred ACKs to result in
23803 		 * timer-based ACKing.  If we have held off an ACK
23804 		 * when there was more than an mss here, and the timer
23805 		 * goes off, we have to worry about the possibility
23806 		 * that the sender isn't doing slow-start, or is out
23807 		 * of step with us for some other reason.  We fall
23808 		 * permanently back in the direction of
23809 		 * ACK-every-other-packet as suggested in RFC 1122.
23810 		 */
23811 		if (tcp->tcp_rack_abs_max > 2)
23812 			tcp->tcp_rack_abs_max--;
23813 		tcp->tcp_rack_cur_max = 2;
23814 	}
23815 	mp = tcp_ack_mp(tcp);
23816 
23817 	if (mp != NULL) {
23818 		BUMP_LOCAL(tcp->tcp_obsegs);
23819 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23820 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23821 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23822 	}
23823 }
23824 
23825 
23826 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23827 static mblk_t *
23828 tcp_ack_mp(tcp_t *tcp)
23829 {
23830 	uint32_t	seq_no;
23831 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23832 
23833 	/*
23834 	 * There are a few cases to be considered while setting the sequence no.
23835 	 * Essentially, we can come here while processing an unacceptable pkt
23836 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23837 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23838 	 * If we are here for a zero window probe, stick with suna. In all
23839 	 * other cases, we check if suna + swnd encompasses snxt and set
23840 	 * the sequence number to snxt, if so. If snxt falls outside the
23841 	 * window (the receiver probably shrunk its window), we will go with
23842 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23843 	 * receiver.
23844 	 */
23845 	if (tcp->tcp_zero_win_probe) {
23846 		seq_no = tcp->tcp_suna;
23847 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23848 		ASSERT(tcp->tcp_swnd == 0);
23849 		seq_no = tcp->tcp_snxt;
23850 	} else {
23851 		seq_no = SEQ_GT(tcp->tcp_snxt,
23852 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23853 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23854 	}
23855 
23856 	if (tcp->tcp_valid_bits) {
23857 		/*
23858 		 * For the complex case where we have to send some
23859 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23860 		 */
23861 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23862 		    NULL, B_FALSE));
23863 	} else {
23864 		/* Generate a simple ACK */
23865 		int	data_length;
23866 		uchar_t	*rptr;
23867 		tcph_t	*tcph;
23868 		mblk_t	*mp1;
23869 		int32_t	tcp_hdr_len;
23870 		int32_t	tcp_tcp_hdr_len;
23871 		int32_t	num_sack_blk = 0;
23872 		int32_t sack_opt_len;
23873 
23874 		/*
23875 		 * Allocate space for TCP + IP headers
23876 		 * and link-level header
23877 		 */
23878 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23879 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23880 			    tcp->tcp_num_sack_blk);
23881 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23882 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23883 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23884 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23885 		} else {
23886 			tcp_hdr_len = tcp->tcp_hdr_len;
23887 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23888 		}
23889 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23890 		if (!mp1)
23891 			return (NULL);
23892 
23893 		/* Update the latest receive window size in TCP header. */
23894 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23895 		    tcp->tcp_tcph->th_win);
23896 		/* copy in prototype TCP + IP header */
23897 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23898 		mp1->b_rptr = rptr;
23899 		mp1->b_wptr = rptr + tcp_hdr_len;
23900 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23901 
23902 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23903 
23904 		/* Set the TCP sequence number. */
23905 		U32_TO_ABE32(seq_no, tcph->th_seq);
23906 
23907 		/* Set up the TCP flag field. */
23908 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23909 		if (tcp->tcp_ecn_echo_on)
23910 			tcph->th_flags[0] |= TH_ECE;
23911 
23912 		tcp->tcp_rack = tcp->tcp_rnxt;
23913 		tcp->tcp_rack_cnt = 0;
23914 
23915 		/* fill in timestamp option if in use */
23916 		if (tcp->tcp_snd_ts_ok) {
23917 			uint32_t llbolt = (uint32_t)lbolt;
23918 
23919 			U32_TO_BE32(llbolt,
23920 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23921 			U32_TO_BE32(tcp->tcp_ts_recent,
23922 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23923 		}
23924 
23925 		/* Fill in SACK options */
23926 		if (num_sack_blk > 0) {
23927 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23928 			sack_blk_t *tmp;
23929 			int32_t	i;
23930 
23931 			wptr[0] = TCPOPT_NOP;
23932 			wptr[1] = TCPOPT_NOP;
23933 			wptr[2] = TCPOPT_SACK;
23934 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23935 			    sizeof (sack_blk_t);
23936 			wptr += TCPOPT_REAL_SACK_LEN;
23937 
23938 			tmp = tcp->tcp_sack_list;
23939 			for (i = 0; i < num_sack_blk; i++) {
23940 				U32_TO_BE32(tmp[i].begin, wptr);
23941 				wptr += sizeof (tcp_seq);
23942 				U32_TO_BE32(tmp[i].end, wptr);
23943 				wptr += sizeof (tcp_seq);
23944 			}
23945 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23946 			    << 4);
23947 		}
23948 
23949 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23950 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23951 		} else {
23952 			/* Check for ip6i_t header in sticky hdrs */
23953 			ip6_t *ip6 = (ip6_t *)(rptr +
23954 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23955 			    sizeof (ip6i_t) : 0));
23956 
23957 			ip6->ip6_plen = htons(tcp_hdr_len -
23958 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23959 		}
23960 
23961 		/*
23962 		 * Prime pump for checksum calculation in IP.  Include the
23963 		 * adjustment for a source route if any.
23964 		 */
23965 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23966 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23967 		U16_TO_ABE16(data_length, tcph->th_sum);
23968 
23969 		if (tcp->tcp_ip_forward_progress) {
23970 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23971 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23972 			tcp->tcp_ip_forward_progress = B_FALSE;
23973 		}
23974 		return (mp1);
23975 	}
23976 }
23977 
23978 /*
23979  * Hash list insertion routine for tcp_t structures.
23980  * Inserts entries with the ones bound to a specific IP address first
23981  * followed by those bound to INADDR_ANY.
23982  */
23983 static void
23984 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23985 {
23986 	tcp_t	**tcpp;
23987 	tcp_t	*tcpnext;
23988 
23989 	if (tcp->tcp_ptpbhn != NULL) {
23990 		ASSERT(!caller_holds_lock);
23991 		tcp_bind_hash_remove(tcp);
23992 	}
23993 	tcpp = &tbf->tf_tcp;
23994 	if (!caller_holds_lock) {
23995 		mutex_enter(&tbf->tf_lock);
23996 	} else {
23997 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23998 	}
23999 	tcpnext = tcpp[0];
24000 	if (tcpnext) {
24001 		/*
24002 		 * If the new tcp bound to the INADDR_ANY address
24003 		 * and the first one in the list is not bound to
24004 		 * INADDR_ANY we skip all entries until we find the
24005 		 * first one bound to INADDR_ANY.
24006 		 * This makes sure that applications binding to a
24007 		 * specific address get preference over those binding to
24008 		 * INADDR_ANY.
24009 		 */
24010 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
24011 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
24012 			while ((tcpnext = tcpp[0]) != NULL &&
24013 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
24014 				tcpp = &(tcpnext->tcp_bind_hash);
24015 			if (tcpnext)
24016 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24017 		} else
24018 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24019 	}
24020 	tcp->tcp_bind_hash = tcpnext;
24021 	tcp->tcp_ptpbhn = tcpp;
24022 	tcpp[0] = tcp;
24023 	if (!caller_holds_lock)
24024 		mutex_exit(&tbf->tf_lock);
24025 }
24026 
24027 /*
24028  * Hash list removal routine for tcp_t structures.
24029  */
24030 static void
24031 tcp_bind_hash_remove(tcp_t *tcp)
24032 {
24033 	tcp_t	*tcpnext;
24034 	kmutex_t *lockp;
24035 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24036 
24037 	if (tcp->tcp_ptpbhn == NULL)
24038 		return;
24039 
24040 	/*
24041 	 * Extract the lock pointer in case there are concurrent
24042 	 * hash_remove's for this instance.
24043 	 */
24044 	ASSERT(tcp->tcp_lport != 0);
24045 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
24046 
24047 	ASSERT(lockp != NULL);
24048 	mutex_enter(lockp);
24049 	if (tcp->tcp_ptpbhn) {
24050 		tcpnext = tcp->tcp_bind_hash;
24051 		if (tcpnext) {
24052 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24053 			tcp->tcp_bind_hash = NULL;
24054 		}
24055 		*tcp->tcp_ptpbhn = tcpnext;
24056 		tcp->tcp_ptpbhn = NULL;
24057 	}
24058 	mutex_exit(lockp);
24059 }
24060 
24061 
24062 /*
24063  * Hash list lookup routine for tcp_t structures.
24064  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24065  */
24066 static tcp_t *
24067 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24068 {
24069 	tf_t	*tf;
24070 	tcp_t	*tcp;
24071 
24072 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24073 	mutex_enter(&tf->tf_lock);
24074 	for (tcp = tf->tf_tcp; tcp != NULL;
24075 	    tcp = tcp->tcp_acceptor_hash) {
24076 		if (tcp->tcp_acceptor_id == id) {
24077 			CONN_INC_REF(tcp->tcp_connp);
24078 			mutex_exit(&tf->tf_lock);
24079 			return (tcp);
24080 		}
24081 	}
24082 	mutex_exit(&tf->tf_lock);
24083 	return (NULL);
24084 }
24085 
24086 
24087 /*
24088  * Hash list insertion routine for tcp_t structures.
24089  */
24090 void
24091 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24092 {
24093 	tf_t	*tf;
24094 	tcp_t	**tcpp;
24095 	tcp_t	*tcpnext;
24096 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24097 
24098 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24099 
24100 	if (tcp->tcp_ptpahn != NULL)
24101 		tcp_acceptor_hash_remove(tcp);
24102 	tcpp = &tf->tf_tcp;
24103 	mutex_enter(&tf->tf_lock);
24104 	tcpnext = tcpp[0];
24105 	if (tcpnext)
24106 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24107 	tcp->tcp_acceptor_hash = tcpnext;
24108 	tcp->tcp_ptpahn = tcpp;
24109 	tcpp[0] = tcp;
24110 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24111 	mutex_exit(&tf->tf_lock);
24112 }
24113 
24114 /*
24115  * Hash list removal routine for tcp_t structures.
24116  */
24117 static void
24118 tcp_acceptor_hash_remove(tcp_t *tcp)
24119 {
24120 	tcp_t	*tcpnext;
24121 	kmutex_t *lockp;
24122 
24123 	/*
24124 	 * Extract the lock pointer in case there are concurrent
24125 	 * hash_remove's for this instance.
24126 	 */
24127 	lockp = tcp->tcp_acceptor_lockp;
24128 
24129 	if (tcp->tcp_ptpahn == NULL)
24130 		return;
24131 
24132 	ASSERT(lockp != NULL);
24133 	mutex_enter(lockp);
24134 	if (tcp->tcp_ptpahn) {
24135 		tcpnext = tcp->tcp_acceptor_hash;
24136 		if (tcpnext) {
24137 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24138 			tcp->tcp_acceptor_hash = NULL;
24139 		}
24140 		*tcp->tcp_ptpahn = tcpnext;
24141 		tcp->tcp_ptpahn = NULL;
24142 	}
24143 	mutex_exit(lockp);
24144 	tcp->tcp_acceptor_lockp = NULL;
24145 }
24146 
24147 /* Data for fast netmask macro used by tcp_hsp_lookup */
24148 
24149 static ipaddr_t netmasks[] = {
24150 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24151 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24152 };
24153 
24154 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24155 
24156 /*
24157  * XXX This routine should go away and instead we should use the metrics
24158  * associated with the routes to determine the default sndspace and rcvspace.
24159  */
24160 static tcp_hsp_t *
24161 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24162 {
24163 	tcp_hsp_t *hsp = NULL;
24164 
24165 	/* Quick check without acquiring the lock. */
24166 	if (tcps->tcps_hsp_hash == NULL)
24167 		return (NULL);
24168 
24169 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24170 
24171 	/* This routine finds the best-matching HSP for address addr. */
24172 
24173 	if (tcps->tcps_hsp_hash) {
24174 		int i;
24175 		ipaddr_t srchaddr;
24176 		tcp_hsp_t *hsp_net;
24177 
24178 		/* We do three passes: host, network, and subnet. */
24179 
24180 		srchaddr = addr;
24181 
24182 		for (i = 1; i <= 3; i++) {
24183 			/* Look for exact match on srchaddr */
24184 
24185 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24186 			while (hsp) {
24187 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24188 				    hsp->tcp_hsp_addr == srchaddr)
24189 					break;
24190 				hsp = hsp->tcp_hsp_next;
24191 			}
24192 			ASSERT(hsp == NULL ||
24193 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24194 
24195 			/*
24196 			 * If this is the first pass:
24197 			 *   If we found a match, great, return it.
24198 			 *   If not, search for the network on the second pass.
24199 			 */
24200 
24201 			if (i == 1)
24202 				if (hsp)
24203 					break;
24204 				else
24205 				{
24206 					srchaddr = addr & netmask(addr);
24207 					continue;
24208 				}
24209 
24210 			/*
24211 			 * If this is the second pass:
24212 			 *   If we found a match, but there's a subnet mask,
24213 			 *    save the match but try again using the subnet
24214 			 *    mask on the third pass.
24215 			 *   Otherwise, return whatever we found.
24216 			 */
24217 
24218 			if (i == 2) {
24219 				if (hsp && hsp->tcp_hsp_subnet) {
24220 					hsp_net = hsp;
24221 					srchaddr = addr & hsp->tcp_hsp_subnet;
24222 					continue;
24223 				} else {
24224 					break;
24225 				}
24226 			}
24227 
24228 			/*
24229 			 * This must be the third pass.  If we didn't find
24230 			 * anything, return the saved network HSP instead.
24231 			 */
24232 
24233 			if (!hsp)
24234 				hsp = hsp_net;
24235 		}
24236 	}
24237 
24238 	rw_exit(&tcps->tcps_hsp_lock);
24239 	return (hsp);
24240 }
24241 
24242 /*
24243  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24244  * match lookup.
24245  */
24246 static tcp_hsp_t *
24247 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24248 {
24249 	tcp_hsp_t *hsp = NULL;
24250 
24251 	/* Quick check without acquiring the lock. */
24252 	if (tcps->tcps_hsp_hash == NULL)
24253 		return (NULL);
24254 
24255 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24256 
24257 	/* This routine finds the best-matching HSP for address addr. */
24258 
24259 	if (tcps->tcps_hsp_hash) {
24260 		int i;
24261 		in6_addr_t v6srchaddr;
24262 		tcp_hsp_t *hsp_net;
24263 
24264 		/* We do three passes: host, network, and subnet. */
24265 
24266 		v6srchaddr = *v6addr;
24267 
24268 		for (i = 1; i <= 3; i++) {
24269 			/* Look for exact match on srchaddr */
24270 
24271 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24272 			    V4_PART_OF_V6(v6srchaddr))];
24273 			while (hsp) {
24274 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24275 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24276 				    &v6srchaddr))
24277 					break;
24278 				hsp = hsp->tcp_hsp_next;
24279 			}
24280 
24281 			/*
24282 			 * If this is the first pass:
24283 			 *   If we found a match, great, return it.
24284 			 *   If not, search for the network on the second pass.
24285 			 */
24286 
24287 			if (i == 1)
24288 				if (hsp)
24289 					break;
24290 				else {
24291 					/* Assume a 64 bit mask */
24292 					v6srchaddr.s6_addr32[0] =
24293 					    v6addr->s6_addr32[0];
24294 					v6srchaddr.s6_addr32[1] =
24295 					    v6addr->s6_addr32[1];
24296 					v6srchaddr.s6_addr32[2] = 0;
24297 					v6srchaddr.s6_addr32[3] = 0;
24298 					continue;
24299 				}
24300 
24301 			/*
24302 			 * If this is the second pass:
24303 			 *   If we found a match, but there's a subnet mask,
24304 			 *    save the match but try again using the subnet
24305 			 *    mask on the third pass.
24306 			 *   Otherwise, return whatever we found.
24307 			 */
24308 
24309 			if (i == 2) {
24310 				ASSERT(hsp == NULL ||
24311 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24312 				if (hsp &&
24313 				    !IN6_IS_ADDR_UNSPECIFIED(
24314 				    &hsp->tcp_hsp_subnet_v6)) {
24315 					hsp_net = hsp;
24316 					V6_MASK_COPY(*v6addr,
24317 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24318 					continue;
24319 				} else {
24320 					break;
24321 				}
24322 			}
24323 
24324 			/*
24325 			 * This must be the third pass.  If we didn't find
24326 			 * anything, return the saved network HSP instead.
24327 			 */
24328 
24329 			if (!hsp)
24330 				hsp = hsp_net;
24331 		}
24332 	}
24333 
24334 	rw_exit(&tcps->tcps_hsp_lock);
24335 	return (hsp);
24336 }
24337 
24338 /*
24339  * Type three generator adapted from the random() function in 4.4 BSD:
24340  */
24341 
24342 /*
24343  * Copyright (c) 1983, 1993
24344  *	The Regents of the University of California.  All rights reserved.
24345  *
24346  * Redistribution and use in source and binary forms, with or without
24347  * modification, are permitted provided that the following conditions
24348  * are met:
24349  * 1. Redistributions of source code must retain the above copyright
24350  *    notice, this list of conditions and the following disclaimer.
24351  * 2. Redistributions in binary form must reproduce the above copyright
24352  *    notice, this list of conditions and the following disclaimer in the
24353  *    documentation and/or other materials provided with the distribution.
24354  * 3. All advertising materials mentioning features or use of this software
24355  *    must display the following acknowledgement:
24356  *	This product includes software developed by the University of
24357  *	California, Berkeley and its contributors.
24358  * 4. Neither the name of the University nor the names of its contributors
24359  *    may be used to endorse or promote products derived from this software
24360  *    without specific prior written permission.
24361  *
24362  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24363  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24364  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24365  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24366  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24367  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24368  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24369  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24370  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24371  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24372  * SUCH DAMAGE.
24373  */
24374 
24375 /* Type 3 -- x**31 + x**3 + 1 */
24376 #define	DEG_3		31
24377 #define	SEP_3		3
24378 
24379 
24380 /* Protected by tcp_random_lock */
24381 static int tcp_randtbl[DEG_3 + 1];
24382 
24383 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24384 static int *tcp_random_rptr = &tcp_randtbl[1];
24385 
24386 static int *tcp_random_state = &tcp_randtbl[1];
24387 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24388 
24389 kmutex_t tcp_random_lock;
24390 
24391 void
24392 tcp_random_init(void)
24393 {
24394 	int i;
24395 	hrtime_t hrt;
24396 	time_t wallclock;
24397 	uint64_t result;
24398 
24399 	/*
24400 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24401 	 * a longlong, which may contain resolution down to nanoseconds.
24402 	 * The current time will either be a 32-bit or a 64-bit quantity.
24403 	 * XOR the two together in a 64-bit result variable.
24404 	 * Convert the result to a 32-bit value by multiplying the high-order
24405 	 * 32-bits by the low-order 32-bits.
24406 	 */
24407 
24408 	hrt = gethrtime();
24409 	(void) drv_getparm(TIME, &wallclock);
24410 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24411 	mutex_enter(&tcp_random_lock);
24412 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24413 	    (result & 0xffffffff);
24414 
24415 	for (i = 1; i < DEG_3; i++)
24416 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24417 		    + 12345;
24418 	tcp_random_fptr = &tcp_random_state[SEP_3];
24419 	tcp_random_rptr = &tcp_random_state[0];
24420 	mutex_exit(&tcp_random_lock);
24421 	for (i = 0; i < 10 * DEG_3; i++)
24422 		(void) tcp_random();
24423 }
24424 
24425 /*
24426  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24427  * This range is selected to be approximately centered on TCP_ISS / 2,
24428  * and easy to compute. We get this value by generating a 32-bit random
24429  * number, selecting out the high-order 17 bits, and then adding one so
24430  * that we never return zero.
24431  */
24432 int
24433 tcp_random(void)
24434 {
24435 	int i;
24436 
24437 	mutex_enter(&tcp_random_lock);
24438 	*tcp_random_fptr += *tcp_random_rptr;
24439 
24440 	/*
24441 	 * The high-order bits are more random than the low-order bits,
24442 	 * so we select out the high-order 17 bits and add one so that
24443 	 * we never return zero.
24444 	 */
24445 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24446 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24447 		tcp_random_fptr = tcp_random_state;
24448 		++tcp_random_rptr;
24449 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24450 		tcp_random_rptr = tcp_random_state;
24451 
24452 	mutex_exit(&tcp_random_lock);
24453 	return (i);
24454 }
24455 
24456 /*
24457  * XXX This will go away when TPI is extended to send
24458  * info reqs to sockfs/timod .....
24459  * Given a queue, set the max packet size for the write
24460  * side of the queue below stream head.  This value is
24461  * cached on the stream head.
24462  * Returns 1 on success, 0 otherwise.
24463  */
24464 static int
24465 setmaxps(queue_t *q, int maxpsz)
24466 {
24467 	struct stdata	*stp;
24468 	queue_t		*wq;
24469 	stp = STREAM(q);
24470 
24471 	/*
24472 	 * At this point change of a queue parameter is not allowed
24473 	 * when a multiplexor is sitting on top.
24474 	 */
24475 	if (stp->sd_flag & STPLEX)
24476 		return (0);
24477 
24478 	claimstr(stp->sd_wrq);
24479 	wq = stp->sd_wrq->q_next;
24480 	ASSERT(wq != NULL);
24481 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
24482 	releasestr(stp->sd_wrq);
24483 	return (1);
24484 }
24485 
24486 static int
24487 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24488     int *t_errorp, int *sys_errorp)
24489 {
24490 	int error;
24491 	int is_absreq_failure;
24492 	t_scalar_t *opt_lenp;
24493 	t_scalar_t opt_offset;
24494 	int prim_type;
24495 	struct T_conn_req *tcreqp;
24496 	struct T_conn_res *tcresp;
24497 	cred_t *cr;
24498 
24499 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24500 
24501 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24502 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24503 	    prim_type == T_CONN_RES);
24504 
24505 	switch (prim_type) {
24506 	case T_CONN_REQ:
24507 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24508 		opt_offset = tcreqp->OPT_offset;
24509 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24510 		break;
24511 	case O_T_CONN_RES:
24512 	case T_CONN_RES:
24513 		tcresp = (struct T_conn_res *)mp->b_rptr;
24514 		opt_offset = tcresp->OPT_offset;
24515 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24516 		break;
24517 	}
24518 
24519 	*t_errorp = 0;
24520 	*sys_errorp = 0;
24521 	*do_disconnectp = 0;
24522 
24523 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24524 	    opt_offset, cr, &tcp_opt_obj,
24525 	    NULL, &is_absreq_failure);
24526 
24527 	switch (error) {
24528 	case  0:		/* no error */
24529 		ASSERT(is_absreq_failure == 0);
24530 		return (0);
24531 	case ENOPROTOOPT:
24532 		*t_errorp = TBADOPT;
24533 		break;
24534 	case EACCES:
24535 		*t_errorp = TACCES;
24536 		break;
24537 	default:
24538 		*t_errorp = TSYSERR; *sys_errorp = error;
24539 		break;
24540 	}
24541 	if (is_absreq_failure != 0) {
24542 		/*
24543 		 * The connection request should get the local ack
24544 		 * T_OK_ACK and then a T_DISCON_IND.
24545 		 */
24546 		*do_disconnectp = 1;
24547 	}
24548 	return (-1);
24549 }
24550 
24551 /*
24552  * Split this function out so that if the secret changes, I'm okay.
24553  *
24554  * Initialize the tcp_iss_cookie and tcp_iss_key.
24555  */
24556 
24557 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24558 
24559 static void
24560 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24561 {
24562 	struct {
24563 		int32_t current_time;
24564 		uint32_t randnum;
24565 		uint16_t pad;
24566 		uint8_t ether[6];
24567 		uint8_t passwd[PASSWD_SIZE];
24568 	} tcp_iss_cookie;
24569 	time_t t;
24570 
24571 	/*
24572 	 * Start with the current absolute time.
24573 	 */
24574 	(void) drv_getparm(TIME, &t);
24575 	tcp_iss_cookie.current_time = t;
24576 
24577 	/*
24578 	 * XXX - Need a more random number per RFC 1750, not this crap.
24579 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24580 	 */
24581 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24582 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24583 
24584 	/*
24585 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24586 	 * as a good template.
24587 	 */
24588 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24589 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24590 
24591 	/*
24592 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24593 	 */
24594 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24595 
24596 	/*
24597 	 * See 4010593 if this section becomes a problem again,
24598 	 * but the local ethernet address is useful here.
24599 	 */
24600 	(void) localetheraddr(NULL,
24601 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24602 
24603 	/*
24604 	 * Hash 'em all together.  The MD5Final is called per-connection.
24605 	 */
24606 	mutex_enter(&tcps->tcps_iss_key_lock);
24607 	MD5Init(&tcps->tcps_iss_key);
24608 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24609 	    sizeof (tcp_iss_cookie));
24610 	mutex_exit(&tcps->tcps_iss_key_lock);
24611 }
24612 
24613 /*
24614  * Set the RFC 1948 pass phrase
24615  */
24616 /* ARGSUSED */
24617 static int
24618 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24619     cred_t *cr)
24620 {
24621 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24622 
24623 	/*
24624 	 * Basically, value contains a new pass phrase.  Pass it along!
24625 	 */
24626 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24627 	return (0);
24628 }
24629 
24630 /* ARGSUSED */
24631 static int
24632 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24633 {
24634 	bzero(buf, sizeof (tcp_sack_info_t));
24635 	return (0);
24636 }
24637 
24638 /* ARGSUSED */
24639 static int
24640 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24641 {
24642 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24643 	return (0);
24644 }
24645 
24646 /*
24647  * Make sure we wait until the default queue is setup, yet allow
24648  * tcp_g_q_create() to open a TCP stream.
24649  * We need to allow tcp_g_q_create() do do an open
24650  * of tcp, hence we compare curhread.
24651  * All others have to wait until the tcps_g_q has been
24652  * setup.
24653  */
24654 void
24655 tcp_g_q_setup(tcp_stack_t *tcps)
24656 {
24657 	mutex_enter(&tcps->tcps_g_q_lock);
24658 	if (tcps->tcps_g_q != NULL) {
24659 		mutex_exit(&tcps->tcps_g_q_lock);
24660 		return;
24661 	}
24662 	if (tcps->tcps_g_q_creator == NULL) {
24663 		/* This thread will set it up */
24664 		tcps->tcps_g_q_creator = curthread;
24665 		mutex_exit(&tcps->tcps_g_q_lock);
24666 		tcp_g_q_create(tcps);
24667 		mutex_enter(&tcps->tcps_g_q_lock);
24668 		ASSERT(tcps->tcps_g_q_creator == curthread);
24669 		tcps->tcps_g_q_creator = NULL;
24670 		cv_signal(&tcps->tcps_g_q_cv);
24671 		ASSERT(tcps->tcps_g_q != NULL);
24672 		mutex_exit(&tcps->tcps_g_q_lock);
24673 		return;
24674 	}
24675 	/* Everybody but the creator has to wait */
24676 	if (tcps->tcps_g_q_creator != curthread) {
24677 		while (tcps->tcps_g_q == NULL)
24678 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24679 	}
24680 	mutex_exit(&tcps->tcps_g_q_lock);
24681 }
24682 
24683 #define	IP	"ip"
24684 
24685 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24686 
24687 /*
24688  * Create a default tcp queue here instead of in strplumb
24689  */
24690 void
24691 tcp_g_q_create(tcp_stack_t *tcps)
24692 {
24693 	int error;
24694 	ldi_handle_t	lh = NULL;
24695 	ldi_ident_t	li = NULL;
24696 	int		rval;
24697 	cred_t		*cr;
24698 	major_t IP_MAJ;
24699 
24700 #ifdef NS_DEBUG
24701 	(void) printf("tcp_g_q_create()\n");
24702 #endif
24703 
24704 	IP_MAJ = ddi_name_to_major(IP);
24705 
24706 	ASSERT(tcps->tcps_g_q_creator == curthread);
24707 
24708 	error = ldi_ident_from_major(IP_MAJ, &li);
24709 	if (error) {
24710 #ifdef DEBUG
24711 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24712 		    error);
24713 #endif
24714 		return;
24715 	}
24716 
24717 	cr = zone_get_kcred(netstackid_to_zoneid(
24718 	    tcps->tcps_netstack->netstack_stackid));
24719 	ASSERT(cr != NULL);
24720 	/*
24721 	 * We set the tcp default queue to IPv6 because IPv4 falls
24722 	 * back to IPv6 when it can't find a client, but
24723 	 * IPv6 does not fall back to IPv4.
24724 	 */
24725 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24726 	if (error) {
24727 #ifdef DEBUG
24728 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24729 		    error);
24730 #endif
24731 		goto out;
24732 	}
24733 
24734 	/*
24735 	 * This ioctl causes the tcp framework to cache a pointer to
24736 	 * this stream, so we don't want to close the stream after
24737 	 * this operation.
24738 	 * Use the kernel credentials that are for the zone we're in.
24739 	 */
24740 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24741 	    (intptr_t)0, FKIOCTL, cr, &rval);
24742 	if (error) {
24743 #ifdef DEBUG
24744 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24745 		    "error %d\n", error);
24746 #endif
24747 		goto out;
24748 	}
24749 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24750 	lh = NULL;
24751 out:
24752 	/* Close layered handles */
24753 	if (li)
24754 		ldi_ident_release(li);
24755 	/* Keep cred around until _inactive needs it */
24756 	tcps->tcps_g_q_cr = cr;
24757 }
24758 
24759 /*
24760  * We keep tcp_g_q set until all other tcp_t's in the zone
24761  * has gone away, and then when tcp_g_q_inactive() is called
24762  * we clear it.
24763  */
24764 void
24765 tcp_g_q_destroy(tcp_stack_t *tcps)
24766 {
24767 #ifdef NS_DEBUG
24768 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24769 	    tcps->tcps_netstack->netstack_stackid);
24770 #endif
24771 
24772 	if (tcps->tcps_g_q == NULL) {
24773 		return;	/* Nothing to cleanup */
24774 	}
24775 	/*
24776 	 * Drop reference corresponding to the default queue.
24777 	 * This reference was added from tcp_open when the default queue
24778 	 * was created, hence we compensate for this extra drop in
24779 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24780 	 * the default queue was the last one to be open, in which
24781 	 * case, then tcp_g_q_inactive will be
24782 	 * called as a result of the refrele.
24783 	 */
24784 	TCPS_REFRELE(tcps);
24785 }
24786 
24787 /*
24788  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24789  * Run by tcp_q_q_inactive using a taskq.
24790  */
24791 static void
24792 tcp_g_q_close(void *arg)
24793 {
24794 	tcp_stack_t *tcps = arg;
24795 	int error;
24796 	ldi_handle_t	lh = NULL;
24797 	ldi_ident_t	li = NULL;
24798 	cred_t		*cr;
24799 	major_t IP_MAJ;
24800 
24801 	IP_MAJ = ddi_name_to_major(IP);
24802 
24803 #ifdef NS_DEBUG
24804 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24805 	    tcps->tcps_netstack->netstack_stackid,
24806 	    tcps->tcps_netstack->netstack_refcnt);
24807 #endif
24808 	lh = tcps->tcps_g_q_lh;
24809 	if (lh == NULL)
24810 		return;	/* Nothing to cleanup */
24811 
24812 	ASSERT(tcps->tcps_refcnt == 1);
24813 	ASSERT(tcps->tcps_g_q != NULL);
24814 
24815 	error = ldi_ident_from_major(IP_MAJ, &li);
24816 	if (error) {
24817 #ifdef DEBUG
24818 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24819 		    error);
24820 #endif
24821 		return;
24822 	}
24823 
24824 	cr = tcps->tcps_g_q_cr;
24825 	tcps->tcps_g_q_cr = NULL;
24826 	ASSERT(cr != NULL);
24827 
24828 	/*
24829 	 * Make sure we can break the recursion when tcp_close decrements
24830 	 * the reference count causing g_q_inactive to be called again.
24831 	 */
24832 	tcps->tcps_g_q_lh = NULL;
24833 
24834 	/* close the default queue */
24835 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24836 	/*
24837 	 * At this point in time tcps and the rest of netstack_t might
24838 	 * have been deleted.
24839 	 */
24840 	tcps = NULL;
24841 
24842 	/* Close layered handles */
24843 	ldi_ident_release(li);
24844 	crfree(cr);
24845 }
24846 
24847 /*
24848  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24849  *
24850  * Have to ensure that the ldi routines are not used by an
24851  * interrupt thread by using a taskq.
24852  */
24853 void
24854 tcp_g_q_inactive(tcp_stack_t *tcps)
24855 {
24856 	if (tcps->tcps_g_q_lh == NULL)
24857 		return;	/* Nothing to cleanup */
24858 
24859 	ASSERT(tcps->tcps_refcnt == 0);
24860 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24861 
24862 	if (servicing_interrupt()) {
24863 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24864 		    (void *) tcps, TQ_SLEEP);
24865 	} else {
24866 		tcp_g_q_close(tcps);
24867 	}
24868 }
24869 
24870 /*
24871  * Called by IP when IP is loaded into the kernel
24872  */
24873 void
24874 tcp_ddi_g_init(void)
24875 {
24876 	tcp_timercache = kmem_cache_create("tcp_timercache",
24877 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24878 	    NULL, NULL, NULL, NULL, NULL, 0);
24879 
24880 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24881 	    sizeof (tcp_sack_info_t), 0,
24882 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24883 
24884 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24885 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24886 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24887 
24888 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24889 
24890 	/* Initialize the random number generator */
24891 	tcp_random_init();
24892 
24893 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
24894 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
24895 
24896 	/* A single callback independently of how many netstacks we have */
24897 	ip_squeue_init(tcp_squeue_add);
24898 
24899 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24900 
24901 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24902 	    TASKQ_PREPOPULATE);
24903 
24904 	/*
24905 	 * We want to be informed each time a stack is created or
24906 	 * destroyed in the kernel, so we can maintain the
24907 	 * set of tcp_stack_t's.
24908 	 */
24909 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24910 	    tcp_stack_fini);
24911 }
24912 
24913 
24914 /*
24915  * Initialize the TCP stack instance.
24916  */
24917 static void *
24918 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24919 {
24920 	tcp_stack_t	*tcps;
24921 	tcpparam_t	*pa;
24922 	int		i;
24923 
24924 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24925 	tcps->tcps_netstack = ns;
24926 
24927 	/* Initialize locks */
24928 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24929 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24930 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24931 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24932 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24933 
24934 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24935 	tcps->tcps_g_epriv_ports[0] = 2049;
24936 	tcps->tcps_g_epriv_ports[1] = 4045;
24937 	tcps->tcps_min_anonpriv_port = 512;
24938 
24939 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24940 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24941 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24942 	    TCP_FANOUT_SIZE, KM_SLEEP);
24943 
24944 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24945 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24946 		    MUTEX_DEFAULT, NULL);
24947 	}
24948 
24949 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24950 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24951 		    MUTEX_DEFAULT, NULL);
24952 	}
24953 
24954 	/* TCP's IPsec code calls the packet dropper. */
24955 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24956 
24957 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24958 	tcps->tcps_params = pa;
24959 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24960 
24961 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24962 	    A_CNT(lcl_tcp_param_arr), tcps);
24963 
24964 	/*
24965 	 * Note: To really walk the device tree you need the devinfo
24966 	 * pointer to your device which is only available after probe/attach.
24967 	 * The following is safe only because it uses ddi_root_node()
24968 	 */
24969 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24970 	    tcp_opt_obj.odb_opt_arr_cnt);
24971 
24972 	/*
24973 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24974 	 * by the boot scripts.
24975 	 *
24976 	 * Use NULL name, as the name is caught by the new lockstats.
24977 	 *
24978 	 * Initialize with some random, non-guessable string, like the global
24979 	 * T_INFO_ACK.
24980 	 */
24981 
24982 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24983 	    sizeof (tcp_g_t_info_ack), tcps);
24984 
24985 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24986 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24987 
24988 	return (tcps);
24989 }
24990 
24991 /*
24992  * Called when the IP module is about to be unloaded.
24993  */
24994 void
24995 tcp_ddi_g_destroy(void)
24996 {
24997 	tcp_g_kstat_fini(tcp_g_kstat);
24998 	tcp_g_kstat = NULL;
24999 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25000 
25001 	mutex_destroy(&tcp_random_lock);
25002 
25003 	kmem_cache_destroy(tcp_timercache);
25004 	kmem_cache_destroy(tcp_sack_info_cache);
25005 	kmem_cache_destroy(tcp_iphc_cache);
25006 
25007 	netstack_unregister(NS_TCP);
25008 	taskq_destroy(tcp_taskq);
25009 }
25010 
25011 /*
25012  * Shut down the TCP stack instance.
25013  */
25014 /* ARGSUSED */
25015 static void
25016 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25017 {
25018 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25019 
25020 	tcp_g_q_destroy(tcps);
25021 }
25022 
25023 /*
25024  * Free the TCP stack instance.
25025  */
25026 static void
25027 tcp_stack_fini(netstackid_t stackid, void *arg)
25028 {
25029 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25030 	int i;
25031 
25032 	nd_free(&tcps->tcps_g_nd);
25033 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25034 	tcps->tcps_params = NULL;
25035 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25036 	tcps->tcps_wroff_xtra_param = NULL;
25037 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25038 	tcps->tcps_mdt_head_param = NULL;
25039 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25040 	tcps->tcps_mdt_tail_param = NULL;
25041 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25042 	tcps->tcps_mdt_max_pbufs_param = NULL;
25043 
25044 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25045 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25046 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25047 	}
25048 
25049 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25050 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25051 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25052 	}
25053 
25054 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25055 	tcps->tcps_bind_fanout = NULL;
25056 
25057 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25058 	tcps->tcps_acceptor_fanout = NULL;
25059 
25060 	mutex_destroy(&tcps->tcps_iss_key_lock);
25061 	rw_destroy(&tcps->tcps_hsp_lock);
25062 	mutex_destroy(&tcps->tcps_g_q_lock);
25063 	cv_destroy(&tcps->tcps_g_q_cv);
25064 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25065 
25066 	ip_drop_unregister(&tcps->tcps_dropper);
25067 
25068 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25069 	tcps->tcps_kstat = NULL;
25070 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25071 
25072 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25073 	tcps->tcps_mibkp = NULL;
25074 
25075 	kmem_free(tcps, sizeof (*tcps));
25076 }
25077 
25078 /*
25079  * Generate ISS, taking into account NDD changes may happen halfway through.
25080  * (If the iss is not zero, set it.)
25081  */
25082 
25083 static void
25084 tcp_iss_init(tcp_t *tcp)
25085 {
25086 	MD5_CTX context;
25087 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25088 	uint32_t answer[4];
25089 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25090 
25091 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25092 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25093 	switch (tcps->tcps_strong_iss) {
25094 	case 2:
25095 		mutex_enter(&tcps->tcps_iss_key_lock);
25096 		context = tcps->tcps_iss_key;
25097 		mutex_exit(&tcps->tcps_iss_key_lock);
25098 		arg.ports = tcp->tcp_ports;
25099 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25100 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25101 			    &arg.src);
25102 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25103 			    &arg.dst);
25104 		} else {
25105 			arg.src = tcp->tcp_ip6h->ip6_src;
25106 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25107 		}
25108 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25109 		MD5Final((uchar_t *)answer, &context);
25110 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25111 		/*
25112 		 * Now that we've hashed into a unique per-connection sequence
25113 		 * space, add a random increment per strong_iss == 1.  So I
25114 		 * guess we'll have to...
25115 		 */
25116 		/* FALLTHRU */
25117 	case 1:
25118 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25119 		break;
25120 	default:
25121 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25122 		break;
25123 	}
25124 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25125 	tcp->tcp_fss = tcp->tcp_iss - 1;
25126 	tcp->tcp_suna = tcp->tcp_iss;
25127 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25128 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25129 	tcp->tcp_csuna = tcp->tcp_snxt;
25130 }
25131 
25132 /*
25133  * Exported routine for extracting active tcp connection status.
25134  *
25135  * This is used by the Solaris Cluster Networking software to
25136  * gather a list of connections that need to be forwarded to
25137  * specific nodes in the cluster when configuration changes occur.
25138  *
25139  * The callback is invoked for each tcp_t structure. Returning
25140  * non-zero from the callback routine terminates the search.
25141  */
25142 int
25143 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25144     void *arg)
25145 {
25146 	netstack_handle_t nh;
25147 	netstack_t *ns;
25148 	int ret = 0;
25149 
25150 	netstack_next_init(&nh);
25151 	while ((ns = netstack_next(&nh)) != NULL) {
25152 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25153 		    ns->netstack_tcp);
25154 		netstack_rele(ns);
25155 	}
25156 	netstack_next_fini(&nh);
25157 	return (ret);
25158 }
25159 
25160 static int
25161 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25162     tcp_stack_t *tcps)
25163 {
25164 	tcp_t *tcp;
25165 	cl_tcp_info_t	cl_tcpi;
25166 	connf_t	*connfp;
25167 	conn_t	*connp;
25168 	int	i;
25169 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25170 
25171 	ASSERT(callback != NULL);
25172 
25173 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25174 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25175 		connp = NULL;
25176 
25177 		while ((connp =
25178 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25179 
25180 			tcp = connp->conn_tcp;
25181 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25182 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25183 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25184 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25185 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25186 			/*
25187 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25188 			 * addresses. They are copied implicitly below as
25189 			 * mapped addresses.
25190 			 */
25191 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25192 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25193 				cl_tcpi.cl_tcpi_faddr =
25194 				    tcp->tcp_ipha->ipha_dst;
25195 			} else {
25196 				cl_tcpi.cl_tcpi_faddr_v6 =
25197 				    tcp->tcp_ip6h->ip6_dst;
25198 			}
25199 
25200 			/*
25201 			 * If the callback returns non-zero
25202 			 * we terminate the traversal.
25203 			 */
25204 			if ((*callback)(&cl_tcpi, arg) != 0) {
25205 				CONN_DEC_REF(tcp->tcp_connp);
25206 				return (1);
25207 			}
25208 		}
25209 	}
25210 
25211 	return (0);
25212 }
25213 
25214 /*
25215  * Macros used for accessing the different types of sockaddr
25216  * structures inside a tcp_ioc_abort_conn_t.
25217  */
25218 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25219 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25220 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25221 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25222 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25223 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25224 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25225 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25226 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25227 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25228 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25229 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25230 
25231 /*
25232  * Return the correct error code to mimic the behavior
25233  * of a connection reset.
25234  */
25235 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25236 		switch ((state)) {		\
25237 		case TCPS_SYN_SENT:		\
25238 		case TCPS_SYN_RCVD:		\
25239 			(err) = ECONNREFUSED;	\
25240 			break;			\
25241 		case TCPS_ESTABLISHED:		\
25242 		case TCPS_FIN_WAIT_1:		\
25243 		case TCPS_FIN_WAIT_2:		\
25244 		case TCPS_CLOSE_WAIT:		\
25245 			(err) = ECONNRESET;	\
25246 			break;			\
25247 		case TCPS_CLOSING:		\
25248 		case TCPS_LAST_ACK:		\
25249 		case TCPS_TIME_WAIT:		\
25250 			(err) = 0;		\
25251 			break;			\
25252 		default:			\
25253 			(err) = ENXIO;		\
25254 		}				\
25255 	}
25256 
25257 /*
25258  * Check if a tcp structure matches the info in acp.
25259  */
25260 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25261 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25262 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25263 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25264 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25265 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25266 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25267 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25268 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25269 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25270 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25271 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25272 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25273 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25274 	&(tcp)->tcp_ip_src_v6)) &&				\
25275 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25276 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25277 	&(tcp)->tcp_remote_v6)) &&				\
25278 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25279 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25280 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25281 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25282 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25283 	(acp)->ac_end >= (tcp)->tcp_state))
25284 
25285 #define	TCP_AC_MATCH(acp, tcp)					\
25286 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25287 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25288 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25289 
25290 /*
25291  * Build a message containing a tcp_ioc_abort_conn_t structure
25292  * which is filled in with information from acp and tp.
25293  */
25294 static mblk_t *
25295 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25296 {
25297 	mblk_t *mp;
25298 	tcp_ioc_abort_conn_t *tacp;
25299 
25300 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25301 	if (mp == NULL)
25302 		return (NULL);
25303 
25304 	mp->b_datap->db_type = M_CTL;
25305 
25306 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25307 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25308 	    sizeof (uint32_t));
25309 
25310 	tacp->ac_start = acp->ac_start;
25311 	tacp->ac_end = acp->ac_end;
25312 	tacp->ac_zoneid = acp->ac_zoneid;
25313 
25314 	if (acp->ac_local.ss_family == AF_INET) {
25315 		tacp->ac_local.ss_family = AF_INET;
25316 		tacp->ac_remote.ss_family = AF_INET;
25317 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25318 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25319 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25320 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25321 	} else {
25322 		tacp->ac_local.ss_family = AF_INET6;
25323 		tacp->ac_remote.ss_family = AF_INET6;
25324 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25325 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25326 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25327 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25328 	}
25329 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25330 	return (mp);
25331 }
25332 
25333 /*
25334  * Print a tcp_ioc_abort_conn_t structure.
25335  */
25336 static void
25337 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25338 {
25339 	char lbuf[128];
25340 	char rbuf[128];
25341 	sa_family_t af;
25342 	in_port_t lport, rport;
25343 	ushort_t logflags;
25344 
25345 	af = acp->ac_local.ss_family;
25346 
25347 	if (af == AF_INET) {
25348 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25349 		    lbuf, 128);
25350 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25351 		    rbuf, 128);
25352 		lport = ntohs(TCP_AC_V4LPORT(acp));
25353 		rport = ntohs(TCP_AC_V4RPORT(acp));
25354 	} else {
25355 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25356 		    lbuf, 128);
25357 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25358 		    rbuf, 128);
25359 		lport = ntohs(TCP_AC_V6LPORT(acp));
25360 		rport = ntohs(TCP_AC_V6RPORT(acp));
25361 	}
25362 
25363 	logflags = SL_TRACE | SL_NOTE;
25364 	/*
25365 	 * Don't print this message to the console if the operation was done
25366 	 * to a non-global zone.
25367 	 */
25368 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25369 		logflags |= SL_CONSOLE;
25370 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25371 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25372 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25373 	    acp->ac_start, acp->ac_end);
25374 }
25375 
25376 /*
25377  * Called inside tcp_rput when a message built using
25378  * tcp_ioctl_abort_build_msg is put into a queue.
25379  * Note that when we get here there is no wildcard in acp any more.
25380  */
25381 static void
25382 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25383 {
25384 	tcp_ioc_abort_conn_t *acp;
25385 
25386 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25387 	if (tcp->tcp_state <= acp->ac_end) {
25388 		/*
25389 		 * If we get here, we are already on the correct
25390 		 * squeue. This ioctl follows the following path
25391 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25392 		 * ->tcp_ioctl_abort->squeue_fill (if on a
25393 		 * different squeue)
25394 		 */
25395 		int errcode;
25396 
25397 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25398 		(void) tcp_clean_death(tcp, errcode, 26);
25399 	}
25400 	freemsg(mp);
25401 }
25402 
25403 /*
25404  * Abort all matching connections on a hash chain.
25405  */
25406 static int
25407 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25408     boolean_t exact, tcp_stack_t *tcps)
25409 {
25410 	int nmatch, err = 0;
25411 	tcp_t *tcp;
25412 	MBLKP mp, last, listhead = NULL;
25413 	conn_t	*tconnp;
25414 	connf_t	*connfp;
25415 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25416 
25417 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25418 
25419 startover:
25420 	nmatch = 0;
25421 
25422 	mutex_enter(&connfp->connf_lock);
25423 	for (tconnp = connfp->connf_head; tconnp != NULL;
25424 	    tconnp = tconnp->conn_next) {
25425 		tcp = tconnp->conn_tcp;
25426 		if (TCP_AC_MATCH(acp, tcp)) {
25427 			CONN_INC_REF(tcp->tcp_connp);
25428 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25429 			if (mp == NULL) {
25430 				err = ENOMEM;
25431 				CONN_DEC_REF(tcp->tcp_connp);
25432 				break;
25433 			}
25434 			mp->b_prev = (mblk_t *)tcp;
25435 
25436 			if (listhead == NULL) {
25437 				listhead = mp;
25438 				last = mp;
25439 			} else {
25440 				last->b_next = mp;
25441 				last = mp;
25442 			}
25443 			nmatch++;
25444 			if (exact)
25445 				break;
25446 		}
25447 
25448 		/* Avoid holding lock for too long. */
25449 		if (nmatch >= 500)
25450 			break;
25451 	}
25452 	mutex_exit(&connfp->connf_lock);
25453 
25454 	/* Pass mp into the correct tcp */
25455 	while ((mp = listhead) != NULL) {
25456 		listhead = listhead->b_next;
25457 		tcp = (tcp_t *)mp->b_prev;
25458 		mp->b_next = mp->b_prev = NULL;
25459 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
25460 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
25461 	}
25462 
25463 	*count += nmatch;
25464 	if (nmatch >= 500 && err == 0)
25465 		goto startover;
25466 	return (err);
25467 }
25468 
25469 /*
25470  * Abort all connections that matches the attributes specified in acp.
25471  */
25472 static int
25473 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25474 {
25475 	sa_family_t af;
25476 	uint32_t  ports;
25477 	uint16_t *pports;
25478 	int err = 0, count = 0;
25479 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25480 	int index = -1;
25481 	ushort_t logflags;
25482 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25483 
25484 	af = acp->ac_local.ss_family;
25485 
25486 	if (af == AF_INET) {
25487 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25488 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25489 			pports = (uint16_t *)&ports;
25490 			pports[1] = TCP_AC_V4LPORT(acp);
25491 			pports[0] = TCP_AC_V4RPORT(acp);
25492 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25493 		}
25494 	} else {
25495 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25496 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25497 			pports = (uint16_t *)&ports;
25498 			pports[1] = TCP_AC_V6LPORT(acp);
25499 			pports[0] = TCP_AC_V6RPORT(acp);
25500 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25501 		}
25502 	}
25503 
25504 	/*
25505 	 * For cases where remote addr, local port, and remote port are non-
25506 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25507 	 */
25508 	if (index != -1) {
25509 		err = tcp_ioctl_abort_bucket(acp, index,
25510 		    &count, exact, tcps);
25511 	} else {
25512 		/*
25513 		 * loop through all entries for wildcard case
25514 		 */
25515 		for (index = 0;
25516 		    index < ipst->ips_ipcl_conn_fanout_size;
25517 		    index++) {
25518 			err = tcp_ioctl_abort_bucket(acp, index,
25519 			    &count, exact, tcps);
25520 			if (err != 0)
25521 				break;
25522 		}
25523 	}
25524 
25525 	logflags = SL_TRACE | SL_NOTE;
25526 	/*
25527 	 * Don't print this message to the console if the operation was done
25528 	 * to a non-global zone.
25529 	 */
25530 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25531 		logflags |= SL_CONSOLE;
25532 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25533 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25534 	if (err == 0 && count == 0)
25535 		err = ENOENT;
25536 	return (err);
25537 }
25538 
25539 /*
25540  * Process the TCP_IOC_ABORT_CONN ioctl request.
25541  */
25542 static void
25543 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25544 {
25545 	int	err;
25546 	IOCP    iocp;
25547 	MBLKP   mp1;
25548 	sa_family_t laf, raf;
25549 	tcp_ioc_abort_conn_t *acp;
25550 	zone_t		*zptr;
25551 	conn_t		*connp = Q_TO_CONN(q);
25552 	zoneid_t	zoneid = connp->conn_zoneid;
25553 	tcp_t		*tcp = connp->conn_tcp;
25554 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25555 
25556 	iocp = (IOCP)mp->b_rptr;
25557 
25558 	if ((mp1 = mp->b_cont) == NULL ||
25559 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25560 		err = EINVAL;
25561 		goto out;
25562 	}
25563 
25564 	/* check permissions */
25565 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25566 		err = EPERM;
25567 		goto out;
25568 	}
25569 
25570 	if (mp1->b_cont != NULL) {
25571 		freemsg(mp1->b_cont);
25572 		mp1->b_cont = NULL;
25573 	}
25574 
25575 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25576 	laf = acp->ac_local.ss_family;
25577 	raf = acp->ac_remote.ss_family;
25578 
25579 	/* check that a zone with the supplied zoneid exists */
25580 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25581 		zptr = zone_find_by_id(zoneid);
25582 		if (zptr != NULL) {
25583 			zone_rele(zptr);
25584 		} else {
25585 			err = EINVAL;
25586 			goto out;
25587 		}
25588 	}
25589 
25590 	/*
25591 	 * For exclusive stacks we set the zoneid to zero
25592 	 * to make TCP operate as if in the global zone.
25593 	 */
25594 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25595 		acp->ac_zoneid = GLOBAL_ZONEID;
25596 
25597 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25598 	    acp->ac_start > acp->ac_end || laf != raf ||
25599 	    (laf != AF_INET && laf != AF_INET6)) {
25600 		err = EINVAL;
25601 		goto out;
25602 	}
25603 
25604 	tcp_ioctl_abort_dump(acp);
25605 	err = tcp_ioctl_abort(acp, tcps);
25606 
25607 out:
25608 	if (mp1 != NULL) {
25609 		freemsg(mp1);
25610 		mp->b_cont = NULL;
25611 	}
25612 
25613 	if (err != 0)
25614 		miocnak(q, mp, 0, err);
25615 	else
25616 		miocack(q, mp, 0, 0);
25617 }
25618 
25619 /*
25620  * tcp_time_wait_processing() handles processing of incoming packets when
25621  * the tcp is in the TIME_WAIT state.
25622  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25623  * on the time wait list.
25624  */
25625 void
25626 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25627     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25628 {
25629 	int32_t		bytes_acked;
25630 	int32_t		gap;
25631 	int32_t		rgap;
25632 	tcp_opt_t	tcpopt;
25633 	uint_t		flags;
25634 	uint32_t	new_swnd = 0;
25635 	conn_t		*connp;
25636 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25637 
25638 	BUMP_LOCAL(tcp->tcp_ibsegs);
25639 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25640 
25641 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25642 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25643 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25644 	if (tcp->tcp_snd_ts_ok) {
25645 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25646 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25647 			    tcp->tcp_rnxt, TH_ACK);
25648 			goto done;
25649 		}
25650 	}
25651 	gap = seg_seq - tcp->tcp_rnxt;
25652 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25653 	if (gap < 0) {
25654 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25655 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25656 		    (seg_len > -gap ? -gap : seg_len));
25657 		seg_len += gap;
25658 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25659 			if (flags & TH_RST) {
25660 				goto done;
25661 			}
25662 			if ((flags & TH_FIN) && seg_len == -1) {
25663 				/*
25664 				 * When TCP receives a duplicate FIN in
25665 				 * TIME_WAIT state, restart the 2 MSL timer.
25666 				 * See page 73 in RFC 793. Make sure this TCP
25667 				 * is already on the TIME_WAIT list. If not,
25668 				 * just restart the timer.
25669 				 */
25670 				if (TCP_IS_DETACHED(tcp)) {
25671 					if (tcp_time_wait_remove(tcp, NULL) ==
25672 					    B_TRUE) {
25673 						tcp_time_wait_append(tcp);
25674 						TCP_DBGSTAT(tcps,
25675 						    tcp_rput_time_wait);
25676 					}
25677 				} else {
25678 					ASSERT(tcp != NULL);
25679 					TCP_TIMER_RESTART(tcp,
25680 					    tcps->tcps_time_wait_interval);
25681 				}
25682 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25683 				    tcp->tcp_rnxt, TH_ACK);
25684 				goto done;
25685 			}
25686 			flags |=  TH_ACK_NEEDED;
25687 			seg_len = 0;
25688 			goto process_ack;
25689 		}
25690 
25691 		/* Fix seg_seq, and chew the gap off the front. */
25692 		seg_seq = tcp->tcp_rnxt;
25693 	}
25694 
25695 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25696 		/*
25697 		 * Make sure that when we accept the connection, pick
25698 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25699 		 * old connection.
25700 		 *
25701 		 * The next ISS generated is equal to tcp_iss_incr_extra
25702 		 * + ISS_INCR/2 + other components depending on the
25703 		 * value of tcp_strong_iss.  We pre-calculate the new
25704 		 * ISS here and compare with tcp_snxt to determine if
25705 		 * we need to make adjustment to tcp_iss_incr_extra.
25706 		 *
25707 		 * The above calculation is ugly and is a
25708 		 * waste of CPU cycles...
25709 		 */
25710 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25711 		int32_t adj;
25712 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25713 
25714 		switch (tcps->tcps_strong_iss) {
25715 		case 2: {
25716 			/* Add time and MD5 components. */
25717 			uint32_t answer[4];
25718 			struct {
25719 				uint32_t ports;
25720 				in6_addr_t src;
25721 				in6_addr_t dst;
25722 			} arg;
25723 			MD5_CTX context;
25724 
25725 			mutex_enter(&tcps->tcps_iss_key_lock);
25726 			context = tcps->tcps_iss_key;
25727 			mutex_exit(&tcps->tcps_iss_key_lock);
25728 			arg.ports = tcp->tcp_ports;
25729 			/* We use MAPPED addresses in tcp_iss_init */
25730 			arg.src = tcp->tcp_ip_src_v6;
25731 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25732 				IN6_IPADDR_TO_V4MAPPED(
25733 				    tcp->tcp_ipha->ipha_dst,
25734 				    &arg.dst);
25735 			} else {
25736 				arg.dst =
25737 				    tcp->tcp_ip6h->ip6_dst;
25738 			}
25739 			MD5Update(&context, (uchar_t *)&arg,
25740 			    sizeof (arg));
25741 			MD5Final((uchar_t *)answer, &context);
25742 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25743 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25744 			break;
25745 		}
25746 		case 1:
25747 			/* Add time component and min random (i.e. 1). */
25748 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25749 			break;
25750 		default:
25751 			/* Add only time component. */
25752 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25753 			break;
25754 		}
25755 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25756 			/*
25757 			 * New ISS not guaranteed to be ISS_INCR/2
25758 			 * ahead of the current tcp_snxt, so add the
25759 			 * difference to tcp_iss_incr_extra.
25760 			 */
25761 			tcps->tcps_iss_incr_extra += adj;
25762 		}
25763 		/*
25764 		 * If tcp_clean_death() can not perform the task now,
25765 		 * drop the SYN packet and let the other side re-xmit.
25766 		 * Otherwise pass the SYN packet back in, since the
25767 		 * old tcp state has been cleaned up or freed.
25768 		 */
25769 		if (tcp_clean_death(tcp, 0, 27) == -1)
25770 			goto done;
25771 		/*
25772 		 * We will come back to tcp_rput_data
25773 		 * on the global queue. Packets destined
25774 		 * for the global queue will be checked
25775 		 * with global policy. But the policy for
25776 		 * this packet has already been checked as
25777 		 * this was destined for the detached
25778 		 * connection. We need to bypass policy
25779 		 * check this time by attaching a dummy
25780 		 * ipsec_in with ipsec_in_dont_check set.
25781 		 */
25782 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25783 		if (connp != NULL) {
25784 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25785 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25786 			return;
25787 		}
25788 		goto done;
25789 	}
25790 
25791 	/*
25792 	 * rgap is the amount of stuff received out of window.  A negative
25793 	 * value is the amount out of window.
25794 	 */
25795 	if (rgap < 0) {
25796 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25797 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25798 		/* Fix seg_len and make sure there is something left. */
25799 		seg_len += rgap;
25800 		if (seg_len <= 0) {
25801 			if (flags & TH_RST) {
25802 				goto done;
25803 			}
25804 			flags |=  TH_ACK_NEEDED;
25805 			seg_len = 0;
25806 			goto process_ack;
25807 		}
25808 	}
25809 	/*
25810 	 * Check whether we can update tcp_ts_recent.  This test is
25811 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25812 	 * Extensions for High Performance: An Update", Internet Draft.
25813 	 */
25814 	if (tcp->tcp_snd_ts_ok &&
25815 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25816 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25817 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25818 		tcp->tcp_last_rcv_lbolt = lbolt64;
25819 	}
25820 
25821 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25822 		/* Always ack out of order packets */
25823 		flags |= TH_ACK_NEEDED;
25824 		seg_len = 0;
25825 	} else if (seg_len > 0) {
25826 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25827 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25828 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25829 	}
25830 	if (flags & TH_RST) {
25831 		(void) tcp_clean_death(tcp, 0, 28);
25832 		goto done;
25833 	}
25834 	if (flags & TH_SYN) {
25835 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25836 		    TH_RST|TH_ACK);
25837 		/*
25838 		 * Do not delete the TCP structure if it is in
25839 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25840 		 */
25841 		goto done;
25842 	}
25843 process_ack:
25844 	if (flags & TH_ACK) {
25845 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25846 		if (bytes_acked <= 0) {
25847 			if (bytes_acked == 0 && seg_len == 0 &&
25848 			    new_swnd == tcp->tcp_swnd)
25849 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25850 		} else {
25851 			/* Acks something not sent */
25852 			flags |= TH_ACK_NEEDED;
25853 		}
25854 	}
25855 	if (flags & TH_ACK_NEEDED) {
25856 		/*
25857 		 * Time to send an ack for some reason.
25858 		 */
25859 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25860 		    tcp->tcp_rnxt, TH_ACK);
25861 	}
25862 done:
25863 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25864 		DB_CKSUMSTART(mp) = 0;
25865 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25866 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25867 	}
25868 	freemsg(mp);
25869 }
25870 
25871 /*
25872  * Allocate a T_SVR4_OPTMGMT_REQ.
25873  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
25874  * that tcp_rput_other can drop the acks.
25875  */
25876 static mblk_t *
25877 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
25878 {
25879 	mblk_t *mp;
25880 	struct T_optmgmt_req *tor;
25881 	struct opthdr *oh;
25882 	uint_t size;
25883 	char *optptr;
25884 
25885 	size = sizeof (*tor) + sizeof (*oh) + optlen;
25886 	mp = allocb(size, BPRI_MED);
25887 	if (mp == NULL)
25888 		return (NULL);
25889 
25890 	mp->b_wptr += size;
25891 	mp->b_datap->db_type = M_PROTO;
25892 	tor = (struct T_optmgmt_req *)mp->b_rptr;
25893 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
25894 	tor->MGMT_flags = T_NEGOTIATE;
25895 	tor->OPT_length = sizeof (*oh) + optlen;
25896 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
25897 
25898 	oh = (struct opthdr *)&tor[1];
25899 	oh->level = level;
25900 	oh->name = cmd;
25901 	oh->len = optlen;
25902 	if (optlen != 0) {
25903 		optptr = (char *)&oh[1];
25904 		bcopy(opt, optptr, optlen);
25905 	}
25906 	return (mp);
25907 }
25908 
25909 /*
25910  * TCP Timers Implementation.
25911  */
25912 timeout_id_t
25913 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25914 {
25915 	mblk_t *mp;
25916 	tcp_timer_t *tcpt;
25917 	tcp_t *tcp = connp->conn_tcp;
25918 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25919 
25920 	ASSERT(connp->conn_sqp != NULL);
25921 
25922 	TCP_DBGSTAT(tcps, tcp_timeout_calls);
25923 
25924 	if (tcp->tcp_timercache == NULL) {
25925 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25926 	} else {
25927 		TCP_DBGSTAT(tcps, tcp_timeout_cached_alloc);
25928 		mp = tcp->tcp_timercache;
25929 		tcp->tcp_timercache = mp->b_next;
25930 		mp->b_next = NULL;
25931 		ASSERT(mp->b_wptr == NULL);
25932 	}
25933 
25934 	CONN_INC_REF(connp);
25935 	tcpt = (tcp_timer_t *)mp->b_rptr;
25936 	tcpt->connp = connp;
25937 	tcpt->tcpt_proc = f;
25938 	/*
25939 	 * TCP timers are normal timeouts. Plus, they do not require more than
25940 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25941 	 * rounding up the expiration to the next resolution boundary, we can
25942 	 * batch timers in the callout subsystem to make TCP timers more
25943 	 * efficient. The roundup also protects short timers from expiring too
25944 	 * early before they have a chance to be cancelled.
25945 	 */
25946 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25947 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25948 
25949 	return ((timeout_id_t)mp);
25950 }
25951 
25952 static void
25953 tcp_timer_callback(void *arg)
25954 {
25955 	mblk_t *mp = (mblk_t *)arg;
25956 	tcp_timer_t *tcpt;
25957 	conn_t	*connp;
25958 
25959 	tcpt = (tcp_timer_t *)mp->b_rptr;
25960 	connp = tcpt->connp;
25961 	squeue_fill(connp->conn_sqp, mp,
25962 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
25963 }
25964 
25965 static void
25966 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25967 {
25968 	tcp_timer_t *tcpt;
25969 	conn_t *connp = (conn_t *)arg;
25970 	tcp_t *tcp = connp->conn_tcp;
25971 
25972 	tcpt = (tcp_timer_t *)mp->b_rptr;
25973 	ASSERT(connp == tcpt->connp);
25974 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25975 
25976 	/*
25977 	 * If the TCP has reached the closed state, don't proceed any
25978 	 * further. This TCP logically does not exist on the system.
25979 	 * tcpt_proc could for example access queues, that have already
25980 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25981 	 */
25982 	if (tcp->tcp_state != TCPS_CLOSED) {
25983 		(*tcpt->tcpt_proc)(connp);
25984 	} else {
25985 		tcp->tcp_timer_tid = 0;
25986 	}
25987 	tcp_timer_free(connp->conn_tcp, mp);
25988 }
25989 
25990 /*
25991  * There is potential race with untimeout and the handler firing at the same
25992  * time. The mblock may be freed by the handler while we are trying to use
25993  * it. But since both should execute on the same squeue, this race should not
25994  * occur.
25995  */
25996 clock_t
25997 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25998 {
25999 	mblk_t	*mp = (mblk_t *)id;
26000 	tcp_timer_t *tcpt;
26001 	clock_t delta;
26002 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26003 
26004 	TCP_DBGSTAT(tcps, tcp_timeout_cancel_reqs);
26005 
26006 	if (mp == NULL)
26007 		return (-1);
26008 
26009 	tcpt = (tcp_timer_t *)mp->b_rptr;
26010 	ASSERT(tcpt->connp == connp);
26011 
26012 	delta = untimeout_default(tcpt->tcpt_tid, 0);
26013 
26014 	if (delta >= 0) {
26015 		TCP_DBGSTAT(tcps, tcp_timeout_canceled);
26016 		tcp_timer_free(connp->conn_tcp, mp);
26017 		CONN_DEC_REF(connp);
26018 	}
26019 
26020 	return (delta);
26021 }
26022 
26023 /*
26024  * Allocate space for the timer event. The allocation looks like mblk, but it is
26025  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26026  *
26027  * Dealing with failures: If we can't allocate from the timer cache we try
26028  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26029  * points to b_rptr.
26030  * If we can't allocate anything using allocb_tryhard(), we perform a last
26031  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26032  * save the actual allocation size in b_datap.
26033  */
26034 mblk_t *
26035 tcp_timermp_alloc(int kmflags)
26036 {
26037 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26038 	    kmflags & ~KM_PANIC);
26039 
26040 	if (mp != NULL) {
26041 		mp->b_next = mp->b_prev = NULL;
26042 		mp->b_rptr = (uchar_t *)(&mp[1]);
26043 		mp->b_wptr = NULL;
26044 		mp->b_datap = NULL;
26045 		mp->b_queue = NULL;
26046 		mp->b_cont = NULL;
26047 	} else if (kmflags & KM_PANIC) {
26048 		/*
26049 		 * Failed to allocate memory for the timer. Try allocating from
26050 		 * dblock caches.
26051 		 */
26052 		/* ipclassifier calls this from a constructor - hence no tcps */
26053 		TCP_G_STAT(tcp_timermp_allocfail);
26054 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26055 		if (mp == NULL) {
26056 			size_t size = 0;
26057 			/*
26058 			 * Memory is really low. Try tryhard allocation.
26059 			 *
26060 			 * ipclassifier calls this from a constructor -
26061 			 * hence no tcps
26062 			 */
26063 			TCP_G_STAT(tcp_timermp_allocdblfail);
26064 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26065 			    sizeof (tcp_timer_t), &size, kmflags);
26066 			mp->b_rptr = (uchar_t *)(&mp[1]);
26067 			mp->b_next = mp->b_prev = NULL;
26068 			mp->b_wptr = (uchar_t *)-1;
26069 			mp->b_datap = (dblk_t *)size;
26070 			mp->b_queue = NULL;
26071 			mp->b_cont = NULL;
26072 		}
26073 		ASSERT(mp->b_wptr != NULL);
26074 	}
26075 	/* ipclassifier calls this from a constructor - hence no tcps */
26076 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26077 
26078 	return (mp);
26079 }
26080 
26081 /*
26082  * Free per-tcp timer cache.
26083  * It can only contain entries from tcp_timercache.
26084  */
26085 void
26086 tcp_timermp_free(tcp_t *tcp)
26087 {
26088 	mblk_t *mp;
26089 
26090 	while ((mp = tcp->tcp_timercache) != NULL) {
26091 		ASSERT(mp->b_wptr == NULL);
26092 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26093 		kmem_cache_free(tcp_timercache, mp);
26094 	}
26095 }
26096 
26097 /*
26098  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26099  * events there already (currently at most two events are cached).
26100  * If the event is not allocated from the timer cache, free it right away.
26101  */
26102 static void
26103 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26104 {
26105 	mblk_t *mp1 = tcp->tcp_timercache;
26106 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26107 
26108 	if (mp->b_wptr != NULL) {
26109 		/*
26110 		 * This allocation is not from a timer cache, free it right
26111 		 * away.
26112 		 */
26113 		if (mp->b_wptr != (uchar_t *)-1)
26114 			freeb(mp);
26115 		else
26116 			kmem_free(mp, (size_t)mp->b_datap);
26117 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26118 		/* Cache this timer block for future allocations */
26119 		mp->b_rptr = (uchar_t *)(&mp[1]);
26120 		mp->b_next = mp1;
26121 		tcp->tcp_timercache = mp;
26122 	} else {
26123 		kmem_cache_free(tcp_timercache, mp);
26124 		TCP_DBGSTAT(tcps, tcp_timermp_freed);
26125 	}
26126 }
26127 
26128 /*
26129  * End of TCP Timers implementation.
26130  */
26131 
26132 /*
26133  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26134  * on the specified backing STREAMS q. Note, the caller may make the
26135  * decision to call based on the tcp_t.tcp_flow_stopped value which
26136  * when check outside the q's lock is only an advisory check ...
26137  */
26138 
26139 void
26140 tcp_setqfull(tcp_t *tcp)
26141 {
26142 	queue_t *q = tcp->tcp_wq;
26143 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26144 
26145 	if (!(q->q_flag & QFULL)) {
26146 		mutex_enter(QLOCK(q));
26147 		if (!(q->q_flag & QFULL)) {
26148 			/* still need to set QFULL */
26149 			q->q_flag |= QFULL;
26150 			tcp->tcp_flow_stopped = B_TRUE;
26151 			mutex_exit(QLOCK(q));
26152 			TCP_STAT(tcps, tcp_flwctl_on);
26153 		} else {
26154 			mutex_exit(QLOCK(q));
26155 		}
26156 	}
26157 }
26158 
26159 void
26160 tcp_clrqfull(tcp_t *tcp)
26161 {
26162 	queue_t *q = tcp->tcp_wq;
26163 
26164 	if (q->q_flag & QFULL) {
26165 		mutex_enter(QLOCK(q));
26166 		if (q->q_flag & QFULL) {
26167 			q->q_flag &= ~QFULL;
26168 			tcp->tcp_flow_stopped = B_FALSE;
26169 			mutex_exit(QLOCK(q));
26170 			if (q->q_flag & QWANTW)
26171 				qbackenable(q, 0);
26172 		} else {
26173 			mutex_exit(QLOCK(q));
26174 		}
26175 	}
26176 }
26177 
26178 
26179 /*
26180  * kstats related to squeues i.e. not per IP instance
26181  */
26182 static void *
26183 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26184 {
26185 	kstat_t *ksp;
26186 
26187 	tcp_g_stat_t template = {
26188 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26189 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26190 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26191 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26192 	};
26193 
26194 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26195 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26196 	    KSTAT_FLAG_VIRTUAL);
26197 
26198 	if (ksp == NULL)
26199 		return (NULL);
26200 
26201 	bcopy(&template, tcp_g_statp, sizeof (template));
26202 	ksp->ks_data = (void *)tcp_g_statp;
26203 
26204 	kstat_install(ksp);
26205 	return (ksp);
26206 }
26207 
26208 static void
26209 tcp_g_kstat_fini(kstat_t *ksp)
26210 {
26211 	if (ksp != NULL) {
26212 		kstat_delete(ksp);
26213 	}
26214 }
26215 
26216 
26217 static void *
26218 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26219 {
26220 	kstat_t *ksp;
26221 
26222 	tcp_stat_t template = {
26223 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26224 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26225 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26226 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26227 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26228 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26229 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26230 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26231 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26232 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26233 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26234 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26235 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26236 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26237 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26238 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26239 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26240 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26241 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26242 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26243 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26244 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26245 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26246 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26247 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26248 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26249 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26250 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26251 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26252 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26253 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26254 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26255 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26256 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26257 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26258 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26259 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26260 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26261 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26262 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26263 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26264 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26265 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26266 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26267 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26268 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26269 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26270 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26271 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26272 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26273 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26274 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26275 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26276 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26277 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26278 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26279 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26280 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26281 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26282 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26283 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26284 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26285 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26286 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26287 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26288 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26289 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26290 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26291 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26292 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26293 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26294 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26295 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26296 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26297 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26298 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26299 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26300 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26301 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26302 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26303 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26304 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26305 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26306 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26307 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26308 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26309 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26310 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26311 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26312 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26313 	};
26314 
26315 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26316 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26317 	    KSTAT_FLAG_VIRTUAL, stackid);
26318 
26319 	if (ksp == NULL)
26320 		return (NULL);
26321 
26322 	bcopy(&template, tcps_statisticsp, sizeof (template));
26323 	ksp->ks_data = (void *)tcps_statisticsp;
26324 	ksp->ks_private = (void *)(uintptr_t)stackid;
26325 
26326 	kstat_install(ksp);
26327 	return (ksp);
26328 }
26329 
26330 static void
26331 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26332 {
26333 	if (ksp != NULL) {
26334 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26335 		kstat_delete_netstack(ksp, stackid);
26336 	}
26337 }
26338 
26339 /*
26340  * TCP Kstats implementation
26341  */
26342 static void *
26343 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26344 {
26345 	kstat_t	*ksp;
26346 
26347 	tcp_named_kstat_t template = {
26348 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26349 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26350 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26351 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26352 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26353 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26354 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26355 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26356 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26357 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26358 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26359 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26360 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26361 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26362 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26363 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26364 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26365 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26366 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26367 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26368 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26369 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26370 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26371 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26372 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26373 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26374 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26375 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26376 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26377 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26378 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26379 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26380 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26381 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26382 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26383 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26384 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26385 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26386 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26387 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26388 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26389 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26390 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26391 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26392 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26393 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26394 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26395 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26396 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26397 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26398 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26399 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26400 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26401 	};
26402 
26403 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26404 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26405 
26406 	if (ksp == NULL)
26407 		return (NULL);
26408 
26409 	template.rtoAlgorithm.value.ui32 = 4;
26410 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26411 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26412 	template.maxConn.value.i32 = -1;
26413 
26414 	bcopy(&template, ksp->ks_data, sizeof (template));
26415 	ksp->ks_update = tcp_kstat_update;
26416 	ksp->ks_private = (void *)(uintptr_t)stackid;
26417 
26418 	kstat_install(ksp);
26419 	return (ksp);
26420 }
26421 
26422 static void
26423 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26424 {
26425 	if (ksp != NULL) {
26426 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26427 		kstat_delete_netstack(ksp, stackid);
26428 	}
26429 }
26430 
26431 static int
26432 tcp_kstat_update(kstat_t *kp, int rw)
26433 {
26434 	tcp_named_kstat_t *tcpkp;
26435 	tcp_t		*tcp;
26436 	connf_t		*connfp;
26437 	conn_t		*connp;
26438 	int 		i;
26439 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26440 	netstack_t	*ns;
26441 	tcp_stack_t	*tcps;
26442 	ip_stack_t	*ipst;
26443 
26444 	if ((kp == NULL) || (kp->ks_data == NULL))
26445 		return (EIO);
26446 
26447 	if (rw == KSTAT_WRITE)
26448 		return (EACCES);
26449 
26450 	ns = netstack_find_by_stackid(stackid);
26451 	if (ns == NULL)
26452 		return (-1);
26453 	tcps = ns->netstack_tcp;
26454 	if (tcps == NULL) {
26455 		netstack_rele(ns);
26456 		return (-1);
26457 	}
26458 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26459 
26460 	tcpkp->currEstab.value.ui32 = 0;
26461 
26462 	ipst = ns->netstack_ip;
26463 
26464 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26465 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26466 		connp = NULL;
26467 		while ((connp =
26468 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26469 			tcp = connp->conn_tcp;
26470 			switch (tcp_snmp_state(tcp)) {
26471 			case MIB2_TCP_established:
26472 			case MIB2_TCP_closeWait:
26473 				tcpkp->currEstab.value.ui32++;
26474 				break;
26475 			}
26476 		}
26477 	}
26478 
26479 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26480 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26481 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26482 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26483 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26484 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26485 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26486 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26487 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26488 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26489 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26490 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26491 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26492 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26493 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26494 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26495 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26496 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26497 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26498 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26499 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26500 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26501 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26502 	tcpkp->inDataInorderSegs.value.ui32 =
26503 	    tcps->tcps_mib.tcpInDataInorderSegs;
26504 	tcpkp->inDataInorderBytes.value.ui32 =
26505 	    tcps->tcps_mib.tcpInDataInorderBytes;
26506 	tcpkp->inDataUnorderSegs.value.ui32 =
26507 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26508 	tcpkp->inDataUnorderBytes.value.ui32 =
26509 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26510 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26511 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26512 	tcpkp->inDataPartDupSegs.value.ui32 =
26513 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26514 	tcpkp->inDataPartDupBytes.value.ui32 =
26515 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26516 	tcpkp->inDataPastWinSegs.value.ui32 =
26517 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26518 	tcpkp->inDataPastWinBytes.value.ui32 =
26519 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26520 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26521 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26522 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26523 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26524 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26525 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26526 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26527 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26528 	tcpkp->timKeepaliveProbe.value.ui32 =
26529 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26530 	tcpkp->timKeepaliveDrop.value.ui32 =
26531 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26532 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26533 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26534 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26535 	tcpkp->outSackRetransSegs.value.ui32 =
26536 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26537 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26538 
26539 	netstack_rele(ns);
26540 	return (0);
26541 }
26542 
26543 void
26544 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26545 {
26546 	uint16_t	hdr_len;
26547 	ipha_t		*ipha;
26548 	uint8_t		*nexthdrp;
26549 	tcph_t		*tcph;
26550 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26551 
26552 	/* Already has an eager */
26553 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26554 		TCP_STAT(tcps, tcp_reinput_syn);
26555 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
26556 		    connp, SQTAG_TCP_REINPUT_EAGER);
26557 		return;
26558 	}
26559 
26560 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26561 	case IPV4_VERSION:
26562 		ipha = (ipha_t *)mp->b_rptr;
26563 		hdr_len = IPH_HDR_LENGTH(ipha);
26564 		break;
26565 	case IPV6_VERSION:
26566 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26567 		    &hdr_len, &nexthdrp)) {
26568 			CONN_DEC_REF(connp);
26569 			freemsg(mp);
26570 			return;
26571 		}
26572 		break;
26573 	}
26574 
26575 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26576 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26577 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26578 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26579 	}
26580 
26581 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
26582 	    SQTAG_TCP_REINPUT);
26583 }
26584 
26585 static squeue_func_t
26586 tcp_squeue_switch(int val)
26587 {
26588 	squeue_func_t rval = squeue_fill;
26589 
26590 	switch (val) {
26591 	case 1:
26592 		rval = squeue_enter_nodrain;
26593 		break;
26594 	case 2:
26595 		rval = squeue_enter;
26596 		break;
26597 	default:
26598 		break;
26599 	}
26600 	return (rval);
26601 }
26602 
26603 /*
26604  * This is called once for each squeue - globally for all stack
26605  * instances.
26606  */
26607 static void
26608 tcp_squeue_add(squeue_t *sqp)
26609 {
26610 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26611 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26612 
26613 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26614 	tcp_time_wait->tcp_time_wait_tid =
26615 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26616 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26617 	    CALLOUT_FLAG_ROUNDUP);
26618 	if (tcp_free_list_max_cnt == 0) {
26619 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26620 		    max_ncpus : boot_max_ncpus);
26621 
26622 		/*
26623 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26624 		 */
26625 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26626 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26627 	}
26628 	tcp_time_wait->tcp_free_list_cnt = 0;
26629 }
26630