xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 9b4e3ac25d882519cad3fc11f0c53b07f4e60536)
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/socketvar.h>
62 #include <sys/sockio.h>
63 #include <sys/isa_defs.h>
64 #include <sys/md5.h>
65 #include <sys/random.h>
66 #include <sys/sodirect.h>
67 #include <sys/uio.h>
68 #include <sys/systm.h>
69 #include <netinet/in.h>
70 #include <netinet/tcp.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <net/if.h>
74 #include <net/route.h>
75 #include <inet/ipsec_impl.h>
76 
77 #include <inet/common.h>
78 #include <inet/ip.h>
79 #include <inet/ip_impl.h>
80 #include <inet/ip6.h>
81 #include <inet/ip_ndp.h>
82 #include <inet/proto_set.h>
83 #include <inet/mib2.h>
84 #include <inet/nd.h>
85 #include <inet/optcom.h>
86 #include <inet/snmpcom.h>
87 #include <inet/kstatcom.h>
88 #include <inet/tcp.h>
89 #include <inet/tcp_impl.h>
90 #include <net/pfkeyv2.h>
91 #include <inet/ipsec_info.h>
92 #include <inet/ipdrop.h>
93 
94 #include <inet/ipclassifier.h>
95 #include <inet/ip_ire.h>
96 #include <inet/ip_ftable.h>
97 #include <inet/ip_if.h>
98 #include <inet/ipp_common.h>
99 #include <inet/ip_netinfo.h>
100 #include <sys/squeue_impl.h>
101 #include <sys/squeue.h>
102 #include <inet/kssl/ksslapi.h>
103 #include <sys/tsol/label.h>
104 #include <sys/tsol/tnet.h>
105 #include <rpc/pmap_prot.h>
106 #include <sys/callo.h>
107 
108 /*
109  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
110  *
111  * (Read the detailed design doc in PSARC case directory)
112  *
113  * The entire tcp state is contained in tcp_t and conn_t structure
114  * which are allocated in tandem using ipcl_conn_create() and passing
115  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
116  * the references on the tcp_t. The tcp_t structure is never compressed
117  * and packets always land on the correct TCP perimeter from the time
118  * eager is created till the time tcp_t dies (as such the old mentat
119  * TCP global queue is not used for detached state and no IPSEC checking
120  * is required). The global queue is still allocated to send out resets
121  * for connection which have no listeners and IP directly calls
122  * tcp_xmit_listeners_reset() which does any policy check.
123  *
124  * Protection and Synchronisation mechanism:
125  *
126  * The tcp data structure does not use any kind of lock for protecting
127  * its state but instead uses 'squeues' for mutual exclusion from various
128  * read and write side threads. To access a tcp member, the thread should
129  * always be behind squeue (via squeue_enter with flags as SQ_FILL, SQ_PROCESS,
130  * or SQ_NODRAIN). Since the squeues allow a direct function call, caller
131  * can pass any tcp function having prototype of edesc_t as argument
132  * (different from traditional STREAMs model where packets come in only
133  * designated entry points). The list of functions that can be directly
134  * called via squeue are listed before the usual function prototype.
135  *
136  * Referencing:
137  *
138  * TCP is MT-Hot and we use a reference based scheme to make sure that the
139  * tcp structure doesn't disappear when its needed. When the application
140  * creates an outgoing connection or accepts an incoming connection, we
141  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
142  * The IP reference is just a symbolic reference since ip_tcpclose()
143  * looks at tcp structure after tcp_close_output() returns which could
144  * have dropped the last TCP reference. So as long as the connection is
145  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
146  * conn_t. The classifier puts its own reference when the connection is
147  * inserted in listen or connected hash. Anytime a thread needs to enter
148  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
149  * on write side or by doing a classify on read side and then puts a
150  * reference on the conn before doing squeue_enter/tryenter/fill. For
151  * read side, the classifier itself puts the reference under fanout lock
152  * to make sure that tcp can't disappear before it gets processed. The
153  * squeue will drop this reference automatically so the called function
154  * doesn't have to do a DEC_REF.
155  *
156  * Opening a new connection:
157  *
158  * The outgoing connection open is pretty simple. tcp_open() does the
159  * work in creating the conn/tcp structure and initializing it. The
160  * squeue assignment is done based on the CPU the application
161  * is running on. So for outbound connections, processing is always done
162  * on application CPU which might be different from the incoming CPU
163  * being interrupted by the NIC. An optimal way would be to figure out
164  * the NIC <-> CPU binding at listen time, and assign the outgoing
165  * connection to the squeue attached to the CPU that will be interrupted
166  * for incoming packets (we know the NIC based on the bind IP address).
167  * This might seem like a problem if more data is going out but the
168  * fact is that in most cases the transmit is ACK driven transmit where
169  * the outgoing data normally sits on TCP's xmit queue waiting to be
170  * transmitted.
171  *
172  * Accepting a connection:
173  *
174  * This is a more interesting case because of various races involved in
175  * establishing a eager in its own perimeter. Read the meta comment on
176  * top of tcp_conn_request(). But briefly, the squeue is picked by
177  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
178  *
179  * Closing a connection:
180  *
181  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
182  * via squeue to do the close and mark the tcp as detached if the connection
183  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
184  * reference but tcp_close() drop IP's reference always. So if tcp was
185  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
186  * and 1 because it is in classifier's connected hash. This is the condition
187  * we use to determine that its OK to clean up the tcp outside of squeue
188  * when time wait expires (check the ref under fanout and conn_lock and
189  * if it is 2, remove it from fanout hash and kill it).
190  *
191  * Although close just drops the necessary references and marks the
192  * tcp_detached state, tcp_close needs to know the tcp_detached has been
193  * set (under squeue) before letting the STREAM go away (because a
194  * inbound packet might attempt to go up the STREAM while the close
195  * has happened and tcp_detached is not set). So a special lock and
196  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
197  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
198  * tcp_detached.
199  *
200  * Special provisions and fast paths:
201  *
202  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
203  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
204  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
205  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
206  * check to send packets directly to tcp_rput_data via squeue. Everyone
207  * else comes through tcp_input() on the read side.
208  *
209  * We also make special provisions for sockfs by marking tcp_issocket
210  * whenever we have only sockfs on top of TCP. This allows us to skip
211  * putting the tcp in acceptor hash since a sockfs listener can never
212  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
213  * since eager has already been allocated and the accept now happens
214  * on acceptor STREAM. There is a big blob of comment on top of
215  * tcp_conn_request explaining the new accept. When socket is POP'd,
216  * sockfs sends us an ioctl to mark the fact and we go back to old
217  * behaviour. Once tcp_issocket is unset, its never set for the
218  * life of that connection.
219  *
220  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
221  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
222  * directly to the socket (sodirect) and start an asynchronous copyout
223  * to a user-land receive-side buffer (uioa) when a blocking socket read
224  * (e.g. read, recv, ...) is pending.
225  *
226  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
227  * NULL so points to an sodirect_t and if marked enabled then we enqueue
228  * all mblk_t's directly to the socket.
229  *
230  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
231  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
232  * copyout will be started directly to the user-land uio buffer. Also, as we
233  * have a pending read, TCP's push logic can take into account the number of
234  * bytes to be received and only awake the blocked read()er when the uioa_t
235  * byte count has been satisfied.
236  *
237  * IPsec notes :
238  *
239  * Since a packet is always executed on the correct TCP perimeter
240  * all IPsec processing is defered to IP including checking new
241  * connections and setting IPSEC policies for new connection. The
242  * only exception is tcp_xmit_listeners_reset() which is called
243  * directly from IP and needs to policy check to see if TH_RST
244  * can be sent out.
245  *
246  * PFHooks notes :
247  *
248  * For mdt case, one meta buffer contains multiple packets. Mblks for every
249  * packet are assembled and passed to the hooks. When packets are blocked,
250  * or boundary of any packet is changed, the mdt processing is stopped, and
251  * packets of the meta buffer are send to the IP path one by one.
252  */
253 
254 /*
255  * Values for squeue switch:
256  * 1: SQ_NODRAIN
257  * 2: SQ_PROCESS
258  * 3: SQ_FILL
259  */
260 int tcp_squeue_wput = 2;	/* /etc/systems */
261 int tcp_squeue_flag;
262 
263 /*
264  * Macros for sodirect:
265  *
266  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
267  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
268  * if it exists and is enabled, else to NULL. Note, in the current
269  * sodirect implementation the sod_lockp must not be held across any
270  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
271  * will result as sod_lockp is the streamhead stdata.sd_lock.
272  *
273  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
274  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
275  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
276  * being used when sodirect code paths should be.
277  */
278 
279 #define	SOD_PTR_ENTER(tcp, sodp)					\
280 	(sodp) = (tcp)->tcp_sodirect;					\
281 									\
282 	if ((sodp) != NULL) {						\
283 		mutex_enter((sodp)->sod_lockp);				\
284 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
285 			mutex_exit((sodp)->sod_lockp);			\
286 			(sodp) = NULL;					\
287 		}							\
288 	}
289 
290 #define	SOD_NOT_ENABLED(tcp)						\
291 	((tcp)->tcp_sodirect == NULL ||					\
292 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
293 
294 /*
295  * This controls how tiny a write must be before we try to copy it
296  * into the the mblk on the tail of the transmit queue.  Not much
297  * speedup is observed for values larger than sixteen.  Zero will
298  * disable the optimisation.
299  */
300 int tcp_tx_pull_len = 16;
301 
302 /*
303  * TCP Statistics.
304  *
305  * How TCP statistics work.
306  *
307  * There are two types of statistics invoked by two macros.
308  *
309  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
310  * supposed to be used in non MT-hot paths of the code.
311  *
312  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
313  * supposed to be used for DEBUG purposes and may be used on a hot path.
314  *
315  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
316  * (use "kstat tcp" to get them).
317  *
318  * There is also additional debugging facility that marks tcp_clean_death()
319  * instances and saves them in tcp_t structure. It is triggered by
320  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
321  * tcp_clean_death() calls that counts the number of times each tag was hit. It
322  * is triggered by TCP_CLD_COUNTERS define.
323  *
324  * How to add new counters.
325  *
326  * 1) Add a field in the tcp_stat structure describing your counter.
327  * 2) Add a line in the template in tcp_kstat2_init() with the name
328  *    of the counter.
329  *
330  *    IMPORTANT!! - make sure that both are in sync !!
331  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
332  *
333  * Please avoid using private counters which are not kstat-exported.
334  *
335  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
336  * in tcp_t structure.
337  *
338  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
339  */
340 
341 #ifndef TCP_DEBUG_COUNTER
342 #ifdef DEBUG
343 #define	TCP_DEBUG_COUNTER 1
344 #else
345 #define	TCP_DEBUG_COUNTER 0
346 #endif
347 #endif
348 
349 #define	TCP_CLD_COUNTERS 0
350 
351 #define	TCP_TAG_CLEAN_DEATH 1
352 #define	TCP_MAX_CLEAN_DEATH_TAG 32
353 
354 #ifdef lint
355 static int _lint_dummy_;
356 #endif
357 
358 #if TCP_CLD_COUNTERS
359 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
360 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
361 #elif defined(lint)
362 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
363 #else
364 #define	TCP_CLD_STAT(x)
365 #endif
366 
367 #if TCP_DEBUG_COUNTER
368 #define	TCP_DBGSTAT(tcps, x)	\
369 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
370 #define	TCP_G_DBGSTAT(x)	\
371 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
372 #elif defined(lint)
373 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
374 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
375 #else
376 #define	TCP_DBGSTAT(tcps, x)
377 #define	TCP_G_DBGSTAT(x)
378 #endif
379 
380 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
381 
382 tcp_g_stat_t	tcp_g_statistics;
383 kstat_t		*tcp_g_kstat;
384 
385 /*
386  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
387  * tcp write side.
388  */
389 #define	CALL_IP_WPUT(connp, q, mp) {					\
390 	ASSERT(((q)->q_flag & QREADR) == 0);				\
391 	TCP_DBGSTAT(connp->conn_netstack->netstack_tcp, tcp_ip_output);	\
392 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
393 }
394 
395 /* Macros for timestamp comparisons */
396 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
397 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
398 
399 /*
400  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
401  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
402  * by adding three components: a time component which grows by 1 every 4096
403  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
404  * a per-connection component which grows by 125000 for every new connection;
405  * and an "extra" component that grows by a random amount centered
406  * approximately on 64000.  This causes the the ISS generator to cycle every
407  * 4.89 hours if no TCP connections are made, and faster if connections are
408  * made.
409  *
410  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
411  * components: a time component which grows by 250000 every second; and
412  * a per-connection component which grows by 125000 for every new connections.
413  *
414  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
415  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
416  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
417  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
418  * password.
419  */
420 #define	ISS_INCR	250000
421 #define	ISS_NSEC_SHT	12
422 
423 static sin_t	sin_null;	/* Zero address for quick clears */
424 static sin6_t	sin6_null;	/* Zero address for quick clears */
425 
426 /*
427  * This implementation follows the 4.3BSD interpretation of the urgent
428  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
429  * incompatible changes in protocols like telnet and rlogin.
430  */
431 #define	TCP_OLD_URP_INTERPRETATION	1
432 
433 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
434 	(TCP_IS_DETACHED(tcp) && \
435 	    (!(tcp)->tcp_hard_binding))
436 
437 /*
438  * TCP reassembly macros.  We hide starting and ending sequence numbers in
439  * b_next and b_prev of messages on the reassembly queue.  The messages are
440  * chained using b_cont.  These macros are used in tcp_reass() so we don't
441  * have to see the ugly casts and assignments.
442  */
443 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
444 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
445 					(mblk_t *)(uintptr_t)(u))
446 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
447 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
448 					(mblk_t *)(uintptr_t)(u))
449 
450 /*
451  * Implementation of TCP Timers.
452  * =============================
453  *
454  * INTERFACE:
455  *
456  * There are two basic functions dealing with tcp timers:
457  *
458  *	timeout_id_t	tcp_timeout(connp, func, time)
459  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
460  *	TCP_TIMER_RESTART(tcp, intvl)
461  *
462  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
463  * after 'time' ticks passed. The function called by timeout() must adhere to
464  * the same restrictions as a driver soft interrupt handler - it must not sleep
465  * or call other functions that might sleep. The value returned is the opaque
466  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
467  * cancel the request. The call to tcp_timeout() may fail in which case it
468  * returns zero. This is different from the timeout(9F) function which never
469  * fails.
470  *
471  * The call-back function 'func' always receives 'connp' as its single
472  * argument. It is always executed in the squeue corresponding to the tcp
473  * structure. The tcp structure is guaranteed to be present at the time the
474  * call-back is called.
475  *
476  * NOTE: The call-back function 'func' is never called if tcp is in
477  * 	the TCPS_CLOSED state.
478  *
479  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
480  * request. locks acquired by the call-back routine should not be held across
481  * the call to tcp_timeout_cancel() or a deadlock may result.
482  *
483  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
484  * Otherwise, it returns an integer value greater than or equal to 0. In
485  * particular, if the call-back function is already placed on the squeue, it can
486  * not be canceled.
487  *
488  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
489  * 	within squeue context corresponding to the tcp instance. Since the
490  *	call-back is also called via the same squeue, there are no race
491  *	conditions described in untimeout(9F) manual page since all calls are
492  *	strictly serialized.
493  *
494  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
495  *	stored in tcp_timer_tid and starts a new one using
496  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
497  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
498  *	field.
499  *
500  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
501  *	call-back may still be called, so it is possible tcp_timer() will be
502  *	called several times. This should not be a problem since tcp_timer()
503  *	should always check the tcp instance state.
504  *
505  *
506  * IMPLEMENTATION:
507  *
508  * TCP timers are implemented using three-stage process. The call to
509  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
510  * when the timer expires. The tcp_timer_callback() arranges the call of the
511  * tcp_timer_handler() function via squeue corresponding to the tcp
512  * instance. The tcp_timer_handler() calls actual requested timeout call-back
513  * and passes tcp instance as an argument to it. Information is passed between
514  * stages using the tcp_timer_t structure which contains the connp pointer, the
515  * tcp call-back to call and the timeout id returned by the timeout(9F).
516  *
517  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
518  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
519  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
520  * returns the pointer to this mblk.
521  *
522  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
523  * looks like a normal mblk without actual dblk attached to it.
524  *
525  * To optimize performance each tcp instance holds a small cache of timer
526  * mblocks. In the current implementation it caches up to two timer mblocks per
527  * tcp instance. The cache is preserved over tcp frees and is only freed when
528  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
529  * timer processing happens on a corresponding squeue, the cache manipulation
530  * does not require any locks. Experiments show that majority of timer mblocks
531  * allocations are satisfied from the tcp cache and do not involve kmem calls.
532  *
533  * The tcp_timeout() places a refhold on the connp instance which guarantees
534  * that it will be present at the time the call-back function fires. The
535  * tcp_timer_handler() drops the reference after calling the call-back, so the
536  * call-back function does not need to manipulate the references explicitly.
537  */
538 
539 typedef struct tcp_timer_s {
540 	conn_t	*connp;
541 	void 	(*tcpt_proc)(void *);
542 	callout_id_t   tcpt_tid;
543 } tcp_timer_t;
544 
545 static kmem_cache_t *tcp_timercache;
546 kmem_cache_t	*tcp_sack_info_cache;
547 kmem_cache_t	*tcp_iphc_cache;
548 
549 /*
550  * For scalability, we must not run a timer for every TCP connection
551  * in TIME_WAIT state.  To see why, consider (for time wait interval of
552  * 4 minutes):
553  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
554  *
555  * This list is ordered by time, so you need only delete from the head
556  * until you get to entries which aren't old enough to delete yet.
557  * The list consists of only the detached TIME_WAIT connections.
558  *
559  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
560  * becomes detached TIME_WAIT (either by changing the state and already
561  * being detached or the other way around). This means that the TIME_WAIT
562  * state can be extended (up to doubled) if the connection doesn't become
563  * detached for a long time.
564  *
565  * The list manipulations (including tcp_time_wait_next/prev)
566  * are protected by the tcp_time_wait_lock. The content of the
567  * detached TIME_WAIT connections is protected by the normal perimeters.
568  *
569  * This list is per squeue and squeues are shared across the tcp_stack_t's.
570  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
571  * and conn_netstack.
572  * The tcp_t's that are added to tcp_free_list are disassociated and
573  * have NULL tcp_tcps and conn_netstack pointers.
574  */
575 typedef struct tcp_squeue_priv_s {
576 	kmutex_t	tcp_time_wait_lock;
577 	callout_id_t	tcp_time_wait_tid;
578 	tcp_t		*tcp_time_wait_head;
579 	tcp_t		*tcp_time_wait_tail;
580 	tcp_t		*tcp_free_list;
581 	uint_t		tcp_free_list_cnt;
582 } tcp_squeue_priv_t;
583 
584 /*
585  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
586  * Running it every 5 seconds seems to give the best results.
587  */
588 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
589 
590 /*
591  * To prevent memory hog, limit the number of entries in tcp_free_list
592  * to 1% of available memory / number of cpus
593  */
594 uint_t tcp_free_list_max_cnt = 0;
595 
596 #define	TCP_XMIT_LOWATER	4096
597 #define	TCP_XMIT_HIWATER	49152
598 #define	TCP_RECV_LOWATER	2048
599 #define	TCP_RECV_HIWATER	49152
600 
601 /*
602  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
603  */
604 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
605 
606 #define	TIDUSZ	4096	/* transport interface data unit size */
607 
608 /*
609  * Bind hash list size and has function.  It has to be a power of 2 for
610  * hashing.
611  */
612 #define	TCP_BIND_FANOUT_SIZE	512
613 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
614 /*
615  * Size of listen and acceptor hash list.  It has to be a power of 2 for
616  * hashing.
617  */
618 #define	TCP_FANOUT_SIZE		256
619 
620 #ifdef	_ILP32
621 #define	TCP_ACCEPTOR_HASH(accid)					\
622 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
623 #else
624 #define	TCP_ACCEPTOR_HASH(accid)					\
625 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
626 #endif	/* _ILP32 */
627 
628 #define	IP_ADDR_CACHE_SIZE	2048
629 #define	IP_ADDR_CACHE_HASH(faddr)					\
630 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
631 
632 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
633 #define	TCP_HSP_HASH_SIZE 256
634 
635 #define	TCP_HSP_HASH(addr)					\
636 	(((addr>>24) ^ (addr >>16) ^			\
637 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
638 
639 /*
640  * TCP options struct returned from tcp_parse_options.
641  */
642 typedef struct tcp_opt_s {
643 	uint32_t	tcp_opt_mss;
644 	uint32_t	tcp_opt_wscale;
645 	uint32_t	tcp_opt_ts_val;
646 	uint32_t	tcp_opt_ts_ecr;
647 	tcp_t		*tcp;
648 } tcp_opt_t;
649 
650 /*
651  * TCP option struct passing information b/w lisenter and eager.
652  */
653 struct tcp_options {
654 	uint_t			to_flags;
655 	ssize_t			to_boundif;	/* IPV6_BOUND_IF */
656 	sock_upper_handle_t	to_handle;
657 };
658 
659 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
660 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
661 #define	TCPOPT_UPPERHANDLE	0x00000004	/* set upper handle */
662 
663 /*
664  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
665  */
666 
667 #ifdef _BIG_ENDIAN
668 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
669 	(TCPOPT_TSTAMP << 8) | 10)
670 #else
671 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
672 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
673 #endif
674 
675 /*
676  * Flags returned from tcp_parse_options.
677  */
678 #define	TCP_OPT_MSS_PRESENT	1
679 #define	TCP_OPT_WSCALE_PRESENT	2
680 #define	TCP_OPT_TSTAMP_PRESENT	4
681 #define	TCP_OPT_SACK_OK_PRESENT	8
682 #define	TCP_OPT_SACK_PRESENT	16
683 
684 /* TCP option length */
685 #define	TCPOPT_NOP_LEN		1
686 #define	TCPOPT_MAXSEG_LEN	4
687 #define	TCPOPT_WS_LEN		3
688 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
689 #define	TCPOPT_TSTAMP_LEN	10
690 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
691 #define	TCPOPT_SACK_OK_LEN	2
692 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
693 #define	TCPOPT_REAL_SACK_LEN	4
694 #define	TCPOPT_MAX_SACK_LEN	36
695 #define	TCPOPT_HEADER_LEN	2
696 
697 /* TCP cwnd burst factor. */
698 #define	TCP_CWND_INFINITE	65535
699 #define	TCP_CWND_SS		3
700 #define	TCP_CWND_NORMAL		5
701 
702 /* Maximum TCP initial cwin (start/restart). */
703 #define	TCP_MAX_INIT_CWND	8
704 
705 /*
706  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
707  * either tcp_slow_start_initial or tcp_slow_start_after idle
708  * depending on the caller.  If the upper layer has not used the
709  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
710  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
711  * If the upper layer has changed set the tcp_init_cwnd, just use
712  * it to calculate the tcp_cwnd.
713  */
714 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
715 {									\
716 	if ((tcp)->tcp_init_cwnd == 0) {				\
717 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
718 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
719 	} else {							\
720 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
721 	}								\
722 	tcp->tcp_cwnd_cnt = 0;						\
723 }
724 
725 /* TCP Timer control structure */
726 typedef struct tcpt_s {
727 	pfv_t	tcpt_pfv;	/* The routine we are to call */
728 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
729 } tcpt_t;
730 
731 /* Host Specific Parameter structure */
732 typedef struct tcp_hsp {
733 	struct tcp_hsp	*tcp_hsp_next;
734 	in6_addr_t	tcp_hsp_addr_v6;
735 	in6_addr_t	tcp_hsp_subnet_v6;
736 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
737 	int32_t		tcp_hsp_sendspace;
738 	int32_t		tcp_hsp_recvspace;
739 	int32_t		tcp_hsp_tstamp;
740 } tcp_hsp_t;
741 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
742 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
743 
744 /*
745  * Functions called directly via squeue having a prototype of edesc_t.
746  */
747 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
748 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
749 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
750 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
751 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
752 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
753 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
754 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
755 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
756 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
757 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
758 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
759 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
760 
761 
762 /* Prototype for TCP functions */
763 static void	tcp_random_init(void);
764 int		tcp_random(void);
765 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
766 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
767 		    tcp_t *eager);
768 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
769 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
770     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
771     boolean_t user_specified);
772 static void	tcp_closei_local(tcp_t *tcp);
773 static void	tcp_close_detached(tcp_t *tcp);
774 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
775 			mblk_t *idmp, mblk_t **defermp);
776 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
777 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
778 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
779 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
780 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
781 		    uint32_t scope_id, cred_t *cr, pid_t pid);
782 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
783 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
784 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
785 static char	*tcp_display(tcp_t *tcp, char *, char);
786 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
787 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
788 static void	tcp_eager_unlink(tcp_t *tcp);
789 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
790 		    int unixerr);
791 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
792 		    int tlierr, int unixerr);
793 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
794 		    cred_t *cr);
795 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
796 		    char *value, caddr_t cp, cred_t *cr);
797 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
798 		    char *value, caddr_t cp, cred_t *cr);
799 static int	tcp_tpistate(tcp_t *tcp);
800 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
801     int caller_holds_lock);
802 static void	tcp_bind_hash_remove(tcp_t *tcp);
803 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
804 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
805 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
806 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
807 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
808 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
809 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
810 void		tcp_g_q_setup(tcp_stack_t *);
811 void		tcp_g_q_create(tcp_stack_t *);
812 void		tcp_g_q_destroy(tcp_stack_t *);
813 static int	tcp_header_init_ipv4(tcp_t *tcp);
814 static int	tcp_header_init_ipv6(tcp_t *tcp);
815 int		tcp_init(tcp_t *tcp, queue_t *q);
816 static int	tcp_init_values(tcp_t *tcp);
817 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
818 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
819 static void	tcp_ip_notify(tcp_t *tcp);
820 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
821 static void	tcp_iss_init(tcp_t *tcp);
822 static void	tcp_keepalive_killer(void *arg);
823 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
824 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
825 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
826 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
827 static boolean_t tcp_allow_connopt_set(int level, int name);
828 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
829 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
830 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
831 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
832 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
833 		    mblk_t *mblk);
834 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
835 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
836 		    uchar_t *ptr, uint_t len);
837 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
838 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
839     tcp_stack_t *);
840 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
841 		    caddr_t cp, cred_t *cr);
842 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
843 		    caddr_t cp, cred_t *cr);
844 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
845 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
846 		    caddr_t cp, cred_t *cr);
847 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
848 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
849 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
850 static void	tcp_reinit(tcp_t *tcp);
851 static void	tcp_reinit_values(tcp_t *tcp);
852 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
853 		    tcp_t *thisstream, cred_t *cr);
854 
855 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
856 static uint_t	tcp_rcv_drain(tcp_t *tcp);
857 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
858 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
859 static void	tcp_ss_rexmit(tcp_t *tcp);
860 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
861 static void	tcp_process_options(tcp_t *, tcph_t *);
862 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
863 static void	tcp_rsrv(queue_t *q);
864 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
865 static int	tcp_snmp_state(tcp_t *tcp);
866 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
867 		    cred_t *cr);
868 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
869 		    cred_t *cr);
870 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
871 		    cred_t *cr);
872 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
873 		    cred_t *cr);
874 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
875 		    cred_t *cr);
876 static void	tcp_timer(void *arg);
877 static void	tcp_timer_callback(void *);
878 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
879     boolean_t random);
880 static in_port_t tcp_get_next_priv_port(const tcp_t *);
881 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
882 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
883 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
884 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
885 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
886 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
887 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
888 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
889 		    const int num_sack_blk, int *usable, uint_t *snxt,
890 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
891 		    const int mdt_thres);
892 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
893 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
894 		    const int num_sack_blk, int *usable, uint_t *snxt,
895 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
896 		    const int mdt_thres);
897 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
898 		    int num_sack_blk);
899 static void	tcp_wsrv(queue_t *q);
900 static int	tcp_xmit_end(tcp_t *tcp);
901 static void	tcp_ack_timer(void *arg);
902 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
903 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
904 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
905 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
906 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
907 		    uint32_t ack, int ctl);
908 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
909 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
910 static int	setmaxps(queue_t *q, int maxpsz);
911 static void	tcp_set_rto(tcp_t *, time_t);
912 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
913 		    boolean_t, boolean_t);
914 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
915 		    boolean_t ipsec_mctl);
916 static int	tcp_build_hdrs(tcp_t *);
917 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
918 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
919 		    tcph_t *tcph);
920 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
921 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
922 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
923 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
924 		    const boolean_t, const uint32_t, const uint32_t,
925 		    const uint32_t, const uint32_t, tcp_stack_t *);
926 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
927 		    const uint_t, const uint_t, boolean_t *);
928 static mblk_t	*tcp_lso_info_mp(mblk_t *);
929 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
930 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
931 extern mblk_t	*tcp_timermp_alloc(int);
932 extern void	tcp_timermp_free(tcp_t *);
933 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
934 static void	tcp_stop_lingering(tcp_t *tcp);
935 static void	tcp_close_linger_timeout(void *arg);
936 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
937 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
938 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
939 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
940 static void	tcp_g_kstat_fini(kstat_t *);
941 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
942 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
943 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
944 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
945 static int	tcp_kstat_update(kstat_t *kp, int rw);
946 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
947 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
948 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
949 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
950 			tcph_t *tcph, mblk_t *idmp);
951 static int	tcp_squeue_switch(int);
952 
953 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
954 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
955 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
956 static int	tcp_tpi_close(queue_t *, int);
957 static int	tcpclose_accept(queue_t *);
958 
959 static void	tcp_squeue_add(squeue_t *);
960 static boolean_t tcp_zcopy_check(tcp_t *);
961 static void	tcp_zcopy_notify(tcp_t *);
962 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
963 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
964 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
965 
966 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
967 
968 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
969 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
970 
971 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
972 	    sock_upper_handle_t, cred_t *);
973 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
974 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int);
975 static int tcp_do_listen(conn_t *, int, cred_t *);
976 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
977     cred_t *, pid_t);
978 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
979     boolean_t);
980 static int tcp_do_unbind(conn_t *);
981 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
982     boolean_t);
983 
984 /*
985  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
986  *
987  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
988  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
989  * (defined in tcp.h) needs to be filled in and passed into the kernel
990  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
991  * structure contains the four-tuple of a TCP connection and a range of TCP
992  * states (specified by ac_start and ac_end). The use of wildcard addresses
993  * and ports is allowed. Connections with a matching four tuple and a state
994  * within the specified range will be aborted. The valid states for the
995  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
996  * inclusive.
997  *
998  * An application which has its connection aborted by this ioctl will receive
999  * an error that is dependent on the connection state at the time of the abort.
1000  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
1001  * though a RST packet has been received.  If the connection state is equal to
1002  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
1003  * and all resources associated with the connection will be freed.
1004  */
1005 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
1006 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
1007 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
1008 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
1009 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
1010 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
1011     boolean_t, tcp_stack_t *);
1012 
1013 static struct module_info tcp_rinfo =  {
1014 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
1015 };
1016 
1017 static struct module_info tcp_winfo =  {
1018 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
1019 };
1020 
1021 /*
1022  * Entry points for TCP as a device. The normal case which supports
1023  * the TCP functionality.
1024  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
1025  */
1026 struct qinit tcp_rinitv4 = {
1027 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, NULL, &tcp_rinfo
1028 };
1029 
1030 struct qinit tcp_rinitv6 = {
1031 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_tpi_close, NULL, &tcp_rinfo
1032 };
1033 
1034 struct qinit tcp_winit = {
1035 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1036 };
1037 
1038 /* Initial entry point for TCP in socket mode. */
1039 struct qinit tcp_sock_winit = {
1040 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1041 };
1042 
1043 /* TCP entry point during fallback */
1044 struct qinit tcp_fallback_sock_winit = {
1045 	(pfi_t)tcp_wput_fallback, NULL, NULL, NULL, NULL, &tcp_winfo
1046 };
1047 
1048 /*
1049  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1050  * an accept. Avoid allocating data structures since eager has already
1051  * been created.
1052  */
1053 struct qinit tcp_acceptor_rinit = {
1054 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1055 };
1056 
1057 struct qinit tcp_acceptor_winit = {
1058 	(pfi_t)tcp_tpi_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1059 };
1060 
1061 /*
1062  * Entry points for TCP loopback (read side only)
1063  * The open routine is only used for reopens, thus no need to
1064  * have a separate one for tcp_openv6.
1065  */
1066 struct qinit tcp_loopback_rinit = {
1067 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_tpi_close, (pfi_t)0,
1068 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1069 };
1070 
1071 /* For AF_INET aka /dev/tcp */
1072 struct streamtab tcpinfov4 = {
1073 	&tcp_rinitv4, &tcp_winit
1074 };
1075 
1076 /* For AF_INET6 aka /dev/tcp6 */
1077 struct streamtab tcpinfov6 = {
1078 	&tcp_rinitv6, &tcp_winit
1079 };
1080 
1081 sock_downcalls_t sock_tcp_downcalls;
1082 
1083 /*
1084  * Have to ensure that tcp_g_q_close is not done by an
1085  * interrupt thread.
1086  */
1087 static taskq_t *tcp_taskq;
1088 
1089 /* Setable only in /etc/system. Move to ndd? */
1090 boolean_t tcp_icmp_source_quench = B_FALSE;
1091 
1092 /*
1093  * Following assumes TPI alignment requirements stay along 32 bit
1094  * boundaries
1095  */
1096 #define	ROUNDUP32(x) \
1097 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1098 
1099 /* Template for response to info request. */
1100 static struct T_info_ack tcp_g_t_info_ack = {
1101 	T_INFO_ACK,		/* PRIM_type */
1102 	0,			/* TSDU_size */
1103 	T_INFINITE,		/* ETSDU_size */
1104 	T_INVALID,		/* CDATA_size */
1105 	T_INVALID,		/* DDATA_size */
1106 	sizeof (sin_t),		/* ADDR_size */
1107 	0,			/* OPT_size - not initialized here */
1108 	TIDUSZ,			/* TIDU_size */
1109 	T_COTS_ORD,		/* SERV_type */
1110 	TCPS_IDLE,		/* CURRENT_state */
1111 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1112 };
1113 
1114 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1115 	T_INFO_ACK,		/* PRIM_type */
1116 	0,			/* TSDU_size */
1117 	T_INFINITE,		/* ETSDU_size */
1118 	T_INVALID,		/* CDATA_size */
1119 	T_INVALID,		/* DDATA_size */
1120 	sizeof (sin6_t),	/* ADDR_size */
1121 	0,			/* OPT_size - not initialized here */
1122 	TIDUSZ,		/* TIDU_size */
1123 	T_COTS_ORD,		/* SERV_type */
1124 	TCPS_IDLE,		/* CURRENT_state */
1125 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1126 };
1127 
1128 #define	MS	1L
1129 #define	SECONDS	(1000 * MS)
1130 #define	MINUTES	(60 * SECONDS)
1131 #define	HOURS	(60 * MINUTES)
1132 #define	DAYS	(24 * HOURS)
1133 
1134 #define	PARAM_MAX (~(uint32_t)0)
1135 
1136 /* Max size IP datagram is 64k - 1 */
1137 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1138 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1139 /* Max of the above */
1140 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1141 
1142 /* Largest TCP port number */
1143 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1144 
1145 /*
1146  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1147  * layer header.  It has to be a multiple of 4.
1148  */
1149 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1150 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1151 
1152 /*
1153  * All of these are alterable, within the min/max values given, at run time.
1154  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1155  * per the TCP spec.
1156  */
1157 /* BEGIN CSTYLED */
1158 static tcpparam_t	lcl_tcp_param_arr[] = {
1159  /*min		max		value		name */
1160  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1161  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1162  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1163  { 1,		1024,		1,		"tcp_conn_req_min" },
1164  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1165  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1166  { 0,		10,		0,		"tcp_debug" },
1167  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1168  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1169  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1170  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1171  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1172  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1173  { 1,		255,		64,		"tcp_ipv4_ttl"},
1174  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1175  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1176  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1177  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1178  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1179  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1180  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1181  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1182  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1183  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1184  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1185  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1186  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1187  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1188  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1189  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1190  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1191  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1192  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1193  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1194  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1195  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1196  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1197 /*
1198  * Question:  What default value should I set for tcp_strong_iss?
1199  */
1200  { 0,		2,		1,		"tcp_strong_iss"},
1201  { 0,		65536,		20,		"tcp_rtt_updates"},
1202  { 0,		1,		1,		"tcp_wscale_always"},
1203  { 0,		1,		0,		"tcp_tstamp_always"},
1204  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1205  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1206  { 0,		16,		2,		"tcp_deferred_acks_max"},
1207  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1208  { 1,		4,		4,		"tcp_slow_start_initial"},
1209  { 0,		2,		2,		"tcp_sack_permitted"},
1210  { 0,		1,		1,		"tcp_compression_enabled"},
1211  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1212  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1213  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1214  { 0,		1,		0,		"tcp_rev_src_routes"},
1215  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1216  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1217  { 0,		16,		8,		"tcp_local_dacks_max"},
1218  { 0,		2,		1,		"tcp_ecn_permitted"},
1219  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1220  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1221  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1222  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1223  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1224 };
1225 /* END CSTYLED */
1226 
1227 /*
1228  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1229  * each header fragment in the header buffer.  Each parameter value has
1230  * to be a multiple of 4 (32-bit aligned).
1231  */
1232 static tcpparam_t lcl_tcp_mdt_head_param =
1233 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1234 static tcpparam_t lcl_tcp_mdt_tail_param =
1235 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1236 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1237 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1238 
1239 /*
1240  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1241  * the maximum number of payload buffers associated per Multidata.
1242  */
1243 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1244 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1245 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1246 
1247 /* Round up the value to the nearest mss. */
1248 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1249 
1250 /*
1251  * Set ECN capable transport (ECT) code point in IP header.
1252  *
1253  * Note that there are 2 ECT code points '01' and '10', which are called
1254  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1255  * point ECT(0) for TCP as described in RFC 2481.
1256  */
1257 #define	SET_ECT(tcp, iph) \
1258 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1259 		/* We need to clear the code point first. */ \
1260 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1261 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1262 	} else { \
1263 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1264 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1265 	}
1266 
1267 /*
1268  * The format argument to pass to tcp_display().
1269  * DISP_PORT_ONLY means that the returned string has only port info.
1270  * DISP_ADDR_AND_PORT means that the returned string also contains the
1271  * remote and local IP address.
1272  */
1273 #define	DISP_PORT_ONLY		1
1274 #define	DISP_ADDR_AND_PORT	2
1275 
1276 #define	NDD_TOO_QUICK_MSG \
1277 	"ndd get info rate too high for non-privileged users, try again " \
1278 	"later.\n"
1279 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1280 
1281 #define	IS_VMLOANED_MBLK(mp) \
1282 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1283 
1284 
1285 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1286 boolean_t tcp_mdt_chain = B_TRUE;
1287 
1288 /*
1289  * MDT threshold in the form of effective send MSS multiplier; we take
1290  * the MDT path if the amount of unsent data exceeds the threshold value
1291  * (default threshold is 1*SMSS).
1292  */
1293 uint_t tcp_mdt_smss_threshold = 1;
1294 
1295 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1296 
1297 /*
1298  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1299  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1300  * determined dynamically during tcp_adapt_ire(), which is the default.
1301  */
1302 boolean_t tcp_static_maxpsz = B_FALSE;
1303 
1304 /* Setable in /etc/system */
1305 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1306 uint32_t tcp_random_anon_port = 1;
1307 
1308 /*
1309  * To reach to an eager in Q0 which can be dropped due to an incoming
1310  * new SYN request when Q0 is full, a new doubly linked list is
1311  * introduced. This list allows to select an eager from Q0 in O(1) time.
1312  * This is needed to avoid spending too much time walking through the
1313  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1314  * this new list has to be a member of Q0.
1315  * This list is headed by listener's tcp_t. When the list is empty,
1316  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1317  * of listener's tcp_t point to listener's tcp_t itself.
1318  *
1319  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1320  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1321  * These macros do not affect the eager's membership to Q0.
1322  */
1323 
1324 
1325 #define	MAKE_DROPPABLE(listener, eager)					\
1326 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1327 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1328 		    = (eager);						\
1329 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1330 		(eager)->tcp_eager_next_drop_q0 =			\
1331 		    (listener)->tcp_eager_next_drop_q0;			\
1332 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1333 	}
1334 
1335 #define	MAKE_UNDROPPABLE(eager)						\
1336 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1337 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1338 		    = (eager)->tcp_eager_prev_drop_q0;			\
1339 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1340 		    = (eager)->tcp_eager_next_drop_q0;			\
1341 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1342 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1343 	}
1344 
1345 /*
1346  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1347  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1348  * data, TCP will not respond with an ACK.  RFC 793 requires that
1349  * TCP responds with an ACK for such a bogus ACK.  By not following
1350  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1351  * an attacker successfully spoofs an acceptable segment to our
1352  * peer; or when our peer is "confused."
1353  */
1354 uint32_t tcp_drop_ack_unsent_cnt = 10;
1355 
1356 /*
1357  * Hook functions to enable cluster networking
1358  * On non-clustered systems these vectors must always be NULL.
1359  */
1360 
1361 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1362 			    uint8_t *laddrp, in_port_t lport) = NULL;
1363 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1364 			    uint8_t *laddrp, in_port_t lport) = NULL;
1365 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1366 			    uint8_t *laddrp, in_port_t lport,
1367 			    uint8_t *faddrp, in_port_t fport) = NULL;
1368 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1369 			    uint8_t *laddrp, in_port_t lport,
1370 			    uint8_t *faddrp, in_port_t fport) = NULL;
1371 
1372 /*
1373  * The following are defined in ip.c
1374  */
1375 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1376 				uint8_t *laddrp);
1377 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1378 				uint8_t *laddrp, uint8_t *faddrp);
1379 
1380 #define	CL_INET_CONNECT(tcp)		{			\
1381 	if (cl_inet_connect != NULL) {				\
1382 		/*						\
1383 		 * Running in cluster mode - register active connection	\
1384 		 * information						\
1385 		 */							\
1386 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1387 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1388 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1389 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1390 				    (in_port_t)(tcp)->tcp_lport,	\
1391 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1392 				    (in_port_t)(tcp)->tcp_fport);	\
1393 			}						\
1394 		} else {						\
1395 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1396 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1397 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1398 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1399 				    (in_port_t)(tcp)->tcp_lport,	\
1400 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1401 				    (in_port_t)(tcp)->tcp_fport);	\
1402 			}						\
1403 		}							\
1404 	}								\
1405 }
1406 
1407 #define	CL_INET_DISCONNECT(tcp)	{				\
1408 	if (cl_inet_disconnect != NULL) {				\
1409 		/*							\
1410 		 * Running in cluster mode - deregister active		\
1411 		 * connection information				\
1412 		 */							\
1413 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1414 			if ((tcp)->tcp_ip_src != 0) {			\
1415 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1416 				    AF_INET,				\
1417 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1418 				    (in_port_t)(tcp)->tcp_lport,	\
1419 				    (uint8_t *)				\
1420 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1421 				    (in_port_t)(tcp)->tcp_fport);	\
1422 			}						\
1423 		} else {						\
1424 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1425 			    &(tcp)->tcp_ip_src_v6)) {			\
1426 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1427 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1428 				    (in_port_t)(tcp)->tcp_lport,	\
1429 				    (uint8_t *)				\
1430 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1431 				    (in_port_t)(tcp)->tcp_fport);	\
1432 			}						\
1433 		}							\
1434 	}								\
1435 }
1436 
1437 /*
1438  * Cluster networking hook for traversing current connection list.
1439  * This routine is used to extract the current list of live connections
1440  * which must continue to to be dispatched to this node.
1441  */
1442 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1443 
1444 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1445     void *arg, tcp_stack_t *tcps);
1446 
1447 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1448 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1449 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1450 	    ip6_t *, ip6h, int, 0);
1451 
1452 /*
1453  * Figure out the value of window scale opton.  Note that the rwnd is
1454  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1455  * We cannot find the scale value and then do a round up of tcp_rwnd
1456  * because the scale value may not be correct after that.
1457  *
1458  * Set the compiler flag to make this function inline.
1459  */
1460 static void
1461 tcp_set_ws_value(tcp_t *tcp)
1462 {
1463 	int i;
1464 	uint32_t rwnd = tcp->tcp_rwnd;
1465 
1466 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1467 	    i++, rwnd >>= 1)
1468 		;
1469 	tcp->tcp_rcv_ws = i;
1470 }
1471 
1472 /*
1473  * Remove a connection from the list of detached TIME_WAIT connections.
1474  * It returns B_FALSE if it can't remove the connection from the list
1475  * as the connection has already been removed from the list due to an
1476  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1477  */
1478 static boolean_t
1479 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1480 {
1481 	boolean_t	locked = B_FALSE;
1482 
1483 	if (tcp_time_wait == NULL) {
1484 		tcp_time_wait = *((tcp_squeue_priv_t **)
1485 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1486 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1487 		locked = B_TRUE;
1488 	} else {
1489 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1490 	}
1491 
1492 	if (tcp->tcp_time_wait_expire == 0) {
1493 		ASSERT(tcp->tcp_time_wait_next == NULL);
1494 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1495 		if (locked)
1496 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1497 		return (B_FALSE);
1498 	}
1499 	ASSERT(TCP_IS_DETACHED(tcp));
1500 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1501 
1502 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1503 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1504 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1505 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1506 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1507 			    NULL;
1508 		} else {
1509 			tcp_time_wait->tcp_time_wait_tail = NULL;
1510 		}
1511 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1512 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1513 		ASSERT(tcp->tcp_time_wait_next == NULL);
1514 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1515 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1516 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1517 	} else {
1518 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1519 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1520 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1521 		    tcp->tcp_time_wait_next;
1522 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1523 		    tcp->tcp_time_wait_prev;
1524 	}
1525 	tcp->tcp_time_wait_next = NULL;
1526 	tcp->tcp_time_wait_prev = NULL;
1527 	tcp->tcp_time_wait_expire = 0;
1528 
1529 	if (locked)
1530 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1531 	return (B_TRUE);
1532 }
1533 
1534 /*
1535  * Add a connection to the list of detached TIME_WAIT connections
1536  * and set its time to expire.
1537  */
1538 static void
1539 tcp_time_wait_append(tcp_t *tcp)
1540 {
1541 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1542 	tcp_squeue_priv_t *tcp_time_wait =
1543 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1544 	    SQPRIVATE_TCP));
1545 
1546 	tcp_timers_stop(tcp);
1547 
1548 	/* Freed above */
1549 	ASSERT(tcp->tcp_timer_tid == 0);
1550 	ASSERT(tcp->tcp_ack_tid == 0);
1551 
1552 	/* must have happened at the time of detaching the tcp */
1553 	ASSERT(tcp->tcp_ptpahn == NULL);
1554 	ASSERT(tcp->tcp_flow_stopped == 0);
1555 	ASSERT(tcp->tcp_time_wait_next == NULL);
1556 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1557 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1558 	ASSERT(tcp->tcp_listener == NULL);
1559 
1560 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1561 	/*
1562 	 * The value computed below in tcp->tcp_time_wait_expire may
1563 	 * appear negative or wrap around. That is ok since our
1564 	 * interest is only in the difference between the current lbolt
1565 	 * value and tcp->tcp_time_wait_expire. But the value should not
1566 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1567 	 * The corresponding comparison in tcp_time_wait_collector() uses
1568 	 * modular arithmetic.
1569 	 */
1570 	tcp->tcp_time_wait_expire +=
1571 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1572 	if (tcp->tcp_time_wait_expire == 0)
1573 		tcp->tcp_time_wait_expire = 1;
1574 
1575 	ASSERT(TCP_IS_DETACHED(tcp));
1576 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1577 	ASSERT(tcp->tcp_time_wait_next == NULL);
1578 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1579 	TCP_DBGSTAT(tcps, tcp_time_wait);
1580 
1581 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1582 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1583 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1584 		tcp_time_wait->tcp_time_wait_head = tcp;
1585 	} else {
1586 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1587 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1588 		    TCPS_TIME_WAIT);
1589 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1590 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1591 	}
1592 	tcp_time_wait->tcp_time_wait_tail = tcp;
1593 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1594 }
1595 
1596 /* ARGSUSED */
1597 void
1598 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1599 {
1600 	conn_t	*connp = (conn_t *)arg;
1601 	tcp_t	*tcp = connp->conn_tcp;
1602 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1603 
1604 	ASSERT(tcp != NULL);
1605 	if (tcp->tcp_state == TCPS_CLOSED) {
1606 		return;
1607 	}
1608 
1609 	ASSERT((tcp->tcp_family == AF_INET &&
1610 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1611 	    (tcp->tcp_family == AF_INET6 &&
1612 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1613 	    tcp->tcp_ipversion == IPV6_VERSION)));
1614 	ASSERT(!tcp->tcp_listener);
1615 
1616 	TCP_STAT(tcps, tcp_time_wait_reap);
1617 	ASSERT(TCP_IS_DETACHED(tcp));
1618 
1619 	/*
1620 	 * Because they have no upstream client to rebind or tcp_close()
1621 	 * them later, we axe the connection here and now.
1622 	 */
1623 	tcp_close_detached(tcp);
1624 }
1625 
1626 /*
1627  * Remove cached/latched IPsec references.
1628  */
1629 void
1630 tcp_ipsec_cleanup(tcp_t *tcp)
1631 {
1632 	conn_t		*connp = tcp->tcp_connp;
1633 
1634 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1635 
1636 	if (connp->conn_latch != NULL) {
1637 		IPLATCH_REFRELE(connp->conn_latch,
1638 		    connp->conn_netstack);
1639 		connp->conn_latch = NULL;
1640 	}
1641 	if (connp->conn_policy != NULL) {
1642 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1643 		connp->conn_policy = NULL;
1644 	}
1645 }
1646 
1647 /*
1648  * Cleaup before placing on free list.
1649  * Disassociate from the netstack/tcp_stack_t since the freelist
1650  * is per squeue and not per netstack.
1651  */
1652 void
1653 tcp_cleanup(tcp_t *tcp)
1654 {
1655 	mblk_t		*mp;
1656 	char		*tcp_iphc;
1657 	int		tcp_iphc_len;
1658 	int		tcp_hdr_grown;
1659 	tcp_sack_info_t	*tcp_sack_info;
1660 	conn_t		*connp = tcp->tcp_connp;
1661 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1662 	netstack_t	*ns = tcps->tcps_netstack;
1663 	mblk_t		*tcp_rsrv_mp;
1664 
1665 	tcp_bind_hash_remove(tcp);
1666 
1667 	/* Cleanup that which needs the netstack first */
1668 	tcp_ipsec_cleanup(tcp);
1669 
1670 	tcp_free(tcp);
1671 
1672 	/* Release any SSL context */
1673 	if (tcp->tcp_kssl_ent != NULL) {
1674 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1675 		tcp->tcp_kssl_ent = NULL;
1676 	}
1677 
1678 	if (tcp->tcp_kssl_ctx != NULL) {
1679 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1680 		tcp->tcp_kssl_ctx = NULL;
1681 	}
1682 	tcp->tcp_kssl_pending = B_FALSE;
1683 
1684 	conn_delete_ire(connp, NULL);
1685 
1686 	/*
1687 	 * Since we will bzero the entire structure, we need to
1688 	 * remove it and reinsert it in global hash list. We
1689 	 * know the walkers can't get to this conn because we
1690 	 * had set CONDEMNED flag earlier and checked reference
1691 	 * under conn_lock so walker won't pick it and when we
1692 	 * go the ipcl_globalhash_remove() below, no walker
1693 	 * can get to it.
1694 	 */
1695 	ipcl_globalhash_remove(connp);
1696 
1697 	/*
1698 	 * Now it is safe to decrement the reference counts.
1699 	 * This might be the last reference on the netstack and TCPS
1700 	 * in which case it will cause the tcp_g_q_close and
1701 	 * the freeing of the IP Instance.
1702 	 */
1703 	connp->conn_netstack = NULL;
1704 	netstack_rele(ns);
1705 	ASSERT(tcps != NULL);
1706 	tcp->tcp_tcps = NULL;
1707 	TCPS_REFRELE(tcps);
1708 
1709 	/* Save some state */
1710 	mp = tcp->tcp_timercache;
1711 
1712 	tcp_sack_info = tcp->tcp_sack_info;
1713 	tcp_iphc = tcp->tcp_iphc;
1714 	tcp_iphc_len = tcp->tcp_iphc_len;
1715 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1716 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1717 
1718 	if (connp->conn_cred != NULL) {
1719 		crfree(connp->conn_cred);
1720 		connp->conn_cred = NULL;
1721 	}
1722 	if (connp->conn_peercred != NULL) {
1723 		crfree(connp->conn_peercred);
1724 		connp->conn_peercred = NULL;
1725 	}
1726 	ipcl_conn_cleanup(connp);
1727 	connp->conn_flags = IPCL_TCPCONN;
1728 	bzero(tcp, sizeof (tcp_t));
1729 
1730 	/* restore the state */
1731 	tcp->tcp_timercache = mp;
1732 
1733 	tcp->tcp_sack_info = tcp_sack_info;
1734 	tcp->tcp_iphc = tcp_iphc;
1735 	tcp->tcp_iphc_len = tcp_iphc_len;
1736 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1737 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1738 
1739 	tcp->tcp_connp = connp;
1740 
1741 	ASSERT(connp->conn_tcp == tcp);
1742 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1743 	connp->conn_state_flags = CONN_INCIPIENT;
1744 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1745 	ASSERT(connp->conn_ref == 1);
1746 }
1747 
1748 /*
1749  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1750  * is done forwards from the head.
1751  * This walks all stack instances since
1752  * tcp_time_wait remains global across all stacks.
1753  */
1754 /* ARGSUSED */
1755 void
1756 tcp_time_wait_collector(void *arg)
1757 {
1758 	tcp_t *tcp;
1759 	clock_t now;
1760 	mblk_t *mp;
1761 	conn_t *connp;
1762 	kmutex_t *lock;
1763 	boolean_t removed;
1764 
1765 	squeue_t *sqp = (squeue_t *)arg;
1766 	tcp_squeue_priv_t *tcp_time_wait =
1767 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1768 
1769 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1770 	tcp_time_wait->tcp_time_wait_tid = 0;
1771 
1772 	if (tcp_time_wait->tcp_free_list != NULL &&
1773 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1774 		TCP_G_STAT(tcp_freelist_cleanup);
1775 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1776 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1777 			tcp->tcp_time_wait_next = NULL;
1778 			tcp_time_wait->tcp_free_list_cnt--;
1779 			ASSERT(tcp->tcp_tcps == NULL);
1780 			CONN_DEC_REF(tcp->tcp_connp);
1781 		}
1782 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1783 	}
1784 
1785 	/*
1786 	 * In order to reap time waits reliably, we should use a
1787 	 * source of time that is not adjustable by the user -- hence
1788 	 * the call to ddi_get_lbolt().
1789 	 */
1790 	now = ddi_get_lbolt();
1791 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1792 		/*
1793 		 * Compare times using modular arithmetic, since
1794 		 * lbolt can wrapover.
1795 		 */
1796 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1797 			break;
1798 		}
1799 
1800 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1801 		ASSERT(removed);
1802 
1803 		connp = tcp->tcp_connp;
1804 		ASSERT(connp->conn_fanout != NULL);
1805 		lock = &connp->conn_fanout->connf_lock;
1806 		/*
1807 		 * This is essentially a TW reclaim fast path optimization for
1808 		 * performance where the timewait collector checks under the
1809 		 * fanout lock (so that no one else can get access to the
1810 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1811 		 * the classifier hash list. If ref count is indeed 2, we can
1812 		 * just remove the conn under the fanout lock and avoid
1813 		 * cleaning up the conn under the squeue, provided that
1814 		 * clustering callbacks are not enabled. If clustering is
1815 		 * enabled, we need to make the clustering callback before
1816 		 * setting the CONDEMNED flag and after dropping all locks and
1817 		 * so we forego this optimization and fall back to the slow
1818 		 * path. Also please see the comments in tcp_closei_local
1819 		 * regarding the refcnt logic.
1820 		 *
1821 		 * Since we are holding the tcp_time_wait_lock, its better
1822 		 * not to block on the fanout_lock because other connections
1823 		 * can't add themselves to time_wait list. So we do a
1824 		 * tryenter instead of mutex_enter.
1825 		 */
1826 		if (mutex_tryenter(lock)) {
1827 			mutex_enter(&connp->conn_lock);
1828 			if ((connp->conn_ref == 2) &&
1829 			    (cl_inet_disconnect == NULL)) {
1830 				ipcl_hash_remove_locked(connp,
1831 				    connp->conn_fanout);
1832 				/*
1833 				 * Set the CONDEMNED flag now itself so that
1834 				 * the refcnt cannot increase due to any
1835 				 * walker. But we have still not cleaned up
1836 				 * conn_ire_cache. This is still ok since
1837 				 * we are going to clean it up in tcp_cleanup
1838 				 * immediately and any interface unplumb
1839 				 * thread will wait till the ire is blown away
1840 				 */
1841 				connp->conn_state_flags |= CONN_CONDEMNED;
1842 				mutex_exit(lock);
1843 				mutex_exit(&connp->conn_lock);
1844 				if (tcp_time_wait->tcp_free_list_cnt <
1845 				    tcp_free_list_max_cnt) {
1846 					/* Add to head of tcp_free_list */
1847 					mutex_exit(
1848 					    &tcp_time_wait->tcp_time_wait_lock);
1849 					tcp_cleanup(tcp);
1850 					ASSERT(connp->conn_latch == NULL);
1851 					ASSERT(connp->conn_policy == NULL);
1852 					ASSERT(tcp->tcp_tcps == NULL);
1853 					ASSERT(connp->conn_netstack == NULL);
1854 
1855 					mutex_enter(
1856 					    &tcp_time_wait->tcp_time_wait_lock);
1857 					tcp->tcp_time_wait_next =
1858 					    tcp_time_wait->tcp_free_list;
1859 					tcp_time_wait->tcp_free_list = tcp;
1860 					tcp_time_wait->tcp_free_list_cnt++;
1861 					continue;
1862 				} else {
1863 					/* Do not add to tcp_free_list */
1864 					mutex_exit(
1865 					    &tcp_time_wait->tcp_time_wait_lock);
1866 					tcp_bind_hash_remove(tcp);
1867 					conn_delete_ire(tcp->tcp_connp, NULL);
1868 					tcp_ipsec_cleanup(tcp);
1869 					CONN_DEC_REF(tcp->tcp_connp);
1870 				}
1871 			} else {
1872 				CONN_INC_REF_LOCKED(connp);
1873 				mutex_exit(lock);
1874 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1875 				mutex_exit(&connp->conn_lock);
1876 				/*
1877 				 * We can reuse the closemp here since conn has
1878 				 * detached (otherwise we wouldn't even be in
1879 				 * time_wait list). tcp_closemp_used can safely
1880 				 * be changed without taking a lock as no other
1881 				 * thread can concurrently access it at this
1882 				 * point in the connection lifecycle.
1883 				 */
1884 
1885 				if (tcp->tcp_closemp.b_prev == NULL)
1886 					tcp->tcp_closemp_used = B_TRUE;
1887 				else
1888 					cmn_err(CE_PANIC,
1889 					    "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_ENTER_ONE(connp->conn_sqp, mp,
1897 				    tcp_timewait_output, connp,
1898 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1899 			}
1900 		} else {
1901 			mutex_enter(&connp->conn_lock);
1902 			CONN_INC_REF_LOCKED(connp);
1903 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1904 			mutex_exit(&connp->conn_lock);
1905 			/*
1906 			 * We can reuse the closemp here since conn has
1907 			 * detached (otherwise we wouldn't even be in
1908 			 * time_wait list). tcp_closemp_used can safely
1909 			 * be changed without taking a lock as no other
1910 			 * thread can concurrently access it at this
1911 			 * point in the connection lifecycle.
1912 			 */
1913 
1914 			if (tcp->tcp_closemp.b_prev == NULL)
1915 				tcp->tcp_closemp_used = B_TRUE;
1916 			else
1917 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1918 				    "concurrent use of tcp_closemp: "
1919 				    "connp %p tcp %p\n", (void *)connp,
1920 				    (void *)tcp);
1921 
1922 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1923 			mp = &tcp->tcp_closemp;
1924 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1925 			    tcp_timewait_output, connp,
1926 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1927 		}
1928 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1929 	}
1930 
1931 	if (tcp_time_wait->tcp_free_list != NULL)
1932 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1933 
1934 	tcp_time_wait->tcp_time_wait_tid =
1935 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1936 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1937 	    CALLOUT_FLAG_ROUNDUP);
1938 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1939 }
1940 
1941 /*
1942  * Reply to a clients T_CONN_RES TPI message. This function
1943  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1944  * on the acceptor STREAM and processed in tcp_wput_accept().
1945  * Read the block comment on top of tcp_conn_request().
1946  */
1947 static void
1948 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1949 {
1950 	tcp_t	*acceptor;
1951 	tcp_t	*eager;
1952 	tcp_t   *tcp;
1953 	struct T_conn_res	*tcr;
1954 	t_uscalar_t	acceptor_id;
1955 	t_scalar_t	seqnum;
1956 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1957 	struct tcp_options *tcpopt;
1958 	mblk_t	*ok_mp;
1959 	mblk_t	*mp1;
1960 	tcp_stack_t	*tcps = listener->tcp_tcps;
1961 
1962 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1963 		tcp_err_ack(listener, mp, TPROTO, 0);
1964 		return;
1965 	}
1966 	tcr = (struct T_conn_res *)mp->b_rptr;
1967 
1968 	/*
1969 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1970 	 * read side queue of the streams device underneath us i.e. the
1971 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1972 	 * look it up in the queue_hash.  Under LP64 it sends down the
1973 	 * minor_t of the accepting endpoint.
1974 	 *
1975 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1976 	 * fanout hash lock is held.
1977 	 * This prevents any thread from entering the acceptor queue from
1978 	 * below (since it has not been hard bound yet i.e. any inbound
1979 	 * packets will arrive on the listener or default tcp queue and
1980 	 * go through tcp_lookup).
1981 	 * The CONN_INC_REF will prevent the acceptor from closing.
1982 	 *
1983 	 * XXX It is still possible for a tli application to send down data
1984 	 * on the accepting stream while another thread calls t_accept.
1985 	 * This should not be a problem for well-behaved applications since
1986 	 * the T_OK_ACK is sent after the queue swapping is completed.
1987 	 *
1988 	 * If the accepting fd is the same as the listening fd, avoid
1989 	 * queue hash lookup since that will return an eager listener in a
1990 	 * already established state.
1991 	 */
1992 	acceptor_id = tcr->ACCEPTOR_id;
1993 	mutex_enter(&listener->tcp_eager_lock);
1994 	if (listener->tcp_acceptor_id == acceptor_id) {
1995 		eager = listener->tcp_eager_next_q;
1996 		/* only count how many T_CONN_INDs so don't count q0 */
1997 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1998 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1999 			mutex_exit(&listener->tcp_eager_lock);
2000 			tcp_err_ack(listener, mp, TBADF, 0);
2001 			return;
2002 		}
2003 		if (listener->tcp_conn_req_cnt_q0 != 0) {
2004 			/* Throw away all the eagers on q0. */
2005 			tcp_eager_cleanup(listener, 1);
2006 		}
2007 		if (listener->tcp_syn_defense) {
2008 			listener->tcp_syn_defense = B_FALSE;
2009 			if (listener->tcp_ip_addr_cache != NULL) {
2010 				kmem_free(listener->tcp_ip_addr_cache,
2011 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
2012 				listener->tcp_ip_addr_cache = NULL;
2013 			}
2014 		}
2015 		/*
2016 		 * Transfer tcp_conn_req_max to the eager so that when
2017 		 * a disconnect occurs we can revert the endpoint to the
2018 		 * listen state.
2019 		 */
2020 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2021 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2022 		/*
2023 		 * Get a reference on the acceptor just like the
2024 		 * tcp_acceptor_hash_lookup below.
2025 		 */
2026 		acceptor = listener;
2027 		CONN_INC_REF(acceptor->tcp_connp);
2028 	} else {
2029 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
2030 		if (acceptor == NULL) {
2031 			if (listener->tcp_debug) {
2032 				(void) strlog(TCP_MOD_ID, 0, 1,
2033 				    SL_ERROR|SL_TRACE,
2034 				    "tcp_accept: did not find acceptor 0x%x\n",
2035 				    acceptor_id);
2036 			}
2037 			mutex_exit(&listener->tcp_eager_lock);
2038 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2039 			return;
2040 		}
2041 		/*
2042 		 * Verify acceptor state. The acceptable states for an acceptor
2043 		 * include TCPS_IDLE and TCPS_BOUND.
2044 		 */
2045 		switch (acceptor->tcp_state) {
2046 		case TCPS_IDLE:
2047 			/* FALLTHRU */
2048 		case TCPS_BOUND:
2049 			break;
2050 		default:
2051 			CONN_DEC_REF(acceptor->tcp_connp);
2052 			mutex_exit(&listener->tcp_eager_lock);
2053 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2054 			return;
2055 		}
2056 	}
2057 
2058 	/* The listener must be in TCPS_LISTEN */
2059 	if (listener->tcp_state != TCPS_LISTEN) {
2060 		CONN_DEC_REF(acceptor->tcp_connp);
2061 		mutex_exit(&listener->tcp_eager_lock);
2062 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2063 		return;
2064 	}
2065 
2066 	/*
2067 	 * Rendezvous with an eager connection request packet hanging off
2068 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2069 	 * tcp structure when the connection packet arrived in
2070 	 * tcp_conn_request().
2071 	 */
2072 	seqnum = tcr->SEQ_number;
2073 	eager = listener;
2074 	do {
2075 		eager = eager->tcp_eager_next_q;
2076 		if (eager == NULL) {
2077 			CONN_DEC_REF(acceptor->tcp_connp);
2078 			mutex_exit(&listener->tcp_eager_lock);
2079 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2080 			return;
2081 		}
2082 	} while (eager->tcp_conn_req_seqnum != seqnum);
2083 	mutex_exit(&listener->tcp_eager_lock);
2084 
2085 	/*
2086 	 * At this point, both acceptor and listener have 2 ref
2087 	 * that they begin with. Acceptor has one additional ref
2088 	 * we placed in lookup while listener has 3 additional
2089 	 * ref for being behind the squeue (tcp_accept() is
2090 	 * done on listener's squeue); being in classifier hash;
2091 	 * and eager's ref on listener.
2092 	 */
2093 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2094 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2095 
2096 	/*
2097 	 * The eager at this point is set in its own squeue and
2098 	 * could easily have been killed (tcp_accept_finish will
2099 	 * deal with that) because of a TH_RST so we can only
2100 	 * ASSERT for a single ref.
2101 	 */
2102 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2103 
2104 	/* Pre allocate the stroptions mblk also */
2105 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2106 	    sizeof (struct T_conn_res)), BPRI_HI);
2107 	if (opt_mp == NULL) {
2108 		CONN_DEC_REF(acceptor->tcp_connp);
2109 		CONN_DEC_REF(eager->tcp_connp);
2110 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2111 		return;
2112 	}
2113 	DB_TYPE(opt_mp) = M_SETOPTS;
2114 	opt_mp->b_wptr += sizeof (struct tcp_options);
2115 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2116 	tcpopt->to_flags = 0;
2117 
2118 	/*
2119 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2120 	 * from listener to acceptor.
2121 	 */
2122 	if (listener->tcp_bound_if != 0) {
2123 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2124 		tcpopt->to_boundif = listener->tcp_bound_if;
2125 	}
2126 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2127 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2128 	}
2129 
2130 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2131 	if ((mp1 = copymsg(mp)) == NULL) {
2132 		CONN_DEC_REF(acceptor->tcp_connp);
2133 		CONN_DEC_REF(eager->tcp_connp);
2134 		freemsg(opt_mp);
2135 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2136 		return;
2137 	}
2138 
2139 	tcr = (struct T_conn_res *)mp1->b_rptr;
2140 
2141 	/*
2142 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2143 	 * which allocates a larger mblk and appends the new
2144 	 * local address to the ok_ack.  The address is copied by
2145 	 * soaccept() for getsockname().
2146 	 */
2147 	{
2148 		int extra;
2149 
2150 		extra = (eager->tcp_family == AF_INET) ?
2151 		    sizeof (sin_t) : sizeof (sin6_t);
2152 
2153 		/*
2154 		 * Try to re-use mp, if possible.  Otherwise, allocate
2155 		 * an mblk and return it as ok_mp.  In any case, mp
2156 		 * is no longer usable upon return.
2157 		 */
2158 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2159 			CONN_DEC_REF(acceptor->tcp_connp);
2160 			CONN_DEC_REF(eager->tcp_connp);
2161 			freemsg(opt_mp);
2162 			/* Original mp has been freed by now, so use mp1 */
2163 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2164 			return;
2165 		}
2166 
2167 		mp = NULL;	/* We should never use mp after this point */
2168 
2169 		switch (extra) {
2170 		case sizeof (sin_t): {
2171 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2172 
2173 				ok_mp->b_wptr += extra;
2174 				sin->sin_family = AF_INET;
2175 				sin->sin_port = eager->tcp_lport;
2176 				sin->sin_addr.s_addr =
2177 				    eager->tcp_ipha->ipha_src;
2178 				break;
2179 			}
2180 		case sizeof (sin6_t): {
2181 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2182 
2183 				ok_mp->b_wptr += extra;
2184 				sin6->sin6_family = AF_INET6;
2185 				sin6->sin6_port = eager->tcp_lport;
2186 				if (eager->tcp_ipversion == IPV4_VERSION) {
2187 					sin6->sin6_flowinfo = 0;
2188 					IN6_IPADDR_TO_V4MAPPED(
2189 					    eager->tcp_ipha->ipha_src,
2190 					    &sin6->sin6_addr);
2191 				} else {
2192 					ASSERT(eager->tcp_ip6h != NULL);
2193 					sin6->sin6_flowinfo =
2194 					    eager->tcp_ip6h->ip6_vcf &
2195 					    ~IPV6_VERS_AND_FLOW_MASK;
2196 					sin6->sin6_addr =
2197 					    eager->tcp_ip6h->ip6_src;
2198 				}
2199 				sin6->sin6_scope_id = 0;
2200 				sin6->__sin6_src_id = 0;
2201 				break;
2202 			}
2203 		default:
2204 			break;
2205 		}
2206 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2207 	}
2208 
2209 	/*
2210 	 * If there are no options we know that the T_CONN_RES will
2211 	 * succeed. However, we can't send the T_OK_ACK upstream until
2212 	 * the tcp_accept_swap is done since it would be dangerous to
2213 	 * let the application start using the new fd prior to the swap.
2214 	 */
2215 	tcp_accept_swap(listener, acceptor, eager);
2216 
2217 	/*
2218 	 * tcp_accept_swap unlinks eager from listener but does not drop
2219 	 * the eager's reference on the listener.
2220 	 */
2221 	ASSERT(eager->tcp_listener == NULL);
2222 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2223 
2224 	/*
2225 	 * The eager is now associated with its own queue. Insert in
2226 	 * the hash so that the connection can be reused for a future
2227 	 * T_CONN_RES.
2228 	 */
2229 	tcp_acceptor_hash_insert(acceptor_id, eager);
2230 
2231 	/*
2232 	 * We now do the processing of options with T_CONN_RES.
2233 	 * We delay till now since we wanted to have queue to pass to
2234 	 * option processing routines that points back to the right
2235 	 * instance structure which does not happen until after
2236 	 * tcp_accept_swap().
2237 	 *
2238 	 * Note:
2239 	 * The sanity of the logic here assumes that whatever options
2240 	 * are appropriate to inherit from listner=>eager are done
2241 	 * before this point, and whatever were to be overridden (or not)
2242 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2243 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2244 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2245 	 * This may not be true at this point in time but can be fixed
2246 	 * independently. This option processing code starts with
2247 	 * the instantiated acceptor instance and the final queue at
2248 	 * this point.
2249 	 */
2250 
2251 	if (tcr->OPT_length != 0) {
2252 		/* Options to process */
2253 		int t_error = 0;
2254 		int sys_error = 0;
2255 		int do_disconnect = 0;
2256 
2257 		if (tcp_conprim_opt_process(eager, mp1,
2258 		    &do_disconnect, &t_error, &sys_error) < 0) {
2259 			eager->tcp_accept_error = 1;
2260 			if (do_disconnect) {
2261 				/*
2262 				 * An option failed which does not allow
2263 				 * connection to be accepted.
2264 				 *
2265 				 * We allow T_CONN_RES to succeed and
2266 				 * put a T_DISCON_IND on the eager queue.
2267 				 */
2268 				ASSERT(t_error == 0 && sys_error == 0);
2269 				eager->tcp_send_discon_ind = 1;
2270 			} else {
2271 				ASSERT(t_error != 0);
2272 				freemsg(ok_mp);
2273 				/*
2274 				 * Original mp was either freed or set
2275 				 * to ok_mp above, so use mp1 instead.
2276 				 */
2277 				tcp_err_ack(listener, mp1, t_error, sys_error);
2278 				goto finish;
2279 			}
2280 		}
2281 		/*
2282 		 * Most likely success in setting options (except if
2283 		 * eager->tcp_send_discon_ind set).
2284 		 * mp1 option buffer represented by OPT_length/offset
2285 		 * potentially modified and contains results of setting
2286 		 * options at this point
2287 		 */
2288 	}
2289 
2290 	/* We no longer need mp1, since all options processing has passed */
2291 	freemsg(mp1);
2292 
2293 	putnext(listener->tcp_rq, ok_mp);
2294 
2295 	mutex_enter(&listener->tcp_eager_lock);
2296 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2297 		tcp_t	*tail;
2298 		mblk_t	*conn_ind;
2299 
2300 		/*
2301 		 * This path should not be executed if listener and
2302 		 * acceptor streams are the same.
2303 		 */
2304 		ASSERT(listener != acceptor);
2305 
2306 		tcp = listener->tcp_eager_prev_q0;
2307 		/*
2308 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2309 		 * deferred T_conn_ind queue. We need to get to the head of
2310 		 * the queue in order to send up T_conn_ind the same order as
2311 		 * how the 3WHS is completed.
2312 		 */
2313 		while (tcp != listener) {
2314 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2315 				break;
2316 			else
2317 				tcp = tcp->tcp_eager_prev_q0;
2318 		}
2319 		ASSERT(tcp != listener);
2320 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2321 		ASSERT(conn_ind != NULL);
2322 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2323 
2324 		/* Move from q0 to q */
2325 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2326 		listener->tcp_conn_req_cnt_q0--;
2327 		listener->tcp_conn_req_cnt_q++;
2328 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2329 		    tcp->tcp_eager_prev_q0;
2330 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2331 		    tcp->tcp_eager_next_q0;
2332 		tcp->tcp_eager_prev_q0 = NULL;
2333 		tcp->tcp_eager_next_q0 = NULL;
2334 		tcp->tcp_conn_def_q0 = B_FALSE;
2335 
2336 		/* Make sure the tcp isn't in the list of droppables */
2337 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2338 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2339 
2340 		/*
2341 		 * Insert at end of the queue because sockfs sends
2342 		 * down T_CONN_RES in chronological order. Leaving
2343 		 * the older conn indications at front of the queue
2344 		 * helps reducing search time.
2345 		 */
2346 		tail = listener->tcp_eager_last_q;
2347 		if (tail != NULL)
2348 			tail->tcp_eager_next_q = tcp;
2349 		else
2350 			listener->tcp_eager_next_q = tcp;
2351 		listener->tcp_eager_last_q = tcp;
2352 		tcp->tcp_eager_next_q = NULL;
2353 		mutex_exit(&listener->tcp_eager_lock);
2354 		putnext(tcp->tcp_rq, conn_ind);
2355 	} else {
2356 		mutex_exit(&listener->tcp_eager_lock);
2357 	}
2358 
2359 	/*
2360 	 * Done with the acceptor - free it
2361 	 *
2362 	 * Note: from this point on, no access to listener should be made
2363 	 * as listener can be equal to acceptor.
2364 	 */
2365 finish:
2366 	ASSERT(acceptor->tcp_detached);
2367 	ASSERT(tcps->tcps_g_q != NULL);
2368 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2369 	acceptor->tcp_rq = tcps->tcps_g_q;
2370 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2371 	(void) tcp_clean_death(acceptor, 0, 2);
2372 	CONN_DEC_REF(acceptor->tcp_connp);
2373 
2374 	/*
2375 	 * In case we already received a FIN we have to make tcp_rput send
2376 	 * the ordrel_ind. This will also send up a window update if the window
2377 	 * has opened up.
2378 	 *
2379 	 * In the normal case of a successful connection acceptance
2380 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2381 	 * indication that this was just accepted. This tells tcp_rput to
2382 	 * pass up any data queued in tcp_rcv_list.
2383 	 *
2384 	 * In the fringe case where options sent with T_CONN_RES failed and
2385 	 * we required, we would be indicating a T_DISCON_IND to blow
2386 	 * away this connection.
2387 	 */
2388 
2389 	/*
2390 	 * XXX: we currently have a problem if XTI application closes the
2391 	 * acceptor stream in between. This problem exists in on10-gate also
2392 	 * and is well know but nothing can be done short of major rewrite
2393 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2394 	 * eager same squeue as listener (we can distinguish non socket
2395 	 * listeners at the time of handling a SYN in tcp_conn_request)
2396 	 * and do most of the work that tcp_accept_finish does here itself
2397 	 * and then get behind the acceptor squeue to access the acceptor
2398 	 * queue.
2399 	 */
2400 	/*
2401 	 * We already have a ref on tcp so no need to do one before squeue_enter
2402 	 */
2403 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2404 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2405 }
2406 
2407 /*
2408  * Swap information between the eager and acceptor for a TLI/XTI client.
2409  * The sockfs accept is done on the acceptor stream and control goes
2410  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2411  * called. In either case, both the eager and listener are in their own
2412  * perimeter (squeue) and the code has to deal with potential race.
2413  *
2414  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2415  */
2416 static void
2417 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2418 {
2419 	conn_t	*econnp, *aconnp;
2420 
2421 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2422 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2423 	ASSERT(!eager->tcp_hard_bound);
2424 	ASSERT(!TCP_IS_SOCKET(acceptor));
2425 	ASSERT(!TCP_IS_SOCKET(eager));
2426 	ASSERT(!TCP_IS_SOCKET(listener));
2427 
2428 	acceptor->tcp_detached = B_TRUE;
2429 	/*
2430 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2431 	 * the acceptor id.
2432 	 */
2433 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2434 
2435 	/* remove eager from listen list... */
2436 	mutex_enter(&listener->tcp_eager_lock);
2437 	tcp_eager_unlink(eager);
2438 	ASSERT(eager->tcp_eager_next_q == NULL &&
2439 	    eager->tcp_eager_last_q == NULL);
2440 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2441 	    eager->tcp_eager_prev_q0 == NULL);
2442 	mutex_exit(&listener->tcp_eager_lock);
2443 	eager->tcp_rq = acceptor->tcp_rq;
2444 	eager->tcp_wq = acceptor->tcp_wq;
2445 
2446 	econnp = eager->tcp_connp;
2447 	aconnp = acceptor->tcp_connp;
2448 
2449 	eager->tcp_rq->q_ptr = econnp;
2450 	eager->tcp_wq->q_ptr = econnp;
2451 
2452 	/*
2453 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2454 	 * which might be a different squeue from our peer TCP instance.
2455 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2456 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2457 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2458 	 * above reach global visibility prior to the clearing of tcp_detached.
2459 	 */
2460 	membar_producer();
2461 	eager->tcp_detached = B_FALSE;
2462 
2463 	ASSERT(eager->tcp_ack_tid == 0);
2464 
2465 	econnp->conn_dev = aconnp->conn_dev;
2466 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2467 	ASSERT(econnp->conn_minor_arena != NULL);
2468 	if (eager->tcp_cred != NULL)
2469 		crfree(eager->tcp_cred);
2470 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2471 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2472 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2473 
2474 	aconnp->conn_cred = NULL;
2475 
2476 	econnp->conn_zoneid = aconnp->conn_zoneid;
2477 	econnp->conn_allzones = aconnp->conn_allzones;
2478 
2479 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2480 	aconnp->conn_mac_exempt = B_FALSE;
2481 
2482 	ASSERT(aconnp->conn_peercred == NULL);
2483 
2484 	/* Do the IPC initialization */
2485 	CONN_INC_REF(econnp);
2486 
2487 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2488 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2489 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2490 
2491 	/* Done with old IPC. Drop its ref on its connp */
2492 	CONN_DEC_REF(aconnp);
2493 }
2494 
2495 
2496 /*
2497  * Adapt to the information, such as rtt and rtt_sd, provided from the
2498  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2499  *
2500  * Checks for multicast and broadcast destination address.
2501  * Returns zero on failure; non-zero if ok.
2502  *
2503  * Note that the MSS calculation here is based on the info given in
2504  * the IRE.  We do not do any calculation based on TCP options.  They
2505  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2506  * knows which options to use.
2507  *
2508  * Note on how TCP gets its parameters for a connection.
2509  *
2510  * When a tcp_t structure is allocated, it gets all the default parameters.
2511  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2512  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2513  * default.
2514  *
2515  * An incoming SYN with a multicast or broadcast destination address, is dropped
2516  * in 1 of 2 places.
2517  *
2518  * 1. If the packet was received over the wire it is dropped in
2519  * ip_rput_process_broadcast()
2520  *
2521  * 2. If the packet was received through internal IP loopback, i.e. the packet
2522  * was generated and received on the same machine, it is dropped in
2523  * ip_wput_local()
2524  *
2525  * An incoming SYN with a multicast or broadcast source address is always
2526  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2527  * reject an attempt to connect to a broadcast or multicast (destination)
2528  * address.
2529  */
2530 static int
2531 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2532 {
2533 	tcp_hsp_t	*hsp;
2534 	ire_t		*ire;
2535 	ire_t		*sire = NULL;
2536 	iulp_t		*ire_uinfo = NULL;
2537 	uint32_t	mss_max;
2538 	uint32_t	mss;
2539 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2540 	conn_t		*connp = tcp->tcp_connp;
2541 	boolean_t	ire_cacheable = B_FALSE;
2542 	zoneid_t	zoneid = connp->conn_zoneid;
2543 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2544 	    MATCH_IRE_SECATTR;
2545 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2546 	ill_t		*ill = NULL;
2547 	boolean_t	incoming = (ire_mp == NULL);
2548 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2549 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2550 
2551 	ASSERT(connp->conn_ire_cache == NULL);
2552 
2553 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2554 
2555 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2556 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2557 			return (0);
2558 		}
2559 		/*
2560 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2561 		 * for the destination with the nexthop as gateway.
2562 		 * ire_ctable_lookup() is used because this particular
2563 		 * ire, if it exists, will be marked private.
2564 		 * If that is not available, use the interface ire
2565 		 * for the nexthop.
2566 		 *
2567 		 * TSol: tcp_update_label will detect label mismatches based
2568 		 * only on the destination's label, but that would not
2569 		 * detect label mismatches based on the security attributes
2570 		 * of routes or next hop gateway. Hence we need to pass the
2571 		 * label to ire_ftable_lookup below in order to locate the
2572 		 * right prefix (and/or) ire cache. Similarly we also need
2573 		 * pass the label to the ire_cache_lookup below to locate
2574 		 * the right ire that also matches on the label.
2575 		 */
2576 		if (tcp->tcp_connp->conn_nexthop_set) {
2577 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2578 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2579 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2580 			    ipst);
2581 			if (ire == NULL) {
2582 				ire = ire_ftable_lookup(
2583 				    tcp->tcp_connp->conn_nexthop_v4,
2584 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2585 				    tsl, match_flags, ipst);
2586 				if (ire == NULL)
2587 					return (0);
2588 			} else {
2589 				ire_uinfo = &ire->ire_uinfo;
2590 			}
2591 		} else {
2592 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2593 			    zoneid, tsl, ipst);
2594 			if (ire != NULL) {
2595 				ire_cacheable = B_TRUE;
2596 				ire_uinfo = (ire_mp != NULL) ?
2597 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2598 				    &ire->ire_uinfo;
2599 
2600 			} else {
2601 				if (ire_mp == NULL) {
2602 					ire = ire_ftable_lookup(
2603 					    tcp->tcp_connp->conn_rem,
2604 					    0, 0, 0, NULL, &sire, zoneid, 0,
2605 					    tsl, (MATCH_IRE_RECURSIVE |
2606 					    MATCH_IRE_DEFAULT), ipst);
2607 					if (ire == NULL)
2608 						return (0);
2609 					ire_uinfo = (sire != NULL) ?
2610 					    &sire->ire_uinfo :
2611 					    &ire->ire_uinfo;
2612 				} else {
2613 					ire = (ire_t *)ire_mp->b_rptr;
2614 					ire_uinfo =
2615 					    &((ire_t *)
2616 					    ire_mp->b_rptr)->ire_uinfo;
2617 				}
2618 			}
2619 		}
2620 		ASSERT(ire != NULL);
2621 
2622 		if ((ire->ire_src_addr == INADDR_ANY) ||
2623 		    (ire->ire_type & IRE_BROADCAST)) {
2624 			/*
2625 			 * ire->ire_mp is non null when ire_mp passed in is used
2626 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2627 			 */
2628 			if (ire->ire_mp == NULL)
2629 				ire_refrele(ire);
2630 			if (sire != NULL)
2631 				ire_refrele(sire);
2632 			return (0);
2633 		}
2634 
2635 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2636 			ipaddr_t src_addr;
2637 
2638 			/*
2639 			 * ip_bind_connected() has stored the correct source
2640 			 * address in conn_src.
2641 			 */
2642 			src_addr = tcp->tcp_connp->conn_src;
2643 			tcp->tcp_ipha->ipha_src = src_addr;
2644 			/*
2645 			 * Copy of the src addr. in tcp_t is needed
2646 			 * for the lookup funcs.
2647 			 */
2648 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2649 		}
2650 		/*
2651 		 * Set the fragment bit so that IP will tell us if the MTU
2652 		 * should change. IP tells us the latest setting of
2653 		 * ip_path_mtu_discovery through ire_frag_flag.
2654 		 */
2655 		if (ipst->ips_ip_path_mtu_discovery) {
2656 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2657 			    htons(IPH_DF);
2658 		}
2659 		/*
2660 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2661 		 * for IP_NEXTHOP. No cache ire has been found for the
2662 		 * destination and we are working with the nexthop's
2663 		 * interface ire. Since we need to forward all packets
2664 		 * to the nexthop first, we "blindly" set tcp_localnet
2665 		 * to false, eventhough the destination may also be
2666 		 * onlink.
2667 		 */
2668 		if (ire_uinfo == NULL)
2669 			tcp->tcp_localnet = 0;
2670 		else
2671 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2672 	} else {
2673 		/*
2674 		 * For incoming connection ire_mp = NULL
2675 		 * For outgoing connection ire_mp != NULL
2676 		 * Technically we should check conn_incoming_ill
2677 		 * when ire_mp is NULL and conn_outgoing_ill when
2678 		 * ire_mp is non-NULL. But this is performance
2679 		 * critical path and for IPV*_BOUND_IF, outgoing
2680 		 * and incoming ill are always set to the same value.
2681 		 */
2682 		ill_t	*dst_ill = NULL;
2683 		ipif_t  *dst_ipif = NULL;
2684 
2685 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2686 
2687 		if (connp->conn_outgoing_ill != NULL) {
2688 			/* Outgoing or incoming path */
2689 			int   err;
2690 
2691 			dst_ill = conn_get_held_ill(connp,
2692 			    &connp->conn_outgoing_ill, &err);
2693 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2694 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2695 				return (0);
2696 			}
2697 			match_flags |= MATCH_IRE_ILL;
2698 			dst_ipif = dst_ill->ill_ipif;
2699 		}
2700 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2701 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2702 
2703 		if (ire != NULL) {
2704 			ire_cacheable = B_TRUE;
2705 			ire_uinfo = (ire_mp != NULL) ?
2706 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2707 			    &ire->ire_uinfo;
2708 		} else {
2709 			if (ire_mp == NULL) {
2710 				ire = ire_ftable_lookup_v6(
2711 				    &tcp->tcp_connp->conn_remv6,
2712 				    0, 0, 0, dst_ipif, &sire, zoneid,
2713 				    0, tsl, match_flags, ipst);
2714 				if (ire == NULL) {
2715 					if (dst_ill != NULL)
2716 						ill_refrele(dst_ill);
2717 					return (0);
2718 				}
2719 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2720 				    &ire->ire_uinfo;
2721 			} else {
2722 				ire = (ire_t *)ire_mp->b_rptr;
2723 				ire_uinfo =
2724 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2725 			}
2726 		}
2727 		if (dst_ill != NULL)
2728 			ill_refrele(dst_ill);
2729 
2730 		ASSERT(ire != NULL);
2731 		ASSERT(ire_uinfo != NULL);
2732 
2733 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2734 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2735 			/*
2736 			 * ire->ire_mp is non null when ire_mp passed in is used
2737 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2738 			 */
2739 			if (ire->ire_mp == NULL)
2740 				ire_refrele(ire);
2741 			if (sire != NULL)
2742 				ire_refrele(sire);
2743 			return (0);
2744 		}
2745 
2746 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2747 			in6_addr_t	src_addr;
2748 
2749 			/*
2750 			 * ip_bind_connected_v6() has stored the correct source
2751 			 * address per IPv6 addr. selection policy in
2752 			 * conn_src_v6.
2753 			 */
2754 			src_addr = tcp->tcp_connp->conn_srcv6;
2755 
2756 			tcp->tcp_ip6h->ip6_src = src_addr;
2757 			/*
2758 			 * Copy of the src addr. in tcp_t is needed
2759 			 * for the lookup funcs.
2760 			 */
2761 			tcp->tcp_ip_src_v6 = src_addr;
2762 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2763 			    &connp->conn_srcv6));
2764 		}
2765 		tcp->tcp_localnet =
2766 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2767 	}
2768 
2769 	/*
2770 	 * This allows applications to fail quickly when connections are made
2771 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2772 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2773 	 */
2774 	if ((ire->ire_flags & RTF_REJECT) &&
2775 	    (ire->ire_flags & RTF_PRIVATE))
2776 		goto error;
2777 
2778 	/*
2779 	 * Make use of the cached rtt and rtt_sd values to calculate the
2780 	 * initial RTO.  Note that they are already initialized in
2781 	 * tcp_init_values().
2782 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2783 	 * IP_NEXTHOP, but instead are using the interface ire for the
2784 	 * nexthop, then we do not use the ire_uinfo from that ire to
2785 	 * do any initializations.
2786 	 */
2787 	if (ire_uinfo != NULL) {
2788 		if (ire_uinfo->iulp_rtt != 0) {
2789 			clock_t	rto;
2790 
2791 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2792 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2793 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2794 			    tcps->tcps_rexmit_interval_extra +
2795 			    (tcp->tcp_rtt_sa >> 5);
2796 
2797 			if (rto > tcps->tcps_rexmit_interval_max) {
2798 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2799 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2800 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2801 			} else {
2802 				tcp->tcp_rto = rto;
2803 			}
2804 		}
2805 		if (ire_uinfo->iulp_ssthresh != 0)
2806 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2807 		else
2808 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2809 		if (ire_uinfo->iulp_spipe > 0) {
2810 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2811 			    tcps->tcps_max_buf);
2812 			if (tcps->tcps_snd_lowat_fraction != 0)
2813 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2814 				    tcps->tcps_snd_lowat_fraction;
2815 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2816 		}
2817 		/*
2818 		 * Note that up till now, acceptor always inherits receive
2819 		 * window from the listener.  But if there is a metrics
2820 		 * associated with a host, we should use that instead of
2821 		 * inheriting it from listener. Thus we need to pass this
2822 		 * info back to the caller.
2823 		 */
2824 		if (ire_uinfo->iulp_rpipe > 0) {
2825 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2826 			    tcps->tcps_max_buf);
2827 		}
2828 
2829 		if (ire_uinfo->iulp_rtomax > 0) {
2830 			tcp->tcp_second_timer_threshold =
2831 			    ire_uinfo->iulp_rtomax;
2832 		}
2833 
2834 		/*
2835 		 * Use the metric option settings, iulp_tstamp_ok and
2836 		 * iulp_wscale_ok, only for active open. What this means
2837 		 * is that if the other side uses timestamp or window
2838 		 * scale option, TCP will also use those options. That
2839 		 * is for passive open.  If the application sets a
2840 		 * large window, window scale is enabled regardless of
2841 		 * the value in iulp_wscale_ok.  This is the behavior
2842 		 * since 2.6.  So we keep it.
2843 		 * The only case left in passive open processing is the
2844 		 * check for SACK.
2845 		 * For ECN, it should probably be like SACK.  But the
2846 		 * current value is binary, so we treat it like the other
2847 		 * cases.  The metric only controls active open.For passive
2848 		 * open, the ndd param, tcp_ecn_permitted, controls the
2849 		 * behavior.
2850 		 */
2851 		if (!tcp_detached) {
2852 			/*
2853 			 * The if check means that the following can only
2854 			 * be turned on by the metrics only IRE, but not off.
2855 			 */
2856 			if (ire_uinfo->iulp_tstamp_ok)
2857 				tcp->tcp_snd_ts_ok = B_TRUE;
2858 			if (ire_uinfo->iulp_wscale_ok)
2859 				tcp->tcp_snd_ws_ok = B_TRUE;
2860 			if (ire_uinfo->iulp_sack == 2)
2861 				tcp->tcp_snd_sack_ok = B_TRUE;
2862 			if (ire_uinfo->iulp_ecn_ok)
2863 				tcp->tcp_ecn_ok = B_TRUE;
2864 		} else {
2865 			/*
2866 			 * Passive open.
2867 			 *
2868 			 * As above, the if check means that SACK can only be
2869 			 * turned on by the metric only IRE.
2870 			 */
2871 			if (ire_uinfo->iulp_sack > 0) {
2872 				tcp->tcp_snd_sack_ok = B_TRUE;
2873 			}
2874 		}
2875 	}
2876 
2877 
2878 	/*
2879 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2880 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2881 	 * length of all those options exceeds 28 bytes.  But because
2882 	 * of the tcp_mss_min check below, we may not have a problem if
2883 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2884 	 * the negative problem still exists.  And the check defeats PMTUd.
2885 	 * In fact, if PMTUd finds that the MSS should be smaller than
2886 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2887 	 * value.
2888 	 *
2889 	 * We do not deal with that now.  All those problems related to
2890 	 * PMTUd will be fixed later.
2891 	 */
2892 	ASSERT(ire->ire_max_frag != 0);
2893 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2894 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2895 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2896 			mss = MIN(mss, IPV6_MIN_MTU);
2897 		}
2898 	}
2899 
2900 	/* Sanity check for MSS value. */
2901 	if (tcp->tcp_ipversion == IPV4_VERSION)
2902 		mss_max = tcps->tcps_mss_max_ipv4;
2903 	else
2904 		mss_max = tcps->tcps_mss_max_ipv6;
2905 
2906 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2907 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2908 		/*
2909 		 * After receiving an ICMPv6 "packet too big" message with a
2910 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2911 		 * will insert a 8-byte fragment header in every packet; we
2912 		 * reduce the MSS by that amount here.
2913 		 */
2914 		mss -= sizeof (ip6_frag_t);
2915 	}
2916 
2917 	if (tcp->tcp_ipsec_overhead == 0)
2918 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2919 
2920 	mss -= tcp->tcp_ipsec_overhead;
2921 
2922 	if (mss < tcps->tcps_mss_min)
2923 		mss = tcps->tcps_mss_min;
2924 	if (mss > mss_max)
2925 		mss = mss_max;
2926 
2927 	/* Note that this is the maximum MSS, excluding all options. */
2928 	tcp->tcp_mss = mss;
2929 
2930 	/*
2931 	 * Initialize the ISS here now that we have the full connection ID.
2932 	 * The RFC 1948 method of initial sequence number generation requires
2933 	 * knowledge of the full connection ID before setting the ISS.
2934 	 */
2935 
2936 	tcp_iss_init(tcp);
2937 
2938 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2939 		tcp->tcp_loopback = B_TRUE;
2940 
2941 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2942 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2943 	} else {
2944 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2945 	}
2946 
2947 	if (hsp != NULL) {
2948 		/* Only modify if we're going to make them bigger */
2949 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2950 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2951 			if (tcps->tcps_snd_lowat_fraction != 0)
2952 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2953 				    tcps->tcps_snd_lowat_fraction;
2954 		}
2955 
2956 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2957 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2958 		}
2959 
2960 		/* Copy timestamp flag only for active open */
2961 		if (!tcp_detached)
2962 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2963 	}
2964 
2965 	if (sire != NULL)
2966 		IRE_REFRELE(sire);
2967 
2968 	/*
2969 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2970 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2971 	 */
2972 	if (tcp->tcp_loopback ||
2973 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2974 		/*
2975 		 * For incoming, see if this tcp may be MDT-capable.  For
2976 		 * outgoing, this process has been taken care of through
2977 		 * tcp_rput_other.
2978 		 */
2979 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2980 		tcp->tcp_ire_ill_check_done = B_TRUE;
2981 	}
2982 
2983 	mutex_enter(&connp->conn_lock);
2984 	/*
2985 	 * Make sure that conn is not marked incipient
2986 	 * for incoming connections. A blind
2987 	 * removal of incipient flag is cheaper than
2988 	 * check and removal.
2989 	 */
2990 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2991 
2992 	/*
2993 	 * Must not cache forwarding table routes
2994 	 * or recache an IRE after the conn_t has
2995 	 * had conn_ire_cache cleared and is flagged
2996 	 * unusable, (see the CONN_CACHE_IRE() macro).
2997 	 */
2998 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2999 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
3000 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3001 			connp->conn_ire_cache = ire;
3002 			IRE_UNTRACE_REF(ire);
3003 			rw_exit(&ire->ire_bucket->irb_lock);
3004 			mutex_exit(&connp->conn_lock);
3005 			return (1);
3006 		}
3007 		rw_exit(&ire->ire_bucket->irb_lock);
3008 	}
3009 	mutex_exit(&connp->conn_lock);
3010 
3011 	if (ire->ire_mp == NULL)
3012 		ire_refrele(ire);
3013 	return (1);
3014 
3015 error:
3016 	if (ire->ire_mp == NULL)
3017 		ire_refrele(ire);
3018 	if (sire != NULL)
3019 		ire_refrele(sire);
3020 	return (0);
3021 }
3022 
3023 static void
3024 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
3025 {
3026 	int	error;
3027 	conn_t	*connp = tcp->tcp_connp;
3028 	struct sockaddr	*sa;
3029 	mblk_t  *mp1;
3030 	struct T_bind_req *tbr;
3031 	int	backlog;
3032 	socklen_t	len;
3033 	sin_t	*sin;
3034 	sin6_t	*sin6;
3035 
3036 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3037 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3038 		if (tcp->tcp_debug) {
3039 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3040 			    "tcp_tpi_bind: bad req, len %u",
3041 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3042 		}
3043 		tcp_err_ack(tcp, mp, TPROTO, 0);
3044 		return;
3045 	}
3046 	/* Make sure the largest address fits */
3047 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3048 	if (mp1 == NULL) {
3049 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3050 		return;
3051 	}
3052 	mp = mp1;
3053 	tbr = (struct T_bind_req *)mp->b_rptr;
3054 
3055 	backlog = tbr->CONIND_number;
3056 	len = tbr->ADDR_length;
3057 
3058 	switch (len) {
3059 	case 0:		/* request for a generic port */
3060 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3061 		if (tcp->tcp_family == AF_INET) {
3062 			tbr->ADDR_length = sizeof (sin_t);
3063 			sin = (sin_t *)&tbr[1];
3064 			*sin = sin_null;
3065 			sin->sin_family = AF_INET;
3066 			sa = (struct sockaddr *)sin;
3067 			len = sizeof (sin_t);
3068 			mp->b_wptr = (uchar_t *)&sin[1];
3069 		} else {
3070 			ASSERT(tcp->tcp_family == AF_INET6);
3071 			tbr->ADDR_length = sizeof (sin6_t);
3072 			sin6 = (sin6_t *)&tbr[1];
3073 			*sin6 = sin6_null;
3074 			sin6->sin6_family = AF_INET6;
3075 			sa = (struct sockaddr *)sin6;
3076 			len = sizeof (sin6_t);
3077 			mp->b_wptr = (uchar_t *)&sin6[1];
3078 		}
3079 		break;
3080 
3081 	case sizeof (sin_t):    /* Complete IPv4 address */
3082 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3083 		    sizeof (sin_t));
3084 		break;
3085 
3086 	case sizeof (sin6_t): /* Complete IPv6 address */
3087 		sa = (struct sockaddr *)mi_offset_param(mp,
3088 		    tbr->ADDR_offset, sizeof (sin6_t));
3089 		break;
3090 
3091 	default:
3092 		if (tcp->tcp_debug) {
3093 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3094 			    "tcp_tpi_bind: bad address length, %d",
3095 			    tbr->ADDR_length);
3096 		}
3097 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3098 		return;
3099 	}
3100 
3101 	error = tcp_bind_check(connp, sa, len, DB_CRED(mp),
3102 	    tbr->PRIM_type != O_T_BIND_REQ);
3103 	if (error == 0) {
3104 		if (tcp->tcp_family == AF_INET) {
3105 			sin = (sin_t *)sa;
3106 			sin->sin_port = tcp->tcp_lport;
3107 		} else {
3108 			sin6 = (sin6_t *)sa;
3109 			sin6->sin6_port = tcp->tcp_lport;
3110 		}
3111 
3112 		if (backlog > 0) {
3113 			error = tcp_do_listen(connp, backlog, DB_CRED(mp));
3114 		}
3115 	}
3116 done:
3117 	if (error > 0) {
3118 		tcp_err_ack(tcp, mp, TSYSERR, error);
3119 	} else if (error < 0) {
3120 		tcp_err_ack(tcp, mp, -error, 0);
3121 	} else {
3122 		mp->b_datap->db_type = M_PCPROTO;
3123 		tbr->PRIM_type = T_BIND_ACK;
3124 		putnext(tcp->tcp_rq, mp);
3125 	}
3126 }
3127 
3128 /*
3129  * If the "bind_to_req_port_only" parameter is set, if the requested port
3130  * number is available, return it, If not return 0
3131  *
3132  * If "bind_to_req_port_only" parameter is not set and
3133  * If the requested port number is available, return it.  If not, return
3134  * the first anonymous port we happen across.  If no anonymous ports are
3135  * available, return 0. addr is the requested local address, if any.
3136  *
3137  * In either case, when succeeding update the tcp_t to record the port number
3138  * and insert it in the bind hash table.
3139  *
3140  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3141  * without setting SO_REUSEADDR. This is needed so that they
3142  * can be viewed as two independent transport protocols.
3143  */
3144 static in_port_t
3145 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3146     int reuseaddr, boolean_t quick_connect,
3147     boolean_t bind_to_req_port_only, boolean_t user_specified)
3148 {
3149 	/* number of times we have run around the loop */
3150 	int count = 0;
3151 	/* maximum number of times to run around the loop */
3152 	int loopmax;
3153 	conn_t *connp = tcp->tcp_connp;
3154 	zoneid_t zoneid = connp->conn_zoneid;
3155 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3156 
3157 	/*
3158 	 * Lookup for free addresses is done in a loop and "loopmax"
3159 	 * influences how long we spin in the loop
3160 	 */
3161 	if (bind_to_req_port_only) {
3162 		/*
3163 		 * If the requested port is busy, don't bother to look
3164 		 * for a new one. Setting loop maximum count to 1 has
3165 		 * that effect.
3166 		 */
3167 		loopmax = 1;
3168 	} else {
3169 		/*
3170 		 * If the requested port is busy, look for a free one
3171 		 * in the anonymous port range.
3172 		 * Set loopmax appropriately so that one does not look
3173 		 * forever in the case all of the anonymous ports are in use.
3174 		 */
3175 		if (tcp->tcp_anon_priv_bind) {
3176 			/*
3177 			 * loopmax =
3178 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3179 			 */
3180 			loopmax = IPPORT_RESERVED -
3181 			    tcps->tcps_min_anonpriv_port;
3182 		} else {
3183 			loopmax = (tcps->tcps_largest_anon_port -
3184 			    tcps->tcps_smallest_anon_port + 1);
3185 		}
3186 	}
3187 	do {
3188 		uint16_t	lport;
3189 		tf_t		*tbf;
3190 		tcp_t		*ltcp;
3191 		conn_t		*lconnp;
3192 
3193 		lport = htons(port);
3194 
3195 		/*
3196 		 * Ensure that the tcp_t is not currently in the bind hash.
3197 		 * Hold the lock on the hash bucket to ensure that
3198 		 * the duplicate check plus the insertion is an atomic
3199 		 * operation.
3200 		 *
3201 		 * This function does an inline lookup on the bind hash list
3202 		 * Make sure that we access only members of tcp_t
3203 		 * and that we don't look at tcp_tcp, since we are not
3204 		 * doing a CONN_INC_REF.
3205 		 */
3206 		tcp_bind_hash_remove(tcp);
3207 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3208 		mutex_enter(&tbf->tf_lock);
3209 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3210 		    ltcp = ltcp->tcp_bind_hash) {
3211 			if (lport == ltcp->tcp_lport)
3212 				break;
3213 		}
3214 
3215 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3216 			boolean_t not_socket;
3217 			boolean_t exclbind;
3218 
3219 			lconnp = ltcp->tcp_connp;
3220 
3221 			/*
3222 			 * On a labeled system, we must treat bindings to ports
3223 			 * on shared IP addresses by sockets with MAC exemption
3224 			 * privilege as being in all zones, as there's
3225 			 * otherwise no way to identify the right receiver.
3226 			 */
3227 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3228 			    IPCL_ZONE_MATCH(connp,
3229 			    ltcp->tcp_connp->conn_zoneid)) &&
3230 			    !lconnp->conn_mac_exempt &&
3231 			    !connp->conn_mac_exempt)
3232 				continue;
3233 
3234 			/*
3235 			 * If TCP_EXCLBIND is set for either the bound or
3236 			 * binding endpoint, the semantics of bind
3237 			 * is changed according to the following.
3238 			 *
3239 			 * spec = specified address (v4 or v6)
3240 			 * unspec = unspecified address (v4 or v6)
3241 			 * A = specified addresses are different for endpoints
3242 			 *
3243 			 * bound	bind to		allowed
3244 			 * -------------------------------------
3245 			 * unspec	unspec		no
3246 			 * unspec	spec		no
3247 			 * spec		unspec		no
3248 			 * spec		spec		yes if A
3249 			 *
3250 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3251 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3252 			 *
3253 			 * Note:
3254 			 *
3255 			 * 1. Because of TLI semantics, an endpoint can go
3256 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3257 			 * TCPS_BOUND, depending on whether it is originally
3258 			 * a listener or not.  That is why we need to check
3259 			 * for states greater than or equal to TCPS_BOUND
3260 			 * here.
3261 			 *
3262 			 * 2. Ideally, we should only check for state equals
3263 			 * to TCPS_LISTEN. And the following check should be
3264 			 * added.
3265 			 *
3266 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3267 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3268 			 *		...
3269 			 * }
3270 			 *
3271 			 * The semantics will be changed to this.  If the
3272 			 * endpoint on the list is in state not equal to
3273 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3274 			 * set, let the bind succeed.
3275 			 *
3276 			 * Because of (1), we cannot do that for TLI
3277 			 * endpoints.  But we can do that for socket endpoints.
3278 			 * If in future, we can change this going back
3279 			 * semantics, we can use the above check for TLI also.
3280 			 */
3281 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3282 			    TCP_IS_SOCKET(tcp));
3283 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3284 
3285 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3286 			    (exclbind && (not_socket ||
3287 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3288 				if (V6_OR_V4_INADDR_ANY(
3289 				    ltcp->tcp_bound_source_v6) ||
3290 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3291 				    IN6_ARE_ADDR_EQUAL(laddr,
3292 				    &ltcp->tcp_bound_source_v6)) {
3293 					break;
3294 				}
3295 				continue;
3296 			}
3297 
3298 			/*
3299 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3300 			 * have disjoint port number spaces, if *_EXCLBIND
3301 			 * is not set and only if the application binds to a
3302 			 * specific port. We use the same autoassigned port
3303 			 * number space for IPv4 and IPv6 sockets.
3304 			 */
3305 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3306 			    bind_to_req_port_only)
3307 				continue;
3308 
3309 			/*
3310 			 * Ideally, we should make sure that the source
3311 			 * address, remote address, and remote port in the
3312 			 * four tuple for this tcp-connection is unique.
3313 			 * However, trying to find out the local source
3314 			 * address would require too much code duplication
3315 			 * with IP, since IP needs needs to have that code
3316 			 * to support userland TCP implementations.
3317 			 */
3318 			if (quick_connect &&
3319 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3320 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3321 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3322 			    &ltcp->tcp_remote_v6)))
3323 				continue;
3324 
3325 			if (!reuseaddr) {
3326 				/*
3327 				 * No socket option SO_REUSEADDR.
3328 				 * If existing port is bound to
3329 				 * a non-wildcard IP address
3330 				 * and the requesting stream is
3331 				 * bound to a distinct
3332 				 * different IP addresses
3333 				 * (non-wildcard, also), keep
3334 				 * going.
3335 				 */
3336 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3337 				    !V6_OR_V4_INADDR_ANY(
3338 				    ltcp->tcp_bound_source_v6) &&
3339 				    !IN6_ARE_ADDR_EQUAL(laddr,
3340 				    &ltcp->tcp_bound_source_v6))
3341 					continue;
3342 				if (ltcp->tcp_state >= TCPS_BOUND) {
3343 					/*
3344 					 * This port is being used and
3345 					 * its state is >= TCPS_BOUND,
3346 					 * so we can't bind to it.
3347 					 */
3348 					break;
3349 				}
3350 			} else {
3351 				/*
3352 				 * socket option SO_REUSEADDR is set on the
3353 				 * binding tcp_t.
3354 				 *
3355 				 * If two streams are bound to
3356 				 * same IP address or both addr
3357 				 * and bound source are wildcards
3358 				 * (INADDR_ANY), we want to stop
3359 				 * searching.
3360 				 * We have found a match of IP source
3361 				 * address and source port, which is
3362 				 * refused regardless of the
3363 				 * SO_REUSEADDR setting, so we break.
3364 				 */
3365 				if (IN6_ARE_ADDR_EQUAL(laddr,
3366 				    &ltcp->tcp_bound_source_v6) &&
3367 				    (ltcp->tcp_state == TCPS_LISTEN ||
3368 				    ltcp->tcp_state == TCPS_BOUND))
3369 					break;
3370 			}
3371 		}
3372 		if (ltcp != NULL) {
3373 			/* The port number is busy */
3374 			mutex_exit(&tbf->tf_lock);
3375 		} else {
3376 			/*
3377 			 * This port is ours. Insert in fanout and mark as
3378 			 * bound to prevent others from getting the port
3379 			 * number.
3380 			 */
3381 			tcp->tcp_state = TCPS_BOUND;
3382 			tcp->tcp_lport = htons(port);
3383 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3384 
3385 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3386 			    tcp->tcp_lport)] == tbf);
3387 			tcp_bind_hash_insert(tbf, tcp, 1);
3388 
3389 			mutex_exit(&tbf->tf_lock);
3390 
3391 			/*
3392 			 * We don't want tcp_next_port_to_try to "inherit"
3393 			 * a port number supplied by the user in a bind.
3394 			 */
3395 			if (user_specified)
3396 				return (port);
3397 
3398 			/*
3399 			 * This is the only place where tcp_next_port_to_try
3400 			 * is updated. After the update, it may or may not
3401 			 * be in the valid range.
3402 			 */
3403 			if (!tcp->tcp_anon_priv_bind)
3404 				tcps->tcps_next_port_to_try = port + 1;
3405 			return (port);
3406 		}
3407 
3408 		if (tcp->tcp_anon_priv_bind) {
3409 			port = tcp_get_next_priv_port(tcp);
3410 		} else {
3411 			if (count == 0 && user_specified) {
3412 				/*
3413 				 * We may have to return an anonymous port. So
3414 				 * get one to start with.
3415 				 */
3416 				port =
3417 				    tcp_update_next_port(
3418 				    tcps->tcps_next_port_to_try,
3419 				    tcp, B_TRUE);
3420 				user_specified = B_FALSE;
3421 			} else {
3422 				port = tcp_update_next_port(port + 1, tcp,
3423 				    B_FALSE);
3424 			}
3425 		}
3426 		if (port == 0)
3427 			break;
3428 
3429 		/*
3430 		 * Don't let this loop run forever in the case where
3431 		 * all of the anonymous ports are in use.
3432 		 */
3433 	} while (++count < loopmax);
3434 	return (0);
3435 }
3436 
3437 /*
3438  * tcp_clean_death / tcp_close_detached must not be called more than once
3439  * on a tcp. Thus every function that potentially calls tcp_clean_death
3440  * must check for the tcp state before calling tcp_clean_death.
3441  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3442  * tcp_timer_handler, all check for the tcp state.
3443  */
3444 /* ARGSUSED */
3445 void
3446 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3447 {
3448 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3449 
3450 	freemsg(mp);
3451 	if (tcp->tcp_state > TCPS_BOUND)
3452 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3453 		    ETIMEDOUT, 5);
3454 }
3455 
3456 /*
3457  * We are dying for some reason.  Try to do it gracefully.  (May be called
3458  * as writer.)
3459  *
3460  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3461  * done by a service procedure).
3462  * TBD - Should the return value distinguish between the tcp_t being
3463  * freed and it being reinitialized?
3464  */
3465 static int
3466 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3467 {
3468 	mblk_t	*mp;
3469 	queue_t	*q;
3470 	conn_t	*connp = tcp->tcp_connp;
3471 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3472 	sodirect_t	*sodp;
3473 
3474 	TCP_CLD_STAT(tag);
3475 
3476 #if TCP_TAG_CLEAN_DEATH
3477 	tcp->tcp_cleandeathtag = tag;
3478 #endif
3479 
3480 	if (tcp->tcp_fused)
3481 		tcp_unfuse(tcp);
3482 
3483 	if (tcp->tcp_linger_tid != 0 &&
3484 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3485 		tcp_stop_lingering(tcp);
3486 	}
3487 
3488 	ASSERT(tcp != NULL);
3489 	ASSERT((tcp->tcp_family == AF_INET &&
3490 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3491 	    (tcp->tcp_family == AF_INET6 &&
3492 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3493 	    tcp->tcp_ipversion == IPV6_VERSION)));
3494 
3495 	if (TCP_IS_DETACHED(tcp)) {
3496 		if (tcp->tcp_hard_binding) {
3497 			/*
3498 			 * Its an eager that we are dealing with. We close the
3499 			 * eager but in case a conn_ind has already gone to the
3500 			 * listener, let tcp_accept_finish() send a discon_ind
3501 			 * to the listener and drop the last reference. If the
3502 			 * listener doesn't even know about the eager i.e. the
3503 			 * conn_ind hasn't gone up, blow away the eager and drop
3504 			 * the last reference as well. If the conn_ind has gone
3505 			 * up, state should be BOUND. tcp_accept_finish
3506 			 * will figure out that the connection has received a
3507 			 * RST and will send a DISCON_IND to the application.
3508 			 */
3509 			tcp_closei_local(tcp);
3510 			if (!tcp->tcp_tconnind_started) {
3511 				CONN_DEC_REF(connp);
3512 			} else {
3513 				tcp->tcp_state = TCPS_BOUND;
3514 			}
3515 		} else {
3516 			tcp_close_detached(tcp);
3517 		}
3518 		return (0);
3519 	}
3520 
3521 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3522 
3523 	/* If sodirect, not anymore */
3524 	SOD_PTR_ENTER(tcp, sodp);
3525 	if (sodp != NULL) {
3526 		tcp->tcp_sodirect = NULL;
3527 		mutex_exit(sodp->sod_lockp);
3528 	}
3529 
3530 	q = tcp->tcp_rq;
3531 
3532 	/* Trash all inbound data */
3533 	if (!IPCL_IS_NONSTR(connp)) {
3534 		ASSERT(q != NULL);
3535 		flushq(q, FLUSHALL);
3536 	}
3537 
3538 	/*
3539 	 * If we are at least part way open and there is error
3540 	 * (err==0 implies no error)
3541 	 * notify our client by a T_DISCON_IND.
3542 	 */
3543 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3544 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3545 		    !TCP_IS_SOCKET(tcp)) {
3546 			/*
3547 			 * Send M_FLUSH according to TPI. Because sockets will
3548 			 * (and must) ignore FLUSHR we do that only for TPI
3549 			 * endpoints and sockets in STREAMS mode.
3550 			 */
3551 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3552 		}
3553 		if (tcp->tcp_debug) {
3554 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3555 			    "tcp_clean_death: discon err %d", err);
3556 		}
3557 		if (IPCL_IS_NONSTR(connp)) {
3558 			/* Direct socket, use upcall */
3559 			(*connp->conn_upcalls->su_disconnected)(
3560 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3561 		} else {
3562 			mp = mi_tpi_discon_ind(NULL, err, 0);
3563 			if (mp != NULL) {
3564 				putnext(q, mp);
3565 			} else {
3566 				if (tcp->tcp_debug) {
3567 					(void) strlog(TCP_MOD_ID, 0, 1,
3568 					    SL_ERROR|SL_TRACE,
3569 					    "tcp_clean_death, sending M_ERROR");
3570 				}
3571 				(void) putnextctl1(q, M_ERROR, EPROTO);
3572 			}
3573 		}
3574 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3575 			/* SYN_SENT or SYN_RCVD */
3576 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3577 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3578 			/* ESTABLISHED or CLOSE_WAIT */
3579 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3580 		}
3581 	}
3582 
3583 	tcp_reinit(tcp);
3584 	if (IPCL_IS_NONSTR(connp))
3585 		(void) tcp_do_unbind(connp);
3586 
3587 	return (-1);
3588 }
3589 
3590 /*
3591  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3592  * to expire, stop the wait and finish the close.
3593  */
3594 static void
3595 tcp_stop_lingering(tcp_t *tcp)
3596 {
3597 	clock_t	delta = 0;
3598 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3599 
3600 	tcp->tcp_linger_tid = 0;
3601 	if (tcp->tcp_state > TCPS_LISTEN) {
3602 		tcp_acceptor_hash_remove(tcp);
3603 		mutex_enter(&tcp->tcp_non_sq_lock);
3604 		if (tcp->tcp_flow_stopped) {
3605 			tcp_clrqfull(tcp);
3606 		}
3607 		mutex_exit(&tcp->tcp_non_sq_lock);
3608 
3609 		if (tcp->tcp_timer_tid != 0) {
3610 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3611 			tcp->tcp_timer_tid = 0;
3612 		}
3613 		/*
3614 		 * Need to cancel those timers which will not be used when
3615 		 * TCP is detached.  This has to be done before the tcp_wq
3616 		 * is set to the global queue.
3617 		 */
3618 		tcp_timers_stop(tcp);
3619 
3620 		tcp->tcp_detached = B_TRUE;
3621 		ASSERT(tcps->tcps_g_q != NULL);
3622 		tcp->tcp_rq = tcps->tcps_g_q;
3623 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3624 
3625 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3626 			tcp_time_wait_append(tcp);
3627 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3628 			goto finish;
3629 		}
3630 
3631 		/*
3632 		 * If delta is zero the timer event wasn't executed and was
3633 		 * successfully canceled. In this case we need to restart it
3634 		 * with the minimal delta possible.
3635 		 */
3636 		if (delta >= 0) {
3637 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3638 			    delta ? delta : 1);
3639 		}
3640 	} else {
3641 		tcp_closei_local(tcp);
3642 		CONN_DEC_REF(tcp->tcp_connp);
3643 	}
3644 finish:
3645 	/* Signal closing thread that it can complete close */
3646 	mutex_enter(&tcp->tcp_closelock);
3647 	tcp->tcp_detached = B_TRUE;
3648 	ASSERT(tcps->tcps_g_q != NULL);
3649 
3650 	tcp->tcp_rq = tcps->tcps_g_q;
3651 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3652 
3653 	tcp->tcp_closed = 1;
3654 	cv_signal(&tcp->tcp_closecv);
3655 	mutex_exit(&tcp->tcp_closelock);
3656 }
3657 
3658 /*
3659  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3660  * expires.
3661  */
3662 static void
3663 tcp_close_linger_timeout(void *arg)
3664 {
3665 	conn_t	*connp = (conn_t *)arg;
3666 	tcp_t 	*tcp = connp->conn_tcp;
3667 
3668 	tcp->tcp_client_errno = ETIMEDOUT;
3669 	tcp_stop_lingering(tcp);
3670 }
3671 
3672 static void
3673 tcp_close_common(conn_t *connp, int flags)
3674 {
3675 	tcp_t		*tcp = connp->conn_tcp;
3676 	mblk_t 		*mp = &tcp->tcp_closemp;
3677 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3678 	mblk_t		*bp;
3679 
3680 	ASSERT(connp->conn_ref >= 2);
3681 
3682 	/*
3683 	 * Mark the conn as closing. ill_pending_mp_add will not
3684 	 * add any mp to the pending mp list, after this conn has
3685 	 * started closing. Same for sq_pending_mp_add
3686 	 */
3687 	mutex_enter(&connp->conn_lock);
3688 	connp->conn_state_flags |= CONN_CLOSING;
3689 	if (connp->conn_oper_pending_ill != NULL)
3690 		conn_ioctl_cleanup_reqd = B_TRUE;
3691 	CONN_INC_REF_LOCKED(connp);
3692 	mutex_exit(&connp->conn_lock);
3693 	tcp->tcp_closeflags = (uint8_t)flags;
3694 	ASSERT(connp->conn_ref >= 3);
3695 
3696 	/*
3697 	 * tcp_closemp_used is used below without any protection of a lock
3698 	 * as we don't expect any one else to use it concurrently at this
3699 	 * point otherwise it would be a major defect.
3700 	 */
3701 
3702 	if (mp->b_prev == NULL)
3703 		tcp->tcp_closemp_used = B_TRUE;
3704 	else
3705 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3706 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3707 
3708 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3709 
3710 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3711 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3712 
3713 	mutex_enter(&tcp->tcp_closelock);
3714 	while (!tcp->tcp_closed) {
3715 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3716 			/*
3717 			 * The cv_wait_sig() was interrupted. We now do the
3718 			 * following:
3719 			 *
3720 			 * 1) If the endpoint was lingering, we allow this
3721 			 * to be interrupted by cancelling the linger timeout
3722 			 * and closing normally.
3723 			 *
3724 			 * 2) Revert to calling cv_wait()
3725 			 *
3726 			 * We revert to using cv_wait() to avoid an
3727 			 * infinite loop which can occur if the calling
3728 			 * thread is higher priority than the squeue worker
3729 			 * thread and is bound to the same cpu.
3730 			 */
3731 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3732 				mutex_exit(&tcp->tcp_closelock);
3733 				/* Entering squeue, bump ref count. */
3734 				CONN_INC_REF(connp);
3735 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3736 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3737 				    tcp_linger_interrupted, connp,
3738 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3739 				mutex_enter(&tcp->tcp_closelock);
3740 			}
3741 			break;
3742 		}
3743 	}
3744 	while (!tcp->tcp_closed)
3745 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3746 	mutex_exit(&tcp->tcp_closelock);
3747 
3748 	/*
3749 	 * In the case of listener streams that have eagers in the q or q0
3750 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3751 	 * tcp_wq of the eagers point to our queues. By waiting for the
3752 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3753 	 * up their queue pointers and also dropped their references to us.
3754 	 */
3755 	if (tcp->tcp_wait_for_eagers) {
3756 		mutex_enter(&connp->conn_lock);
3757 		while (connp->conn_ref != 1) {
3758 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3759 		}
3760 		mutex_exit(&connp->conn_lock);
3761 	}
3762 	/*
3763 	 * ioctl cleanup. The mp is queued in the
3764 	 * ill_pending_mp or in the sq_pending_mp.
3765 	 */
3766 	if (conn_ioctl_cleanup_reqd)
3767 		conn_ioctl_cleanup(connp);
3768 
3769 	tcp->tcp_cpid = -1;
3770 }
3771 
3772 static int
3773 tcp_tpi_close(queue_t *q, int flags)
3774 {
3775 	conn_t		*connp;
3776 
3777 	ASSERT(WR(q)->q_next == NULL);
3778 
3779 	if (flags & SO_FALLBACK) {
3780 		/*
3781 		 * stream is being closed while in fallback
3782 		 * simply free the resources that were allocated
3783 		 */
3784 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3785 		qprocsoff(q);
3786 		goto done;
3787 	}
3788 
3789 	connp = Q_TO_CONN(q);
3790 	/*
3791 	 * We are being closed as /dev/tcp or /dev/tcp6.
3792 	 */
3793 	tcp_close_common(connp, flags);
3794 
3795 	qprocsoff(q);
3796 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3797 
3798 	/*
3799 	 * Drop IP's reference on the conn. This is the last reference
3800 	 * on the connp if the state was less than established. If the
3801 	 * connection has gone into timewait state, then we will have
3802 	 * one ref for the TCP and one more ref (total of two) for the
3803 	 * classifier connected hash list (a timewait connections stays
3804 	 * in connected hash till closed).
3805 	 *
3806 	 * We can't assert the references because there might be other
3807 	 * transient reference places because of some walkers or queued
3808 	 * packets in squeue for the timewait state.
3809 	 */
3810 	CONN_DEC_REF(connp);
3811 done:
3812 	q->q_ptr = WR(q)->q_ptr = NULL;
3813 	return (0);
3814 }
3815 
3816 static int
3817 tcpclose_accept(queue_t *q)
3818 {
3819 	vmem_t	*minor_arena;
3820 	dev_t	conn_dev;
3821 
3822 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3823 
3824 	/*
3825 	 * We had opened an acceptor STREAM for sockfs which is
3826 	 * now being closed due to some error.
3827 	 */
3828 	qprocsoff(q);
3829 
3830 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3831 	conn_dev = (dev_t)RD(q)->q_ptr;
3832 	ASSERT(minor_arena != NULL);
3833 	ASSERT(conn_dev != 0);
3834 	inet_minor_free(minor_arena, conn_dev);
3835 	q->q_ptr = WR(q)->q_ptr = NULL;
3836 	return (0);
3837 }
3838 
3839 /*
3840  * Called by tcp_close() routine via squeue when lingering is
3841  * interrupted by a signal.
3842  */
3843 
3844 /* ARGSUSED */
3845 static void
3846 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3847 {
3848 	conn_t	*connp = (conn_t *)arg;
3849 	tcp_t	*tcp = connp->conn_tcp;
3850 
3851 	freeb(mp);
3852 	if (tcp->tcp_linger_tid != 0 &&
3853 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3854 		tcp_stop_lingering(tcp);
3855 		tcp->tcp_client_errno = EINTR;
3856 	}
3857 }
3858 
3859 /*
3860  * Called by streams close routine via squeues when our client blows off her
3861  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3862  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3863  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3864  * acked.
3865  *
3866  * NOTE: tcp_close potentially returns error when lingering.
3867  * However, the stream head currently does not pass these errors
3868  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3869  * errors to the application (from tsleep()) and not errors
3870  * like ECONNRESET caused by receiving a reset packet.
3871  */
3872 
3873 /* ARGSUSED */
3874 static void
3875 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3876 {
3877 	char	*msg;
3878 	conn_t	*connp = (conn_t *)arg;
3879 	tcp_t	*tcp = connp->conn_tcp;
3880 	clock_t	delta = 0;
3881 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3882 
3883 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3884 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3885 
3886 	mutex_enter(&tcp->tcp_eager_lock);
3887 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3888 		/* Cleanup for listener */
3889 		tcp_eager_cleanup(tcp, 0);
3890 		tcp->tcp_wait_for_eagers = 1;
3891 	}
3892 	mutex_exit(&tcp->tcp_eager_lock);
3893 
3894 	connp->conn_mdt_ok = B_FALSE;
3895 	tcp->tcp_mdt = B_FALSE;
3896 
3897 	connp->conn_lso_ok = B_FALSE;
3898 	tcp->tcp_lso = B_FALSE;
3899 
3900 	msg = NULL;
3901 	switch (tcp->tcp_state) {
3902 	case TCPS_CLOSED:
3903 	case TCPS_IDLE:
3904 	case TCPS_BOUND:
3905 	case TCPS_LISTEN:
3906 		break;
3907 	case TCPS_SYN_SENT:
3908 		msg = "tcp_close, during connect";
3909 		break;
3910 	case TCPS_SYN_RCVD:
3911 		/*
3912 		 * Close during the connect 3-way handshake
3913 		 * but here there may or may not be pending data
3914 		 * already on queue. Process almost same as in
3915 		 * the ESTABLISHED state.
3916 		 */
3917 		/* FALLTHRU */
3918 	default:
3919 		if (tcp->tcp_sodirect != NULL) {
3920 			/* Ok, no more sodirect */
3921 			tcp->tcp_sodirect = NULL;
3922 		}
3923 
3924 		if (tcp->tcp_fused)
3925 			tcp_unfuse(tcp);
3926 
3927 		/*
3928 		 * If SO_LINGER has set a zero linger time, abort the
3929 		 * connection with a reset.
3930 		 */
3931 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3932 			msg = "tcp_close, zero lingertime";
3933 			break;
3934 		}
3935 
3936 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3937 		/*
3938 		 * Abort connection if there is unread data queued.
3939 		 */
3940 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3941 			msg = "tcp_close, unread data";
3942 			break;
3943 		}
3944 		/*
3945 		 * tcp_hard_bound is now cleared thus all packets go through
3946 		 * tcp_lookup. This fact is used by tcp_detach below.
3947 		 *
3948 		 * We have done a qwait() above which could have possibly
3949 		 * drained more messages in turn causing transition to a
3950 		 * different state. Check whether we have to do the rest
3951 		 * of the processing or not.
3952 		 */
3953 		if (tcp->tcp_state <= TCPS_LISTEN)
3954 			break;
3955 
3956 		/*
3957 		 * Transmit the FIN before detaching the tcp_t.
3958 		 * After tcp_detach returns this queue/perimeter
3959 		 * no longer owns the tcp_t thus others can modify it.
3960 		 */
3961 		(void) tcp_xmit_end(tcp);
3962 
3963 		/*
3964 		 * If lingering on close then wait until the fin is acked,
3965 		 * the SO_LINGER time passes, or a reset is sent/received.
3966 		 */
3967 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
3968 		    !(tcp->tcp_fin_acked) &&
3969 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
3970 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
3971 				tcp->tcp_client_errno = EWOULDBLOCK;
3972 			} else if (tcp->tcp_client_errno == 0) {
3973 
3974 				ASSERT(tcp->tcp_linger_tid == 0);
3975 
3976 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
3977 				    tcp_close_linger_timeout,
3978 				    tcp->tcp_lingertime * hz);
3979 
3980 				/* tcp_close_linger_timeout will finish close */
3981 				if (tcp->tcp_linger_tid == 0)
3982 					tcp->tcp_client_errno = ENOSR;
3983 				else
3984 					return;
3985 			}
3986 
3987 			/*
3988 			 * Check if we need to detach or just close
3989 			 * the instance.
3990 			 */
3991 			if (tcp->tcp_state <= TCPS_LISTEN)
3992 				break;
3993 		}
3994 
3995 		/*
3996 		 * Make sure that no other thread will access the tcp_rq of
3997 		 * this instance (through lookups etc.) as tcp_rq will go
3998 		 * away shortly.
3999 		 */
4000 		tcp_acceptor_hash_remove(tcp);
4001 
4002 		mutex_enter(&tcp->tcp_non_sq_lock);
4003 		if (tcp->tcp_flow_stopped) {
4004 			tcp_clrqfull(tcp);
4005 		}
4006 		mutex_exit(&tcp->tcp_non_sq_lock);
4007 
4008 		if (tcp->tcp_timer_tid != 0) {
4009 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4010 			tcp->tcp_timer_tid = 0;
4011 		}
4012 		/*
4013 		 * Need to cancel those timers which will not be used when
4014 		 * TCP is detached.  This has to be done before the tcp_wq
4015 		 * is set to the global queue.
4016 		 */
4017 		tcp_timers_stop(tcp);
4018 
4019 		tcp->tcp_detached = B_TRUE;
4020 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4021 			tcp_time_wait_append(tcp);
4022 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4023 			ASSERT(connp->conn_ref >= 3);
4024 			goto finish;
4025 		}
4026 
4027 		/*
4028 		 * If delta is zero the timer event wasn't executed and was
4029 		 * successfully canceled. In this case we need to restart it
4030 		 * with the minimal delta possible.
4031 		 */
4032 		if (delta >= 0)
4033 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4034 			    delta ? delta : 1);
4035 
4036 		ASSERT(connp->conn_ref >= 3);
4037 		goto finish;
4038 	}
4039 
4040 	/* Detach did not complete. Still need to remove q from stream. */
4041 	if (msg) {
4042 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4043 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4044 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4045 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4046 		    tcp->tcp_state == TCPS_SYN_RCVD)
4047 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4048 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4049 	}
4050 
4051 	tcp_closei_local(tcp);
4052 	CONN_DEC_REF(connp);
4053 	ASSERT(connp->conn_ref >= 2);
4054 
4055 finish:
4056 	/*
4057 	 * Although packets are always processed on the correct
4058 	 * tcp's perimeter and access is serialized via squeue's,
4059 	 * IP still needs a queue when sending packets in time_wait
4060 	 * state so use WR(tcps_g_q) till ip_output() can be
4061 	 * changed to deal with just connp. For read side, we
4062 	 * could have set tcp_rq to NULL but there are some cases
4063 	 * in tcp_rput_data() from early days of this code which
4064 	 * do a putnext without checking if tcp is closed. Those
4065 	 * need to be identified before both tcp_rq and tcp_wq
4066 	 * can be set to NULL and tcps_g_q can disappear forever.
4067 	 */
4068 	mutex_enter(&tcp->tcp_closelock);
4069 	/*
4070 	 * Don't change the queues in the case of a listener that has
4071 	 * eagers in its q or q0. It could surprise the eagers.
4072 	 * Instead wait for the eagers outside the squeue.
4073 	 */
4074 	if (!tcp->tcp_wait_for_eagers) {
4075 		tcp->tcp_detached = B_TRUE;
4076 		/*
4077 		 * When default queue is closing we set tcps_g_q to NULL
4078 		 * after the close is done.
4079 		 */
4080 		ASSERT(tcps->tcps_g_q != NULL);
4081 		tcp->tcp_rq = tcps->tcps_g_q;
4082 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4083 	}
4084 
4085 	/* Signal tcp_close() to finish closing. */
4086 	tcp->tcp_closed = 1;
4087 	cv_signal(&tcp->tcp_closecv);
4088 	mutex_exit(&tcp->tcp_closelock);
4089 }
4090 
4091 
4092 /*
4093  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4094  * Some stream heads get upset if they see these later on as anything but NULL.
4095  */
4096 static void
4097 tcp_close_mpp(mblk_t **mpp)
4098 {
4099 	mblk_t	*mp;
4100 
4101 	if ((mp = *mpp) != NULL) {
4102 		do {
4103 			mp->b_next = NULL;
4104 			mp->b_prev = NULL;
4105 		} while ((mp = mp->b_cont) != NULL);
4106 
4107 		mp = *mpp;
4108 		*mpp = NULL;
4109 		freemsg(mp);
4110 	}
4111 }
4112 
4113 /* Do detached close. */
4114 static void
4115 tcp_close_detached(tcp_t *tcp)
4116 {
4117 	if (tcp->tcp_fused)
4118 		tcp_unfuse(tcp);
4119 
4120 	/*
4121 	 * Clustering code serializes TCP disconnect callbacks and
4122 	 * cluster tcp list walks by blocking a TCP disconnect callback
4123 	 * if a cluster tcp list walk is in progress. This ensures
4124 	 * accurate accounting of TCPs in the cluster code even though
4125 	 * the TCP list walk itself is not atomic.
4126 	 */
4127 	tcp_closei_local(tcp);
4128 	CONN_DEC_REF(tcp->tcp_connp);
4129 }
4130 
4131 /*
4132  * Stop all TCP timers, and free the timer mblks if requested.
4133  */
4134 void
4135 tcp_timers_stop(tcp_t *tcp)
4136 {
4137 	if (tcp->tcp_timer_tid != 0) {
4138 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4139 		tcp->tcp_timer_tid = 0;
4140 	}
4141 	if (tcp->tcp_ka_tid != 0) {
4142 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4143 		tcp->tcp_ka_tid = 0;
4144 	}
4145 	if (tcp->tcp_ack_tid != 0) {
4146 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4147 		tcp->tcp_ack_tid = 0;
4148 	}
4149 	if (tcp->tcp_push_tid != 0) {
4150 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4151 		tcp->tcp_push_tid = 0;
4152 	}
4153 }
4154 
4155 /*
4156  * The tcp_t is going away. Remove it from all lists and set it
4157  * to TCPS_CLOSED. The freeing up of memory is deferred until
4158  * tcp_inactive. This is needed since a thread in tcp_rput might have
4159  * done a CONN_INC_REF on this structure before it was removed from the
4160  * hashes.
4161  */
4162 static void
4163 tcp_closei_local(tcp_t *tcp)
4164 {
4165 	ire_t 	*ire;
4166 	conn_t	*connp = tcp->tcp_connp;
4167 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4168 
4169 	if (!TCP_IS_SOCKET(tcp))
4170 		tcp_acceptor_hash_remove(tcp);
4171 
4172 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4173 	tcp->tcp_ibsegs = 0;
4174 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4175 	tcp->tcp_obsegs = 0;
4176 
4177 	/*
4178 	 * If we are an eager connection hanging off a listener that
4179 	 * hasn't formally accepted the connection yet, get off his
4180 	 * list and blow off any data that we have accumulated.
4181 	 */
4182 	if (tcp->tcp_listener != NULL) {
4183 		tcp_t	*listener = tcp->tcp_listener;
4184 		mutex_enter(&listener->tcp_eager_lock);
4185 		/*
4186 		 * tcp_tconnind_started == B_TRUE means that the
4187 		 * conn_ind has already gone to listener. At
4188 		 * this point, eager will be closed but we
4189 		 * leave it in listeners eager list so that
4190 		 * if listener decides to close without doing
4191 		 * accept, we can clean this up. In tcp_wput_accept
4192 		 * we take care of the case of accept on closed
4193 		 * eager.
4194 		 */
4195 		if (!tcp->tcp_tconnind_started) {
4196 			tcp_eager_unlink(tcp);
4197 			mutex_exit(&listener->tcp_eager_lock);
4198 			/*
4199 			 * We don't want to have any pointers to the
4200 			 * listener queue, after we have released our
4201 			 * reference on the listener
4202 			 */
4203 			ASSERT(tcps->tcps_g_q != NULL);
4204 			tcp->tcp_rq = tcps->tcps_g_q;
4205 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4206 			CONN_DEC_REF(listener->tcp_connp);
4207 		} else {
4208 			mutex_exit(&listener->tcp_eager_lock);
4209 		}
4210 	}
4211 
4212 	/* Stop all the timers */
4213 	tcp_timers_stop(tcp);
4214 
4215 	if (tcp->tcp_state == TCPS_LISTEN) {
4216 		if (tcp->tcp_ip_addr_cache) {
4217 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4218 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4219 			tcp->tcp_ip_addr_cache = NULL;
4220 		}
4221 	}
4222 	mutex_enter(&tcp->tcp_non_sq_lock);
4223 	if (tcp->tcp_flow_stopped)
4224 		tcp_clrqfull(tcp);
4225 	mutex_exit(&tcp->tcp_non_sq_lock);
4226 
4227 	tcp_bind_hash_remove(tcp);
4228 	/*
4229 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4230 	 * is trying to remove this tcp from the time wait list, we will
4231 	 * block in tcp_time_wait_remove while trying to acquire the
4232 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4233 	 * requires the ipcl_hash_remove to be ordered after the
4234 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4235 	 */
4236 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4237 		(void) tcp_time_wait_remove(tcp, NULL);
4238 	CL_INET_DISCONNECT(tcp);
4239 	ipcl_hash_remove(connp);
4240 
4241 	/*
4242 	 * Delete the cached ire in conn_ire_cache and also mark
4243 	 * the conn as CONDEMNED
4244 	 */
4245 	mutex_enter(&connp->conn_lock);
4246 	connp->conn_state_flags |= CONN_CONDEMNED;
4247 	ire = connp->conn_ire_cache;
4248 	connp->conn_ire_cache = NULL;
4249 	mutex_exit(&connp->conn_lock);
4250 	if (ire != NULL)
4251 		IRE_REFRELE_NOTR(ire);
4252 
4253 	/* Need to cleanup any pending ioctls */
4254 	ASSERT(tcp->tcp_time_wait_next == NULL);
4255 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4256 	ASSERT(tcp->tcp_time_wait_expire == 0);
4257 	tcp->tcp_state = TCPS_CLOSED;
4258 
4259 	/* Release any SSL context */
4260 	if (tcp->tcp_kssl_ent != NULL) {
4261 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4262 		tcp->tcp_kssl_ent = NULL;
4263 	}
4264 	if (tcp->tcp_kssl_ctx != NULL) {
4265 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4266 		tcp->tcp_kssl_ctx = NULL;
4267 	}
4268 	tcp->tcp_kssl_pending = B_FALSE;
4269 
4270 	tcp_ipsec_cleanup(tcp);
4271 }
4272 
4273 /*
4274  * tcp is dying (called from ipcl_conn_destroy and error cases).
4275  * Free the tcp_t in either case.
4276  */
4277 void
4278 tcp_free(tcp_t *tcp)
4279 {
4280 	mblk_t	*mp;
4281 	ip6_pkt_t	*ipp;
4282 
4283 	ASSERT(tcp != NULL);
4284 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4285 
4286 	tcp->tcp_rq = NULL;
4287 	tcp->tcp_wq = NULL;
4288 
4289 	tcp_close_mpp(&tcp->tcp_xmit_head);
4290 	tcp_close_mpp(&tcp->tcp_reass_head);
4291 	if (tcp->tcp_rcv_list != NULL) {
4292 		/* Free b_next chain */
4293 		tcp_close_mpp(&tcp->tcp_rcv_list);
4294 	}
4295 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4296 		freemsg(mp);
4297 	}
4298 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4299 		freemsg(mp);
4300 	}
4301 
4302 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4303 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4304 		freeb(tcp->tcp_fused_sigurg_mp);
4305 		tcp->tcp_fused_sigurg_mp = NULL;
4306 	}
4307 
4308 	if (tcp->tcp_ordrel_mp != NULL) {
4309 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4310 		freeb(tcp->tcp_ordrel_mp);
4311 		tcp->tcp_ordrel_mp = NULL;
4312 	}
4313 
4314 	if (tcp->tcp_ordrel_mp != NULL) {
4315 		freeb(tcp->tcp_ordrel_mp);
4316 		tcp->tcp_ordrel_mp = NULL;
4317 	}
4318 
4319 	if (tcp->tcp_sack_info != NULL) {
4320 		if (tcp->tcp_notsack_list != NULL) {
4321 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4322 		}
4323 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4324 	}
4325 
4326 	if (tcp->tcp_hopopts != NULL) {
4327 		mi_free(tcp->tcp_hopopts);
4328 		tcp->tcp_hopopts = NULL;
4329 		tcp->tcp_hopoptslen = 0;
4330 	}
4331 	ASSERT(tcp->tcp_hopoptslen == 0);
4332 	if (tcp->tcp_dstopts != NULL) {
4333 		mi_free(tcp->tcp_dstopts);
4334 		tcp->tcp_dstopts = NULL;
4335 		tcp->tcp_dstoptslen = 0;
4336 	}
4337 	ASSERT(tcp->tcp_dstoptslen == 0);
4338 	if (tcp->tcp_rtdstopts != NULL) {
4339 		mi_free(tcp->tcp_rtdstopts);
4340 		tcp->tcp_rtdstopts = NULL;
4341 		tcp->tcp_rtdstoptslen = 0;
4342 	}
4343 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4344 	if (tcp->tcp_rthdr != NULL) {
4345 		mi_free(tcp->tcp_rthdr);
4346 		tcp->tcp_rthdr = NULL;
4347 		tcp->tcp_rthdrlen = 0;
4348 	}
4349 	ASSERT(tcp->tcp_rthdrlen == 0);
4350 
4351 	ipp = &tcp->tcp_sticky_ipp;
4352 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4353 	    IPPF_RTHDR))
4354 		ip6_pkt_free(ipp);
4355 
4356 	/*
4357 	 * Free memory associated with the tcp/ip header template.
4358 	 */
4359 
4360 	if (tcp->tcp_iphc != NULL)
4361 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4362 
4363 	/*
4364 	 * Following is really a blowing away a union.
4365 	 * It happens to have exactly two members of identical size
4366 	 * the following code is enough.
4367 	 */
4368 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4369 }
4370 
4371 
4372 /*
4373  * Put a connection confirmation message upstream built from the
4374  * address information within 'iph' and 'tcph'.  Report our success or failure.
4375  */
4376 static boolean_t
4377 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4378     mblk_t **defermp)
4379 {
4380 	sin_t	sin;
4381 	sin6_t	sin6;
4382 	mblk_t	*mp;
4383 	char	*optp = NULL;
4384 	int	optlen = 0;
4385 	cred_t	*cr;
4386 
4387 	if (defermp != NULL)
4388 		*defermp = NULL;
4389 
4390 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4391 		/*
4392 		 * Return in T_CONN_CON results of option negotiation through
4393 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4394 		 * negotiation, then what is received from remote end needs
4395 		 * to be taken into account but there is no such thing (yet?)
4396 		 * in our TCP/IP.
4397 		 * Note: We do not use mi_offset_param() here as
4398 		 * tcp_opts_conn_req contents do not directly come from
4399 		 * an application and are either generated in kernel or
4400 		 * from user input that was already verified.
4401 		 */
4402 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4403 		optp = (char *)(mp->b_rptr +
4404 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4405 		optlen = (int)
4406 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4407 	}
4408 
4409 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4410 		ipha_t *ipha = (ipha_t *)iphdr;
4411 
4412 		/* packet is IPv4 */
4413 		if (tcp->tcp_family == AF_INET) {
4414 			sin = sin_null;
4415 			sin.sin_addr.s_addr = ipha->ipha_src;
4416 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4417 			sin.sin_family = AF_INET;
4418 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4419 			    (int)sizeof (sin_t), optp, optlen);
4420 		} else {
4421 			sin6 = sin6_null;
4422 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4423 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4424 			sin6.sin6_family = AF_INET6;
4425 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4426 			    (int)sizeof (sin6_t), optp, optlen);
4427 
4428 		}
4429 	} else {
4430 		ip6_t	*ip6h = (ip6_t *)iphdr;
4431 
4432 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4433 		ASSERT(tcp->tcp_family == AF_INET6);
4434 		sin6 = sin6_null;
4435 		sin6.sin6_addr = ip6h->ip6_src;
4436 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4437 		sin6.sin6_family = AF_INET6;
4438 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4439 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4440 		    (int)sizeof (sin6_t), optp, optlen);
4441 	}
4442 
4443 	if (!mp)
4444 		return (B_FALSE);
4445 
4446 	if ((cr = DB_CRED(idmp)) != NULL) {
4447 		mblk_setcred(mp, cr);
4448 		DB_CPID(mp) = DB_CPID(idmp);
4449 	}
4450 
4451 	if (defermp == NULL) {
4452 		conn_t *connp = tcp->tcp_connp;
4453 		if (IPCL_IS_NONSTR(connp)) {
4454 			(*connp->conn_upcalls->su_connected)
4455 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4456 			    DB_CPID(mp));
4457 			freemsg(mp);
4458 		} else {
4459 			putnext(tcp->tcp_rq, mp);
4460 		}
4461 	} else {
4462 		*defermp = mp;
4463 	}
4464 
4465 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4466 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4467 	return (B_TRUE);
4468 }
4469 
4470 /*
4471  * Defense for the SYN attack -
4472  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4473  *    one from the list of droppable eagers. This list is a subset of q0.
4474  *    see comments before the definition of MAKE_DROPPABLE().
4475  * 2. Don't drop a SYN request before its first timeout. This gives every
4476  *    request at least til the first timeout to complete its 3-way handshake.
4477  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4478  *    requests currently on the queue that has timed out. This will be used
4479  *    as an indicator of whether an attack is under way, so that appropriate
4480  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4481  *    either when eager goes into ESTABLISHED, or gets freed up.)
4482  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4483  *    # of timeout drops back to <= q0len/32 => SYN alert off
4484  */
4485 static boolean_t
4486 tcp_drop_q0(tcp_t *tcp)
4487 {
4488 	tcp_t	*eager;
4489 	mblk_t	*mp;
4490 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4491 
4492 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4493 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4494 
4495 	/* Pick oldest eager from the list of droppable eagers */
4496 	eager = tcp->tcp_eager_prev_drop_q0;
4497 
4498 	/* If list is empty. return B_FALSE */
4499 	if (eager == tcp) {
4500 		return (B_FALSE);
4501 	}
4502 
4503 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4504 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4505 		return (B_FALSE);
4506 
4507 	/*
4508 	 * Take this eager out from the list of droppable eagers since we are
4509 	 * going to drop it.
4510 	 */
4511 	MAKE_UNDROPPABLE(eager);
4512 
4513 	if (tcp->tcp_debug) {
4514 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4515 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4516 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4517 		    tcp->tcp_conn_req_cnt_q0,
4518 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4519 	}
4520 
4521 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4522 
4523 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4524 	CONN_INC_REF(eager->tcp_connp);
4525 
4526 	/* Mark the IRE created for this SYN request temporary */
4527 	tcp_ip_ire_mark_advice(eager);
4528 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4529 	    tcp_clean_death_wrapper, eager->tcp_connp,
4530 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4531 
4532 	return (B_TRUE);
4533 }
4534 
4535 int
4536 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4537     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4538 {
4539 	tcp_t 		*ltcp = lconnp->conn_tcp;
4540 	tcp_t		*tcp = connp->conn_tcp;
4541 	mblk_t		*tpi_mp;
4542 	ipha_t		*ipha;
4543 	ip6_t		*ip6h;
4544 	sin6_t 		sin6;
4545 	in6_addr_t 	v6dst;
4546 	int		err;
4547 	int		ifindex = 0;
4548 	cred_t		*cr;
4549 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4550 
4551 	if (ipvers == IPV4_VERSION) {
4552 		ipha = (ipha_t *)mp->b_rptr;
4553 
4554 		connp->conn_send = ip_output;
4555 		connp->conn_recv = tcp_input;
4556 
4557 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4558 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4559 
4560 		sin6 = sin6_null;
4561 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4562 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4563 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4564 		sin6.sin6_family = AF_INET6;
4565 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4566 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4567 		if (tcp->tcp_recvdstaddr) {
4568 			sin6_t	sin6d;
4569 
4570 			sin6d = sin6_null;
4571 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4572 			    &sin6d.sin6_addr);
4573 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4574 			sin6d.sin6_family = AF_INET;
4575 			tpi_mp = mi_tpi_extconn_ind(NULL,
4576 			    (char *)&sin6d, sizeof (sin6_t),
4577 			    (char *)&tcp,
4578 			    (t_scalar_t)sizeof (intptr_t),
4579 			    (char *)&sin6d, sizeof (sin6_t),
4580 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4581 		} else {
4582 			tpi_mp = mi_tpi_conn_ind(NULL,
4583 			    (char *)&sin6, sizeof (sin6_t),
4584 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4585 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4586 		}
4587 	} else {
4588 		ip6h = (ip6_t *)mp->b_rptr;
4589 
4590 		connp->conn_send = ip_output_v6;
4591 		connp->conn_recv = tcp_input;
4592 
4593 		connp->conn_srcv6 = ip6h->ip6_dst;
4594 		connp->conn_remv6 = ip6h->ip6_src;
4595 
4596 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4597 		ifindex = (int)DB_CKSUMSTUFF(mp);
4598 		DB_CKSUMSTUFF(mp) = 0;
4599 
4600 		sin6 = sin6_null;
4601 		sin6.sin6_addr = ip6h->ip6_src;
4602 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4603 		sin6.sin6_family = AF_INET6;
4604 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4605 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4606 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4607 
4608 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4609 			/* Pass up the scope_id of remote addr */
4610 			sin6.sin6_scope_id = ifindex;
4611 		} else {
4612 			sin6.sin6_scope_id = 0;
4613 		}
4614 		if (tcp->tcp_recvdstaddr) {
4615 			sin6_t	sin6d;
4616 
4617 			sin6d = sin6_null;
4618 			sin6.sin6_addr = ip6h->ip6_dst;
4619 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4620 			sin6d.sin6_family = AF_INET;
4621 			tpi_mp = mi_tpi_extconn_ind(NULL,
4622 			    (char *)&sin6d, sizeof (sin6_t),
4623 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4624 			    (char *)&sin6d, sizeof (sin6_t),
4625 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4626 		} else {
4627 			tpi_mp = mi_tpi_conn_ind(NULL,
4628 			    (char *)&sin6, sizeof (sin6_t),
4629 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4630 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4631 		}
4632 	}
4633 
4634 	if (tpi_mp == NULL)
4635 		return (ENOMEM);
4636 
4637 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4638 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4639 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4640 	connp->conn_fully_bound = B_FALSE;
4641 
4642 	/* Inherit information from the "parent" */
4643 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4644 	tcp->tcp_family = ltcp->tcp_family;
4645 
4646 	tcp->tcp_wq = ltcp->tcp_wq;
4647 	tcp->tcp_rq = ltcp->tcp_rq;
4648 
4649 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4650 	tcp->tcp_detached = B_TRUE;
4651 	SOCK_CONNID_INIT(tcp->tcp_connid);
4652 	if ((err = tcp_init_values(tcp)) != 0) {
4653 		freemsg(tpi_mp);
4654 		return (err);
4655 	}
4656 
4657 	if (ipvers == IPV4_VERSION) {
4658 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4659 			freemsg(tpi_mp);
4660 			return (err);
4661 		}
4662 		ASSERT(tcp->tcp_ipha != NULL);
4663 	} else {
4664 		/* ifindex must be already set */
4665 		ASSERT(ifindex != 0);
4666 
4667 		if (ltcp->tcp_bound_if != 0) {
4668 			/*
4669 			 * Set newtcp's bound_if equal to
4670 			 * listener's value. If ifindex is
4671 			 * not the same as ltcp->tcp_bound_if,
4672 			 * it must be a packet for the ipmp group
4673 			 * of interfaces
4674 			 */
4675 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4676 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4677 			tcp->tcp_bound_if = ifindex;
4678 		}
4679 
4680 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4681 		tcp->tcp_recvifindex = 0;
4682 		tcp->tcp_recvhops = 0xffffffffU;
4683 		ASSERT(tcp->tcp_ip6h != NULL);
4684 	}
4685 
4686 	tcp->tcp_lport = ltcp->tcp_lport;
4687 
4688 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4689 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4690 			/*
4691 			 * Listener had options of some sort; eager inherits.
4692 			 * Free up the eager template and allocate one
4693 			 * of the right size.
4694 			 */
4695 			if (tcp->tcp_hdr_grown) {
4696 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4697 			} else {
4698 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4699 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4700 			}
4701 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4702 			    KM_NOSLEEP);
4703 			if (tcp->tcp_iphc == NULL) {
4704 				tcp->tcp_iphc_len = 0;
4705 				freemsg(tpi_mp);
4706 				return (ENOMEM);
4707 			}
4708 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4709 			tcp->tcp_hdr_grown = B_TRUE;
4710 		}
4711 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4712 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4713 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4714 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4715 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4716 
4717 		/*
4718 		 * Copy the IP+TCP header template from listener to eager
4719 		 */
4720 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4721 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4722 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4723 			    IPPROTO_RAW) {
4724 				tcp->tcp_ip6h =
4725 				    (ip6_t *)(tcp->tcp_iphc +
4726 				    sizeof (ip6i_t));
4727 			} else {
4728 				tcp->tcp_ip6h =
4729 				    (ip6_t *)(tcp->tcp_iphc);
4730 			}
4731 			tcp->tcp_ipha = NULL;
4732 		} else {
4733 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4734 			tcp->tcp_ip6h = NULL;
4735 		}
4736 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4737 		    tcp->tcp_ip_hdr_len);
4738 	} else {
4739 		/*
4740 		 * only valid case when ipversion of listener and
4741 		 * eager differ is when listener is IPv6 and
4742 		 * eager is IPv4.
4743 		 * Eager header template has been initialized to the
4744 		 * maximum v4 header sizes, which includes space for
4745 		 * TCP and IP options.
4746 		 */
4747 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4748 		    (tcp->tcp_ipversion == IPV4_VERSION));
4749 		ASSERT(tcp->tcp_iphc_len >=
4750 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4751 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4752 		/* copy IP header fields individually */
4753 		tcp->tcp_ipha->ipha_ttl =
4754 		    ltcp->tcp_ip6h->ip6_hops;
4755 		bcopy(ltcp->tcp_tcph->th_lport,
4756 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4757 	}
4758 
4759 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4760 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4761 	    sizeof (in_port_t));
4762 
4763 	if (ltcp->tcp_lport == 0) {
4764 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4765 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4766 		    sizeof (in_port_t));
4767 	}
4768 
4769 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4770 		ASSERT(ipha != NULL);
4771 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4772 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4773 
4774 		/* Source routing option copyover (reverse it) */
4775 		if (tcps->tcps_rev_src_routes)
4776 			tcp_opt_reverse(tcp, ipha);
4777 	} else {
4778 		ASSERT(ip6h != NULL);
4779 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4780 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4781 	}
4782 
4783 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4784 	ASSERT(!tcp->tcp_tconnind_started);
4785 	/*
4786 	 * If the SYN contains a credential, it's a loopback packet; attach
4787 	 * the credential to the TPI message.
4788 	 */
4789 	if ((cr = DB_CRED(idmp)) != NULL) {
4790 		mblk_setcred(tpi_mp, cr);
4791 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4792 	}
4793 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4794 
4795 	/* Inherit the listener's SSL protection state */
4796 
4797 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4798 		kssl_hold_ent(tcp->tcp_kssl_ent);
4799 		tcp->tcp_kssl_pending = B_TRUE;
4800 	}
4801 
4802 	/* Inherit the listener's non-STREAMS flag */
4803 	if (IPCL_IS_NONSTR(lconnp)) {
4804 		connp->conn_flags |= IPCL_NONSTR;
4805 		connp->conn_upcalls = lconnp->conn_upcalls;
4806 	}
4807 
4808 	return (0);
4809 }
4810 
4811 
4812 int
4813 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4814     tcph_t *tcph, mblk_t *idmp)
4815 {
4816 	tcp_t 		*ltcp = lconnp->conn_tcp;
4817 	tcp_t		*tcp = connp->conn_tcp;
4818 	sin_t		sin;
4819 	mblk_t		*tpi_mp = NULL;
4820 	int		err;
4821 	cred_t		*cr;
4822 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4823 
4824 	sin = sin_null;
4825 	sin.sin_addr.s_addr = ipha->ipha_src;
4826 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4827 	sin.sin_family = AF_INET;
4828 	if (ltcp->tcp_recvdstaddr) {
4829 		sin_t	sind;
4830 
4831 		sind = sin_null;
4832 		sind.sin_addr.s_addr = ipha->ipha_dst;
4833 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4834 		sind.sin_family = AF_INET;
4835 		tpi_mp = mi_tpi_extconn_ind(NULL,
4836 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4837 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4838 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4839 	} else {
4840 		tpi_mp = mi_tpi_conn_ind(NULL,
4841 		    (char *)&sin, sizeof (sin_t),
4842 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4843 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4844 	}
4845 
4846 	if (tpi_mp == NULL) {
4847 		return (ENOMEM);
4848 	}
4849 
4850 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4851 	connp->conn_send = ip_output;
4852 	connp->conn_recv = tcp_input;
4853 	connp->conn_fully_bound = B_FALSE;
4854 
4855 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4856 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4857 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4858 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4859 
4860 	/* Inherit information from the "parent" */
4861 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4862 	tcp->tcp_family = ltcp->tcp_family;
4863 	tcp->tcp_wq = ltcp->tcp_wq;
4864 	tcp->tcp_rq = ltcp->tcp_rq;
4865 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4866 	tcp->tcp_detached = B_TRUE;
4867 	SOCK_CONNID_INIT(tcp->tcp_connid);
4868 	if ((err = tcp_init_values(tcp)) != 0) {
4869 		freemsg(tpi_mp);
4870 		return (err);
4871 	}
4872 
4873 	/*
4874 	 * Let's make sure that eager tcp template has enough space to
4875 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4876 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4877 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4878 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4879 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4880 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4881 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4882 	 */
4883 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4884 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4885 
4886 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4887 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4888 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4889 	tcp->tcp_ttl = ltcp->tcp_ttl;
4890 	tcp->tcp_tos = ltcp->tcp_tos;
4891 
4892 	/* Copy the IP+TCP header template from listener to eager */
4893 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4894 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4895 	tcp->tcp_ip6h = NULL;
4896 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4897 	    tcp->tcp_ip_hdr_len);
4898 
4899 	/* Initialize the IP addresses and Ports */
4900 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4901 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4902 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4903 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4904 
4905 	/* Source routing option copyover (reverse it) */
4906 	if (tcps->tcps_rev_src_routes)
4907 		tcp_opt_reverse(tcp, ipha);
4908 
4909 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4910 	ASSERT(!tcp->tcp_tconnind_started);
4911 
4912 	/*
4913 	 * If the SYN contains a credential, it's a loopback packet; attach
4914 	 * the credential to the TPI message.
4915 	 */
4916 	if ((cr = DB_CRED(idmp)) != NULL) {
4917 		mblk_setcred(tpi_mp, cr);
4918 		DB_CPID(tpi_mp) = DB_CPID(idmp);
4919 	}
4920 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4921 
4922 	/* Inherit the listener's SSL protection state */
4923 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4924 		kssl_hold_ent(tcp->tcp_kssl_ent);
4925 		tcp->tcp_kssl_pending = B_TRUE;
4926 	}
4927 
4928 	/* Inherit the listener's non-STREAMS flag */
4929 	if (IPCL_IS_NONSTR(lconnp)) {
4930 		connp->conn_flags |= IPCL_NONSTR;
4931 		connp->conn_upcalls = lconnp->conn_upcalls;
4932 	}
4933 
4934 	return (0);
4935 }
4936 
4937 /*
4938  * sets up conn for ipsec.
4939  * if the first mblk is M_CTL it is consumed and mpp is updated.
4940  * in case of error mpp is freed.
4941  */
4942 conn_t *
4943 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4944 {
4945 	conn_t 		*connp = tcp->tcp_connp;
4946 	conn_t 		*econnp;
4947 	squeue_t 	*new_sqp;
4948 	mblk_t 		*first_mp = *mpp;
4949 	mblk_t		*mp = *mpp;
4950 	boolean_t	mctl_present = B_FALSE;
4951 	uint_t		ipvers;
4952 
4953 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4954 	if (econnp == NULL) {
4955 		freemsg(first_mp);
4956 		return (NULL);
4957 	}
4958 	if (DB_TYPE(mp) == M_CTL) {
4959 		if (mp->b_cont == NULL ||
4960 		    mp->b_cont->b_datap->db_type != M_DATA) {
4961 			freemsg(first_mp);
4962 			return (NULL);
4963 		}
4964 		mp = mp->b_cont;
4965 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4966 			freemsg(first_mp);
4967 			return (NULL);
4968 		}
4969 
4970 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4971 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4972 		mctl_present = B_TRUE;
4973 	} else {
4974 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4975 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4976 	}
4977 
4978 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4979 	DB_CKSUMSTART(mp) = 0;
4980 
4981 	ASSERT(OK_32PTR(mp->b_rptr));
4982 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
4983 	if (ipvers == IPV4_VERSION) {
4984 		uint16_t  	*up;
4985 		uint32_t	ports;
4986 		ipha_t		*ipha;
4987 
4988 		ipha = (ipha_t *)mp->b_rptr;
4989 		up = (uint16_t *)((uchar_t *)ipha +
4990 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
4991 		ports = *(uint32_t *)up;
4992 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
4993 		    ipha->ipha_dst, ipha->ipha_src, ports);
4994 	} else {
4995 		uint16_t  	*up;
4996 		uint32_t	ports;
4997 		uint16_t	ip_hdr_len;
4998 		uint8_t		*nexthdrp;
4999 		ip6_t 		*ip6h;
5000 		tcph_t		*tcph;
5001 
5002 		ip6h = (ip6_t *)mp->b_rptr;
5003 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5004 			ip_hdr_len = IPV6_HDR_LEN;
5005 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5006 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5007 			CONN_DEC_REF(econnp);
5008 			freemsg(first_mp);
5009 			return (NULL);
5010 		}
5011 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5012 		up = (uint16_t *)tcph->th_lport;
5013 		ports = *(uint32_t *)up;
5014 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5015 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5016 	}
5017 
5018 	/*
5019 	 * The caller already ensured that there is a sqp present.
5020 	 */
5021 	econnp->conn_sqp = new_sqp;
5022 	econnp->conn_initial_sqp = new_sqp;
5023 
5024 	if (connp->conn_policy != NULL) {
5025 		ipsec_in_t *ii;
5026 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5027 		ASSERT(ii->ipsec_in_policy == NULL);
5028 		IPPH_REFHOLD(connp->conn_policy);
5029 		ii->ipsec_in_policy = connp->conn_policy;
5030 
5031 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5032 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5033 			CONN_DEC_REF(econnp);
5034 			freemsg(first_mp);
5035 			return (NULL);
5036 		}
5037 	}
5038 
5039 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5040 		CONN_DEC_REF(econnp);
5041 		freemsg(first_mp);
5042 		return (NULL);
5043 	}
5044 
5045 	/*
5046 	 * If we know we have some policy, pass the "IPSEC"
5047 	 * options size TCP uses this adjust the MSS.
5048 	 */
5049 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5050 	if (mctl_present) {
5051 		freeb(first_mp);
5052 		*mpp = mp;
5053 	}
5054 
5055 	return (econnp);
5056 }
5057 
5058 /*
5059  * tcp_get_conn/tcp_free_conn
5060  *
5061  * tcp_get_conn is used to get a clean tcp connection structure.
5062  * It tries to reuse the connections put on the freelist by the
5063  * time_wait_collector failing which it goes to kmem_cache. This
5064  * way has two benefits compared to just allocating from and
5065  * freeing to kmem_cache.
5066  * 1) The time_wait_collector can free (which includes the cleanup)
5067  * outside the squeue. So when the interrupt comes, we have a clean
5068  * connection sitting in the freelist. Obviously, this buys us
5069  * performance.
5070  *
5071  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5072  * has multiple disadvantages - tying up the squeue during alloc, and the
5073  * fact that IPSec policy initialization has to happen here which
5074  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5075  * But allocating the conn/tcp in IP land is also not the best since
5076  * we can't check the 'q' and 'q0' which are protected by squeue and
5077  * blindly allocate memory which might have to be freed here if we are
5078  * not allowed to accept the connection. By using the freelist and
5079  * putting the conn/tcp back in freelist, we don't pay a penalty for
5080  * allocating memory without checking 'q/q0' and freeing it if we can't
5081  * accept the connection.
5082  *
5083  * Care should be taken to put the conn back in the same squeue's freelist
5084  * from which it was allocated. Best results are obtained if conn is
5085  * allocated from listener's squeue and freed to the same. Time wait
5086  * collector will free up the freelist is the connection ends up sitting
5087  * there for too long.
5088  */
5089 void *
5090 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5091 {
5092 	tcp_t			*tcp = NULL;
5093 	conn_t			*connp = NULL;
5094 	squeue_t		*sqp = (squeue_t *)arg;
5095 	tcp_squeue_priv_t 	*tcp_time_wait;
5096 	netstack_t		*ns;
5097 
5098 	tcp_time_wait =
5099 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5100 
5101 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5102 	tcp = tcp_time_wait->tcp_free_list;
5103 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5104 	if (tcp != NULL) {
5105 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5106 		tcp_time_wait->tcp_free_list_cnt--;
5107 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5108 		tcp->tcp_time_wait_next = NULL;
5109 		connp = tcp->tcp_connp;
5110 		connp->conn_flags |= IPCL_REUSED;
5111 
5112 		ASSERT(tcp->tcp_tcps == NULL);
5113 		ASSERT(connp->conn_netstack == NULL);
5114 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5115 		ns = tcps->tcps_netstack;
5116 		netstack_hold(ns);
5117 		connp->conn_netstack = ns;
5118 		tcp->tcp_tcps = tcps;
5119 		TCPS_REFHOLD(tcps);
5120 		ipcl_globalhash_insert(connp);
5121 		return ((void *)connp);
5122 	}
5123 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5124 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5125 	    tcps->tcps_netstack)) == NULL)
5126 		return (NULL);
5127 	tcp = connp->conn_tcp;
5128 	/*
5129 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5130 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5131 	 */
5132 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5133 		ipcl_conn_destroy(connp);
5134 		return (NULL);
5135 	}
5136 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5137 	tcp->tcp_tcps = tcps;
5138 	TCPS_REFHOLD(tcps);
5139 
5140 	return ((void *)connp);
5141 }
5142 
5143 /*
5144  * Update the cached label for the given tcp_t.  This should be called once per
5145  * connection, and before any packets are sent or tcp_process_options is
5146  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5147  */
5148 static boolean_t
5149 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5150 {
5151 	conn_t *connp = tcp->tcp_connp;
5152 
5153 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5154 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5155 		int added;
5156 
5157 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5158 		    connp->conn_mac_exempt,
5159 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5160 			return (B_FALSE);
5161 
5162 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5163 		if (added == -1)
5164 			return (B_FALSE);
5165 		tcp->tcp_hdr_len += added;
5166 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5167 		tcp->tcp_ip_hdr_len += added;
5168 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5169 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5170 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5171 			    tcp->tcp_hdr_len);
5172 			if (added == -1)
5173 				return (B_FALSE);
5174 			tcp->tcp_hdr_len += added;
5175 			tcp->tcp_tcph = (tcph_t *)
5176 			    ((uchar_t *)tcp->tcp_tcph + added);
5177 			tcp->tcp_ip_hdr_len += added;
5178 		}
5179 	} else {
5180 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5181 
5182 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5183 		    connp->conn_mac_exempt,
5184 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5185 			return (B_FALSE);
5186 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5187 		    &tcp->tcp_label_len, optbuf) != 0)
5188 			return (B_FALSE);
5189 		if (tcp_build_hdrs(tcp) != 0)
5190 			return (B_FALSE);
5191 	}
5192 
5193 	connp->conn_ulp_labeled = 1;
5194 
5195 	return (B_TRUE);
5196 }
5197 
5198 /* BEGIN CSTYLED */
5199 /*
5200  *
5201  * The sockfs ACCEPT path:
5202  * =======================
5203  *
5204  * The eager is now established in its own perimeter as soon as SYN is
5205  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5206  * completes the accept processing on the acceptor STREAM. The sending
5207  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5208  * listener but a TLI/XTI listener completes the accept processing
5209  * on the listener perimeter.
5210  *
5211  * Common control flow for 3 way handshake:
5212  * ----------------------------------------
5213  *
5214  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5215  *					-> tcp_conn_request()
5216  *
5217  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5218  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5219  *
5220  * Sockfs ACCEPT Path:
5221  * -------------------
5222  *
5223  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5224  * as STREAM entry point)
5225  *
5226  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5227  *
5228  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5229  * association (we are not behind eager's squeue but sockfs is protecting us
5230  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5231  * is changed to point at tcp_wput().
5232  *
5233  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5234  * listener (done on listener's perimeter).
5235  *
5236  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5237  * accept.
5238  *
5239  * TLI/XTI client ACCEPT path:
5240  * ---------------------------
5241  *
5242  * soaccept() sends T_CONN_RES on the listener STREAM.
5243  *
5244  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5245  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5246  *
5247  * Locks:
5248  * ======
5249  *
5250  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5251  * and listeners->tcp_eager_next_q.
5252  *
5253  * Referencing:
5254  * ============
5255  *
5256  * 1) We start out in tcp_conn_request by eager placing a ref on
5257  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5258  *
5259  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5260  * doing so we place a ref on the eager. This ref is finally dropped at the
5261  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5262  * reference is dropped by the squeue framework.
5263  *
5264  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5265  *
5266  * The reference must be released by the same entity that added the reference
5267  * In the above scheme, the eager is the entity that adds and releases the
5268  * references. Note that tcp_accept_finish executes in the squeue of the eager
5269  * (albeit after it is attached to the acceptor stream). Though 1. executes
5270  * in the listener's squeue, the eager is nascent at this point and the
5271  * reference can be considered to have been added on behalf of the eager.
5272  *
5273  * Eager getting a Reset or listener closing:
5274  * ==========================================
5275  *
5276  * Once the listener and eager are linked, the listener never does the unlink.
5277  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5278  * a message on all eager perimeter. The eager then does the unlink, clears
5279  * any pointers to the listener's queue and drops the reference to the
5280  * listener. The listener waits in tcp_close outside the squeue until its
5281  * refcount has dropped to 1. This ensures that the listener has waited for
5282  * all eagers to clear their association with the listener.
5283  *
5284  * Similarly, if eager decides to go away, it can unlink itself and close.
5285  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5286  * the reference to eager is still valid because of the extra ref we put
5287  * in tcp_send_conn_ind.
5288  *
5289  * Listener can always locate the eager under the protection
5290  * of the listener->tcp_eager_lock, and then do a refhold
5291  * on the eager during the accept processing.
5292  *
5293  * The acceptor stream accesses the eager in the accept processing
5294  * based on the ref placed on eager before sending T_conn_ind.
5295  * The only entity that can negate this refhold is a listener close
5296  * which is mutually exclusive with an active acceptor stream.
5297  *
5298  * Eager's reference on the listener
5299  * ===================================
5300  *
5301  * If the accept happens (even on a closed eager) the eager drops its
5302  * reference on the listener at the start of tcp_accept_finish. If the
5303  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5304  * the reference is dropped in tcp_closei_local. If the listener closes,
5305  * the reference is dropped in tcp_eager_kill. In all cases the reference
5306  * is dropped while executing in the eager's context (squeue).
5307  */
5308 /* END CSTYLED */
5309 
5310 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5311 
5312 /*
5313  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5314  * tcp_rput_data will not see any SYN packets.
5315  */
5316 /* ARGSUSED */
5317 void
5318 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5319 {
5320 	tcph_t		*tcph;
5321 	uint32_t	seg_seq;
5322 	tcp_t		*eager;
5323 	uint_t		ipvers;
5324 	ipha_t		*ipha;
5325 	ip6_t		*ip6h;
5326 	int		err;
5327 	conn_t		*econnp = NULL;
5328 	squeue_t	*new_sqp;
5329 	mblk_t		*mp1;
5330 	uint_t 		ip_hdr_len;
5331 	conn_t		*connp = (conn_t *)arg;
5332 	tcp_t		*tcp = connp->conn_tcp;
5333 	cred_t		*credp;
5334 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5335 	ip_stack_t	*ipst;
5336 
5337 	if (tcp->tcp_state != TCPS_LISTEN)
5338 		goto error2;
5339 
5340 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5341 
5342 	mutex_enter(&tcp->tcp_eager_lock);
5343 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5344 		mutex_exit(&tcp->tcp_eager_lock);
5345 		TCP_STAT(tcps, tcp_listendrop);
5346 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5347 		if (tcp->tcp_debug) {
5348 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5349 			    "tcp_conn_request: listen backlog (max=%d) "
5350 			    "overflow (%d pending) on %s",
5351 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5352 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5353 		}
5354 		goto error2;
5355 	}
5356 
5357 	if (tcp->tcp_conn_req_cnt_q0 >=
5358 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5359 		/*
5360 		 * Q0 is full. Drop a pending half-open req from the queue
5361 		 * to make room for the new SYN req. Also mark the time we
5362 		 * drop a SYN.
5363 		 *
5364 		 * A more aggressive defense against SYN attack will
5365 		 * be to set the "tcp_syn_defense" flag now.
5366 		 */
5367 		TCP_STAT(tcps, tcp_listendropq0);
5368 		tcp->tcp_last_rcv_lbolt = lbolt64;
5369 		if (!tcp_drop_q0(tcp)) {
5370 			mutex_exit(&tcp->tcp_eager_lock);
5371 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5372 			if (tcp->tcp_debug) {
5373 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5374 				    "tcp_conn_request: listen half-open queue "
5375 				    "(max=%d) full (%d pending) on %s",
5376 				    tcps->tcps_conn_req_max_q0,
5377 				    tcp->tcp_conn_req_cnt_q0,
5378 				    tcp_display(tcp, NULL,
5379 				    DISP_PORT_ONLY));
5380 			}
5381 			goto error2;
5382 		}
5383 	}
5384 	mutex_exit(&tcp->tcp_eager_lock);
5385 
5386 	/*
5387 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5388 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5389 	 * link local address.  If IPSec is enabled, db_struioflag has
5390 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5391 	 * otherwise an error case if neither of them is set.
5392 	 */
5393 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5394 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5395 		DB_CKSUMSTART(mp) = 0;
5396 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5397 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5398 		if (econnp == NULL)
5399 			goto error2;
5400 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5401 		econnp->conn_sqp = new_sqp;
5402 		econnp->conn_initial_sqp = new_sqp;
5403 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5404 		/*
5405 		 * mp is updated in tcp_get_ipsec_conn().
5406 		 */
5407 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5408 		if (econnp == NULL) {
5409 			/*
5410 			 * mp freed by tcp_get_ipsec_conn.
5411 			 */
5412 			return;
5413 		}
5414 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5415 	} else {
5416 		goto error2;
5417 	}
5418 
5419 	ASSERT(DB_TYPE(mp) == M_DATA);
5420 
5421 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5422 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5423 	ASSERT(OK_32PTR(mp->b_rptr));
5424 	if (ipvers == IPV4_VERSION) {
5425 		ipha = (ipha_t *)mp->b_rptr;
5426 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5427 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5428 	} else {
5429 		ip6h = (ip6_t *)mp->b_rptr;
5430 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5431 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5432 	}
5433 
5434 	if (tcp->tcp_family == AF_INET) {
5435 		ASSERT(ipvers == IPV4_VERSION);
5436 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5437 	} else {
5438 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5439 	}
5440 
5441 	if (err)
5442 		goto error3;
5443 
5444 	eager = econnp->conn_tcp;
5445 
5446 	/*
5447 	 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that at close
5448 	 * time, we will always have that to send up.  Otherwise, we need to do
5449 	 * special handling in case the allocation fails at that time.
5450 	 */
5451 	ASSERT(eager->tcp_ordrel_mp == NULL);
5452 	if (!IPCL_IS_NONSTR(econnp) &&
5453 	    (eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5454 		goto error3;
5455 
5456 	/* Inherit various TCP parameters from the listener */
5457 	eager->tcp_naglim = tcp->tcp_naglim;
5458 	eager->tcp_first_timer_threshold =
5459 	    tcp->tcp_first_timer_threshold;
5460 	eager->tcp_second_timer_threshold =
5461 	    tcp->tcp_second_timer_threshold;
5462 
5463 	eager->tcp_first_ctimer_threshold =
5464 	    tcp->tcp_first_ctimer_threshold;
5465 	eager->tcp_second_ctimer_threshold =
5466 	    tcp->tcp_second_ctimer_threshold;
5467 
5468 	/*
5469 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5470 	 * If it does not, the eager's receive window will be set to the
5471 	 * listener's receive window later in this function.
5472 	 */
5473 	eager->tcp_rwnd = 0;
5474 
5475 	/*
5476 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5477 	 * calling tcp_process_options() where tcp_mss_set() is called
5478 	 * to set the initial cwnd.
5479 	 */
5480 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5481 
5482 	/*
5483 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5484 	 * zone id before the accept is completed in tcp_wput_accept().
5485 	 */
5486 	econnp->conn_zoneid = connp->conn_zoneid;
5487 	econnp->conn_allzones = connp->conn_allzones;
5488 
5489 	/* Copy nexthop information from listener to eager */
5490 	if (connp->conn_nexthop_set) {
5491 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5492 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5493 	}
5494 
5495 	/*
5496 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5497 	 * eager is accepted
5498 	 */
5499 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5500 	crhold(credp);
5501 
5502 	/*
5503 	 * If the caller has the process-wide flag set, then default to MAC
5504 	 * exempt mode.  This allows read-down to unlabeled hosts.
5505 	 */
5506 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5507 		econnp->conn_mac_exempt = B_TRUE;
5508 
5509 	if (is_system_labeled()) {
5510 		cred_t *cr;
5511 
5512 		if (connp->conn_mlp_type != mlptSingle) {
5513 			cr = econnp->conn_peercred = DB_CRED(mp);
5514 			if (cr != NULL)
5515 				crhold(cr);
5516 			else
5517 				cr = econnp->conn_cred;
5518 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5519 			    econnp, cred_t *, cr)
5520 		} else {
5521 			cr = econnp->conn_cred;
5522 			DTRACE_PROBE2(syn_accept, conn_t *,
5523 			    econnp, cred_t *, cr)
5524 		}
5525 
5526 		if (!tcp_update_label(eager, cr)) {
5527 			DTRACE_PROBE3(
5528 			    tx__ip__log__error__connrequest__tcp,
5529 			    char *, "eager connp(1) label on SYN mp(2) failed",
5530 			    conn_t *, econnp, mblk_t *, mp);
5531 			goto error3;
5532 		}
5533 	}
5534 
5535 	eager->tcp_hard_binding = B_TRUE;
5536 
5537 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5538 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5539 
5540 	CL_INET_CONNECT(eager);
5541 
5542 	/*
5543 	 * No need to check for multicast destination since ip will only pass
5544 	 * up multicasts to those that have expressed interest
5545 	 * TODO: what about rejecting broadcasts?
5546 	 * Also check that source is not a multicast or broadcast address.
5547 	 */
5548 	eager->tcp_state = TCPS_SYN_RCVD;
5549 
5550 
5551 	/*
5552 	 * There should be no ire in the mp as we are being called after
5553 	 * receiving the SYN.
5554 	 */
5555 	ASSERT(tcp_ire_mp(&mp) == NULL);
5556 
5557 	/*
5558 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5559 	 */
5560 
5561 	if (tcp_adapt_ire(eager, NULL) == 0) {
5562 		/* Undo the bind_hash_insert */
5563 		tcp_bind_hash_remove(eager);
5564 		goto error3;
5565 	}
5566 
5567 	/* Process all TCP options. */
5568 	tcp_process_options(eager, tcph);
5569 
5570 	/* Is the other end ECN capable? */
5571 	if (tcps->tcps_ecn_permitted >= 1 &&
5572 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5573 		eager->tcp_ecn_ok = B_TRUE;
5574 	}
5575 
5576 	/*
5577 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5578 	 * window size changed via SO_RCVBUF option.  First round up the
5579 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5580 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5581 	 * setting.
5582 	 *
5583 	 * Note if there is a rpipe metric associated with the remote host,
5584 	 * we should not inherit receive window size from listener.
5585 	 */
5586 	eager->tcp_rwnd = MSS_ROUNDUP(
5587 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5588 	    eager->tcp_rwnd), eager->tcp_mss);
5589 	if (eager->tcp_snd_ws_ok)
5590 		tcp_set_ws_value(eager);
5591 	/*
5592 	 * Note that this is the only place tcp_rwnd_set() is called for
5593 	 * accepting a connection.  We need to call it here instead of
5594 	 * after the 3-way handshake because we need to tell the other
5595 	 * side our rwnd in the SYN-ACK segment.
5596 	 */
5597 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5598 
5599 	/*
5600 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5601 	 * via soaccept()->soinheritoptions() which essentially applies
5602 	 * all the listener options to the new STREAM. The options that we
5603 	 * need to take care of are:
5604 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5605 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5606 	 * SO_SNDBUF, SO_RCVBUF.
5607 	 *
5608 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5609 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5610 	 *		tcp_maxpsz_set() gets called later from
5611 	 *		tcp_accept_finish(), the option takes effect.
5612 	 *
5613 	 */
5614 	/* Set the TCP options */
5615 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5616 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5617 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5618 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5619 	eager->tcp_oobinline = tcp->tcp_oobinline;
5620 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5621 	eager->tcp_broadcast = tcp->tcp_broadcast;
5622 	eager->tcp_useloopback = tcp->tcp_useloopback;
5623 	eager->tcp_dontroute = tcp->tcp_dontroute;
5624 	eager->tcp_debug = tcp->tcp_debug;
5625 	eager->tcp_linger = tcp->tcp_linger;
5626 	eager->tcp_lingertime = tcp->tcp_lingertime;
5627 	if (tcp->tcp_ka_enabled)
5628 		eager->tcp_ka_enabled = 1;
5629 
5630 	/* Set the IP options */
5631 	econnp->conn_broadcast = connp->conn_broadcast;
5632 	econnp->conn_loopback = connp->conn_loopback;
5633 	econnp->conn_dontroute = connp->conn_dontroute;
5634 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5635 
5636 	/* Put a ref on the listener for the eager. */
5637 	CONN_INC_REF(connp);
5638 	mutex_enter(&tcp->tcp_eager_lock);
5639 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5640 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5641 	tcp->tcp_eager_next_q0 = eager;
5642 	eager->tcp_eager_prev_q0 = tcp;
5643 
5644 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5645 	eager->tcp_listener = tcp;
5646 	eager->tcp_saved_listener = tcp;
5647 
5648 	/*
5649 	 * Tag this detached tcp vector for later retrieval
5650 	 * by our listener client in tcp_accept().
5651 	 */
5652 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5653 	tcp->tcp_conn_req_cnt_q0++;
5654 	if (++tcp->tcp_conn_req_seqnum == -1) {
5655 		/*
5656 		 * -1 is "special" and defined in TPI as something
5657 		 * that should never be used in T_CONN_IND
5658 		 */
5659 		++tcp->tcp_conn_req_seqnum;
5660 	}
5661 	mutex_exit(&tcp->tcp_eager_lock);
5662 
5663 	if (tcp->tcp_syn_defense) {
5664 		/* Don't drop the SYN that comes from a good IP source */
5665 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5666 		if (addr_cache != NULL && eager->tcp_remote ==
5667 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5668 			eager->tcp_dontdrop = B_TRUE;
5669 		}
5670 	}
5671 
5672 	/*
5673 	 * We need to insert the eager in its own perimeter but as soon
5674 	 * as we do that, we expose the eager to the classifier and
5675 	 * should not touch any field outside the eager's perimeter.
5676 	 * So do all the work necessary before inserting the eager
5677 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5678 	 * will succeed but undo everything if it fails.
5679 	 */
5680 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5681 	eager->tcp_irs = seg_seq;
5682 	eager->tcp_rack = seg_seq;
5683 	eager->tcp_rnxt = seg_seq + 1;
5684 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5685 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5686 	eager->tcp_state = TCPS_SYN_RCVD;
5687 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5688 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5689 	if (mp1 == NULL) {
5690 		/*
5691 		 * Increment the ref count as we are going to
5692 		 * enqueueing an mp in squeue
5693 		 */
5694 		CONN_INC_REF(econnp);
5695 		goto error;
5696 	}
5697 	DB_CPID(mp1) = tcp->tcp_cpid;
5698 	mblk_setcred(mp1, tcp->tcp_cred);
5699 	eager->tcp_cpid = tcp->tcp_cpid;
5700 	eager->tcp_open_time = lbolt64;
5701 
5702 	/*
5703 	 * We need to start the rto timer. In normal case, we start
5704 	 * the timer after sending the packet on the wire (or at
5705 	 * least believing that packet was sent by waiting for
5706 	 * CALL_IP_WPUT() to return). Since this is the first packet
5707 	 * being sent on the wire for the eager, our initial tcp_rto
5708 	 * is at least tcp_rexmit_interval_min which is a fairly
5709 	 * large value to allow the algorithm to adjust slowly to large
5710 	 * fluctuations of RTT during first few transmissions.
5711 	 *
5712 	 * Starting the timer first and then sending the packet in this
5713 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5714 	 * is of the order of several 100ms and starting the timer
5715 	 * first and then sending the packet will result in difference
5716 	 * of few micro seconds.
5717 	 *
5718 	 * Without this optimization, we are forced to hold the fanout
5719 	 * lock across the ipcl_bind_insert() and sending the packet
5720 	 * so that we don't race against an incoming packet (maybe RST)
5721 	 * for this eager.
5722 	 *
5723 	 * It is necessary to acquire an extra reference on the eager
5724 	 * at this point and hold it until after tcp_send_data() to
5725 	 * ensure against an eager close race.
5726 	 */
5727 
5728 	CONN_INC_REF(eager->tcp_connp);
5729 
5730 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5731 
5732 	/*
5733 	 * Insert the eager in its own perimeter now. We are ready to deal
5734 	 * with any packets on eager.
5735 	 */
5736 	if (eager->tcp_ipversion == IPV4_VERSION) {
5737 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5738 			goto error;
5739 		}
5740 	} else {
5741 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5742 			goto error;
5743 		}
5744 	}
5745 
5746 	/* mark conn as fully-bound */
5747 	econnp->conn_fully_bound = B_TRUE;
5748 
5749 	/* Send the SYN-ACK */
5750 	tcp_send_data(eager, eager->tcp_wq, mp1);
5751 	CONN_DEC_REF(eager->tcp_connp);
5752 	freemsg(mp);
5753 
5754 	return;
5755 error:
5756 	freemsg(mp1);
5757 	eager->tcp_closemp_used = B_TRUE;
5758 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5759 	mp1 = &eager->tcp_closemp;
5760 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5761 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5762 
5763 	/*
5764 	 * If a connection already exists, send the mp to that connections so
5765 	 * that it can be appropriately dealt with.
5766 	 */
5767 	ipst = tcps->tcps_netstack->netstack_ip;
5768 
5769 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5770 		if (!IPCL_IS_CONNECTED(econnp)) {
5771 			/*
5772 			 * Something bad happened. ipcl_conn_insert()
5773 			 * failed because a connection already existed
5774 			 * in connected hash but we can't find it
5775 			 * anymore (someone blew it away). Just
5776 			 * free this message and hopefully remote
5777 			 * will retransmit at which time the SYN can be
5778 			 * treated as a new connection or dealth with
5779 			 * a TH_RST if a connection already exists.
5780 			 */
5781 			CONN_DEC_REF(econnp);
5782 			freemsg(mp);
5783 		} else {
5784 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5785 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5786 		}
5787 	} else {
5788 		/* Nobody wants this packet */
5789 		freemsg(mp);
5790 	}
5791 	return;
5792 error3:
5793 	CONN_DEC_REF(econnp);
5794 error2:
5795 	freemsg(mp);
5796 }
5797 
5798 /*
5799  * In an ideal case of vertical partition in NUMA architecture, its
5800  * beneficial to have the listener and all the incoming connections
5801  * tied to the same squeue. The other constraint is that incoming
5802  * connections should be tied to the squeue attached to interrupted
5803  * CPU for obvious locality reason so this leaves the listener to
5804  * be tied to the same squeue. Our only problem is that when listener
5805  * is binding, the CPU that will get interrupted by the NIC whose
5806  * IP address the listener is binding to is not even known. So
5807  * the code below allows us to change that binding at the time the
5808  * CPU is interrupted by virtue of incoming connection's squeue.
5809  *
5810  * This is usefull only in case of a listener bound to a specific IP
5811  * address. For other kind of listeners, they get bound the
5812  * very first time and there is no attempt to rebind them.
5813  */
5814 void
5815 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5816 {
5817 	conn_t		*connp = (conn_t *)arg;
5818 	squeue_t	*sqp = (squeue_t *)arg2;
5819 	squeue_t	*new_sqp;
5820 	uint32_t	conn_flags;
5821 
5822 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5823 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5824 	} else {
5825 		goto done;
5826 	}
5827 
5828 	if (connp->conn_fanout == NULL)
5829 		goto done;
5830 
5831 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5832 		mutex_enter(&connp->conn_fanout->connf_lock);
5833 		mutex_enter(&connp->conn_lock);
5834 		/*
5835 		 * No one from read or write side can access us now
5836 		 * except for already queued packets on this squeue.
5837 		 * But since we haven't changed the squeue yet, they
5838 		 * can't execute. If they are processed after we have
5839 		 * changed the squeue, they are sent back to the
5840 		 * correct squeue down below.
5841 		 * But a listner close can race with processing of
5842 		 * incoming SYN. If incoming SYN processing changes
5843 		 * the squeue then the listener close which is waiting
5844 		 * to enter the squeue would operate on the wrong
5845 		 * squeue. Hence we don't change the squeue here unless
5846 		 * the refcount is exactly the minimum refcount. The
5847 		 * minimum refcount of 4 is counted as - 1 each for
5848 		 * TCP and IP, 1 for being in the classifier hash, and
5849 		 * 1 for the mblk being processed.
5850 		 */
5851 
5852 		if (connp->conn_ref != 4 ||
5853 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5854 			mutex_exit(&connp->conn_lock);
5855 			mutex_exit(&connp->conn_fanout->connf_lock);
5856 			goto done;
5857 		}
5858 		if (connp->conn_sqp != new_sqp) {
5859 			while (connp->conn_sqp != new_sqp)
5860 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5861 		}
5862 
5863 		do {
5864 			conn_flags = connp->conn_flags;
5865 			conn_flags |= IPCL_FULLY_BOUND;
5866 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5867 			    conn_flags);
5868 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5869 
5870 		mutex_exit(&connp->conn_fanout->connf_lock);
5871 		mutex_exit(&connp->conn_lock);
5872 	}
5873 
5874 done:
5875 	if (connp->conn_sqp != sqp) {
5876 		CONN_INC_REF(connp);
5877 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5878 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5879 	} else {
5880 		tcp_conn_request(connp, mp, sqp);
5881 	}
5882 }
5883 
5884 /*
5885  * Successful connect request processing begins when our client passes
5886  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5887  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5888  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5889  *   upstream <- tcp_rput()		<- IP
5890  * After various error checks are completed, tcp_tpi_connect() lays
5891  * the target address and port into the composite header template,
5892  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5893  * request followed by an IRE request, and passes the three mblk message
5894  * down to IP looking like this:
5895  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5896  * Processing continues in tcp_rput() when we receive the following message:
5897  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5898  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5899  * to fire off the connection request, and then passes the T_OK_ACK mblk
5900  * upstream that we filled in below.  There are, of course, numerous
5901  * error conditions along the way which truncate the processing described
5902  * above.
5903  */
5904 static void
5905 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5906 {
5907 	sin_t		*sin;
5908 	queue_t		*q = tcp->tcp_wq;
5909 	struct T_conn_req	*tcr;
5910 	struct sockaddr	*sa;
5911 	socklen_t	len;
5912 	int		error;
5913 
5914 	tcr = (struct T_conn_req *)mp->b_rptr;
5915 
5916 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5917 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5918 		tcp_err_ack(tcp, mp, TPROTO, 0);
5919 		return;
5920 	}
5921 
5922 	/*
5923 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5924 	 * will always have that to send up.  Otherwise, we need to do
5925 	 * special handling in case the allocation fails at that time.
5926 	 * If the end point is TPI, the tcp_t can be reused and the
5927 	 * tcp_ordrel_mp may be allocated already.
5928 	 */
5929 	if (tcp->tcp_ordrel_mp == NULL) {
5930 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5931 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5932 			return;
5933 		}
5934 	}
5935 
5936 	/*
5937 	 * Determine packet type based on type of address passed in
5938 	 * the request should contain an IPv4 or IPv6 address.
5939 	 * Make sure that address family matches the type of
5940 	 * family of the the address passed down
5941 	 */
5942 	switch (tcr->DEST_length) {
5943 	default:
5944 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5945 		return;
5946 
5947 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5948 		/*
5949 		 * XXX: The check for valid DEST_length was not there
5950 		 * in earlier releases and some buggy
5951 		 * TLI apps (e.g Sybase) got away with not feeding
5952 		 * in sin_zero part of address.
5953 		 * We allow that bug to keep those buggy apps humming.
5954 		 * Test suites require the check on DEST_length.
5955 		 * We construct a new mblk with valid DEST_length
5956 		 * free the original so the rest of the code does
5957 		 * not have to keep track of this special shorter
5958 		 * length address case.
5959 		 */
5960 		mblk_t *nmp;
5961 		struct T_conn_req *ntcr;
5962 		sin_t *nsin;
5963 
5964 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
5965 		    tcr->OPT_length, BPRI_HI);
5966 		if (nmp == NULL) {
5967 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5968 			return;
5969 		}
5970 		ntcr = (struct T_conn_req *)nmp->b_rptr;
5971 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
5972 		ntcr->PRIM_type = T_CONN_REQ;
5973 		ntcr->DEST_length = sizeof (sin_t);
5974 		ntcr->DEST_offset = sizeof (struct T_conn_req);
5975 
5976 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
5977 		*nsin = sin_null;
5978 		/* Get pointer to shorter address to copy from original mp */
5979 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
5980 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
5981 		if (sin == NULL || !OK_32PTR((char *)sin)) {
5982 			freemsg(nmp);
5983 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5984 			return;
5985 		}
5986 		nsin->sin_family = sin->sin_family;
5987 		nsin->sin_port = sin->sin_port;
5988 		nsin->sin_addr = sin->sin_addr;
5989 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
5990 		nmp->b_wptr = (uchar_t *)&nsin[1];
5991 		if (tcr->OPT_length != 0) {
5992 			ntcr->OPT_length = tcr->OPT_length;
5993 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
5994 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
5995 			    (uchar_t *)ntcr + ntcr->OPT_offset,
5996 			    tcr->OPT_length);
5997 			nmp->b_wptr += tcr->OPT_length;
5998 		}
5999 		freemsg(mp);	/* original mp freed */
6000 		mp = nmp;	/* re-initialize original variables */
6001 		tcr = ntcr;
6002 	}
6003 	/* FALLTHRU */
6004 
6005 	case sizeof (sin_t):
6006 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6007 		    sizeof (sin_t));
6008 		len = sizeof (sin_t);
6009 		break;
6010 
6011 	case sizeof (sin6_t):
6012 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6013 		    sizeof (sin6_t));
6014 		len = sizeof (sin6_t);
6015 		break;
6016 	}
6017 
6018 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6019 	if (error != 0) {
6020 		tcp_err_ack(tcp, mp, TSYSERR, error);
6021 		return;
6022 	}
6023 
6024 	/*
6025 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6026 	 * should key on their sequence number and cut them loose.
6027 	 */
6028 
6029 	/*
6030 	 * If options passed in, feed it for verification and handling
6031 	 */
6032 	if (tcr->OPT_length != 0) {
6033 		mblk_t	*ok_mp;
6034 		mblk_t	*discon_mp;
6035 		mblk_t  *conn_opts_mp;
6036 		int t_error, sys_error, do_disconnect;
6037 
6038 		conn_opts_mp = NULL;
6039 
6040 		if (tcp_conprim_opt_process(tcp, mp,
6041 		    &do_disconnect, &t_error, &sys_error) < 0) {
6042 			if (do_disconnect) {
6043 				ASSERT(t_error == 0 && sys_error == 0);
6044 				discon_mp = mi_tpi_discon_ind(NULL,
6045 				    ECONNREFUSED, 0);
6046 				if (!discon_mp) {
6047 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6048 					    TSYSERR, ENOMEM);
6049 					return;
6050 				}
6051 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6052 				if (!ok_mp) {
6053 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6054 					    TSYSERR, ENOMEM);
6055 					return;
6056 				}
6057 				qreply(q, ok_mp);
6058 				qreply(q, discon_mp); /* no flush! */
6059 			} else {
6060 				ASSERT(t_error != 0);
6061 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6062 				    sys_error);
6063 			}
6064 			return;
6065 		}
6066 		/*
6067 		 * Success in setting options, the mp option buffer represented
6068 		 * by OPT_length/offset has been potentially modified and
6069 		 * contains results of option processing. We copy it in
6070 		 * another mp to save it for potentially influencing returning
6071 		 * it in T_CONN_CONN.
6072 		 */
6073 		if (tcr->OPT_length != 0) { /* there are resulting options */
6074 			conn_opts_mp = copyb(mp);
6075 			if (!conn_opts_mp) {
6076 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6077 				    TSYSERR, ENOMEM);
6078 				return;
6079 			}
6080 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6081 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6082 			/*
6083 			 * Note:
6084 			 * These resulting option negotiation can include any
6085 			 * end-to-end negotiation options but there no such
6086 			 * thing (yet?) in our TCP/IP.
6087 			 */
6088 		}
6089 	}
6090 
6091 	/* call the non-TPI version */
6092 	error = tcp_do_connect(tcp->tcp_connp, sa, len, DB_CRED(mp),
6093 	    DB_CPID(mp));
6094 	if (error < 0) {
6095 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6096 	} else if (error > 0) {
6097 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6098 	} else {
6099 		mp = mi_tpi_ok_ack_alloc(mp);
6100 	}
6101 
6102 	/*
6103 	 * Note: Code below is the "failure" case
6104 	 */
6105 	/* return error ack and blow away saved option results if any */
6106 connect_failed:
6107 	if (mp != NULL)
6108 		putnext(tcp->tcp_rq, mp);
6109 	else {
6110 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6111 		    TSYSERR, ENOMEM);
6112 	}
6113 }
6114 
6115 /*
6116  * Handle connect to IPv4 destinations, including connections for AF_INET6
6117  * sockets connecting to IPv4 mapped IPv6 destinations.
6118  */
6119 static int
6120 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6121     uint_t srcid, cred_t *cr, pid_t pid)
6122 {
6123 	tcph_t	*tcph;
6124 	mblk_t	*mp;
6125 	ipaddr_t dstaddr = *dstaddrp;
6126 	int32_t	oldstate;
6127 	uint16_t lport;
6128 	int	error = 0;
6129 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6130 
6131 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6132 
6133 	/* Check for attempt to connect to INADDR_ANY */
6134 	if (dstaddr == INADDR_ANY)  {
6135 		/*
6136 		 * SunOS 4.x and 4.3 BSD allow an application
6137 		 * to connect a TCP socket to INADDR_ANY.
6138 		 * When they do this, the kernel picks the
6139 		 * address of one interface and uses it
6140 		 * instead.  The kernel usually ends up
6141 		 * picking the address of the loopback
6142 		 * interface.  This is an undocumented feature.
6143 		 * However, we provide the same thing here
6144 		 * in order to have source and binary
6145 		 * compatibility with SunOS 4.x.
6146 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6147 		 * generate the T_CONN_CON.
6148 		 */
6149 		dstaddr = htonl(INADDR_LOOPBACK);
6150 		*dstaddrp = dstaddr;
6151 	}
6152 
6153 	/* Handle __sin6_src_id if socket not bound to an IP address */
6154 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6155 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6156 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6157 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6158 		    tcp->tcp_ipha->ipha_src);
6159 	}
6160 
6161 	/*
6162 	 * Don't let an endpoint connect to itself.  Note that
6163 	 * the test here does not catch the case where the
6164 	 * source IP addr was left unspecified by the user. In
6165 	 * this case, the source addr is set in tcp_adapt_ire()
6166 	 * using the reply to the T_BIND message that we send
6167 	 * down to IP here and the check is repeated in tcp_rput_other.
6168 	 */
6169 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6170 	    dstport == tcp->tcp_lport) {
6171 		error = -TBADADDR;
6172 		goto failed;
6173 	}
6174 
6175 	tcp->tcp_ipha->ipha_dst = dstaddr;
6176 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6177 
6178 	/*
6179 	 * Massage a source route if any putting the first hop
6180 	 * in iph_dst. Compute a starting value for the checksum which
6181 	 * takes into account that the original iph_dst should be
6182 	 * included in the checksum but that ip will include the
6183 	 * first hop in the source route in the tcp checksum.
6184 	 */
6185 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6186 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6187 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6188 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6189 	if ((int)tcp->tcp_sum < 0)
6190 		tcp->tcp_sum--;
6191 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6192 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6193 	    (tcp->tcp_sum >> 16));
6194 	tcph = tcp->tcp_tcph;
6195 	*(uint16_t *)tcph->th_fport = dstport;
6196 	tcp->tcp_fport = dstport;
6197 
6198 	oldstate = tcp->tcp_state;
6199 	/*
6200 	 * At this point the remote destination address and remote port fields
6201 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6202 	 * have to see which state tcp was in so we can take apropriate action.
6203 	 */
6204 	if (oldstate == TCPS_IDLE) {
6205 		/*
6206 		 * We support a quick connect capability here, allowing
6207 		 * clients to transition directly from IDLE to SYN_SENT
6208 		 * tcp_bindi will pick an unused port, insert the connection
6209 		 * in the bind hash and transition to BOUND state.
6210 		 */
6211 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6212 		    tcp, B_TRUE);
6213 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6214 		    B_FALSE, B_FALSE);
6215 		if (lport == 0) {
6216 			error = -TNOADDR;
6217 			goto failed;
6218 		}
6219 	}
6220 	tcp->tcp_state = TCPS_SYN_SENT;
6221 
6222 	mp = allocb(sizeof (ire_t), BPRI_HI);
6223 	if (mp == NULL) {
6224 		tcp->tcp_state = oldstate;
6225 		error = ENOMEM;
6226 		goto failed;
6227 	}
6228 	mp->b_wptr += sizeof (ire_t);
6229 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6230 	tcp->tcp_hard_binding = 1;
6231 	if (cr == NULL) {
6232 		cr = tcp->tcp_cred;
6233 		pid = tcp->tcp_cpid;
6234 	}
6235 	mblk_setcred(mp, cr);
6236 	DB_CPID(mp) = pid;
6237 
6238 	/*
6239 	 * We need to make sure that the conn_recv is set to a non-null
6240 	 * value before we insert the conn_t into the classifier table.
6241 	 * This is to avoid a race with an incoming packet which does
6242 	 * an ipcl_classify().
6243 	 */
6244 	tcp->tcp_connp->conn_recv = tcp_input;
6245 
6246 	if (tcp->tcp_family == AF_INET) {
6247 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6248 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6249 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE);
6250 	} else {
6251 		in6_addr_t v6src;
6252 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6253 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6254 		} else {
6255 			v6src = tcp->tcp_ip6h->ip6_src;
6256 		}
6257 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6258 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6259 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6260 	}
6261 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6262 	tcp->tcp_active_open = 1;
6263 
6264 	return (tcp_post_ip_bind(tcp, mp, error));
6265 failed:
6266 	/* return error ack and blow away saved option results if any */
6267 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6268 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6269 	return (error);
6270 }
6271 
6272 /*
6273  * Handle connect to IPv6 destinations.
6274  */
6275 static int
6276 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6277     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6278 {
6279 	tcph_t	*tcph;
6280 	mblk_t	*mp;
6281 	ip6_rthdr_t *rth;
6282 	int32_t  oldstate;
6283 	uint16_t lport;
6284 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6285 	int	error = 0;
6286 	conn_t	*connp = tcp->tcp_connp;
6287 
6288 	ASSERT(tcp->tcp_family == AF_INET6);
6289 
6290 	/*
6291 	 * If we're here, it means that the destination address is a native
6292 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6293 	 * reason why it might not be IPv6 is if the socket was bound to an
6294 	 * IPv4-mapped IPv6 address.
6295 	 */
6296 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6297 		return (-TBADADDR);
6298 	}
6299 
6300 	/*
6301 	 * Interpret a zero destination to mean loopback.
6302 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6303 	 * generate the T_CONN_CON.
6304 	 */
6305 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6306 		*dstaddrp = ipv6_loopback;
6307 	}
6308 
6309 	/* Handle __sin6_src_id if socket not bound to an IP address */
6310 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6311 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6312 		    connp->conn_zoneid, tcps->tcps_netstack);
6313 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6314 	}
6315 
6316 	/*
6317 	 * Take care of the scope_id now and add ip6i_t
6318 	 * if ip6i_t is not already allocated through TCP
6319 	 * sticky options. At this point tcp_ip6h does not
6320 	 * have dst info, thus use dstaddrp.
6321 	 */
6322 	if (scope_id != 0 &&
6323 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6324 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6325 		ip6i_t  *ip6i;
6326 
6327 		ipp->ipp_ifindex = scope_id;
6328 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6329 
6330 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6331 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6332 			/* Already allocated */
6333 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6334 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6335 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6336 		} else {
6337 			int reterr;
6338 
6339 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6340 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6341 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6342 			reterr = tcp_build_hdrs(tcp);
6343 			if (reterr != 0)
6344 				goto failed;
6345 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6346 		}
6347 	}
6348 
6349 	/*
6350 	 * Don't let an endpoint connect to itself.  Note that
6351 	 * the test here does not catch the case where the
6352 	 * source IP addr was left unspecified by the user. In
6353 	 * this case, the source addr is set in tcp_adapt_ire()
6354 	 * using the reply to the T_BIND message that we send
6355 	 * down to IP here and the check is repeated in tcp_rput_other.
6356 	 */
6357 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6358 	    (dstport == tcp->tcp_lport)) {
6359 		error = -TBADADDR;
6360 		goto failed;
6361 	}
6362 
6363 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6364 	tcp->tcp_remote_v6 = *dstaddrp;
6365 	tcp->tcp_ip6h->ip6_vcf =
6366 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6367 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6368 
6369 	/*
6370 	 * Massage a routing header (if present) putting the first hop
6371 	 * in ip6_dst. Compute a starting value for the checksum which
6372 	 * takes into account that the original ip6_dst should be
6373 	 * included in the checksum but that ip will include the
6374 	 * first hop in the source route in the tcp checksum.
6375 	 */
6376 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6377 	if (rth != NULL) {
6378 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6379 		    tcps->tcps_netstack);
6380 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6381 		    (tcp->tcp_sum >> 16));
6382 	} else {
6383 		tcp->tcp_sum = 0;
6384 	}
6385 
6386 	tcph = tcp->tcp_tcph;
6387 	*(uint16_t *)tcph->th_fport = dstport;
6388 	tcp->tcp_fport = dstport;
6389 
6390 	oldstate = tcp->tcp_state;
6391 	/*
6392 	 * At this point the remote destination address and remote port fields
6393 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6394 	 * have to see which state tcp was in so we can take apropriate action.
6395 	 */
6396 	if (oldstate == TCPS_IDLE) {
6397 		/*
6398 		 * We support a quick connect capability here, allowing
6399 		 * clients to transition directly from IDLE to SYN_SENT
6400 		 * tcp_bindi will pick an unused port, insert the connection
6401 		 * in the bind hash and transition to BOUND state.
6402 		 */
6403 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6404 		    tcp, B_TRUE);
6405 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6406 		    B_FALSE, B_FALSE);
6407 		if (lport == 0) {
6408 			error = -TNOADDR;
6409 			goto failed;
6410 		}
6411 	}
6412 	tcp->tcp_state = TCPS_SYN_SENT;
6413 
6414 	mp = allocb(sizeof (ire_t), BPRI_HI);
6415 	if (mp != NULL) {
6416 		in6_addr_t v6src;
6417 
6418 		mp->b_wptr += sizeof (ire_t);
6419 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6420 		if (cr == NULL) {
6421 			cr = tcp->tcp_cred;
6422 			pid = tcp->tcp_cpid;
6423 		}
6424 		mblk_setcred(mp, cr);
6425 		DB_CPID(mp) = pid;
6426 		tcp->tcp_hard_binding = 1;
6427 
6428 		/*
6429 		 * We need to make sure that the conn_recv is set to a non-null
6430 		 * value before we insert the conn_t into the classifier table.
6431 		 * This is to avoid a race with an incoming packet which does
6432 		 * an ipcl_classify().
6433 		 */
6434 		tcp->tcp_connp->conn_recv = tcp_input;
6435 
6436 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6437 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6438 		} else {
6439 			v6src = tcp->tcp_ip6h->ip6_src;
6440 		}
6441 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6442 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6443 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE);
6444 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6445 		tcp->tcp_active_open = 1;
6446 
6447 		return (tcp_post_ip_bind(tcp, mp, error));
6448 	}
6449 	/* Error case */
6450 	tcp->tcp_state = oldstate;
6451 	error = ENOMEM;
6452 
6453 failed:
6454 	/* return error ack and blow away saved option results if any */
6455 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6456 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6457 	return (error);
6458 }
6459 
6460 /*
6461  * We need a stream q for detached closing tcp connections
6462  * to use.  Our client hereby indicates that this q is the
6463  * one to use.
6464  */
6465 static void
6466 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6467 {
6468 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6469 	queue_t	*q = tcp->tcp_wq;
6470 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6471 
6472 #ifdef NS_DEBUG
6473 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6474 	    tcps->tcps_netstack->netstack_stackid);
6475 #endif
6476 	mp->b_datap->db_type = M_IOCACK;
6477 	iocp->ioc_count = 0;
6478 	mutex_enter(&tcps->tcps_g_q_lock);
6479 	if (tcps->tcps_g_q != NULL) {
6480 		mutex_exit(&tcps->tcps_g_q_lock);
6481 		iocp->ioc_error = EALREADY;
6482 	} else {
6483 		int error = 0;
6484 		conn_t *connp = tcp->tcp_connp;
6485 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6486 
6487 		tcps->tcps_g_q = tcp->tcp_rq;
6488 		mutex_exit(&tcps->tcps_g_q_lock);
6489 		iocp->ioc_error = 0;
6490 		iocp->ioc_rval = 0;
6491 		/*
6492 		 * We are passing tcp_sticky_ipp as NULL
6493 		 * as it is not useful for tcp_default queue
6494 		 *
6495 		 * Set conn_recv just in case.
6496 		 */
6497 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6498 
6499 		ASSERT(connp->conn_af_isv6);
6500 		connp->conn_ulp = IPPROTO_TCP;
6501 
6502 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6503 		    NULL || connp->conn_mac_exempt) {
6504 			error = -TBADADDR;
6505 		} else {
6506 			connp->conn_srcv6 = ipv6_all_zeros;
6507 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6508 		}
6509 
6510 		(void) tcp_post_ip_bind(tcp, NULL, error);
6511 	}
6512 	qreply(q, mp);
6513 }
6514 
6515 static int
6516 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6517 {
6518 	tcp_t	*ltcp = NULL;
6519 	conn_t	*connp;
6520 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6521 
6522 	/*
6523 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6524 	 * when the stream is in BOUND state. Do not send a reset,
6525 	 * since the destination IP address is not valid, and it can
6526 	 * be the initialized value of all zeros (broadcast address).
6527 	 *
6528 	 * XXX There won't be any pending bind request to IP.
6529 	 */
6530 	if (tcp->tcp_state <= TCPS_BOUND) {
6531 		if (tcp->tcp_debug) {
6532 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6533 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6534 		}
6535 		return (TOUTSTATE);
6536 	}
6537 
6538 
6539 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6540 
6541 		/*
6542 		 * According to TPI, for non-listeners, ignore seqnum
6543 		 * and disconnect.
6544 		 * Following interpretation of -1 seqnum is historical
6545 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6546 		 * a valid seqnum should not be -1).
6547 		 *
6548 		 *	-1 means disconnect everything
6549 		 *	regardless even on a listener.
6550 		 */
6551 
6552 		int old_state = tcp->tcp_state;
6553 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6554 
6555 		/*
6556 		 * The connection can't be on the tcp_time_wait_head list
6557 		 * since it is not detached.
6558 		 */
6559 		ASSERT(tcp->tcp_time_wait_next == NULL);
6560 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6561 		ASSERT(tcp->tcp_time_wait_expire == 0);
6562 		ltcp = NULL;
6563 		/*
6564 		 * If it used to be a listener, check to make sure no one else
6565 		 * has taken the port before switching back to LISTEN state.
6566 		 */
6567 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6568 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6569 			    tcp->tcp_ipha->ipha_src,
6570 			    tcp->tcp_connp->conn_zoneid, ipst);
6571 			if (connp != NULL)
6572 				ltcp = connp->conn_tcp;
6573 		} else {
6574 			/* Allow tcp_bound_if listeners? */
6575 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6576 			    &tcp->tcp_ip6h->ip6_src, 0,
6577 			    tcp->tcp_connp->conn_zoneid, ipst);
6578 			if (connp != NULL)
6579 				ltcp = connp->conn_tcp;
6580 		}
6581 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6582 			tcp->tcp_state = TCPS_LISTEN;
6583 		} else if (old_state > TCPS_BOUND) {
6584 			tcp->tcp_conn_req_max = 0;
6585 			tcp->tcp_state = TCPS_BOUND;
6586 		}
6587 		if (ltcp != NULL)
6588 			CONN_DEC_REF(ltcp->tcp_connp);
6589 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6590 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6591 		} else if (old_state == TCPS_ESTABLISHED ||
6592 		    old_state == TCPS_CLOSE_WAIT) {
6593 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6594 		}
6595 
6596 		if (tcp->tcp_fused)
6597 			tcp_unfuse(tcp);
6598 
6599 		mutex_enter(&tcp->tcp_eager_lock);
6600 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6601 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6602 			tcp_eager_cleanup(tcp, 0);
6603 		}
6604 		mutex_exit(&tcp->tcp_eager_lock);
6605 
6606 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6607 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6608 
6609 		tcp_reinit(tcp);
6610 
6611 		return (0);
6612 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6613 		return (TBADSEQ);
6614 	}
6615 	return (0);
6616 }
6617 
6618 /*
6619  * Our client hereby directs us to reject the connection request
6620  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6621  * of sending the appropriate RST, not an ICMP error.
6622  */
6623 static void
6624 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6625 {
6626 	t_scalar_t seqnum;
6627 	int	error;
6628 
6629 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6630 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6631 		tcp_err_ack(tcp, mp, TPROTO, 0);
6632 		return;
6633 	}
6634 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6635 	error = tcp_disconnect_common(tcp, seqnum);
6636 	if (error != 0)
6637 		tcp_err_ack(tcp, mp, error, 0);
6638 	else {
6639 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6640 			/* Send M_FLUSH according to TPI */
6641 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6642 		}
6643 		mp = mi_tpi_ok_ack_alloc(mp);
6644 		if (mp)
6645 			putnext(tcp->tcp_rq, mp);
6646 	}
6647 }
6648 
6649 /*
6650  * Diagnostic routine used to return a string associated with the tcp state.
6651  * Note that if the caller does not supply a buffer, it will use an internal
6652  * static string.  This means that if multiple threads call this function at
6653  * the same time, output can be corrupted...  Note also that this function
6654  * does not check the size of the supplied buffer.  The caller has to make
6655  * sure that it is big enough.
6656  */
6657 static char *
6658 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6659 {
6660 	char		buf1[30];
6661 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6662 	char		*buf;
6663 	char		*cp;
6664 	in6_addr_t	local, remote;
6665 	char		local_addrbuf[INET6_ADDRSTRLEN];
6666 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6667 
6668 	if (sup_buf != NULL)
6669 		buf = sup_buf;
6670 	else
6671 		buf = priv_buf;
6672 
6673 	if (tcp == NULL)
6674 		return ("NULL_TCP");
6675 	switch (tcp->tcp_state) {
6676 	case TCPS_CLOSED:
6677 		cp = "TCP_CLOSED";
6678 		break;
6679 	case TCPS_IDLE:
6680 		cp = "TCP_IDLE";
6681 		break;
6682 	case TCPS_BOUND:
6683 		cp = "TCP_BOUND";
6684 		break;
6685 	case TCPS_LISTEN:
6686 		cp = "TCP_LISTEN";
6687 		break;
6688 	case TCPS_SYN_SENT:
6689 		cp = "TCP_SYN_SENT";
6690 		break;
6691 	case TCPS_SYN_RCVD:
6692 		cp = "TCP_SYN_RCVD";
6693 		break;
6694 	case TCPS_ESTABLISHED:
6695 		cp = "TCP_ESTABLISHED";
6696 		break;
6697 	case TCPS_CLOSE_WAIT:
6698 		cp = "TCP_CLOSE_WAIT";
6699 		break;
6700 	case TCPS_FIN_WAIT_1:
6701 		cp = "TCP_FIN_WAIT_1";
6702 		break;
6703 	case TCPS_CLOSING:
6704 		cp = "TCP_CLOSING";
6705 		break;
6706 	case TCPS_LAST_ACK:
6707 		cp = "TCP_LAST_ACK";
6708 		break;
6709 	case TCPS_FIN_WAIT_2:
6710 		cp = "TCP_FIN_WAIT_2";
6711 		break;
6712 	case TCPS_TIME_WAIT:
6713 		cp = "TCP_TIME_WAIT";
6714 		break;
6715 	default:
6716 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6717 		cp = buf1;
6718 		break;
6719 	}
6720 	switch (format) {
6721 	case DISP_ADDR_AND_PORT:
6722 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6723 			/*
6724 			 * Note that we use the remote address in the tcp_b
6725 			 * structure.  This means that it will print out
6726 			 * the real destination address, not the next hop's
6727 			 * address if source routing is used.
6728 			 */
6729 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6730 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6731 
6732 		} else {
6733 			local = tcp->tcp_ip_src_v6;
6734 			remote = tcp->tcp_remote_v6;
6735 		}
6736 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6737 		    sizeof (local_addrbuf));
6738 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6739 		    sizeof (remote_addrbuf));
6740 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6741 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6742 		    ntohs(tcp->tcp_fport), cp);
6743 		break;
6744 	case DISP_PORT_ONLY:
6745 	default:
6746 		(void) mi_sprintf(buf, "[%u, %u] %s",
6747 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6748 		break;
6749 	}
6750 
6751 	return (buf);
6752 }
6753 
6754 /*
6755  * Called via squeue to get on to eager's perimeter. It sends a
6756  * TH_RST if eager is in the fanout table. The listener wants the
6757  * eager to disappear either by means of tcp_eager_blowoff() or
6758  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6759  * called (via squeue) if the eager cannot be inserted in the
6760  * fanout table in tcp_conn_request().
6761  */
6762 /* ARGSUSED */
6763 void
6764 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6765 {
6766 	conn_t	*econnp = (conn_t *)arg;
6767 	tcp_t	*eager = econnp->conn_tcp;
6768 	tcp_t	*listener = eager->tcp_listener;
6769 	tcp_stack_t	*tcps = eager->tcp_tcps;
6770 
6771 	/*
6772 	 * We could be called because listener is closing. Since
6773 	 * the eager is using listener's queue's, its not safe.
6774 	 * Better use the default queue just to send the TH_RST
6775 	 * out.
6776 	 */
6777 	ASSERT(tcps->tcps_g_q != NULL);
6778 	eager->tcp_rq = tcps->tcps_g_q;
6779 	eager->tcp_wq = WR(tcps->tcps_g_q);
6780 
6781 	/*
6782 	 * An eager's conn_fanout will be NULL if it's a duplicate
6783 	 * for an existing 4-tuples in the conn fanout table.
6784 	 * We don't want to send an RST out in such case.
6785 	 */
6786 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6787 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6788 		    eager, eager->tcp_snxt, 0, TH_RST);
6789 	}
6790 
6791 	/* We are here because listener wants this eager gone */
6792 	if (listener != NULL) {
6793 		mutex_enter(&listener->tcp_eager_lock);
6794 		tcp_eager_unlink(eager);
6795 		if (eager->tcp_tconnind_started) {
6796 			/*
6797 			 * The eager has sent a conn_ind up to the
6798 			 * listener but listener decides to close
6799 			 * instead. We need to drop the extra ref
6800 			 * placed on eager in tcp_rput_data() before
6801 			 * sending the conn_ind to listener.
6802 			 */
6803 			CONN_DEC_REF(econnp);
6804 		}
6805 		mutex_exit(&listener->tcp_eager_lock);
6806 		CONN_DEC_REF(listener->tcp_connp);
6807 	}
6808 
6809 	if (eager->tcp_state > TCPS_BOUND)
6810 		tcp_close_detached(eager);
6811 }
6812 
6813 /*
6814  * Reset any eager connection hanging off this listener marked
6815  * with 'seqnum' and then reclaim it's resources.
6816  */
6817 static boolean_t
6818 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6819 {
6820 	tcp_t	*eager;
6821 	mblk_t 	*mp;
6822 	tcp_stack_t	*tcps = listener->tcp_tcps;
6823 
6824 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6825 	eager = listener;
6826 	mutex_enter(&listener->tcp_eager_lock);
6827 	do {
6828 		eager = eager->tcp_eager_next_q;
6829 		if (eager == NULL) {
6830 			mutex_exit(&listener->tcp_eager_lock);
6831 			return (B_FALSE);
6832 		}
6833 	} while (eager->tcp_conn_req_seqnum != seqnum);
6834 
6835 	if (eager->tcp_closemp_used) {
6836 		mutex_exit(&listener->tcp_eager_lock);
6837 		return (B_TRUE);
6838 	}
6839 	eager->tcp_closemp_used = B_TRUE;
6840 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6841 	CONN_INC_REF(eager->tcp_connp);
6842 	mutex_exit(&listener->tcp_eager_lock);
6843 	mp = &eager->tcp_closemp;
6844 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6845 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6846 	return (B_TRUE);
6847 }
6848 
6849 /*
6850  * Reset any eager connection hanging off this listener
6851  * and then reclaim it's resources.
6852  */
6853 static void
6854 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6855 {
6856 	tcp_t	*eager;
6857 	mblk_t	*mp;
6858 	tcp_stack_t	*tcps = listener->tcp_tcps;
6859 
6860 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6861 
6862 	if (!q0_only) {
6863 		/* First cleanup q */
6864 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6865 		eager = listener->tcp_eager_next_q;
6866 		while (eager != NULL) {
6867 			if (!eager->tcp_closemp_used) {
6868 				eager->tcp_closemp_used = B_TRUE;
6869 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6870 				CONN_INC_REF(eager->tcp_connp);
6871 				mp = &eager->tcp_closemp;
6872 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6873 				    tcp_eager_kill, eager->tcp_connp,
6874 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6875 			}
6876 			eager = eager->tcp_eager_next_q;
6877 		}
6878 	}
6879 	/* Then cleanup q0 */
6880 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6881 	eager = listener->tcp_eager_next_q0;
6882 	while (eager != listener) {
6883 		if (!eager->tcp_closemp_used) {
6884 			eager->tcp_closemp_used = B_TRUE;
6885 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6886 			CONN_INC_REF(eager->tcp_connp);
6887 			mp = &eager->tcp_closemp;
6888 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6889 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6890 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6891 		}
6892 		eager = eager->tcp_eager_next_q0;
6893 	}
6894 }
6895 
6896 /*
6897  * If we are an eager connection hanging off a listener that hasn't
6898  * formally accepted the connection yet, get off his list and blow off
6899  * any data that we have accumulated.
6900  */
6901 static void
6902 tcp_eager_unlink(tcp_t *tcp)
6903 {
6904 	tcp_t	*listener = tcp->tcp_listener;
6905 
6906 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6907 	ASSERT(listener != NULL);
6908 	if (tcp->tcp_eager_next_q0 != NULL) {
6909 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6910 
6911 		/* Remove the eager tcp from q0 */
6912 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6913 		    tcp->tcp_eager_prev_q0;
6914 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6915 		    tcp->tcp_eager_next_q0;
6916 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6917 		listener->tcp_conn_req_cnt_q0--;
6918 
6919 		tcp->tcp_eager_next_q0 = NULL;
6920 		tcp->tcp_eager_prev_q0 = NULL;
6921 
6922 		/*
6923 		 * Take the eager out, if it is in the list of droppable
6924 		 * eagers.
6925 		 */
6926 		MAKE_UNDROPPABLE(tcp);
6927 
6928 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6929 			/* we have timed out before */
6930 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6931 			listener->tcp_syn_rcvd_timeout--;
6932 		}
6933 	} else {
6934 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6935 		tcp_t	*prev = NULL;
6936 
6937 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6938 			if (tcpp[0] == tcp) {
6939 				if (listener->tcp_eager_last_q == tcp) {
6940 					/*
6941 					 * If we are unlinking the last
6942 					 * element on the list, adjust
6943 					 * tail pointer. Set tail pointer
6944 					 * to nil when list is empty.
6945 					 */
6946 					ASSERT(tcp->tcp_eager_next_q == NULL);
6947 					if (listener->tcp_eager_last_q ==
6948 					    listener->tcp_eager_next_q) {
6949 						listener->tcp_eager_last_q =
6950 						    NULL;
6951 					} else {
6952 						/*
6953 						 * We won't get here if there
6954 						 * is only one eager in the
6955 						 * list.
6956 						 */
6957 						ASSERT(prev != NULL);
6958 						listener->tcp_eager_last_q =
6959 						    prev;
6960 					}
6961 				}
6962 				tcpp[0] = tcp->tcp_eager_next_q;
6963 				tcp->tcp_eager_next_q = NULL;
6964 				tcp->tcp_eager_last_q = NULL;
6965 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
6966 				listener->tcp_conn_req_cnt_q--;
6967 				break;
6968 			}
6969 			prev = tcpp[0];
6970 		}
6971 	}
6972 	tcp->tcp_listener = NULL;
6973 }
6974 
6975 /* Shorthand to generate and send TPI error acks to our client */
6976 static void
6977 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
6978 {
6979 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
6980 		putnext(tcp->tcp_rq, mp);
6981 }
6982 
6983 /* Shorthand to generate and send TPI error acks to our client */
6984 static void
6985 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
6986     int t_error, int sys_error)
6987 {
6988 	struct T_error_ack	*teackp;
6989 
6990 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
6991 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
6992 		teackp = (struct T_error_ack *)mp->b_rptr;
6993 		teackp->ERROR_prim = primitive;
6994 		teackp->TLI_error = t_error;
6995 		teackp->UNIX_error = sys_error;
6996 		putnext(tcp->tcp_rq, mp);
6997 	}
6998 }
6999 
7000 /*
7001  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7002  * but instead the code relies on:
7003  * - the fact that the address of the array and its size never changes
7004  * - the atomic assignment of the elements of the array
7005  */
7006 /* ARGSUSED */
7007 static int
7008 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7009 {
7010 	int i;
7011 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7012 
7013 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7014 		if (tcps->tcps_g_epriv_ports[i] != 0)
7015 			(void) mi_mpprintf(mp, "%d ",
7016 			    tcps->tcps_g_epriv_ports[i]);
7017 	}
7018 	return (0);
7019 }
7020 
7021 /*
7022  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7023  * threads from changing it at the same time.
7024  */
7025 /* ARGSUSED */
7026 static int
7027 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7028     cred_t *cr)
7029 {
7030 	long	new_value;
7031 	int	i;
7032 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7033 
7034 	/*
7035 	 * Fail the request if the new value does not lie within the
7036 	 * port number limits.
7037 	 */
7038 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7039 	    new_value <= 0 || new_value >= 65536) {
7040 		return (EINVAL);
7041 	}
7042 
7043 	mutex_enter(&tcps->tcps_epriv_port_lock);
7044 	/* Check if the value is already in the list */
7045 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7046 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7047 			mutex_exit(&tcps->tcps_epriv_port_lock);
7048 			return (EEXIST);
7049 		}
7050 	}
7051 	/* Find an empty slot */
7052 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7053 		if (tcps->tcps_g_epriv_ports[i] == 0)
7054 			break;
7055 	}
7056 	if (i == tcps->tcps_g_num_epriv_ports) {
7057 		mutex_exit(&tcps->tcps_epriv_port_lock);
7058 		return (EOVERFLOW);
7059 	}
7060 	/* Set the new value */
7061 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7062 	mutex_exit(&tcps->tcps_epriv_port_lock);
7063 	return (0);
7064 }
7065 
7066 /*
7067  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7068  * threads from changing it at the same time.
7069  */
7070 /* ARGSUSED */
7071 static int
7072 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7073     cred_t *cr)
7074 {
7075 	long	new_value;
7076 	int	i;
7077 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7078 
7079 	/*
7080 	 * Fail the request if the new value does not lie within the
7081 	 * port number limits.
7082 	 */
7083 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7084 	    new_value >= 65536) {
7085 		return (EINVAL);
7086 	}
7087 
7088 	mutex_enter(&tcps->tcps_epriv_port_lock);
7089 	/* Check that the value is already in the list */
7090 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7091 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7092 			break;
7093 	}
7094 	if (i == tcps->tcps_g_num_epriv_ports) {
7095 		mutex_exit(&tcps->tcps_epriv_port_lock);
7096 		return (ESRCH);
7097 	}
7098 	/* Clear the value */
7099 	tcps->tcps_g_epriv_ports[i] = 0;
7100 	mutex_exit(&tcps->tcps_epriv_port_lock);
7101 	return (0);
7102 }
7103 
7104 /* Return the TPI/TLI equivalent of our current tcp_state */
7105 static int
7106 tcp_tpistate(tcp_t *tcp)
7107 {
7108 	switch (tcp->tcp_state) {
7109 	case TCPS_IDLE:
7110 		return (TS_UNBND);
7111 	case TCPS_LISTEN:
7112 		/*
7113 		 * Return whether there are outstanding T_CONN_IND waiting
7114 		 * for the matching T_CONN_RES. Therefore don't count q0.
7115 		 */
7116 		if (tcp->tcp_conn_req_cnt_q > 0)
7117 			return (TS_WRES_CIND);
7118 		else
7119 			return (TS_IDLE);
7120 	case TCPS_BOUND:
7121 		return (TS_IDLE);
7122 	case TCPS_SYN_SENT:
7123 		return (TS_WCON_CREQ);
7124 	case TCPS_SYN_RCVD:
7125 		/*
7126 		 * Note: assumption: this has to the active open SYN_RCVD.
7127 		 * The passive instance is detached in SYN_RCVD stage of
7128 		 * incoming connection processing so we cannot get request
7129 		 * for T_info_ack on it.
7130 		 */
7131 		return (TS_WACK_CRES);
7132 	case TCPS_ESTABLISHED:
7133 		return (TS_DATA_XFER);
7134 	case TCPS_CLOSE_WAIT:
7135 		return (TS_WREQ_ORDREL);
7136 	case TCPS_FIN_WAIT_1:
7137 		return (TS_WIND_ORDREL);
7138 	case TCPS_FIN_WAIT_2:
7139 		return (TS_WIND_ORDREL);
7140 
7141 	case TCPS_CLOSING:
7142 	case TCPS_LAST_ACK:
7143 	case TCPS_TIME_WAIT:
7144 	case TCPS_CLOSED:
7145 		/*
7146 		 * Following TS_WACK_DREQ7 is a rendition of "not
7147 		 * yet TS_IDLE" TPI state. There is no best match to any
7148 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7149 		 * choose a value chosen that will map to TLI/XTI level
7150 		 * state of TSTATECHNG (state is process of changing) which
7151 		 * captures what this dummy state represents.
7152 		 */
7153 		return (TS_WACK_DREQ7);
7154 	default:
7155 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7156 		    tcp->tcp_state, tcp_display(tcp, NULL,
7157 		    DISP_PORT_ONLY));
7158 		return (TS_UNBND);
7159 	}
7160 }
7161 
7162 static void
7163 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7164 {
7165 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7166 
7167 	if (tcp->tcp_family == AF_INET6)
7168 		*tia = tcp_g_t_info_ack_v6;
7169 	else
7170 		*tia = tcp_g_t_info_ack;
7171 	tia->CURRENT_state = tcp_tpistate(tcp);
7172 	tia->OPT_size = tcp_max_optsize;
7173 	if (tcp->tcp_mss == 0) {
7174 		/* Not yet set - tcp_open does not set mss */
7175 		if (tcp->tcp_ipversion == IPV4_VERSION)
7176 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7177 		else
7178 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7179 	} else {
7180 		tia->TIDU_size = tcp->tcp_mss;
7181 	}
7182 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7183 }
7184 
7185 static void
7186 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7187     t_uscalar_t cap_bits1)
7188 {
7189 	tcap->CAP_bits1 = 0;
7190 
7191 	if (cap_bits1 & TC1_INFO) {
7192 		tcp_copy_info(&tcap->INFO_ack, tcp);
7193 		tcap->CAP_bits1 |= TC1_INFO;
7194 	}
7195 
7196 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7197 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7198 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7199 	}
7200 
7201 }
7202 
7203 /*
7204  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7205  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7206  * tcp_g_t_info_ack.  The current state of the stream is copied from
7207  * tcp_state.
7208  */
7209 static void
7210 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7211 {
7212 	t_uscalar_t		cap_bits1;
7213 	struct T_capability_ack	*tcap;
7214 
7215 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7216 		freemsg(mp);
7217 		return;
7218 	}
7219 
7220 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7221 
7222 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7223 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7224 	if (mp == NULL)
7225 		return;
7226 
7227 	tcap = (struct T_capability_ack *)mp->b_rptr;
7228 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7229 
7230 	putnext(tcp->tcp_rq, mp);
7231 }
7232 
7233 /*
7234  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7235  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7236  * The current state of the stream is copied from tcp_state.
7237  */
7238 static void
7239 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7240 {
7241 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7242 	    T_INFO_ACK);
7243 	if (!mp) {
7244 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7245 		return;
7246 	}
7247 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7248 	putnext(tcp->tcp_rq, mp);
7249 }
7250 
7251 /* Respond to the TPI addr request */
7252 static void
7253 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7254 {
7255 	sin_t	*sin;
7256 	mblk_t	*ackmp;
7257 	struct T_addr_ack *taa;
7258 
7259 	/* Make it large enough for worst case */
7260 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7261 	    2 * sizeof (sin6_t), 1);
7262 	if (ackmp == NULL) {
7263 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7264 		return;
7265 	}
7266 
7267 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7268 		tcp_addr_req_ipv6(tcp, ackmp);
7269 		return;
7270 	}
7271 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7272 
7273 	bzero(taa, sizeof (struct T_addr_ack));
7274 	ackmp->b_wptr = (uchar_t *)&taa[1];
7275 
7276 	taa->PRIM_type = T_ADDR_ACK;
7277 	ackmp->b_datap->db_type = M_PCPROTO;
7278 
7279 	/*
7280 	 * Note: Following code assumes 32 bit alignment of basic
7281 	 * data structures like sin_t and struct T_addr_ack.
7282 	 */
7283 	if (tcp->tcp_state >= TCPS_BOUND) {
7284 		/*
7285 		 * Fill in local address
7286 		 */
7287 		taa->LOCADDR_length = sizeof (sin_t);
7288 		taa->LOCADDR_offset = sizeof (*taa);
7289 
7290 		sin = (sin_t *)&taa[1];
7291 
7292 		/* Fill zeroes and then intialize non-zero fields */
7293 		*sin = sin_null;
7294 
7295 		sin->sin_family = AF_INET;
7296 
7297 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7298 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7299 
7300 		ackmp->b_wptr = (uchar_t *)&sin[1];
7301 
7302 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7303 			/*
7304 			 * Fill in Remote address
7305 			 */
7306 			taa->REMADDR_length = sizeof (sin_t);
7307 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7308 			    taa->LOCADDR_length);
7309 
7310 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7311 			*sin = sin_null;
7312 			sin->sin_family = AF_INET;
7313 			sin->sin_addr.s_addr = tcp->tcp_remote;
7314 			sin->sin_port = tcp->tcp_fport;
7315 
7316 			ackmp->b_wptr = (uchar_t *)&sin[1];
7317 		}
7318 	}
7319 	putnext(tcp->tcp_rq, ackmp);
7320 }
7321 
7322 /* Assumes that tcp_addr_req gets enough space and alignment */
7323 static void
7324 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7325 {
7326 	sin6_t	*sin6;
7327 	struct T_addr_ack *taa;
7328 
7329 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7330 	ASSERT(OK_32PTR(ackmp->b_rptr));
7331 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7332 	    2 * sizeof (sin6_t));
7333 
7334 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7335 
7336 	bzero(taa, sizeof (struct T_addr_ack));
7337 	ackmp->b_wptr = (uchar_t *)&taa[1];
7338 
7339 	taa->PRIM_type = T_ADDR_ACK;
7340 	ackmp->b_datap->db_type = M_PCPROTO;
7341 
7342 	/*
7343 	 * Note: Following code assumes 32 bit alignment of basic
7344 	 * data structures like sin6_t and struct T_addr_ack.
7345 	 */
7346 	if (tcp->tcp_state >= TCPS_BOUND) {
7347 		/*
7348 		 * Fill in local address
7349 		 */
7350 		taa->LOCADDR_length = sizeof (sin6_t);
7351 		taa->LOCADDR_offset = sizeof (*taa);
7352 
7353 		sin6 = (sin6_t *)&taa[1];
7354 		*sin6 = sin6_null;
7355 
7356 		sin6->sin6_family = AF_INET6;
7357 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7358 		sin6->sin6_port = tcp->tcp_lport;
7359 
7360 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7361 
7362 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7363 			/*
7364 			 * Fill in Remote address
7365 			 */
7366 			taa->REMADDR_length = sizeof (sin6_t);
7367 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7368 			    taa->LOCADDR_length);
7369 
7370 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7371 			*sin6 = sin6_null;
7372 			sin6->sin6_family = AF_INET6;
7373 			sin6->sin6_flowinfo =
7374 			    tcp->tcp_ip6h->ip6_vcf &
7375 			    ~IPV6_VERS_AND_FLOW_MASK;
7376 			sin6->sin6_addr = tcp->tcp_remote_v6;
7377 			sin6->sin6_port = tcp->tcp_fport;
7378 
7379 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7380 		}
7381 	}
7382 	putnext(tcp->tcp_rq, ackmp);
7383 }
7384 
7385 /*
7386  * Handle reinitialization of a tcp structure.
7387  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7388  */
7389 static void
7390 tcp_reinit(tcp_t *tcp)
7391 {
7392 	mblk_t	*mp;
7393 	int 	err;
7394 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7395 
7396 	TCP_STAT(tcps, tcp_reinit_calls);
7397 
7398 	/* tcp_reinit should never be called for detached tcp_t's */
7399 	ASSERT(tcp->tcp_listener == NULL);
7400 	ASSERT((tcp->tcp_family == AF_INET &&
7401 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7402 	    (tcp->tcp_family == AF_INET6 &&
7403 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7404 	    tcp->tcp_ipversion == IPV6_VERSION)));
7405 
7406 	/* Cancel outstanding timers */
7407 	tcp_timers_stop(tcp);
7408 
7409 	/*
7410 	 * Reset everything in the state vector, after updating global
7411 	 * MIB data from instance counters.
7412 	 */
7413 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7414 	tcp->tcp_ibsegs = 0;
7415 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7416 	tcp->tcp_obsegs = 0;
7417 
7418 	tcp_close_mpp(&tcp->tcp_xmit_head);
7419 	if (tcp->tcp_snd_zcopy_aware)
7420 		tcp_zcopy_notify(tcp);
7421 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7422 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7423 	mutex_enter(&tcp->tcp_non_sq_lock);
7424 	if (tcp->tcp_flow_stopped &&
7425 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7426 		tcp_clrqfull(tcp);
7427 	}
7428 	mutex_exit(&tcp->tcp_non_sq_lock);
7429 	tcp_close_mpp(&tcp->tcp_reass_head);
7430 	tcp->tcp_reass_tail = NULL;
7431 	if (tcp->tcp_rcv_list != NULL) {
7432 		/* Free b_next chain */
7433 		tcp_close_mpp(&tcp->tcp_rcv_list);
7434 		tcp->tcp_rcv_last_head = NULL;
7435 		tcp->tcp_rcv_last_tail = NULL;
7436 		tcp->tcp_rcv_cnt = 0;
7437 	}
7438 	tcp->tcp_rcv_last_tail = NULL;
7439 
7440 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7441 		freemsg(mp);
7442 		tcp->tcp_urp_mp = NULL;
7443 	}
7444 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7445 		freemsg(mp);
7446 		tcp->tcp_urp_mark_mp = NULL;
7447 	}
7448 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7449 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7450 		freeb(tcp->tcp_fused_sigurg_mp);
7451 		tcp->tcp_fused_sigurg_mp = NULL;
7452 	}
7453 	if (tcp->tcp_ordrel_mp != NULL) {
7454 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7455 		freeb(tcp->tcp_ordrel_mp);
7456 		tcp->tcp_ordrel_mp = NULL;
7457 	}
7458 
7459 	/*
7460 	 * Following is a union with two members which are
7461 	 * identical types and size so the following cleanup
7462 	 * is enough.
7463 	 */
7464 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7465 
7466 	CL_INET_DISCONNECT(tcp);
7467 
7468 	/*
7469 	 * The connection can't be on the tcp_time_wait_head list
7470 	 * since it is not detached.
7471 	 */
7472 	ASSERT(tcp->tcp_time_wait_next == NULL);
7473 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7474 	ASSERT(tcp->tcp_time_wait_expire == 0);
7475 
7476 	if (tcp->tcp_kssl_pending) {
7477 		tcp->tcp_kssl_pending = B_FALSE;
7478 
7479 		/* Don't reset if the initialized by bind. */
7480 		if (tcp->tcp_kssl_ent != NULL) {
7481 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7482 			    KSSL_NO_PROXY);
7483 		}
7484 	}
7485 	if (tcp->tcp_kssl_ctx != NULL) {
7486 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7487 		tcp->tcp_kssl_ctx = NULL;
7488 	}
7489 
7490 	/*
7491 	 * Reset/preserve other values
7492 	 */
7493 	tcp_reinit_values(tcp);
7494 	ipcl_hash_remove(tcp->tcp_connp);
7495 	conn_delete_ire(tcp->tcp_connp, NULL);
7496 	tcp_ipsec_cleanup(tcp);
7497 
7498 	if (tcp->tcp_conn_req_max != 0) {
7499 		/*
7500 		 * This is the case when a TLI program uses the same
7501 		 * transport end point to accept a connection.  This
7502 		 * makes the TCP both a listener and acceptor.  When
7503 		 * this connection is closed, we need to set the state
7504 		 * back to TCPS_LISTEN.  Make sure that the eager list
7505 		 * is reinitialized.
7506 		 *
7507 		 * Note that this stream is still bound to the four
7508 		 * tuples of the previous connection in IP.  If a new
7509 		 * SYN with different foreign address comes in, IP will
7510 		 * not find it and will send it to the global queue.  In
7511 		 * the global queue, TCP will do a tcp_lookup_listener()
7512 		 * to find this stream.  This works because this stream
7513 		 * is only removed from connected hash.
7514 		 *
7515 		 */
7516 		tcp->tcp_state = TCPS_LISTEN;
7517 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7518 		tcp->tcp_eager_next_drop_q0 = tcp;
7519 		tcp->tcp_eager_prev_drop_q0 = tcp;
7520 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7521 		if (tcp->tcp_family == AF_INET6) {
7522 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7523 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7524 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7525 		} else {
7526 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7527 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7528 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7529 		}
7530 	} else {
7531 		tcp->tcp_state = TCPS_BOUND;
7532 	}
7533 
7534 	/*
7535 	 * Initialize to default values
7536 	 * Can't fail since enough header template space already allocated
7537 	 * at open().
7538 	 */
7539 	err = tcp_init_values(tcp);
7540 	ASSERT(err == 0);
7541 	/* Restore state in tcp_tcph */
7542 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7543 	if (tcp->tcp_ipversion == IPV4_VERSION)
7544 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7545 	else
7546 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7547 	/*
7548 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7549 	 * since the lookup funcs can only lookup on tcp_t
7550 	 */
7551 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7552 
7553 	ASSERT(tcp->tcp_ptpbhn != NULL);
7554 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7555 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7556 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7557 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7558 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7559 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7560 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7561 }
7562 
7563 /*
7564  * Force values to zero that need be zero.
7565  * Do not touch values asociated with the BOUND or LISTEN state
7566  * since the connection will end up in that state after the reinit.
7567  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7568  * structure!
7569  */
7570 static void
7571 tcp_reinit_values(tcp)
7572 	tcp_t *tcp;
7573 {
7574 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7575 
7576 #ifndef	lint
7577 #define	DONTCARE(x)
7578 #define	PRESERVE(x)
7579 #else
7580 #define	DONTCARE(x)	((x) = (x))
7581 #define	PRESERVE(x)	((x) = (x))
7582 #endif	/* lint */
7583 
7584 	PRESERVE(tcp->tcp_bind_hash_port);
7585 	PRESERVE(tcp->tcp_bind_hash);
7586 	PRESERVE(tcp->tcp_ptpbhn);
7587 	PRESERVE(tcp->tcp_acceptor_hash);
7588 	PRESERVE(tcp->tcp_ptpahn);
7589 
7590 	/* Should be ASSERT NULL on these with new code! */
7591 	ASSERT(tcp->tcp_time_wait_next == NULL);
7592 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7593 	ASSERT(tcp->tcp_time_wait_expire == 0);
7594 	PRESERVE(tcp->tcp_state);
7595 	PRESERVE(tcp->tcp_rq);
7596 	PRESERVE(tcp->tcp_wq);
7597 
7598 	ASSERT(tcp->tcp_xmit_head == NULL);
7599 	ASSERT(tcp->tcp_xmit_last == NULL);
7600 	ASSERT(tcp->tcp_unsent == 0);
7601 	ASSERT(tcp->tcp_xmit_tail == NULL);
7602 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7603 
7604 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7605 	tcp->tcp_suna = 0;			/* Displayed in mib */
7606 	tcp->tcp_swnd = 0;
7607 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7608 
7609 	ASSERT(tcp->tcp_ibsegs == 0);
7610 	ASSERT(tcp->tcp_obsegs == 0);
7611 
7612 	if (tcp->tcp_iphc != NULL) {
7613 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7614 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7615 	}
7616 
7617 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7618 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7619 	DONTCARE(tcp->tcp_ipha);
7620 	DONTCARE(tcp->tcp_ip6h);
7621 	DONTCARE(tcp->tcp_ip_hdr_len);
7622 	DONTCARE(tcp->tcp_tcph);
7623 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7624 	tcp->tcp_valid_bits = 0;
7625 
7626 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7627 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7628 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7629 	tcp->tcp_last_rcv_lbolt = 0;
7630 
7631 	tcp->tcp_init_cwnd = 0;
7632 
7633 	tcp->tcp_urp_last_valid = 0;
7634 	tcp->tcp_hard_binding = 0;
7635 	tcp->tcp_hard_bound = 0;
7636 	PRESERVE(tcp->tcp_cred);
7637 	PRESERVE(tcp->tcp_cpid);
7638 	PRESERVE(tcp->tcp_open_time);
7639 	PRESERVE(tcp->tcp_exclbind);
7640 
7641 	tcp->tcp_fin_acked = 0;
7642 	tcp->tcp_fin_rcvd = 0;
7643 	tcp->tcp_fin_sent = 0;
7644 	tcp->tcp_ordrel_done = 0;
7645 
7646 	tcp->tcp_debug = 0;
7647 	tcp->tcp_dontroute = 0;
7648 	tcp->tcp_broadcast = 0;
7649 
7650 	tcp->tcp_useloopback = 0;
7651 	tcp->tcp_reuseaddr = 0;
7652 	tcp->tcp_oobinline = 0;
7653 	tcp->tcp_dgram_errind = 0;
7654 
7655 	tcp->tcp_detached = 0;
7656 	tcp->tcp_bind_pending = 0;
7657 	tcp->tcp_unbind_pending = 0;
7658 
7659 	tcp->tcp_snd_ws_ok = B_FALSE;
7660 	tcp->tcp_snd_ts_ok = B_FALSE;
7661 	tcp->tcp_linger = 0;
7662 	tcp->tcp_ka_enabled = 0;
7663 	tcp->tcp_zero_win_probe = 0;
7664 
7665 	tcp->tcp_loopback = 0;
7666 	tcp->tcp_refuse = 0;
7667 	tcp->tcp_localnet = 0;
7668 	tcp->tcp_syn_defense = 0;
7669 	tcp->tcp_set_timer = 0;
7670 
7671 	tcp->tcp_active_open = 0;
7672 	tcp->tcp_rexmit = B_FALSE;
7673 	tcp->tcp_xmit_zc_clean = B_FALSE;
7674 
7675 	tcp->tcp_snd_sack_ok = B_FALSE;
7676 	PRESERVE(tcp->tcp_recvdstaddr);
7677 	tcp->tcp_hwcksum = B_FALSE;
7678 
7679 	tcp->tcp_ire_ill_check_done = B_FALSE;
7680 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7681 
7682 	tcp->tcp_mdt = B_FALSE;
7683 	tcp->tcp_mdt_hdr_head = 0;
7684 	tcp->tcp_mdt_hdr_tail = 0;
7685 
7686 	tcp->tcp_conn_def_q0 = 0;
7687 	tcp->tcp_ip_forward_progress = B_FALSE;
7688 	tcp->tcp_anon_priv_bind = 0;
7689 	tcp->tcp_ecn_ok = B_FALSE;
7690 
7691 	tcp->tcp_cwr = B_FALSE;
7692 	tcp->tcp_ecn_echo_on = B_FALSE;
7693 
7694 	if (tcp->tcp_sack_info != NULL) {
7695 		if (tcp->tcp_notsack_list != NULL) {
7696 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7697 		}
7698 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7699 		tcp->tcp_sack_info = NULL;
7700 	}
7701 
7702 	tcp->tcp_rcv_ws = 0;
7703 	tcp->tcp_snd_ws = 0;
7704 	tcp->tcp_ts_recent = 0;
7705 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7706 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7707 	tcp->tcp_if_mtu = 0;
7708 
7709 	ASSERT(tcp->tcp_reass_head == NULL);
7710 	ASSERT(tcp->tcp_reass_tail == NULL);
7711 
7712 	tcp->tcp_cwnd_cnt = 0;
7713 
7714 	ASSERT(tcp->tcp_rcv_list == NULL);
7715 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7716 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7717 	ASSERT(tcp->tcp_rcv_cnt == 0);
7718 
7719 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7720 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7721 	tcp->tcp_csuna = 0;
7722 
7723 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7724 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7725 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7726 	tcp->tcp_rtt_update = 0;
7727 
7728 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7729 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7730 
7731 	tcp->tcp_rack = 0;			/* Displayed in mib */
7732 	tcp->tcp_rack_cnt = 0;
7733 	tcp->tcp_rack_cur_max = 0;
7734 	tcp->tcp_rack_abs_max = 0;
7735 
7736 	tcp->tcp_max_swnd = 0;
7737 
7738 	ASSERT(tcp->tcp_listener == NULL);
7739 
7740 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7741 
7742 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7743 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7744 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7745 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7746 
7747 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7748 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7749 	PRESERVE(tcp->tcp_conn_req_max);
7750 	PRESERVE(tcp->tcp_conn_req_seqnum);
7751 
7752 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7753 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7754 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7755 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7756 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7757 
7758 	tcp->tcp_lingertime = 0;
7759 
7760 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7761 	ASSERT(tcp->tcp_urp_mp == NULL);
7762 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7763 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7764 
7765 	ASSERT(tcp->tcp_eager_next_q == NULL);
7766 	ASSERT(tcp->tcp_eager_last_q == NULL);
7767 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7768 	    tcp->tcp_eager_prev_q0 == NULL) ||
7769 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7770 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7771 
7772 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7773 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7774 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7775 
7776 	tcp->tcp_client_errno = 0;
7777 
7778 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7779 
7780 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7781 
7782 	PRESERVE(tcp->tcp_bound_source_v6);
7783 	tcp->tcp_last_sent_len = 0;
7784 	tcp->tcp_dupack_cnt = 0;
7785 
7786 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7787 	PRESERVE(tcp->tcp_lport);
7788 
7789 	PRESERVE(tcp->tcp_acceptor_lockp);
7790 
7791 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7792 	PRESERVE(tcp->tcp_acceptor_id);
7793 	DONTCARE(tcp->tcp_ipsec_overhead);
7794 
7795 	PRESERVE(tcp->tcp_family);
7796 	if (tcp->tcp_family == AF_INET6) {
7797 		tcp->tcp_ipversion = IPV6_VERSION;
7798 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7799 	} else {
7800 		tcp->tcp_ipversion = IPV4_VERSION;
7801 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7802 	}
7803 
7804 	tcp->tcp_bound_if = 0;
7805 	tcp->tcp_ipv6_recvancillary = 0;
7806 	tcp->tcp_recvifindex = 0;
7807 	tcp->tcp_recvhops = 0;
7808 	tcp->tcp_closed = 0;
7809 	tcp->tcp_cleandeathtag = 0;
7810 	if (tcp->tcp_hopopts != NULL) {
7811 		mi_free(tcp->tcp_hopopts);
7812 		tcp->tcp_hopopts = NULL;
7813 		tcp->tcp_hopoptslen = 0;
7814 	}
7815 	ASSERT(tcp->tcp_hopoptslen == 0);
7816 	if (tcp->tcp_dstopts != NULL) {
7817 		mi_free(tcp->tcp_dstopts);
7818 		tcp->tcp_dstopts = NULL;
7819 		tcp->tcp_dstoptslen = 0;
7820 	}
7821 	ASSERT(tcp->tcp_dstoptslen == 0);
7822 	if (tcp->tcp_rtdstopts != NULL) {
7823 		mi_free(tcp->tcp_rtdstopts);
7824 		tcp->tcp_rtdstopts = NULL;
7825 		tcp->tcp_rtdstoptslen = 0;
7826 	}
7827 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7828 	if (tcp->tcp_rthdr != NULL) {
7829 		mi_free(tcp->tcp_rthdr);
7830 		tcp->tcp_rthdr = NULL;
7831 		tcp->tcp_rthdrlen = 0;
7832 	}
7833 	ASSERT(tcp->tcp_rthdrlen == 0);
7834 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7835 
7836 	/* Reset fusion-related fields */
7837 	tcp->tcp_fused = B_FALSE;
7838 	tcp->tcp_unfusable = B_FALSE;
7839 	tcp->tcp_fused_sigurg = B_FALSE;
7840 	tcp->tcp_direct_sockfs = B_FALSE;
7841 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7842 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7843 	tcp->tcp_loopback_peer = NULL;
7844 	tcp->tcp_fuse_rcv_hiwater = 0;
7845 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7846 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7847 
7848 	tcp->tcp_lso = B_FALSE;
7849 
7850 	tcp->tcp_in_ack_unsent = 0;
7851 	tcp->tcp_cork = B_FALSE;
7852 	tcp->tcp_tconnind_started = B_FALSE;
7853 
7854 	PRESERVE(tcp->tcp_squeue_bytes);
7855 
7856 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7857 	ASSERT(!tcp->tcp_kssl_pending);
7858 	PRESERVE(tcp->tcp_kssl_ent);
7859 
7860 	/* Sodirect */
7861 	tcp->tcp_sodirect = NULL;
7862 
7863 	tcp->tcp_closemp_used = B_FALSE;
7864 
7865 	PRESERVE(tcp->tcp_rsrv_mp);
7866 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7867 
7868 #ifdef DEBUG
7869 	DONTCARE(tcp->tcmp_stk[0]);
7870 #endif
7871 
7872 	PRESERVE(tcp->tcp_connid);
7873 
7874 
7875 #undef	DONTCARE
7876 #undef	PRESERVE
7877 }
7878 
7879 /*
7880  * Allocate necessary resources and initialize state vector.
7881  * Guaranteed not to fail so that when an error is returned,
7882  * the caller doesn't need to do any additional cleanup.
7883  */
7884 int
7885 tcp_init(tcp_t *tcp, queue_t *q)
7886 {
7887 	int	err;
7888 
7889 	tcp->tcp_rq = q;
7890 	tcp->tcp_wq = WR(q);
7891 	tcp->tcp_state = TCPS_IDLE;
7892 	if ((err = tcp_init_values(tcp)) != 0)
7893 		tcp_timers_stop(tcp);
7894 	return (err);
7895 }
7896 
7897 static int
7898 tcp_init_values(tcp_t *tcp)
7899 {
7900 	int	err;
7901 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7902 
7903 	ASSERT((tcp->tcp_family == AF_INET &&
7904 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7905 	    (tcp->tcp_family == AF_INET6 &&
7906 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7907 	    tcp->tcp_ipversion == IPV6_VERSION)));
7908 
7909 	/*
7910 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7911 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7912 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7913 	 * during first few transmissions of a connection as seen in slow
7914 	 * links.
7915 	 */
7916 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7917 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7918 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7919 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7920 	    tcps->tcps_conn_grace_period;
7921 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7922 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7923 	tcp->tcp_timer_backoff = 0;
7924 	tcp->tcp_ms_we_have_waited = 0;
7925 	tcp->tcp_last_recv_time = lbolt;
7926 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7927 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7928 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7929 
7930 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7931 
7932 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7933 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7934 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7935 	/*
7936 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7937 	 * passive open.
7938 	 */
7939 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7940 
7941 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7942 
7943 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7944 
7945 	tcp->tcp_mdt_hdr_head = 0;
7946 	tcp->tcp_mdt_hdr_tail = 0;
7947 
7948 	/* Reset fusion-related fields */
7949 	tcp->tcp_fused = B_FALSE;
7950 	tcp->tcp_unfusable = B_FALSE;
7951 	tcp->tcp_fused_sigurg = B_FALSE;
7952 	tcp->tcp_direct_sockfs = B_FALSE;
7953 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7954 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7955 	tcp->tcp_loopback_peer = NULL;
7956 	tcp->tcp_fuse_rcv_hiwater = 0;
7957 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7958 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7959 
7960 	/* Sodirect */
7961 	tcp->tcp_sodirect = NULL;
7962 
7963 	/* Initialize the header template */
7964 	if (tcp->tcp_ipversion == IPV4_VERSION) {
7965 		err = tcp_header_init_ipv4(tcp);
7966 	} else {
7967 		err = tcp_header_init_ipv6(tcp);
7968 	}
7969 	if (err)
7970 		return (err);
7971 
7972 	/*
7973 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
7974 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
7975 	 */
7976 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
7977 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
7978 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
7979 
7980 	tcp->tcp_cork = B_FALSE;
7981 	/*
7982 	 * Init the tcp_debug option.  This value determines whether TCP
7983 	 * calls strlog() to print out debug messages.  Doing this
7984 	 * initialization here means that this value is not inherited thru
7985 	 * tcp_reinit().
7986 	 */
7987 	tcp->tcp_debug = tcps->tcps_dbg;
7988 
7989 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
7990 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
7991 
7992 	return (0);
7993 }
7994 
7995 /*
7996  * Initialize the IPv4 header. Loses any record of any IP options.
7997  */
7998 static int
7999 tcp_header_init_ipv4(tcp_t *tcp)
8000 {
8001 	tcph_t		*tcph;
8002 	uint32_t	sum;
8003 	conn_t		*connp;
8004 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8005 
8006 	/*
8007 	 * This is a simple initialization. If there's
8008 	 * already a template, it should never be too small,
8009 	 * so reuse it.  Otherwise, allocate space for the new one.
8010 	 */
8011 	if (tcp->tcp_iphc == NULL) {
8012 		ASSERT(tcp->tcp_iphc_len == 0);
8013 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8014 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8015 		if (tcp->tcp_iphc == NULL) {
8016 			tcp->tcp_iphc_len = 0;
8017 			return (ENOMEM);
8018 		}
8019 	}
8020 
8021 	/* options are gone; may need a new label */
8022 	connp = tcp->tcp_connp;
8023 	connp->conn_mlp_type = mlptSingle;
8024 	connp->conn_ulp_labeled = !is_system_labeled();
8025 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8026 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8027 	tcp->tcp_ip6h = NULL;
8028 	tcp->tcp_ipversion = IPV4_VERSION;
8029 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8030 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8031 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8032 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8033 	tcp->tcp_ipha->ipha_version_and_hdr_length
8034 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8035 	tcp->tcp_ipha->ipha_ident = 0;
8036 
8037 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8038 	tcp->tcp_tos = 0;
8039 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8040 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8041 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8042 
8043 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8044 	tcp->tcp_tcph = tcph;
8045 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8046 	/*
8047 	 * IP wants our header length in the checksum field to
8048 	 * allow it to perform a single pseudo-header+checksum
8049 	 * calculation on behalf of TCP.
8050 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8051 	 */
8052 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8053 	sum = (sum >> 16) + (sum & 0xFFFF);
8054 	U16_TO_ABE16(sum, tcph->th_sum);
8055 	return (0);
8056 }
8057 
8058 /*
8059  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8060  */
8061 static int
8062 tcp_header_init_ipv6(tcp_t *tcp)
8063 {
8064 	tcph_t	*tcph;
8065 	uint32_t	sum;
8066 	conn_t	*connp;
8067 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8068 
8069 	/*
8070 	 * This is a simple initialization. If there's
8071 	 * already a template, it should never be too small,
8072 	 * so reuse it. Otherwise, allocate space for the new one.
8073 	 * Ensure that there is enough space to "downgrade" the tcp_t
8074 	 * to an IPv4 tcp_t. This requires having space for a full load
8075 	 * of IPv4 options, as well as a full load of TCP options
8076 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8077 	 * than a v6 header and a TCP header with a full load of TCP options
8078 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8079 	 * We want to avoid reallocation in the "downgraded" case when
8080 	 * processing outbound IPv4 options.
8081 	 */
8082 	if (tcp->tcp_iphc == NULL) {
8083 		ASSERT(tcp->tcp_iphc_len == 0);
8084 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8085 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8086 		if (tcp->tcp_iphc == NULL) {
8087 			tcp->tcp_iphc_len = 0;
8088 			return (ENOMEM);
8089 		}
8090 	}
8091 
8092 	/* options are gone; may need a new label */
8093 	connp = tcp->tcp_connp;
8094 	connp->conn_mlp_type = mlptSingle;
8095 	connp->conn_ulp_labeled = !is_system_labeled();
8096 
8097 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8098 	tcp->tcp_ipversion = IPV6_VERSION;
8099 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8100 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8101 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8102 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8103 	tcp->tcp_ipha = NULL;
8104 
8105 	/* Initialize the header template */
8106 
8107 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8108 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8109 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8110 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8111 
8112 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8113 	tcp->tcp_tcph = tcph;
8114 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8115 	/*
8116 	 * IP wants our header length in the checksum field to
8117 	 * allow it to perform a single psuedo-header+checksum
8118 	 * calculation on behalf of TCP.
8119 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8120 	 */
8121 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8122 	sum = (sum >> 16) + (sum & 0xFFFF);
8123 	U16_TO_ABE16(sum, tcph->th_sum);
8124 	return (0);
8125 }
8126 
8127 /* At minimum we need 8 bytes in the TCP header for the lookup */
8128 #define	ICMP_MIN_TCP_HDR	8
8129 
8130 /*
8131  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8132  * passed up by IP. The message is always received on the correct tcp_t.
8133  * Assumes that IP has pulled up everything up to and including the ICMP header.
8134  */
8135 void
8136 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8137 {
8138 	icmph_t *icmph;
8139 	ipha_t	*ipha;
8140 	int	iph_hdr_length;
8141 	tcph_t	*tcph;
8142 	boolean_t ipsec_mctl = B_FALSE;
8143 	boolean_t secure;
8144 	mblk_t *first_mp = mp;
8145 	int32_t new_mss;
8146 	uint32_t ratio;
8147 	size_t mp_size = MBLKL(mp);
8148 	uint32_t seg_seq;
8149 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8150 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8151 
8152 	/* Assume IP provides aligned packets - otherwise toss */
8153 	if (!OK_32PTR(mp->b_rptr)) {
8154 		freemsg(mp);
8155 		return;
8156 	}
8157 
8158 	/*
8159 	 * Since ICMP errors are normal data marked with M_CTL when sent
8160 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8161 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8162 	 */
8163 	if ((mp_size == sizeof (ipsec_info_t)) &&
8164 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8165 		ASSERT(mp->b_cont != NULL);
8166 		mp = mp->b_cont;
8167 		/* IP should have done this */
8168 		ASSERT(OK_32PTR(mp->b_rptr));
8169 		mp_size = MBLKL(mp);
8170 		ipsec_mctl = B_TRUE;
8171 	}
8172 
8173 	/*
8174 	 * Verify that we have a complete outer IP header. If not, drop it.
8175 	 */
8176 	if (mp_size < sizeof (ipha_t)) {
8177 noticmpv4:
8178 		freemsg(first_mp);
8179 		return;
8180 	}
8181 
8182 	ipha = (ipha_t *)mp->b_rptr;
8183 	/*
8184 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8185 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8186 	 */
8187 	switch (IPH_HDR_VERSION(ipha)) {
8188 	case IPV6_VERSION:
8189 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8190 		return;
8191 	case IPV4_VERSION:
8192 		break;
8193 	default:
8194 		goto noticmpv4;
8195 	}
8196 
8197 	/* Skip past the outer IP and ICMP headers */
8198 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8199 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8200 	/*
8201 	 * If we don't have the correct outer IP header length or if the ULP
8202 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8203 	 * send it upstream.
8204 	 */
8205 	if (iph_hdr_length < sizeof (ipha_t) ||
8206 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8207 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8208 		goto noticmpv4;
8209 	}
8210 	ipha = (ipha_t *)&icmph[1];
8211 
8212 	/* Skip past the inner IP and find the ULP header */
8213 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8214 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8215 	/*
8216 	 * If we don't have the correct inner IP header length or if the ULP
8217 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8218 	 * bytes of TCP header, drop it.
8219 	 */
8220 	if (iph_hdr_length < sizeof (ipha_t) ||
8221 	    ipha->ipha_protocol != IPPROTO_TCP ||
8222 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8223 		goto noticmpv4;
8224 	}
8225 
8226 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8227 		if (ipsec_mctl) {
8228 			secure = ipsec_in_is_secure(first_mp);
8229 		} else {
8230 			secure = B_FALSE;
8231 		}
8232 		if (secure) {
8233 			/*
8234 			 * If we are willing to accept this in clear
8235 			 * we don't have to verify policy.
8236 			 */
8237 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8238 				if (!tcp_check_policy(tcp, first_mp,
8239 				    ipha, NULL, secure, ipsec_mctl)) {
8240 					/*
8241 					 * tcp_check_policy called
8242 					 * ip_drop_packet() on failure.
8243 					 */
8244 					return;
8245 				}
8246 			}
8247 		}
8248 	} else if (ipsec_mctl) {
8249 		/*
8250 		 * This is a hard_bound connection. IP has already
8251 		 * verified policy. We don't have to do it again.
8252 		 */
8253 		freeb(first_mp);
8254 		first_mp = mp;
8255 		ipsec_mctl = B_FALSE;
8256 	}
8257 
8258 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8259 	/*
8260 	 * TCP SHOULD check that the TCP sequence number contained in
8261 	 * payload of the ICMP error message is within the range
8262 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8263 	 */
8264 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8265 		/*
8266 		 * The ICMP message is bogus, just drop it.  But if this is
8267 		 * an ICMP too big message, IP has already changed
8268 		 * the ire_max_frag to the bogus value.  We need to change
8269 		 * it back.
8270 		 */
8271 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8272 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8273 			conn_t *connp = tcp->tcp_connp;
8274 			ire_t *ire;
8275 			int flag;
8276 
8277 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8278 				flag = tcp->tcp_ipha->
8279 				    ipha_fragment_offset_and_flags;
8280 			} else {
8281 				flag = 0;
8282 			}
8283 			mutex_enter(&connp->conn_lock);
8284 			if ((ire = connp->conn_ire_cache) != NULL) {
8285 				mutex_enter(&ire->ire_lock);
8286 				mutex_exit(&connp->conn_lock);
8287 				ire->ire_max_frag = tcp->tcp_if_mtu;
8288 				ire->ire_frag_flag |= flag;
8289 				mutex_exit(&ire->ire_lock);
8290 			} else {
8291 				mutex_exit(&connp->conn_lock);
8292 			}
8293 		}
8294 		goto noticmpv4;
8295 	}
8296 
8297 	switch (icmph->icmph_type) {
8298 	case ICMP_DEST_UNREACHABLE:
8299 		switch (icmph->icmph_code) {
8300 		case ICMP_FRAGMENTATION_NEEDED:
8301 			/*
8302 			 * Reduce the MSS based on the new MTU.  This will
8303 			 * eliminate any fragmentation locally.
8304 			 * N.B.  There may well be some funny side-effects on
8305 			 * the local send policy and the remote receive policy.
8306 			 * Pending further research, we provide
8307 			 * tcp_ignore_path_mtu just in case this proves
8308 			 * disastrous somewhere.
8309 			 *
8310 			 * After updating the MSS, retransmit part of the
8311 			 * dropped segment using the new mss by calling
8312 			 * tcp_wput_data().  Need to adjust all those
8313 			 * params to make sure tcp_wput_data() work properly.
8314 			 */
8315 			if (tcps->tcps_ignore_path_mtu ||
8316 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8317 				break;
8318 
8319 			/*
8320 			 * Decrease the MSS by time stamp options
8321 			 * IP options and IPSEC options. tcp_hdr_len
8322 			 * includes time stamp option and IP option
8323 			 * length.  Note that new_mss may be negative
8324 			 * if tcp_ipsec_overhead is large and the
8325 			 * icmph_du_mtu is the minimum value, which is 68.
8326 			 */
8327 			new_mss = ntohs(icmph->icmph_du_mtu) -
8328 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8329 
8330 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8331 			    new_mss);
8332 
8333 			/*
8334 			 * Only update the MSS if the new one is
8335 			 * smaller than the previous one.  This is
8336 			 * to avoid problems when getting multiple
8337 			 * ICMP errors for the same MTU.
8338 			 */
8339 			if (new_mss >= tcp->tcp_mss)
8340 				break;
8341 
8342 			/*
8343 			 * Note that we are using the template header's DF
8344 			 * bit in the fast path sending.  So we need to compare
8345 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8346 			 * And stop doing IPv4 PMTUd if new_mss is less than
8347 			 * MAX(tcps_mss_min, ip_pmtu_min).
8348 			 */
8349 			if (new_mss < tcps->tcps_mss_min ||
8350 			    new_mss < ipst->ips_ip_pmtu_min) {
8351 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8352 				    0;
8353 			}
8354 
8355 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8356 			ASSERT(ratio >= 1);
8357 			tcp_mss_set(tcp, new_mss, B_TRUE);
8358 
8359 			/*
8360 			 * Make sure we have something to
8361 			 * send.
8362 			 */
8363 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8364 			    (tcp->tcp_xmit_head != NULL)) {
8365 				/*
8366 				 * Shrink tcp_cwnd in
8367 				 * proportion to the old MSS/new MSS.
8368 				 */
8369 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8370 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8371 				    (tcp->tcp_unsent == 0)) {
8372 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8373 				} else {
8374 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8375 				}
8376 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8377 				tcp->tcp_rexmit = B_TRUE;
8378 				tcp->tcp_dupack_cnt = 0;
8379 				tcp->tcp_snd_burst = TCP_CWND_SS;
8380 				tcp_ss_rexmit(tcp);
8381 			}
8382 			break;
8383 		case ICMP_PORT_UNREACHABLE:
8384 		case ICMP_PROTOCOL_UNREACHABLE:
8385 			switch (tcp->tcp_state) {
8386 			case TCPS_SYN_SENT:
8387 			case TCPS_SYN_RCVD:
8388 				/*
8389 				 * ICMP can snipe away incipient
8390 				 * TCP connections as long as
8391 				 * seq number is same as initial
8392 				 * send seq number.
8393 				 */
8394 				if (seg_seq == tcp->tcp_iss) {
8395 					(void) tcp_clean_death(tcp,
8396 					    ECONNREFUSED, 6);
8397 				}
8398 				break;
8399 			}
8400 			break;
8401 		case ICMP_HOST_UNREACHABLE:
8402 		case ICMP_NET_UNREACHABLE:
8403 			/* Record the error in case we finally time out. */
8404 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8405 				tcp->tcp_client_errno = EHOSTUNREACH;
8406 			else
8407 				tcp->tcp_client_errno = ENETUNREACH;
8408 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8409 				if (tcp->tcp_listener != NULL &&
8410 				    tcp->tcp_listener->tcp_syn_defense) {
8411 					/*
8412 					 * Ditch the half-open connection if we
8413 					 * suspect a SYN attack is under way.
8414 					 */
8415 					tcp_ip_ire_mark_advice(tcp);
8416 					(void) tcp_clean_death(tcp,
8417 					    tcp->tcp_client_errno, 7);
8418 				}
8419 			}
8420 			break;
8421 		default:
8422 			break;
8423 		}
8424 		break;
8425 	case ICMP_SOURCE_QUENCH: {
8426 		/*
8427 		 * use a global boolean to control
8428 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8429 		 * The default is false.
8430 		 */
8431 		if (tcp_icmp_source_quench) {
8432 			/*
8433 			 * Reduce the sending rate as if we got a
8434 			 * retransmit timeout
8435 			 */
8436 			uint32_t npkt;
8437 
8438 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8439 			    tcp->tcp_mss;
8440 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8441 			tcp->tcp_cwnd = tcp->tcp_mss;
8442 			tcp->tcp_cwnd_cnt = 0;
8443 		}
8444 		break;
8445 	}
8446 	}
8447 	freemsg(first_mp);
8448 }
8449 
8450 /*
8451  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8452  * error messages passed up by IP.
8453  * Assumes that IP has pulled up all the extension headers as well
8454  * as the ICMPv6 header.
8455  */
8456 static void
8457 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8458 {
8459 	icmp6_t *icmp6;
8460 	ip6_t	*ip6h;
8461 	uint16_t	iph_hdr_length;
8462 	tcpha_t	*tcpha;
8463 	uint8_t	*nexthdrp;
8464 	uint32_t new_mss;
8465 	uint32_t ratio;
8466 	boolean_t secure;
8467 	mblk_t *first_mp = mp;
8468 	size_t mp_size;
8469 	uint32_t seg_seq;
8470 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8471 
8472 	/*
8473 	 * The caller has determined if this is an IPSEC_IN packet and
8474 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8475 	 */
8476 	if (ipsec_mctl)
8477 		mp = mp->b_cont;
8478 
8479 	mp_size = MBLKL(mp);
8480 
8481 	/*
8482 	 * Verify that we have a complete IP header. If not, send it upstream.
8483 	 */
8484 	if (mp_size < sizeof (ip6_t)) {
8485 noticmpv6:
8486 		freemsg(first_mp);
8487 		return;
8488 	}
8489 
8490 	/*
8491 	 * Verify this is an ICMPV6 packet, else send it upstream.
8492 	 */
8493 	ip6h = (ip6_t *)mp->b_rptr;
8494 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8495 		iph_hdr_length = IPV6_HDR_LEN;
8496 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8497 	    &nexthdrp) ||
8498 	    *nexthdrp != IPPROTO_ICMPV6) {
8499 		goto noticmpv6;
8500 	}
8501 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8502 	ip6h = (ip6_t *)&icmp6[1];
8503 	/*
8504 	 * Verify if we have a complete ICMP and inner IP header.
8505 	 */
8506 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8507 		goto noticmpv6;
8508 
8509 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8510 		goto noticmpv6;
8511 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8512 	/*
8513 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8514 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8515 	 * packet.
8516 	 */
8517 	if ((*nexthdrp != IPPROTO_TCP) ||
8518 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8519 		goto noticmpv6;
8520 	}
8521 
8522 	/*
8523 	 * ICMP errors come on the right queue or come on
8524 	 * listener/global queue for detached connections and
8525 	 * get switched to the right queue. If it comes on the
8526 	 * right queue, policy check has already been done by IP
8527 	 * and thus free the first_mp without verifying the policy.
8528 	 * If it has come for a non-hard bound connection, we need
8529 	 * to verify policy as IP may not have done it.
8530 	 */
8531 	if (!tcp->tcp_hard_bound) {
8532 		if (ipsec_mctl) {
8533 			secure = ipsec_in_is_secure(first_mp);
8534 		} else {
8535 			secure = B_FALSE;
8536 		}
8537 		if (secure) {
8538 			/*
8539 			 * If we are willing to accept this in clear
8540 			 * we don't have to verify policy.
8541 			 */
8542 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8543 				if (!tcp_check_policy(tcp, first_mp,
8544 				    NULL, ip6h, secure, ipsec_mctl)) {
8545 					/*
8546 					 * tcp_check_policy called
8547 					 * ip_drop_packet() on failure.
8548 					 */
8549 					return;
8550 				}
8551 			}
8552 		}
8553 	} else if (ipsec_mctl) {
8554 		/*
8555 		 * This is a hard_bound connection. IP has already
8556 		 * verified policy. We don't have to do it again.
8557 		 */
8558 		freeb(first_mp);
8559 		first_mp = mp;
8560 		ipsec_mctl = B_FALSE;
8561 	}
8562 
8563 	seg_seq = ntohl(tcpha->tha_seq);
8564 	/*
8565 	 * TCP SHOULD check that the TCP sequence number contained in
8566 	 * payload of the ICMP error message is within the range
8567 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8568 	 */
8569 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8570 		/*
8571 		 * If the ICMP message is bogus, should we kill the
8572 		 * connection, or should we just drop the bogus ICMP
8573 		 * message? It would probably make more sense to just
8574 		 * drop the message so that if this one managed to get
8575 		 * in, the real connection should not suffer.
8576 		 */
8577 		goto noticmpv6;
8578 	}
8579 
8580 	switch (icmp6->icmp6_type) {
8581 	case ICMP6_PACKET_TOO_BIG:
8582 		/*
8583 		 * Reduce the MSS based on the new MTU.  This will
8584 		 * eliminate any fragmentation locally.
8585 		 * N.B.  There may well be some funny side-effects on
8586 		 * the local send policy and the remote receive policy.
8587 		 * Pending further research, we provide
8588 		 * tcp_ignore_path_mtu just in case this proves
8589 		 * disastrous somewhere.
8590 		 *
8591 		 * After updating the MSS, retransmit part of the
8592 		 * dropped segment using the new mss by calling
8593 		 * tcp_wput_data().  Need to adjust all those
8594 		 * params to make sure tcp_wput_data() work properly.
8595 		 */
8596 		if (tcps->tcps_ignore_path_mtu)
8597 			break;
8598 
8599 		/*
8600 		 * Decrease the MSS by time stamp options
8601 		 * IP options and IPSEC options. tcp_hdr_len
8602 		 * includes time stamp option and IP option
8603 		 * length.
8604 		 */
8605 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8606 		    tcp->tcp_ipsec_overhead;
8607 
8608 		/*
8609 		 * Only update the MSS if the new one is
8610 		 * smaller than the previous one.  This is
8611 		 * to avoid problems when getting multiple
8612 		 * ICMP errors for the same MTU.
8613 		 */
8614 		if (new_mss >= tcp->tcp_mss)
8615 			break;
8616 
8617 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8618 		ASSERT(ratio >= 1);
8619 		tcp_mss_set(tcp, new_mss, B_TRUE);
8620 
8621 		/*
8622 		 * Make sure we have something to
8623 		 * send.
8624 		 */
8625 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8626 		    (tcp->tcp_xmit_head != NULL)) {
8627 			/*
8628 			 * Shrink tcp_cwnd in
8629 			 * proportion to the old MSS/new MSS.
8630 			 */
8631 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8632 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8633 			    (tcp->tcp_unsent == 0)) {
8634 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8635 			} else {
8636 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8637 			}
8638 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8639 			tcp->tcp_rexmit = B_TRUE;
8640 			tcp->tcp_dupack_cnt = 0;
8641 			tcp->tcp_snd_burst = TCP_CWND_SS;
8642 			tcp_ss_rexmit(tcp);
8643 		}
8644 		break;
8645 
8646 	case ICMP6_DST_UNREACH:
8647 		switch (icmp6->icmp6_code) {
8648 		case ICMP6_DST_UNREACH_NOPORT:
8649 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8650 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8651 			    (seg_seq == tcp->tcp_iss)) {
8652 				(void) tcp_clean_death(tcp,
8653 				    ECONNREFUSED, 8);
8654 			}
8655 			break;
8656 
8657 		case ICMP6_DST_UNREACH_ADMIN:
8658 		case ICMP6_DST_UNREACH_NOROUTE:
8659 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8660 		case ICMP6_DST_UNREACH_ADDR:
8661 			/* Record the error in case we finally time out. */
8662 			tcp->tcp_client_errno = EHOSTUNREACH;
8663 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8664 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8665 			    (seg_seq == tcp->tcp_iss)) {
8666 				if (tcp->tcp_listener != NULL &&
8667 				    tcp->tcp_listener->tcp_syn_defense) {
8668 					/*
8669 					 * Ditch the half-open connection if we
8670 					 * suspect a SYN attack is under way.
8671 					 */
8672 					tcp_ip_ire_mark_advice(tcp);
8673 					(void) tcp_clean_death(tcp,
8674 					    tcp->tcp_client_errno, 9);
8675 				}
8676 			}
8677 
8678 
8679 			break;
8680 		default:
8681 			break;
8682 		}
8683 		break;
8684 
8685 	case ICMP6_PARAM_PROB:
8686 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8687 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8688 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8689 		    (uchar_t *)nexthdrp) {
8690 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8691 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8692 				(void) tcp_clean_death(tcp,
8693 				    ECONNREFUSED, 10);
8694 			}
8695 			break;
8696 		}
8697 		break;
8698 
8699 	case ICMP6_TIME_EXCEEDED:
8700 	default:
8701 		break;
8702 	}
8703 	freemsg(first_mp);
8704 }
8705 
8706 /*
8707  * Notify IP that we are having trouble with this connection.  IP should
8708  * blow the IRE away and start over.
8709  */
8710 static void
8711 tcp_ip_notify(tcp_t *tcp)
8712 {
8713 	struct iocblk	*iocp;
8714 	ipid_t	*ipid;
8715 	mblk_t	*mp;
8716 
8717 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8718 	if (tcp->tcp_ipversion == IPV6_VERSION)
8719 		return;
8720 
8721 	mp = mkiocb(IP_IOCTL);
8722 	if (mp == NULL)
8723 		return;
8724 
8725 	iocp = (struct iocblk *)mp->b_rptr;
8726 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8727 
8728 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8729 	if (!mp->b_cont) {
8730 		freeb(mp);
8731 		return;
8732 	}
8733 
8734 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8735 	mp->b_cont->b_wptr += iocp->ioc_count;
8736 	bzero(ipid, sizeof (*ipid));
8737 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8738 	ipid->ipid_ire_type = IRE_CACHE;
8739 	ipid->ipid_addr_offset = sizeof (ipid_t);
8740 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8741 	/*
8742 	 * Note: in the case of source routing we want to blow away the
8743 	 * route to the first source route hop.
8744 	 */
8745 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8746 	    sizeof (tcp->tcp_ipha->ipha_dst));
8747 
8748 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8749 }
8750 
8751 /* Unlink and return any mblk that looks like it contains an ire */
8752 static mblk_t *
8753 tcp_ire_mp(mblk_t **mpp)
8754 {
8755 	mblk_t 	*mp = *mpp;
8756 	mblk_t	*prev_mp = NULL;
8757 
8758 	for (;;) {
8759 		switch (DB_TYPE(mp)) {
8760 		case IRE_DB_TYPE:
8761 		case IRE_DB_REQ_TYPE:
8762 			if (mp == *mpp) {
8763 				*mpp = mp->b_cont;
8764 			} else {
8765 				prev_mp->b_cont = mp->b_cont;
8766 			}
8767 			mp->b_cont = NULL;
8768 			return (mp);
8769 		default:
8770 			break;
8771 		}
8772 		prev_mp = mp;
8773 		mp = mp->b_cont;
8774 		if (mp == NULL)
8775 			break;
8776 	}
8777 	return (mp);
8778 }
8779 
8780 /*
8781  * Timer callback routine for keepalive probe.  We do a fake resend of
8782  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8783  * check to see if we have heard anything from the other end for the last
8784  * RTO period.  If we have, set the timer to expire for another
8785  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8786  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8787  * the timeout if we have not heard from the other side.  If for more than
8788  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8789  * kill the connection unless the keepalive abort threshold is 0.  In
8790  * that case, we will probe "forever."
8791  */
8792 static void
8793 tcp_keepalive_killer(void *arg)
8794 {
8795 	mblk_t	*mp;
8796 	conn_t	*connp = (conn_t *)arg;
8797 	tcp_t  	*tcp = connp->conn_tcp;
8798 	int32_t	firetime;
8799 	int32_t	idletime;
8800 	int32_t	ka_intrvl;
8801 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8802 
8803 	tcp->tcp_ka_tid = 0;
8804 
8805 	if (tcp->tcp_fused)
8806 		return;
8807 
8808 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8809 	ka_intrvl = tcp->tcp_ka_interval;
8810 
8811 	/*
8812 	 * Keepalive probe should only be sent if the application has not
8813 	 * done a close on the connection.
8814 	 */
8815 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8816 		return;
8817 	}
8818 	/* Timer fired too early, restart it. */
8819 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8820 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8821 		    MSEC_TO_TICK(ka_intrvl));
8822 		return;
8823 	}
8824 
8825 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8826 	/*
8827 	 * If we have not heard from the other side for a long
8828 	 * time, kill the connection unless the keepalive abort
8829 	 * threshold is 0.  In that case, we will probe "forever."
8830 	 */
8831 	if (tcp->tcp_ka_abort_thres != 0 &&
8832 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8833 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8834 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8835 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8836 		return;
8837 	}
8838 
8839 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8840 	    idletime >= ka_intrvl) {
8841 		/* Fake resend of last ACKed byte. */
8842 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8843 
8844 		if (mp1 != NULL) {
8845 			*mp1->b_wptr++ = '\0';
8846 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8847 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8848 			freeb(mp1);
8849 			/*
8850 			 * if allocation failed, fall through to start the
8851 			 * timer back.
8852 			 */
8853 			if (mp != NULL) {
8854 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8855 				BUMP_MIB(&tcps->tcps_mib,
8856 				    tcpTimKeepaliveProbe);
8857 				if (tcp->tcp_ka_last_intrvl != 0) {
8858 					int max;
8859 					/*
8860 					 * We should probe again at least
8861 					 * in ka_intrvl, but not more than
8862 					 * tcp_rexmit_interval_max.
8863 					 */
8864 					max = tcps->tcps_rexmit_interval_max;
8865 					firetime = MIN(ka_intrvl - 1,
8866 					    tcp->tcp_ka_last_intrvl << 1);
8867 					if (firetime > max)
8868 						firetime = max;
8869 				} else {
8870 					firetime = tcp->tcp_rto;
8871 				}
8872 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8873 				    tcp_keepalive_killer,
8874 				    MSEC_TO_TICK(firetime));
8875 				tcp->tcp_ka_last_intrvl = firetime;
8876 				return;
8877 			}
8878 		}
8879 	} else {
8880 		tcp->tcp_ka_last_intrvl = 0;
8881 	}
8882 
8883 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8884 	if ((firetime = ka_intrvl - idletime) < 0) {
8885 		firetime = ka_intrvl;
8886 	}
8887 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8888 	    MSEC_TO_TICK(firetime));
8889 }
8890 
8891 int
8892 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8893 {
8894 	queue_t	*q = tcp->tcp_rq;
8895 	int32_t	mss = tcp->tcp_mss;
8896 	int	maxpsz;
8897 	conn_t	*connp = tcp->tcp_connp;
8898 
8899 	if (TCP_IS_DETACHED(tcp))
8900 		return (mss);
8901 	if (tcp->tcp_fused) {
8902 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8903 		mss = INFPSZ;
8904 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8905 		/*
8906 		 * Set the sd_qn_maxpsz according to the socket send buffer
8907 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8908 		 * instruct the stream head to copyin user data into contiguous
8909 		 * kernel-allocated buffers without breaking it up into smaller
8910 		 * chunks.  We round up the buffer size to the nearest SMSS.
8911 		 */
8912 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8913 		if (tcp->tcp_kssl_ctx == NULL)
8914 			mss = INFPSZ;
8915 		else
8916 			mss = SSL3_MAX_RECORD_LEN;
8917 	} else {
8918 		/*
8919 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8920 		 * (and a multiple of the mss).  This instructs the stream
8921 		 * head to break down larger than SMSS writes into SMSS-
8922 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8923 		 */
8924 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8925 		maxpsz = tcp->tcp_maxpsz * mss;
8926 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8927 			maxpsz = tcp->tcp_xmit_hiwater/2;
8928 			/* Round up to nearest mss */
8929 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8930 		}
8931 	}
8932 
8933 	(void) proto_set_maxpsz(q, connp, maxpsz);
8934 	if (!(IPCL_IS_NONSTR(connp))) {
8935 		/* XXX do it in set_maxpsz()? */
8936 		tcp->tcp_wq->q_maxpsz = maxpsz;
8937 	}
8938 
8939 	if (set_maxblk)
8940 		(void) proto_set_tx_maxblk(q, connp, mss);
8941 	return (mss);
8942 }
8943 
8944 /*
8945  * Extract option values from a tcp header.  We put any found values into the
8946  * tcpopt struct and return a bitmask saying which options were found.
8947  */
8948 static int
8949 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8950 {
8951 	uchar_t		*endp;
8952 	int		len;
8953 	uint32_t	mss;
8954 	uchar_t		*up = (uchar_t *)tcph;
8955 	int		found = 0;
8956 	int32_t		sack_len;
8957 	tcp_seq		sack_begin, sack_end;
8958 	tcp_t		*tcp;
8959 
8960 	endp = up + TCP_HDR_LENGTH(tcph);
8961 	up += TCP_MIN_HEADER_LENGTH;
8962 	while (up < endp) {
8963 		len = endp - up;
8964 		switch (*up) {
8965 		case TCPOPT_EOL:
8966 			break;
8967 
8968 		case TCPOPT_NOP:
8969 			up++;
8970 			continue;
8971 
8972 		case TCPOPT_MAXSEG:
8973 			if (len < TCPOPT_MAXSEG_LEN ||
8974 			    up[1] != TCPOPT_MAXSEG_LEN)
8975 				break;
8976 
8977 			mss = BE16_TO_U16(up+2);
8978 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
8979 			tcpopt->tcp_opt_mss = mss;
8980 			found |= TCP_OPT_MSS_PRESENT;
8981 
8982 			up += TCPOPT_MAXSEG_LEN;
8983 			continue;
8984 
8985 		case TCPOPT_WSCALE:
8986 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
8987 				break;
8988 
8989 			if (up[2] > TCP_MAX_WINSHIFT)
8990 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
8991 			else
8992 				tcpopt->tcp_opt_wscale = up[2];
8993 			found |= TCP_OPT_WSCALE_PRESENT;
8994 
8995 			up += TCPOPT_WS_LEN;
8996 			continue;
8997 
8998 		case TCPOPT_SACK_PERMITTED:
8999 			if (len < TCPOPT_SACK_OK_LEN ||
9000 			    up[1] != TCPOPT_SACK_OK_LEN)
9001 				break;
9002 			found |= TCP_OPT_SACK_OK_PRESENT;
9003 			up += TCPOPT_SACK_OK_LEN;
9004 			continue;
9005 
9006 		case TCPOPT_SACK:
9007 			if (len <= 2 || up[1] <= 2 || len < up[1])
9008 				break;
9009 
9010 			/* If TCP is not interested in SACK blks... */
9011 			if ((tcp = tcpopt->tcp) == NULL) {
9012 				up += up[1];
9013 				continue;
9014 			}
9015 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9016 			up += TCPOPT_HEADER_LEN;
9017 
9018 			/*
9019 			 * If the list is empty, allocate one and assume
9020 			 * nothing is sack'ed.
9021 			 */
9022 			ASSERT(tcp->tcp_sack_info != NULL);
9023 			if (tcp->tcp_notsack_list == NULL) {
9024 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9025 				    tcp->tcp_suna, tcp->tcp_snxt,
9026 				    &(tcp->tcp_num_notsack_blk),
9027 				    &(tcp->tcp_cnt_notsack_list));
9028 
9029 				/*
9030 				 * Make sure tcp_notsack_list is not NULL.
9031 				 * This happens when kmem_alloc(KM_NOSLEEP)
9032 				 * returns NULL.
9033 				 */
9034 				if (tcp->tcp_notsack_list == NULL) {
9035 					up += sack_len;
9036 					continue;
9037 				}
9038 				tcp->tcp_fack = tcp->tcp_suna;
9039 			}
9040 
9041 			while (sack_len > 0) {
9042 				if (up + 8 > endp) {
9043 					up = endp;
9044 					break;
9045 				}
9046 				sack_begin = BE32_TO_U32(up);
9047 				up += 4;
9048 				sack_end = BE32_TO_U32(up);
9049 				up += 4;
9050 				sack_len -= 8;
9051 				/*
9052 				 * Bounds checking.  Make sure the SACK
9053 				 * info is within tcp_suna and tcp_snxt.
9054 				 * If this SACK blk is out of bound, ignore
9055 				 * it but continue to parse the following
9056 				 * blks.
9057 				 */
9058 				if (SEQ_LEQ(sack_end, sack_begin) ||
9059 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9060 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9061 					continue;
9062 				}
9063 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9064 				    sack_begin, sack_end,
9065 				    &(tcp->tcp_num_notsack_blk),
9066 				    &(tcp->tcp_cnt_notsack_list));
9067 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9068 					tcp->tcp_fack = sack_end;
9069 				}
9070 			}
9071 			found |= TCP_OPT_SACK_PRESENT;
9072 			continue;
9073 
9074 		case TCPOPT_TSTAMP:
9075 			if (len < TCPOPT_TSTAMP_LEN ||
9076 			    up[1] != TCPOPT_TSTAMP_LEN)
9077 				break;
9078 
9079 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9080 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9081 
9082 			found |= TCP_OPT_TSTAMP_PRESENT;
9083 
9084 			up += TCPOPT_TSTAMP_LEN;
9085 			continue;
9086 
9087 		default:
9088 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9089 				break;
9090 			up += up[1];
9091 			continue;
9092 		}
9093 		break;
9094 	}
9095 	return (found);
9096 }
9097 
9098 /*
9099  * Set the mss associated with a particular tcp based on its current value,
9100  * and a new one passed in. Observe minimums and maximums, and reset
9101  * other state variables that we want to view as multiples of mss.
9102  *
9103  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9104  * highwater marks etc. need to be initialized or adjusted.
9105  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9106  *    packet arrives.
9107  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9108  *    ICMP6_PACKET_TOO_BIG arrives.
9109  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9110  *    to increase the MSS to use the extra bytes available.
9111  *
9112  * Callers except tcp_paws_check() ensure that they only reduce mss.
9113  */
9114 static void
9115 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9116 {
9117 	uint32_t	mss_max;
9118 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9119 
9120 	if (tcp->tcp_ipversion == IPV4_VERSION)
9121 		mss_max = tcps->tcps_mss_max_ipv4;
9122 	else
9123 		mss_max = tcps->tcps_mss_max_ipv6;
9124 
9125 	if (mss < tcps->tcps_mss_min)
9126 		mss = tcps->tcps_mss_min;
9127 	if (mss > mss_max)
9128 		mss = mss_max;
9129 	/*
9130 	 * Unless naglim has been set by our client to
9131 	 * a non-mss value, force naglim to track mss.
9132 	 * This can help to aggregate small writes.
9133 	 */
9134 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9135 		tcp->tcp_naglim = mss;
9136 	/*
9137 	 * TCP should be able to buffer at least 4 MSS data for obvious
9138 	 * performance reason.
9139 	 */
9140 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9141 		tcp->tcp_xmit_hiwater = mss << 2;
9142 
9143 	if (do_ss) {
9144 		/*
9145 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9146 		 * changing due to a reduction in MTU, presumably as a
9147 		 * result of a new path component, reset cwnd to its
9148 		 * "initial" value, as a multiple of the new mss.
9149 		 */
9150 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9151 	} else {
9152 		/*
9153 		 * Called by tcp_paws_check(), the mss increased
9154 		 * marginally to allow use of space previously taken
9155 		 * by the timestamp option. It would be inappropriate
9156 		 * to apply slow start or tcp_init_cwnd values to
9157 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9158 		 */
9159 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9160 		tcp->tcp_cwnd_cnt = 0;
9161 	}
9162 	tcp->tcp_mss = mss;
9163 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9164 }
9165 
9166 /* For /dev/tcp aka AF_INET open */
9167 static int
9168 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9169 {
9170 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9171 }
9172 
9173 /* For /dev/tcp6 aka AF_INET6 open */
9174 static int
9175 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9176 {
9177 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9178 }
9179 
9180 static conn_t *
9181 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9182     boolean_t issocket, int *errorp)
9183 {
9184 	tcp_t		*tcp = NULL;
9185 	conn_t		*connp;
9186 	int		err;
9187 	zoneid_t	zoneid;
9188 	tcp_stack_t	*tcps;
9189 	squeue_t	*sqp;
9190 
9191 	ASSERT(errorp != NULL);
9192 	/*
9193 	 * Find the proper zoneid and netstack.
9194 	 */
9195 	/*
9196 	 * Special case for install: miniroot needs to be able to
9197 	 * access files via NFS as though it were always in the
9198 	 * global zone.
9199 	 */
9200 	if (credp == kcred && nfs_global_client_only != 0) {
9201 		zoneid = GLOBAL_ZONEID;
9202 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9203 		    netstack_tcp;
9204 		ASSERT(tcps != NULL);
9205 	} else {
9206 		netstack_t *ns;
9207 
9208 		ns = netstack_find_by_cred(credp);
9209 		ASSERT(ns != NULL);
9210 		tcps = ns->netstack_tcp;
9211 		ASSERT(tcps != NULL);
9212 
9213 		/*
9214 		 * For exclusive stacks we set the zoneid to zero
9215 		 * to make TCP operate as if in the global zone.
9216 		 */
9217 		if (tcps->tcps_netstack->netstack_stackid !=
9218 		    GLOBAL_NETSTACKID)
9219 			zoneid = GLOBAL_ZONEID;
9220 		else
9221 			zoneid = crgetzoneid(credp);
9222 	}
9223 	/*
9224 	 * For stackid zero this is done from strplumb.c, but
9225 	 * non-zero stackids are handled here.
9226 	 */
9227 	if (tcps->tcps_g_q == NULL &&
9228 	    tcps->tcps_netstack->netstack_stackid !=
9229 	    GLOBAL_NETSTACKID) {
9230 		tcp_g_q_setup(tcps);
9231 	}
9232 
9233 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9234 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9235 	/*
9236 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9237 	 * so we drop it by one.
9238 	 */
9239 	netstack_rele(tcps->tcps_netstack);
9240 	if (connp == NULL) {
9241 		*errorp = ENOSR;
9242 		return (NULL);
9243 	}
9244 	connp->conn_sqp = sqp;
9245 	connp->conn_initial_sqp = connp->conn_sqp;
9246 	tcp = connp->conn_tcp;
9247 
9248 	if (isv6) {
9249 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9250 		connp->conn_send = ip_output_v6;
9251 		connp->conn_af_isv6 = B_TRUE;
9252 		connp->conn_pkt_isv6 = B_TRUE;
9253 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9254 		tcp->tcp_ipversion = IPV6_VERSION;
9255 		tcp->tcp_family = AF_INET6;
9256 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9257 	} else {
9258 		connp->conn_flags |= IPCL_TCP4;
9259 		connp->conn_send = ip_output;
9260 		connp->conn_af_isv6 = B_FALSE;
9261 		connp->conn_pkt_isv6 = B_FALSE;
9262 		tcp->tcp_ipversion = IPV4_VERSION;
9263 		tcp->tcp_family = AF_INET;
9264 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9265 	}
9266 
9267 	/*
9268 	 * TCP keeps a copy of cred for cache locality reasons but
9269 	 * we put a reference only once. If connp->conn_cred
9270 	 * becomes invalid, tcp_cred should also be set to NULL.
9271 	 */
9272 	tcp->tcp_cred = connp->conn_cred = credp;
9273 	crhold(connp->conn_cred);
9274 	tcp->tcp_cpid = curproc->p_pid;
9275 	tcp->tcp_open_time = lbolt64;
9276 	connp->conn_zoneid = zoneid;
9277 	connp->conn_mlp_type = mlptSingle;
9278 	connp->conn_ulp_labeled = !is_system_labeled();
9279 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9280 	ASSERT(tcp->tcp_tcps == tcps);
9281 
9282 	/*
9283 	 * If the caller has the process-wide flag set, then default to MAC
9284 	 * exempt mode.  This allows read-down to unlabeled hosts.
9285 	 */
9286 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9287 		connp->conn_mac_exempt = B_TRUE;
9288 
9289 	connp->conn_dev = NULL;
9290 	if (issocket) {
9291 		connp->conn_flags |= IPCL_SOCKET;
9292 		tcp->tcp_issocket = 1;
9293 	}
9294 
9295 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9296 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9297 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9298 
9299 	/* Non-zero default values */
9300 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9301 
9302 	if (q == NULL) {
9303 		/*
9304 		 * Create a helper stream for non-STREAMS socket.
9305 		 */
9306 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9307 		if (err != 0) {
9308 			ip1dbg(("tcp_create: create of IP helper stream "
9309 			    "failed\n"));
9310 			CONN_DEC_REF(connp);
9311 			*errorp = err;
9312 			return (NULL);
9313 		}
9314 		q = connp->conn_rq;
9315 	} else {
9316 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9317 	}
9318 
9319 	SOCK_CONNID_INIT(tcp->tcp_connid);
9320 	err = tcp_init(tcp, q);
9321 	if (err != 0) {
9322 		CONN_DEC_REF(connp);
9323 		*errorp = err;
9324 		return (NULL);
9325 	}
9326 
9327 	return (connp);
9328 }
9329 
9330 static int
9331 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9332     boolean_t isv6)
9333 {
9334 	tcp_t		*tcp = NULL;
9335 	conn_t		*connp = NULL;
9336 	int		err;
9337 	vmem_t		*minor_arena = NULL;
9338 	dev_t		conn_dev;
9339 	boolean_t	issocket;
9340 
9341 	if (q->q_ptr != NULL)
9342 		return (0);
9343 
9344 	if (sflag == MODOPEN)
9345 		return (EINVAL);
9346 
9347 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9348 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9349 		minor_arena = ip_minor_arena_la;
9350 	} else {
9351 		/*
9352 		 * Either minor numbers in the large arena were exhausted
9353 		 * or a non socket application is doing the open.
9354 		 * Try to allocate from the small arena.
9355 		 */
9356 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9357 			return (EBUSY);
9358 		}
9359 		minor_arena = ip_minor_arena_sa;
9360 	}
9361 
9362 	ASSERT(minor_arena != NULL);
9363 
9364 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9365 
9366 	if (flag & SO_FALLBACK) {
9367 		/*
9368 		 * Non streams socket needs a stream to fallback to
9369 		 */
9370 		RD(q)->q_ptr = (void *)conn_dev;
9371 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9372 		WR(q)->q_ptr = (void *)minor_arena;
9373 		qprocson(q);
9374 		return (0);
9375 	} else if (flag & SO_ACCEPTOR) {
9376 		q->q_qinfo = &tcp_acceptor_rinit;
9377 		/*
9378 		 * the conn_dev and minor_arena will be subsequently used by
9379 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9380 		 * minor device number for this connection from the q_ptr.
9381 		 */
9382 		RD(q)->q_ptr = (void *)conn_dev;
9383 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9384 		WR(q)->q_ptr = (void *)minor_arena;
9385 		qprocson(q);
9386 		return (0);
9387 	}
9388 
9389 	issocket = flag & SO_SOCKSTR;
9390 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9391 
9392 	if (connp == NULL) {
9393 		inet_minor_free(minor_arena, conn_dev);
9394 		q->q_ptr = WR(q)->q_ptr = NULL;
9395 		return (err);
9396 	}
9397 
9398 	q->q_ptr = WR(q)->q_ptr = connp;
9399 
9400 	connp->conn_dev = conn_dev;
9401 	connp->conn_minor_arena = minor_arena;
9402 
9403 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9404 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9405 
9406 	if (issocket) {
9407 		WR(q)->q_qinfo = &tcp_sock_winit;
9408 	} else {
9409 		tcp = connp->conn_tcp;
9410 #ifdef  _ILP32
9411 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9412 #else
9413 		tcp->tcp_acceptor_id = conn_dev;
9414 #endif  /* _ILP32 */
9415 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9416 	}
9417 
9418 	/*
9419 	 * Put the ref for TCP. Ref for IP was already put
9420 	 * by ipcl_conn_create. Also Make the conn_t globally
9421 	 * visible to walkers
9422 	 */
9423 	mutex_enter(&connp->conn_lock);
9424 	CONN_INC_REF_LOCKED(connp);
9425 	ASSERT(connp->conn_ref == 2);
9426 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9427 	mutex_exit(&connp->conn_lock);
9428 
9429 	qprocson(q);
9430 	return (0);
9431 }
9432 
9433 /*
9434  * Some TCP options can be "set" by requesting them in the option
9435  * buffer. This is needed for XTI feature test though we do not
9436  * allow it in general. We interpret that this mechanism is more
9437  * applicable to OSI protocols and need not be allowed in general.
9438  * This routine filters out options for which it is not allowed (most)
9439  * and lets through those (few) for which it is. [ The XTI interface
9440  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9441  * ever implemented will have to be allowed here ].
9442  */
9443 static boolean_t
9444 tcp_allow_connopt_set(int level, int name)
9445 {
9446 
9447 	switch (level) {
9448 	case IPPROTO_TCP:
9449 		switch (name) {
9450 		case TCP_NODELAY:
9451 			return (B_TRUE);
9452 		default:
9453 			return (B_FALSE);
9454 		}
9455 		/*NOTREACHED*/
9456 	default:
9457 		return (B_FALSE);
9458 	}
9459 	/*NOTREACHED*/
9460 }
9461 
9462 /*
9463  * this routine gets default values of certain options whose default
9464  * values are maintained by protocol specific code
9465  */
9466 /* ARGSUSED */
9467 int
9468 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9469 {
9470 	int32_t	*i1 = (int32_t *)ptr;
9471 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9472 
9473 	switch (level) {
9474 	case IPPROTO_TCP:
9475 		switch (name) {
9476 		case TCP_NOTIFY_THRESHOLD:
9477 			*i1 = tcps->tcps_ip_notify_interval;
9478 			break;
9479 		case TCP_ABORT_THRESHOLD:
9480 			*i1 = tcps->tcps_ip_abort_interval;
9481 			break;
9482 		case TCP_CONN_NOTIFY_THRESHOLD:
9483 			*i1 = tcps->tcps_ip_notify_cinterval;
9484 			break;
9485 		case TCP_CONN_ABORT_THRESHOLD:
9486 			*i1 = tcps->tcps_ip_abort_cinterval;
9487 			break;
9488 		default:
9489 			return (-1);
9490 		}
9491 		break;
9492 	case IPPROTO_IP:
9493 		switch (name) {
9494 		case IP_TTL:
9495 			*i1 = tcps->tcps_ipv4_ttl;
9496 			break;
9497 		default:
9498 			return (-1);
9499 		}
9500 		break;
9501 	case IPPROTO_IPV6:
9502 		switch (name) {
9503 		case IPV6_UNICAST_HOPS:
9504 			*i1 = tcps->tcps_ipv6_hoplimit;
9505 			break;
9506 		default:
9507 			return (-1);
9508 		}
9509 		break;
9510 	default:
9511 		return (-1);
9512 	}
9513 	return (sizeof (int));
9514 }
9515 
9516 static int
9517 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9518 {
9519 	int		*i1 = (int *)ptr;
9520 	tcp_t		*tcp = connp->conn_tcp;
9521 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9522 
9523 	switch (level) {
9524 	case SOL_SOCKET:
9525 		switch (name) {
9526 		case SO_LINGER:	{
9527 			struct linger *lgr = (struct linger *)ptr;
9528 
9529 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9530 			lgr->l_linger = tcp->tcp_lingertime;
9531 			}
9532 			return (sizeof (struct linger));
9533 		case SO_DEBUG:
9534 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9535 			break;
9536 		case SO_KEEPALIVE:
9537 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9538 			break;
9539 		case SO_DONTROUTE:
9540 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9541 			break;
9542 		case SO_USELOOPBACK:
9543 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9544 			break;
9545 		case SO_BROADCAST:
9546 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9547 			break;
9548 		case SO_REUSEADDR:
9549 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9550 			break;
9551 		case SO_OOBINLINE:
9552 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9553 			break;
9554 		case SO_DGRAM_ERRIND:
9555 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9556 			break;
9557 		case SO_TYPE:
9558 			*i1 = SOCK_STREAM;
9559 			break;
9560 		case SO_SNDBUF:
9561 			*i1 = tcp->tcp_xmit_hiwater;
9562 			break;
9563 		case SO_RCVBUF:
9564 			*i1 = tcp->tcp_recv_hiwater;
9565 			break;
9566 		case SO_SND_COPYAVOID:
9567 			*i1 = tcp->tcp_snd_zcopy_on ?
9568 			    SO_SND_COPYAVOID : 0;
9569 			break;
9570 		case SO_ALLZONES:
9571 			*i1 = connp->conn_allzones ? 1 : 0;
9572 			break;
9573 		case SO_ANON_MLP:
9574 			*i1 = connp->conn_anon_mlp;
9575 			break;
9576 		case SO_MAC_EXEMPT:
9577 			*i1 = connp->conn_mac_exempt;
9578 			break;
9579 		case SO_EXCLBIND:
9580 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9581 			break;
9582 		case SO_PROTOTYPE:
9583 			*i1 = IPPROTO_TCP;
9584 			break;
9585 		case SO_DOMAIN:
9586 			*i1 = tcp->tcp_family;
9587 			break;
9588 		case SO_ACCEPTCONN:
9589 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9590 		default:
9591 			return (-1);
9592 		}
9593 		break;
9594 	case IPPROTO_TCP:
9595 		switch (name) {
9596 		case TCP_NODELAY:
9597 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9598 			break;
9599 		case TCP_MAXSEG:
9600 			*i1 = tcp->tcp_mss;
9601 			break;
9602 		case TCP_NOTIFY_THRESHOLD:
9603 			*i1 = (int)tcp->tcp_first_timer_threshold;
9604 			break;
9605 		case TCP_ABORT_THRESHOLD:
9606 			*i1 = tcp->tcp_second_timer_threshold;
9607 			break;
9608 		case TCP_CONN_NOTIFY_THRESHOLD:
9609 			*i1 = tcp->tcp_first_ctimer_threshold;
9610 			break;
9611 		case TCP_CONN_ABORT_THRESHOLD:
9612 			*i1 = tcp->tcp_second_ctimer_threshold;
9613 			break;
9614 		case TCP_RECVDSTADDR:
9615 			*i1 = tcp->tcp_recvdstaddr;
9616 			break;
9617 		case TCP_ANONPRIVBIND:
9618 			*i1 = tcp->tcp_anon_priv_bind;
9619 			break;
9620 		case TCP_EXCLBIND:
9621 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9622 			break;
9623 		case TCP_INIT_CWND:
9624 			*i1 = tcp->tcp_init_cwnd;
9625 			break;
9626 		case TCP_KEEPALIVE_THRESHOLD:
9627 			*i1 = tcp->tcp_ka_interval;
9628 			break;
9629 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9630 			*i1 = tcp->tcp_ka_abort_thres;
9631 			break;
9632 		case TCP_CORK:
9633 			*i1 = tcp->tcp_cork;
9634 			break;
9635 		default:
9636 			return (-1);
9637 		}
9638 		break;
9639 	case IPPROTO_IP:
9640 		if (tcp->tcp_family != AF_INET)
9641 			return (-1);
9642 		switch (name) {
9643 		case IP_OPTIONS:
9644 		case T_IP_OPTIONS: {
9645 			/*
9646 			 * This is compatible with BSD in that in only return
9647 			 * the reverse source route with the final destination
9648 			 * as the last entry. The first 4 bytes of the option
9649 			 * will contain the final destination.
9650 			 */
9651 			int	opt_len;
9652 
9653 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9654 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9655 			ASSERT(opt_len >= 0);
9656 			/* Caller ensures enough space */
9657 			if (opt_len > 0) {
9658 				/*
9659 				 * TODO: Do we have to handle getsockopt on an
9660 				 * initiator as well?
9661 				 */
9662 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9663 			}
9664 			return (0);
9665 			}
9666 		case IP_TOS:
9667 		case T_IP_TOS:
9668 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9669 			break;
9670 		case IP_TTL:
9671 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9672 			break;
9673 		case IP_NEXTHOP:
9674 			/* Handled at IP level */
9675 			return (-EINVAL);
9676 		default:
9677 			return (-1);
9678 		}
9679 		break;
9680 	case IPPROTO_IPV6:
9681 		/*
9682 		 * IPPROTO_IPV6 options are only supported for sockets
9683 		 * that are using IPv6 on the wire.
9684 		 */
9685 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9686 			return (-1);
9687 		}
9688 		switch (name) {
9689 		case IPV6_UNICAST_HOPS:
9690 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9691 			break;	/* goto sizeof (int) option return */
9692 		case IPV6_BOUND_IF:
9693 			/* Zero if not set */
9694 			*i1 = tcp->tcp_bound_if;
9695 			break;	/* goto sizeof (int) option return */
9696 		case IPV6_RECVPKTINFO:
9697 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9698 				*i1 = 1;
9699 			else
9700 				*i1 = 0;
9701 			break;	/* goto sizeof (int) option return */
9702 		case IPV6_RECVTCLASS:
9703 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9704 				*i1 = 1;
9705 			else
9706 				*i1 = 0;
9707 			break;	/* goto sizeof (int) option return */
9708 		case IPV6_RECVHOPLIMIT:
9709 			if (tcp->tcp_ipv6_recvancillary &
9710 			    TCP_IPV6_RECVHOPLIMIT)
9711 				*i1 = 1;
9712 			else
9713 				*i1 = 0;
9714 			break;	/* goto sizeof (int) option return */
9715 		case IPV6_RECVHOPOPTS:
9716 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9717 				*i1 = 1;
9718 			else
9719 				*i1 = 0;
9720 			break;	/* goto sizeof (int) option return */
9721 		case IPV6_RECVDSTOPTS:
9722 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9723 				*i1 = 1;
9724 			else
9725 				*i1 = 0;
9726 			break;	/* goto sizeof (int) option return */
9727 		case _OLD_IPV6_RECVDSTOPTS:
9728 			if (tcp->tcp_ipv6_recvancillary &
9729 			    TCP_OLD_IPV6_RECVDSTOPTS)
9730 				*i1 = 1;
9731 			else
9732 				*i1 = 0;
9733 			break;	/* goto sizeof (int) option return */
9734 		case IPV6_RECVRTHDR:
9735 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9736 				*i1 = 1;
9737 			else
9738 				*i1 = 0;
9739 			break;	/* goto sizeof (int) option return */
9740 		case IPV6_RECVRTHDRDSTOPTS:
9741 			if (tcp->tcp_ipv6_recvancillary &
9742 			    TCP_IPV6_RECVRTDSTOPTS)
9743 				*i1 = 1;
9744 			else
9745 				*i1 = 0;
9746 			break;	/* goto sizeof (int) option return */
9747 		case IPV6_PKTINFO: {
9748 			/* XXX assumes that caller has room for max size! */
9749 			struct in6_pktinfo *pkti;
9750 
9751 			pkti = (struct in6_pktinfo *)ptr;
9752 			if (ipp->ipp_fields & IPPF_IFINDEX)
9753 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9754 			else
9755 				pkti->ipi6_ifindex = 0;
9756 			if (ipp->ipp_fields & IPPF_ADDR)
9757 				pkti->ipi6_addr = ipp->ipp_addr;
9758 			else
9759 				pkti->ipi6_addr = ipv6_all_zeros;
9760 			return (sizeof (struct in6_pktinfo));
9761 		}
9762 		case IPV6_TCLASS:
9763 			if (ipp->ipp_fields & IPPF_TCLASS)
9764 				*i1 = ipp->ipp_tclass;
9765 			else
9766 				*i1 = IPV6_FLOW_TCLASS(
9767 				    IPV6_DEFAULT_VERS_AND_FLOW);
9768 			break;	/* goto sizeof (int) option return */
9769 		case IPV6_NEXTHOP: {
9770 			sin6_t *sin6 = (sin6_t *)ptr;
9771 
9772 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9773 				return (0);
9774 			*sin6 = sin6_null;
9775 			sin6->sin6_family = AF_INET6;
9776 			sin6->sin6_addr = ipp->ipp_nexthop;
9777 			return (sizeof (sin6_t));
9778 		}
9779 		case IPV6_HOPOPTS:
9780 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9781 				return (0);
9782 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9783 				return (0);
9784 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9785 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9786 			if (tcp->tcp_label_len > 0) {
9787 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9788 				ptr[1] = (ipp->ipp_hopoptslen -
9789 				    tcp->tcp_label_len + 7) / 8 - 1;
9790 			}
9791 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9792 		case IPV6_RTHDRDSTOPTS:
9793 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9794 				return (0);
9795 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9796 			return (ipp->ipp_rtdstoptslen);
9797 		case IPV6_RTHDR:
9798 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9799 				return (0);
9800 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9801 			return (ipp->ipp_rthdrlen);
9802 		case IPV6_DSTOPTS:
9803 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9804 				return (0);
9805 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9806 			return (ipp->ipp_dstoptslen);
9807 		case IPV6_SRC_PREFERENCES:
9808 			return (ip6_get_src_preferences(connp,
9809 			    (uint32_t *)ptr));
9810 		case IPV6_PATHMTU: {
9811 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9812 
9813 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9814 				return (-1);
9815 
9816 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9817 			    connp->conn_fport, mtuinfo,
9818 			    connp->conn_netstack));
9819 		}
9820 		default:
9821 			return (-1);
9822 		}
9823 		break;
9824 	default:
9825 		return (-1);
9826 	}
9827 	return (sizeof (int));
9828 }
9829 
9830 /*
9831  * TCP routine to get the values of options.
9832  */
9833 int
9834 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9835 {
9836 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9837 }
9838 
9839 /* returns UNIX error, the optlen is a value-result arg */
9840 int
9841 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9842     void *optvalp, socklen_t *optlen, cred_t *cr)
9843 {
9844 	conn_t		*connp = (conn_t *)proto_handle;
9845 	squeue_t	*sqp = connp->conn_sqp;
9846 	int		error;
9847 	t_uscalar_t	max_optbuf_len;
9848 	void		*optvalp_buf;
9849 	int		len;
9850 
9851 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9852 	    tcp_opt_obj.odb_opt_des_arr,
9853 	    tcp_opt_obj.odb_opt_arr_cnt,
9854 	    tcp_opt_obj.odb_topmost_tpiprovider,
9855 	    B_FALSE, B_TRUE, cr);
9856 	if (error != 0) {
9857 		if (error < 0) {
9858 			error = proto_tlitosyserr(-error);
9859 		}
9860 		return (error);
9861 	}
9862 
9863 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9864 
9865 	error = squeue_synch_enter(sqp, connp, 0);
9866 	if (error == ENOMEM) {
9867 		return (ENOMEM);
9868 	}
9869 
9870 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9871 	squeue_synch_exit(sqp, connp);
9872 
9873 	if (len < 0) {
9874 		/*
9875 		 * Pass on to IP
9876 		 */
9877 		kmem_free(optvalp_buf, max_optbuf_len);
9878 		return (ip_get_options(connp, level, option_name,
9879 		    optvalp, optlen, cr));
9880 	} else {
9881 		/*
9882 		 * update optlen and copy option value
9883 		 */
9884 		t_uscalar_t size = MIN(len, *optlen);
9885 		bcopy(optvalp_buf, optvalp, size);
9886 		bcopy(&size, optlen, sizeof (size));
9887 
9888 		kmem_free(optvalp_buf, max_optbuf_len);
9889 		return (0);
9890 	}
9891 }
9892 
9893 /*
9894  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9895  * Parameters are assumed to be verified by the caller.
9896  */
9897 /* ARGSUSED */
9898 int
9899 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9900     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9901     void *thisdg_attrs, cred_t *cr)
9902 {
9903 	tcp_t	*tcp = connp->conn_tcp;
9904 	int	*i1 = (int *)invalp;
9905 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9906 	boolean_t checkonly;
9907 	int	reterr;
9908 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9909 
9910 	switch (optset_context) {
9911 	case SETFN_OPTCOM_CHECKONLY:
9912 		checkonly = B_TRUE;
9913 		/*
9914 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9915 		 * inlen != 0 implies value supplied and
9916 		 * 	we have to "pretend" to set it.
9917 		 * inlen == 0 implies that there is no
9918 		 * 	value part in T_CHECK request and just validation
9919 		 * done elsewhere should be enough, we just return here.
9920 		 */
9921 		if (inlen == 0) {
9922 			*outlenp = 0;
9923 			return (0);
9924 		}
9925 		break;
9926 	case SETFN_OPTCOM_NEGOTIATE:
9927 		checkonly = B_FALSE;
9928 		break;
9929 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9930 	case SETFN_CONN_NEGOTIATE:
9931 		checkonly = B_FALSE;
9932 		/*
9933 		 * Negotiating local and "association-related" options
9934 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9935 		 * primitives is allowed by XTI, but we choose
9936 		 * to not implement this style negotiation for Internet
9937 		 * protocols (We interpret it is a must for OSI world but
9938 		 * optional for Internet protocols) for all options.
9939 		 * [ Will do only for the few options that enable test
9940 		 * suites that our XTI implementation of this feature
9941 		 * works for transports that do allow it ]
9942 		 */
9943 		if (!tcp_allow_connopt_set(level, name)) {
9944 			*outlenp = 0;
9945 			return (EINVAL);
9946 		}
9947 		break;
9948 	default:
9949 		/*
9950 		 * We should never get here
9951 		 */
9952 		*outlenp = 0;
9953 		return (EINVAL);
9954 	}
9955 
9956 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9957 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9958 
9959 	/*
9960 	 * For TCP, we should have no ancillary data sent down
9961 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
9962 	 * has to be zero.
9963 	 */
9964 	ASSERT(thisdg_attrs == NULL);
9965 
9966 	/*
9967 	 * For fixed length options, no sanity check
9968 	 * of passed in length is done. It is assumed *_optcom_req()
9969 	 * routines do the right thing.
9970 	 */
9971 	switch (level) {
9972 	case SOL_SOCKET:
9973 		switch (name) {
9974 		case SO_LINGER: {
9975 			struct linger *lgr = (struct linger *)invalp;
9976 
9977 			if (!checkonly) {
9978 				if (lgr->l_onoff) {
9979 					tcp->tcp_linger = 1;
9980 					tcp->tcp_lingertime = lgr->l_linger;
9981 				} else {
9982 					tcp->tcp_linger = 0;
9983 					tcp->tcp_lingertime = 0;
9984 				}
9985 				/* struct copy */
9986 				*(struct linger *)outvalp = *lgr;
9987 			} else {
9988 				if (!lgr->l_onoff) {
9989 					((struct linger *)
9990 					    outvalp)->l_onoff = 0;
9991 					((struct linger *)
9992 					    outvalp)->l_linger = 0;
9993 				} else {
9994 					/* struct copy */
9995 					*(struct linger *)outvalp = *lgr;
9996 				}
9997 			}
9998 			*outlenp = sizeof (struct linger);
9999 			return (0);
10000 		}
10001 		case SO_DEBUG:
10002 			if (!checkonly)
10003 				tcp->tcp_debug = onoff;
10004 			break;
10005 		case SO_KEEPALIVE:
10006 			if (checkonly) {
10007 				/* check only case */
10008 				break;
10009 			}
10010 
10011 			if (!onoff) {
10012 				if (tcp->tcp_ka_enabled) {
10013 					if (tcp->tcp_ka_tid != 0) {
10014 						(void) TCP_TIMER_CANCEL(tcp,
10015 						    tcp->tcp_ka_tid);
10016 						tcp->tcp_ka_tid = 0;
10017 					}
10018 					tcp->tcp_ka_enabled = 0;
10019 				}
10020 				break;
10021 			}
10022 			if (!tcp->tcp_ka_enabled) {
10023 				/* Crank up the keepalive timer */
10024 				tcp->tcp_ka_last_intrvl = 0;
10025 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10026 				    tcp_keepalive_killer,
10027 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10028 				tcp->tcp_ka_enabled = 1;
10029 			}
10030 			break;
10031 		case SO_DONTROUTE:
10032 			/*
10033 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10034 			 * only of interest to IP.  We track them here only so
10035 			 * that we can report their current value.
10036 			 */
10037 			if (!checkonly) {
10038 				tcp->tcp_dontroute = onoff;
10039 				tcp->tcp_connp->conn_dontroute = onoff;
10040 			}
10041 			break;
10042 		case SO_USELOOPBACK:
10043 			if (!checkonly) {
10044 				tcp->tcp_useloopback = onoff;
10045 				tcp->tcp_connp->conn_loopback = onoff;
10046 			}
10047 			break;
10048 		case SO_BROADCAST:
10049 			if (!checkonly) {
10050 				tcp->tcp_broadcast = onoff;
10051 				tcp->tcp_connp->conn_broadcast = onoff;
10052 			}
10053 			break;
10054 		case SO_REUSEADDR:
10055 			if (!checkonly) {
10056 				tcp->tcp_reuseaddr = onoff;
10057 				tcp->tcp_connp->conn_reuseaddr = onoff;
10058 			}
10059 			break;
10060 		case SO_OOBINLINE:
10061 			if (!checkonly) {
10062 				tcp->tcp_oobinline = onoff;
10063 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10064 					proto_set_rx_oob_opt(connp, onoff);
10065 			}
10066 			break;
10067 		case SO_DGRAM_ERRIND:
10068 			if (!checkonly)
10069 				tcp->tcp_dgram_errind = onoff;
10070 			break;
10071 		case SO_SNDBUF: {
10072 			if (*i1 > tcps->tcps_max_buf) {
10073 				*outlenp = 0;
10074 				return (ENOBUFS);
10075 			}
10076 			if (checkonly)
10077 				break;
10078 
10079 			tcp->tcp_xmit_hiwater = *i1;
10080 			if (tcps->tcps_snd_lowat_fraction != 0)
10081 				tcp->tcp_xmit_lowater =
10082 				    tcp->tcp_xmit_hiwater /
10083 				    tcps->tcps_snd_lowat_fraction;
10084 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10085 			/*
10086 			 * If we are flow-controlled, recheck the condition.
10087 			 * There are apps that increase SO_SNDBUF size when
10088 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10089 			 * control condition to be lifted right away.
10090 			 */
10091 			mutex_enter(&tcp->tcp_non_sq_lock);
10092 			if (tcp->tcp_flow_stopped &&
10093 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10094 				tcp_clrqfull(tcp);
10095 			}
10096 			mutex_exit(&tcp->tcp_non_sq_lock);
10097 			break;
10098 		}
10099 		case SO_RCVBUF:
10100 			if (*i1 > tcps->tcps_max_buf) {
10101 				*outlenp = 0;
10102 				return (ENOBUFS);
10103 			}
10104 			/* Silently ignore zero */
10105 			if (!checkonly && *i1 != 0) {
10106 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10107 				(void) tcp_rwnd_set(tcp, *i1);
10108 			}
10109 			/*
10110 			 * XXX should we return the rwnd here
10111 			 * and tcp_opt_get ?
10112 			 */
10113 			break;
10114 		case SO_SND_COPYAVOID:
10115 			if (!checkonly) {
10116 				/* we only allow enable at most once for now */
10117 				if (tcp->tcp_loopback ||
10118 				    (tcp->tcp_kssl_ctx != NULL) ||
10119 				    (!tcp->tcp_snd_zcopy_aware &&
10120 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10121 					*outlenp = 0;
10122 					return (EOPNOTSUPP);
10123 				}
10124 				tcp->tcp_snd_zcopy_aware = 1;
10125 			}
10126 			break;
10127 		case SO_ALLZONES:
10128 			/* Pass option along to IP level for handling */
10129 			return (-EINVAL);
10130 		case SO_ANON_MLP:
10131 			/* Pass option along to IP level for handling */
10132 			return (-EINVAL);
10133 		case SO_MAC_EXEMPT:
10134 			/* Pass option along to IP level for handling */
10135 			return (-EINVAL);
10136 		case SO_EXCLBIND:
10137 			if (!checkonly)
10138 				tcp->tcp_exclbind = onoff;
10139 			break;
10140 		default:
10141 			*outlenp = 0;
10142 			return (EINVAL);
10143 		}
10144 		break;
10145 	case IPPROTO_TCP:
10146 		switch (name) {
10147 		case TCP_NODELAY:
10148 			if (!checkonly)
10149 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10150 			break;
10151 		case TCP_NOTIFY_THRESHOLD:
10152 			if (!checkonly)
10153 				tcp->tcp_first_timer_threshold = *i1;
10154 			break;
10155 		case TCP_ABORT_THRESHOLD:
10156 			if (!checkonly)
10157 				tcp->tcp_second_timer_threshold = *i1;
10158 			break;
10159 		case TCP_CONN_NOTIFY_THRESHOLD:
10160 			if (!checkonly)
10161 				tcp->tcp_first_ctimer_threshold = *i1;
10162 			break;
10163 		case TCP_CONN_ABORT_THRESHOLD:
10164 			if (!checkonly)
10165 				tcp->tcp_second_ctimer_threshold = *i1;
10166 			break;
10167 		case TCP_RECVDSTADDR:
10168 			if (tcp->tcp_state > TCPS_LISTEN)
10169 				return (EOPNOTSUPP);
10170 			if (!checkonly)
10171 				tcp->tcp_recvdstaddr = onoff;
10172 			break;
10173 		case TCP_ANONPRIVBIND:
10174 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10175 			    IPPROTO_TCP)) != 0) {
10176 				*outlenp = 0;
10177 				return (reterr);
10178 			}
10179 			if (!checkonly) {
10180 				tcp->tcp_anon_priv_bind = onoff;
10181 			}
10182 			break;
10183 		case TCP_EXCLBIND:
10184 			if (!checkonly)
10185 				tcp->tcp_exclbind = onoff;
10186 			break;	/* goto sizeof (int) option return */
10187 		case TCP_INIT_CWND: {
10188 			uint32_t init_cwnd = *((uint32_t *)invalp);
10189 
10190 			if (checkonly)
10191 				break;
10192 
10193 			/*
10194 			 * Only allow socket with network configuration
10195 			 * privilege to set the initial cwnd to be larger
10196 			 * than allowed by RFC 3390.
10197 			 */
10198 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10199 				tcp->tcp_init_cwnd = init_cwnd;
10200 				break;
10201 			}
10202 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10203 				*outlenp = 0;
10204 				return (reterr);
10205 			}
10206 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10207 				*outlenp = 0;
10208 				return (EINVAL);
10209 			}
10210 			tcp->tcp_init_cwnd = init_cwnd;
10211 			break;
10212 		}
10213 		case TCP_KEEPALIVE_THRESHOLD:
10214 			if (checkonly)
10215 				break;
10216 
10217 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10218 			    *i1 > tcps->tcps_keepalive_interval_high) {
10219 				*outlenp = 0;
10220 				return (EINVAL);
10221 			}
10222 			if (*i1 != tcp->tcp_ka_interval) {
10223 				tcp->tcp_ka_interval = *i1;
10224 				/*
10225 				 * Check if we need to restart the
10226 				 * keepalive timer.
10227 				 */
10228 				if (tcp->tcp_ka_tid != 0) {
10229 					ASSERT(tcp->tcp_ka_enabled);
10230 					(void) TCP_TIMER_CANCEL(tcp,
10231 					    tcp->tcp_ka_tid);
10232 					tcp->tcp_ka_last_intrvl = 0;
10233 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10234 					    tcp_keepalive_killer,
10235 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10236 				}
10237 			}
10238 			break;
10239 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10240 			if (!checkonly) {
10241 				if (*i1 <
10242 				    tcps->tcps_keepalive_abort_interval_low ||
10243 				    *i1 >
10244 				    tcps->tcps_keepalive_abort_interval_high) {
10245 					*outlenp = 0;
10246 					return (EINVAL);
10247 				}
10248 				tcp->tcp_ka_abort_thres = *i1;
10249 			}
10250 			break;
10251 		case TCP_CORK:
10252 			if (!checkonly) {
10253 				/*
10254 				 * if tcp->tcp_cork was set and is now
10255 				 * being unset, we have to make sure that
10256 				 * the remaining data gets sent out. Also
10257 				 * unset tcp->tcp_cork so that tcp_wput_data()
10258 				 * can send data even if it is less than mss
10259 				 */
10260 				if (tcp->tcp_cork && onoff == 0 &&
10261 				    tcp->tcp_unsent > 0) {
10262 					tcp->tcp_cork = B_FALSE;
10263 					tcp_wput_data(tcp, NULL, B_FALSE);
10264 				}
10265 				tcp->tcp_cork = onoff;
10266 			}
10267 			break;
10268 		default:
10269 			*outlenp = 0;
10270 			return (EINVAL);
10271 		}
10272 		break;
10273 	case IPPROTO_IP:
10274 		if (tcp->tcp_family != AF_INET) {
10275 			*outlenp = 0;
10276 			return (ENOPROTOOPT);
10277 		}
10278 		switch (name) {
10279 		case IP_OPTIONS:
10280 		case T_IP_OPTIONS:
10281 			reterr = tcp_opt_set_header(tcp, checkonly,
10282 			    invalp, inlen);
10283 			if (reterr) {
10284 				*outlenp = 0;
10285 				return (reterr);
10286 			}
10287 			/* OK return - copy input buffer into output buffer */
10288 			if (invalp != outvalp) {
10289 				/* don't trust bcopy for identical src/dst */
10290 				bcopy(invalp, outvalp, inlen);
10291 			}
10292 			*outlenp = inlen;
10293 			return (0);
10294 		case IP_TOS:
10295 		case T_IP_TOS:
10296 			if (!checkonly) {
10297 				tcp->tcp_ipha->ipha_type_of_service =
10298 				    (uchar_t)*i1;
10299 				tcp->tcp_tos = (uchar_t)*i1;
10300 			}
10301 			break;
10302 		case IP_TTL:
10303 			if (!checkonly) {
10304 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10305 				tcp->tcp_ttl = (uchar_t)*i1;
10306 			}
10307 			break;
10308 		case IP_BOUND_IF:
10309 		case IP_NEXTHOP:
10310 			/* Handled at the IP level */
10311 			return (-EINVAL);
10312 		case IP_SEC_OPT:
10313 			/*
10314 			 * We should not allow policy setting after
10315 			 * we start listening for connections.
10316 			 */
10317 			if (tcp->tcp_state == TCPS_LISTEN) {
10318 				return (EINVAL);
10319 			} else {
10320 				/* Handled at the IP level */
10321 				return (-EINVAL);
10322 			}
10323 		default:
10324 			*outlenp = 0;
10325 			return (EINVAL);
10326 		}
10327 		break;
10328 	case IPPROTO_IPV6: {
10329 		ip6_pkt_t		*ipp;
10330 
10331 		/*
10332 		 * IPPROTO_IPV6 options are only supported for sockets
10333 		 * that are using IPv6 on the wire.
10334 		 */
10335 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10336 			*outlenp = 0;
10337 			return (ENOPROTOOPT);
10338 		}
10339 		/*
10340 		 * Only sticky options; no ancillary data
10341 		 */
10342 		ipp = &tcp->tcp_sticky_ipp;
10343 
10344 		switch (name) {
10345 		case IPV6_UNICAST_HOPS:
10346 			/* -1 means use default */
10347 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10348 				*outlenp = 0;
10349 				return (EINVAL);
10350 			}
10351 			if (!checkonly) {
10352 				if (*i1 == -1) {
10353 					tcp->tcp_ip6h->ip6_hops =
10354 					    ipp->ipp_unicast_hops =
10355 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10356 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10357 					/* Pass modified value to IP. */
10358 					*i1 = tcp->tcp_ip6h->ip6_hops;
10359 				} else {
10360 					tcp->tcp_ip6h->ip6_hops =
10361 					    ipp->ipp_unicast_hops =
10362 					    (uint8_t)*i1;
10363 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10364 				}
10365 				reterr = tcp_build_hdrs(tcp);
10366 				if (reterr != 0)
10367 					return (reterr);
10368 			}
10369 			break;
10370 		case IPV6_BOUND_IF:
10371 			if (!checkonly) {
10372 				tcp->tcp_bound_if = *i1;
10373 				PASS_OPT_TO_IP(connp);
10374 			}
10375 			break;
10376 		/*
10377 		 * Set boolean switches for ancillary data delivery
10378 		 */
10379 		case IPV6_RECVPKTINFO:
10380 			if (!checkonly) {
10381 				if (onoff)
10382 					tcp->tcp_ipv6_recvancillary |=
10383 					    TCP_IPV6_RECVPKTINFO;
10384 				else
10385 					tcp->tcp_ipv6_recvancillary &=
10386 					    ~TCP_IPV6_RECVPKTINFO;
10387 				/* Force it to be sent up with the next msg */
10388 				tcp->tcp_recvifindex = 0;
10389 				PASS_OPT_TO_IP(connp);
10390 			}
10391 			break;
10392 		case IPV6_RECVTCLASS:
10393 			if (!checkonly) {
10394 				if (onoff)
10395 					tcp->tcp_ipv6_recvancillary |=
10396 					    TCP_IPV6_RECVTCLASS;
10397 				else
10398 					tcp->tcp_ipv6_recvancillary &=
10399 					    ~TCP_IPV6_RECVTCLASS;
10400 				PASS_OPT_TO_IP(connp);
10401 			}
10402 			break;
10403 		case IPV6_RECVHOPLIMIT:
10404 			if (!checkonly) {
10405 				if (onoff)
10406 					tcp->tcp_ipv6_recvancillary |=
10407 					    TCP_IPV6_RECVHOPLIMIT;
10408 				else
10409 					tcp->tcp_ipv6_recvancillary &=
10410 					    ~TCP_IPV6_RECVHOPLIMIT;
10411 				/* Force it to be sent up with the next msg */
10412 				tcp->tcp_recvhops = 0xffffffffU;
10413 				PASS_OPT_TO_IP(connp);
10414 			}
10415 			break;
10416 		case IPV6_RECVHOPOPTS:
10417 			if (!checkonly) {
10418 				if (onoff)
10419 					tcp->tcp_ipv6_recvancillary |=
10420 					    TCP_IPV6_RECVHOPOPTS;
10421 				else
10422 					tcp->tcp_ipv6_recvancillary &=
10423 					    ~TCP_IPV6_RECVHOPOPTS;
10424 				PASS_OPT_TO_IP(connp);
10425 			}
10426 			break;
10427 		case IPV6_RECVDSTOPTS:
10428 			if (!checkonly) {
10429 				if (onoff)
10430 					tcp->tcp_ipv6_recvancillary |=
10431 					    TCP_IPV6_RECVDSTOPTS;
10432 				else
10433 					tcp->tcp_ipv6_recvancillary &=
10434 					    ~TCP_IPV6_RECVDSTOPTS;
10435 				PASS_OPT_TO_IP(connp);
10436 			}
10437 			break;
10438 		case _OLD_IPV6_RECVDSTOPTS:
10439 			if (!checkonly) {
10440 				if (onoff)
10441 					tcp->tcp_ipv6_recvancillary |=
10442 					    TCP_OLD_IPV6_RECVDSTOPTS;
10443 				else
10444 					tcp->tcp_ipv6_recvancillary &=
10445 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10446 			}
10447 			break;
10448 		case IPV6_RECVRTHDR:
10449 			if (!checkonly) {
10450 				if (onoff)
10451 					tcp->tcp_ipv6_recvancillary |=
10452 					    TCP_IPV6_RECVRTHDR;
10453 				else
10454 					tcp->tcp_ipv6_recvancillary &=
10455 					    ~TCP_IPV6_RECVRTHDR;
10456 				PASS_OPT_TO_IP(connp);
10457 			}
10458 			break;
10459 		case IPV6_RECVRTHDRDSTOPTS:
10460 			if (!checkonly) {
10461 				if (onoff)
10462 					tcp->tcp_ipv6_recvancillary |=
10463 					    TCP_IPV6_RECVRTDSTOPTS;
10464 				else
10465 					tcp->tcp_ipv6_recvancillary &=
10466 					    ~TCP_IPV6_RECVRTDSTOPTS;
10467 				PASS_OPT_TO_IP(connp);
10468 			}
10469 			break;
10470 		case IPV6_PKTINFO:
10471 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10472 				return (EINVAL);
10473 			if (checkonly)
10474 				break;
10475 
10476 			if (inlen == 0) {
10477 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10478 			} else {
10479 				struct in6_pktinfo *pkti;
10480 
10481 				pkti = (struct in6_pktinfo *)invalp;
10482 				/*
10483 				 * RFC 3542 states that ipi6_addr must be
10484 				 * the unspecified address when setting the
10485 				 * IPV6_PKTINFO sticky socket option on a
10486 				 * TCP socket.
10487 				 */
10488 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10489 					return (EINVAL);
10490 				/*
10491 				 * IP will validate the source address and
10492 				 * interface index.
10493 				 */
10494 				reterr = ip_set_options(tcp->tcp_connp, level,
10495 				    name, invalp, inlen, cr);
10496 				if (reterr != 0)
10497 					return (reterr);
10498 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10499 				ipp->ipp_addr = pkti->ipi6_addr;
10500 				if (ipp->ipp_ifindex != 0)
10501 					ipp->ipp_fields |= IPPF_IFINDEX;
10502 				else
10503 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10504 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10505 					ipp->ipp_fields |= IPPF_ADDR;
10506 				else
10507 					ipp->ipp_fields &= ~IPPF_ADDR;
10508 			}
10509 			reterr = tcp_build_hdrs(tcp);
10510 			if (reterr != 0)
10511 				return (reterr);
10512 			PASS_OPT_TO_IP(connp);
10513 			break;
10514 		case IPV6_TCLASS:
10515 			if (inlen != 0 && inlen != sizeof (int))
10516 				return (EINVAL);
10517 			if (checkonly)
10518 				break;
10519 
10520 			if (inlen == 0) {
10521 				ipp->ipp_fields &= ~IPPF_TCLASS;
10522 			} else {
10523 				if (*i1 > 255 || *i1 < -1)
10524 					return (EINVAL);
10525 				if (*i1 == -1) {
10526 					ipp->ipp_tclass = 0;
10527 					*i1 = 0;
10528 				} else {
10529 					ipp->ipp_tclass = *i1;
10530 				}
10531 				ipp->ipp_fields |= IPPF_TCLASS;
10532 			}
10533 			reterr = tcp_build_hdrs(tcp);
10534 			if (reterr != 0)
10535 				return (reterr);
10536 			break;
10537 		case IPV6_NEXTHOP:
10538 			/*
10539 			 * IP will verify that the nexthop is reachable
10540 			 * and fail for sticky options.
10541 			 */
10542 			if (inlen != 0 && inlen != sizeof (sin6_t))
10543 				return (EINVAL);
10544 			if (checkonly)
10545 				break;
10546 
10547 			if (inlen == 0) {
10548 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10549 			} else {
10550 				sin6_t *sin6 = (sin6_t *)invalp;
10551 
10552 				if (sin6->sin6_family != AF_INET6)
10553 					return (EAFNOSUPPORT);
10554 				if (IN6_IS_ADDR_V4MAPPED(
10555 				    &sin6->sin6_addr))
10556 					return (EADDRNOTAVAIL);
10557 				ipp->ipp_nexthop = sin6->sin6_addr;
10558 				if (!IN6_IS_ADDR_UNSPECIFIED(
10559 				    &ipp->ipp_nexthop))
10560 					ipp->ipp_fields |= IPPF_NEXTHOP;
10561 				else
10562 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10563 			}
10564 			reterr = tcp_build_hdrs(tcp);
10565 			if (reterr != 0)
10566 				return (reterr);
10567 			PASS_OPT_TO_IP(connp);
10568 			break;
10569 		case IPV6_HOPOPTS: {
10570 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10571 
10572 			/*
10573 			 * Sanity checks - minimum size, size a multiple of
10574 			 * eight bytes, and matching size passed in.
10575 			 */
10576 			if (inlen != 0 &&
10577 			    inlen != (8 * (hopts->ip6h_len + 1)))
10578 				return (EINVAL);
10579 
10580 			if (checkonly)
10581 				break;
10582 
10583 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10584 			    (uchar_t **)&ipp->ipp_hopopts,
10585 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10586 			if (reterr != 0)
10587 				return (reterr);
10588 			if (ipp->ipp_hopoptslen == 0)
10589 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10590 			else
10591 				ipp->ipp_fields |= IPPF_HOPOPTS;
10592 			reterr = tcp_build_hdrs(tcp);
10593 			if (reterr != 0)
10594 				return (reterr);
10595 			break;
10596 		}
10597 		case IPV6_RTHDRDSTOPTS: {
10598 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10599 
10600 			/*
10601 			 * Sanity checks - minimum size, size a multiple of
10602 			 * eight bytes, and matching size passed in.
10603 			 */
10604 			if (inlen != 0 &&
10605 			    inlen != (8 * (dopts->ip6d_len + 1)))
10606 				return (EINVAL);
10607 
10608 			if (checkonly)
10609 				break;
10610 
10611 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10612 			    (uchar_t **)&ipp->ipp_rtdstopts,
10613 			    &ipp->ipp_rtdstoptslen, 0);
10614 			if (reterr != 0)
10615 				return (reterr);
10616 			if (ipp->ipp_rtdstoptslen == 0)
10617 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10618 			else
10619 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10620 			reterr = tcp_build_hdrs(tcp);
10621 			if (reterr != 0)
10622 				return (reterr);
10623 			break;
10624 		}
10625 		case IPV6_DSTOPTS: {
10626 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10627 
10628 			/*
10629 			 * Sanity checks - minimum size, size a multiple of
10630 			 * eight bytes, and matching size passed in.
10631 			 */
10632 			if (inlen != 0 &&
10633 			    inlen != (8 * (dopts->ip6d_len + 1)))
10634 				return (EINVAL);
10635 
10636 			if (checkonly)
10637 				break;
10638 
10639 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10640 			    (uchar_t **)&ipp->ipp_dstopts,
10641 			    &ipp->ipp_dstoptslen, 0);
10642 			if (reterr != 0)
10643 				return (reterr);
10644 			if (ipp->ipp_dstoptslen == 0)
10645 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10646 			else
10647 				ipp->ipp_fields |= IPPF_DSTOPTS;
10648 			reterr = tcp_build_hdrs(tcp);
10649 			if (reterr != 0)
10650 				return (reterr);
10651 			break;
10652 		}
10653 		case IPV6_RTHDR: {
10654 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10655 
10656 			/*
10657 			 * Sanity checks - minimum size, size a multiple of
10658 			 * eight bytes, and matching size passed in.
10659 			 */
10660 			if (inlen != 0 &&
10661 			    inlen != (8 * (rt->ip6r_len + 1)))
10662 				return (EINVAL);
10663 
10664 			if (checkonly)
10665 				break;
10666 
10667 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10668 			    (uchar_t **)&ipp->ipp_rthdr,
10669 			    &ipp->ipp_rthdrlen, 0);
10670 			if (reterr != 0)
10671 				return (reterr);
10672 			if (ipp->ipp_rthdrlen == 0)
10673 				ipp->ipp_fields &= ~IPPF_RTHDR;
10674 			else
10675 				ipp->ipp_fields |= IPPF_RTHDR;
10676 			reterr = tcp_build_hdrs(tcp);
10677 			if (reterr != 0)
10678 				return (reterr);
10679 			break;
10680 		}
10681 		case IPV6_V6ONLY:
10682 			if (!checkonly) {
10683 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10684 			}
10685 			break;
10686 		case IPV6_USE_MIN_MTU:
10687 			if (inlen != sizeof (int))
10688 				return (EINVAL);
10689 
10690 			if (*i1 < -1 || *i1 > 1)
10691 				return (EINVAL);
10692 
10693 			if (checkonly)
10694 				break;
10695 
10696 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10697 			ipp->ipp_use_min_mtu = *i1;
10698 			break;
10699 		case IPV6_BOUND_PIF:
10700 			/* Handled at the IP level */
10701 			return (-EINVAL);
10702 		case IPV6_SEC_OPT:
10703 			/*
10704 			 * We should not allow policy setting after
10705 			 * we start listening for connections.
10706 			 */
10707 			if (tcp->tcp_state == TCPS_LISTEN) {
10708 				return (EINVAL);
10709 			} else {
10710 				/* Handled at the IP level */
10711 				return (-EINVAL);
10712 			}
10713 		case IPV6_SRC_PREFERENCES:
10714 			if (inlen != sizeof (uint32_t))
10715 				return (EINVAL);
10716 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10717 			    *(uint32_t *)invalp);
10718 			if (reterr != 0) {
10719 				*outlenp = 0;
10720 				return (reterr);
10721 			}
10722 			break;
10723 		default:
10724 			*outlenp = 0;
10725 			return (EINVAL);
10726 		}
10727 		break;
10728 	}		/* end IPPROTO_IPV6 */
10729 	default:
10730 		*outlenp = 0;
10731 		return (EINVAL);
10732 	}
10733 	/*
10734 	 * Common case of OK return with outval same as inval
10735 	 */
10736 	if (invalp != outvalp) {
10737 		/* don't trust bcopy for identical src/dst */
10738 		(void) bcopy(invalp, outvalp, inlen);
10739 	}
10740 	*outlenp = inlen;
10741 	return (0);
10742 }
10743 
10744 /* ARGSUSED */
10745 int
10746 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10747     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10748     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10749 {
10750 	conn_t	*connp =  Q_TO_CONN(q);
10751 
10752 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10753 	    outlenp, outvalp, thisdg_attrs, cr));
10754 }
10755 
10756 int
10757 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10758     const void *optvalp, socklen_t optlen, cred_t *cr)
10759 {
10760 	conn_t		*connp = (conn_t *)proto_handle;
10761 	squeue_t	*sqp = connp->conn_sqp;
10762 	int		error;
10763 
10764 	/*
10765 	 * Entering the squeue synchronously can result in a context switch,
10766 	 * which can cause a rather sever performance degradation. So we try to
10767 	 * handle whatever options we can without entering the squeue.
10768 	 */
10769 	if (level == IPPROTO_TCP) {
10770 		switch (option_name) {
10771 		case TCP_NODELAY:
10772 			if (optlen != sizeof (int32_t))
10773 				return (EINVAL);
10774 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10775 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10776 			    connp->conn_tcp->tcp_mss;
10777 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10778 			return (0);
10779 		default:
10780 			break;
10781 		}
10782 	}
10783 
10784 	error = squeue_synch_enter(sqp, connp, 0);
10785 	if (error == ENOMEM) {
10786 		return (ENOMEM);
10787 	}
10788 
10789 	error = proto_opt_check(level, option_name, optlen, NULL,
10790 	    tcp_opt_obj.odb_opt_des_arr,
10791 	    tcp_opt_obj.odb_opt_arr_cnt,
10792 	    tcp_opt_obj.odb_topmost_tpiprovider,
10793 	    B_TRUE, B_FALSE, cr);
10794 
10795 	if (error != 0) {
10796 		if (error < 0) {
10797 			error = proto_tlitosyserr(-error);
10798 		}
10799 		squeue_synch_exit(sqp, connp);
10800 		return (error);
10801 	}
10802 
10803 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10804 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10805 	    NULL, cr);
10806 	squeue_synch_exit(sqp, connp);
10807 
10808 	if (error < 0) {
10809 		/*
10810 		 * Pass on to ip
10811 		 */
10812 		error = ip_set_options(connp, level, option_name, optvalp,
10813 		    optlen, cr);
10814 	}
10815 	return (error);
10816 }
10817 
10818 /*
10819  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10820  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10821  * headers, and the maximum size tcp header (to avoid reallocation
10822  * on the fly for additional tcp options).
10823  * Returns failure if can't allocate memory.
10824  */
10825 static int
10826 tcp_build_hdrs(tcp_t *tcp)
10827 {
10828 	char	*hdrs;
10829 	uint_t	hdrs_len;
10830 	ip6i_t	*ip6i;
10831 	char	buf[TCP_MAX_HDR_LENGTH];
10832 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10833 	in6_addr_t src, dst;
10834 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10835 	conn_t *connp = tcp->tcp_connp;
10836 
10837 	/*
10838 	 * save the existing tcp header and source/dest IP addresses
10839 	 */
10840 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10841 	src = tcp->tcp_ip6h->ip6_src;
10842 	dst = tcp->tcp_ip6h->ip6_dst;
10843 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10844 	ASSERT(hdrs_len != 0);
10845 	if (hdrs_len > tcp->tcp_iphc_len) {
10846 		/* Need to reallocate */
10847 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10848 		if (hdrs == NULL)
10849 			return (ENOMEM);
10850 		if (tcp->tcp_iphc != NULL) {
10851 			if (tcp->tcp_hdr_grown) {
10852 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10853 			} else {
10854 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10855 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10856 			}
10857 			tcp->tcp_iphc_len = 0;
10858 		}
10859 		ASSERT(tcp->tcp_iphc_len == 0);
10860 		tcp->tcp_iphc = hdrs;
10861 		tcp->tcp_iphc_len = hdrs_len;
10862 		tcp->tcp_hdr_grown = B_TRUE;
10863 	}
10864 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10865 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10866 
10867 	/* Set header fields not in ipp */
10868 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10869 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10870 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10871 	} else {
10872 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10873 	}
10874 	/*
10875 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10876 	 *
10877 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10878 	 */
10879 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10880 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10881 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10882 
10883 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10884 
10885 	tcp->tcp_ip6h->ip6_src = src;
10886 	tcp->tcp_ip6h->ip6_dst = dst;
10887 
10888 	/*
10889 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10890 	 * the default value for TCP.
10891 	 */
10892 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10893 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10894 
10895 	/*
10896 	 * If we're setting extension headers after a connection
10897 	 * has been established, and if we have a routing header
10898 	 * among the extension headers, call ip_massage_options_v6 to
10899 	 * manipulate the routing header/ip6_dst set the checksum
10900 	 * difference in the tcp header template.
10901 	 * (This happens in tcp_connect_ipv6 if the routing header
10902 	 * is set prior to the connect.)
10903 	 * Set the tcp_sum to zero first in case we've cleared a
10904 	 * routing header or don't have one at all.
10905 	 */
10906 	tcp->tcp_sum = 0;
10907 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10908 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10909 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10910 		    (uint8_t *)tcp->tcp_tcph);
10911 		if (rth != NULL) {
10912 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10913 			    rth, tcps->tcps_netstack);
10914 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10915 			    (tcp->tcp_sum >> 16));
10916 		}
10917 	}
10918 
10919 	/* Try to get everything in a single mblk */
10920 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10921 	    hdrs_len + tcps->tcps_wroff_xtra);
10922 	return (0);
10923 }
10924 
10925 /*
10926  * Transfer any source route option from ipha to buf/dst in reversed form.
10927  */
10928 static int
10929 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10930 {
10931 	ipoptp_t	opts;
10932 	uchar_t		*opt;
10933 	uint8_t		optval;
10934 	uint8_t		optlen;
10935 	uint32_t	len = 0;
10936 
10937 	for (optval = ipoptp_first(&opts, ipha);
10938 	    optval != IPOPT_EOL;
10939 	    optval = ipoptp_next(&opts)) {
10940 		opt = opts.ipoptp_cur;
10941 		optlen = opts.ipoptp_len;
10942 		switch (optval) {
10943 			int	off1, off2;
10944 		case IPOPT_SSRR:
10945 		case IPOPT_LSRR:
10946 
10947 			/* Reverse source route */
10948 			/*
10949 			 * First entry should be the next to last one in the
10950 			 * current source route (the last entry is our
10951 			 * address.)
10952 			 * The last entry should be the final destination.
10953 			 */
10954 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
10955 			buf[IPOPT_OLEN] = (uint8_t)optlen;
10956 			off1 = IPOPT_MINOFF_SR - 1;
10957 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
10958 			if (off2 < 0) {
10959 				/* No entries in source route */
10960 				break;
10961 			}
10962 			bcopy(opt + off2, dst, IP_ADDR_LEN);
10963 			/*
10964 			 * Note: use src since ipha has not had its src
10965 			 * and dst reversed (it is in the state it was
10966 			 * received.
10967 			 */
10968 			bcopy(&ipha->ipha_src, buf + off2,
10969 			    IP_ADDR_LEN);
10970 			off2 -= IP_ADDR_LEN;
10971 
10972 			while (off2 > 0) {
10973 				bcopy(opt + off2, buf + off1,
10974 				    IP_ADDR_LEN);
10975 				off1 += IP_ADDR_LEN;
10976 				off2 -= IP_ADDR_LEN;
10977 			}
10978 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
10979 			buf += optlen;
10980 			len += optlen;
10981 			break;
10982 		}
10983 	}
10984 done:
10985 	/* Pad the resulting options */
10986 	while (len & 0x3) {
10987 		*buf++ = IPOPT_EOL;
10988 		len++;
10989 	}
10990 	return (len);
10991 }
10992 
10993 
10994 /*
10995  * Extract and revert a source route from ipha (if any)
10996  * and then update the relevant fields in both tcp_t and the standard header.
10997  */
10998 static void
10999 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11000 {
11001 	char	buf[TCP_MAX_HDR_LENGTH];
11002 	uint_t	tcph_len;
11003 	int	len;
11004 
11005 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11006 	len = IPH_HDR_LENGTH(ipha);
11007 	if (len == IP_SIMPLE_HDR_LENGTH)
11008 		/* Nothing to do */
11009 		return;
11010 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11011 	    (len & 0x3))
11012 		return;
11013 
11014 	tcph_len = tcp->tcp_tcp_hdr_len;
11015 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11016 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11017 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11018 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11019 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11020 	len += IP_SIMPLE_HDR_LENGTH;
11021 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11022 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11023 	if ((int)tcp->tcp_sum < 0)
11024 		tcp->tcp_sum--;
11025 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11026 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11027 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11028 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11029 	tcp->tcp_ip_hdr_len = len;
11030 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11031 	    (IP_VERSION << 4) | (len >> 2);
11032 	len += tcph_len;
11033 	tcp->tcp_hdr_len = len;
11034 }
11035 
11036 /*
11037  * Copy the standard header into its new location,
11038  * lay in the new options and then update the relevant
11039  * fields in both tcp_t and the standard header.
11040  */
11041 static int
11042 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11043 {
11044 	uint_t	tcph_len;
11045 	uint8_t	*ip_optp;
11046 	tcph_t	*new_tcph;
11047 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11048 	conn_t	*connp = tcp->tcp_connp;
11049 
11050 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11051 		return (EINVAL);
11052 
11053 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11054 		return (EINVAL);
11055 
11056 	if (checkonly) {
11057 		/*
11058 		 * do not really set, just pretend to - T_CHECK
11059 		 */
11060 		return (0);
11061 	}
11062 
11063 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11064 	if (tcp->tcp_label_len > 0) {
11065 		int padlen;
11066 		uint8_t opt;
11067 
11068 		/* convert list termination to no-ops */
11069 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11070 		ip_optp += ip_optp[IPOPT_OLEN];
11071 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11072 		while (--padlen >= 0)
11073 			*ip_optp++ = opt;
11074 	}
11075 	tcph_len = tcp->tcp_tcp_hdr_len;
11076 	new_tcph = (tcph_t *)(ip_optp + len);
11077 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11078 	tcp->tcp_tcph = new_tcph;
11079 	bcopy(ptr, ip_optp, len);
11080 
11081 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11082 
11083 	tcp->tcp_ip_hdr_len = len;
11084 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11085 	    (IP_VERSION << 4) | (len >> 2);
11086 	tcp->tcp_hdr_len = len + tcph_len;
11087 	if (!TCP_IS_DETACHED(tcp)) {
11088 		/* Always allocate room for all options. */
11089 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11090 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11091 	}
11092 	return (0);
11093 }
11094 
11095 /* Get callback routine passed to nd_load by tcp_param_register */
11096 /* ARGSUSED */
11097 static int
11098 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11099 {
11100 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11101 
11102 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11103 	return (0);
11104 }
11105 
11106 /*
11107  * Walk through the param array specified registering each element with the
11108  * named dispatch handler.
11109  */
11110 static boolean_t
11111 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11112 {
11113 	for (; cnt-- > 0; tcppa++) {
11114 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11115 			if (!nd_load(ndp, tcppa->tcp_param_name,
11116 			    tcp_param_get, tcp_param_set,
11117 			    (caddr_t)tcppa)) {
11118 				nd_free(ndp);
11119 				return (B_FALSE);
11120 			}
11121 		}
11122 	}
11123 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11124 	    KM_SLEEP);
11125 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11126 	    sizeof (tcpparam_t));
11127 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11128 	    tcp_param_get, tcp_param_set_aligned,
11129 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11130 		nd_free(ndp);
11131 		return (B_FALSE);
11132 	}
11133 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11134 	    KM_SLEEP);
11135 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11136 	    sizeof (tcpparam_t));
11137 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11138 	    tcp_param_get, tcp_param_set_aligned,
11139 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11140 		nd_free(ndp);
11141 		return (B_FALSE);
11142 	}
11143 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11144 	    KM_SLEEP);
11145 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11146 	    sizeof (tcpparam_t));
11147 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11148 	    tcp_param_get, tcp_param_set_aligned,
11149 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11150 		nd_free(ndp);
11151 		return (B_FALSE);
11152 	}
11153 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11154 	    KM_SLEEP);
11155 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11156 	    sizeof (tcpparam_t));
11157 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11158 	    tcp_param_get, tcp_param_set_aligned,
11159 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11160 		nd_free(ndp);
11161 		return (B_FALSE);
11162 	}
11163 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11164 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11165 		nd_free(ndp);
11166 		return (B_FALSE);
11167 	}
11168 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11169 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11170 		nd_free(ndp);
11171 		return (B_FALSE);
11172 	}
11173 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11174 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11175 		nd_free(ndp);
11176 		return (B_FALSE);
11177 	}
11178 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11179 	    NULL)) {
11180 		nd_free(ndp);
11181 		return (B_FALSE);
11182 	}
11183 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11184 	    NULL, NULL)) {
11185 		nd_free(ndp);
11186 		return (B_FALSE);
11187 	}
11188 	if (!nd_load(ndp, "tcp_listen_hash",
11189 	    tcp_listen_hash_report, NULL, NULL)) {
11190 		nd_free(ndp);
11191 		return (B_FALSE);
11192 	}
11193 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11194 	    NULL, NULL)) {
11195 		nd_free(ndp);
11196 		return (B_FALSE);
11197 	}
11198 	if (!nd_load(ndp, "tcp_acceptor_hash",
11199 	    tcp_acceptor_hash_report, NULL, NULL)) {
11200 		nd_free(ndp);
11201 		return (B_FALSE);
11202 	}
11203 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11204 	    tcp_1948_phrase_set, NULL)) {
11205 		nd_free(ndp);
11206 		return (B_FALSE);
11207 	}
11208 	/*
11209 	 * Dummy ndd variables - only to convey obsolescence information
11210 	 * through printing of their name (no get or set routines)
11211 	 * XXX Remove in future releases ?
11212 	 */
11213 	if (!nd_load(ndp,
11214 	    "tcp_close_wait_interval(obsoleted - "
11215 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11216 		nd_free(ndp);
11217 		return (B_FALSE);
11218 	}
11219 	return (B_TRUE);
11220 }
11221 
11222 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11223 /* ARGSUSED */
11224 static int
11225 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11226     cred_t *cr)
11227 {
11228 	long new_value;
11229 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11230 
11231 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11232 	    new_value < tcppa->tcp_param_min ||
11233 	    new_value > tcppa->tcp_param_max) {
11234 		return (EINVAL);
11235 	}
11236 	/*
11237 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11238 	 * round it up.  For future 64 bit requirement, we actually make it
11239 	 * a multiple of 8.
11240 	 */
11241 	if (new_value & 0x7) {
11242 		new_value = (new_value & ~0x7) + 0x8;
11243 	}
11244 	tcppa->tcp_param_val = new_value;
11245 	return (0);
11246 }
11247 
11248 /* Set callback routine passed to nd_load by tcp_param_register */
11249 /* ARGSUSED */
11250 static int
11251 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11252 {
11253 	long	new_value;
11254 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11255 
11256 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11257 	    new_value < tcppa->tcp_param_min ||
11258 	    new_value > tcppa->tcp_param_max) {
11259 		return (EINVAL);
11260 	}
11261 	tcppa->tcp_param_val = new_value;
11262 	return (0);
11263 }
11264 
11265 /*
11266  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11267  * is filled, return as much as we can.  The message passed in may be
11268  * multi-part, chained using b_cont.  "start" is the starting sequence
11269  * number for this piece.
11270  */
11271 static mblk_t *
11272 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11273 {
11274 	uint32_t	end;
11275 	mblk_t		*mp1;
11276 	mblk_t		*mp2;
11277 	mblk_t		*next_mp;
11278 	uint32_t	u1;
11279 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11280 
11281 	/* Walk through all the new pieces. */
11282 	do {
11283 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11284 		    (uintptr_t)INT_MAX);
11285 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11286 		next_mp = mp->b_cont;
11287 		if (start == end) {
11288 			/* Empty.  Blast it. */
11289 			freeb(mp);
11290 			continue;
11291 		}
11292 		mp->b_cont = NULL;
11293 		TCP_REASS_SET_SEQ(mp, start);
11294 		TCP_REASS_SET_END(mp, end);
11295 		mp1 = tcp->tcp_reass_tail;
11296 		if (!mp1) {
11297 			tcp->tcp_reass_tail = mp;
11298 			tcp->tcp_reass_head = mp;
11299 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11300 			UPDATE_MIB(&tcps->tcps_mib,
11301 			    tcpInDataUnorderBytes, end - start);
11302 			continue;
11303 		}
11304 		/* New stuff completely beyond tail? */
11305 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11306 			/* Link it on end. */
11307 			mp1->b_cont = mp;
11308 			tcp->tcp_reass_tail = mp;
11309 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11310 			UPDATE_MIB(&tcps->tcps_mib,
11311 			    tcpInDataUnorderBytes, end - start);
11312 			continue;
11313 		}
11314 		mp1 = tcp->tcp_reass_head;
11315 		u1 = TCP_REASS_SEQ(mp1);
11316 		/* New stuff at the front? */
11317 		if (SEQ_LT(start, u1)) {
11318 			/* Yes... Check for overlap. */
11319 			mp->b_cont = mp1;
11320 			tcp->tcp_reass_head = mp;
11321 			tcp_reass_elim_overlap(tcp, mp);
11322 			continue;
11323 		}
11324 		/*
11325 		 * The new piece fits somewhere between the head and tail.
11326 		 * We find our slot, where mp1 precedes us and mp2 trails.
11327 		 */
11328 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11329 			u1 = TCP_REASS_SEQ(mp2);
11330 			if (SEQ_LEQ(start, u1))
11331 				break;
11332 		}
11333 		/* Link ourselves in */
11334 		mp->b_cont = mp2;
11335 		mp1->b_cont = mp;
11336 
11337 		/* Trim overlap with following mblk(s) first */
11338 		tcp_reass_elim_overlap(tcp, mp);
11339 
11340 		/* Trim overlap with preceding mblk */
11341 		tcp_reass_elim_overlap(tcp, mp1);
11342 
11343 	} while (start = end, mp = next_mp);
11344 	mp1 = tcp->tcp_reass_head;
11345 	/* Anything ready to go? */
11346 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11347 		return (NULL);
11348 	/* Eat what we can off the queue */
11349 	for (;;) {
11350 		mp = mp1->b_cont;
11351 		end = TCP_REASS_END(mp1);
11352 		TCP_REASS_SET_SEQ(mp1, 0);
11353 		TCP_REASS_SET_END(mp1, 0);
11354 		if (!mp) {
11355 			tcp->tcp_reass_tail = NULL;
11356 			break;
11357 		}
11358 		if (end != TCP_REASS_SEQ(mp)) {
11359 			mp1->b_cont = NULL;
11360 			break;
11361 		}
11362 		mp1 = mp;
11363 	}
11364 	mp1 = tcp->tcp_reass_head;
11365 	tcp->tcp_reass_head = mp;
11366 	return (mp1);
11367 }
11368 
11369 /* Eliminate any overlap that mp may have over later mblks */
11370 static void
11371 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11372 {
11373 	uint32_t	end;
11374 	mblk_t		*mp1;
11375 	uint32_t	u1;
11376 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11377 
11378 	end = TCP_REASS_END(mp);
11379 	while ((mp1 = mp->b_cont) != NULL) {
11380 		u1 = TCP_REASS_SEQ(mp1);
11381 		if (!SEQ_GT(end, u1))
11382 			break;
11383 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11384 			mp->b_wptr -= end - u1;
11385 			TCP_REASS_SET_END(mp, u1);
11386 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11387 			UPDATE_MIB(&tcps->tcps_mib,
11388 			    tcpInDataPartDupBytes, end - u1);
11389 			break;
11390 		}
11391 		mp->b_cont = mp1->b_cont;
11392 		TCP_REASS_SET_SEQ(mp1, 0);
11393 		TCP_REASS_SET_END(mp1, 0);
11394 		freeb(mp1);
11395 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11396 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11397 	}
11398 	if (!mp1)
11399 		tcp->tcp_reass_tail = mp;
11400 }
11401 
11402 static uint_t
11403 tcp_rwnd_reopen(tcp_t *tcp)
11404 {
11405 	uint_t ret = 0;
11406 	uint_t thwin;
11407 
11408 	/* Learn the latest rwnd information that we sent to the other side. */
11409 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11410 	    << tcp->tcp_rcv_ws;
11411 	/* This is peer's calculated send window (our receive window). */
11412 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11413 	/*
11414 	 * Increase the receive window to max.  But we need to do receiver
11415 	 * SWS avoidance.  This means that we need to check the increase of
11416 	 * of receive window is at least 1 MSS.
11417 	 */
11418 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11419 		/*
11420 		 * If the window that the other side knows is less than max
11421 		 * deferred acks segments, send an update immediately.
11422 		 */
11423 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11424 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11425 			ret = TH_ACK_NEEDED;
11426 		}
11427 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11428 	}
11429 	return (ret);
11430 }
11431 
11432 /*
11433  * Send up all messages queued on tcp_rcv_list.
11434  */
11435 static uint_t
11436 tcp_rcv_drain(tcp_t *tcp)
11437 {
11438 	mblk_t *mp;
11439 	uint_t ret = 0;
11440 #ifdef DEBUG
11441 	uint_t cnt = 0;
11442 #endif
11443 	queue_t	*q = tcp->tcp_rq;
11444 
11445 	/* Can't drain on an eager connection */
11446 	if (tcp->tcp_listener != NULL)
11447 		return (ret);
11448 
11449 	/* Can't be a non-STREAMS connection or sodirect enabled */
11450 	ASSERT((!IPCL_IS_NONSTR(tcp->tcp_connp)) && SOD_NOT_ENABLED(tcp));
11451 
11452 	/* No need for the push timer now. */
11453 	if (tcp->tcp_push_tid != 0) {
11454 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11455 		tcp->tcp_push_tid = 0;
11456 	}
11457 
11458 	/*
11459 	 * Handle two cases here: we are currently fused or we were
11460 	 * previously fused and have some urgent data to be delivered
11461 	 * upstream.  The latter happens because we either ran out of
11462 	 * memory or were detached and therefore sending the SIGURG was
11463 	 * deferred until this point.  In either case we pass control
11464 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11465 	 * some work.
11466 	 */
11467 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11468 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11469 		    tcp->tcp_fused_sigurg_mp != NULL);
11470 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11471 		    &tcp->tcp_fused_sigurg_mp))
11472 			return (ret);
11473 	}
11474 
11475 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11476 		tcp->tcp_rcv_list = mp->b_next;
11477 		mp->b_next = NULL;
11478 #ifdef DEBUG
11479 		cnt += msgdsize(mp);
11480 #endif
11481 		/* Does this need SSL processing first? */
11482 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11483 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11484 			    mblk_t *, mp);
11485 			tcp_kssl_input(tcp, mp);
11486 			continue;
11487 		}
11488 		putnext(q, mp);
11489 	}
11490 #ifdef DEBUG
11491 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11492 #endif
11493 	tcp->tcp_rcv_last_head = NULL;
11494 	tcp->tcp_rcv_last_tail = NULL;
11495 	tcp->tcp_rcv_cnt = 0;
11496 
11497 	if (canputnext(q))
11498 		return (tcp_rwnd_reopen(tcp));
11499 
11500 	return (ret);
11501 }
11502 
11503 /*
11504  * Queue data on tcp_rcv_list which is a b_next chain.
11505  * tcp_rcv_last_head/tail is the last element of this chain.
11506  * Each element of the chain is a b_cont chain.
11507  *
11508  * M_DATA messages are added to the current element.
11509  * Other messages are added as new (b_next) elements.
11510  */
11511 void
11512 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11513 {
11514 	ASSERT(seg_len == msgdsize(mp));
11515 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11516 
11517 	if (tcp->tcp_rcv_list == NULL) {
11518 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11519 		tcp->tcp_rcv_list = mp;
11520 		tcp->tcp_rcv_last_head = mp;
11521 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11522 		tcp->tcp_rcv_last_tail->b_cont = mp;
11523 	} else {
11524 		tcp->tcp_rcv_last_head->b_next = mp;
11525 		tcp->tcp_rcv_last_head = mp;
11526 	}
11527 
11528 	while (mp->b_cont)
11529 		mp = mp->b_cont;
11530 
11531 	tcp->tcp_rcv_last_tail = mp;
11532 	tcp->tcp_rcv_cnt += seg_len;
11533 	tcp->tcp_rwnd -= seg_len;
11534 }
11535 
11536 /*
11537  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11538  * above, in addition when uioa is enabled schedule an asynchronous uio
11539  * prior to enqueuing. They implement the combinhed semantics of the
11540  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11541  * canputnext(), i.e. flow-control with backenable.
11542  *
11543  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11544  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11545  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11546  *
11547  * Must be called with sodp->sod_lockp held and will return with the lock
11548  * released.
11549  */
11550 static uint_t
11551 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11552 {
11553 	queue_t		*q = tcp->tcp_rq;
11554 	uint_t		thwin;
11555 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11556 	uint_t		ret = 0;
11557 
11558 	/* Can't be an eager connection */
11559 	ASSERT(tcp->tcp_listener == NULL);
11560 
11561 	/* Caller must have lock held */
11562 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11563 
11564 	/* Sodirect mode so must not be a tcp_rcv_list */
11565 	ASSERT(tcp->tcp_rcv_list == NULL);
11566 
11567 	if (SOD_QFULL(sodp)) {
11568 		/* Q is full, mark Q for need backenable */
11569 		SOD_QSETBE(sodp);
11570 	}
11571 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11572 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11573 	    << tcp->tcp_rcv_ws;
11574 	/* This is peer's calculated send window (our available rwnd). */
11575 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11576 	/*
11577 	 * Increase the receive window to max.  But we need to do receiver
11578 	 * SWS avoidance.  This means that we need to check the increase of
11579 	 * of receive window is at least 1 MSS.
11580 	 */
11581 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11582 		/*
11583 		 * If the window that the other side knows is less than max
11584 		 * deferred acks segments, send an update immediately.
11585 		 */
11586 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11587 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11588 			ret = TH_ACK_NEEDED;
11589 		}
11590 		tcp->tcp_rwnd = q->q_hiwat;
11591 	}
11592 
11593 	if (!SOD_QEMPTY(sodp)) {
11594 		/* Wakeup to socket */
11595 		sodp->sod_state &= SOD_WAKE_CLR;
11596 		sodp->sod_state |= SOD_WAKE_DONE;
11597 		(sodp->sod_wakeup)(sodp);
11598 		/* wakeup() does the mutex_ext() */
11599 	} else {
11600 		/* Q is empty, no need to wake */
11601 		sodp->sod_state &= SOD_WAKE_CLR;
11602 		sodp->sod_state |= SOD_WAKE_NOT;
11603 		mutex_exit(sodp->sod_lockp);
11604 	}
11605 
11606 	/* No need for the push timer now. */
11607 	if (tcp->tcp_push_tid != 0) {
11608 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11609 		tcp->tcp_push_tid = 0;
11610 	}
11611 
11612 	return (ret);
11613 }
11614 
11615 /*
11616  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11617  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11618  * to the user-land buffer and flag the mblk_t as such.
11619  *
11620  * Also, handle tcp_rwnd.
11621  */
11622 uint_t
11623 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11624 {
11625 	uioa_t		*uioap = &sodp->sod_uioa;
11626 	boolean_t	qfull;
11627 	uint_t		thwin;
11628 
11629 	/* Can't be an eager connection */
11630 	ASSERT(tcp->tcp_listener == NULL);
11631 
11632 	/* Caller must have lock held */
11633 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11634 
11635 	/* Sodirect mode so must not be a tcp_rcv_list */
11636 	ASSERT(tcp->tcp_rcv_list == NULL);
11637 
11638 	/* Passed in segment length must be equal to mblk_t chain data size */
11639 	ASSERT(seg_len == msgdsize(mp));
11640 
11641 	if (DB_TYPE(mp) != M_DATA) {
11642 		/* Only process M_DATA mblk_t's */
11643 		goto enq;
11644 	}
11645 	if (uioap->uioa_state & UIOA_ENABLED) {
11646 		/* Uioa is enabled */
11647 		mblk_t		*mp1 = mp;
11648 		mblk_t		*lmp = NULL;
11649 
11650 		if (seg_len > uioap->uio_resid) {
11651 			/*
11652 			 * There isn't enough uio space for the mblk_t chain
11653 			 * so disable uioa such that this and any additional
11654 			 * mblk_t data is handled by the socket and schedule
11655 			 * the socket for wakeup to finish this uioa.
11656 			 */
11657 			uioap->uioa_state &= UIOA_CLR;
11658 			uioap->uioa_state |= UIOA_FINI;
11659 			if (sodp->sod_state & SOD_WAKE_NOT) {
11660 				sodp->sod_state &= SOD_WAKE_CLR;
11661 				sodp->sod_state |= SOD_WAKE_NEED;
11662 			}
11663 			goto enq;
11664 		}
11665 		do {
11666 			uint32_t	len = MBLKL(mp1);
11667 
11668 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11669 				/* Scheduled, mark dblk_t as such */
11670 				DB_FLAGS(mp1) |= DBLK_UIOA;
11671 			} else {
11672 				/* Error, turn off async processing */
11673 				uioap->uioa_state &= UIOA_CLR;
11674 				uioap->uioa_state |= UIOA_FINI;
11675 				break;
11676 			}
11677 			lmp = mp1;
11678 		} while ((mp1 = mp1->b_cont) != NULL);
11679 
11680 		if (mp1 != NULL || uioap->uio_resid == 0) {
11681 			/*
11682 			 * Not all mblk_t(s) uioamoved (error) or all uio
11683 			 * space has been consumed so schedule the socket
11684 			 * for wakeup to finish this uio.
11685 			 */
11686 			sodp->sod_state &= SOD_WAKE_CLR;
11687 			sodp->sod_state |= SOD_WAKE_NEED;
11688 
11689 			/* Break the mblk chain if neccessary. */
11690 			if (mp1 != NULL && lmp != NULL) {
11691 				mp->b_next = mp1;
11692 				lmp->b_cont = NULL;
11693 			}
11694 		}
11695 	} else if (uioap->uioa_state & UIOA_FINI) {
11696 		/*
11697 		 * Post UIO_ENABLED waiting for socket to finish processing
11698 		 * so just enqueue and update tcp_rwnd.
11699 		 */
11700 		if (SOD_QFULL(sodp))
11701 			tcp->tcp_rwnd -= seg_len;
11702 	} else if (sodp->sod_want > 0) {
11703 		/*
11704 		 * Uioa isn't enabled but sodirect has a pending read().
11705 		 */
11706 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11707 			if (sodp->sod_state & SOD_WAKE_NOT) {
11708 				/* Schedule socket for wakeup */
11709 				sodp->sod_state &= SOD_WAKE_CLR;
11710 				sodp->sod_state |= SOD_WAKE_NEED;
11711 			}
11712 			tcp->tcp_rwnd -= seg_len;
11713 		}
11714 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11715 		/*
11716 		 * No pending sodirect read() so used the default
11717 		 * TCP push logic to guess that a push is needed.
11718 		 */
11719 		if (sodp->sod_state & SOD_WAKE_NOT) {
11720 			/* Schedule socket for wakeup */
11721 			sodp->sod_state &= SOD_WAKE_CLR;
11722 			sodp->sod_state |= SOD_WAKE_NEED;
11723 		}
11724 		tcp->tcp_rwnd -= seg_len;
11725 	} else {
11726 		/* Just update tcp_rwnd */
11727 		tcp->tcp_rwnd -= seg_len;
11728 	}
11729 enq:
11730 	qfull = SOD_QFULL(sodp);
11731 
11732 	(sodp->sod_enqueue)(sodp, mp);
11733 
11734 	if (! qfull && SOD_QFULL(sodp)) {
11735 		/* Wasn't QFULL, now QFULL, need back-enable */
11736 		SOD_QSETBE(sodp);
11737 	}
11738 
11739 	/*
11740 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11741 	 * first get advertised rwnd.
11742 	 */
11743 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11744 	/* Minus delayed ACK count */
11745 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11746 	if (thwin < tcp->tcp_mss) {
11747 		/* Remote avail swnd < mss, need ACK now */
11748 		return (TH_ACK_NEEDED);
11749 	}
11750 
11751 	return (0);
11752 }
11753 
11754 /*
11755  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11756  *
11757  * This is the default entry function into TCP on the read side. TCP is
11758  * always entered via squeue i.e. using squeue's for mutual exclusion.
11759  * When classifier does a lookup to find the tcp, it also puts a reference
11760  * on the conn structure associated so the tcp is guaranteed to exist
11761  * when we come here. We still need to check the state because it might
11762  * as well has been closed. The squeue processing function i.e. squeue_enter,
11763  * is responsible for doing the CONN_DEC_REF.
11764  *
11765  * Apart from the default entry point, IP also sends packets directly to
11766  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11767  * connections.
11768  */
11769 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11770 void
11771 tcp_input(void *arg, mblk_t *mp, void *arg2)
11772 {
11773 	conn_t	*connp = (conn_t *)arg;
11774 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11775 
11776 	/* arg2 is the sqp */
11777 	ASSERT(arg2 != NULL);
11778 	ASSERT(mp != NULL);
11779 
11780 	/*
11781 	 * Don't accept any input on a closed tcp as this TCP logically does
11782 	 * not exist on the system. Don't proceed further with this TCP.
11783 	 * For eg. this packet could trigger another close of this tcp
11784 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11785 	 * tcp_clean_death / tcp_closei_local must be called at most once
11786 	 * on a TCP. In this case we need to refeed the packet into the
11787 	 * classifier and figure out where the packet should go. Need to
11788 	 * preserve the recv_ill somehow. Until we figure that out, for
11789 	 * now just drop the packet if we can't classify the packet.
11790 	 */
11791 	if (tcp->tcp_state == TCPS_CLOSED ||
11792 	    tcp->tcp_state == TCPS_BOUND) {
11793 		conn_t	*new_connp;
11794 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11795 
11796 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11797 		if (new_connp != NULL) {
11798 			tcp_reinput(new_connp, mp, arg2);
11799 			return;
11800 		}
11801 		/* We failed to classify. For now just drop the packet */
11802 		freemsg(mp);
11803 		return;
11804 	}
11805 
11806 	if (DB_TYPE(mp) != M_DATA) {
11807 		tcp_rput_common(tcp, mp);
11808 		return;
11809 	}
11810 
11811 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11812 		squeue_t	*final_sqp;
11813 
11814 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11815 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11816 		DB_CKSUMSTART(mp) = 0;
11817 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11818 		    connp->conn_final_sqp == NULL &&
11819 		    tcp_outbound_squeue_switch) {
11820 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11821 			connp->conn_final_sqp = final_sqp;
11822 			if (connp->conn_final_sqp != connp->conn_sqp) {
11823 				CONN_INC_REF(connp);
11824 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11825 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11826 				    tcp_rput_data, connp, ip_squeue_flag,
11827 				    SQTAG_CONNECT_FINISH);
11828 				return;
11829 			}
11830 		}
11831 	}
11832 	tcp_rput_data(connp, mp, arg2);
11833 }
11834 
11835 /*
11836  * The read side put procedure.
11837  * The packets passed up by ip are assume to be aligned according to
11838  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11839  */
11840 static void
11841 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11842 {
11843 	/*
11844 	 * tcp_rput_data() does not expect M_CTL except for the case
11845 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11846 	 * type. Need to make sure that any other M_CTLs don't make
11847 	 * it to tcp_rput_data since it is not expecting any and doesn't
11848 	 * check for it.
11849 	 */
11850 	if (DB_TYPE(mp) == M_CTL) {
11851 		switch (*(uint32_t *)(mp->b_rptr)) {
11852 		case TCP_IOC_ABORT_CONN:
11853 			/*
11854 			 * Handle connection abort request.
11855 			 */
11856 			tcp_ioctl_abort_handler(tcp, mp);
11857 			return;
11858 		case IPSEC_IN:
11859 			/*
11860 			 * Only secure icmp arrive in TCP and they
11861 			 * don't go through data path.
11862 			 */
11863 			tcp_icmp_error(tcp, mp);
11864 			return;
11865 		case IN_PKTINFO:
11866 			/*
11867 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11868 			 * sockets that are receiving IPv4 traffic. tcp
11869 			 */
11870 			ASSERT(tcp->tcp_family == AF_INET6);
11871 			ASSERT(tcp->tcp_ipv6_recvancillary &
11872 			    TCP_IPV6_RECVPKTINFO);
11873 			tcp_rput_data(tcp->tcp_connp, mp,
11874 			    tcp->tcp_connp->conn_sqp);
11875 			return;
11876 		case MDT_IOC_INFO_UPDATE:
11877 			/*
11878 			 * Handle Multidata information update; the
11879 			 * following routine will free the message.
11880 			 */
11881 			if (tcp->tcp_connp->conn_mdt_ok) {
11882 				tcp_mdt_update(tcp,
11883 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11884 				    B_FALSE);
11885 			}
11886 			freemsg(mp);
11887 			return;
11888 		case LSO_IOC_INFO_UPDATE:
11889 			/*
11890 			 * Handle LSO information update; the following
11891 			 * routine will free the message.
11892 			 */
11893 			if (tcp->tcp_connp->conn_lso_ok) {
11894 				tcp_lso_update(tcp,
11895 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11896 			}
11897 			freemsg(mp);
11898 			return;
11899 		default:
11900 			/*
11901 			 * tcp_icmp_err() will process the M_CTL packets.
11902 			 * Non-ICMP packets, if any, will be discarded in
11903 			 * tcp_icmp_err(). We will process the ICMP packet
11904 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11905 			 * incoming ICMP packet may result in changing
11906 			 * the tcp_mss, which we would need if we have
11907 			 * packets to retransmit.
11908 			 */
11909 			tcp_icmp_error(tcp, mp);
11910 			return;
11911 		}
11912 	}
11913 
11914 	/* No point processing the message if tcp is already closed */
11915 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11916 		freemsg(mp);
11917 		return;
11918 	}
11919 
11920 	tcp_rput_other(tcp, mp);
11921 }
11922 
11923 
11924 /* The minimum of smoothed mean deviation in RTO calculation. */
11925 #define	TCP_SD_MIN	400
11926 
11927 /*
11928  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11929  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11930  * are the same as those in Appendix A.2 of that paper.
11931  *
11932  * m = new measurement
11933  * sa = smoothed RTT average (8 * average estimates).
11934  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11935  */
11936 static void
11937 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11938 {
11939 	long m = TICK_TO_MSEC(rtt);
11940 	clock_t sa = tcp->tcp_rtt_sa;
11941 	clock_t sv = tcp->tcp_rtt_sd;
11942 	clock_t rto;
11943 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11944 
11945 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11946 	tcp->tcp_rtt_update++;
11947 
11948 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11949 	if (sa != 0) {
11950 		/*
11951 		 * Update average estimator:
11952 		 *	new rtt = 7/8 old rtt + 1/8 Error
11953 		 */
11954 
11955 		/* m is now Error in estimate. */
11956 		m -= sa >> 3;
11957 		if ((sa += m) <= 0) {
11958 			/*
11959 			 * Don't allow the smoothed average to be negative.
11960 			 * We use 0 to denote reinitialization of the
11961 			 * variables.
11962 			 */
11963 			sa = 1;
11964 		}
11965 
11966 		/*
11967 		 * Update deviation estimator:
11968 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
11969 		 */
11970 		if (m < 0)
11971 			m = -m;
11972 		m -= sv >> 2;
11973 		sv += m;
11974 	} else {
11975 		/*
11976 		 * This follows BSD's implementation.  So the reinitialized
11977 		 * RTO is 3 * m.  We cannot go less than 2 because if the
11978 		 * link is bandwidth dominated, doubling the window size
11979 		 * during slow start means doubling the RTT.  We want to be
11980 		 * more conservative when we reinitialize our estimates.  3
11981 		 * is just a convenient number.
11982 		 */
11983 		sa = m << 3;
11984 		sv = m << 1;
11985 	}
11986 	if (sv < TCP_SD_MIN) {
11987 		/*
11988 		 * We do not know that if sa captures the delay ACK
11989 		 * effect as in a long train of segments, a receiver
11990 		 * does not delay its ACKs.  So set the minimum of sv
11991 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
11992 		 * of BSD DATO.  That means the minimum of mean
11993 		 * deviation is 100 ms.
11994 		 *
11995 		 */
11996 		sv = TCP_SD_MIN;
11997 	}
11998 	tcp->tcp_rtt_sa = sa;
11999 	tcp->tcp_rtt_sd = sv;
12000 	/*
12001 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12002 	 *
12003 	 * Add tcp_rexmit_interval extra in case of extreme environment
12004 	 * where the algorithm fails to work.  The default value of
12005 	 * tcp_rexmit_interval_extra should be 0.
12006 	 *
12007 	 * As we use a finer grained clock than BSD and update
12008 	 * RTO for every ACKs, add in another .25 of RTT to the
12009 	 * deviation of RTO to accomodate burstiness of 1/4 of
12010 	 * window size.
12011 	 */
12012 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12013 
12014 	if (rto > tcps->tcps_rexmit_interval_max) {
12015 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12016 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12017 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12018 	} else {
12019 		tcp->tcp_rto = rto;
12020 	}
12021 
12022 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12023 	tcp->tcp_timer_backoff = 0;
12024 }
12025 
12026 /*
12027  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12028  * send queue which starts at the given seq. no.
12029  *
12030  * Parameters:
12031  *	tcp_t *tcp: the tcp instance pointer.
12032  *	uint32_t seq: the starting seq. no of the requested segment.
12033  *	int32_t *off: after the execution, *off will be the offset to
12034  *		the returned mblk which points to the requested seq no.
12035  *		It is the caller's responsibility to send in a non-null off.
12036  *
12037  * Return:
12038  *	A mblk_t pointer pointing to the requested segment in send queue.
12039  */
12040 static mblk_t *
12041 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12042 {
12043 	int32_t	cnt;
12044 	mblk_t	*mp;
12045 
12046 	/* Defensive coding.  Make sure we don't send incorrect data. */
12047 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12048 		return (NULL);
12049 
12050 	cnt = seq - tcp->tcp_suna;
12051 	mp = tcp->tcp_xmit_head;
12052 	while (cnt > 0 && mp != NULL) {
12053 		cnt -= mp->b_wptr - mp->b_rptr;
12054 		if (cnt < 0) {
12055 			cnt += mp->b_wptr - mp->b_rptr;
12056 			break;
12057 		}
12058 		mp = mp->b_cont;
12059 	}
12060 	ASSERT(mp != NULL);
12061 	*off = cnt;
12062 	return (mp);
12063 }
12064 
12065 /*
12066  * This function handles all retransmissions if SACK is enabled for this
12067  * connection.  First it calculates how many segments can be retransmitted
12068  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12069  * segments.  A segment is eligible if sack_cnt for that segment is greater
12070  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12071  * all eligible segments, it checks to see if TCP can send some new segments
12072  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12073  *
12074  * Parameters:
12075  *	tcp_t *tcp: the tcp structure of the connection.
12076  *	uint_t *flags: in return, appropriate value will be set for
12077  *	tcp_rput_data().
12078  */
12079 static void
12080 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12081 {
12082 	notsack_blk_t	*notsack_blk;
12083 	int32_t		usable_swnd;
12084 	int32_t		mss;
12085 	uint32_t	seg_len;
12086 	mblk_t		*xmit_mp;
12087 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12088 
12089 	ASSERT(tcp->tcp_sack_info != NULL);
12090 	ASSERT(tcp->tcp_notsack_list != NULL);
12091 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12092 
12093 	/* Defensive coding in case there is a bug... */
12094 	if (tcp->tcp_notsack_list == NULL) {
12095 		return;
12096 	}
12097 	notsack_blk = tcp->tcp_notsack_list;
12098 	mss = tcp->tcp_mss;
12099 
12100 	/*
12101 	 * Limit the num of outstanding data in the network to be
12102 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12103 	 */
12104 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12105 
12106 	/* At least retransmit 1 MSS of data. */
12107 	if (usable_swnd <= 0) {
12108 		usable_swnd = mss;
12109 	}
12110 
12111 	/* Make sure no new RTT samples will be taken. */
12112 	tcp->tcp_csuna = tcp->tcp_snxt;
12113 
12114 	notsack_blk = tcp->tcp_notsack_list;
12115 	while (usable_swnd > 0) {
12116 		mblk_t		*snxt_mp, *tmp_mp;
12117 		tcp_seq		begin = tcp->tcp_sack_snxt;
12118 		tcp_seq		end;
12119 		int32_t		off;
12120 
12121 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12122 			if (SEQ_GT(notsack_blk->end, begin) &&
12123 			    (notsack_blk->sack_cnt >=
12124 			    tcps->tcps_dupack_fast_retransmit)) {
12125 				end = notsack_blk->end;
12126 				if (SEQ_LT(begin, notsack_blk->begin)) {
12127 					begin = notsack_blk->begin;
12128 				}
12129 				break;
12130 			}
12131 		}
12132 		/*
12133 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12134 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12135 		 * set to tcp_cwnd_ssthresh.
12136 		 */
12137 		if (notsack_blk == NULL) {
12138 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12139 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12140 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12141 				ASSERT(tcp->tcp_cwnd > 0);
12142 				return;
12143 			} else {
12144 				usable_swnd = usable_swnd / mss;
12145 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12146 				    MAX(usable_swnd * mss, mss);
12147 				*flags |= TH_XMIT_NEEDED;
12148 				return;
12149 			}
12150 		}
12151 
12152 		/*
12153 		 * Note that we may send more than usable_swnd allows here
12154 		 * because of round off, but no more than 1 MSS of data.
12155 		 */
12156 		seg_len = end - begin;
12157 		if (seg_len > mss)
12158 			seg_len = mss;
12159 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12160 		ASSERT(snxt_mp != NULL);
12161 		/* This should not happen.  Defensive coding again... */
12162 		if (snxt_mp == NULL) {
12163 			return;
12164 		}
12165 
12166 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12167 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12168 		if (xmit_mp == NULL)
12169 			return;
12170 
12171 		usable_swnd -= seg_len;
12172 		tcp->tcp_pipe += seg_len;
12173 		tcp->tcp_sack_snxt = begin + seg_len;
12174 
12175 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12176 
12177 		/*
12178 		 * Update the send timestamp to avoid false retransmission.
12179 		 */
12180 		snxt_mp->b_prev = (mblk_t *)lbolt;
12181 
12182 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12183 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12184 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12185 		/*
12186 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12187 		 * This happens when new data sent during fast recovery is
12188 		 * also lost.  If TCP retransmits those new data, it needs
12189 		 * to extend SACK recover phase to avoid starting another
12190 		 * fast retransmit/recovery unnecessarily.
12191 		 */
12192 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12193 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12194 		}
12195 	}
12196 }
12197 
12198 /*
12199  * This function handles policy checking at TCP level for non-hard_bound/
12200  * detached connections.
12201  */
12202 static boolean_t
12203 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12204     boolean_t secure, boolean_t mctl_present)
12205 {
12206 	ipsec_latch_t *ipl = NULL;
12207 	ipsec_action_t *act = NULL;
12208 	mblk_t *data_mp;
12209 	ipsec_in_t *ii;
12210 	const char *reason;
12211 	kstat_named_t *counter;
12212 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12213 	ipsec_stack_t	*ipss;
12214 	ip_stack_t	*ipst;
12215 
12216 	ASSERT(mctl_present || !secure);
12217 
12218 	ASSERT((ipha == NULL && ip6h != NULL) ||
12219 	    (ip6h == NULL && ipha != NULL));
12220 
12221 	/*
12222 	 * We don't necessarily have an ipsec_in_act action to verify
12223 	 * policy because of assymetrical policy where we have only
12224 	 * outbound policy and no inbound policy (possible with global
12225 	 * policy).
12226 	 */
12227 	if (!secure) {
12228 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12229 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12230 			return (B_TRUE);
12231 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12232 		    "tcp_check_policy", ipha, ip6h, secure,
12233 		    tcps->tcps_netstack);
12234 		ipss = tcps->tcps_netstack->netstack_ipsec;
12235 
12236 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12237 		    DROPPER(ipss, ipds_tcp_clear),
12238 		    &tcps->tcps_dropper);
12239 		return (B_FALSE);
12240 	}
12241 
12242 	/*
12243 	 * We have a secure packet.
12244 	 */
12245 	if (act == NULL) {
12246 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12247 		    "tcp_check_policy", ipha, ip6h, secure,
12248 		    tcps->tcps_netstack);
12249 		ipss = tcps->tcps_netstack->netstack_ipsec;
12250 
12251 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12252 		    DROPPER(ipss, ipds_tcp_secure),
12253 		    &tcps->tcps_dropper);
12254 		return (B_FALSE);
12255 	}
12256 
12257 	/*
12258 	 * XXX This whole routine is currently incorrect.  ipl should
12259 	 * be set to the latch pointer, but is currently not set, so
12260 	 * we initialize it to NULL to avoid picking up random garbage.
12261 	 */
12262 	if (ipl == NULL)
12263 		return (B_TRUE);
12264 
12265 	data_mp = first_mp->b_cont;
12266 
12267 	ii = (ipsec_in_t *)first_mp->b_rptr;
12268 
12269 	ipst = tcps->tcps_netstack->netstack_ip;
12270 
12271 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12272 	    &counter, tcp->tcp_connp)) {
12273 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12274 		return (B_TRUE);
12275 	}
12276 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12277 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12278 	    reason);
12279 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12280 
12281 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12282 	    &tcps->tcps_dropper);
12283 	return (B_FALSE);
12284 }
12285 
12286 /*
12287  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12288  * retransmission after a timeout.
12289  *
12290  * To limit the number of duplicate segments, we limit the number of segment
12291  * to be sent in one time to tcp_snd_burst, the burst variable.
12292  */
12293 static void
12294 tcp_ss_rexmit(tcp_t *tcp)
12295 {
12296 	uint32_t	snxt;
12297 	uint32_t	smax;
12298 	int32_t		win;
12299 	int32_t		mss;
12300 	int32_t		off;
12301 	int32_t		burst = tcp->tcp_snd_burst;
12302 	mblk_t		*snxt_mp;
12303 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12304 
12305 	/*
12306 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12307 	 * all unack'ed segments.
12308 	 */
12309 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12310 		smax = tcp->tcp_rexmit_max;
12311 		snxt = tcp->tcp_rexmit_nxt;
12312 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12313 			snxt = tcp->tcp_suna;
12314 		}
12315 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12316 		win -= snxt - tcp->tcp_suna;
12317 		mss = tcp->tcp_mss;
12318 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12319 
12320 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12321 		    (burst > 0) && (snxt_mp != NULL)) {
12322 			mblk_t	*xmit_mp;
12323 			mblk_t	*old_snxt_mp = snxt_mp;
12324 			uint32_t cnt = mss;
12325 
12326 			if (win < cnt) {
12327 				cnt = win;
12328 			}
12329 			if (SEQ_GT(snxt + cnt, smax)) {
12330 				cnt = smax - snxt;
12331 			}
12332 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12333 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12334 			if (xmit_mp == NULL)
12335 				return;
12336 
12337 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12338 
12339 			snxt += cnt;
12340 			win -= cnt;
12341 			/*
12342 			 * Update the send timestamp to avoid false
12343 			 * retransmission.
12344 			 */
12345 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12346 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12347 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12348 
12349 			tcp->tcp_rexmit_nxt = snxt;
12350 			burst--;
12351 		}
12352 		/*
12353 		 * If we have transmitted all we have at the time
12354 		 * we started the retranmission, we can leave
12355 		 * the rest of the job to tcp_wput_data().  But we
12356 		 * need to check the send window first.  If the
12357 		 * win is not 0, go on with tcp_wput_data().
12358 		 */
12359 		if (SEQ_LT(snxt, smax) || win == 0) {
12360 			return;
12361 		}
12362 	}
12363 	/* Only call tcp_wput_data() if there is data to be sent. */
12364 	if (tcp->tcp_unsent) {
12365 		tcp_wput_data(tcp, NULL, B_FALSE);
12366 	}
12367 }
12368 
12369 /*
12370  * Process all TCP option in SYN segment.  Note that this function should
12371  * be called after tcp_adapt_ire() is called so that the necessary info
12372  * from IRE is already set in the tcp structure.
12373  *
12374  * This function sets up the correct tcp_mss value according to the
12375  * MSS option value and our header size.  It also sets up the window scale
12376  * and timestamp values, and initialize SACK info blocks.  But it does not
12377  * change receive window size after setting the tcp_mss value.  The caller
12378  * should do the appropriate change.
12379  */
12380 void
12381 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12382 {
12383 	int options;
12384 	tcp_opt_t tcpopt;
12385 	uint32_t mss_max;
12386 	char *tmp_tcph;
12387 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12388 
12389 	tcpopt.tcp = NULL;
12390 	options = tcp_parse_options(tcph, &tcpopt);
12391 
12392 	/*
12393 	 * Process MSS option.  Note that MSS option value does not account
12394 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12395 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12396 	 * IPv6.
12397 	 */
12398 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12399 		if (tcp->tcp_ipversion == IPV4_VERSION)
12400 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12401 		else
12402 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12403 	} else {
12404 		if (tcp->tcp_ipversion == IPV4_VERSION)
12405 			mss_max = tcps->tcps_mss_max_ipv4;
12406 		else
12407 			mss_max = tcps->tcps_mss_max_ipv6;
12408 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12409 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12410 		else if (tcpopt.tcp_opt_mss > mss_max)
12411 			tcpopt.tcp_opt_mss = mss_max;
12412 	}
12413 
12414 	/* Process Window Scale option. */
12415 	if (options & TCP_OPT_WSCALE_PRESENT) {
12416 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12417 		tcp->tcp_snd_ws_ok = B_TRUE;
12418 	} else {
12419 		tcp->tcp_snd_ws = B_FALSE;
12420 		tcp->tcp_snd_ws_ok = B_FALSE;
12421 		tcp->tcp_rcv_ws = B_FALSE;
12422 	}
12423 
12424 	/* Process Timestamp option. */
12425 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12426 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12427 		tmp_tcph = (char *)tcp->tcp_tcph;
12428 
12429 		tcp->tcp_snd_ts_ok = B_TRUE;
12430 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12431 		tcp->tcp_last_rcv_lbolt = lbolt64;
12432 		ASSERT(OK_32PTR(tmp_tcph));
12433 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12434 
12435 		/* Fill in our template header with basic timestamp option. */
12436 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12437 		tmp_tcph[0] = TCPOPT_NOP;
12438 		tmp_tcph[1] = TCPOPT_NOP;
12439 		tmp_tcph[2] = TCPOPT_TSTAMP;
12440 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12441 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12442 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12443 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12444 	} else {
12445 		tcp->tcp_snd_ts_ok = B_FALSE;
12446 	}
12447 
12448 	/*
12449 	 * Process SACK options.  If SACK is enabled for this connection,
12450 	 * then allocate the SACK info structure.  Note the following ways
12451 	 * when tcp_snd_sack_ok is set to true.
12452 	 *
12453 	 * For active connection: in tcp_adapt_ire() called in
12454 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12455 	 * is checked.
12456 	 *
12457 	 * For passive connection: in tcp_adapt_ire() called in
12458 	 * tcp_accept_comm().
12459 	 *
12460 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12461 	 * That check makes sure that if we did not send a SACK OK option,
12462 	 * we will not enable SACK for this connection even though the other
12463 	 * side sends us SACK OK option.  For active connection, the SACK
12464 	 * info structure has already been allocated.  So we need to free
12465 	 * it if SACK is disabled.
12466 	 */
12467 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12468 	    (tcp->tcp_snd_sack_ok ||
12469 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12470 		/* This should be true only in the passive case. */
12471 		if (tcp->tcp_sack_info == NULL) {
12472 			ASSERT(TCP_IS_DETACHED(tcp));
12473 			tcp->tcp_sack_info =
12474 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12475 		}
12476 		if (tcp->tcp_sack_info == NULL) {
12477 			tcp->tcp_snd_sack_ok = B_FALSE;
12478 		} else {
12479 			tcp->tcp_snd_sack_ok = B_TRUE;
12480 			if (tcp->tcp_snd_ts_ok) {
12481 				tcp->tcp_max_sack_blk = 3;
12482 			} else {
12483 				tcp->tcp_max_sack_blk = 4;
12484 			}
12485 		}
12486 	} else {
12487 		/*
12488 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12489 		 * no SACK info will be used for this
12490 		 * connection.  This assumes that SACK usage
12491 		 * permission is negotiated.  This may need
12492 		 * to be changed once this is clarified.
12493 		 */
12494 		if (tcp->tcp_sack_info != NULL) {
12495 			ASSERT(tcp->tcp_notsack_list == NULL);
12496 			kmem_cache_free(tcp_sack_info_cache,
12497 			    tcp->tcp_sack_info);
12498 			tcp->tcp_sack_info = NULL;
12499 		}
12500 		tcp->tcp_snd_sack_ok = B_FALSE;
12501 	}
12502 
12503 	/*
12504 	 * Now we know the exact TCP/IP header length, subtract
12505 	 * that from tcp_mss to get our side's MSS.
12506 	 */
12507 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12508 	/*
12509 	 * Here we assume that the other side's header size will be equal to
12510 	 * our header size.  We calculate the real MSS accordingly.  Need to
12511 	 * take into additional stuffs IPsec puts in.
12512 	 *
12513 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12514 	 */
12515 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12516 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12517 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12518 
12519 	/*
12520 	 * Set MSS to the smaller one of both ends of the connection.
12521 	 * We should not have called tcp_mss_set() before, but our
12522 	 * side of the MSS should have been set to a proper value
12523 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12524 	 * STREAM head parameters properly.
12525 	 *
12526 	 * If we have a larger-than-16-bit window but the other side
12527 	 * didn't want to do window scale, tcp_rwnd_set() will take
12528 	 * care of that.
12529 	 */
12530 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12531 }
12532 
12533 /*
12534  * Sends the T_CONN_IND to the listener. The caller calls this
12535  * functions via squeue to get inside the listener's perimeter
12536  * once the 3 way hand shake is done a T_CONN_IND needs to be
12537  * sent. As an optimization, the caller can call this directly
12538  * if listener's perimeter is same as eager's.
12539  */
12540 /* ARGSUSED */
12541 void
12542 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12543 {
12544 	conn_t			*lconnp = (conn_t *)arg;
12545 	tcp_t			*listener = lconnp->conn_tcp;
12546 	tcp_t			*tcp;
12547 	struct T_conn_ind	*conn_ind;
12548 	ipaddr_t 		*addr_cache;
12549 	boolean_t		need_send_conn_ind = B_FALSE;
12550 	tcp_stack_t		*tcps = listener->tcp_tcps;
12551 
12552 	/* retrieve the eager */
12553 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12554 	ASSERT(conn_ind->OPT_offset != 0 &&
12555 	    conn_ind->OPT_length == sizeof (intptr_t));
12556 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12557 	    conn_ind->OPT_length);
12558 
12559 	/*
12560 	 * TLI/XTI applications will get confused by
12561 	 * sending eager as an option since it violates
12562 	 * the option semantics. So remove the eager as
12563 	 * option since TLI/XTI app doesn't need it anyway.
12564 	 */
12565 	if (!TCP_IS_SOCKET(listener)) {
12566 		conn_ind->OPT_length = 0;
12567 		conn_ind->OPT_offset = 0;
12568 	}
12569 	if (listener->tcp_state == TCPS_CLOSED ||
12570 	    TCP_IS_DETACHED(listener)) {
12571 		/*
12572 		 * If listener has closed, it would have caused a
12573 		 * a cleanup/blowoff to happen for the eager. We
12574 		 * just need to return.
12575 		 */
12576 		freemsg(mp);
12577 		return;
12578 	}
12579 
12580 
12581 	/*
12582 	 * if the conn_req_q is full defer passing up the
12583 	 * T_CONN_IND until space is availabe after t_accept()
12584 	 * processing
12585 	 */
12586 	mutex_enter(&listener->tcp_eager_lock);
12587 
12588 	/*
12589 	 * Take the eager out, if it is in the list of droppable eagers
12590 	 * as we are here because the 3W handshake is over.
12591 	 */
12592 	MAKE_UNDROPPABLE(tcp);
12593 
12594 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12595 		tcp_t *tail;
12596 
12597 		/*
12598 		 * The eager already has an extra ref put in tcp_rput_data
12599 		 * so that it stays till accept comes back even though it
12600 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12601 		 */
12602 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12603 		listener->tcp_conn_req_cnt_q0--;
12604 		listener->tcp_conn_req_cnt_q++;
12605 
12606 		/* Move from SYN_RCVD to ESTABLISHED list  */
12607 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12608 		    tcp->tcp_eager_prev_q0;
12609 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12610 		    tcp->tcp_eager_next_q0;
12611 		tcp->tcp_eager_prev_q0 = NULL;
12612 		tcp->tcp_eager_next_q0 = NULL;
12613 
12614 		/*
12615 		 * Insert at end of the queue because sockfs
12616 		 * sends down T_CONN_RES in chronological
12617 		 * order. Leaving the older conn indications
12618 		 * at front of the queue helps reducing search
12619 		 * time.
12620 		 */
12621 		tail = listener->tcp_eager_last_q;
12622 		if (tail != NULL)
12623 			tail->tcp_eager_next_q = tcp;
12624 		else
12625 			listener->tcp_eager_next_q = tcp;
12626 		listener->tcp_eager_last_q = tcp;
12627 		tcp->tcp_eager_next_q = NULL;
12628 		/*
12629 		 * Delay sending up the T_conn_ind until we are
12630 		 * done with the eager. Once we have have sent up
12631 		 * the T_conn_ind, the accept can potentially complete
12632 		 * any time and release the refhold we have on the eager.
12633 		 */
12634 		need_send_conn_ind = B_TRUE;
12635 	} else {
12636 		/*
12637 		 * Defer connection on q0 and set deferred
12638 		 * connection bit true
12639 		 */
12640 		tcp->tcp_conn_def_q0 = B_TRUE;
12641 
12642 		/* take tcp out of q0 ... */
12643 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12644 		    tcp->tcp_eager_next_q0;
12645 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12646 		    tcp->tcp_eager_prev_q0;
12647 
12648 		/* ... and place it at the end of q0 */
12649 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12650 		tcp->tcp_eager_next_q0 = listener;
12651 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12652 		listener->tcp_eager_prev_q0 = tcp;
12653 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12654 	}
12655 
12656 	/* we have timed out before */
12657 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12658 		tcp->tcp_syn_rcvd_timeout = 0;
12659 		listener->tcp_syn_rcvd_timeout--;
12660 		if (listener->tcp_syn_defense &&
12661 		    listener->tcp_syn_rcvd_timeout <=
12662 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12663 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12664 		    listener->tcp_last_rcv_lbolt)) {
12665 			/*
12666 			 * Turn off the defense mode if we
12667 			 * believe the SYN attack is over.
12668 			 */
12669 			listener->tcp_syn_defense = B_FALSE;
12670 			if (listener->tcp_ip_addr_cache) {
12671 				kmem_free((void *)listener->tcp_ip_addr_cache,
12672 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12673 				listener->tcp_ip_addr_cache = NULL;
12674 			}
12675 		}
12676 	}
12677 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12678 	if (addr_cache != NULL) {
12679 		/*
12680 		 * We have finished a 3-way handshake with this
12681 		 * remote host. This proves the IP addr is good.
12682 		 * Cache it!
12683 		 */
12684 		addr_cache[IP_ADDR_CACHE_HASH(
12685 		    tcp->tcp_remote)] = tcp->tcp_remote;
12686 	}
12687 	mutex_exit(&listener->tcp_eager_lock);
12688 	if (need_send_conn_ind) {
12689 		if (IPCL_IS_NONSTR(lconnp)) {
12690 			ASSERT(tcp->tcp_listener == listener);
12691 			ASSERT(tcp->tcp_saved_listener == listener);
12692 			if ((*lconnp->conn_upcalls->su_newconn)
12693 			    (lconnp->conn_upper_handle,
12694 			    (sock_lower_handle_t)tcp->tcp_connp,
12695 			    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
12696 			    &tcp->tcp_connp->conn_upcalls) != NULL) {
12697 				/*
12698 				 * Keep the message around
12699 				 * in case of fallback
12700 				 */
12701 				tcp->tcp_conn.tcp_eager_conn_ind = mp;
12702 			} else {
12703 				freemsg(mp);
12704 			}
12705 		} else {
12706 			putnext(listener->tcp_rq, mp);
12707 		}
12708 	}
12709 }
12710 
12711 mblk_t *
12712 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12713     uint_t *ifindexp, ip6_pkt_t *ippp)
12714 {
12715 	ip_pktinfo_t	*pinfo;
12716 	ip6_t		*ip6h;
12717 	uchar_t		*rptr;
12718 	mblk_t		*first_mp = mp;
12719 	boolean_t	mctl_present = B_FALSE;
12720 	uint_t 		ifindex = 0;
12721 	ip6_pkt_t	ipp;
12722 	uint_t		ipvers;
12723 	uint_t		ip_hdr_len;
12724 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12725 
12726 	rptr = mp->b_rptr;
12727 	ASSERT(OK_32PTR(rptr));
12728 	ASSERT(tcp != NULL);
12729 	ipp.ipp_fields = 0;
12730 
12731 	switch DB_TYPE(mp) {
12732 	case M_CTL:
12733 		mp = mp->b_cont;
12734 		if (mp == NULL) {
12735 			freemsg(first_mp);
12736 			return (NULL);
12737 		}
12738 		if (DB_TYPE(mp) != M_DATA) {
12739 			freemsg(first_mp);
12740 			return (NULL);
12741 		}
12742 		mctl_present = B_TRUE;
12743 		break;
12744 	case M_DATA:
12745 		break;
12746 	default:
12747 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12748 		freemsg(mp);
12749 		return (NULL);
12750 	}
12751 	ipvers = IPH_HDR_VERSION(rptr);
12752 	if (ipvers == IPV4_VERSION) {
12753 		if (tcp == NULL) {
12754 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12755 			goto done;
12756 		}
12757 
12758 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12759 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12760 
12761 		/*
12762 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12763 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12764 		 */
12765 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12766 		    mctl_present) {
12767 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12768 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12769 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12770 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12771 				ipp.ipp_fields |= IPPF_IFINDEX;
12772 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12773 				ifindex = pinfo->ip_pkt_ifindex;
12774 			}
12775 			freeb(first_mp);
12776 			mctl_present = B_FALSE;
12777 		}
12778 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12779 	} else {
12780 		ip6h = (ip6_t *)rptr;
12781 
12782 		ASSERT(ipvers == IPV6_VERSION);
12783 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12784 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12785 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12786 
12787 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12788 			uint8_t	nexthdrp;
12789 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12790 
12791 			/* Look for ifindex information */
12792 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12793 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12794 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12795 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12796 					freemsg(first_mp);
12797 					return (NULL);
12798 				}
12799 
12800 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12801 					ASSERT(ip6i->ip6i_ifindex != 0);
12802 					ipp.ipp_fields |= IPPF_IFINDEX;
12803 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12804 					ifindex = ip6i->ip6i_ifindex;
12805 				}
12806 				rptr = (uchar_t *)&ip6i[1];
12807 				mp->b_rptr = rptr;
12808 				if (rptr == mp->b_wptr) {
12809 					mblk_t *mp1;
12810 					mp1 = mp->b_cont;
12811 					freeb(mp);
12812 					mp = mp1;
12813 					rptr = mp->b_rptr;
12814 				}
12815 				if (MBLKL(mp) < IPV6_HDR_LEN +
12816 				    sizeof (tcph_t)) {
12817 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12818 					freemsg(first_mp);
12819 					return (NULL);
12820 				}
12821 				ip6h = (ip6_t *)rptr;
12822 			}
12823 
12824 			/*
12825 			 * Find any potentially interesting extension headers
12826 			 * as well as the length of the IPv6 + extension
12827 			 * headers.
12828 			 */
12829 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12830 			/* Verify if this is a TCP packet */
12831 			if (nexthdrp != IPPROTO_TCP) {
12832 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12833 				freemsg(first_mp);
12834 				return (NULL);
12835 			}
12836 		} else {
12837 			ip_hdr_len = IPV6_HDR_LEN;
12838 		}
12839 	}
12840 
12841 done:
12842 	if (ipversp != NULL)
12843 		*ipversp = ipvers;
12844 	if (ip_hdr_lenp != NULL)
12845 		*ip_hdr_lenp = ip_hdr_len;
12846 	if (ippp != NULL)
12847 		*ippp = ipp;
12848 	if (ifindexp != NULL)
12849 		*ifindexp = ifindex;
12850 	if (mctl_present) {
12851 		freeb(first_mp);
12852 	}
12853 	return (mp);
12854 }
12855 
12856 /*
12857  * Handle M_DATA messages from IP. Its called directly from IP via
12858  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12859  * in this path.
12860  *
12861  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12862  * v4 and v6), we are called through tcp_input() and a M_CTL can
12863  * be present for options but tcp_find_pktinfo() deals with it. We
12864  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12865  *
12866  * The first argument is always the connp/tcp to which the mp belongs.
12867  * There are no exceptions to this rule. The caller has already put
12868  * a reference on this connp/tcp and once tcp_rput_data() returns,
12869  * the squeue will do the refrele.
12870  *
12871  * The TH_SYN for the listener directly go to tcp_conn_request via
12872  * squeue.
12873  *
12874  * sqp: NULL = recursive, sqp != NULL means called from squeue
12875  */
12876 void
12877 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12878 {
12879 	int32_t		bytes_acked;
12880 	int32_t		gap;
12881 	mblk_t		*mp1;
12882 	uint_t		flags;
12883 	uint32_t	new_swnd = 0;
12884 	uchar_t		*iphdr;
12885 	uchar_t		*rptr;
12886 	int32_t		rgap;
12887 	uint32_t	seg_ack;
12888 	int		seg_len;
12889 	uint_t		ip_hdr_len;
12890 	uint32_t	seg_seq;
12891 	tcph_t		*tcph;
12892 	int		urp;
12893 	tcp_opt_t	tcpopt;
12894 	uint_t		ipvers;
12895 	ip6_pkt_t	ipp;
12896 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12897 	uint32_t	cwnd;
12898 	uint32_t	add;
12899 	int		npkt;
12900 	int		mss;
12901 	conn_t		*connp = (conn_t *)arg;
12902 	squeue_t	*sqp = (squeue_t *)arg2;
12903 	tcp_t		*tcp = connp->conn_tcp;
12904 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12905 
12906 	/*
12907 	 * RST from fused tcp loopback peer should trigger an unfuse.
12908 	 */
12909 	if (tcp->tcp_fused) {
12910 		TCP_STAT(tcps, tcp_fusion_aborted);
12911 		tcp_unfuse(tcp);
12912 	}
12913 
12914 	iphdr = mp->b_rptr;
12915 	rptr = mp->b_rptr;
12916 	ASSERT(OK_32PTR(rptr));
12917 
12918 	/*
12919 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12920 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12921 	 * necessary information.
12922 	 */
12923 	if (IPCL_IS_TCP4(connp)) {
12924 		ipvers = IPV4_VERSION;
12925 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12926 	} else {
12927 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
12928 		    NULL, &ipp);
12929 		if (mp == NULL) {
12930 			TCP_STAT(tcps, tcp_rput_v6_error);
12931 			return;
12932 		}
12933 		iphdr = mp->b_rptr;
12934 		rptr = mp->b_rptr;
12935 	}
12936 	ASSERT(DB_TYPE(mp) == M_DATA);
12937 	ASSERT(mp->b_next == NULL);
12938 
12939 	tcph = (tcph_t *)&rptr[ip_hdr_len];
12940 	seg_seq = ABE32_TO_U32(tcph->th_seq);
12941 	seg_ack = ABE32_TO_U32(tcph->th_ack);
12942 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
12943 	seg_len = (int)(mp->b_wptr - rptr) -
12944 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
12945 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
12946 		do {
12947 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
12948 			    (uintptr_t)INT_MAX);
12949 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
12950 		} while ((mp1 = mp1->b_cont) != NULL &&
12951 		    mp1->b_datap->db_type == M_DATA);
12952 	}
12953 
12954 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
12955 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
12956 		    seg_len, tcph);
12957 		return;
12958 	}
12959 
12960 	if (sqp != NULL) {
12961 		/*
12962 		 * This is the correct place to update tcp_last_recv_time. Note
12963 		 * that it is also updated for tcp structure that belongs to
12964 		 * global and listener queues which do not really need updating.
12965 		 * But that should not cause any harm.  And it is updated for
12966 		 * all kinds of incoming segments, not only for data segments.
12967 		 */
12968 		tcp->tcp_last_recv_time = lbolt;
12969 	}
12970 
12971 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
12972 
12973 	BUMP_LOCAL(tcp->tcp_ibsegs);
12974 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
12975 
12976 	if ((flags & TH_URG) && sqp != NULL) {
12977 		/*
12978 		 * TCP can't handle urgent pointers that arrive before
12979 		 * the connection has been accept()ed since it can't
12980 		 * buffer OOB data.  Discard segment if this happens.
12981 		 *
12982 		 * We can't just rely on a non-null tcp_listener to indicate
12983 		 * that the accept() has completed since unlinking of the
12984 		 * eager and completion of the accept are not atomic.
12985 		 * tcp_detached, when it is not set (B_FALSE) indicates
12986 		 * that the accept() has completed.
12987 		 *
12988 		 * Nor can it reassemble urgent pointers, so discard
12989 		 * if it's not the next segment expected.
12990 		 *
12991 		 * Otherwise, collapse chain into one mblk (discard if
12992 		 * that fails).  This makes sure the headers, retransmitted
12993 		 * data, and new data all are in the same mblk.
12994 		 */
12995 		ASSERT(mp != NULL);
12996 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
12997 			freemsg(mp);
12998 			return;
12999 		}
13000 		/* Update pointers into message */
13001 		iphdr = rptr = mp->b_rptr;
13002 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13003 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13004 			/*
13005 			 * Since we can't handle any data with this urgent
13006 			 * pointer that is out of sequence, we expunge
13007 			 * the data.  This allows us to still register
13008 			 * the urgent mark and generate the M_PCSIG,
13009 			 * which we can do.
13010 			 */
13011 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13012 			seg_len = 0;
13013 		}
13014 	}
13015 
13016 	switch (tcp->tcp_state) {
13017 	case TCPS_SYN_SENT:
13018 		if (flags & TH_ACK) {
13019 			/*
13020 			 * Note that our stack cannot send data before a
13021 			 * connection is established, therefore the
13022 			 * following check is valid.  Otherwise, it has
13023 			 * to be changed.
13024 			 */
13025 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13026 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13027 				freemsg(mp);
13028 				if (flags & TH_RST)
13029 					return;
13030 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13031 				    tcp, seg_ack, 0, TH_RST);
13032 				return;
13033 			}
13034 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13035 		}
13036 		if (flags & TH_RST) {
13037 			freemsg(mp);
13038 			if (flags & TH_ACK)
13039 				(void) tcp_clean_death(tcp,
13040 				    ECONNREFUSED, 13);
13041 			return;
13042 		}
13043 		if (!(flags & TH_SYN)) {
13044 			freemsg(mp);
13045 			return;
13046 		}
13047 
13048 		/* Process all TCP options. */
13049 		tcp_process_options(tcp, tcph);
13050 		/*
13051 		 * The following changes our rwnd to be a multiple of the
13052 		 * MIN(peer MSS, our MSS) for performance reason.
13053 		 */
13054 		(void) tcp_rwnd_set(tcp,
13055 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
13056 
13057 		/* Is the other end ECN capable? */
13058 		if (tcp->tcp_ecn_ok) {
13059 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13060 				tcp->tcp_ecn_ok = B_FALSE;
13061 			}
13062 		}
13063 		/*
13064 		 * Clear ECN flags because it may interfere with later
13065 		 * processing.
13066 		 */
13067 		flags &= ~(TH_ECE|TH_CWR);
13068 
13069 		tcp->tcp_irs = seg_seq;
13070 		tcp->tcp_rack = seg_seq;
13071 		tcp->tcp_rnxt = seg_seq + 1;
13072 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13073 		if (!TCP_IS_DETACHED(tcp)) {
13074 			/* Allocate room for SACK options if needed. */
13075 			if (tcp->tcp_snd_sack_ok) {
13076 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13077 				    tcp->tcp_hdr_len +
13078 				    TCPOPT_MAX_SACK_LEN +
13079 				    (tcp->tcp_loopback ? 0 :
13080 				    tcps->tcps_wroff_xtra));
13081 			} else {
13082 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13083 				    tcp->tcp_hdr_len +
13084 				    (tcp->tcp_loopback ? 0 :
13085 				    tcps->tcps_wroff_xtra));
13086 			}
13087 		}
13088 		if (flags & TH_ACK) {
13089 			/*
13090 			 * If we can't get the confirmation upstream, pretend
13091 			 * we didn't even see this one.
13092 			 *
13093 			 * XXX: how can we pretend we didn't see it if we
13094 			 * have updated rnxt et. al.
13095 			 *
13096 			 * For loopback we defer sending up the T_CONN_CON
13097 			 * until after some checks below.
13098 			 */
13099 			mp1 = NULL;
13100 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13101 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13102 				freemsg(mp);
13103 				return;
13104 			}
13105 			/* SYN was acked - making progress */
13106 			if (tcp->tcp_ipversion == IPV6_VERSION)
13107 				tcp->tcp_ip_forward_progress = B_TRUE;
13108 
13109 			/* One for the SYN */
13110 			tcp->tcp_suna = tcp->tcp_iss + 1;
13111 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13112 			tcp->tcp_state = TCPS_ESTABLISHED;
13113 
13114 			/*
13115 			 * If SYN was retransmitted, need to reset all
13116 			 * retransmission info.  This is because this
13117 			 * segment will be treated as a dup ACK.
13118 			 */
13119 			if (tcp->tcp_rexmit) {
13120 				tcp->tcp_rexmit = B_FALSE;
13121 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13122 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13123 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13124 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13125 				tcp->tcp_ms_we_have_waited = 0;
13126 
13127 				/*
13128 				 * Set tcp_cwnd back to 1 MSS, per
13129 				 * recommendation from
13130 				 * draft-floyd-incr-init-win-01.txt,
13131 				 * Increasing TCP's Initial Window.
13132 				 */
13133 				tcp->tcp_cwnd = tcp->tcp_mss;
13134 			}
13135 
13136 			tcp->tcp_swl1 = seg_seq;
13137 			tcp->tcp_swl2 = seg_ack;
13138 
13139 			new_swnd = BE16_TO_U16(tcph->th_win);
13140 			tcp->tcp_swnd = new_swnd;
13141 			if (new_swnd > tcp->tcp_max_swnd)
13142 				tcp->tcp_max_swnd = new_swnd;
13143 
13144 			/*
13145 			 * Always send the three-way handshake ack immediately
13146 			 * in order to make the connection complete as soon as
13147 			 * possible on the accepting host.
13148 			 */
13149 			flags |= TH_ACK_NEEDED;
13150 
13151 			/*
13152 			 * Special case for loopback.  At this point we have
13153 			 * received SYN-ACK from the remote endpoint.  In
13154 			 * order to ensure that both endpoints reach the
13155 			 * fused state prior to any data exchange, the final
13156 			 * ACK needs to be sent before we indicate T_CONN_CON
13157 			 * to the module upstream.
13158 			 */
13159 			if (tcp->tcp_loopback) {
13160 				mblk_t *ack_mp;
13161 
13162 				ASSERT(!tcp->tcp_unfusable);
13163 				ASSERT(mp1 != NULL);
13164 				/*
13165 				 * For loopback, we always get a pure SYN-ACK
13166 				 * and only need to send back the final ACK
13167 				 * with no data (this is because the other
13168 				 * tcp is ours and we don't do T/TCP).  This
13169 				 * final ACK triggers the passive side to
13170 				 * perform fusion in ESTABLISHED state.
13171 				 */
13172 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13173 					if (tcp->tcp_ack_tid != 0) {
13174 						(void) TCP_TIMER_CANCEL(tcp,
13175 						    tcp->tcp_ack_tid);
13176 						tcp->tcp_ack_tid = 0;
13177 					}
13178 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13179 					BUMP_LOCAL(tcp->tcp_obsegs);
13180 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13181 
13182 					if (!IPCL_IS_NONSTR(connp)) {
13183 						/* Send up T_CONN_CON */
13184 						putnext(tcp->tcp_rq, mp1);
13185 					} else {
13186 						(*connp->conn_upcalls->
13187 						    su_connected)
13188 						    (connp->conn_upper_handle,
13189 						    tcp->tcp_connid,
13190 						    DB_CRED(mp1),
13191 						    DB_CPID(mp1));
13192 						freemsg(mp1);
13193 					}
13194 
13195 					freemsg(mp);
13196 					return;
13197 				}
13198 				/*
13199 				 * Forget fusion; we need to handle more
13200 				 * complex cases below.  Send the deferred
13201 				 * T_CONN_CON message upstream and proceed
13202 				 * as usual.  Mark this tcp as not capable
13203 				 * of fusion.
13204 				 */
13205 				TCP_STAT(tcps, tcp_fusion_unfusable);
13206 				tcp->tcp_unfusable = B_TRUE;
13207 				if (!IPCL_IS_NONSTR(connp)) {
13208 					putnext(tcp->tcp_rq, mp1);
13209 				} else {
13210 					(*connp->conn_upcalls->su_connected)
13211 					    (connp->conn_upper_handle,
13212 					    tcp->tcp_connid, DB_CRED(mp1),
13213 					    DB_CPID(mp1));
13214 					freemsg(mp1);
13215 				}
13216 			}
13217 
13218 			/*
13219 			 * Check to see if there is data to be sent.  If
13220 			 * yes, set the transmit flag.  Then check to see
13221 			 * if received data processing needs to be done.
13222 			 * If not, go straight to xmit_check.  This short
13223 			 * cut is OK as we don't support T/TCP.
13224 			 */
13225 			if (tcp->tcp_unsent)
13226 				flags |= TH_XMIT_NEEDED;
13227 
13228 			if (seg_len == 0 && !(flags & TH_URG)) {
13229 				freemsg(mp);
13230 				goto xmit_check;
13231 			}
13232 
13233 			flags &= ~TH_SYN;
13234 			seg_seq++;
13235 			break;
13236 		}
13237 		tcp->tcp_state = TCPS_SYN_RCVD;
13238 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13239 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13240 		if (mp1) {
13241 			DB_CPID(mp1) = tcp->tcp_cpid;
13242 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13243 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13244 		}
13245 		freemsg(mp);
13246 		return;
13247 	case TCPS_SYN_RCVD:
13248 		if (flags & TH_ACK) {
13249 			/*
13250 			 * In this state, a SYN|ACK packet is either bogus
13251 			 * because the other side must be ACKing our SYN which
13252 			 * indicates it has seen the ACK for their SYN and
13253 			 * shouldn't retransmit it or we're crossing SYNs
13254 			 * on active open.
13255 			 */
13256 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13257 				freemsg(mp);
13258 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13259 				    tcp, seg_ack, 0, TH_RST);
13260 				return;
13261 			}
13262 			/*
13263 			 * NOTE: RFC 793 pg. 72 says this should be
13264 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13265 			 * but that would mean we have an ack that ignored
13266 			 * our SYN.
13267 			 */
13268 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13269 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13270 				freemsg(mp);
13271 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13272 				    tcp, seg_ack, 0, TH_RST);
13273 				return;
13274 			}
13275 		}
13276 		break;
13277 	case TCPS_LISTEN:
13278 		/*
13279 		 * Only a TLI listener can come through this path when a
13280 		 * acceptor is going back to be a listener and a packet
13281 		 * for the acceptor hits the classifier. For a socket
13282 		 * listener, this can never happen because a listener
13283 		 * can never accept connection on itself and hence a
13284 		 * socket acceptor can not go back to being a listener.
13285 		 */
13286 		ASSERT(!TCP_IS_SOCKET(tcp));
13287 		/*FALLTHRU*/
13288 	case TCPS_CLOSED:
13289 	case TCPS_BOUND: {
13290 		conn_t	*new_connp;
13291 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13292 
13293 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13294 		if (new_connp != NULL) {
13295 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13296 			return;
13297 		}
13298 		/* We failed to classify. For now just drop the packet */
13299 		freemsg(mp);
13300 		return;
13301 	}
13302 	case TCPS_IDLE:
13303 		/*
13304 		 * Handle the case where the tcp_clean_death() has happened
13305 		 * on a connection (application hasn't closed yet) but a packet
13306 		 * was already queued on squeue before tcp_clean_death()
13307 		 * was processed. Calling tcp_clean_death() twice on same
13308 		 * connection can result in weird behaviour.
13309 		 */
13310 		freemsg(mp);
13311 		return;
13312 	default:
13313 		break;
13314 	}
13315 
13316 	/*
13317 	 * Already on the correct queue/perimeter.
13318 	 * If this is a detached connection and not an eager
13319 	 * connection hanging off a listener then new data
13320 	 * (past the FIN) will cause a reset.
13321 	 * We do a special check here where it
13322 	 * is out of the main line, rather than check
13323 	 * if we are detached every time we see new
13324 	 * data down below.
13325 	 */
13326 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13327 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13328 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13329 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13330 
13331 		freemsg(mp);
13332 		/*
13333 		 * This could be an SSL closure alert. We're detached so just
13334 		 * acknowledge it this last time.
13335 		 */
13336 		if (tcp->tcp_kssl_ctx != NULL) {
13337 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13338 			tcp->tcp_kssl_ctx = NULL;
13339 
13340 			tcp->tcp_rnxt += seg_len;
13341 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13342 			flags |= TH_ACK_NEEDED;
13343 			goto ack_check;
13344 		}
13345 
13346 		tcp_xmit_ctl("new data when detached", tcp,
13347 		    tcp->tcp_snxt, 0, TH_RST);
13348 		(void) tcp_clean_death(tcp, EPROTO, 12);
13349 		return;
13350 	}
13351 
13352 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13353 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13354 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13355 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13356 
13357 	if (tcp->tcp_snd_ts_ok) {
13358 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13359 			/*
13360 			 * This segment is not acceptable.
13361 			 * Drop it and send back an ACK.
13362 			 */
13363 			freemsg(mp);
13364 			flags |= TH_ACK_NEEDED;
13365 			goto ack_check;
13366 		}
13367 	} else if (tcp->tcp_snd_sack_ok) {
13368 		ASSERT(tcp->tcp_sack_info != NULL);
13369 		tcpopt.tcp = tcp;
13370 		/*
13371 		 * SACK info in already updated in tcp_parse_options.  Ignore
13372 		 * all other TCP options...
13373 		 */
13374 		(void) tcp_parse_options(tcph, &tcpopt);
13375 	}
13376 try_again:;
13377 	mss = tcp->tcp_mss;
13378 	gap = seg_seq - tcp->tcp_rnxt;
13379 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13380 	/*
13381 	 * gap is the amount of sequence space between what we expect to see
13382 	 * and what we got for seg_seq.  A positive value for gap means
13383 	 * something got lost.  A negative value means we got some old stuff.
13384 	 */
13385 	if (gap < 0) {
13386 		/* Old stuff present.  Is the SYN in there? */
13387 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13388 		    (seg_len != 0)) {
13389 			flags &= ~TH_SYN;
13390 			seg_seq++;
13391 			urp--;
13392 			/* Recompute the gaps after noting the SYN. */
13393 			goto try_again;
13394 		}
13395 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13396 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13397 		    (seg_len > -gap ? -gap : seg_len));
13398 		/* Remove the old stuff from seg_len. */
13399 		seg_len += gap;
13400 		/*
13401 		 * Anything left?
13402 		 * Make sure to check for unack'd FIN when rest of data
13403 		 * has been previously ack'd.
13404 		 */
13405 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13406 			/*
13407 			 * Resets are only valid if they lie within our offered
13408 			 * window.  If the RST bit is set, we just ignore this
13409 			 * segment.
13410 			 */
13411 			if (flags & TH_RST) {
13412 				freemsg(mp);
13413 				return;
13414 			}
13415 
13416 			/*
13417 			 * The arriving of dup data packets indicate that we
13418 			 * may have postponed an ack for too long, or the other
13419 			 * side's RTT estimate is out of shape. Start acking
13420 			 * more often.
13421 			 */
13422 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13423 			    tcp->tcp_rack_cnt >= 1 &&
13424 			    tcp->tcp_rack_abs_max > 2) {
13425 				tcp->tcp_rack_abs_max--;
13426 			}
13427 			tcp->tcp_rack_cur_max = 1;
13428 
13429 			/*
13430 			 * This segment is "unacceptable".  None of its
13431 			 * sequence space lies within our advertized window.
13432 			 *
13433 			 * Adjust seg_len to the original value for tracing.
13434 			 */
13435 			seg_len -= gap;
13436 			if (tcp->tcp_debug) {
13437 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13438 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13439 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13440 				    "seg_len %d, rnxt %u, snxt %u, %s",
13441 				    gap, rgap, flags, seg_seq, seg_ack,
13442 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13443 				    tcp_display(tcp, NULL,
13444 				    DISP_ADDR_AND_PORT));
13445 			}
13446 
13447 			/*
13448 			 * Arrange to send an ACK in response to the
13449 			 * unacceptable segment per RFC 793 page 69. There
13450 			 * is only one small difference between ours and the
13451 			 * acceptability test in the RFC - we accept ACK-only
13452 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13453 			 * will be generated.
13454 			 *
13455 			 * Note that we have to ACK an ACK-only packet at least
13456 			 * for stacks that send 0-length keep-alives with
13457 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13458 			 * section 4.2.3.6. As long as we don't ever generate
13459 			 * an unacceptable packet in response to an incoming
13460 			 * packet that is unacceptable, it should not cause
13461 			 * "ACK wars".
13462 			 */
13463 			flags |=  TH_ACK_NEEDED;
13464 
13465 			/*
13466 			 * Continue processing this segment in order to use the
13467 			 * ACK information it contains, but skip all other
13468 			 * sequence-number processing.	Processing the ACK
13469 			 * information is necessary in order to
13470 			 * re-synchronize connections that may have lost
13471 			 * synchronization.
13472 			 *
13473 			 * We clear seg_len and flag fields related to
13474 			 * sequence number processing as they are not
13475 			 * to be trusted for an unacceptable segment.
13476 			 */
13477 			seg_len = 0;
13478 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13479 			goto process_ack;
13480 		}
13481 
13482 		/* Fix seg_seq, and chew the gap off the front. */
13483 		seg_seq = tcp->tcp_rnxt;
13484 		urp += gap;
13485 		do {
13486 			mblk_t	*mp2;
13487 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13488 			    (uintptr_t)UINT_MAX);
13489 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13490 			if (gap > 0) {
13491 				mp->b_rptr = mp->b_wptr - gap;
13492 				break;
13493 			}
13494 			mp2 = mp;
13495 			mp = mp->b_cont;
13496 			freeb(mp2);
13497 		} while (gap < 0);
13498 		/*
13499 		 * If the urgent data has already been acknowledged, we
13500 		 * should ignore TH_URG below
13501 		 */
13502 		if (urp < 0)
13503 			flags &= ~TH_URG;
13504 	}
13505 	/*
13506 	 * rgap is the amount of stuff received out of window.  A negative
13507 	 * value is the amount out of window.
13508 	 */
13509 	if (rgap < 0) {
13510 		mblk_t	*mp2;
13511 
13512 		if (tcp->tcp_rwnd == 0) {
13513 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13514 		} else {
13515 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13516 			UPDATE_MIB(&tcps->tcps_mib,
13517 			    tcpInDataPastWinBytes, -rgap);
13518 		}
13519 
13520 		/*
13521 		 * seg_len does not include the FIN, so if more than
13522 		 * just the FIN is out of window, we act like we don't
13523 		 * see it.  (If just the FIN is out of window, rgap
13524 		 * will be zero and we will go ahead and acknowledge
13525 		 * the FIN.)
13526 		 */
13527 		flags &= ~TH_FIN;
13528 
13529 		/* Fix seg_len and make sure there is something left. */
13530 		seg_len += rgap;
13531 		if (seg_len <= 0) {
13532 			/*
13533 			 * Resets are only valid if they lie within our offered
13534 			 * window.  If the RST bit is set, we just ignore this
13535 			 * segment.
13536 			 */
13537 			if (flags & TH_RST) {
13538 				freemsg(mp);
13539 				return;
13540 			}
13541 
13542 			/* Per RFC 793, we need to send back an ACK. */
13543 			flags |= TH_ACK_NEEDED;
13544 
13545 			/*
13546 			 * Send SIGURG as soon as possible i.e. even
13547 			 * if the TH_URG was delivered in a window probe
13548 			 * packet (which will be unacceptable).
13549 			 *
13550 			 * We generate a signal if none has been generated
13551 			 * for this connection or if this is a new urgent
13552 			 * byte. Also send a zero-length "unmarked" message
13553 			 * to inform SIOCATMARK that this is not the mark.
13554 			 *
13555 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13556 			 * is sent up. This plus the check for old data
13557 			 * (gap >= 0) handles the wraparound of the sequence
13558 			 * number space without having to always track the
13559 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13560 			 * this max in its rcv_up variable).
13561 			 *
13562 			 * This prevents duplicate SIGURGS due to a "late"
13563 			 * zero-window probe when the T_EXDATA_IND has already
13564 			 * been sent up.
13565 			 */
13566 			if ((flags & TH_URG) &&
13567 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13568 			    tcp->tcp_urp_last))) {
13569 				if (IPCL_IS_NONSTR(connp)) {
13570 					if (!TCP_IS_DETACHED(tcp)) {
13571 						(*connp->conn_upcalls->
13572 						    su_signal_oob)
13573 						    (connp->conn_upper_handle,
13574 						    urp);
13575 					}
13576 				} else {
13577 					mp1 = allocb(0, BPRI_MED);
13578 					if (mp1 == NULL) {
13579 						freemsg(mp);
13580 						return;
13581 					}
13582 					if (!TCP_IS_DETACHED(tcp) &&
13583 					    !putnextctl1(tcp->tcp_rq,
13584 					    M_PCSIG, SIGURG)) {
13585 						/* Try again on the rexmit. */
13586 						freemsg(mp1);
13587 						freemsg(mp);
13588 						return;
13589 					}
13590 					/*
13591 					 * If the next byte would be the mark
13592 					 * then mark with MARKNEXT else mark
13593 					 * with NOTMARKNEXT.
13594 					 */
13595 					if (gap == 0 && urp == 0)
13596 						mp1->b_flag |= MSGMARKNEXT;
13597 					else
13598 						mp1->b_flag |= MSGNOTMARKNEXT;
13599 					freemsg(tcp->tcp_urp_mark_mp);
13600 					tcp->tcp_urp_mark_mp = mp1;
13601 					flags |= TH_SEND_URP_MARK;
13602 				}
13603 				tcp->tcp_urp_last_valid = B_TRUE;
13604 				tcp->tcp_urp_last = urp + seg_seq;
13605 			}
13606 			/*
13607 			 * If this is a zero window probe, continue to
13608 			 * process the ACK part.  But we need to set seg_len
13609 			 * to 0 to avoid data processing.  Otherwise just
13610 			 * drop the segment and send back an ACK.
13611 			 */
13612 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13613 				flags &= ~(TH_SYN | TH_URG);
13614 				seg_len = 0;
13615 				goto process_ack;
13616 			} else {
13617 				freemsg(mp);
13618 				goto ack_check;
13619 			}
13620 		}
13621 		/* Pitch out of window stuff off the end. */
13622 		rgap = seg_len;
13623 		mp2 = mp;
13624 		do {
13625 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13626 			    (uintptr_t)INT_MAX);
13627 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13628 			if (rgap < 0) {
13629 				mp2->b_wptr += rgap;
13630 				if ((mp1 = mp2->b_cont) != NULL) {
13631 					mp2->b_cont = NULL;
13632 					freemsg(mp1);
13633 				}
13634 				break;
13635 			}
13636 		} while ((mp2 = mp2->b_cont) != NULL);
13637 	}
13638 ok:;
13639 	/*
13640 	 * TCP should check ECN info for segments inside the window only.
13641 	 * Therefore the check should be done here.
13642 	 */
13643 	if (tcp->tcp_ecn_ok) {
13644 		if (flags & TH_CWR) {
13645 			tcp->tcp_ecn_echo_on = B_FALSE;
13646 		}
13647 		/*
13648 		 * Note that both ECN_CE and CWR can be set in the
13649 		 * same segment.  In this case, we once again turn
13650 		 * on ECN_ECHO.
13651 		 */
13652 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13653 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13654 
13655 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13656 				tcp->tcp_ecn_echo_on = B_TRUE;
13657 			}
13658 		} else {
13659 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13660 
13661 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13662 			    htonl(IPH_ECN_CE << 20)) {
13663 				tcp->tcp_ecn_echo_on = B_TRUE;
13664 			}
13665 		}
13666 	}
13667 
13668 	/*
13669 	 * Check whether we can update tcp_ts_recent.  This test is
13670 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13671 	 * Extensions for High Performance: An Update", Internet Draft.
13672 	 */
13673 	if (tcp->tcp_snd_ts_ok &&
13674 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13675 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13676 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13677 		tcp->tcp_last_rcv_lbolt = lbolt64;
13678 	}
13679 
13680 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13681 		/*
13682 		 * FIN in an out of order segment.  We record this in
13683 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13684 		 * Clear the FIN so that any check on FIN flag will fail.
13685 		 * Remember that FIN also counts in the sequence number
13686 		 * space.  So we need to ack out of order FIN only segments.
13687 		 */
13688 		if (flags & TH_FIN) {
13689 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13690 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13691 			flags &= ~TH_FIN;
13692 			flags |= TH_ACK_NEEDED;
13693 		}
13694 		if (seg_len > 0) {
13695 			/* Fill in the SACK blk list. */
13696 			if (tcp->tcp_snd_sack_ok) {
13697 				ASSERT(tcp->tcp_sack_info != NULL);
13698 				tcp_sack_insert(tcp->tcp_sack_list,
13699 				    seg_seq, seg_seq + seg_len,
13700 				    &(tcp->tcp_num_sack_blk));
13701 			}
13702 
13703 			/*
13704 			 * Attempt reassembly and see if we have something
13705 			 * ready to go.
13706 			 */
13707 			mp = tcp_reass(tcp, mp, seg_seq);
13708 			/* Always ack out of order packets */
13709 			flags |= TH_ACK_NEEDED | TH_PUSH;
13710 			if (mp) {
13711 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13712 				    (uintptr_t)INT_MAX);
13713 				seg_len = mp->b_cont ? msgdsize(mp) :
13714 				    (int)(mp->b_wptr - mp->b_rptr);
13715 				seg_seq = tcp->tcp_rnxt;
13716 				/*
13717 				 * A gap is filled and the seq num and len
13718 				 * of the gap match that of a previously
13719 				 * received FIN, put the FIN flag back in.
13720 				 */
13721 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13722 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13723 					flags |= TH_FIN;
13724 					tcp->tcp_valid_bits &=
13725 					    ~TCP_OFO_FIN_VALID;
13726 				}
13727 			} else {
13728 				/*
13729 				 * Keep going even with NULL mp.
13730 				 * There may be a useful ACK or something else
13731 				 * we don't want to miss.
13732 				 *
13733 				 * But TCP should not perform fast retransmit
13734 				 * because of the ack number.  TCP uses
13735 				 * seg_len == 0 to determine if it is a pure
13736 				 * ACK.  And this is not a pure ACK.
13737 				 */
13738 				seg_len = 0;
13739 				ofo_seg = B_TRUE;
13740 			}
13741 		}
13742 	} else if (seg_len > 0) {
13743 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13744 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13745 		/*
13746 		 * If an out of order FIN was received before, and the seq
13747 		 * num and len of the new segment match that of the FIN,
13748 		 * put the FIN flag back in.
13749 		 */
13750 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13751 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13752 			flags |= TH_FIN;
13753 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13754 		}
13755 	}
13756 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13757 	if (flags & TH_RST) {
13758 		freemsg(mp);
13759 		switch (tcp->tcp_state) {
13760 		case TCPS_SYN_RCVD:
13761 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13762 			break;
13763 		case TCPS_ESTABLISHED:
13764 		case TCPS_FIN_WAIT_1:
13765 		case TCPS_FIN_WAIT_2:
13766 		case TCPS_CLOSE_WAIT:
13767 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13768 			break;
13769 		case TCPS_CLOSING:
13770 		case TCPS_LAST_ACK:
13771 			(void) tcp_clean_death(tcp, 0, 16);
13772 			break;
13773 		default:
13774 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13775 			(void) tcp_clean_death(tcp, ENXIO, 17);
13776 			break;
13777 		}
13778 		return;
13779 	}
13780 	if (flags & TH_SYN) {
13781 		/*
13782 		 * See RFC 793, Page 71
13783 		 *
13784 		 * The seq number must be in the window as it should
13785 		 * be "fixed" above.  If it is outside window, it should
13786 		 * be already rejected.  Note that we allow seg_seq to be
13787 		 * rnxt + rwnd because we want to accept 0 window probe.
13788 		 */
13789 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13790 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13791 		freemsg(mp);
13792 		/*
13793 		 * If the ACK flag is not set, just use our snxt as the
13794 		 * seq number of the RST segment.
13795 		 */
13796 		if (!(flags & TH_ACK)) {
13797 			seg_ack = tcp->tcp_snxt;
13798 		}
13799 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13800 		    TH_RST|TH_ACK);
13801 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13802 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13803 		return;
13804 	}
13805 	/*
13806 	 * urp could be -1 when the urp field in the packet is 0
13807 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13808 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13809 	 */
13810 	if (flags & TH_URG && urp >= 0) {
13811 		if (!tcp->tcp_urp_last_valid ||
13812 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13813 			if (IPCL_IS_NONSTR(connp)) {
13814 				if (!TCP_IS_DETACHED(tcp)) {
13815 					(*connp->conn_upcalls->su_signal_oob)
13816 					    (connp->conn_upper_handle, urp);
13817 				}
13818 			} else {
13819 				/*
13820 				 * If we haven't generated the signal yet for
13821 				 * this urgent pointer value, do it now.  Also,
13822 				 * send up a zero-length M_DATA indicating
13823 				 * whether or not this is the mark. The latter
13824 				 * is not needed when a T_EXDATA_IND is sent up.
13825 				 * However, if there are allocation failures
13826 				 * this code relies on the sender retransmitting
13827 				 * and the socket code for determining the mark
13828 				 * should not block waiting for the peer to
13829 				 * transmit. Thus, for simplicity we always
13830 				 * send up the mark indication.
13831 				 */
13832 				mp1 = allocb(0, BPRI_MED);
13833 				if (mp1 == NULL) {
13834 					freemsg(mp);
13835 					return;
13836 				}
13837 				if (!TCP_IS_DETACHED(tcp) &&
13838 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13839 				    SIGURG)) {
13840 					/* Try again on the rexmit. */
13841 					freemsg(mp1);
13842 					freemsg(mp);
13843 					return;
13844 				}
13845 				/*
13846 				 * Mark with NOTMARKNEXT for now.
13847 				 * The code below will change this to MARKNEXT
13848 				 * if we are at the mark.
13849 				 *
13850 				 * If there are allocation failures (e.g. in
13851 				 * dupmsg below) the next time tcp_rput_data
13852 				 * sees the urgent segment it will send up the
13853 				 * MSGMARKNEXT message.
13854 				 */
13855 				mp1->b_flag |= MSGNOTMARKNEXT;
13856 				freemsg(tcp->tcp_urp_mark_mp);
13857 				tcp->tcp_urp_mark_mp = mp1;
13858 				flags |= TH_SEND_URP_MARK;
13859 #ifdef DEBUG
13860 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13861 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13862 				    "last %x, %s",
13863 				    seg_seq, urp, tcp->tcp_urp_last,
13864 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13865 #endif /* DEBUG */
13866 			}
13867 			tcp->tcp_urp_last_valid = B_TRUE;
13868 			tcp->tcp_urp_last = urp + seg_seq;
13869 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13870 			/*
13871 			 * An allocation failure prevented the previous
13872 			 * tcp_rput_data from sending up the allocated
13873 			 * MSG*MARKNEXT message - send it up this time
13874 			 * around.
13875 			 */
13876 			flags |= TH_SEND_URP_MARK;
13877 		}
13878 
13879 		/*
13880 		 * If the urgent byte is in this segment, make sure that it is
13881 		 * all by itself.  This makes it much easier to deal with the
13882 		 * possibility of an allocation failure on the T_exdata_ind.
13883 		 * Note that seg_len is the number of bytes in the segment, and
13884 		 * urp is the offset into the segment of the urgent byte.
13885 		 * urp < seg_len means that the urgent byte is in this segment.
13886 		 */
13887 		if (urp < seg_len) {
13888 			if (seg_len != 1) {
13889 				uint32_t  tmp_rnxt;
13890 				/*
13891 				 * Break it up and feed it back in.
13892 				 * Re-attach the IP header.
13893 				 */
13894 				mp->b_rptr = iphdr;
13895 				if (urp > 0) {
13896 					/*
13897 					 * There is stuff before the urgent
13898 					 * byte.
13899 					 */
13900 					mp1 = dupmsg(mp);
13901 					if (!mp1) {
13902 						/*
13903 						 * Trim from urgent byte on.
13904 						 * The rest will come back.
13905 						 */
13906 						(void) adjmsg(mp,
13907 						    urp - seg_len);
13908 						tcp_rput_data(connp,
13909 						    mp, NULL);
13910 						return;
13911 					}
13912 					(void) adjmsg(mp1, urp - seg_len);
13913 					/* Feed this piece back in. */
13914 					tmp_rnxt = tcp->tcp_rnxt;
13915 					tcp_rput_data(connp, mp1, NULL);
13916 					/*
13917 					 * If the data passed back in was not
13918 					 * processed (ie: bad ACK) sending
13919 					 * the remainder back in will cause a
13920 					 * loop. In this case, drop the
13921 					 * packet and let the sender try
13922 					 * sending a good packet.
13923 					 */
13924 					if (tmp_rnxt == tcp->tcp_rnxt) {
13925 						freemsg(mp);
13926 						return;
13927 					}
13928 				}
13929 				if (urp != seg_len - 1) {
13930 					uint32_t  tmp_rnxt;
13931 					/*
13932 					 * There is stuff after the urgent
13933 					 * byte.
13934 					 */
13935 					mp1 = dupmsg(mp);
13936 					if (!mp1) {
13937 						/*
13938 						 * Trim everything beyond the
13939 						 * urgent byte.  The rest will
13940 						 * come back.
13941 						 */
13942 						(void) adjmsg(mp,
13943 						    urp + 1 - seg_len);
13944 						tcp_rput_data(connp,
13945 						    mp, NULL);
13946 						return;
13947 					}
13948 					(void) adjmsg(mp1, urp + 1 - seg_len);
13949 					tmp_rnxt = tcp->tcp_rnxt;
13950 					tcp_rput_data(connp, mp1, NULL);
13951 					/*
13952 					 * If the data passed back in was not
13953 					 * processed (ie: bad ACK) sending
13954 					 * the remainder back in will cause a
13955 					 * loop. In this case, drop the
13956 					 * packet and let the sender try
13957 					 * sending a good packet.
13958 					 */
13959 					if (tmp_rnxt == tcp->tcp_rnxt) {
13960 						freemsg(mp);
13961 						return;
13962 					}
13963 				}
13964 				tcp_rput_data(connp, mp, NULL);
13965 				return;
13966 			}
13967 			/*
13968 			 * This segment contains only the urgent byte.  We
13969 			 * have to allocate the T_exdata_ind, if we can.
13970 			 */
13971 			if (IPCL_IS_NONSTR(connp)) {
13972 				int error;
13973 
13974 				(*connp->conn_upcalls->su_recv)
13975 				    (connp->conn_upper_handle, mp, seg_len,
13976 				    MSG_OOB, &error, NULL);
13977 				mp = NULL;
13978 				goto update_ack;
13979 			} else if (!tcp->tcp_urp_mp) {
13980 				struct T_exdata_ind *tei;
13981 				mp1 = allocb(sizeof (struct T_exdata_ind),
13982 				    BPRI_MED);
13983 				if (!mp1) {
13984 					/*
13985 					 * Sigh... It'll be back.
13986 					 * Generate any MSG*MARK message now.
13987 					 */
13988 					freemsg(mp);
13989 					seg_len = 0;
13990 					if (flags & TH_SEND_URP_MARK) {
13991 
13992 
13993 						ASSERT(tcp->tcp_urp_mark_mp);
13994 						tcp->tcp_urp_mark_mp->b_flag &=
13995 						    ~MSGNOTMARKNEXT;
13996 						tcp->tcp_urp_mark_mp->b_flag |=
13997 						    MSGMARKNEXT;
13998 					}
13999 					goto ack_check;
14000 				}
14001 				mp1->b_datap->db_type = M_PROTO;
14002 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14003 				tei->PRIM_type = T_EXDATA_IND;
14004 				tei->MORE_flag = 0;
14005 				mp1->b_wptr = (uchar_t *)&tei[1];
14006 				tcp->tcp_urp_mp = mp1;
14007 #ifdef DEBUG
14008 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14009 				    "tcp_rput: allocated exdata_ind %s",
14010 				    tcp_display(tcp, NULL,
14011 				    DISP_PORT_ONLY));
14012 #endif /* DEBUG */
14013 				/*
14014 				 * There is no need to send a separate MSG*MARK
14015 				 * message since the T_EXDATA_IND will be sent
14016 				 * now.
14017 				 */
14018 				flags &= ~TH_SEND_URP_MARK;
14019 				freemsg(tcp->tcp_urp_mark_mp);
14020 				tcp->tcp_urp_mark_mp = NULL;
14021 			}
14022 			/*
14023 			 * Now we are all set.  On the next putnext upstream,
14024 			 * tcp_urp_mp will be non-NULL and will get prepended
14025 			 * to what has to be this piece containing the urgent
14026 			 * byte.  If for any reason we abort this segment below,
14027 			 * if it comes back, we will have this ready, or it
14028 			 * will get blown off in close.
14029 			 */
14030 		} else if (urp == seg_len) {
14031 			/*
14032 			 * The urgent byte is the next byte after this sequence
14033 			 * number. If there is data it is marked with
14034 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14035 			 * since it is not needed. Otherwise, if the code
14036 			 * above just allocated a zero-length tcp_urp_mark_mp
14037 			 * message, that message is tagged with MSGMARKNEXT.
14038 			 * Sending up these MSGMARKNEXT messages makes
14039 			 * SIOCATMARK work correctly even though
14040 			 * the T_EXDATA_IND will not be sent up until the
14041 			 * urgent byte arrives.
14042 			 */
14043 			if (seg_len != 0) {
14044 				flags |= TH_MARKNEXT_NEEDED;
14045 				freemsg(tcp->tcp_urp_mark_mp);
14046 				tcp->tcp_urp_mark_mp = NULL;
14047 				flags &= ~TH_SEND_URP_MARK;
14048 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14049 				flags |= TH_SEND_URP_MARK;
14050 				tcp->tcp_urp_mark_mp->b_flag &=
14051 				    ~MSGNOTMARKNEXT;
14052 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14053 			}
14054 #ifdef DEBUG
14055 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14056 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14057 			    seg_len, flags,
14058 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14059 #endif /* DEBUG */
14060 		}
14061 #ifdef DEBUG
14062 		else {
14063 			/* Data left until we hit mark */
14064 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14065 			    "tcp_rput: URP %d bytes left, %s",
14066 			    urp - seg_len, tcp_display(tcp, NULL,
14067 			    DISP_PORT_ONLY));
14068 		}
14069 #endif /* DEBUG */
14070 	}
14071 
14072 process_ack:
14073 	if (!(flags & TH_ACK)) {
14074 		freemsg(mp);
14075 		goto xmit_check;
14076 	}
14077 	}
14078 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14079 
14080 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14081 		tcp->tcp_ip_forward_progress = B_TRUE;
14082 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14083 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14084 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14085 			/* 3-way handshake complete - pass up the T_CONN_IND */
14086 			tcp_t	*listener = tcp->tcp_listener;
14087 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14088 
14089 			tcp->tcp_tconnind_started = B_TRUE;
14090 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14091 			/*
14092 			 * We are here means eager is fine but it can
14093 			 * get a TH_RST at any point between now and till
14094 			 * accept completes and disappear. We need to
14095 			 * ensure that reference to eager is valid after
14096 			 * we get out of eager's perimeter. So we do
14097 			 * an extra refhold.
14098 			 */
14099 			CONN_INC_REF(connp);
14100 
14101 			/*
14102 			 * The listener also exists because of the refhold
14103 			 * done in tcp_conn_request. Its possible that it
14104 			 * might have closed. We will check that once we
14105 			 * get inside listeners context.
14106 			 */
14107 			CONN_INC_REF(listener->tcp_connp);
14108 			if (listener->tcp_connp->conn_sqp ==
14109 			    connp->conn_sqp) {
14110 				/*
14111 				 * We optimize by not calling an SQUEUE_ENTER
14112 				 * on the listener since we know that the
14113 				 * listener and eager squeues are the same.
14114 				 * We are able to make this check safely only
14115 				 * because neither the eager nor the listener
14116 				 * can change its squeue. Only an active connect
14117 				 * can change its squeue
14118 				 */
14119 				tcp_send_conn_ind(listener->tcp_connp, mp,
14120 				    listener->tcp_connp->conn_sqp);
14121 				CONN_DEC_REF(listener->tcp_connp);
14122 			} else if (!tcp->tcp_loopback) {
14123 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14124 				    mp, tcp_send_conn_ind,
14125 				    listener->tcp_connp, SQ_FILL,
14126 				    SQTAG_TCP_CONN_IND);
14127 			} else {
14128 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14129 				    mp, tcp_send_conn_ind,
14130 				    listener->tcp_connp, SQ_PROCESS,
14131 				    SQTAG_TCP_CONN_IND);
14132 			}
14133 		}
14134 
14135 		if (tcp->tcp_active_open) {
14136 			/*
14137 			 * We are seeing the final ack in the three way
14138 			 * hand shake of a active open'ed connection
14139 			 * so we must send up a T_CONN_CON
14140 			 */
14141 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14142 				freemsg(mp);
14143 				return;
14144 			}
14145 			/*
14146 			 * Don't fuse the loopback endpoints for
14147 			 * simultaneous active opens.
14148 			 */
14149 			if (tcp->tcp_loopback) {
14150 				TCP_STAT(tcps, tcp_fusion_unfusable);
14151 				tcp->tcp_unfusable = B_TRUE;
14152 			}
14153 		}
14154 
14155 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14156 		bytes_acked--;
14157 		/* SYN was acked - making progress */
14158 		if (tcp->tcp_ipversion == IPV6_VERSION)
14159 			tcp->tcp_ip_forward_progress = B_TRUE;
14160 
14161 		/*
14162 		 * If SYN was retransmitted, need to reset all
14163 		 * retransmission info as this segment will be
14164 		 * treated as a dup ACK.
14165 		 */
14166 		if (tcp->tcp_rexmit) {
14167 			tcp->tcp_rexmit = B_FALSE;
14168 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14169 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14170 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14171 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14172 			tcp->tcp_ms_we_have_waited = 0;
14173 			tcp->tcp_cwnd = mss;
14174 		}
14175 
14176 		/*
14177 		 * We set the send window to zero here.
14178 		 * This is needed if there is data to be
14179 		 * processed already on the queue.
14180 		 * Later (at swnd_update label), the
14181 		 * "new_swnd > tcp_swnd" condition is satisfied
14182 		 * the XMIT_NEEDED flag is set in the current
14183 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14184 		 * called if there is already data on queue in
14185 		 * this state.
14186 		 */
14187 		tcp->tcp_swnd = 0;
14188 
14189 		if (new_swnd > tcp->tcp_max_swnd)
14190 			tcp->tcp_max_swnd = new_swnd;
14191 		tcp->tcp_swl1 = seg_seq;
14192 		tcp->tcp_swl2 = seg_ack;
14193 		tcp->tcp_state = TCPS_ESTABLISHED;
14194 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14195 
14196 		/* Fuse when both sides are in ESTABLISHED state */
14197 		if (tcp->tcp_loopback && do_tcp_fusion)
14198 			tcp_fuse(tcp, iphdr, tcph);
14199 
14200 	}
14201 	/* This code follows 4.4BSD-Lite2 mostly. */
14202 	if (bytes_acked < 0)
14203 		goto est;
14204 
14205 	/*
14206 	 * If TCP is ECN capable and the congestion experience bit is
14207 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14208 	 * done once per window (or more loosely, per RTT).
14209 	 */
14210 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14211 		tcp->tcp_cwr = B_FALSE;
14212 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14213 		if (!tcp->tcp_cwr) {
14214 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14215 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14216 			tcp->tcp_cwnd = npkt * mss;
14217 			/*
14218 			 * If the cwnd is 0, use the timer to clock out
14219 			 * new segments.  This is required by the ECN spec.
14220 			 */
14221 			if (npkt == 0) {
14222 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14223 				/*
14224 				 * This makes sure that when the ACK comes
14225 				 * back, we will increase tcp_cwnd by 1 MSS.
14226 				 */
14227 				tcp->tcp_cwnd_cnt = 0;
14228 			}
14229 			tcp->tcp_cwr = B_TRUE;
14230 			/*
14231 			 * This marks the end of the current window of in
14232 			 * flight data.  That is why we don't use
14233 			 * tcp_suna + tcp_swnd.  Only data in flight can
14234 			 * provide ECN info.
14235 			 */
14236 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14237 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14238 		}
14239 	}
14240 
14241 	mp1 = tcp->tcp_xmit_head;
14242 	if (bytes_acked == 0) {
14243 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14244 			int dupack_cnt;
14245 
14246 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14247 			/*
14248 			 * Fast retransmit.  When we have seen exactly three
14249 			 * identical ACKs while we have unacked data
14250 			 * outstanding we take it as a hint that our peer
14251 			 * dropped something.
14252 			 *
14253 			 * If TCP is retransmitting, don't do fast retransmit.
14254 			 */
14255 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14256 			    ! tcp->tcp_rexmit) {
14257 				/* Do Limited Transmit */
14258 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14259 				    tcps->tcps_dupack_fast_retransmit) {
14260 					/*
14261 					 * RFC 3042
14262 					 *
14263 					 * What we need to do is temporarily
14264 					 * increase tcp_cwnd so that new
14265 					 * data can be sent if it is allowed
14266 					 * by the receive window (tcp_rwnd).
14267 					 * tcp_wput_data() will take care of
14268 					 * the rest.
14269 					 *
14270 					 * If the connection is SACK capable,
14271 					 * only do limited xmit when there
14272 					 * is SACK info.
14273 					 *
14274 					 * Note how tcp_cwnd is incremented.
14275 					 * The first dup ACK will increase
14276 					 * it by 1 MSS.  The second dup ACK
14277 					 * will increase it by 2 MSS.  This
14278 					 * means that only 1 new segment will
14279 					 * be sent for each dup ACK.
14280 					 */
14281 					if (tcp->tcp_unsent > 0 &&
14282 					    (!tcp->tcp_snd_sack_ok ||
14283 					    (tcp->tcp_snd_sack_ok &&
14284 					    tcp->tcp_notsack_list != NULL))) {
14285 						tcp->tcp_cwnd += mss <<
14286 						    (tcp->tcp_dupack_cnt - 1);
14287 						flags |= TH_LIMIT_XMIT;
14288 					}
14289 				} else if (dupack_cnt ==
14290 				    tcps->tcps_dupack_fast_retransmit) {
14291 
14292 				/*
14293 				 * If we have reduced tcp_ssthresh
14294 				 * because of ECN, do not reduce it again
14295 				 * unless it is already one window of data
14296 				 * away.  After one window of data, tcp_cwr
14297 				 * should then be cleared.  Note that
14298 				 * for non ECN capable connection, tcp_cwr
14299 				 * should always be false.
14300 				 *
14301 				 * Adjust cwnd since the duplicate
14302 				 * ack indicates that a packet was
14303 				 * dropped (due to congestion.)
14304 				 */
14305 				if (!tcp->tcp_cwr) {
14306 					npkt = ((tcp->tcp_snxt -
14307 					    tcp->tcp_suna) >> 1) / mss;
14308 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14309 					    mss;
14310 					tcp->tcp_cwnd = (npkt +
14311 					    tcp->tcp_dupack_cnt) * mss;
14312 				}
14313 				if (tcp->tcp_ecn_ok) {
14314 					tcp->tcp_cwr = B_TRUE;
14315 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14316 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14317 				}
14318 
14319 				/*
14320 				 * We do Hoe's algorithm.  Refer to her
14321 				 * paper "Improving the Start-up Behavior
14322 				 * of a Congestion Control Scheme for TCP,"
14323 				 * appeared in SIGCOMM'96.
14324 				 *
14325 				 * Save highest seq no we have sent so far.
14326 				 * Be careful about the invisible FIN byte.
14327 				 */
14328 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14329 				    (tcp->tcp_unsent == 0)) {
14330 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14331 				} else {
14332 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14333 				}
14334 
14335 				/*
14336 				 * Do not allow bursty traffic during.
14337 				 * fast recovery.  Refer to Fall and Floyd's
14338 				 * paper "Simulation-based Comparisons of
14339 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14340 				 * This is a best current practise.
14341 				 */
14342 				tcp->tcp_snd_burst = TCP_CWND_SS;
14343 
14344 				/*
14345 				 * For SACK:
14346 				 * Calculate tcp_pipe, which is the
14347 				 * estimated number of bytes in
14348 				 * network.
14349 				 *
14350 				 * tcp_fack is the highest sack'ed seq num
14351 				 * TCP has received.
14352 				 *
14353 				 * tcp_pipe is explained in the above quoted
14354 				 * Fall and Floyd's paper.  tcp_fack is
14355 				 * explained in Mathis and Mahdavi's
14356 				 * "Forward Acknowledgment: Refining TCP
14357 				 * Congestion Control" in SIGCOMM '96.
14358 				 */
14359 				if (tcp->tcp_snd_sack_ok) {
14360 					ASSERT(tcp->tcp_sack_info != NULL);
14361 					if (tcp->tcp_notsack_list != NULL) {
14362 						tcp->tcp_pipe = tcp->tcp_snxt -
14363 						    tcp->tcp_fack;
14364 						tcp->tcp_sack_snxt = seg_ack;
14365 						flags |= TH_NEED_SACK_REXMIT;
14366 					} else {
14367 						/*
14368 						 * Always initialize tcp_pipe
14369 						 * even though we don't have
14370 						 * any SACK info.  If later
14371 						 * we get SACK info and
14372 						 * tcp_pipe is not initialized,
14373 						 * funny things will happen.
14374 						 */
14375 						tcp->tcp_pipe =
14376 						    tcp->tcp_cwnd_ssthresh;
14377 					}
14378 				} else {
14379 					flags |= TH_REXMIT_NEEDED;
14380 				} /* tcp_snd_sack_ok */
14381 
14382 				} else {
14383 					/*
14384 					 * Here we perform congestion
14385 					 * avoidance, but NOT slow start.
14386 					 * This is known as the Fast
14387 					 * Recovery Algorithm.
14388 					 */
14389 					if (tcp->tcp_snd_sack_ok &&
14390 					    tcp->tcp_notsack_list != NULL) {
14391 						flags |= TH_NEED_SACK_REXMIT;
14392 						tcp->tcp_pipe -= mss;
14393 						if (tcp->tcp_pipe < 0)
14394 							tcp->tcp_pipe = 0;
14395 					} else {
14396 					/*
14397 					 * We know that one more packet has
14398 					 * left the pipe thus we can update
14399 					 * cwnd.
14400 					 */
14401 					cwnd = tcp->tcp_cwnd + mss;
14402 					if (cwnd > tcp->tcp_cwnd_max)
14403 						cwnd = tcp->tcp_cwnd_max;
14404 					tcp->tcp_cwnd = cwnd;
14405 					if (tcp->tcp_unsent > 0)
14406 						flags |= TH_XMIT_NEEDED;
14407 					}
14408 				}
14409 			}
14410 		} else if (tcp->tcp_zero_win_probe) {
14411 			/*
14412 			 * If the window has opened, need to arrange
14413 			 * to send additional data.
14414 			 */
14415 			if (new_swnd != 0) {
14416 				/* tcp_suna != tcp_snxt */
14417 				/* Packet contains a window update */
14418 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14419 				tcp->tcp_zero_win_probe = 0;
14420 				tcp->tcp_timer_backoff = 0;
14421 				tcp->tcp_ms_we_have_waited = 0;
14422 
14423 				/*
14424 				 * Transmit starting with tcp_suna since
14425 				 * the one byte probe is not ack'ed.
14426 				 * If TCP has sent more than one identical
14427 				 * probe, tcp_rexmit will be set.  That means
14428 				 * tcp_ss_rexmit() will send out the one
14429 				 * byte along with new data.  Otherwise,
14430 				 * fake the retransmission.
14431 				 */
14432 				flags |= TH_XMIT_NEEDED;
14433 				if (!tcp->tcp_rexmit) {
14434 					tcp->tcp_rexmit = B_TRUE;
14435 					tcp->tcp_dupack_cnt = 0;
14436 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14437 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14438 				}
14439 			}
14440 		}
14441 		goto swnd_update;
14442 	}
14443 
14444 	/*
14445 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14446 	 * If the ACK value acks something that we have not yet sent, it might
14447 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14448 	 * other side.
14449 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14450 	 * state is handled above, so we can always just drop the segment and
14451 	 * send an ACK here.
14452 	 *
14453 	 * Should we send ACKs in response to ACK only segments?
14454 	 */
14455 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14456 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14457 		/* drop the received segment */
14458 		freemsg(mp);
14459 
14460 		/*
14461 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14462 		 * greater than 0, check if the number of such
14463 		 * bogus ACks is greater than that count.  If yes,
14464 		 * don't send back any ACK.  This prevents TCP from
14465 		 * getting into an ACK storm if somehow an attacker
14466 		 * successfully spoofs an acceptable segment to our
14467 		 * peer.
14468 		 */
14469 		if (tcp_drop_ack_unsent_cnt > 0 &&
14470 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14471 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14472 			return;
14473 		}
14474 		mp = tcp_ack_mp(tcp);
14475 		if (mp != NULL) {
14476 			BUMP_LOCAL(tcp->tcp_obsegs);
14477 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14478 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14479 		}
14480 		return;
14481 	}
14482 
14483 	/*
14484 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14485 	 * blocks that are covered by this ACK.
14486 	 */
14487 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14488 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14489 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14490 	}
14491 
14492 	/*
14493 	 * If we got an ACK after fast retransmit, check to see
14494 	 * if it is a partial ACK.  If it is not and the congestion
14495 	 * window was inflated to account for the other side's
14496 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14497 	 */
14498 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14499 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14500 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14501 			tcp->tcp_dupack_cnt = 0;
14502 			/*
14503 			 * Restore the orig tcp_cwnd_ssthresh after
14504 			 * fast retransmit phase.
14505 			 */
14506 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14507 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14508 			}
14509 			tcp->tcp_rexmit_max = seg_ack;
14510 			tcp->tcp_cwnd_cnt = 0;
14511 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14512 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14513 
14514 			/*
14515 			 * Remove all notsack info to avoid confusion with
14516 			 * the next fast retrasnmit/recovery phase.
14517 			 */
14518 			if (tcp->tcp_snd_sack_ok &&
14519 			    tcp->tcp_notsack_list != NULL) {
14520 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14521 			}
14522 		} else {
14523 			if (tcp->tcp_snd_sack_ok &&
14524 			    tcp->tcp_notsack_list != NULL) {
14525 				flags |= TH_NEED_SACK_REXMIT;
14526 				tcp->tcp_pipe -= mss;
14527 				if (tcp->tcp_pipe < 0)
14528 					tcp->tcp_pipe = 0;
14529 			} else {
14530 				/*
14531 				 * Hoe's algorithm:
14532 				 *
14533 				 * Retransmit the unack'ed segment and
14534 				 * restart fast recovery.  Note that we
14535 				 * need to scale back tcp_cwnd to the
14536 				 * original value when we started fast
14537 				 * recovery.  This is to prevent overly
14538 				 * aggressive behaviour in sending new
14539 				 * segments.
14540 				 */
14541 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14542 				    tcps->tcps_dupack_fast_retransmit * mss;
14543 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14544 				flags |= TH_REXMIT_NEEDED;
14545 			}
14546 		}
14547 	} else {
14548 		tcp->tcp_dupack_cnt = 0;
14549 		if (tcp->tcp_rexmit) {
14550 			/*
14551 			 * TCP is retranmitting.  If the ACK ack's all
14552 			 * outstanding data, update tcp_rexmit_max and
14553 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14554 			 * to the correct value.
14555 			 *
14556 			 * Note that SEQ_LEQ() is used.  This is to avoid
14557 			 * unnecessary fast retransmit caused by dup ACKs
14558 			 * received when TCP does slow start retransmission
14559 			 * after a time out.  During this phase, TCP may
14560 			 * send out segments which are already received.
14561 			 * This causes dup ACKs to be sent back.
14562 			 */
14563 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14564 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14565 					tcp->tcp_rexmit_nxt = seg_ack;
14566 				}
14567 				if (seg_ack != tcp->tcp_rexmit_max) {
14568 					flags |= TH_XMIT_NEEDED;
14569 				}
14570 			} else {
14571 				tcp->tcp_rexmit = B_FALSE;
14572 				tcp->tcp_xmit_zc_clean = B_FALSE;
14573 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14574 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14575 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14576 			}
14577 			tcp->tcp_ms_we_have_waited = 0;
14578 		}
14579 	}
14580 
14581 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14582 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14583 	tcp->tcp_suna = seg_ack;
14584 	if (tcp->tcp_zero_win_probe != 0) {
14585 		tcp->tcp_zero_win_probe = 0;
14586 		tcp->tcp_timer_backoff = 0;
14587 	}
14588 
14589 	/*
14590 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14591 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14592 	 * will not reach here.
14593 	 */
14594 	if (mp1 == NULL) {
14595 		goto fin_acked;
14596 	}
14597 
14598 	/*
14599 	 * Update the congestion window.
14600 	 *
14601 	 * If TCP is not ECN capable or TCP is ECN capable but the
14602 	 * congestion experience bit is not set, increase the tcp_cwnd as
14603 	 * usual.
14604 	 */
14605 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14606 		cwnd = tcp->tcp_cwnd;
14607 		add = mss;
14608 
14609 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14610 			/*
14611 			 * This is to prevent an increase of less than 1 MSS of
14612 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14613 			 * may send out tinygrams in order to preserve mblk
14614 			 * boundaries.
14615 			 *
14616 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14617 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14618 			 * increased by 1 MSS for every RTTs.
14619 			 */
14620 			if (tcp->tcp_cwnd_cnt <= 0) {
14621 				tcp->tcp_cwnd_cnt = cwnd + add;
14622 			} else {
14623 				tcp->tcp_cwnd_cnt -= add;
14624 				add = 0;
14625 			}
14626 		}
14627 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14628 	}
14629 
14630 	/* See if the latest urgent data has been acknowledged */
14631 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14632 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14633 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14634 
14635 	/* Can we update the RTT estimates? */
14636 	if (tcp->tcp_snd_ts_ok) {
14637 		/* Ignore zero timestamp echo-reply. */
14638 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14639 			tcp_set_rto(tcp, (int32_t)lbolt -
14640 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14641 		}
14642 
14643 		/* If needed, restart the timer. */
14644 		if (tcp->tcp_set_timer == 1) {
14645 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14646 			tcp->tcp_set_timer = 0;
14647 		}
14648 		/*
14649 		 * Update tcp_csuna in case the other side stops sending
14650 		 * us timestamps.
14651 		 */
14652 		tcp->tcp_csuna = tcp->tcp_snxt;
14653 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14654 		/*
14655 		 * An ACK sequence we haven't seen before, so get the RTT
14656 		 * and update the RTO. But first check if the timestamp is
14657 		 * valid to use.
14658 		 */
14659 		if ((mp1->b_next != NULL) &&
14660 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14661 			tcp_set_rto(tcp, (int32_t)lbolt -
14662 			    (int32_t)(intptr_t)mp1->b_prev);
14663 		else
14664 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14665 
14666 		/* Remeber the last sequence to be ACKed */
14667 		tcp->tcp_csuna = seg_ack;
14668 		if (tcp->tcp_set_timer == 1) {
14669 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14670 			tcp->tcp_set_timer = 0;
14671 		}
14672 	} else {
14673 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14674 	}
14675 
14676 	/* Eat acknowledged bytes off the xmit queue. */
14677 	for (;;) {
14678 		mblk_t	*mp2;
14679 		uchar_t	*wptr;
14680 
14681 		wptr = mp1->b_wptr;
14682 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14683 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14684 		if (bytes_acked < 0) {
14685 			mp1->b_rptr = wptr + bytes_acked;
14686 			/*
14687 			 * Set a new timestamp if all the bytes timed by the
14688 			 * old timestamp have been ack'ed.
14689 			 */
14690 			if (SEQ_GT(seg_ack,
14691 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14692 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14693 				mp1->b_next = NULL;
14694 			}
14695 			break;
14696 		}
14697 		mp1->b_next = NULL;
14698 		mp1->b_prev = NULL;
14699 		mp2 = mp1;
14700 		mp1 = mp1->b_cont;
14701 
14702 		/*
14703 		 * This notification is required for some zero-copy
14704 		 * clients to maintain a copy semantic. After the data
14705 		 * is ack'ed, client is safe to modify or reuse the buffer.
14706 		 */
14707 		if (tcp->tcp_snd_zcopy_aware &&
14708 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14709 			tcp_zcopy_notify(tcp);
14710 		freeb(mp2);
14711 		if (bytes_acked == 0) {
14712 			if (mp1 == NULL) {
14713 				/* Everything is ack'ed, clear the tail. */
14714 				tcp->tcp_xmit_tail = NULL;
14715 				/*
14716 				 * Cancel the timer unless we are still
14717 				 * waiting for an ACK for the FIN packet.
14718 				 */
14719 				if (tcp->tcp_timer_tid != 0 &&
14720 				    tcp->tcp_snxt == tcp->tcp_suna) {
14721 					(void) TCP_TIMER_CANCEL(tcp,
14722 					    tcp->tcp_timer_tid);
14723 					tcp->tcp_timer_tid = 0;
14724 				}
14725 				goto pre_swnd_update;
14726 			}
14727 			if (mp2 != tcp->tcp_xmit_tail)
14728 				break;
14729 			tcp->tcp_xmit_tail = mp1;
14730 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14731 			    (uintptr_t)INT_MAX);
14732 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14733 			    mp1->b_rptr);
14734 			break;
14735 		}
14736 		if (mp1 == NULL) {
14737 			/*
14738 			 * More was acked but there is nothing more
14739 			 * outstanding.  This means that the FIN was
14740 			 * just acked or that we're talking to a clown.
14741 			 */
14742 fin_acked:
14743 			ASSERT(tcp->tcp_fin_sent);
14744 			tcp->tcp_xmit_tail = NULL;
14745 			if (tcp->tcp_fin_sent) {
14746 				/* FIN was acked - making progress */
14747 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14748 				    !tcp->tcp_fin_acked)
14749 					tcp->tcp_ip_forward_progress = B_TRUE;
14750 				tcp->tcp_fin_acked = B_TRUE;
14751 				if (tcp->tcp_linger_tid != 0 &&
14752 				    TCP_TIMER_CANCEL(tcp,
14753 				    tcp->tcp_linger_tid) >= 0) {
14754 					tcp_stop_lingering(tcp);
14755 					freemsg(mp);
14756 					mp = NULL;
14757 				}
14758 			} else {
14759 				/*
14760 				 * We should never get here because
14761 				 * we have already checked that the
14762 				 * number of bytes ack'ed should be
14763 				 * smaller than or equal to what we
14764 				 * have sent so far (it is the
14765 				 * acceptability check of the ACK).
14766 				 * We can only get here if the send
14767 				 * queue is corrupted.
14768 				 *
14769 				 * Terminate the connection and
14770 				 * panic the system.  It is better
14771 				 * for us to panic instead of
14772 				 * continuing to avoid other disaster.
14773 				 */
14774 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14775 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14776 				panic("Memory corruption "
14777 				    "detected for connection %s.",
14778 				    tcp_display(tcp, NULL,
14779 				    DISP_ADDR_AND_PORT));
14780 				/*NOTREACHED*/
14781 			}
14782 			goto pre_swnd_update;
14783 		}
14784 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14785 	}
14786 	if (tcp->tcp_unsent) {
14787 		flags |= TH_XMIT_NEEDED;
14788 	}
14789 pre_swnd_update:
14790 	tcp->tcp_xmit_head = mp1;
14791 swnd_update:
14792 	/*
14793 	 * The following check is different from most other implementations.
14794 	 * For bi-directional transfer, when segments are dropped, the
14795 	 * "normal" check will not accept a window update in those
14796 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14797 	 * segments which are outside receiver's window.  As TCP accepts
14798 	 * the ack in those retransmitted segments, if the window update in
14799 	 * the same segment is not accepted, TCP will incorrectly calculates
14800 	 * that it can send more segments.  This can create a deadlock
14801 	 * with the receiver if its window becomes zero.
14802 	 */
14803 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14804 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14805 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14806 		/*
14807 		 * The criteria for update is:
14808 		 *
14809 		 * 1. the segment acknowledges some data.  Or
14810 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14811 		 * 3. the segment is not old and the advertised window is
14812 		 * larger than the previous advertised window.
14813 		 */
14814 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14815 			flags |= TH_XMIT_NEEDED;
14816 		tcp->tcp_swnd = new_swnd;
14817 		if (new_swnd > tcp->tcp_max_swnd)
14818 			tcp->tcp_max_swnd = new_swnd;
14819 		tcp->tcp_swl1 = seg_seq;
14820 		tcp->tcp_swl2 = seg_ack;
14821 	}
14822 est:
14823 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14824 
14825 		switch (tcp->tcp_state) {
14826 		case TCPS_FIN_WAIT_1:
14827 			if (tcp->tcp_fin_acked) {
14828 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14829 				/*
14830 				 * We implement the non-standard BSD/SunOS
14831 				 * FIN_WAIT_2 flushing algorithm.
14832 				 * If there is no user attached to this
14833 				 * TCP endpoint, then this TCP struct
14834 				 * could hang around forever in FIN_WAIT_2
14835 				 * state if the peer forgets to send us
14836 				 * a FIN.  To prevent this, we wait only
14837 				 * 2*MSL (a convenient time value) for
14838 				 * the FIN to arrive.  If it doesn't show up,
14839 				 * we flush the TCP endpoint.  This algorithm,
14840 				 * though a violation of RFC-793, has worked
14841 				 * for over 10 years in BSD systems.
14842 				 * Note: SunOS 4.x waits 675 seconds before
14843 				 * flushing the FIN_WAIT_2 connection.
14844 				 */
14845 				TCP_TIMER_RESTART(tcp,
14846 				    tcps->tcps_fin_wait_2_flush_interval);
14847 			}
14848 			break;
14849 		case TCPS_FIN_WAIT_2:
14850 			break;	/* Shutdown hook? */
14851 		case TCPS_LAST_ACK:
14852 			freemsg(mp);
14853 			if (tcp->tcp_fin_acked) {
14854 				(void) tcp_clean_death(tcp, 0, 19);
14855 				return;
14856 			}
14857 			goto xmit_check;
14858 		case TCPS_CLOSING:
14859 			if (tcp->tcp_fin_acked) {
14860 				tcp->tcp_state = TCPS_TIME_WAIT;
14861 				/*
14862 				 * Unconditionally clear the exclusive binding
14863 				 * bit so this TIME-WAIT connection won't
14864 				 * interfere with new ones.
14865 				 */
14866 				tcp->tcp_exclbind = 0;
14867 				if (!TCP_IS_DETACHED(tcp)) {
14868 					TCP_TIMER_RESTART(tcp,
14869 					    tcps->tcps_time_wait_interval);
14870 				} else {
14871 					tcp_time_wait_append(tcp);
14872 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14873 				}
14874 			}
14875 			/*FALLTHRU*/
14876 		case TCPS_CLOSE_WAIT:
14877 			freemsg(mp);
14878 			goto xmit_check;
14879 		default:
14880 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14881 			break;
14882 		}
14883 	}
14884 	if (flags & TH_FIN) {
14885 		/* Make sure we ack the fin */
14886 		flags |= TH_ACK_NEEDED;
14887 		if (!tcp->tcp_fin_rcvd) {
14888 			tcp->tcp_fin_rcvd = B_TRUE;
14889 			tcp->tcp_rnxt++;
14890 			tcph = tcp->tcp_tcph;
14891 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14892 
14893 			/*
14894 			 * Generate the ordrel_ind at the end unless we
14895 			 * are an eager guy.
14896 			 * In the eager case tcp_rsrv will do this when run
14897 			 * after tcp_accept is done.
14898 			 */
14899 			if (tcp->tcp_listener == NULL &&
14900 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14901 				flags |= TH_ORDREL_NEEDED;
14902 			switch (tcp->tcp_state) {
14903 			case TCPS_SYN_RCVD:
14904 			case TCPS_ESTABLISHED:
14905 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14906 				/* Keepalive? */
14907 				break;
14908 			case TCPS_FIN_WAIT_1:
14909 				if (!tcp->tcp_fin_acked) {
14910 					tcp->tcp_state = TCPS_CLOSING;
14911 					break;
14912 				}
14913 				/* FALLTHRU */
14914 			case TCPS_FIN_WAIT_2:
14915 				tcp->tcp_state = TCPS_TIME_WAIT;
14916 				/*
14917 				 * Unconditionally clear the exclusive binding
14918 				 * bit so this TIME-WAIT connection won't
14919 				 * interfere with new ones.
14920 				 */
14921 				tcp->tcp_exclbind = 0;
14922 				if (!TCP_IS_DETACHED(tcp)) {
14923 					TCP_TIMER_RESTART(tcp,
14924 					    tcps->tcps_time_wait_interval);
14925 				} else {
14926 					tcp_time_wait_append(tcp);
14927 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14928 				}
14929 				if (seg_len) {
14930 					/*
14931 					 * implies data piggybacked on FIN.
14932 					 * break to handle data.
14933 					 */
14934 					break;
14935 				}
14936 				freemsg(mp);
14937 				goto ack_check;
14938 			}
14939 		}
14940 	}
14941 	if (mp == NULL)
14942 		goto xmit_check;
14943 	if (seg_len == 0) {
14944 		freemsg(mp);
14945 		goto xmit_check;
14946 	}
14947 	if (mp->b_rptr == mp->b_wptr) {
14948 		/*
14949 		 * The header has been consumed, so we remove the
14950 		 * zero-length mblk here.
14951 		 */
14952 		mp1 = mp;
14953 		mp = mp->b_cont;
14954 		freeb(mp1);
14955 	}
14956 update_ack:
14957 	tcph = tcp->tcp_tcph;
14958 	tcp->tcp_rack_cnt++;
14959 	{
14960 		uint32_t cur_max;
14961 
14962 		cur_max = tcp->tcp_rack_cur_max;
14963 		if (tcp->tcp_rack_cnt >= cur_max) {
14964 			/*
14965 			 * We have more unacked data than we should - send
14966 			 * an ACK now.
14967 			 */
14968 			flags |= TH_ACK_NEEDED;
14969 			cur_max++;
14970 			if (cur_max > tcp->tcp_rack_abs_max)
14971 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
14972 			else
14973 				tcp->tcp_rack_cur_max = cur_max;
14974 		} else if (TCP_IS_DETACHED(tcp)) {
14975 			/* We don't have an ACK timer for detached TCP. */
14976 			flags |= TH_ACK_NEEDED;
14977 		} else if (seg_len < mss) {
14978 			/*
14979 			 * If we get a segment that is less than an mss, and we
14980 			 * already have unacknowledged data, and the amount
14981 			 * unacknowledged is not a multiple of mss, then we
14982 			 * better generate an ACK now.  Otherwise, this may be
14983 			 * the tail piece of a transaction, and we would rather
14984 			 * wait for the response.
14985 			 */
14986 			uint32_t udif;
14987 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
14988 			    (uintptr_t)INT_MAX);
14989 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
14990 			if (udif && (udif % mss))
14991 				flags |= TH_ACK_NEEDED;
14992 			else
14993 				flags |= TH_ACK_TIMER_NEEDED;
14994 		} else {
14995 			/* Start delayed ack timer */
14996 			flags |= TH_ACK_TIMER_NEEDED;
14997 		}
14998 	}
14999 	tcp->tcp_rnxt += seg_len;
15000 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15001 
15002 	if (mp == NULL)
15003 		goto xmit_check;
15004 
15005 	/* Update SACK list */
15006 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15007 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15008 		    &(tcp->tcp_num_sack_blk));
15009 	}
15010 
15011 	if (tcp->tcp_urp_mp) {
15012 		tcp->tcp_urp_mp->b_cont = mp;
15013 		mp = tcp->tcp_urp_mp;
15014 		tcp->tcp_urp_mp = NULL;
15015 		/* Ready for a new signal. */
15016 		tcp->tcp_urp_last_valid = B_FALSE;
15017 #ifdef DEBUG
15018 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15019 		    "tcp_rput: sending exdata_ind %s",
15020 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15021 #endif /* DEBUG */
15022 	}
15023 
15024 	/*
15025 	 * Check for ancillary data changes compared to last segment.
15026 	 */
15027 	if (tcp->tcp_ipv6_recvancillary != 0) {
15028 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15029 		ASSERT(mp != NULL);
15030 	}
15031 
15032 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15033 		/*
15034 		 * Side queue inbound data until the accept happens.
15035 		 * tcp_accept/tcp_rput drains this when the accept happens.
15036 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15037 		 * T_EXDATA_IND) it is queued on b_next.
15038 		 * XXX Make urgent data use this. Requires:
15039 		 *	Removing tcp_listener check for TH_URG
15040 		 *	Making M_PCPROTO and MARK messages skip the eager case
15041 		 */
15042 
15043 		if (tcp->tcp_kssl_pending) {
15044 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15045 			    mblk_t *, mp);
15046 			tcp_kssl_input(tcp, mp);
15047 		} else {
15048 			tcp_rcv_enqueue(tcp, mp, seg_len);
15049 		}
15050 	} else {
15051 		sodirect_t	*sodp = tcp->tcp_sodirect;
15052 
15053 		/*
15054 		 * If an sodirect connection and an enabled sodirect_t then
15055 		 * sodp will be set to point to the tcp_t/sonode_t shared
15056 		 * sodirect_t and the sodirect_t's lock will be held.
15057 		 */
15058 		if (sodp != NULL) {
15059 			mutex_enter(sodp->sod_lockp);
15060 			if (!(sodp->sod_state & SOD_ENABLED) ||
15061 			    (tcp->tcp_kssl_ctx != NULL &&
15062 			    DB_TYPE(mp) == M_DATA)) {
15063 				sodp = NULL;
15064 			}
15065 			mutex_exit(sodp->sod_lockp);
15066 		}
15067 		if (mp->b_datap->db_type != M_DATA ||
15068 		    (flags & TH_MARKNEXT_NEEDED)) {
15069 			if (IPCL_IS_NONSTR(connp)) {
15070 				int error;
15071 
15072 				if ((*connp->conn_upcalls->su_recv)
15073 				    (connp->conn_upper_handle, mp,
15074 				    seg_len, 0, &error, NULL) <= 0) {
15075 					if (error == ENOSPC) {
15076 						tcp->tcp_rwnd -= seg_len;
15077 					} else if (error == EOPNOTSUPP) {
15078 						tcp_rcv_enqueue(tcp, mp,
15079 						    seg_len);
15080 					}
15081 				}
15082 			} else if (sodp != NULL) {
15083 				mutex_enter(sodp->sod_lockp);
15084 				SOD_UIOAFINI(sodp);
15085 				if (!SOD_QEMPTY(sodp) &&
15086 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15087 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15088 					/* sod_wakeup() did the mutex_exit() */
15089 				} else {
15090 					mutex_exit(sodp->sod_lockp);
15091 				}
15092 			} else if (tcp->tcp_rcv_list != NULL) {
15093 				flags |= tcp_rcv_drain(tcp);
15094 			}
15095 			ASSERT(tcp->tcp_rcv_list == NULL ||
15096 			    tcp->tcp_fused_sigurg);
15097 
15098 			if (flags & TH_MARKNEXT_NEEDED) {
15099 #ifdef DEBUG
15100 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15101 				    "tcp_rput: sending MSGMARKNEXT %s",
15102 				    tcp_display(tcp, NULL,
15103 				    DISP_PORT_ONLY));
15104 #endif /* DEBUG */
15105 				mp->b_flag |= MSGMARKNEXT;
15106 				flags &= ~TH_MARKNEXT_NEEDED;
15107 			}
15108 
15109 			/* Does this need SSL processing first? */
15110 			if ((tcp->tcp_kssl_ctx != NULL) &&
15111 			    (DB_TYPE(mp) == M_DATA)) {
15112 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15113 				    mblk_t *, mp);
15114 				tcp_kssl_input(tcp, mp);
15115 			} else if (!IPCL_IS_NONSTR(connp)) {
15116 				/* Already handled non-STREAMS case. */
15117 				putnext(tcp->tcp_rq, mp);
15118 				if (!canputnext(tcp->tcp_rq))
15119 					tcp->tcp_rwnd -= seg_len;
15120 			}
15121 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15122 		    (DB_TYPE(mp) == M_DATA)) {
15123 			/* Does this need SSL processing first? */
15124 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15125 			tcp_kssl_input(tcp, mp);
15126 		} else if (IPCL_IS_NONSTR(connp)) {
15127 			/* Non-STREAMS socket */
15128 			boolean_t push = flags & (TH_PUSH|TH_FIN);
15129 			int	error;
15130 
15131 			if ((*connp->conn_upcalls->su_recv)(
15132 			    connp->conn_upper_handle,
15133 			    mp, seg_len, 0, &error, &push) <= 0) {
15134 				if (error == ENOSPC) {
15135 					tcp->tcp_rwnd -= seg_len;
15136 				} else if (error == EOPNOTSUPP) {
15137 					tcp_rcv_enqueue(tcp, mp, seg_len);
15138 				}
15139 			} else if (push) {
15140 				/*
15141 				 * PUSH bit set and sockfs is not
15142 				 * flow controlled
15143 				 */
15144 				flags |= tcp_rwnd_reopen(tcp);
15145 			}
15146 		} else if (sodp != NULL) {
15147 			/*
15148 			 * Sodirect so all mblk_t's are queued on the
15149 			 * socket directly, check for wakeup of blocked
15150 			 * reader (if any), and last if flow-controled.
15151 			 */
15152 			mutex_enter(sodp->sod_lockp);
15153 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15154 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15155 			    (flags & (TH_PUSH|TH_FIN))) {
15156 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15157 				/* sod_wakeup() did the mutex_exit() */
15158 			} else {
15159 				if (SOD_QFULL(sodp)) {
15160 					/* Q is full, need backenable */
15161 					SOD_QSETBE(sodp);
15162 				}
15163 				mutex_exit(sodp->sod_lockp);
15164 			}
15165 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15166 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15167 			if (tcp->tcp_rcv_list != NULL) {
15168 				/*
15169 				 * Enqueue the new segment first and then
15170 				 * call tcp_rcv_drain() to send all data
15171 				 * up.  The other way to do this is to
15172 				 * send all queued data up and then call
15173 				 * putnext() to send the new segment up.
15174 				 * This way can remove the else part later
15175 				 * on.
15176 				 *
15177 				 * We don't do this to avoid one more call to
15178 				 * canputnext() as tcp_rcv_drain() needs to
15179 				 * call canputnext().
15180 				 */
15181 				tcp_rcv_enqueue(tcp, mp, seg_len);
15182 				flags |= tcp_rcv_drain(tcp);
15183 			} else {
15184 				putnext(tcp->tcp_rq, mp);
15185 				if (!canputnext(tcp->tcp_rq))
15186 					tcp->tcp_rwnd -= seg_len;
15187 			}
15188 		} else {
15189 			/*
15190 			 * Enqueue all packets when processing an mblk
15191 			 * from the co queue and also enqueue normal packets.
15192 			 * For packets which belong to SSL stream do SSL
15193 			 * processing first.
15194 			 */
15195 			tcp_rcv_enqueue(tcp, mp, seg_len);
15196 		}
15197 		/*
15198 		 * Make sure the timer is running if we have data waiting
15199 		 * for a push bit. This provides resiliency against
15200 		 * implementations that do not correctly generate push bits.
15201 		 *
15202 		 * Note, for sodirect if Q isn't empty and there's not a
15203 		 * pending wakeup then we need a timer. Also note that sodp
15204 		 * is assumed to be still valid after exit()ing the sod_lockp
15205 		 * above and while the SOD state can change it can only change
15206 		 * such that the Q is empty now even though data was added
15207 		 * above.
15208 		 */
15209 		if (!IPCL_IS_NONSTR(connp) &&
15210 		    ((sodp != NULL && !SOD_QEMPTY(sodp) &&
15211 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15212 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15213 		    tcp->tcp_push_tid == 0) {
15214 			/*
15215 			 * The connection may be closed at this point, so don't
15216 			 * do anything for a detached tcp.
15217 			 */
15218 			if (!TCP_IS_DETACHED(tcp))
15219 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15220 				    tcp_push_timer,
15221 				    MSEC_TO_TICK(
15222 				    tcps->tcps_push_timer_interval));
15223 		}
15224 	}
15225 
15226 xmit_check:
15227 	/* Is there anything left to do? */
15228 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15229 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15230 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15231 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15232 		goto done;
15233 
15234 	/* Any transmit work to do and a non-zero window? */
15235 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15236 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15237 		if (flags & TH_REXMIT_NEEDED) {
15238 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15239 
15240 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15241 			if (snd_size > mss)
15242 				snd_size = mss;
15243 			if (snd_size > tcp->tcp_swnd)
15244 				snd_size = tcp->tcp_swnd;
15245 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15246 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15247 			    B_TRUE);
15248 
15249 			if (mp1 != NULL) {
15250 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15251 				tcp->tcp_csuna = tcp->tcp_snxt;
15252 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15253 				UPDATE_MIB(&tcps->tcps_mib,
15254 				    tcpRetransBytes, snd_size);
15255 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15256 			}
15257 		}
15258 		if (flags & TH_NEED_SACK_REXMIT) {
15259 			tcp_sack_rxmit(tcp, &flags);
15260 		}
15261 		/*
15262 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15263 		 * out new segment.  Note that tcp_rexmit should not be
15264 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15265 		 */
15266 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15267 			if (!tcp->tcp_rexmit) {
15268 				tcp_wput_data(tcp, NULL, B_FALSE);
15269 			} else {
15270 				tcp_ss_rexmit(tcp);
15271 			}
15272 		}
15273 		/*
15274 		 * Adjust tcp_cwnd back to normal value after sending
15275 		 * new data segments.
15276 		 */
15277 		if (flags & TH_LIMIT_XMIT) {
15278 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15279 			/*
15280 			 * This will restart the timer.  Restarting the
15281 			 * timer is used to avoid a timeout before the
15282 			 * limited transmitted segment's ACK gets back.
15283 			 */
15284 			if (tcp->tcp_xmit_head != NULL)
15285 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15286 		}
15287 
15288 		/* Anything more to do? */
15289 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15290 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15291 			goto done;
15292 	}
15293 ack_check:
15294 	if (flags & TH_SEND_URP_MARK) {
15295 		ASSERT(tcp->tcp_urp_mark_mp);
15296 		ASSERT(!IPCL_IS_NONSTR(connp));
15297 		/*
15298 		 * Send up any queued data and then send the mark message
15299 		 */
15300 		sodirect_t *sodp;
15301 
15302 		SOD_PTR_ENTER(tcp, sodp);
15303 
15304 		mp1 = tcp->tcp_urp_mark_mp;
15305 		tcp->tcp_urp_mark_mp = NULL;
15306 		if (sodp != NULL) {
15307 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15308 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15309 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15310 			}
15311 			ASSERT(tcp->tcp_rcv_list == NULL);
15312 
15313 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15314 			/* sod_wakeup() does the mutex_exit() */
15315 		} else if (tcp->tcp_rcv_list != NULL) {
15316 			flags |= tcp_rcv_drain(tcp);
15317 
15318 			ASSERT(tcp->tcp_rcv_list == NULL ||
15319 			    tcp->tcp_fused_sigurg);
15320 
15321 		}
15322 		putnext(tcp->tcp_rq, mp1);
15323 #ifdef DEBUG
15324 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15325 		    "tcp_rput: sending zero-length %s %s",
15326 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15327 		    "MSGNOTMARKNEXT"),
15328 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15329 #endif /* DEBUG */
15330 		flags &= ~TH_SEND_URP_MARK;
15331 	}
15332 	if (flags & TH_ACK_NEEDED) {
15333 		/*
15334 		 * Time to send an ack for some reason.
15335 		 */
15336 		mp1 = tcp_ack_mp(tcp);
15337 
15338 		if (mp1 != NULL) {
15339 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15340 			BUMP_LOCAL(tcp->tcp_obsegs);
15341 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15342 		}
15343 		if (tcp->tcp_ack_tid != 0) {
15344 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15345 			tcp->tcp_ack_tid = 0;
15346 		}
15347 	}
15348 	if (flags & TH_ACK_TIMER_NEEDED) {
15349 		/*
15350 		 * Arrange for deferred ACK or push wait timeout.
15351 		 * Start timer if it is not already running.
15352 		 */
15353 		if (tcp->tcp_ack_tid == 0) {
15354 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15355 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15356 			    (clock_t)tcps->tcps_local_dack_interval :
15357 			    (clock_t)tcps->tcps_deferred_ack_interval));
15358 		}
15359 	}
15360 	if (flags & TH_ORDREL_NEEDED) {
15361 		/*
15362 		 * Send up the ordrel_ind unless we are an eager guy.
15363 		 * In the eager case tcp_rsrv will do this when run
15364 		 * after tcp_accept is done.
15365 		 */
15366 		sodirect_t *sodp;
15367 
15368 		ASSERT(tcp->tcp_listener == NULL);
15369 
15370 		if (IPCL_IS_NONSTR(connp)) {
15371 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15372 			tcp->tcp_ordrel_done = B_TRUE;
15373 			(*connp->conn_upcalls->su_opctl)
15374 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15375 			goto done;
15376 		}
15377 
15378 		SOD_PTR_ENTER(tcp, sodp);
15379 		if (sodp != NULL) {
15380 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15381 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15382 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15383 			}
15384 			/* No more sodirect */
15385 			tcp->tcp_sodirect = NULL;
15386 			if (!SOD_QEMPTY(sodp)) {
15387 				/* Mblk(s) to process, notify */
15388 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15389 				/* sod_wakeup() does the mutex_exit() */
15390 			} else {
15391 				/* Nothing to process */
15392 				mutex_exit(sodp->sod_lockp);
15393 			}
15394 		} else if (tcp->tcp_rcv_list != NULL) {
15395 			/*
15396 			 * Push any mblk(s) enqueued from co processing.
15397 			 */
15398 			flags |= tcp_rcv_drain(tcp);
15399 
15400 			ASSERT(tcp->tcp_rcv_list == NULL ||
15401 			    tcp->tcp_fused_sigurg);
15402 		}
15403 
15404 		mp1 = tcp->tcp_ordrel_mp;
15405 		tcp->tcp_ordrel_mp = NULL;
15406 		tcp->tcp_ordrel_done = B_TRUE;
15407 		putnext(tcp->tcp_rq, mp1);
15408 	}
15409 done:
15410 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15411 }
15412 
15413 /*
15414  * This function does PAWS protection check. Returns B_TRUE if the
15415  * segment passes the PAWS test, else returns B_FALSE.
15416  */
15417 boolean_t
15418 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15419 {
15420 	uint8_t	flags;
15421 	int	options;
15422 	uint8_t *up;
15423 
15424 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15425 	/*
15426 	 * If timestamp option is aligned nicely, get values inline,
15427 	 * otherwise call general routine to parse.  Only do that
15428 	 * if timestamp is the only option.
15429 	 */
15430 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15431 	    TCPOPT_REAL_TS_LEN &&
15432 	    OK_32PTR((up = ((uint8_t *)tcph) +
15433 	    TCP_MIN_HEADER_LENGTH)) &&
15434 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15435 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15436 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15437 
15438 		options = TCP_OPT_TSTAMP_PRESENT;
15439 	} else {
15440 		if (tcp->tcp_snd_sack_ok) {
15441 			tcpoptp->tcp = tcp;
15442 		} else {
15443 			tcpoptp->tcp = NULL;
15444 		}
15445 		options = tcp_parse_options(tcph, tcpoptp);
15446 	}
15447 
15448 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15449 		/*
15450 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15451 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15452 		 */
15453 		if ((flags & TH_RST) == 0 &&
15454 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15455 		    tcp->tcp_ts_recent)) {
15456 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15457 			    PAWS_TIMEOUT)) {
15458 				/* This segment is not acceptable. */
15459 				return (B_FALSE);
15460 			} else {
15461 				/*
15462 				 * Connection has been idle for
15463 				 * too long.  Reset the timestamp
15464 				 * and assume the segment is valid.
15465 				 */
15466 				tcp->tcp_ts_recent =
15467 				    tcpoptp->tcp_opt_ts_val;
15468 			}
15469 		}
15470 	} else {
15471 		/*
15472 		 * If we don't get a timestamp on every packet, we
15473 		 * figure we can't really trust 'em, so we stop sending
15474 		 * and parsing them.
15475 		 */
15476 		tcp->tcp_snd_ts_ok = B_FALSE;
15477 
15478 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15479 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15480 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15481 		/*
15482 		 * Adjust the tcp_mss accordingly. We also need to
15483 		 * adjust tcp_cwnd here in accordance with the new mss.
15484 		 * But we avoid doing a slow start here so as to not
15485 		 * to lose on the transfer rate built up so far.
15486 		 */
15487 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15488 		if (tcp->tcp_snd_sack_ok) {
15489 			ASSERT(tcp->tcp_sack_info != NULL);
15490 			tcp->tcp_max_sack_blk = 4;
15491 		}
15492 	}
15493 	return (B_TRUE);
15494 }
15495 
15496 /*
15497  * Attach ancillary data to a received TCP segments for the
15498  * ancillary pieces requested by the application that are
15499  * different than they were in the previous data segment.
15500  *
15501  * Save the "current" values once memory allocation is ok so that
15502  * when memory allocation fails we can just wait for the next data segment.
15503  */
15504 static mblk_t *
15505 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15506 {
15507 	struct T_optdata_ind *todi;
15508 	int optlen;
15509 	uchar_t *optptr;
15510 	struct T_opthdr *toh;
15511 	uint_t addflag;	/* Which pieces to add */
15512 	mblk_t *mp1;
15513 
15514 	optlen = 0;
15515 	addflag = 0;
15516 	/* If app asked for pktinfo and the index has changed ... */
15517 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15518 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15519 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15520 		optlen += sizeof (struct T_opthdr) +
15521 		    sizeof (struct in6_pktinfo);
15522 		addflag |= TCP_IPV6_RECVPKTINFO;
15523 	}
15524 	/* If app asked for hoplimit and it has changed ... */
15525 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15526 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15527 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15528 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15529 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15530 	}
15531 	/* If app asked for tclass and it has changed ... */
15532 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15533 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15534 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15535 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15536 		addflag |= TCP_IPV6_RECVTCLASS;
15537 	}
15538 	/*
15539 	 * If app asked for hopbyhop headers and it has changed ...
15540 	 * For security labels, note that (1) security labels can't change on
15541 	 * a connected socket at all, (2) we're connected to at most one peer,
15542 	 * (3) if anything changes, then it must be some other extra option.
15543 	 */
15544 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15545 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15546 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15547 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15548 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15549 		    tcp->tcp_label_len;
15550 		addflag |= TCP_IPV6_RECVHOPOPTS;
15551 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15552 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15553 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15554 			return (mp);
15555 	}
15556 	/* If app asked for dst headers before routing headers ... */
15557 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15558 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15559 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15560 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15561 		optlen += sizeof (struct T_opthdr) +
15562 		    ipp->ipp_rtdstoptslen;
15563 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15564 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15565 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15566 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15567 			return (mp);
15568 	}
15569 	/* If app asked for routing headers and it has changed ... */
15570 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15571 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15572 	    (ipp->ipp_fields & IPPF_RTHDR),
15573 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15574 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15575 		addflag |= TCP_IPV6_RECVRTHDR;
15576 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15577 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15578 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15579 			return (mp);
15580 	}
15581 	/* If app asked for dest headers and it has changed ... */
15582 	if ((tcp->tcp_ipv6_recvancillary &
15583 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15584 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15585 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15586 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15587 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15588 		addflag |= TCP_IPV6_RECVDSTOPTS;
15589 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15590 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15591 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15592 			return (mp);
15593 	}
15594 
15595 	if (optlen == 0) {
15596 		/* Nothing to add */
15597 		return (mp);
15598 	}
15599 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15600 	if (mp1 == NULL) {
15601 		/*
15602 		 * Defer sending ancillary data until the next TCP segment
15603 		 * arrives.
15604 		 */
15605 		return (mp);
15606 	}
15607 	mp1->b_cont = mp;
15608 	mp = mp1;
15609 	mp->b_wptr += sizeof (*todi) + optlen;
15610 	mp->b_datap->db_type = M_PROTO;
15611 	todi = (struct T_optdata_ind *)mp->b_rptr;
15612 	todi->PRIM_type = T_OPTDATA_IND;
15613 	todi->DATA_flag = 1;	/* MORE data */
15614 	todi->OPT_length = optlen;
15615 	todi->OPT_offset = sizeof (*todi);
15616 	optptr = (uchar_t *)&todi[1];
15617 	/*
15618 	 * If app asked for pktinfo and the index has changed ...
15619 	 * Note that the local address never changes for the connection.
15620 	 */
15621 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15622 		struct in6_pktinfo *pkti;
15623 
15624 		toh = (struct T_opthdr *)optptr;
15625 		toh->level = IPPROTO_IPV6;
15626 		toh->name = IPV6_PKTINFO;
15627 		toh->len = sizeof (*toh) + sizeof (*pkti);
15628 		toh->status = 0;
15629 		optptr += sizeof (*toh);
15630 		pkti = (struct in6_pktinfo *)optptr;
15631 		if (tcp->tcp_ipversion == IPV6_VERSION)
15632 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15633 		else
15634 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15635 			    &pkti->ipi6_addr);
15636 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15637 		optptr += sizeof (*pkti);
15638 		ASSERT(OK_32PTR(optptr));
15639 		/* Save as "last" value */
15640 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15641 	}
15642 	/* If app asked for hoplimit and it has changed ... */
15643 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15644 		toh = (struct T_opthdr *)optptr;
15645 		toh->level = IPPROTO_IPV6;
15646 		toh->name = IPV6_HOPLIMIT;
15647 		toh->len = sizeof (*toh) + sizeof (uint_t);
15648 		toh->status = 0;
15649 		optptr += sizeof (*toh);
15650 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15651 		optptr += sizeof (uint_t);
15652 		ASSERT(OK_32PTR(optptr));
15653 		/* Save as "last" value */
15654 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15655 	}
15656 	/* If app asked for tclass and it has changed ... */
15657 	if (addflag & TCP_IPV6_RECVTCLASS) {
15658 		toh = (struct T_opthdr *)optptr;
15659 		toh->level = IPPROTO_IPV6;
15660 		toh->name = IPV6_TCLASS;
15661 		toh->len = sizeof (*toh) + sizeof (uint_t);
15662 		toh->status = 0;
15663 		optptr += sizeof (*toh);
15664 		*(uint_t *)optptr = ipp->ipp_tclass;
15665 		optptr += sizeof (uint_t);
15666 		ASSERT(OK_32PTR(optptr));
15667 		/* Save as "last" value */
15668 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15669 	}
15670 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15671 		toh = (struct T_opthdr *)optptr;
15672 		toh->level = IPPROTO_IPV6;
15673 		toh->name = IPV6_HOPOPTS;
15674 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15675 		    tcp->tcp_label_len;
15676 		toh->status = 0;
15677 		optptr += sizeof (*toh);
15678 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15679 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15680 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15681 		ASSERT(OK_32PTR(optptr));
15682 		/* Save as last value */
15683 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15684 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15685 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15686 	}
15687 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15688 		toh = (struct T_opthdr *)optptr;
15689 		toh->level = IPPROTO_IPV6;
15690 		toh->name = IPV6_RTHDRDSTOPTS;
15691 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15692 		toh->status = 0;
15693 		optptr += sizeof (*toh);
15694 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15695 		optptr += ipp->ipp_rtdstoptslen;
15696 		ASSERT(OK_32PTR(optptr));
15697 		/* Save as last value */
15698 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15699 		    &tcp->tcp_rtdstoptslen,
15700 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15701 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15702 	}
15703 	if (addflag & TCP_IPV6_RECVRTHDR) {
15704 		toh = (struct T_opthdr *)optptr;
15705 		toh->level = IPPROTO_IPV6;
15706 		toh->name = IPV6_RTHDR;
15707 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15708 		toh->status = 0;
15709 		optptr += sizeof (*toh);
15710 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15711 		optptr += ipp->ipp_rthdrlen;
15712 		ASSERT(OK_32PTR(optptr));
15713 		/* Save as last value */
15714 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15715 		    (ipp->ipp_fields & IPPF_RTHDR),
15716 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15717 	}
15718 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15719 		toh = (struct T_opthdr *)optptr;
15720 		toh->level = IPPROTO_IPV6;
15721 		toh->name = IPV6_DSTOPTS;
15722 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15723 		toh->status = 0;
15724 		optptr += sizeof (*toh);
15725 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15726 		optptr += ipp->ipp_dstoptslen;
15727 		ASSERT(OK_32PTR(optptr));
15728 		/* Save as last value */
15729 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15730 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15731 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15732 	}
15733 	ASSERT(optptr == mp->b_wptr);
15734 	return (mp);
15735 }
15736 
15737 /*
15738  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15739  * or a "bad" IRE detected by tcp_adapt_ire.
15740  * We can't tell if the failure was due to the laddr or the faddr
15741  * thus we clear out all addresses and ports.
15742  */
15743 static void
15744 tcp_tpi_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15745 {
15746 	queue_t	*q = tcp->tcp_rq;
15747 	tcph_t	*tcph;
15748 	struct T_error_ack *tea;
15749 	conn_t	*connp = tcp->tcp_connp;
15750 
15751 
15752 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15753 
15754 	if (mp->b_cont) {
15755 		freemsg(mp->b_cont);
15756 		mp->b_cont = NULL;
15757 	}
15758 	tea = (struct T_error_ack *)mp->b_rptr;
15759 	switch (tea->PRIM_type) {
15760 	case T_BIND_ACK:
15761 		/*
15762 		 * Need to unbind with classifier since we were just told that
15763 		 * our bind succeeded.
15764 		 */
15765 		tcp->tcp_hard_bound = B_FALSE;
15766 		tcp->tcp_hard_binding = B_FALSE;
15767 
15768 		ipcl_hash_remove(connp);
15769 		/* Reuse the mblk if possible */
15770 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15771 		    sizeof (*tea));
15772 		mp->b_rptr = mp->b_datap->db_base;
15773 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15774 		tea = (struct T_error_ack *)mp->b_rptr;
15775 		tea->PRIM_type = T_ERROR_ACK;
15776 		tea->TLI_error = TSYSERR;
15777 		tea->UNIX_error = error;
15778 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15779 			tea->ERROR_prim = T_CONN_REQ;
15780 		} else {
15781 			tea->ERROR_prim = O_T_BIND_REQ;
15782 		}
15783 		break;
15784 
15785 	case T_ERROR_ACK:
15786 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15787 			tea->ERROR_prim = T_CONN_REQ;
15788 		break;
15789 	default:
15790 		panic("tcp_tpi_bind_failed: unexpected TPI type");
15791 		/*NOTREACHED*/
15792 	}
15793 
15794 	tcp->tcp_state = TCPS_IDLE;
15795 	if (tcp->tcp_ipversion == IPV4_VERSION)
15796 		tcp->tcp_ipha->ipha_src = 0;
15797 	else
15798 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15799 	/*
15800 	 * Copy of the src addr. in tcp_t is needed since
15801 	 * the lookup funcs. can only look at tcp_t
15802 	 */
15803 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15804 
15805 	tcph = tcp->tcp_tcph;
15806 	tcph->th_lport[0] = 0;
15807 	tcph->th_lport[1] = 0;
15808 	tcp_bind_hash_remove(tcp);
15809 	bzero(&connp->u_port, sizeof (connp->u_port));
15810 	/* blow away saved option results if any */
15811 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15812 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15813 
15814 	conn_delete_ire(tcp->tcp_connp, NULL);
15815 	putnext(q, mp);
15816 }
15817 
15818 /*
15819  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15820  * messages.
15821  */
15822 void
15823 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15824 {
15825 	uchar_t	*rptr = mp->b_rptr;
15826 	queue_t	*q = tcp->tcp_rq;
15827 	struct T_error_ack *tea;
15828 
15829 	switch (mp->b_datap->db_type) {
15830 	case M_PROTO:
15831 	case M_PCPROTO:
15832 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15833 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15834 			break;
15835 		tea = (struct T_error_ack *)rptr;
15836 		switch (tea->PRIM_type) {
15837 		case T_BIND_ACK:
15838 			/*
15839 			 * AF_INET socket should not be here.
15840 			 */
15841 			ASSERT(tcp->tcp_family != AF_INET &&
15842 			    tcp->tcp_family != AF_INET6);
15843 			(void) tcp_post_ip_bind(tcp, mp->b_cont, 0);
15844 			return;
15845 		case T_ERROR_ACK:
15846 			if (tcp->tcp_debug) {
15847 				(void) strlog(TCP_MOD_ID, 0, 1,
15848 				    SL_TRACE|SL_ERROR,
15849 				    "tcp_rput_other: case T_ERROR_ACK, "
15850 				    "ERROR_prim == %d",
15851 				    tea->ERROR_prim);
15852 			}
15853 			switch (tea->ERROR_prim) {
15854 			case O_T_BIND_REQ:
15855 			case T_BIND_REQ:
15856 				ASSERT(tcp->tcp_family != AF_INET);
15857 				tcp_tpi_bind_failed(tcp, mp,
15858 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
15859 				    ENETUNREACH : EADDRNOTAVAIL));
15860 				return;
15861 			case T_SVR4_OPTMGMT_REQ:
15862 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
15863 					/* T_OPTMGMT_REQ generated by TCP */
15864 					printf("T_SVR4_OPTMGMT_REQ failed "
15865 					    "%d/%d - dropped (cnt %d)\n",
15866 					    tea->TLI_error, tea->UNIX_error,
15867 					    tcp->tcp_drop_opt_ack_cnt);
15868 					freemsg(mp);
15869 					tcp->tcp_drop_opt_ack_cnt--;
15870 					return;
15871 				}
15872 				break;
15873 			}
15874 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
15875 			    tcp->tcp_drop_opt_ack_cnt > 0) {
15876 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
15877 				    "- dropped (cnt %d)\n",
15878 				    tea->TLI_error, tea->UNIX_error,
15879 				    tcp->tcp_drop_opt_ack_cnt);
15880 				freemsg(mp);
15881 				tcp->tcp_drop_opt_ack_cnt--;
15882 				return;
15883 			}
15884 			break;
15885 		case T_OPTMGMT_ACK:
15886 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
15887 				/* T_OPTMGMT_REQ generated by TCP */
15888 				freemsg(mp);
15889 				tcp->tcp_drop_opt_ack_cnt--;
15890 				return;
15891 			}
15892 			break;
15893 		default:
15894 			ASSERT(tea->ERROR_prim != T_UNBIND_REQ);
15895 			break;
15896 		}
15897 		break;
15898 	case M_FLUSH:
15899 		if (*rptr & FLUSHR)
15900 			flushq(q, FLUSHDATA);
15901 		break;
15902 	default:
15903 		/* M_CTL will be directly sent to tcp_icmp_error() */
15904 		ASSERT(DB_TYPE(mp) != M_CTL);
15905 		break;
15906 	}
15907 	/*
15908 	 * Make sure we set this bit before sending the ACK for
15909 	 * bind. Otherwise accept could possibly run and free
15910 	 * this tcp struct.
15911 	 */
15912 	ASSERT(q != NULL);
15913 	putnext(q, mp);
15914 }
15915 
15916 /* ARGSUSED */
15917 static void
15918 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
15919 {
15920 	conn_t	*connp = (conn_t *)arg;
15921 	tcp_t	*tcp = connp->conn_tcp;
15922 	queue_t	*q = tcp->tcp_rq;
15923 	uint_t	thwin;
15924 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15925 	sodirect_t	*sodp;
15926 	boolean_t	fc;
15927 
15928 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
15929 	tcp->tcp_rsrv_mp = mp;
15930 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
15931 
15932 	TCP_STAT(tcps, tcp_rsrv_calls);
15933 
15934 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
15935 		return;
15936 	}
15937 
15938 	if (tcp->tcp_fused) {
15939 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
15940 
15941 		ASSERT(tcp->tcp_fused);
15942 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
15943 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
15944 		ASSERT(!TCP_IS_DETACHED(tcp));
15945 		ASSERT(tcp->tcp_connp->conn_sqp ==
15946 		    peer_tcp->tcp_connp->conn_sqp);
15947 
15948 		/*
15949 		 * Normally we would not get backenabled in synchronous
15950 		 * streams mode, but in case this happens, we need to plug
15951 		 * synchronous streams during our drain to prevent a race
15952 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
15953 		 */
15954 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
15955 		if (tcp->tcp_rcv_list != NULL)
15956 			(void) tcp_rcv_drain(tcp);
15957 
15958 		if (peer_tcp > tcp) {
15959 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15960 			mutex_enter(&tcp->tcp_non_sq_lock);
15961 		} else {
15962 			mutex_enter(&tcp->tcp_non_sq_lock);
15963 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
15964 		}
15965 
15966 		if (peer_tcp->tcp_flow_stopped &&
15967 		    (TCP_UNSENT_BYTES(peer_tcp) <=
15968 		    peer_tcp->tcp_xmit_lowater)) {
15969 			tcp_clrqfull(peer_tcp);
15970 		}
15971 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
15972 		mutex_exit(&tcp->tcp_non_sq_lock);
15973 
15974 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
15975 		TCP_STAT(tcps, tcp_fusion_backenabled);
15976 		return;
15977 	}
15978 
15979 	SOD_PTR_ENTER(tcp, sodp);
15980 	if (sodp != NULL) {
15981 		/* An sodirect connection */
15982 		if (SOD_QFULL(sodp)) {
15983 			/* Flow-controlled, need another back-enable */
15984 			fc = B_TRUE;
15985 			SOD_QSETBE(sodp);
15986 		} else {
15987 			/* Not flow-controlled */
15988 			fc = B_FALSE;
15989 		}
15990 		mutex_exit(sodp->sod_lockp);
15991 	} else if (canputnext(q)) {
15992 		/* STREAMS, not flow-controlled */
15993 		fc = B_FALSE;
15994 	} else {
15995 		/* STREAMS, flow-controlled */
15996 		fc = B_TRUE;
15997 	}
15998 	if (!fc) {
15999 		/* Not flow-controlled, open rwnd */
16000 		tcp->tcp_rwnd = q->q_hiwat;
16001 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16002 		    << tcp->tcp_rcv_ws;
16003 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16004 		/*
16005 		 * Send back a window update immediately if TCP is above
16006 		 * ESTABLISHED state and the increase of the rcv window
16007 		 * that the other side knows is at least 1 MSS after flow
16008 		 * control is lifted.
16009 		 */
16010 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16011 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16012 			tcp_xmit_ctl(NULL, tcp,
16013 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16014 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16015 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
16016 		}
16017 	}
16018 }
16019 
16020 /*
16021  * The read side service routine is called mostly when we get back-enabled as a
16022  * result of flow control relief.  Since we don't actually queue anything in
16023  * TCP, we have no data to send out of here.  What we do is clear the receive
16024  * window, and send out a window update.
16025  */
16026 static void
16027 tcp_rsrv(queue_t *q)
16028 {
16029 	conn_t		*connp = Q_TO_CONN(q);
16030 	tcp_t		*tcp = connp->conn_tcp;
16031 	mblk_t		*mp;
16032 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16033 
16034 	/* No code does a putq on the read side */
16035 	ASSERT(q->q_first == NULL);
16036 
16037 	/* Nothing to do for the default queue */
16038 	if (q == tcps->tcps_g_q) {
16039 		return;
16040 	}
16041 
16042 	/*
16043 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
16044 	 * been run.  So just return.
16045 	 */
16046 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
16047 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
16048 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
16049 		return;
16050 	}
16051 	tcp->tcp_rsrv_mp = NULL;
16052 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
16053 
16054 	CONN_INC_REF(connp);
16055 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16056 	    SQ_PROCESS, SQTAG_TCP_RSRV);
16057 }
16058 
16059 /*
16060  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16061  * We do not allow the receive window to shrink.  After setting rwnd,
16062  * set the flow control hiwat of the stream.
16063  *
16064  * This function is called in 2 cases:
16065  *
16066  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16067  *    connection (passive open) and in tcp_rput_data() for active connect.
16068  *    This is called after tcp_mss_set() when the desired MSS value is known.
16069  *    This makes sure that our window size is a mutiple of the other side's
16070  *    MSS.
16071  * 2) Handling SO_RCVBUF option.
16072  *
16073  * It is ASSUMED that the requested size is a multiple of the current MSS.
16074  *
16075  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16076  * user requests so.
16077  */
16078 static int
16079 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16080 {
16081 	uint32_t	mss = tcp->tcp_mss;
16082 	uint32_t	old_max_rwnd;
16083 	uint32_t	max_transmittable_rwnd;
16084 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16085 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16086 
16087 	if (tcp->tcp_fused) {
16088 		size_t sth_hiwat;
16089 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16090 
16091 		ASSERT(peer_tcp != NULL);
16092 		/*
16093 		 * Record the stream head's high water mark for
16094 		 * this endpoint; this is used for flow-control
16095 		 * purposes in tcp_fuse_output().
16096 		 */
16097 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16098 		if (!tcp_detached) {
16099 			(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16100 			    sth_hiwat);
16101 			if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
16102 				conn_t *connp = tcp->tcp_connp;
16103 				struct sock_proto_props sopp;
16104 
16105 				sopp.sopp_flags = SOCKOPT_RCVTHRESH;
16106 				sopp.sopp_rcvthresh = sth_hiwat >> 3;
16107 
16108 				(*connp->conn_upcalls->su_set_proto_props)
16109 				    (connp->conn_upper_handle, &sopp);
16110 			}
16111 		}
16112 
16113 		/*
16114 		 * In the fusion case, the maxpsz stream head value of
16115 		 * our peer is set according to its send buffer size
16116 		 * and our receive buffer size; since the latter may
16117 		 * have changed we need to update the peer's maxpsz.
16118 		 */
16119 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16120 		return (rwnd);
16121 	}
16122 
16123 	if (tcp_detached) {
16124 		old_max_rwnd = tcp->tcp_rwnd;
16125 	} else {
16126 		old_max_rwnd = tcp->tcp_recv_hiwater;
16127 	}
16128 
16129 	/*
16130 	 * Insist on a receive window that is at least
16131 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16132 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16133 	 * and delayed acknowledgement.
16134 	 */
16135 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16136 
16137 	/*
16138 	 * If window size info has already been exchanged, TCP should not
16139 	 * shrink the window.  Shrinking window is doable if done carefully.
16140 	 * We may add that support later.  But so far there is not a real
16141 	 * need to do that.
16142 	 */
16143 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16144 		/* MSS may have changed, do a round up again. */
16145 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16146 	}
16147 
16148 	/*
16149 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16150 	 * can be applied even before the window scale option is decided.
16151 	 */
16152 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16153 	if (rwnd > max_transmittable_rwnd) {
16154 		rwnd = max_transmittable_rwnd -
16155 		    (max_transmittable_rwnd % mss);
16156 		if (rwnd < mss)
16157 			rwnd = max_transmittable_rwnd;
16158 		/*
16159 		 * If we're over the limit we may have to back down tcp_rwnd.
16160 		 * The increment below won't work for us. So we set all three
16161 		 * here and the increment below will have no effect.
16162 		 */
16163 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16164 	}
16165 	if (tcp->tcp_localnet) {
16166 		tcp->tcp_rack_abs_max =
16167 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16168 	} else {
16169 		/*
16170 		 * For a remote host on a different subnet (through a router),
16171 		 * we ack every other packet to be conforming to RFC1122.
16172 		 * tcp_deferred_acks_max is default to 2.
16173 		 */
16174 		tcp->tcp_rack_abs_max =
16175 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16176 	}
16177 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16178 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16179 	else
16180 		tcp->tcp_rack_cur_max = 0;
16181 	/*
16182 	 * Increment the current rwnd by the amount the maximum grew (we
16183 	 * can not overwrite it since we might be in the middle of a
16184 	 * connection.)
16185 	 */
16186 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16187 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16188 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16189 		tcp->tcp_cwnd_max = rwnd;
16190 
16191 	if (tcp_detached)
16192 		return (rwnd);
16193 	/*
16194 	 * We set the maximum receive window into rq->q_hiwat if it is
16195 	 * a STREAMS socket.
16196 	 * This is not actually used for flow control.
16197 	 */
16198 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
16199 		tcp->tcp_rq->q_hiwat = rwnd;
16200 	tcp->tcp_recv_hiwater = rwnd;
16201 	/*
16202 	 * Set the STREAM head high water mark. This doesn't have to be
16203 	 * here, since we are simply using default values, but we would
16204 	 * prefer to choose these values algorithmically, with a likely
16205 	 * relationship to rwnd.
16206 	 */
16207 	(void) proto_set_rx_hiwat(tcp->tcp_rq, tcp->tcp_connp,
16208 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16209 	return (rwnd);
16210 }
16211 
16212 /*
16213  * Return SNMP stuff in buffer in mpdata.
16214  */
16215 mblk_t *
16216 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16217 {
16218 	mblk_t			*mpdata;
16219 	mblk_t			*mp_conn_ctl = NULL;
16220 	mblk_t			*mp_conn_tail;
16221 	mblk_t			*mp_attr_ctl = NULL;
16222 	mblk_t			*mp_attr_tail;
16223 	mblk_t			*mp6_conn_ctl = NULL;
16224 	mblk_t			*mp6_conn_tail;
16225 	mblk_t			*mp6_attr_ctl = NULL;
16226 	mblk_t			*mp6_attr_tail;
16227 	struct opthdr		*optp;
16228 	mib2_tcpConnEntry_t	tce;
16229 	mib2_tcp6ConnEntry_t	tce6;
16230 	mib2_transportMLPEntry_t mlp;
16231 	connf_t			*connfp;
16232 	int			i;
16233 	boolean_t 		ispriv;
16234 	zoneid_t 		zoneid;
16235 	int			v4_conn_idx;
16236 	int			v6_conn_idx;
16237 	conn_t			*connp = Q_TO_CONN(q);
16238 	tcp_stack_t		*tcps;
16239 	ip_stack_t		*ipst;
16240 	mblk_t			*mp2ctl;
16241 
16242 	/*
16243 	 * make a copy of the original message
16244 	 */
16245 	mp2ctl = copymsg(mpctl);
16246 
16247 	if (mpctl == NULL ||
16248 	    (mpdata = mpctl->b_cont) == NULL ||
16249 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16250 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16251 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16252 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16253 		freemsg(mp_conn_ctl);
16254 		freemsg(mp_attr_ctl);
16255 		freemsg(mp6_conn_ctl);
16256 		freemsg(mp6_attr_ctl);
16257 		freemsg(mpctl);
16258 		freemsg(mp2ctl);
16259 		return (NULL);
16260 	}
16261 
16262 	ipst = connp->conn_netstack->netstack_ip;
16263 	tcps = connp->conn_netstack->netstack_tcp;
16264 
16265 	/* build table of connections -- need count in fixed part */
16266 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16267 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16268 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16269 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16270 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16271 
16272 	ispriv =
16273 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16274 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16275 
16276 	v4_conn_idx = v6_conn_idx = 0;
16277 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16278 
16279 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16280 		ipst = tcps->tcps_netstack->netstack_ip;
16281 
16282 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16283 
16284 		connp = NULL;
16285 
16286 		while ((connp =
16287 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16288 			tcp_t *tcp;
16289 			boolean_t needattr;
16290 
16291 			if (connp->conn_zoneid != zoneid)
16292 				continue;	/* not in this zone */
16293 
16294 			tcp = connp->conn_tcp;
16295 			UPDATE_MIB(&tcps->tcps_mib,
16296 			    tcpHCInSegs, tcp->tcp_ibsegs);
16297 			tcp->tcp_ibsegs = 0;
16298 			UPDATE_MIB(&tcps->tcps_mib,
16299 			    tcpHCOutSegs, tcp->tcp_obsegs);
16300 			tcp->tcp_obsegs = 0;
16301 
16302 			tce6.tcp6ConnState = tce.tcpConnState =
16303 			    tcp_snmp_state(tcp);
16304 			if (tce.tcpConnState == MIB2_TCP_established ||
16305 			    tce.tcpConnState == MIB2_TCP_closeWait)
16306 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16307 
16308 			needattr = B_FALSE;
16309 			bzero(&mlp, sizeof (mlp));
16310 			if (connp->conn_mlp_type != mlptSingle) {
16311 				if (connp->conn_mlp_type == mlptShared ||
16312 				    connp->conn_mlp_type == mlptBoth)
16313 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16314 				if (connp->conn_mlp_type == mlptPrivate ||
16315 				    connp->conn_mlp_type == mlptBoth)
16316 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16317 				needattr = B_TRUE;
16318 			}
16319 			if (connp->conn_peercred != NULL) {
16320 				ts_label_t *tsl;
16321 
16322 				tsl = crgetlabel(connp->conn_peercred);
16323 				mlp.tme_doi = label2doi(tsl);
16324 				mlp.tme_label = *label2bslabel(tsl);
16325 				needattr = B_TRUE;
16326 			}
16327 
16328 			/* Create a message to report on IPv6 entries */
16329 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16330 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16331 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16332 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16333 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16334 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16335 			/* Don't want just anybody seeing these... */
16336 			if (ispriv) {
16337 				tce6.tcp6ConnEntryInfo.ce_snxt =
16338 				    tcp->tcp_snxt;
16339 				tce6.tcp6ConnEntryInfo.ce_suna =
16340 				    tcp->tcp_suna;
16341 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16342 				    tcp->tcp_rnxt;
16343 				tce6.tcp6ConnEntryInfo.ce_rack =
16344 				    tcp->tcp_rack;
16345 			} else {
16346 				/*
16347 				 * Netstat, unfortunately, uses this to
16348 				 * get send/receive queue sizes.  How to fix?
16349 				 * Why not compute the difference only?
16350 				 */
16351 				tce6.tcp6ConnEntryInfo.ce_snxt =
16352 				    tcp->tcp_snxt - tcp->tcp_suna;
16353 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16354 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16355 				    tcp->tcp_rnxt - tcp->tcp_rack;
16356 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16357 			}
16358 
16359 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16360 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16361 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16362 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16363 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16364 
16365 			tce6.tcp6ConnCreationProcess =
16366 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16367 			    tcp->tcp_cpid;
16368 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16369 
16370 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16371 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16372 
16373 			mlp.tme_connidx = v6_conn_idx++;
16374 			if (needattr)
16375 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16376 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16377 			}
16378 			/*
16379 			 * Create an IPv4 table entry for IPv4 entries and also
16380 			 * for IPv6 entries which are bound to in6addr_any
16381 			 * but don't have IPV6_V6ONLY set.
16382 			 * (i.e. anything an IPv4 peer could connect to)
16383 			 */
16384 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16385 			    (tcp->tcp_state <= TCPS_LISTEN &&
16386 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16387 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16388 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16389 					tce.tcpConnRemAddress = INADDR_ANY;
16390 					tce.tcpConnLocalAddress = INADDR_ANY;
16391 				} else {
16392 					tce.tcpConnRemAddress =
16393 					    tcp->tcp_remote;
16394 					tce.tcpConnLocalAddress =
16395 					    tcp->tcp_ip_src;
16396 				}
16397 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16398 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16399 				/* Don't want just anybody seeing these... */
16400 				if (ispriv) {
16401 					tce.tcpConnEntryInfo.ce_snxt =
16402 					    tcp->tcp_snxt;
16403 					tce.tcpConnEntryInfo.ce_suna =
16404 					    tcp->tcp_suna;
16405 					tce.tcpConnEntryInfo.ce_rnxt =
16406 					    tcp->tcp_rnxt;
16407 					tce.tcpConnEntryInfo.ce_rack =
16408 					    tcp->tcp_rack;
16409 				} else {
16410 					/*
16411 					 * Netstat, unfortunately, uses this to
16412 					 * get send/receive queue sizes.  How
16413 					 * to fix?
16414 					 * Why not compute the difference only?
16415 					 */
16416 					tce.tcpConnEntryInfo.ce_snxt =
16417 					    tcp->tcp_snxt - tcp->tcp_suna;
16418 					tce.tcpConnEntryInfo.ce_suna = 0;
16419 					tce.tcpConnEntryInfo.ce_rnxt =
16420 					    tcp->tcp_rnxt - tcp->tcp_rack;
16421 					tce.tcpConnEntryInfo.ce_rack = 0;
16422 				}
16423 
16424 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16425 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16426 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16427 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16428 				tce.tcpConnEntryInfo.ce_state =
16429 				    tcp->tcp_state;
16430 
16431 				tce.tcpConnCreationProcess =
16432 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16433 				    tcp->tcp_cpid;
16434 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16435 
16436 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16437 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16438 
16439 				mlp.tme_connidx = v4_conn_idx++;
16440 				if (needattr)
16441 					(void) snmp_append_data2(
16442 					    mp_attr_ctl->b_cont,
16443 					    &mp_attr_tail, (char *)&mlp,
16444 					    sizeof (mlp));
16445 			}
16446 		}
16447 	}
16448 
16449 	/* fixed length structure for IPv4 and IPv6 counters */
16450 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16451 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16452 	    sizeof (mib2_tcp6ConnEntry_t));
16453 	/* synchronize 32- and 64-bit counters */
16454 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16455 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16456 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16457 	optp->level = MIB2_TCP;
16458 	optp->name = 0;
16459 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16460 	    sizeof (tcps->tcps_mib));
16461 	optp->len = msgdsize(mpdata);
16462 	qreply(q, mpctl);
16463 
16464 	/* table of connections... */
16465 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16466 	    sizeof (struct T_optmgmt_ack)];
16467 	optp->level = MIB2_TCP;
16468 	optp->name = MIB2_TCP_CONN;
16469 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16470 	qreply(q, mp_conn_ctl);
16471 
16472 	/* table of MLP attributes... */
16473 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16474 	    sizeof (struct T_optmgmt_ack)];
16475 	optp->level = MIB2_TCP;
16476 	optp->name = EXPER_XPORT_MLP;
16477 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16478 	if (optp->len == 0)
16479 		freemsg(mp_attr_ctl);
16480 	else
16481 		qreply(q, mp_attr_ctl);
16482 
16483 	/* table of IPv6 connections... */
16484 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16485 	    sizeof (struct T_optmgmt_ack)];
16486 	optp->level = MIB2_TCP6;
16487 	optp->name = MIB2_TCP6_CONN;
16488 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16489 	qreply(q, mp6_conn_ctl);
16490 
16491 	/* table of IPv6 MLP attributes... */
16492 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16493 	    sizeof (struct T_optmgmt_ack)];
16494 	optp->level = MIB2_TCP6;
16495 	optp->name = EXPER_XPORT_MLP;
16496 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16497 	if (optp->len == 0)
16498 		freemsg(mp6_attr_ctl);
16499 	else
16500 		qreply(q, mp6_attr_ctl);
16501 	return (mp2ctl);
16502 }
16503 
16504 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16505 /* ARGSUSED */
16506 int
16507 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16508 {
16509 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16510 
16511 	switch (level) {
16512 	case MIB2_TCP:
16513 		switch (name) {
16514 		case 13:
16515 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16516 				return (0);
16517 			/* TODO: delete entry defined by tce */
16518 			return (1);
16519 		default:
16520 			return (0);
16521 		}
16522 	default:
16523 		return (1);
16524 	}
16525 }
16526 
16527 /* Translate TCP state to MIB2 TCP state. */
16528 static int
16529 tcp_snmp_state(tcp_t *tcp)
16530 {
16531 	if (tcp == NULL)
16532 		return (0);
16533 
16534 	switch (tcp->tcp_state) {
16535 	case TCPS_CLOSED:
16536 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16537 	case TCPS_BOUND:
16538 		return (MIB2_TCP_closed);
16539 	case TCPS_LISTEN:
16540 		return (MIB2_TCP_listen);
16541 	case TCPS_SYN_SENT:
16542 		return (MIB2_TCP_synSent);
16543 	case TCPS_SYN_RCVD:
16544 		return (MIB2_TCP_synReceived);
16545 	case TCPS_ESTABLISHED:
16546 		return (MIB2_TCP_established);
16547 	case TCPS_CLOSE_WAIT:
16548 		return (MIB2_TCP_closeWait);
16549 	case TCPS_FIN_WAIT_1:
16550 		return (MIB2_TCP_finWait1);
16551 	case TCPS_CLOSING:
16552 		return (MIB2_TCP_closing);
16553 	case TCPS_LAST_ACK:
16554 		return (MIB2_TCP_lastAck);
16555 	case TCPS_FIN_WAIT_2:
16556 		return (MIB2_TCP_finWait2);
16557 	case TCPS_TIME_WAIT:
16558 		return (MIB2_TCP_timeWait);
16559 	default:
16560 		return (0);
16561 	}
16562 }
16563 
16564 static char tcp_report_header[] =
16565 	"TCP     " MI_COL_HDRPAD_STR
16566 	"zone dest	    snxt     suna     "
16567 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16568 	"recent   [lport,fport] state";
16569 
16570 /*
16571  * TCP status report triggered via the Named Dispatch mechanism.
16572  */
16573 /* ARGSUSED */
16574 static void
16575 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16576     cred_t *cr)
16577 {
16578 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16579 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16580 	char cflag;
16581 	in6_addr_t	v6dst;
16582 	char buf[80];
16583 	uint_t print_len, buf_len;
16584 
16585 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16586 	if (buf_len <= 0)
16587 		return;
16588 
16589 	if (hashval >= 0)
16590 		(void) sprintf(hash, "%03d ", hashval);
16591 	else
16592 		hash[0] = '\0';
16593 
16594 	/*
16595 	 * Note that we use the remote address in the tcp_b  structure.
16596 	 * This means that it will print out the real destination address,
16597 	 * not the next hop's address if source routing is used.  This
16598 	 * avoid the confusion on the output because user may not
16599 	 * know that source routing is used for a connection.
16600 	 */
16601 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16602 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16603 	} else {
16604 		v6dst = tcp->tcp_remote_v6;
16605 	}
16606 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16607 	/*
16608 	 * the ispriv checks are so that normal users cannot determine
16609 	 * sequence number information using NDD.
16610 	 */
16611 
16612 	if (TCP_IS_DETACHED(tcp))
16613 		cflag = '*';
16614 	else
16615 		cflag = ' ';
16616 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16617 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16618 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16619 	    hash,
16620 	    (void *)tcp,
16621 	    tcp->tcp_connp->conn_zoneid,
16622 	    addrbuf,
16623 	    (ispriv) ? tcp->tcp_snxt : 0,
16624 	    (ispriv) ? tcp->tcp_suna : 0,
16625 	    tcp->tcp_swnd,
16626 	    (ispriv) ? tcp->tcp_rnxt : 0,
16627 	    (ispriv) ? tcp->tcp_rack : 0,
16628 	    tcp->tcp_rwnd,
16629 	    tcp->tcp_rto,
16630 	    tcp->tcp_mss,
16631 	    tcp->tcp_snd_ws_ok,
16632 	    tcp->tcp_snd_ws,
16633 	    tcp->tcp_rcv_ws,
16634 	    tcp->tcp_snd_ts_ok,
16635 	    tcp->tcp_ts_recent,
16636 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16637 	if (print_len < buf_len) {
16638 		((mblk_t *)mp)->b_wptr += print_len;
16639 	} else {
16640 		((mblk_t *)mp)->b_wptr += buf_len;
16641 	}
16642 }
16643 
16644 /*
16645  * TCP status report (for listeners only) triggered via the Named Dispatch
16646  * mechanism.
16647  */
16648 /* ARGSUSED */
16649 static void
16650 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16651 {
16652 	char addrbuf[INET6_ADDRSTRLEN];
16653 	in6_addr_t	v6dst;
16654 	uint_t print_len, buf_len;
16655 
16656 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16657 	if (buf_len <= 0)
16658 		return;
16659 
16660 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16661 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16662 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16663 	} else {
16664 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16665 		    addrbuf, sizeof (addrbuf));
16666 	}
16667 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16668 	    "%03d "
16669 	    MI_COL_PTRFMT_STR
16670 	    "%d %s %05u %08u %d/%d/%d%c\n",
16671 	    hashval, (void *)tcp,
16672 	    tcp->tcp_connp->conn_zoneid,
16673 	    addrbuf,
16674 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
16675 	    tcp->tcp_conn_req_seqnum,
16676 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
16677 	    tcp->tcp_conn_req_max,
16678 	    tcp->tcp_syn_defense ? '*' : ' ');
16679 	if (print_len < buf_len) {
16680 		((mblk_t *)mp)->b_wptr += print_len;
16681 	} else {
16682 		((mblk_t *)mp)->b_wptr += buf_len;
16683 	}
16684 }
16685 
16686 /* TCP status report triggered via the Named Dispatch mechanism. */
16687 /* ARGSUSED */
16688 static int
16689 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16690 {
16691 	tcp_t	*tcp;
16692 	int	i;
16693 	conn_t	*connp;
16694 	connf_t	*connfp;
16695 	zoneid_t zoneid;
16696 	tcp_stack_t *tcps;
16697 	ip_stack_t *ipst;
16698 
16699 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16700 	tcps = Q_TO_TCP(q)->tcp_tcps;
16701 
16702 	/*
16703 	 * Because of the ndd constraint, at most we can have 64K buffer
16704 	 * to put in all TCP info.  So to be more efficient, just
16705 	 * allocate a 64K buffer here, assuming we need that large buffer.
16706 	 * This may be a problem as any user can read tcp_status.  Therefore
16707 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
16708 	 * This should be OK as normal users should not do this too often.
16709 	 */
16710 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16711 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16712 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16713 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16714 			return (0);
16715 		}
16716 	}
16717 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16718 		/* The following may work even if we cannot get a large buf. */
16719 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16720 		return (0);
16721 	}
16722 
16723 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
16724 
16725 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16726 
16727 		ipst = tcps->tcps_netstack->netstack_ip;
16728 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16729 
16730 		connp = NULL;
16731 
16732 		while ((connp =
16733 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16734 			tcp = connp->conn_tcp;
16735 			if (zoneid != GLOBAL_ZONEID &&
16736 			    zoneid != connp->conn_zoneid)
16737 				continue;
16738 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
16739 			    cr);
16740 		}
16741 
16742 	}
16743 
16744 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16745 	return (0);
16746 }
16747 
16748 /* TCP status report triggered via the Named Dispatch mechanism. */
16749 /* ARGSUSED */
16750 static int
16751 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16752 {
16753 	tf_t	*tbf;
16754 	tcp_t	*tcp, *ltcp;
16755 	int	i;
16756 	zoneid_t zoneid;
16757 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
16758 
16759 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16760 
16761 	/* Refer to comments in tcp_status_report(). */
16762 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16763 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16764 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16765 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16766 			return (0);
16767 		}
16768 	}
16769 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16770 		/* The following may work even if we cannot get a large buf. */
16771 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16772 		return (0);
16773 	}
16774 
16775 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16776 
16777 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
16778 		tbf = &tcps->tcps_bind_fanout[i];
16779 		mutex_enter(&tbf->tf_lock);
16780 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
16781 		    ltcp = ltcp->tcp_bind_hash) {
16782 			for (tcp = ltcp; tcp != NULL;
16783 			    tcp = tcp->tcp_bind_hash_port) {
16784 				if (zoneid != GLOBAL_ZONEID &&
16785 				    zoneid != tcp->tcp_connp->conn_zoneid)
16786 					continue;
16787 				CONN_INC_REF(tcp->tcp_connp);
16788 				tcp_report_item(mp->b_cont, tcp, i,
16789 				    Q_TO_TCP(q), cr);
16790 				CONN_DEC_REF(tcp->tcp_connp);
16791 			}
16792 		}
16793 		mutex_exit(&tbf->tf_lock);
16794 	}
16795 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16796 	return (0);
16797 }
16798 
16799 /* TCP status report triggered via the Named Dispatch mechanism. */
16800 /* ARGSUSED */
16801 static int
16802 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16803 {
16804 	connf_t	*connfp;
16805 	conn_t	*connp;
16806 	tcp_t	*tcp;
16807 	int	i;
16808 	zoneid_t zoneid;
16809 	tcp_stack_t *tcps;
16810 	ip_stack_t	*ipst;
16811 
16812 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16813 	tcps = Q_TO_TCP(q)->tcp_tcps;
16814 
16815 	/* Refer to comments in tcp_status_report(). */
16816 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16817 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16818 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16819 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16820 			return (0);
16821 		}
16822 	}
16823 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16824 		/* The following may work even if we cannot get a large buf. */
16825 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16826 		return (0);
16827 	}
16828 
16829 	(void) mi_mpprintf(mp,
16830 	    "    TCP    " MI_COL_HDRPAD_STR
16831 	    "zone IP addr	 port  seqnum   backlog (q0/q/max)");
16832 
16833 	ipst = tcps->tcps_netstack->netstack_ip;
16834 
16835 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
16836 		connfp = &ipst->ips_ipcl_bind_fanout[i];
16837 		connp = NULL;
16838 		while ((connp =
16839 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16840 			tcp = connp->conn_tcp;
16841 			if (zoneid != GLOBAL_ZONEID &&
16842 			    zoneid != connp->conn_zoneid)
16843 				continue;
16844 			tcp_report_listener(mp->b_cont, tcp, i);
16845 		}
16846 	}
16847 
16848 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16849 	return (0);
16850 }
16851 
16852 /* TCP status report triggered via the Named Dispatch mechanism. */
16853 /* ARGSUSED */
16854 static int
16855 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16856 {
16857 	connf_t	*connfp;
16858 	conn_t	*connp;
16859 	tcp_t	*tcp;
16860 	int	i;
16861 	zoneid_t zoneid;
16862 	tcp_stack_t *tcps;
16863 	ip_stack_t *ipst;
16864 
16865 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16866 	tcps = Q_TO_TCP(q)->tcp_tcps;
16867 	ipst = tcps->tcps_netstack->netstack_ip;
16868 
16869 	/* Refer to comments in tcp_status_report(). */
16870 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16871 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16872 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16873 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16874 			return (0);
16875 		}
16876 	}
16877 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16878 		/* The following may work even if we cannot get a large buf. */
16879 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16880 		return (0);
16881 	}
16882 
16883 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
16884 	    ipst->ips_ipcl_conn_fanout_size);
16885 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16886 
16887 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
16888 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
16889 		connp = NULL;
16890 		while ((connp =
16891 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16892 			tcp = connp->conn_tcp;
16893 			if (zoneid != GLOBAL_ZONEID &&
16894 			    zoneid != connp->conn_zoneid)
16895 				continue;
16896 			tcp_report_item(mp->b_cont, tcp, i,
16897 			    Q_TO_TCP(q), cr);
16898 		}
16899 	}
16900 
16901 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16902 	return (0);
16903 }
16904 
16905 /* TCP status report triggered via the Named Dispatch mechanism. */
16906 /* ARGSUSED */
16907 static int
16908 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
16909 {
16910 	tf_t	*tf;
16911 	tcp_t	*tcp;
16912 	int	i;
16913 	zoneid_t zoneid;
16914 	tcp_stack_t	*tcps;
16915 
16916 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16917 	tcps = Q_TO_TCP(q)->tcp_tcps;
16918 
16919 	/* Refer to comments in tcp_status_report(). */
16920 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
16921 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
16922 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
16923 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
16924 			return (0);
16925 		}
16926 	}
16927 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
16928 		/* The following may work even if we cannot get a large buf. */
16929 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
16930 		return (0);
16931 	}
16932 
16933 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
16934 
16935 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
16936 		tf = &tcps->tcps_acceptor_fanout[i];
16937 		mutex_enter(&tf->tf_lock);
16938 		for (tcp = tf->tf_tcp; tcp != NULL;
16939 		    tcp = tcp->tcp_acceptor_hash) {
16940 			if (zoneid != GLOBAL_ZONEID &&
16941 			    zoneid != tcp->tcp_connp->conn_zoneid)
16942 				continue;
16943 			tcp_report_item(mp->b_cont, tcp, i,
16944 			    Q_TO_TCP(q), cr);
16945 		}
16946 		mutex_exit(&tf->tf_lock);
16947 	}
16948 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
16949 	return (0);
16950 }
16951 
16952 /*
16953  * tcp_timer is the timer service routine.  It handles the retransmission,
16954  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
16955  * from the state of the tcp instance what kind of action needs to be done
16956  * at the time it is called.
16957  */
16958 static void
16959 tcp_timer(void *arg)
16960 {
16961 	mblk_t		*mp;
16962 	clock_t		first_threshold;
16963 	clock_t		second_threshold;
16964 	clock_t		ms;
16965 	uint32_t	mss;
16966 	conn_t		*connp = (conn_t *)arg;
16967 	tcp_t		*tcp = connp->conn_tcp;
16968 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16969 
16970 	tcp->tcp_timer_tid = 0;
16971 
16972 	if (tcp->tcp_fused)
16973 		return;
16974 
16975 	first_threshold =  tcp->tcp_first_timer_threshold;
16976 	second_threshold = tcp->tcp_second_timer_threshold;
16977 	switch (tcp->tcp_state) {
16978 	case TCPS_IDLE:
16979 	case TCPS_BOUND:
16980 	case TCPS_LISTEN:
16981 		return;
16982 	case TCPS_SYN_RCVD: {
16983 		tcp_t	*listener = tcp->tcp_listener;
16984 
16985 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
16986 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
16987 			/* it's our first timeout */
16988 			tcp->tcp_syn_rcvd_timeout = 1;
16989 			mutex_enter(&listener->tcp_eager_lock);
16990 			listener->tcp_syn_rcvd_timeout++;
16991 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
16992 				/*
16993 				 * Make this eager available for drop if we
16994 				 * need to drop one to accomodate a new
16995 				 * incoming SYN request.
16996 				 */
16997 				MAKE_DROPPABLE(listener, tcp);
16998 			}
16999 			if (!listener->tcp_syn_defense &&
17000 			    (listener->tcp_syn_rcvd_timeout >
17001 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
17002 			    (tcps->tcps_conn_req_max_q0 > 200)) {
17003 				/* We may be under attack. Put on a defense. */
17004 				listener->tcp_syn_defense = B_TRUE;
17005 				cmn_err(CE_WARN, "High TCP connect timeout "
17006 				    "rate! System (port %d) may be under a "
17007 				    "SYN flood attack!",
17008 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
17009 
17010 				listener->tcp_ip_addr_cache = kmem_zalloc(
17011 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
17012 				    KM_NOSLEEP);
17013 			}
17014 			mutex_exit(&listener->tcp_eager_lock);
17015 		} else if (listener != NULL) {
17016 			mutex_enter(&listener->tcp_eager_lock);
17017 			tcp->tcp_syn_rcvd_timeout++;
17018 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17019 			    !tcp->tcp_closemp_used) {
17020 				/*
17021 				 * This is our second timeout. Put the tcp in
17022 				 * the list of droppable eagers to allow it to
17023 				 * be dropped, if needed. We don't check
17024 				 * whether tcp_dontdrop is set or not to
17025 				 * protect ourselve from a SYN attack where a
17026 				 * remote host can spoof itself as one of the
17027 				 * good IP source and continue to hold
17028 				 * resources too long.
17029 				 */
17030 				MAKE_DROPPABLE(listener, tcp);
17031 			}
17032 			mutex_exit(&listener->tcp_eager_lock);
17033 		}
17034 	}
17035 		/* FALLTHRU */
17036 	case TCPS_SYN_SENT:
17037 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17038 		second_threshold = tcp->tcp_second_ctimer_threshold;
17039 		break;
17040 	case TCPS_ESTABLISHED:
17041 	case TCPS_FIN_WAIT_1:
17042 	case TCPS_CLOSING:
17043 	case TCPS_CLOSE_WAIT:
17044 	case TCPS_LAST_ACK:
17045 		/* If we have data to rexmit */
17046 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17047 			clock_t	time_to_wait;
17048 
17049 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17050 			if (!tcp->tcp_xmit_head)
17051 				break;
17052 			time_to_wait = lbolt -
17053 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17054 			time_to_wait = tcp->tcp_rto -
17055 			    TICK_TO_MSEC(time_to_wait);
17056 			/*
17057 			 * If the timer fires too early, 1 clock tick earlier,
17058 			 * restart the timer.
17059 			 */
17060 			if (time_to_wait > msec_per_tick) {
17061 				TCP_STAT(tcps, tcp_timer_fire_early);
17062 				TCP_TIMER_RESTART(tcp, time_to_wait);
17063 				return;
17064 			}
17065 			/*
17066 			 * When we probe zero windows, we force the swnd open.
17067 			 * If our peer acks with a closed window swnd will be
17068 			 * set to zero by tcp_rput(). As long as we are
17069 			 * receiving acks tcp_rput will
17070 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17071 			 * first and second interval actions.  NOTE: the timer
17072 			 * interval is allowed to continue its exponential
17073 			 * backoff.
17074 			 */
17075 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17076 				if (tcp->tcp_debug) {
17077 					(void) strlog(TCP_MOD_ID, 0, 1,
17078 					    SL_TRACE, "tcp_timer: zero win");
17079 				}
17080 			} else {
17081 				/*
17082 				 * After retransmission, we need to do
17083 				 * slow start.  Set the ssthresh to one
17084 				 * half of current effective window and
17085 				 * cwnd to one MSS.  Also reset
17086 				 * tcp_cwnd_cnt.
17087 				 *
17088 				 * Note that if tcp_ssthresh is reduced because
17089 				 * of ECN, do not reduce it again unless it is
17090 				 * already one window of data away (tcp_cwr
17091 				 * should then be cleared) or this is a
17092 				 * timeout for a retransmitted segment.
17093 				 */
17094 				uint32_t npkt;
17095 
17096 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17097 					npkt = ((tcp->tcp_timer_backoff ?
17098 					    tcp->tcp_cwnd_ssthresh :
17099 					    tcp->tcp_snxt -
17100 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17101 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17102 					    tcp->tcp_mss;
17103 				}
17104 				tcp->tcp_cwnd = tcp->tcp_mss;
17105 				tcp->tcp_cwnd_cnt = 0;
17106 				if (tcp->tcp_ecn_ok) {
17107 					tcp->tcp_cwr = B_TRUE;
17108 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17109 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17110 				}
17111 			}
17112 			break;
17113 		}
17114 		/*
17115 		 * We have something to send yet we cannot send.  The
17116 		 * reason can be:
17117 		 *
17118 		 * 1. Zero send window: we need to do zero window probe.
17119 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17120 		 * segments.
17121 		 * 3. SWS avoidance: receiver may have shrunk window,
17122 		 * reset our knowledge.
17123 		 *
17124 		 * Note that condition 2 can happen with either 1 or
17125 		 * 3.  But 1 and 3 are exclusive.
17126 		 */
17127 		if (tcp->tcp_unsent != 0) {
17128 			if (tcp->tcp_cwnd == 0) {
17129 				/*
17130 				 * Set tcp_cwnd to 1 MSS so that a
17131 				 * new segment can be sent out.  We
17132 				 * are "clocking out" new data when
17133 				 * the network is really congested.
17134 				 */
17135 				ASSERT(tcp->tcp_ecn_ok);
17136 				tcp->tcp_cwnd = tcp->tcp_mss;
17137 			}
17138 			if (tcp->tcp_swnd == 0) {
17139 				/* Extend window for zero window probe */
17140 				tcp->tcp_swnd++;
17141 				tcp->tcp_zero_win_probe = B_TRUE;
17142 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17143 			} else {
17144 				/*
17145 				 * Handle timeout from sender SWS avoidance.
17146 				 * Reset our knowledge of the max send window
17147 				 * since the receiver might have reduced its
17148 				 * receive buffer.  Avoid setting tcp_max_swnd
17149 				 * to one since that will essentially disable
17150 				 * the SWS checks.
17151 				 *
17152 				 * Note that since we don't have a SWS
17153 				 * state variable, if the timeout is set
17154 				 * for ECN but not for SWS, this
17155 				 * code will also be executed.  This is
17156 				 * fine as tcp_max_swnd is updated
17157 				 * constantly and it will not affect
17158 				 * anything.
17159 				 */
17160 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17161 			}
17162 			tcp_wput_data(tcp, NULL, B_FALSE);
17163 			return;
17164 		}
17165 		/* Is there a FIN that needs to be to re retransmitted? */
17166 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17167 		    !tcp->tcp_fin_acked)
17168 			break;
17169 		/* Nothing to do, return without restarting timer. */
17170 		TCP_STAT(tcps, tcp_timer_fire_miss);
17171 		return;
17172 	case TCPS_FIN_WAIT_2:
17173 		/*
17174 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17175 		 * We waited some time for for peer's FIN, but it hasn't
17176 		 * arrived.  We flush the connection now to avoid
17177 		 * case where the peer has rebooted.
17178 		 */
17179 		if (TCP_IS_DETACHED(tcp)) {
17180 			(void) tcp_clean_death(tcp, 0, 23);
17181 		} else {
17182 			TCP_TIMER_RESTART(tcp,
17183 			    tcps->tcps_fin_wait_2_flush_interval);
17184 		}
17185 		return;
17186 	case TCPS_TIME_WAIT:
17187 		(void) tcp_clean_death(tcp, 0, 24);
17188 		return;
17189 	default:
17190 		if (tcp->tcp_debug) {
17191 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17192 			    "tcp_timer: strange state (%d) %s",
17193 			    tcp->tcp_state, tcp_display(tcp, NULL,
17194 			    DISP_PORT_ONLY));
17195 		}
17196 		return;
17197 	}
17198 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17199 		/*
17200 		 * For zero window probe, we need to send indefinitely,
17201 		 * unless we have not heard from the other side for some
17202 		 * time...
17203 		 */
17204 		if ((tcp->tcp_zero_win_probe == 0) ||
17205 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17206 		    second_threshold)) {
17207 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17208 			/*
17209 			 * If TCP is in SYN_RCVD state, send back a
17210 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17211 			 * should be zero in TCPS_SYN_RCVD state.
17212 			 */
17213 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17214 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17215 				    "in SYN_RCVD",
17216 				    tcp, tcp->tcp_snxt,
17217 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17218 			}
17219 			(void) tcp_clean_death(tcp,
17220 			    tcp->tcp_client_errno ?
17221 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17222 			return;
17223 		} else {
17224 			/*
17225 			 * Set tcp_ms_we_have_waited to second_threshold
17226 			 * so that in next timeout, we will do the above
17227 			 * check (lbolt - tcp_last_recv_time).  This is
17228 			 * also to avoid overflow.
17229 			 *
17230 			 * We don't need to decrement tcp_timer_backoff
17231 			 * to avoid overflow because it will be decremented
17232 			 * later if new timeout value is greater than
17233 			 * tcp_rexmit_interval_max.  In the case when
17234 			 * tcp_rexmit_interval_max is greater than
17235 			 * second_threshold, it means that we will wait
17236 			 * longer than second_threshold to send the next
17237 			 * window probe.
17238 			 */
17239 			tcp->tcp_ms_we_have_waited = second_threshold;
17240 		}
17241 	} else if (ms > first_threshold) {
17242 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17243 		    tcp->tcp_xmit_head != NULL) {
17244 			tcp->tcp_xmit_head =
17245 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17246 		}
17247 		/*
17248 		 * We have been retransmitting for too long...  The RTT
17249 		 * we calculated is probably incorrect.  Reinitialize it.
17250 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17251 		 * tcp_rtt_update so that we won't accidentally cache a
17252 		 * bad value.  But only do this if this is not a zero
17253 		 * window probe.
17254 		 */
17255 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17256 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17257 			    (tcp->tcp_rtt_sa >> 5);
17258 			tcp->tcp_rtt_sa = 0;
17259 			tcp_ip_notify(tcp);
17260 			tcp->tcp_rtt_update = 0;
17261 		}
17262 	}
17263 	tcp->tcp_timer_backoff++;
17264 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17265 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17266 	    tcps->tcps_rexmit_interval_min) {
17267 		/*
17268 		 * This means the original RTO is tcp_rexmit_interval_min.
17269 		 * So we will use tcp_rexmit_interval_min as the RTO value
17270 		 * and do the backoff.
17271 		 */
17272 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17273 	} else {
17274 		ms <<= tcp->tcp_timer_backoff;
17275 	}
17276 	if (ms > tcps->tcps_rexmit_interval_max) {
17277 		ms = tcps->tcps_rexmit_interval_max;
17278 		/*
17279 		 * ms is at max, decrement tcp_timer_backoff to avoid
17280 		 * overflow.
17281 		 */
17282 		tcp->tcp_timer_backoff--;
17283 	}
17284 	tcp->tcp_ms_we_have_waited += ms;
17285 	if (tcp->tcp_zero_win_probe == 0) {
17286 		tcp->tcp_rto = ms;
17287 	}
17288 	TCP_TIMER_RESTART(tcp, ms);
17289 	/*
17290 	 * This is after a timeout and tcp_rto is backed off.  Set
17291 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17292 	 * restart the timer with a correct value.
17293 	 */
17294 	tcp->tcp_set_timer = 1;
17295 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17296 	if (mss > tcp->tcp_mss)
17297 		mss = tcp->tcp_mss;
17298 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17299 		mss = tcp->tcp_swnd;
17300 
17301 	if ((mp = tcp->tcp_xmit_head) != NULL)
17302 		mp->b_prev = (mblk_t *)lbolt;
17303 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17304 	    B_TRUE);
17305 
17306 	/*
17307 	 * When slow start after retransmission begins, start with
17308 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17309 	 * start phase.  tcp_snd_burst controls how many segments
17310 	 * can be sent because of an ack.
17311 	 */
17312 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17313 	tcp->tcp_snd_burst = TCP_CWND_SS;
17314 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17315 	    (tcp->tcp_unsent == 0)) {
17316 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17317 	} else {
17318 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17319 	}
17320 	tcp->tcp_rexmit = B_TRUE;
17321 	tcp->tcp_dupack_cnt = 0;
17322 
17323 	/*
17324 	 * Remove all rexmit SACK blk to start from fresh.
17325 	 */
17326 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17327 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17328 		tcp->tcp_num_notsack_blk = 0;
17329 		tcp->tcp_cnt_notsack_list = 0;
17330 	}
17331 	if (mp == NULL) {
17332 		return;
17333 	}
17334 	/* Attach credentials to retransmitted initial SYNs. */
17335 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17336 		mblk_setcred(mp, tcp->tcp_cred);
17337 		DB_CPID(mp) = tcp->tcp_cpid;
17338 	}
17339 
17340 	tcp->tcp_csuna = tcp->tcp_snxt;
17341 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17342 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17343 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17344 
17345 }
17346 
17347 static int
17348 tcp_do_unbind(conn_t *connp)
17349 {
17350 	tcp_t *tcp = connp->conn_tcp;
17351 	int error = 0;
17352 
17353 	switch (tcp->tcp_state) {
17354 	case TCPS_BOUND:
17355 	case TCPS_LISTEN:
17356 		break;
17357 	default:
17358 		return (-TOUTSTATE);
17359 	}
17360 
17361 	/*
17362 	 * Need to clean up all the eagers since after the unbind, segments
17363 	 * will no longer be delivered to this listener stream.
17364 	 */
17365 	mutex_enter(&tcp->tcp_eager_lock);
17366 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17367 		tcp_eager_cleanup(tcp, 0);
17368 	}
17369 	mutex_exit(&tcp->tcp_eager_lock);
17370 
17371 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17372 		tcp->tcp_ipha->ipha_src = 0;
17373 	} else {
17374 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17375 	}
17376 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17377 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17378 	tcp_bind_hash_remove(tcp);
17379 	tcp->tcp_state = TCPS_IDLE;
17380 	tcp->tcp_mdt = B_FALSE;
17381 
17382 	connp = tcp->tcp_connp;
17383 	connp->conn_mdt_ok = B_FALSE;
17384 	ipcl_hash_remove(connp);
17385 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17386 
17387 	return (error);
17388 }
17389 
17390 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17391 static void
17392 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
17393 {
17394 	int error = tcp_do_unbind(tcp->tcp_connp);
17395 
17396 	if (error > 0) {
17397 		tcp_err_ack(tcp, mp, TSYSERR, error);
17398 	} else if (error < 0) {
17399 		tcp_err_ack(tcp, mp, -error, 0);
17400 	} else {
17401 		/* Send M_FLUSH according to TPI */
17402 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17403 
17404 		mp = mi_tpi_ok_ack_alloc(mp);
17405 		putnext(tcp->tcp_rq, mp);
17406 	}
17407 }
17408 
17409 /*
17410  * Don't let port fall into the privileged range.
17411  * Since the extra privileged ports can be arbitrary we also
17412  * ensure that we exclude those from consideration.
17413  * tcp_g_epriv_ports is not sorted thus we loop over it until
17414  * there are no changes.
17415  *
17416  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17417  * but instead the code relies on:
17418  * - the fact that the address of the array and its size never changes
17419  * - the atomic assignment of the elements of the array
17420  *
17421  * Returns 0 if there are no more ports available.
17422  *
17423  * TS note: skip multilevel ports.
17424  */
17425 static in_port_t
17426 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17427 {
17428 	int i;
17429 	boolean_t restart = B_FALSE;
17430 	tcp_stack_t *tcps = tcp->tcp_tcps;
17431 
17432 	if (random && tcp_random_anon_port != 0) {
17433 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17434 		    sizeof (in_port_t));
17435 		/*
17436 		 * Unless changed by a sys admin, the smallest anon port
17437 		 * is 32768 and the largest anon port is 65535.  It is
17438 		 * very likely (50%) for the random port to be smaller
17439 		 * than the smallest anon port.  When that happens,
17440 		 * add port % (anon port range) to the smallest anon
17441 		 * port to get the random port.  It should fall into the
17442 		 * valid anon port range.
17443 		 */
17444 		if (port < tcps->tcps_smallest_anon_port) {
17445 			port = tcps->tcps_smallest_anon_port +
17446 			    port % (tcps->tcps_largest_anon_port -
17447 			    tcps->tcps_smallest_anon_port);
17448 		}
17449 	}
17450 
17451 retry:
17452 	if (port < tcps->tcps_smallest_anon_port)
17453 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17454 
17455 	if (port > tcps->tcps_largest_anon_port) {
17456 		if (restart)
17457 			return (0);
17458 		restart = B_TRUE;
17459 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17460 	}
17461 
17462 	if (port < tcps->tcps_smallest_nonpriv_port)
17463 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17464 
17465 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17466 		if (port == tcps->tcps_g_epriv_ports[i]) {
17467 			port++;
17468 			/*
17469 			 * Make sure whether the port is in the
17470 			 * valid range.
17471 			 */
17472 			goto retry;
17473 		}
17474 	}
17475 	if (is_system_labeled() &&
17476 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17477 	    IPPROTO_TCP, B_TRUE)) != 0) {
17478 		port = i;
17479 		goto retry;
17480 	}
17481 	return (port);
17482 }
17483 
17484 /*
17485  * Return the next anonymous port in the privileged port range for
17486  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17487  * downwards.  This is the same behavior as documented in the userland
17488  * library call rresvport(3N).
17489  *
17490  * TS note: skip multilevel ports.
17491  */
17492 static in_port_t
17493 tcp_get_next_priv_port(const tcp_t *tcp)
17494 {
17495 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17496 	in_port_t nextport;
17497 	boolean_t restart = B_FALSE;
17498 	tcp_stack_t *tcps = tcp->tcp_tcps;
17499 retry:
17500 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17501 	    next_priv_port >= IPPORT_RESERVED) {
17502 		next_priv_port = IPPORT_RESERVED - 1;
17503 		if (restart)
17504 			return (0);
17505 		restart = B_TRUE;
17506 	}
17507 	if (is_system_labeled() &&
17508 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17509 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17510 		next_priv_port = nextport;
17511 		goto retry;
17512 	}
17513 	return (next_priv_port--);
17514 }
17515 
17516 /* The write side r/w procedure. */
17517 
17518 #if CCS_STATS
17519 struct {
17520 	struct {
17521 		int64_t count, bytes;
17522 	} tot, hit;
17523 } wrw_stats;
17524 #endif
17525 
17526 /*
17527  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17528  * messages.
17529  */
17530 /* ARGSUSED */
17531 static void
17532 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17533 {
17534 	conn_t	*connp = (conn_t *)arg;
17535 	tcp_t	*tcp = connp->conn_tcp;
17536 	queue_t	*q = tcp->tcp_wq;
17537 
17538 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17539 	/*
17540 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17541 	 * Once the close starts, streamhead and sockfs will not let any data
17542 	 * packets come down (close ensures that there are no threads using the
17543 	 * queue and no new threads will come down) but since qprocsoff()
17544 	 * hasn't happened yet, a M_FLUSH or some non data message might
17545 	 * get reflected back (in response to our own FLUSHRW) and get
17546 	 * processed after tcp_close() is done. The conn would still be valid
17547 	 * because a ref would have added but we need to check the state
17548 	 * before actually processing the packet.
17549 	 */
17550 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17551 		freemsg(mp);
17552 		return;
17553 	}
17554 
17555 	switch (DB_TYPE(mp)) {
17556 	case M_IOCDATA:
17557 		tcp_wput_iocdata(tcp, mp);
17558 		break;
17559 	case M_FLUSH:
17560 		tcp_wput_flush(tcp, mp);
17561 		break;
17562 	default:
17563 		CALL_IP_WPUT(connp, q, mp);
17564 		break;
17565 	}
17566 }
17567 
17568 /*
17569  * The TCP fast path write put procedure.
17570  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17571  */
17572 /* ARGSUSED */
17573 void
17574 tcp_output(void *arg, mblk_t *mp, void *arg2)
17575 {
17576 	int		len;
17577 	int		hdrlen;
17578 	int		plen;
17579 	mblk_t		*mp1;
17580 	uchar_t		*rptr;
17581 	uint32_t	snxt;
17582 	tcph_t		*tcph;
17583 	struct datab	*db;
17584 	uint32_t	suna;
17585 	uint32_t	mss;
17586 	ipaddr_t	*dst;
17587 	ipaddr_t	*src;
17588 	uint32_t	sum;
17589 	int		usable;
17590 	conn_t		*connp = (conn_t *)arg;
17591 	tcp_t		*tcp = connp->conn_tcp;
17592 	uint32_t	msize;
17593 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17594 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17595 
17596 	/*
17597 	 * Try and ASSERT the minimum possible references on the
17598 	 * conn early enough. Since we are executing on write side,
17599 	 * the connection is obviously not detached and that means
17600 	 * there is a ref each for TCP and IP. Since we are behind
17601 	 * the squeue, the minimum references needed are 3. If the
17602 	 * conn is in classifier hash list, there should be an
17603 	 * extra ref for that (we check both the possibilities).
17604 	 */
17605 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17606 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17607 
17608 	ASSERT(DB_TYPE(mp) == M_DATA);
17609 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17610 
17611 	mutex_enter(&tcp->tcp_non_sq_lock);
17612 	tcp->tcp_squeue_bytes -= msize;
17613 	mutex_exit(&tcp->tcp_non_sq_lock);
17614 
17615 	/* Check to see if this connection wants to be re-fused. */
17616 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17617 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17618 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17619 			    &tcp->tcp_saved_tcph);
17620 		} else {
17621 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17622 			    &tcp->tcp_saved_tcph);
17623 		}
17624 	}
17625 	/* Bypass tcp protocol for fused tcp loopback */
17626 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17627 		return;
17628 
17629 	mss = tcp->tcp_mss;
17630 	if (tcp->tcp_xmit_zc_clean)
17631 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17632 
17633 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17634 	len = (int)(mp->b_wptr - mp->b_rptr);
17635 
17636 	/*
17637 	 * Criteria for fast path:
17638 	 *
17639 	 *   1. no unsent data
17640 	 *   2. single mblk in request
17641 	 *   3. connection established
17642 	 *   4. data in mblk
17643 	 *   5. len <= mss
17644 	 *   6. no tcp_valid bits
17645 	 */
17646 	if ((tcp->tcp_unsent != 0) ||
17647 	    (tcp->tcp_cork) ||
17648 	    (mp->b_cont != NULL) ||
17649 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17650 	    (len == 0) ||
17651 	    (len > mss) ||
17652 	    (tcp->tcp_valid_bits != 0)) {
17653 		tcp_wput_data(tcp, mp, B_FALSE);
17654 		return;
17655 	}
17656 
17657 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17658 	ASSERT(tcp->tcp_fin_sent == 0);
17659 
17660 	/* queue new packet onto retransmission queue */
17661 	if (tcp->tcp_xmit_head == NULL) {
17662 		tcp->tcp_xmit_head = mp;
17663 	} else {
17664 		tcp->tcp_xmit_last->b_cont = mp;
17665 	}
17666 	tcp->tcp_xmit_last = mp;
17667 	tcp->tcp_xmit_tail = mp;
17668 
17669 	/* find out how much we can send */
17670 	/* BEGIN CSTYLED */
17671 	/*
17672 	 *    un-acked	   usable
17673 	 *  |--------------|-----------------|
17674 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
17675 	 */
17676 	/* END CSTYLED */
17677 
17678 	/* start sending from tcp_snxt */
17679 	snxt = tcp->tcp_snxt;
17680 
17681 	/*
17682 	 * Check to see if this connection has been idled for some
17683 	 * time and no ACK is expected.  If it is, we need to slow
17684 	 * start again to get back the connection's "self-clock" as
17685 	 * described in VJ's paper.
17686 	 *
17687 	 * Refer to the comment in tcp_mss_set() for the calculation
17688 	 * of tcp_cwnd after idle.
17689 	 */
17690 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17691 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17692 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17693 	}
17694 
17695 	usable = tcp->tcp_swnd;		/* tcp window size */
17696 	if (usable > tcp->tcp_cwnd)
17697 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17698 	usable -= snxt;		/* subtract stuff already sent */
17699 	suna = tcp->tcp_suna;
17700 	usable += suna;
17701 	/* usable can be < 0 if the congestion window is smaller */
17702 	if (len > usable) {
17703 		/* Can't send complete M_DATA in one shot */
17704 		goto slow;
17705 	}
17706 
17707 	mutex_enter(&tcp->tcp_non_sq_lock);
17708 	if (tcp->tcp_flow_stopped &&
17709 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17710 		tcp_clrqfull(tcp);
17711 	}
17712 	mutex_exit(&tcp->tcp_non_sq_lock);
17713 
17714 	/*
17715 	 * determine if anything to send (Nagle).
17716 	 *
17717 	 *   1. len < tcp_mss (i.e. small)
17718 	 *   2. unacknowledged data present
17719 	 *   3. len < nagle limit
17720 	 *   4. last packet sent < nagle limit (previous packet sent)
17721 	 */
17722 	if ((len < mss) && (snxt != suna) &&
17723 	    (len < (int)tcp->tcp_naglim) &&
17724 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17725 		/*
17726 		 * This was the first unsent packet and normally
17727 		 * mss < xmit_hiwater so there is no need to worry
17728 		 * about flow control. The next packet will go
17729 		 * through the flow control check in tcp_wput_data().
17730 		 */
17731 		/* leftover work from above */
17732 		tcp->tcp_unsent = len;
17733 		tcp->tcp_xmit_tail_unsent = len;
17734 
17735 		return;
17736 	}
17737 
17738 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17739 
17740 	if (snxt == suna) {
17741 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17742 	}
17743 
17744 	/* we have always sent something */
17745 	tcp->tcp_rack_cnt = 0;
17746 
17747 	tcp->tcp_snxt = snxt + len;
17748 	tcp->tcp_rack = tcp->tcp_rnxt;
17749 
17750 	if ((mp1 = dupb(mp)) == 0)
17751 		goto no_memory;
17752 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17753 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17754 
17755 	/* adjust tcp header information */
17756 	tcph = tcp->tcp_tcph;
17757 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17758 
17759 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17760 	sum = (sum >> 16) + (sum & 0xFFFF);
17761 	U16_TO_ABE16(sum, tcph->th_sum);
17762 
17763 	U32_TO_ABE32(snxt, tcph->th_seq);
17764 
17765 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17766 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17767 	BUMP_LOCAL(tcp->tcp_obsegs);
17768 
17769 	/* Update the latest receive window size in TCP header. */
17770 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17771 	    tcph->th_win);
17772 
17773 	tcp->tcp_last_sent_len = (ushort_t)len;
17774 
17775 	plen = len + tcp->tcp_hdr_len;
17776 
17777 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17778 		tcp->tcp_ipha->ipha_length = htons(plen);
17779 	} else {
17780 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17781 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17782 	}
17783 
17784 	/* see if we need to allocate a mblk for the headers */
17785 	hdrlen = tcp->tcp_hdr_len;
17786 	rptr = mp1->b_rptr - hdrlen;
17787 	db = mp1->b_datap;
17788 	if ((db->db_ref != 2) || rptr < db->db_base ||
17789 	    (!OK_32PTR(rptr))) {
17790 		/* NOTE: we assume allocb returns an OK_32PTR */
17791 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17792 		    tcps->tcps_wroff_xtra, BPRI_MED);
17793 		if (!mp) {
17794 			freemsg(mp1);
17795 			goto no_memory;
17796 		}
17797 		mp->b_cont = mp1;
17798 		mp1 = mp;
17799 		/* Leave room for Link Level header */
17800 		/* hdrlen = tcp->tcp_hdr_len; */
17801 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17802 		mp1->b_wptr = &rptr[hdrlen];
17803 	}
17804 	mp1->b_rptr = rptr;
17805 
17806 	/* Fill in the timestamp option. */
17807 	if (tcp->tcp_snd_ts_ok) {
17808 		U32_TO_BE32((uint32_t)lbolt,
17809 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17810 		U32_TO_BE32(tcp->tcp_ts_recent,
17811 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17812 	} else {
17813 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17814 	}
17815 
17816 	/* copy header into outgoing packet */
17817 	dst = (ipaddr_t *)rptr;
17818 	src = (ipaddr_t *)tcp->tcp_iphc;
17819 	dst[0] = src[0];
17820 	dst[1] = src[1];
17821 	dst[2] = src[2];
17822 	dst[3] = src[3];
17823 	dst[4] = src[4];
17824 	dst[5] = src[5];
17825 	dst[6] = src[6];
17826 	dst[7] = src[7];
17827 	dst[8] = src[8];
17828 	dst[9] = src[9];
17829 	if (hdrlen -= 40) {
17830 		hdrlen >>= 2;
17831 		dst += 10;
17832 		src += 10;
17833 		do {
17834 			*dst++ = *src++;
17835 		} while (--hdrlen);
17836 	}
17837 
17838 	/*
17839 	 * Set the ECN info in the TCP header.  Note that this
17840 	 * is not the template header.
17841 	 */
17842 	if (tcp->tcp_ecn_ok) {
17843 		SET_ECT(tcp, rptr);
17844 
17845 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17846 		if (tcp->tcp_ecn_echo_on)
17847 			tcph->th_flags[0] |= TH_ECE;
17848 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17849 			tcph->th_flags[0] |= TH_CWR;
17850 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17851 		}
17852 	}
17853 
17854 	if (tcp->tcp_ip_forward_progress) {
17855 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17856 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17857 		tcp->tcp_ip_forward_progress = B_FALSE;
17858 	}
17859 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17860 	return;
17861 
17862 	/*
17863 	 * If we ran out of memory, we pretend to have sent the packet
17864 	 * and that it was lost on the wire.
17865 	 */
17866 no_memory:
17867 	return;
17868 
17869 slow:
17870 	/* leftover work from above */
17871 	tcp->tcp_unsent = len;
17872 	tcp->tcp_xmit_tail_unsent = len;
17873 	tcp_wput_data(tcp, NULL, B_FALSE);
17874 }
17875 
17876 /* ARGSUSED */
17877 void
17878 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17879 {
17880 	conn_t			*connp = (conn_t *)arg;
17881 	tcp_t			*tcp = connp->conn_tcp;
17882 	queue_t			*q = tcp->tcp_rq;
17883 	struct tcp_options	*tcpopt;
17884 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17885 
17886 	/* socket options */
17887 	uint_t 			sopp_flags;
17888 	ssize_t			sopp_rxhiwat;
17889 	ssize_t			sopp_maxblk;
17890 	ushort_t		sopp_wroff;
17891 	ushort_t		sopp_tail;
17892 	ushort_t		sopp_copyopt;
17893 
17894 	tcpopt = (struct tcp_options *)mp->b_rptr;
17895 
17896 	/*
17897 	 * Drop the eager's ref on the listener, that was placed when
17898 	 * this eager began life in tcp_conn_request.
17899 	 */
17900 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17901 	if (IPCL_IS_NONSTR(connp)) {
17902 		/* Safe to free conn_ind message */
17903 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17904 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
17905 
17906 		/* The listener tells us which upper handle to use */
17907 		ASSERT(tcpopt->to_flags & TCPOPT_UPPERHANDLE);
17908 		connp->conn_upper_handle = tcpopt->to_handle;
17909 	}
17910 
17911 	tcp->tcp_detached = B_FALSE;
17912 
17913 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
17914 		/*
17915 		 * Someone blewoff the eager before we could finish
17916 		 * the accept.
17917 		 *
17918 		 * The only reason eager exists it because we put in
17919 		 * a ref on it when conn ind went up. We need to send
17920 		 * a disconnect indication up while the last reference
17921 		 * on the eager will be dropped by the squeue when we
17922 		 * return.
17923 		 */
17924 		ASSERT(tcp->tcp_listener == NULL);
17925 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
17926 			if (IPCL_IS_NONSTR(connp)) {
17927 				ASSERT(tcp->tcp_issocket);
17928 				(*connp->conn_upcalls->su_disconnected)(
17929 				    connp->conn_upper_handle, tcp->tcp_connid,
17930 				    ECONNREFUSED);
17931 				freemsg(mp);
17932 			} else {
17933 				struct	T_discon_ind	*tdi;
17934 
17935 				(void) putnextctl1(q, M_FLUSH, FLUSHRW);
17936 				/*
17937 				 * Let us reuse the incoming mblk to avoid
17938 				 * memory allocation failure problems. We know
17939 				 * that the size of the incoming mblk i.e.
17940 				 * stroptions is greater than sizeof
17941 				 * T_discon_ind. So the reallocb below can't
17942 				 * fail.
17943 				 */
17944 				freemsg(mp->b_cont);
17945 				mp->b_cont = NULL;
17946 				ASSERT(DB_REF(mp) == 1);
17947 				mp = reallocb(mp, sizeof (struct T_discon_ind),
17948 				    B_FALSE);
17949 				ASSERT(mp != NULL);
17950 				DB_TYPE(mp) = M_PROTO;
17951 				((union T_primitives *)mp->b_rptr)->type =
17952 				    T_DISCON_IND;
17953 				tdi = (struct T_discon_ind *)mp->b_rptr;
17954 				if (tcp->tcp_issocket) {
17955 					tdi->DISCON_reason = ECONNREFUSED;
17956 					tdi->SEQ_number = 0;
17957 				} else {
17958 					tdi->DISCON_reason = ENOPROTOOPT;
17959 					tdi->SEQ_number =
17960 					    tcp->tcp_conn_req_seqnum;
17961 				}
17962 				mp->b_wptr = mp->b_rptr +
17963 				    sizeof (struct T_discon_ind);
17964 				putnext(q, mp);
17965 				return;
17966 			}
17967 		}
17968 		if (tcp->tcp_hard_binding) {
17969 			tcp->tcp_hard_binding = B_FALSE;
17970 			tcp->tcp_hard_bound = B_TRUE;
17971 		}
17972 		return;
17973 	}
17974 
17975 	if (tcpopt->to_flags & TCPOPT_BOUNDIF) {
17976 		int boundif = tcpopt->to_boundif;
17977 		uint_t len = sizeof (int);
17978 
17979 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17980 		    IPV6_BOUND_IF, len, (uchar_t *)&boundif, &len,
17981 		    (uchar_t *)&boundif, NULL, tcp->tcp_cred);
17982 	}
17983 	if (tcpopt->to_flags & TCPOPT_RECVPKTINFO) {
17984 		uint_t on = 1;
17985 		uint_t len = sizeof (uint_t);
17986 		(void) tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, IPPROTO_IPV6,
17987 		    IPV6_RECVPKTINFO, len, (uchar_t *)&on, &len,
17988 		    (uchar_t *)&on, NULL, tcp->tcp_cred);
17989 	}
17990 
17991 	/*
17992 	 * For a loopback connection with tcp_direct_sockfs on, note that
17993 	 * we don't have to protect tcp_rcv_list yet because synchronous
17994 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
17995 	 * possibly race with us.
17996 	 */
17997 
17998 	/*
17999 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
18000 	 * properly.  This is the first time we know of the acceptor'
18001 	 * queue.  So we do it here.
18002 	 *
18003 	 * XXX
18004 	 */
18005 	if (tcp->tcp_rcv_list == NULL) {
18006 		/*
18007 		 * Recv queue is empty, tcp_rwnd should not have changed.
18008 		 * That means it should be equal to the listener's tcp_rwnd.
18009 		 */
18010 		if (!IPCL_IS_NONSTR(connp))
18011 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
18012 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
18013 	} else {
18014 #ifdef DEBUG
18015 		mblk_t *tmp;
18016 		mblk_t	*mp1;
18017 		uint_t	cnt = 0;
18018 
18019 		mp1 = tcp->tcp_rcv_list;
18020 		while ((tmp = mp1) != NULL) {
18021 			mp1 = tmp->b_next;
18022 			cnt += msgdsize(tmp);
18023 		}
18024 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
18025 #endif
18026 		/* There is some data, add them back to get the max. */
18027 		if (!IPCL_IS_NONSTR(connp))
18028 			tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18029 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18030 	}
18031 	/*
18032 	 * This is the first time we run on the correct
18033 	 * queue after tcp_accept. So fix all the q parameters
18034 	 * here.
18035 	 */
18036 	sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_MAXBLK | SOCKOPT_WROFF;
18037 	sopp_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
18038 
18039 	/*
18040 	 * Record the stream head's high water mark for this endpoint;
18041 	 * this is used for flow-control purposes.
18042 	 */
18043 	sopp_rxhiwat = tcp->tcp_fused ?
18044 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
18045 	    MAX(tcp->tcp_recv_hiwater, tcps->tcps_sth_rcv_hiwat);
18046 
18047 	/*
18048 	 * Determine what write offset value to use depending on SACK and
18049 	 * whether the endpoint is fused or not.
18050 	 */
18051 	if (tcp->tcp_fused) {
18052 		ASSERT(tcp->tcp_loopback);
18053 		ASSERT(tcp->tcp_loopback_peer != NULL);
18054 		/*
18055 		 * For fused tcp loopback, set the stream head's write
18056 		 * offset value to zero since we won't be needing any room
18057 		 * for TCP/IP headers.  This would also improve performance
18058 		 * since it would reduce the amount of work done by kmem.
18059 		 * Non-fused tcp loopback case is handled separately below.
18060 		 */
18061 		sopp_wroff = 0;
18062 		/*
18063 		 * Update the peer's transmit parameters according to
18064 		 * our recently calculated high water mark value.
18065 		 */
18066 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18067 	} else if (tcp->tcp_snd_sack_ok) {
18068 		sopp_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18069 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18070 	} else {
18071 		sopp_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18072 		    tcps->tcps_wroff_xtra);
18073 	}
18074 
18075 	/*
18076 	 * If this is endpoint is handling SSL, then reserve extra
18077 	 * offset and space at the end.
18078 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18079 	 * overriding the previous setting. The extra cost of signing and
18080 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18081 	 * instead of a single contiguous one by the stream head
18082 	 * largely outweighs the statistical reduction of ACKs, when
18083 	 * applicable. The peer will also save on decryption and verification
18084 	 * costs.
18085 	 */
18086 	if (tcp->tcp_kssl_ctx != NULL) {
18087 		sopp_wroff += SSL3_WROFFSET;
18088 
18089 		sopp_flags |= SOCKOPT_TAIL;
18090 		sopp_tail = SSL3_MAX_TAIL_LEN;
18091 
18092 		sopp_flags |= SOCKOPT_ZCOPY;
18093 		sopp_copyopt = ZCVMUNSAFE;
18094 
18095 		sopp_maxblk = SSL3_MAX_RECORD_LEN;
18096 	}
18097 
18098 	/* Send the options up */
18099 	if (IPCL_IS_NONSTR(connp)) {
18100 		struct sock_proto_props sopp;
18101 
18102 		sopp.sopp_flags = sopp_flags;
18103 		sopp.sopp_wroff = sopp_wroff;
18104 		sopp.sopp_maxblk = sopp_maxblk;
18105 		sopp.sopp_rxhiwat = sopp_rxhiwat;
18106 		if (sopp_flags & SOCKOPT_TAIL) {
18107 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18108 			ASSERT(sopp_flags & SOCKOPT_ZCOPY);
18109 			sopp.sopp_tail = sopp_tail;
18110 			sopp.sopp_zcopyflag = sopp_copyopt;
18111 		}
18112 		(*connp->conn_upcalls->su_set_proto_props)
18113 		    (connp->conn_upper_handle, &sopp);
18114 	} else {
18115 		struct stroptions *stropt;
18116 		mblk_t *stropt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18117 		if (stropt_mp == NULL) {
18118 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
18119 			return;
18120 		}
18121 		DB_TYPE(stropt_mp) = M_SETOPTS;
18122 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18123 		stropt_mp->b_wptr += sizeof (struct stroptions);
18124 		stropt = (struct stroptions *)stropt_mp->b_rptr;
18125 		stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
18126 		stropt->so_hiwat = sopp_rxhiwat;
18127 		stropt->so_wroff = sopp_wroff;
18128 		stropt->so_maxblk = sopp_maxblk;
18129 
18130 		if (sopp_flags & SOCKOPT_TAIL) {
18131 			ASSERT(tcp->tcp_kssl_ctx != NULL);
18132 
18133 			stropt->so_flags |= SO_TAIL | SO_COPYOPT;
18134 			stropt->so_tail = sopp_tail;
18135 			stropt->so_copyopt = sopp_copyopt;
18136 		}
18137 
18138 		/* Send the options up */
18139 		putnext(q, stropt_mp);
18140 	}
18141 
18142 	freemsg(mp);
18143 	/*
18144 	 * Pass up any data and/or a fin that has been received.
18145 	 *
18146 	 * Adjust receive window in case it had decreased
18147 	 * (because there is data <=> tcp_rcv_list != NULL)
18148 	 * while the connection was detached. Note that
18149 	 * in case the eager was flow-controlled, w/o this
18150 	 * code, the rwnd may never open up again!
18151 	 */
18152 	if (tcp->tcp_rcv_list != NULL) {
18153 		if (IPCL_IS_NONSTR(connp)) {
18154 			mblk_t *mp;
18155 			int space_left;
18156 			int error;
18157 			boolean_t push = B_TRUE;
18158 
18159 			if (!tcp->tcp_fused && (*connp->conn_upcalls->su_recv)
18160 			    (connp->conn_upper_handle, NULL, 0, 0, &error,
18161 			    &push) >= 0) {
18162 				tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
18163 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18164 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18165 					tcp_xmit_ctl(NULL,
18166 					    tcp, (tcp->tcp_swnd == 0) ?
18167 					    tcp->tcp_suna : tcp->tcp_snxt,
18168 					    tcp->tcp_rnxt, TH_ACK);
18169 				}
18170 			}
18171 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18172 				push = B_TRUE;
18173 				tcp->tcp_rcv_list = mp->b_next;
18174 				mp->b_next = NULL;
18175 				space_left = (*connp->conn_upcalls->su_recv)
18176 				    (connp->conn_upper_handle, mp, msgdsize(mp),
18177 				    0, &error, &push);
18178 				if (space_left < 0) {
18179 					/*
18180 					 * At this point the eager is not
18181 					 * visible to anyone, so fallback
18182 					 * can not happen.
18183 					 */
18184 					ASSERT(error != EOPNOTSUPP);
18185 				}
18186 			}
18187 			tcp->tcp_rcv_last_head = NULL;
18188 			tcp->tcp_rcv_last_tail = NULL;
18189 			tcp->tcp_rcv_cnt = 0;
18190 		} else {
18191 			/* We drain directly in case of fused tcp loopback */
18192 			sodirect_t *sodp;
18193 
18194 			if (!tcp->tcp_fused && canputnext(q)) {
18195 				tcp->tcp_rwnd = q->q_hiwat;
18196 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18197 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18198 					tcp_xmit_ctl(NULL,
18199 					    tcp, (tcp->tcp_swnd == 0) ?
18200 					    tcp->tcp_suna : tcp->tcp_snxt,
18201 					    tcp->tcp_rnxt, TH_ACK);
18202 				}
18203 			}
18204 
18205 			SOD_PTR_ENTER(tcp, sodp);
18206 			if (sodp != NULL) {
18207 				/* Sodirect, move from rcv_list */
18208 				ASSERT(!tcp->tcp_fused);
18209 				while ((mp = tcp->tcp_rcv_list) != NULL) {
18210 					tcp->tcp_rcv_list = mp->b_next;
18211 					mp->b_next = NULL;
18212 					(void) tcp_rcv_sod_enqueue(tcp, sodp,
18213 					    mp, msgdsize(mp));
18214 				}
18215 				tcp->tcp_rcv_last_head = NULL;
18216 				tcp->tcp_rcv_last_tail = NULL;
18217 				tcp->tcp_rcv_cnt = 0;
18218 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
18219 				/* sod_wakeup() did the mutex_exit() */
18220 			} else {
18221 				/* Not sodirect, drain */
18222 				(void) tcp_rcv_drain(tcp);
18223 			}
18224 		}
18225 
18226 		/*
18227 		 * For fused tcp loopback, back-enable peer endpoint
18228 		 * if it's currently flow-controlled.
18229 		 */
18230 		if (tcp->tcp_fused) {
18231 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18232 
18233 			ASSERT(peer_tcp != NULL);
18234 			ASSERT(peer_tcp->tcp_fused);
18235 			/*
18236 			 * In order to change the peer's tcp_flow_stopped,
18237 			 * we need to take locks for both end points. The
18238 			 * highest address is taken first.
18239 			 */
18240 			if (peer_tcp > tcp) {
18241 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18242 				mutex_enter(&tcp->tcp_non_sq_lock);
18243 			} else {
18244 				mutex_enter(&tcp->tcp_non_sq_lock);
18245 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18246 			}
18247 			if (peer_tcp->tcp_flow_stopped) {
18248 				tcp_clrqfull(peer_tcp);
18249 				TCP_STAT(tcps, tcp_fusion_backenabled);
18250 			}
18251 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18252 			mutex_exit(&tcp->tcp_non_sq_lock);
18253 		}
18254 	}
18255 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18256 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18257 		tcp->tcp_ordrel_done = B_TRUE;
18258 		if (IPCL_IS_NONSTR(connp)) {
18259 			ASSERT(tcp->tcp_ordrel_mp == NULL);
18260 			(*connp->conn_upcalls->su_opctl)(
18261 			    connp->conn_upper_handle,
18262 			    SOCK_OPCTL_SHUT_RECV, 0);
18263 		} else {
18264 			mp = tcp->tcp_ordrel_mp;
18265 			tcp->tcp_ordrel_mp = NULL;
18266 			putnext(q, mp);
18267 		}
18268 	}
18269 	if (tcp->tcp_hard_binding) {
18270 		tcp->tcp_hard_binding = B_FALSE;
18271 		tcp->tcp_hard_bound = B_TRUE;
18272 	}
18273 
18274 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
18275 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
18276 	    tcp->tcp_loopback_peer != NULL &&
18277 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
18278 		tcp_fuse_syncstr_enable_pair(tcp);
18279 	}
18280 
18281 	if (tcp->tcp_ka_enabled) {
18282 		tcp->tcp_ka_last_intrvl = 0;
18283 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18284 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18285 	}
18286 
18287 	/*
18288 	 * At this point, eager is fully established and will
18289 	 * have the following references -
18290 	 *
18291 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18292 	 * 1 reference for the squeue which will be dropped by the squeue as
18293 	 *	soon as this function returns.
18294 	 * There will be 1 additonal reference for being in classifier
18295 	 *	hash list provided something bad hasn't happened.
18296 	 */
18297 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18298 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18299 }
18300 
18301 /*
18302  * The function called through squeue to get behind listener's perimeter to
18303  * send a deffered conn_ind.
18304  */
18305 /* ARGSUSED */
18306 void
18307 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18308 {
18309 	conn_t	*connp = (conn_t *)arg;
18310 	tcp_t *listener = connp->conn_tcp;
18311 	struct T_conn_ind *conn_ind;
18312 	tcp_t *tcp;
18313 
18314 	if (listener->tcp_state == TCPS_CLOSED ||
18315 	    TCP_IS_DETACHED(listener)) {
18316 		/*
18317 		 * If listener has closed, it would have caused a
18318 		 * a cleanup/blowoff to happen for the eager.
18319 		 */
18320 
18321 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18322 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18323 		    conn_ind->OPT_length);
18324 		/*
18325 		 * We need to drop the ref on eager that was put
18326 		 * tcp_rput_data() before trying to send the conn_ind
18327 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18328 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18329 		 * listener is closed so we drop the ref.
18330 		 */
18331 		CONN_DEC_REF(tcp->tcp_connp);
18332 		freemsg(mp);
18333 		return;
18334 	}
18335 	if (IPCL_IS_NONSTR(connp)) {
18336 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18337 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18338 		    conn_ind->OPT_length);
18339 
18340 		if ((*connp->conn_upcalls->su_newconn)
18341 		    (connp->conn_upper_handle,
18342 		    (sock_lower_handle_t)tcp->tcp_connp,
18343 		    &sock_tcp_downcalls, DB_CRED(mp), DB_CPID(mp),
18344 		    &tcp->tcp_connp->conn_upcalls) != NULL) {
18345 			/* Keep the message around in case of fallback */
18346 			tcp->tcp_conn.tcp_eager_conn_ind = mp;
18347 		} else {
18348 			freemsg(mp);
18349 		}
18350 	} else {
18351 		putnext(listener->tcp_rq, mp);
18352 	}
18353 }
18354 
18355 /* ARGSUSED */
18356 static int
18357 tcp_accept_common(conn_t *lconnp, conn_t *econnp,
18358     sock_upper_handle_t sock_handle, cred_t *cr)
18359 {
18360 	tcp_t *listener, *eager;
18361 	mblk_t *opt_mp;
18362 	struct tcp_options *tcpopt;
18363 
18364 	listener = lconnp->conn_tcp;
18365 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18366 	eager = econnp->conn_tcp;
18367 	ASSERT(eager->tcp_listener != NULL);
18368 
18369 	ASSERT(eager->tcp_rq != NULL);
18370 
18371 	/* If tcp_fused and sodirect enabled disable it */
18372 	if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18373 		/* Fused, disable sodirect */
18374 		mutex_enter(eager->tcp_sodirect->sod_lockp);
18375 		SOD_DISABLE(eager->tcp_sodirect);
18376 		mutex_exit(eager->tcp_sodirect->sod_lockp);
18377 		eager->tcp_sodirect = NULL;
18378 	}
18379 
18380 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
18381 	if (opt_mp == NULL) {
18382 		return (-TPROTO);
18383 	}
18384 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
18385 	eager->tcp_issocket = B_TRUE;
18386 
18387 	econnp->conn_upcalls = lconnp->conn_upcalls;
18388 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18389 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18390 	ASSERT(econnp->conn_netstack ==
18391 	    listener->tcp_connp->conn_netstack);
18392 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18393 
18394 	/* Put the ref for IP */
18395 	CONN_INC_REF(econnp);
18396 
18397 	/*
18398 	 * We should have minimum of 3 references on the conn
18399 	 * at this point. One each for TCP and IP and one for
18400 	 * the T_conn_ind that was sent up when the 3-way handshake
18401 	 * completed. In the normal case we would also have another
18402 	 * reference (making a total of 4) for the conn being in the
18403 	 * classifier hash list. However the eager could have received
18404 	 * an RST subsequently and tcp_closei_local could have removed
18405 	 * the eager from the classifier hash list, hence we can't
18406 	 * assert that reference.
18407 	 */
18408 	ASSERT(econnp->conn_ref >= 3);
18409 
18410 	opt_mp->b_datap->db_type = M_SETOPTS;
18411 	opt_mp->b_wptr += sizeof (struct tcp_options);
18412 
18413 	/*
18414 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18415 	 * from listener to acceptor. In case of non-STREAMS sockets,
18416 	 * we also need to pass the upper handle along.
18417 	 */
18418 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
18419 	tcpopt->to_flags = 0;
18420 
18421 	if (IPCL_IS_NONSTR(econnp)) {
18422 		ASSERT(sock_handle != NULL);
18423 		tcpopt->to_flags |= TCPOPT_UPPERHANDLE;
18424 		tcpopt->to_handle = sock_handle;
18425 	}
18426 	if (listener->tcp_bound_if != 0) {
18427 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
18428 		tcpopt->to_boundif = listener->tcp_bound_if;
18429 	}
18430 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18431 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
18432 	}
18433 
18434 	mutex_enter(&listener->tcp_eager_lock);
18435 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18436 
18437 		tcp_t *tail;
18438 		tcp_t *tcp;
18439 		mblk_t *mp1;
18440 
18441 		tcp = listener->tcp_eager_prev_q0;
18442 		/*
18443 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
18444 		 * deferred T_conn_ind queue. We need to get to the head
18445 		 * of the queue in order to send up T_conn_ind the same
18446 		 * order as how the 3WHS is completed.
18447 		 */
18448 		while (tcp != listener) {
18449 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18450 			    !tcp->tcp_kssl_pending)
18451 				break;
18452 			else
18453 				tcp = tcp->tcp_eager_prev_q0;
18454 		}
18455 		/* None of the pending eagers can be sent up now */
18456 		if (tcp == listener)
18457 			goto no_more_eagers;
18458 
18459 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18460 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18461 		/* Move from q0 to q */
18462 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18463 		listener->tcp_conn_req_cnt_q0--;
18464 		listener->tcp_conn_req_cnt_q++;
18465 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18466 		    tcp->tcp_eager_prev_q0;
18467 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18468 		    tcp->tcp_eager_next_q0;
18469 		tcp->tcp_eager_prev_q0 = NULL;
18470 		tcp->tcp_eager_next_q0 = NULL;
18471 		tcp->tcp_conn_def_q0 = B_FALSE;
18472 
18473 		/* Make sure the tcp isn't in the list of droppables */
18474 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18475 		    tcp->tcp_eager_prev_drop_q0 == NULL);
18476 
18477 		/*
18478 		 * Insert at end of the queue because sockfs sends
18479 		 * down T_CONN_RES in chronological order. Leaving
18480 		 * the older conn indications at front of the queue
18481 		 * helps reducing search time.
18482 		 */
18483 		tail = listener->tcp_eager_last_q;
18484 		if (tail != NULL) {
18485 			tail->tcp_eager_next_q = tcp;
18486 		} else {
18487 			listener->tcp_eager_next_q = tcp;
18488 		}
18489 		listener->tcp_eager_last_q = tcp;
18490 		tcp->tcp_eager_next_q = NULL;
18491 
18492 		/* Need to get inside the listener perimeter */
18493 		CONN_INC_REF(listener->tcp_connp);
18494 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
18495 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
18496 		    SQTAG_TCP_SEND_PENDING);
18497 	}
18498 no_more_eagers:
18499 	tcp_eager_unlink(eager);
18500 	mutex_exit(&listener->tcp_eager_lock);
18501 
18502 	/*
18503 	 * At this point, the eager is detached from the listener
18504 	 * but we still have an extra refs on eager (apart from the
18505 	 * usual tcp references). The ref was placed in tcp_rput_data
18506 	 * before sending the conn_ind in tcp_send_conn_ind.
18507 	 * The ref will be dropped in tcp_accept_finish().
18508 	 */
18509 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
18510 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
18511 	return (0);
18512 }
18513 
18514 int
18515 tcp_accept(sock_lower_handle_t lproto_handle,
18516     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
18517     cred_t *cr)
18518 {
18519 	conn_t *lconnp, *econnp;
18520 	tcp_t *listener, *eager;
18521 	tcp_stack_t	*tcps;
18522 
18523 	lconnp = (conn_t *)lproto_handle;
18524 	listener = lconnp->conn_tcp;
18525 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18526 	econnp = (conn_t *)eproto_handle;
18527 	eager = econnp->conn_tcp;
18528 	ASSERT(eager->tcp_listener != NULL);
18529 	tcps = eager->tcp_tcps;
18530 
18531 	ASSERT(IPCL_IS_NONSTR(econnp));
18532 	/*
18533 	 * Create helper stream if it is a non-TPI TCP connection.
18534 	 */
18535 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
18536 		ip1dbg(("tcp_accept: create of IP helper stream"
18537 		    " failed\n"));
18538 		return (EPROTO);
18539 	}
18540 	eager->tcp_rq = econnp->conn_rq;
18541 	eager->tcp_wq = econnp->conn_wq;
18542 
18543 	ASSERT(eager->tcp_rq != NULL);
18544 
18545 	eager->tcp_sodirect = SOD_SOTOSODP(sock_handle);
18546 	return (tcp_accept_common(lconnp, econnp, sock_handle, cr));
18547 }
18548 
18549 
18550 /*
18551  * This is the STREAMS entry point for T_CONN_RES coming down on
18552  * Acceptor STREAM when  sockfs listener does accept processing.
18553  * Read the block comment on top of tcp_conn_request().
18554  */
18555 void
18556 tcp_tpi_accept(queue_t *q, mblk_t *mp)
18557 {
18558 	queue_t *rq = RD(q);
18559 	struct T_conn_res *conn_res;
18560 	tcp_t *eager;
18561 	tcp_t *listener;
18562 	struct T_ok_ack *ok;
18563 	t_scalar_t PRIM_type;
18564 	conn_t *econnp;
18565 
18566 	ASSERT(DB_TYPE(mp) == M_PROTO);
18567 
18568 	conn_res = (struct T_conn_res *)mp->b_rptr;
18569 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18570 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18571 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18572 		if (mp != NULL)
18573 			putnext(rq, mp);
18574 		return;
18575 	}
18576 	switch (conn_res->PRIM_type) {
18577 	case O_T_CONN_RES:
18578 	case T_CONN_RES:
18579 		/*
18580 		 * We pass up an err ack if allocb fails. This will
18581 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18582 		 * tcp_eager_blowoff to be called. sockfs will then call
18583 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18584 		 * we need to do the allocb up here because we have to
18585 		 * make sure rq->q_qinfo->qi_qclose still points to the
18586 		 * correct function (tcpclose_accept) in case allocb
18587 		 * fails.
18588 		 */
18589 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18590 		    &eager, conn_res->OPT_length);
18591 		PRIM_type = conn_res->PRIM_type;
18592 		mp->b_datap->db_type = M_PCPROTO;
18593 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18594 		ok = (struct T_ok_ack *)mp->b_rptr;
18595 		ok->PRIM_type = T_OK_ACK;
18596 		ok->CORRECT_prim = PRIM_type;
18597 		econnp = eager->tcp_connp;
18598 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18599 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18600 		eager->tcp_rq = rq;
18601 		eager->tcp_wq = q;
18602 		rq->q_ptr = econnp;
18603 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18604 		q->q_ptr = econnp;
18605 		q->q_qinfo = &tcp_winit;
18606 		listener = eager->tcp_listener;
18607 
18608 		/*
18609 		 * TCP is _D_SODIRECT and sockfs is directly above so
18610 		 * save shared sodirect_t pointer (if any).
18611 		 */
18612 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18613 		if (tcp_accept_common(listener->tcp_connp,
18614 		    econnp, NULL, CRED()) < 0) {
18615 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18616 			if (mp != NULL)
18617 				putnext(rq, mp);
18618 			return;
18619 		}
18620 
18621 		/*
18622 		 * Send the new local address also up to sockfs. There
18623 		 * should already be enough space in the mp that came
18624 		 * down from soaccept().
18625 		 */
18626 		if (eager->tcp_family == AF_INET) {
18627 			sin_t *sin;
18628 
18629 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18630 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18631 			sin = (sin_t *)mp->b_wptr;
18632 			mp->b_wptr += sizeof (sin_t);
18633 			sin->sin_family = AF_INET;
18634 			sin->sin_port = eager->tcp_lport;
18635 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18636 		} else {
18637 			sin6_t *sin6;
18638 
18639 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18640 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18641 			sin6 = (sin6_t *)mp->b_wptr;
18642 			mp->b_wptr += sizeof (sin6_t);
18643 			sin6->sin6_family = AF_INET6;
18644 			sin6->sin6_port = eager->tcp_lport;
18645 			if (eager->tcp_ipversion == IPV4_VERSION) {
18646 				sin6->sin6_flowinfo = 0;
18647 				IN6_IPADDR_TO_V4MAPPED(
18648 				    eager->tcp_ipha->ipha_src,
18649 				    &sin6->sin6_addr);
18650 			} else {
18651 				ASSERT(eager->tcp_ip6h != NULL);
18652 				sin6->sin6_flowinfo =
18653 				    eager->tcp_ip6h->ip6_vcf &
18654 				    ~IPV6_VERS_AND_FLOW_MASK;
18655 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18656 			}
18657 			sin6->sin6_scope_id = 0;
18658 			sin6->__sin6_src_id = 0;
18659 		}
18660 
18661 		putnext(rq, mp);
18662 		return;
18663 	default:
18664 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18665 		if (mp != NULL)
18666 			putnext(rq, mp);
18667 		return;
18668 	}
18669 }
18670 
18671 static int
18672 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18673 {
18674 	sin_t *sin = (sin_t *)sa;
18675 	sin6_t *sin6 = (sin6_t *)sa;
18676 
18677 	switch (tcp->tcp_family) {
18678 	case AF_INET:
18679 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18680 
18681 		if (*salenp < sizeof (sin_t))
18682 			return (EINVAL);
18683 
18684 		*sin = sin_null;
18685 		sin->sin_family = AF_INET;
18686 		sin->sin_port = tcp->tcp_lport;
18687 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18688 		break;
18689 
18690 	case AF_INET6:
18691 		if (*salenp < sizeof (sin6_t))
18692 			return (EINVAL);
18693 
18694 		*sin6 = sin6_null;
18695 		sin6->sin6_family = AF_INET6;
18696 		sin6->sin6_port = tcp->tcp_lport;
18697 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18698 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18699 			    &sin6->sin6_addr);
18700 		} else {
18701 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18702 		}
18703 		break;
18704 	}
18705 
18706 	return (0);
18707 }
18708 
18709 static int
18710 i_tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18711 {
18712 	sin_t *sin = (sin_t *)sa;
18713 	sin6_t *sin6 = (sin6_t *)sa;
18714 
18715 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18716 		return (ENOTCONN);
18717 
18718 	switch (tcp->tcp_family) {
18719 	case AF_INET:
18720 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18721 
18722 		if (*salenp < sizeof (sin_t))
18723 			return (EINVAL);
18724 
18725 		*sin = sin_null;
18726 		sin->sin_family = AF_INET;
18727 		sin->sin_port = tcp->tcp_fport;
18728 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18729 		    sin->sin_addr.s_addr);
18730 		*salenp = sizeof (sin_t);
18731 		break;
18732 
18733 	case AF_INET6:
18734 		if (*salenp < sizeof (sin6_t))
18735 			return (EINVAL);
18736 
18737 		*sin6 = sin6_null;
18738 		sin6->sin6_family = AF_INET6;
18739 		sin6->sin6_port = tcp->tcp_fport;
18740 		sin6->sin6_addr = tcp->tcp_remote_v6;
18741 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18742 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18743 			    ~IPV6_VERS_AND_FLOW_MASK;
18744 		}
18745 		*salenp = sizeof (sin6_t);
18746 		break;
18747 	}
18748 
18749 	return (0);
18750 }
18751 
18752 /*
18753  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18754  */
18755 static void
18756 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18757 {
18758 	void	*data;
18759 	mblk_t	*datamp = mp->b_cont;
18760 	tcp_t	*tcp = Q_TO_TCP(q);
18761 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18762 
18763 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18764 		cmdp->cb_error = EPROTO;
18765 		qreply(q, mp);
18766 		return;
18767 	}
18768 
18769 	data = datamp->b_rptr;
18770 
18771 	switch (cmdp->cb_cmd) {
18772 	case TI_GETPEERNAME:
18773 		cmdp->cb_error = i_tcp_getpeername(tcp, data, &cmdp->cb_len);
18774 		break;
18775 	case TI_GETMYNAME:
18776 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
18777 		break;
18778 	default:
18779 		cmdp->cb_error = EINVAL;
18780 		break;
18781 	}
18782 
18783 	qreply(q, mp);
18784 }
18785 
18786 void
18787 tcp_wput(queue_t *q, mblk_t *mp)
18788 {
18789 	conn_t	*connp = Q_TO_CONN(q);
18790 	tcp_t	*tcp;
18791 	void (*output_proc)();
18792 	t_scalar_t type;
18793 	uchar_t *rptr;
18794 	struct iocblk	*iocp;
18795 	size_t size;
18796 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18797 
18798 	ASSERT(connp->conn_ref >= 2);
18799 
18800 	switch (DB_TYPE(mp)) {
18801 	case M_DATA:
18802 		tcp = connp->conn_tcp;
18803 		ASSERT(tcp != NULL);
18804 
18805 		size = msgdsize(mp);
18806 
18807 		mutex_enter(&tcp->tcp_non_sq_lock);
18808 		tcp->tcp_squeue_bytes += size;
18809 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18810 			tcp_setqfull(tcp);
18811 		}
18812 		mutex_exit(&tcp->tcp_non_sq_lock);
18813 
18814 		if (DB_CRED(mp) == NULL && is_system_labeled())
18815 			msg_setcredpid(mp, CONN_CRED(connp), curproc->p_pid);
18816 
18817 		CONN_INC_REF(connp);
18818 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18819 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18820 		return;
18821 
18822 	case M_CMD:
18823 		tcp_wput_cmdblk(q, mp);
18824 		return;
18825 
18826 	case M_PROTO:
18827 	case M_PCPROTO:
18828 		/*
18829 		 * if it is a snmp message, don't get behind the squeue
18830 		 */
18831 		tcp = connp->conn_tcp;
18832 		rptr = mp->b_rptr;
18833 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18834 			type = ((union T_primitives *)rptr)->type;
18835 		} else {
18836 			if (tcp->tcp_debug) {
18837 				(void) strlog(TCP_MOD_ID, 0, 1,
18838 				    SL_ERROR|SL_TRACE,
18839 				    "tcp_wput_proto, dropping one...");
18840 			}
18841 			freemsg(mp);
18842 			return;
18843 		}
18844 		if (type == T_SVR4_OPTMGMT_REQ) {
18845 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18846 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18847 			    cr)) {
18848 				/*
18849 				 * This was a SNMP request
18850 				 */
18851 				return;
18852 			} else {
18853 				output_proc = tcp_wput_proto;
18854 			}
18855 		} else {
18856 			output_proc = tcp_wput_proto;
18857 		}
18858 		break;
18859 	case M_IOCTL:
18860 		/*
18861 		 * Most ioctls can be processed right away without going via
18862 		 * squeues - process them right here. Those that do require
18863 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18864 		 * are processed by tcp_wput_ioctl().
18865 		 */
18866 		iocp = (struct iocblk *)mp->b_rptr;
18867 		tcp = connp->conn_tcp;
18868 
18869 		switch (iocp->ioc_cmd) {
18870 		case TCP_IOC_ABORT_CONN:
18871 			tcp_ioctl_abort_conn(q, mp);
18872 			return;
18873 		case TI_GETPEERNAME:
18874 		case TI_GETMYNAME:
18875 			mi_copyin(q, mp, NULL,
18876 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18877 			return;
18878 		case ND_SET:
18879 			/* nd_getset does the necessary checks */
18880 		case ND_GET:
18881 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18882 				CALL_IP_WPUT(connp, q, mp);
18883 				return;
18884 			}
18885 			qreply(q, mp);
18886 			return;
18887 		case TCP_IOC_DEFAULT_Q:
18888 			/*
18889 			 * Wants to be the default wq. Check the credentials
18890 			 * first, the rest is executed via squeue.
18891 			 */
18892 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18893 				iocp->ioc_error = EPERM;
18894 				iocp->ioc_count = 0;
18895 				mp->b_datap->db_type = M_IOCACK;
18896 				qreply(q, mp);
18897 				return;
18898 			}
18899 			output_proc = tcp_wput_ioctl;
18900 			break;
18901 		default:
18902 			output_proc = tcp_wput_ioctl;
18903 			break;
18904 		}
18905 		break;
18906 	default:
18907 		output_proc = tcp_wput_nondata;
18908 		break;
18909 	}
18910 
18911 	CONN_INC_REF(connp);
18912 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18913 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18914 }
18915 
18916 /*
18917  * Initial STREAMS write side put() procedure for sockets. It tries to
18918  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18919  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18920  * are handled by tcp_wput() as usual.
18921  *
18922  * All further messages will also be handled by tcp_wput() because we cannot
18923  * be sure that the above short cut is safe later.
18924  */
18925 static void
18926 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18927 {
18928 	conn_t			*connp = Q_TO_CONN(wq);
18929 	tcp_t			*tcp = connp->conn_tcp;
18930 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18931 
18932 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18933 	wq->q_qinfo = &tcp_winit;
18934 
18935 	ASSERT(IPCL_IS_TCP(connp));
18936 	ASSERT(TCP_IS_SOCKET(tcp));
18937 
18938 	if (DB_TYPE(mp) == M_PCPROTO &&
18939 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18940 	    car->PRIM_type == T_CAPABILITY_REQ) {
18941 		tcp_capability_req(tcp, mp);
18942 		return;
18943 	}
18944 
18945 	tcp_wput(wq, mp);
18946 }
18947 
18948 /* ARGSUSED */
18949 static void
18950 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18951 {
18952 #ifdef DEBUG
18953 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18954 #endif
18955 	freemsg(mp);
18956 }
18957 
18958 static boolean_t
18959 tcp_zcopy_check(tcp_t *tcp)
18960 {
18961 	conn_t	*connp = tcp->tcp_connp;
18962 	ire_t	*ire;
18963 	boolean_t	zc_enabled = B_FALSE;
18964 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18965 
18966 	if (do_tcpzcopy == 2)
18967 		zc_enabled = B_TRUE;
18968 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18969 	    IPCL_IS_CONNECTED(connp) &&
18970 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18971 	    connp->conn_dontroute == 0 &&
18972 	    !connp->conn_nexthop_set &&
18973 	    connp->conn_outgoing_ill == NULL &&
18974 	    connp->conn_nofailover_ill == NULL &&
18975 	    do_tcpzcopy == 1) {
18976 		/*
18977 		 * the checks above  closely resemble the fast path checks
18978 		 * in tcp_send_data().
18979 		 */
18980 		mutex_enter(&connp->conn_lock);
18981 		ire = connp->conn_ire_cache;
18982 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18983 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18984 			IRE_REFHOLD(ire);
18985 			if (ire->ire_stq != NULL) {
18986 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
18987 
18988 				zc_enabled = ill && (ill->ill_capabilities &
18989 				    ILL_CAPAB_ZEROCOPY) &&
18990 				    (ill->ill_zerocopy_capab->
18991 				    ill_zerocopy_flags != 0);
18992 			}
18993 			IRE_REFRELE(ire);
18994 		}
18995 		mutex_exit(&connp->conn_lock);
18996 	}
18997 	tcp->tcp_snd_zcopy_on = zc_enabled;
18998 	if (!TCP_IS_DETACHED(tcp)) {
18999 		if (zc_enabled) {
19000 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
19001 			    ZCVMSAFE);
19002 			TCP_STAT(tcps, tcp_zcopy_on);
19003 		} else {
19004 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
19005 			    ZCVMUNSAFE);
19006 			TCP_STAT(tcps, tcp_zcopy_off);
19007 		}
19008 	}
19009 	return (zc_enabled);
19010 }
19011 
19012 static mblk_t *
19013 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
19014 {
19015 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19016 
19017 	if (do_tcpzcopy == 2)
19018 		return (bp);
19019 	else if (tcp->tcp_snd_zcopy_on) {
19020 		tcp->tcp_snd_zcopy_on = B_FALSE;
19021 		if (!TCP_IS_DETACHED(tcp)) {
19022 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
19023 			    ZCVMUNSAFE);
19024 			TCP_STAT(tcps, tcp_zcopy_disable);
19025 		}
19026 	}
19027 	return (tcp_zcopy_backoff(tcp, bp, 0));
19028 }
19029 
19030 /*
19031  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
19032  * the original desballoca'ed segmapped mblk.
19033  */
19034 static mblk_t *
19035 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
19036 {
19037 	mblk_t *head, *tail, *nbp;
19038 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19039 
19040 	if (IS_VMLOANED_MBLK(bp)) {
19041 		TCP_STAT(tcps, tcp_zcopy_backoff);
19042 		if ((head = copyb(bp)) == NULL) {
19043 			/* fail to backoff; leave it for the next backoff */
19044 			tcp->tcp_xmit_zc_clean = B_FALSE;
19045 			return (bp);
19046 		}
19047 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19048 			if (fix_xmitlist)
19049 				tcp_zcopy_notify(tcp);
19050 			else
19051 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19052 		}
19053 		nbp = bp->b_cont;
19054 		if (fix_xmitlist) {
19055 			head->b_prev = bp->b_prev;
19056 			head->b_next = bp->b_next;
19057 			if (tcp->tcp_xmit_tail == bp)
19058 				tcp->tcp_xmit_tail = head;
19059 		}
19060 		bp->b_next = NULL;
19061 		bp->b_prev = NULL;
19062 		freeb(bp);
19063 	} else {
19064 		head = bp;
19065 		nbp = bp->b_cont;
19066 	}
19067 	tail = head;
19068 	while (nbp) {
19069 		if (IS_VMLOANED_MBLK(nbp)) {
19070 			TCP_STAT(tcps, tcp_zcopy_backoff);
19071 			if ((tail->b_cont = copyb(nbp)) == NULL) {
19072 				tcp->tcp_xmit_zc_clean = B_FALSE;
19073 				tail->b_cont = nbp;
19074 				return (head);
19075 			}
19076 			tail = tail->b_cont;
19077 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19078 				if (fix_xmitlist)
19079 					tcp_zcopy_notify(tcp);
19080 				else
19081 					tail->b_datap->db_struioflag |=
19082 					    STRUIO_ZCNOTIFY;
19083 			}
19084 			bp = nbp;
19085 			nbp = nbp->b_cont;
19086 			if (fix_xmitlist) {
19087 				tail->b_prev = bp->b_prev;
19088 				tail->b_next = bp->b_next;
19089 				if (tcp->tcp_xmit_tail == bp)
19090 					tcp->tcp_xmit_tail = tail;
19091 			}
19092 			bp->b_next = NULL;
19093 			bp->b_prev = NULL;
19094 			freeb(bp);
19095 		} else {
19096 			tail->b_cont = nbp;
19097 			tail = nbp;
19098 			nbp = nbp->b_cont;
19099 		}
19100 	}
19101 	if (fix_xmitlist) {
19102 		tcp->tcp_xmit_last = tail;
19103 		tcp->tcp_xmit_zc_clean = B_TRUE;
19104 	}
19105 	return (head);
19106 }
19107 
19108 static void
19109 tcp_zcopy_notify(tcp_t *tcp)
19110 {
19111 	struct stdata	*stp;
19112 	conn_t *connp;
19113 
19114 	if (tcp->tcp_detached)
19115 		return;
19116 	connp = tcp->tcp_connp;
19117 	if (IPCL_IS_NONSTR(connp)) {
19118 		(*connp->conn_upcalls->su_zcopy_notify)
19119 		    (connp->conn_upper_handle);
19120 		return;
19121 	}
19122 	stp = STREAM(tcp->tcp_rq);
19123 	mutex_enter(&stp->sd_lock);
19124 	stp->sd_flag |= STZCNOTIFY;
19125 	cv_broadcast(&stp->sd_zcopy_wait);
19126 	mutex_exit(&stp->sd_lock);
19127 }
19128 
19129 static boolean_t
19130 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19131 {
19132 	ire_t	*ire;
19133 	conn_t	*connp = tcp->tcp_connp;
19134 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19135 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19136 
19137 	mutex_enter(&connp->conn_lock);
19138 	ire = connp->conn_ire_cache;
19139 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19140 
19141 	if ((ire != NULL) &&
19142 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19143 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19144 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19145 		IRE_REFHOLD(ire);
19146 		mutex_exit(&connp->conn_lock);
19147 	} else {
19148 		boolean_t cached = B_FALSE;
19149 		ts_label_t *tsl;
19150 
19151 		/* force a recheck later on */
19152 		tcp->tcp_ire_ill_check_done = B_FALSE;
19153 
19154 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19155 		connp->conn_ire_cache = NULL;
19156 		mutex_exit(&connp->conn_lock);
19157 
19158 		if (ire != NULL)
19159 			IRE_REFRELE_NOTR(ire);
19160 
19161 		tsl = crgetlabel(CONN_CRED(connp));
19162 		ire = (dst ?
19163 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19164 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19165 		    connp->conn_zoneid, tsl, ipst));
19166 
19167 		if (ire == NULL) {
19168 			TCP_STAT(tcps, tcp_ire_null);
19169 			return (B_FALSE);
19170 		}
19171 
19172 		IRE_REFHOLD_NOTR(ire);
19173 
19174 		mutex_enter(&connp->conn_lock);
19175 		if (CONN_CACHE_IRE(connp)) {
19176 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19177 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19178 				TCP_CHECK_IREINFO(tcp, ire);
19179 				connp->conn_ire_cache = ire;
19180 				cached = B_TRUE;
19181 			}
19182 			rw_exit(&ire->ire_bucket->irb_lock);
19183 		}
19184 		mutex_exit(&connp->conn_lock);
19185 
19186 		/*
19187 		 * We can continue to use the ire but since it was
19188 		 * not cached, we should drop the extra reference.
19189 		 */
19190 		if (!cached)
19191 			IRE_REFRELE_NOTR(ire);
19192 
19193 		/*
19194 		 * Rampart note: no need to select a new label here, since
19195 		 * labels are not allowed to change during the life of a TCP
19196 		 * connection.
19197 		 */
19198 	}
19199 
19200 	*irep = ire;
19201 
19202 	return (B_TRUE);
19203 }
19204 
19205 /*
19206  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19207  *
19208  * 0 = success;
19209  * 1 = failed to find ire and ill.
19210  */
19211 static boolean_t
19212 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19213 {
19214 	ipha_t		*ipha;
19215 	ipaddr_t	dst;
19216 	ire_t		*ire;
19217 	ill_t		*ill;
19218 	conn_t		*connp = tcp->tcp_connp;
19219 	mblk_t		*ire_fp_mp;
19220 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19221 
19222 	if (mp != NULL)
19223 		ipha = (ipha_t *)mp->b_rptr;
19224 	else
19225 		ipha = tcp->tcp_ipha;
19226 	dst = ipha->ipha_dst;
19227 
19228 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19229 		return (B_FALSE);
19230 
19231 	if ((ire->ire_flags & RTF_MULTIRT) ||
19232 	    (ire->ire_stq == NULL) ||
19233 	    (ire->ire_nce == NULL) ||
19234 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19235 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19236 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19237 		TCP_STAT(tcps, tcp_ip_ire_send);
19238 		IRE_REFRELE(ire);
19239 		return (B_FALSE);
19240 	}
19241 
19242 	ill = ire_to_ill(ire);
19243 	if (connp->conn_outgoing_ill != NULL) {
19244 		ill_t *conn_outgoing_ill = NULL;
19245 		/*
19246 		 * Choose a good ill in the group to send the packets on.
19247 		 */
19248 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
19249 		ill = ire_to_ill(ire);
19250 	}
19251 	ASSERT(ill != NULL);
19252 
19253 	if (!tcp->tcp_ire_ill_check_done) {
19254 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19255 		tcp->tcp_ire_ill_check_done = B_TRUE;
19256 	}
19257 
19258 	*irep = ire;
19259 	*illp = ill;
19260 
19261 	return (B_TRUE);
19262 }
19263 
19264 static void
19265 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19266 {
19267 	ipha_t		*ipha;
19268 	ipaddr_t	src;
19269 	ipaddr_t	dst;
19270 	uint32_t	cksum;
19271 	ire_t		*ire;
19272 	uint16_t	*up;
19273 	ill_t		*ill;
19274 	conn_t		*connp = tcp->tcp_connp;
19275 	uint32_t	hcksum_txflags = 0;
19276 	mblk_t		*ire_fp_mp;
19277 	uint_t		ire_fp_mp_len;
19278 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19279 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19280 
19281 	ASSERT(DB_TYPE(mp) == M_DATA);
19282 
19283 	if (is_system_labeled() && DB_CRED(mp) == NULL)
19284 		mblk_setcred(mp, CONN_CRED(tcp->tcp_connp));
19285 
19286 	ipha = (ipha_t *)mp->b_rptr;
19287 	src = ipha->ipha_src;
19288 	dst = ipha->ipha_dst;
19289 
19290 	ASSERT(q != NULL);
19291 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19292 
19293 	/*
19294 	 * Drop off fast path for IPv6 and also if options are present or
19295 	 * we need to resolve a TS label.
19296 	 */
19297 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19298 	    !IPCL_IS_CONNECTED(connp) ||
19299 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19300 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19301 	    !connp->conn_ulp_labeled ||
19302 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19303 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19304 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19305 		if (tcp->tcp_snd_zcopy_aware)
19306 			mp = tcp_zcopy_disable(tcp, mp);
19307 		TCP_STAT(tcps, tcp_ip_send);
19308 		CALL_IP_WPUT(connp, q, mp);
19309 		return;
19310 	}
19311 
19312 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19313 		if (tcp->tcp_snd_zcopy_aware)
19314 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19315 		CALL_IP_WPUT(connp, q, mp);
19316 		return;
19317 	}
19318 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19319 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19320 
19321 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19322 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19323 #ifndef _BIG_ENDIAN
19324 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19325 #endif
19326 
19327 	/*
19328 	 * Check to see if we need to re-enable LSO/MDT for this connection
19329 	 * because it was previously disabled due to changes in the ill;
19330 	 * note that by doing it here, this re-enabling only applies when
19331 	 * the packet is not dispatched through CALL_IP_WPUT().
19332 	 *
19333 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19334 	 * case, since that's how we ended up here.  For IPv6, we do the
19335 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19336 	 */
19337 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19338 		/*
19339 		 * Restore LSO for this connection, so that next time around
19340 		 * it is eligible to go through tcp_lsosend() path again.
19341 		 */
19342 		TCP_STAT(tcps, tcp_lso_enabled);
19343 		tcp->tcp_lso = B_TRUE;
19344 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19345 		    "interface %s\n", (void *)connp, ill->ill_name));
19346 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19347 		/*
19348 		 * Restore MDT for this connection, so that next time around
19349 		 * it is eligible to go through tcp_multisend() path again.
19350 		 */
19351 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19352 		tcp->tcp_mdt = B_TRUE;
19353 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19354 		    "interface %s\n", (void *)connp, ill->ill_name));
19355 	}
19356 
19357 	if (tcp->tcp_snd_zcopy_aware) {
19358 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19359 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19360 			mp = tcp_zcopy_disable(tcp, mp);
19361 		/*
19362 		 * we shouldn't need to reset ipha as the mp containing
19363 		 * ipha should never be a zero-copy mp.
19364 		 */
19365 	}
19366 
19367 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19368 		ASSERT(ill->ill_hcksum_capab != NULL);
19369 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19370 	}
19371 
19372 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19373 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19374 
19375 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19376 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19377 
19378 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19379 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19380 
19381 	/* Software checksum? */
19382 	if (DB_CKSUMFLAGS(mp) == 0) {
19383 		TCP_STAT(tcps, tcp_out_sw_cksum);
19384 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19385 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19386 	}
19387 
19388 	/* Calculate IP header checksum if hardware isn't capable */
19389 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19390 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19391 		    ((uint16_t *)ipha)[4]);
19392 	}
19393 
19394 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19395 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19396 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19397 
19398 	UPDATE_OB_PKT_COUNT(ire);
19399 	ire->ire_last_used_time = lbolt;
19400 
19401 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19402 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19403 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19404 	    ntohs(ipha->ipha_length));
19405 
19406 	DTRACE_PROBE4(ip4__physical__out__start,
19407 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
19408 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
19409 	    ipst->ips_ipv4firewall_physical_out,
19410 	    NULL, ill, ipha, mp, mp, 0, ipst);
19411 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19412 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
19413 
19414 	if (mp != NULL) {
19415 		if (ipst->ips_ipobs_enabled) {
19416 			zoneid_t szone;
19417 
19418 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
19419 			    ipst, ALL_ZONES);
19420 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
19421 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
19422 		}
19423 
19424 		ILL_SEND_TX(ill, ire, connp, mp, 0);
19425 	}
19426 
19427 	IRE_REFRELE(ire);
19428 }
19429 
19430 /*
19431  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19432  * if the receiver shrinks the window, i.e. moves the right window to the
19433  * left, the we should not send new data, but should retransmit normally the
19434  * old unacked data between suna and suna + swnd. We might has sent data
19435  * that is now outside the new window, pretend that we didn't send  it.
19436  */
19437 static void
19438 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19439 {
19440 	uint32_t	snxt = tcp->tcp_snxt;
19441 	mblk_t		*xmit_tail;
19442 	int32_t		offset;
19443 
19444 	ASSERT(shrunk_count > 0);
19445 
19446 	/* Pretend we didn't send the data outside the window */
19447 	snxt -= shrunk_count;
19448 
19449 	/* Get the mblk and the offset in it per the shrunk window */
19450 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19451 
19452 	ASSERT(xmit_tail != NULL);
19453 
19454 	/* Reset all the values per the now shrunk window */
19455 	tcp->tcp_snxt = snxt;
19456 	tcp->tcp_xmit_tail = xmit_tail;
19457 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19458 	    offset;
19459 	tcp->tcp_unsent += shrunk_count;
19460 
19461 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19462 		/*
19463 		 * Make sure the timer is running so that we will probe a zero
19464 		 * window.
19465 		 */
19466 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19467 }
19468 
19469 
19470 /*
19471  * The TCP normal data output path.
19472  * NOTE: the logic of the fast path is duplicated from this function.
19473  */
19474 static void
19475 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19476 {
19477 	int		len;
19478 	mblk_t		*local_time;
19479 	mblk_t		*mp1;
19480 	uint32_t	snxt;
19481 	int		tail_unsent;
19482 	int		tcpstate;
19483 	int		usable = 0;
19484 	mblk_t		*xmit_tail;
19485 	queue_t		*q = tcp->tcp_wq;
19486 	int32_t		mss;
19487 	int32_t		num_sack_blk = 0;
19488 	int32_t		tcp_hdr_len;
19489 	int32_t		tcp_tcp_hdr_len;
19490 	int		mdt_thres;
19491 	int		rc;
19492 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19493 	ip_stack_t	*ipst;
19494 
19495 	tcpstate = tcp->tcp_state;
19496 	if (mp == NULL) {
19497 		/*
19498 		 * tcp_wput_data() with NULL mp should only be called when
19499 		 * there is unsent data.
19500 		 */
19501 		ASSERT(tcp->tcp_unsent > 0);
19502 		/* Really tacky... but we need this for detached closes. */
19503 		len = tcp->tcp_unsent;
19504 		goto data_null;
19505 	}
19506 
19507 #if CCS_STATS
19508 	wrw_stats.tot.count++;
19509 	wrw_stats.tot.bytes += msgdsize(mp);
19510 #endif
19511 	ASSERT(mp->b_datap->db_type == M_DATA);
19512 	/*
19513 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19514 	 * or before a connection attempt has begun.
19515 	 */
19516 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19517 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19518 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19519 #ifdef DEBUG
19520 			cmn_err(CE_WARN,
19521 			    "tcp_wput_data: data after ordrel, %s",
19522 			    tcp_display(tcp, NULL,
19523 			    DISP_ADDR_AND_PORT));
19524 #else
19525 			if (tcp->tcp_debug) {
19526 				(void) strlog(TCP_MOD_ID, 0, 1,
19527 				    SL_TRACE|SL_ERROR,
19528 				    "tcp_wput_data: data after ordrel, %s\n",
19529 				    tcp_display(tcp, NULL,
19530 				    DISP_ADDR_AND_PORT));
19531 			}
19532 #endif /* DEBUG */
19533 		}
19534 		if (tcp->tcp_snd_zcopy_aware &&
19535 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19536 			tcp_zcopy_notify(tcp);
19537 		freemsg(mp);
19538 		mutex_enter(&tcp->tcp_non_sq_lock);
19539 		if (tcp->tcp_flow_stopped &&
19540 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19541 			tcp_clrqfull(tcp);
19542 		}
19543 		mutex_exit(&tcp->tcp_non_sq_lock);
19544 		return;
19545 	}
19546 
19547 	/* Strip empties */
19548 	for (;;) {
19549 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19550 		    (uintptr_t)INT_MAX);
19551 		len = (int)(mp->b_wptr - mp->b_rptr);
19552 		if (len > 0)
19553 			break;
19554 		mp1 = mp;
19555 		mp = mp->b_cont;
19556 		freeb(mp1);
19557 		if (!mp) {
19558 			return;
19559 		}
19560 	}
19561 
19562 	/* If we are the first on the list ... */
19563 	if (tcp->tcp_xmit_head == NULL) {
19564 		tcp->tcp_xmit_head = mp;
19565 		tcp->tcp_xmit_tail = mp;
19566 		tcp->tcp_xmit_tail_unsent = len;
19567 	} else {
19568 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19569 		struct datab *dp;
19570 
19571 		mp1 = tcp->tcp_xmit_last;
19572 		if (len < tcp_tx_pull_len &&
19573 		    (dp = mp1->b_datap)->db_ref == 1 &&
19574 		    dp->db_lim - mp1->b_wptr >= len) {
19575 			ASSERT(len > 0);
19576 			ASSERT(!mp1->b_cont);
19577 			if (len == 1) {
19578 				*mp1->b_wptr++ = *mp->b_rptr;
19579 			} else {
19580 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19581 				mp1->b_wptr += len;
19582 			}
19583 			if (mp1 == tcp->tcp_xmit_tail)
19584 				tcp->tcp_xmit_tail_unsent += len;
19585 			mp1->b_cont = mp->b_cont;
19586 			if (tcp->tcp_snd_zcopy_aware &&
19587 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19588 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19589 			freeb(mp);
19590 			mp = mp1;
19591 		} else {
19592 			tcp->tcp_xmit_last->b_cont = mp;
19593 		}
19594 		len += tcp->tcp_unsent;
19595 	}
19596 
19597 	/* Tack on however many more positive length mblks we have */
19598 	if ((mp1 = mp->b_cont) != NULL) {
19599 		do {
19600 			int tlen;
19601 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19602 			    (uintptr_t)INT_MAX);
19603 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19604 			if (tlen <= 0) {
19605 				mp->b_cont = mp1->b_cont;
19606 				freeb(mp1);
19607 			} else {
19608 				len += tlen;
19609 				mp = mp1;
19610 			}
19611 		} while ((mp1 = mp->b_cont) != NULL);
19612 	}
19613 	tcp->tcp_xmit_last = mp;
19614 	tcp->tcp_unsent = len;
19615 
19616 	if (urgent)
19617 		usable = 1;
19618 
19619 data_null:
19620 	snxt = tcp->tcp_snxt;
19621 	xmit_tail = tcp->tcp_xmit_tail;
19622 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19623 
19624 	/*
19625 	 * Note that tcp_mss has been adjusted to take into account the
19626 	 * timestamp option if applicable.  Because SACK options do not
19627 	 * appear in every TCP segments and they are of variable lengths,
19628 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19629 	 * the actual segment length when we need to send a segment which
19630 	 * includes SACK options.
19631 	 */
19632 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19633 		int32_t	opt_len;
19634 
19635 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19636 		    tcp->tcp_num_sack_blk);
19637 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19638 		    2 + TCPOPT_HEADER_LEN;
19639 		mss = tcp->tcp_mss - opt_len;
19640 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19641 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19642 	} else {
19643 		mss = tcp->tcp_mss;
19644 		tcp_hdr_len = tcp->tcp_hdr_len;
19645 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19646 	}
19647 
19648 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19649 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19650 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19651 	}
19652 	if (tcpstate == TCPS_SYN_RCVD) {
19653 		/*
19654 		 * The three-way connection establishment handshake is not
19655 		 * complete yet. We want to queue the data for transmission
19656 		 * after entering ESTABLISHED state (RFC793). A jump to
19657 		 * "done" label effectively leaves data on the queue.
19658 		 */
19659 		goto done;
19660 	} else {
19661 		int usable_r;
19662 
19663 		/*
19664 		 * In the special case when cwnd is zero, which can only
19665 		 * happen if the connection is ECN capable, return now.
19666 		 * New segments is sent using tcp_timer().  The timer
19667 		 * is set in tcp_rput_data().
19668 		 */
19669 		if (tcp->tcp_cwnd == 0) {
19670 			/*
19671 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19672 			 * finished.
19673 			 */
19674 			ASSERT(tcp->tcp_ecn_ok ||
19675 			    tcp->tcp_state < TCPS_ESTABLISHED);
19676 			return;
19677 		}
19678 
19679 		/* NOTE: trouble if xmitting while SYN not acked? */
19680 		usable_r = snxt - tcp->tcp_suna;
19681 		usable_r = tcp->tcp_swnd - usable_r;
19682 
19683 		/*
19684 		 * Check if the receiver has shrunk the window.  If
19685 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19686 		 * cannot be set as there is unsent data, so FIN cannot
19687 		 * be sent out.  Otherwise, we need to take into account
19688 		 * of FIN as it consumes an "invisible" sequence number.
19689 		 */
19690 		ASSERT(tcp->tcp_fin_sent == 0);
19691 		if (usable_r < 0) {
19692 			/*
19693 			 * The receiver has shrunk the window and we have sent
19694 			 * -usable_r date beyond the window, re-adjust.
19695 			 *
19696 			 * If TCP window scaling is enabled, there can be
19697 			 * round down error as the advertised receive window
19698 			 * is actually right shifted n bits.  This means that
19699 			 * the lower n bits info is wiped out.  It will look
19700 			 * like the window is shrunk.  Do a check here to
19701 			 * see if the shrunk amount is actually within the
19702 			 * error in window calculation.  If it is, just
19703 			 * return.  Note that this check is inside the
19704 			 * shrunk window check.  This makes sure that even
19705 			 * though tcp_process_shrunk_swnd() is not called,
19706 			 * we will stop further processing.
19707 			 */
19708 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19709 				tcp_process_shrunk_swnd(tcp, -usable_r);
19710 			}
19711 			return;
19712 		}
19713 
19714 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19715 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19716 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19717 
19718 		/* usable = MIN(usable, unsent) */
19719 		if (usable_r > len)
19720 			usable_r = len;
19721 
19722 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19723 		if (usable_r > 0) {
19724 			usable = usable_r;
19725 		} else {
19726 			/* Bypass all other unnecessary processing. */
19727 			goto done;
19728 		}
19729 	}
19730 
19731 	local_time = (mblk_t *)lbolt;
19732 
19733 	/*
19734 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19735 	 * BSD.  This is more in line with the true intent of Nagle.
19736 	 *
19737 	 * The conditions are:
19738 	 * 1. The amount of unsent data (or amount of data which can be
19739 	 *    sent, whichever is smaller) is less than Nagle limit.
19740 	 * 2. The last sent size is also less than Nagle limit.
19741 	 * 3. There is unack'ed data.
19742 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19743 	 *    Nagle algorithm.  This reduces the probability that urgent
19744 	 *    bytes get "merged" together.
19745 	 * 5. The app has not closed the connection.  This eliminates the
19746 	 *    wait time of the receiving side waiting for the last piece of
19747 	 *    (small) data.
19748 	 *
19749 	 * If all are satisified, exit without sending anything.  Note
19750 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19751 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19752 	 * 4095).
19753 	 */
19754 	if (usable < (int)tcp->tcp_naglim &&
19755 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19756 	    snxt != tcp->tcp_suna &&
19757 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19758 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19759 		goto done;
19760 	}
19761 
19762 	if (tcp->tcp_cork) {
19763 		/*
19764 		 * if the tcp->tcp_cork option is set, then we have to force
19765 		 * TCP not to send partial segment (smaller than MSS bytes).
19766 		 * We are calculating the usable now based on full mss and
19767 		 * will save the rest of remaining data for later.
19768 		 */
19769 		if (usable < mss)
19770 			goto done;
19771 		usable = (usable / mss) * mss;
19772 	}
19773 
19774 	/* Update the latest receive window size in TCP header. */
19775 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19776 	    tcp->tcp_tcph->th_win);
19777 
19778 	/*
19779 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19780 	 *
19781 	 * 1. Simple TCP/IP{v4,v6} (no options).
19782 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19783 	 * 3. If the TCP connection is in ESTABLISHED state.
19784 	 * 4. The TCP is not detached.
19785 	 *
19786 	 * If any of the above conditions have changed during the
19787 	 * connection, stop using LSO/MDT and restore the stream head
19788 	 * parameters accordingly.
19789 	 */
19790 	ipst = tcps->tcps_netstack->netstack_ip;
19791 
19792 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19793 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19794 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19795 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19796 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19797 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19798 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19799 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19800 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19801 		if (tcp->tcp_lso) {
19802 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19803 			tcp->tcp_lso = B_FALSE;
19804 		} else {
19805 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19806 			tcp->tcp_mdt = B_FALSE;
19807 		}
19808 
19809 		/* Anything other than detached is considered pathological */
19810 		if (!TCP_IS_DETACHED(tcp)) {
19811 			if (tcp->tcp_lso)
19812 				TCP_STAT(tcps, tcp_lso_disabled);
19813 			else
19814 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19815 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19816 		}
19817 	}
19818 
19819 	/* Use MDT if sendable amount is greater than the threshold */
19820 	if (tcp->tcp_mdt &&
19821 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19822 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19823 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19824 	    (tcp->tcp_valid_bits == 0 ||
19825 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19826 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19827 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19828 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19829 		    local_time, mdt_thres);
19830 	} else {
19831 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19832 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19833 		    local_time, INT_MAX);
19834 	}
19835 
19836 	/* Pretend that all we were trying to send really got sent */
19837 	if (rc < 0 && tail_unsent < 0) {
19838 		do {
19839 			xmit_tail = xmit_tail->b_cont;
19840 			xmit_tail->b_prev = local_time;
19841 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19842 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19843 			tail_unsent += (int)(xmit_tail->b_wptr -
19844 			    xmit_tail->b_rptr);
19845 		} while (tail_unsent < 0);
19846 	}
19847 done:;
19848 	tcp->tcp_xmit_tail = xmit_tail;
19849 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19850 	len = tcp->tcp_snxt - snxt;
19851 	if (len) {
19852 		/*
19853 		 * If new data was sent, need to update the notsack
19854 		 * list, which is, afterall, data blocks that have
19855 		 * not been sack'ed by the receiver.  New data is
19856 		 * not sack'ed.
19857 		 */
19858 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19859 			/* len is a negative value. */
19860 			tcp->tcp_pipe -= len;
19861 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19862 			    tcp->tcp_snxt, snxt,
19863 			    &(tcp->tcp_num_notsack_blk),
19864 			    &(tcp->tcp_cnt_notsack_list));
19865 		}
19866 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19867 		tcp->tcp_rack = tcp->tcp_rnxt;
19868 		tcp->tcp_rack_cnt = 0;
19869 		if ((snxt + len) == tcp->tcp_suna) {
19870 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19871 		}
19872 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19873 		/*
19874 		 * Didn't send anything. Make sure the timer is running
19875 		 * so that we will probe a zero window.
19876 		 */
19877 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19878 	}
19879 	/* Note that len is the amount we just sent but with a negative sign */
19880 	tcp->tcp_unsent += len;
19881 	mutex_enter(&tcp->tcp_non_sq_lock);
19882 	if (tcp->tcp_flow_stopped) {
19883 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19884 			tcp_clrqfull(tcp);
19885 		}
19886 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19887 		tcp_setqfull(tcp);
19888 	}
19889 	mutex_exit(&tcp->tcp_non_sq_lock);
19890 }
19891 
19892 /*
19893  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19894  * outgoing TCP header with the template header, as well as other
19895  * options such as time-stamp, ECN and/or SACK.
19896  */
19897 static void
19898 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19899 {
19900 	tcph_t *tcp_tmpl, *tcp_h;
19901 	uint32_t *dst, *src;
19902 	int hdrlen;
19903 
19904 	ASSERT(OK_32PTR(rptr));
19905 
19906 	/* Template header */
19907 	tcp_tmpl = tcp->tcp_tcph;
19908 
19909 	/* Header of outgoing packet */
19910 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19911 
19912 	/* dst and src are opaque 32-bit fields, used for copying */
19913 	dst = (uint32_t *)rptr;
19914 	src = (uint32_t *)tcp->tcp_iphc;
19915 	hdrlen = tcp->tcp_hdr_len;
19916 
19917 	/* Fill time-stamp option if needed */
19918 	if (tcp->tcp_snd_ts_ok) {
19919 		U32_TO_BE32((uint32_t)now,
19920 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19921 		U32_TO_BE32(tcp->tcp_ts_recent,
19922 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19923 	} else {
19924 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19925 	}
19926 
19927 	/*
19928 	 * Copy the template header; is this really more efficient than
19929 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19930 	 * but perhaps not for other scenarios.
19931 	 */
19932 	dst[0] = src[0];
19933 	dst[1] = src[1];
19934 	dst[2] = src[2];
19935 	dst[3] = src[3];
19936 	dst[4] = src[4];
19937 	dst[5] = src[5];
19938 	dst[6] = src[6];
19939 	dst[7] = src[7];
19940 	dst[8] = src[8];
19941 	dst[9] = src[9];
19942 	if (hdrlen -= 40) {
19943 		hdrlen >>= 2;
19944 		dst += 10;
19945 		src += 10;
19946 		do {
19947 			*dst++ = *src++;
19948 		} while (--hdrlen);
19949 	}
19950 
19951 	/*
19952 	 * Set the ECN info in the TCP header if it is not a zero
19953 	 * window probe.  Zero window probe is only sent in
19954 	 * tcp_wput_data() and tcp_timer().
19955 	 */
19956 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19957 		SET_ECT(tcp, rptr);
19958 
19959 		if (tcp->tcp_ecn_echo_on)
19960 			tcp_h->th_flags[0] |= TH_ECE;
19961 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19962 			tcp_h->th_flags[0] |= TH_CWR;
19963 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19964 		}
19965 	}
19966 
19967 	/* Fill in SACK options */
19968 	if (num_sack_blk > 0) {
19969 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19970 		sack_blk_t *tmp;
19971 		int32_t	i;
19972 
19973 		wptr[0] = TCPOPT_NOP;
19974 		wptr[1] = TCPOPT_NOP;
19975 		wptr[2] = TCPOPT_SACK;
19976 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19977 		    sizeof (sack_blk_t);
19978 		wptr += TCPOPT_REAL_SACK_LEN;
19979 
19980 		tmp = tcp->tcp_sack_list;
19981 		for (i = 0; i < num_sack_blk; i++) {
19982 			U32_TO_BE32(tmp[i].begin, wptr);
19983 			wptr += sizeof (tcp_seq);
19984 			U32_TO_BE32(tmp[i].end, wptr);
19985 			wptr += sizeof (tcp_seq);
19986 		}
19987 		tcp_h->th_offset_and_rsrvd[0] +=
19988 		    ((num_sack_blk * 2 + 1) << 4);
19989 	}
19990 }
19991 
19992 /*
19993  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
19994  * the destination address and SAP attribute, and if necessary, the
19995  * hardware checksum offload attribute to a Multidata message.
19996  */
19997 static int
19998 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
19999     const uint32_t start, const uint32_t stuff, const uint32_t end,
20000     const uint32_t flags, tcp_stack_t *tcps)
20001 {
20002 	/* Add global destination address & SAP attribute */
20003 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
20004 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
20005 		    "destination address+SAP\n"));
20006 
20007 		if (dlmp != NULL)
20008 			TCP_STAT(tcps, tcp_mdt_allocfail);
20009 		return (-1);
20010 	}
20011 
20012 	/* Add global hwcksum attribute */
20013 	if (hwcksum &&
20014 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
20015 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
20016 		    "checksum attribute\n"));
20017 
20018 		TCP_STAT(tcps, tcp_mdt_allocfail);
20019 		return (-1);
20020 	}
20021 
20022 	return (0);
20023 }
20024 
20025 /*
20026  * Smaller and private version of pdescinfo_t used specifically for TCP,
20027  * which allows for only two payload spans per packet.
20028  */
20029 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
20030 
20031 /*
20032  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
20033  * scheme, and returns one the following:
20034  *
20035  * -1 = failed allocation.
20036  *  0 = success; burst count reached, or usable send window is too small,
20037  *      and that we'd rather wait until later before sending again.
20038  */
20039 static int
20040 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20041     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20042     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20043     const int mdt_thres)
20044 {
20045 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
20046 	multidata_t	*mmd;
20047 	uint_t		obsegs, obbytes, hdr_frag_sz;
20048 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
20049 	int		num_burst_seg, max_pld;
20050 	pdesc_t		*pkt;
20051 	tcp_pdescinfo_t	tcp_pkt_info;
20052 	pdescinfo_t	*pkt_info;
20053 	int		pbuf_idx, pbuf_idx_nxt;
20054 	int		seg_len, len, spill, af;
20055 	boolean_t	add_buffer, zcopy, clusterwide;
20056 	boolean_t	rconfirm = B_FALSE;
20057 	boolean_t	done = B_FALSE;
20058 	uint32_t	cksum;
20059 	uint32_t	hwcksum_flags;
20060 	ire_t		*ire = NULL;
20061 	ill_t		*ill;
20062 	ipha_t		*ipha;
20063 	ip6_t		*ip6h;
20064 	ipaddr_t	src, dst;
20065 	ill_zerocopy_capab_t *zc_cap = NULL;
20066 	uint16_t	*up;
20067 	int		err;
20068 	conn_t		*connp;
20069 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20070 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
20071 	int		usable_mmd, tail_unsent_mmd;
20072 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
20073 	mblk_t		*xmit_tail_mmd;
20074 
20075 #ifdef	_BIG_ENDIAN
20076 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20077 #else
20078 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20079 #endif
20080 
20081 #define	PREP_NEW_MULTIDATA() {			\
20082 	mmd = NULL;				\
20083 	md_mp = md_hbuf = NULL;			\
20084 	cur_hdr_off = 0;			\
20085 	max_pld = tcp->tcp_mdt_max_pld;		\
20086 	pbuf_idx = pbuf_idx_nxt = -1;		\
20087 	add_buffer = B_TRUE;			\
20088 	zcopy = B_FALSE;			\
20089 }
20090 
20091 #define	PREP_NEW_PBUF() {			\
20092 	md_pbuf = md_pbuf_nxt = NULL;		\
20093 	pbuf_idx = pbuf_idx_nxt = -1;		\
20094 	cur_pld_off = 0;			\
20095 	first_snxt = *snxt;			\
20096 	ASSERT(*tail_unsent > 0);		\
20097 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20098 }
20099 
20100 	ASSERT(mdt_thres >= mss);
20101 	ASSERT(*usable > 0 && *usable > mdt_thres);
20102 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20103 	ASSERT(!TCP_IS_DETACHED(tcp));
20104 	ASSERT(tcp->tcp_valid_bits == 0 ||
20105 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20106 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20107 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20108 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20109 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20110 
20111 	connp = tcp->tcp_connp;
20112 	ASSERT(connp != NULL);
20113 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20114 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20115 
20116 	usable_mmd = tail_unsent_mmd = 0;
20117 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20118 	xmit_tail_mmd = NULL;
20119 	/*
20120 	 * Note that tcp will only declare at most 2 payload spans per
20121 	 * packet, which is much lower than the maximum allowable number
20122 	 * of packet spans per Multidata.  For this reason, we use the
20123 	 * privately declared and smaller descriptor info structure, in
20124 	 * order to save some stack space.
20125 	 */
20126 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20127 
20128 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20129 	if (af == AF_INET) {
20130 		dst = tcp->tcp_ipha->ipha_dst;
20131 		src = tcp->tcp_ipha->ipha_src;
20132 		ASSERT(!CLASSD(dst));
20133 	}
20134 	ASSERT(af == AF_INET ||
20135 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20136 
20137 	obsegs = obbytes = 0;
20138 	num_burst_seg = tcp->tcp_snd_burst;
20139 	md_mp_head = NULL;
20140 	PREP_NEW_MULTIDATA();
20141 
20142 	/*
20143 	 * Before we go on further, make sure there is an IRE that we can
20144 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20145 	 * in proceeding any further, and we should just hand everything
20146 	 * off to the legacy path.
20147 	 */
20148 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20149 		goto legacy_send_no_md;
20150 
20151 	ASSERT(ire != NULL);
20152 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20153 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20154 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20155 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20156 	/*
20157 	 * If we do support loopback for MDT (which requires modifications
20158 	 * to the receiving paths), the following assertions should go away,
20159 	 * and we would be sending the Multidata to loopback conn later on.
20160 	 */
20161 	ASSERT(!IRE_IS_LOCAL(ire));
20162 	ASSERT(ire->ire_stq != NULL);
20163 
20164 	ill = ire_to_ill(ire);
20165 	ASSERT(ill != NULL);
20166 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20167 
20168 	if (!tcp->tcp_ire_ill_check_done) {
20169 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20170 		tcp->tcp_ire_ill_check_done = B_TRUE;
20171 	}
20172 
20173 	/*
20174 	 * If the underlying interface conditions have changed, or if the
20175 	 * new interface does not support MDT, go back to legacy path.
20176 	 */
20177 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20178 		/* don't go through this path anymore for this connection */
20179 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20180 		tcp->tcp_mdt = B_FALSE;
20181 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20182 		    "interface %s\n", (void *)connp, ill->ill_name));
20183 		/* IRE will be released prior to returning */
20184 		goto legacy_send_no_md;
20185 	}
20186 
20187 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20188 		zc_cap = ill->ill_zerocopy_capab;
20189 
20190 	/*
20191 	 * Check if we can take tcp fast-path. Note that "incomplete"
20192 	 * ire's (where the link-layer for next hop is not resolved
20193 	 * or where the fast-path header in nce_fp_mp is not available
20194 	 * yet) are sent down the legacy (slow) path.
20195 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20196 	 */
20197 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20198 		/* IRE will be released prior to returning */
20199 		goto legacy_send_no_md;
20200 	}
20201 
20202 	/* go to legacy path if interface doesn't support zerocopy */
20203 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20204 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20205 		/* IRE will be released prior to returning */
20206 		goto legacy_send_no_md;
20207 	}
20208 
20209 	/* does the interface support hardware checksum offload? */
20210 	hwcksum_flags = 0;
20211 	if (ILL_HCKSUM_CAPABLE(ill) &&
20212 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20213 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20214 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20215 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20216 		    HCKSUM_IPHDRCKSUM)
20217 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20218 
20219 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20220 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20221 			hwcksum_flags |= HCK_FULLCKSUM;
20222 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20223 		    HCKSUM_INET_PARTIAL)
20224 			hwcksum_flags |= HCK_PARTIALCKSUM;
20225 	}
20226 
20227 	/*
20228 	 * Each header fragment consists of the leading extra space,
20229 	 * followed by the TCP/IP header, and the trailing extra space.
20230 	 * We make sure that each header fragment begins on a 32-bit
20231 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20232 	 * aligned in tcp_mdt_update).
20233 	 */
20234 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20235 	    tcp->tcp_mdt_hdr_tail), 4);
20236 
20237 	/* are we starting from the beginning of data block? */
20238 	if (*tail_unsent == 0) {
20239 		*xmit_tail = (*xmit_tail)->b_cont;
20240 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20241 		*tail_unsent = (int)MBLKL(*xmit_tail);
20242 	}
20243 
20244 	/*
20245 	 * Here we create one or more Multidata messages, each made up of
20246 	 * one header buffer and up to N payload buffers.  This entire
20247 	 * operation is done within two loops:
20248 	 *
20249 	 * The outer loop mostly deals with creating the Multidata message,
20250 	 * as well as the header buffer that gets added to it.  It also
20251 	 * links the Multidata messages together such that all of them can
20252 	 * be sent down to the lower layer in a single putnext call; this
20253 	 * linking behavior depends on the tcp_mdt_chain tunable.
20254 	 *
20255 	 * The inner loop takes an existing Multidata message, and adds
20256 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20257 	 * packetizes those buffers by filling up the corresponding header
20258 	 * buffer fragments with the proper IP and TCP headers, and by
20259 	 * describing the layout of each packet in the packet descriptors
20260 	 * that get added to the Multidata.
20261 	 */
20262 	do {
20263 		/*
20264 		 * If usable send window is too small, or data blocks in
20265 		 * transmit list are smaller than our threshold (i.e. app
20266 		 * performs large writes followed by small ones), we hand
20267 		 * off the control over to the legacy path.  Note that we'll
20268 		 * get back the control once it encounters a large block.
20269 		 */
20270 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20271 		    (*xmit_tail)->b_cont != NULL &&
20272 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20273 			/* send down what we've got so far */
20274 			if (md_mp_head != NULL) {
20275 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20276 				    obsegs, obbytes, &rconfirm);
20277 			}
20278 			/*
20279 			 * Pass control over to tcp_send(), but tell it to
20280 			 * return to us once a large-size transmission is
20281 			 * possible.
20282 			 */
20283 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20284 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20285 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20286 			    tail_unsent, xmit_tail, local_time,
20287 			    mdt_thres)) <= 0) {
20288 				/* burst count reached, or alloc failed */
20289 				IRE_REFRELE(ire);
20290 				return (err);
20291 			}
20292 
20293 			/* tcp_send() may have sent everything, so check */
20294 			if (*usable <= 0) {
20295 				IRE_REFRELE(ire);
20296 				return (0);
20297 			}
20298 
20299 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20300 			/*
20301 			 * We may have delivered the Multidata, so make sure
20302 			 * to re-initialize before the next round.
20303 			 */
20304 			md_mp_head = NULL;
20305 			obsegs = obbytes = 0;
20306 			num_burst_seg = tcp->tcp_snd_burst;
20307 			PREP_NEW_MULTIDATA();
20308 
20309 			/* are we starting from the beginning of data block? */
20310 			if (*tail_unsent == 0) {
20311 				*xmit_tail = (*xmit_tail)->b_cont;
20312 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20313 				    (uintptr_t)INT_MAX);
20314 				*tail_unsent = (int)MBLKL(*xmit_tail);
20315 			}
20316 		}
20317 		/*
20318 		 * Record current values for parameters we may need to pass
20319 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20320 		 * each iteration of the outer loop (each multidata message
20321 		 * creation). If we have a failure in the inner loop, we send
20322 		 * any complete multidata messages we have before reverting
20323 		 * to using the traditional non-md path.
20324 		 */
20325 		snxt_mmd = *snxt;
20326 		usable_mmd = *usable;
20327 		xmit_tail_mmd = *xmit_tail;
20328 		tail_unsent_mmd = *tail_unsent;
20329 		obsegs_mmd = obsegs;
20330 		obbytes_mmd = obbytes;
20331 
20332 		/*
20333 		 * max_pld limits the number of mblks in tcp's transmit
20334 		 * queue that can be added to a Multidata message.  Once
20335 		 * this counter reaches zero, no more additional mblks
20336 		 * can be added to it.  What happens afterwards depends
20337 		 * on whether or not we are set to chain the Multidata
20338 		 * messages.  If we are to link them together, reset
20339 		 * max_pld to its original value (tcp_mdt_max_pld) and
20340 		 * prepare to create a new Multidata message which will
20341 		 * get linked to md_mp_head.  Else, leave it alone and
20342 		 * let the inner loop break on its own.
20343 		 */
20344 		if (tcp_mdt_chain && max_pld == 0)
20345 			PREP_NEW_MULTIDATA();
20346 
20347 		/* adding a payload buffer; re-initialize values */
20348 		if (add_buffer)
20349 			PREP_NEW_PBUF();
20350 
20351 		/*
20352 		 * If we don't have a Multidata, either because we just
20353 		 * (re)entered this outer loop, or after we branched off
20354 		 * to tcp_send above, setup the Multidata and header
20355 		 * buffer to be used.
20356 		 */
20357 		if (md_mp == NULL) {
20358 			int md_hbuflen;
20359 			uint32_t start, stuff;
20360 
20361 			/*
20362 			 * Calculate Multidata header buffer size large enough
20363 			 * to hold all of the headers that can possibly be
20364 			 * sent at this moment.  We'd rather over-estimate
20365 			 * the size than running out of space; this is okay
20366 			 * since this buffer is small anyway.
20367 			 */
20368 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20369 
20370 			/*
20371 			 * Start and stuff offset for partial hardware
20372 			 * checksum offload; these are currently for IPv4.
20373 			 * For full checksum offload, they are set to zero.
20374 			 */
20375 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20376 				if (af == AF_INET) {
20377 					start = IP_SIMPLE_HDR_LENGTH;
20378 					stuff = IP_SIMPLE_HDR_LENGTH +
20379 					    TCP_CHECKSUM_OFFSET;
20380 				} else {
20381 					start = IPV6_HDR_LEN;
20382 					stuff = IPV6_HDR_LEN +
20383 					    TCP_CHECKSUM_OFFSET;
20384 				}
20385 			} else {
20386 				start = stuff = 0;
20387 			}
20388 
20389 			/*
20390 			 * Create the header buffer, Multidata, as well as
20391 			 * any necessary attributes (destination address,
20392 			 * SAP and hardware checksum offload) that should
20393 			 * be associated with the Multidata message.
20394 			 */
20395 			ASSERT(cur_hdr_off == 0);
20396 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20397 			    ((md_hbuf->b_wptr += md_hbuflen),
20398 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20399 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20400 			    /* fastpath mblk */
20401 			    ire->ire_nce->nce_res_mp,
20402 			    /* hardware checksum enabled */
20403 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20404 			    /* hardware checksum offsets */
20405 			    start, stuff, 0,
20406 			    /* hardware checksum flag */
20407 			    hwcksum_flags, tcps) != 0)) {
20408 legacy_send:
20409 				/*
20410 				 * We arrive here from a failure within the
20411 				 * inner (packetizer) loop or we fail one of
20412 				 * the conditionals above. We restore the
20413 				 * previously checkpointed values for:
20414 				 *    xmit_tail
20415 				 *    usable
20416 				 *    tail_unsent
20417 				 *    snxt
20418 				 *    obbytes
20419 				 *    obsegs
20420 				 * We should then be able to dispatch any
20421 				 * complete multidata before reverting to the
20422 				 * traditional path with consistent parameters
20423 				 * (the inner loop updates these as it
20424 				 * iterates).
20425 				 */
20426 				*xmit_tail = xmit_tail_mmd;
20427 				*usable = usable_mmd;
20428 				*tail_unsent = tail_unsent_mmd;
20429 				*snxt = snxt_mmd;
20430 				obbytes = obbytes_mmd;
20431 				obsegs = obsegs_mmd;
20432 				if (md_mp != NULL) {
20433 					/* Unlink message from the chain */
20434 					if (md_mp_head != NULL) {
20435 						err = (intptr_t)rmvb(md_mp_head,
20436 						    md_mp);
20437 						/*
20438 						 * We can't assert that rmvb
20439 						 * did not return -1, since we
20440 						 * may get here before linkb
20441 						 * happens.  We do, however,
20442 						 * check if we just removed the
20443 						 * only element in the list.
20444 						 */
20445 						if (err == 0)
20446 							md_mp_head = NULL;
20447 					}
20448 					/* md_hbuf gets freed automatically */
20449 					TCP_STAT(tcps, tcp_mdt_discarded);
20450 					freeb(md_mp);
20451 				} else {
20452 					/* Either allocb or mmd_alloc failed */
20453 					TCP_STAT(tcps, tcp_mdt_allocfail);
20454 					if (md_hbuf != NULL)
20455 						freeb(md_hbuf);
20456 				}
20457 
20458 				/* send down what we've got so far */
20459 				if (md_mp_head != NULL) {
20460 					tcp_multisend_data(tcp, ire, ill,
20461 					    md_mp_head, obsegs, obbytes,
20462 					    &rconfirm);
20463 				}
20464 legacy_send_no_md:
20465 				if (ire != NULL)
20466 					IRE_REFRELE(ire);
20467 				/*
20468 				 * Too bad; let the legacy path handle this.
20469 				 * We specify INT_MAX for the threshold, since
20470 				 * we gave up with the Multidata processings
20471 				 * and let the old path have it all.
20472 				 */
20473 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20474 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20475 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20476 				    snxt, tail_unsent, xmit_tail, local_time,
20477 				    INT_MAX));
20478 			}
20479 
20480 			/* link to any existing ones, if applicable */
20481 			TCP_STAT(tcps, tcp_mdt_allocd);
20482 			if (md_mp_head == NULL) {
20483 				md_mp_head = md_mp;
20484 			} else if (tcp_mdt_chain) {
20485 				TCP_STAT(tcps, tcp_mdt_linked);
20486 				linkb(md_mp_head, md_mp);
20487 			}
20488 		}
20489 
20490 		ASSERT(md_mp_head != NULL);
20491 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20492 		ASSERT(md_mp != NULL && mmd != NULL);
20493 		ASSERT(md_hbuf != NULL);
20494 
20495 		/*
20496 		 * Packetize the transmittable portion of the data block;
20497 		 * each data block is essentially added to the Multidata
20498 		 * as a payload buffer.  We also deal with adding more
20499 		 * than one payload buffers, which happens when the remaining
20500 		 * packetized portion of the current payload buffer is less
20501 		 * than MSS, while the next data block in transmit queue
20502 		 * has enough data to make up for one.  This "spillover"
20503 		 * case essentially creates a split-packet, where portions
20504 		 * of the packet's payload fragments may span across two
20505 		 * virtually discontiguous address blocks.
20506 		 */
20507 		seg_len = mss;
20508 		do {
20509 			len = seg_len;
20510 
20511 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20512 			ipha = NULL;
20513 			ip6h = NULL;
20514 
20515 			ASSERT(len > 0);
20516 			ASSERT(max_pld >= 0);
20517 			ASSERT(!add_buffer || cur_pld_off == 0);
20518 
20519 			/*
20520 			 * First time around for this payload buffer; note
20521 			 * in the case of a spillover, the following has
20522 			 * been done prior to adding the split-packet
20523 			 * descriptor to Multidata, and we don't want to
20524 			 * repeat the process.
20525 			 */
20526 			if (add_buffer) {
20527 				ASSERT(mmd != NULL);
20528 				ASSERT(md_pbuf == NULL);
20529 				ASSERT(md_pbuf_nxt == NULL);
20530 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20531 
20532 				/*
20533 				 * Have we reached the limit?  We'd get to
20534 				 * this case when we're not chaining the
20535 				 * Multidata messages together, and since
20536 				 * we're done, terminate this loop.
20537 				 */
20538 				if (max_pld == 0)
20539 					break; /* done */
20540 
20541 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20542 					TCP_STAT(tcps, tcp_mdt_allocfail);
20543 					goto legacy_send; /* out_of_mem */
20544 				}
20545 
20546 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20547 				    zc_cap != NULL) {
20548 					if (!ip_md_zcopy_attr(mmd, NULL,
20549 					    zc_cap->ill_zerocopy_flags)) {
20550 						freeb(md_pbuf);
20551 						TCP_STAT(tcps,
20552 						    tcp_mdt_allocfail);
20553 						/* out_of_mem */
20554 						goto legacy_send;
20555 					}
20556 					zcopy = B_TRUE;
20557 				}
20558 
20559 				md_pbuf->b_rptr += base_pld_off;
20560 
20561 				/*
20562 				 * Add a payload buffer to the Multidata; this
20563 				 * operation must not fail, or otherwise our
20564 				 * logic in this routine is broken.  There
20565 				 * is no memory allocation done by the
20566 				 * routine, so any returned failure simply
20567 				 * tells us that we've done something wrong.
20568 				 *
20569 				 * A failure tells us that either we're adding
20570 				 * the same payload buffer more than once, or
20571 				 * we're trying to add more buffers than
20572 				 * allowed (max_pld calculation is wrong).
20573 				 * None of the above cases should happen, and
20574 				 * we panic because either there's horrible
20575 				 * heap corruption, and/or programming mistake.
20576 				 */
20577 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20578 				if (pbuf_idx < 0) {
20579 					cmn_err(CE_PANIC, "tcp_multisend: "
20580 					    "payload buffer logic error "
20581 					    "detected for tcp %p mmd %p "
20582 					    "pbuf %p (%d)\n",
20583 					    (void *)tcp, (void *)mmd,
20584 					    (void *)md_pbuf, pbuf_idx);
20585 				}
20586 
20587 				ASSERT(max_pld > 0);
20588 				--max_pld;
20589 				add_buffer = B_FALSE;
20590 			}
20591 
20592 			ASSERT(md_mp_head != NULL);
20593 			ASSERT(md_pbuf != NULL);
20594 			ASSERT(md_pbuf_nxt == NULL);
20595 			ASSERT(pbuf_idx != -1);
20596 			ASSERT(pbuf_idx_nxt == -1);
20597 			ASSERT(*usable > 0);
20598 
20599 			/*
20600 			 * We spillover to the next payload buffer only
20601 			 * if all of the following is true:
20602 			 *
20603 			 *   1. There is not enough data on the current
20604 			 *	payload buffer to make up `len',
20605 			 *   2. We are allowed to send `len',
20606 			 *   3. The next payload buffer length is large
20607 			 *	enough to accomodate `spill'.
20608 			 */
20609 			if ((spill = len - *tail_unsent) > 0 &&
20610 			    *usable >= len &&
20611 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20612 			    max_pld > 0) {
20613 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20614 				if (md_pbuf_nxt == NULL) {
20615 					TCP_STAT(tcps, tcp_mdt_allocfail);
20616 					goto legacy_send; /* out_of_mem */
20617 				}
20618 
20619 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20620 				    zc_cap != NULL) {
20621 					if (!ip_md_zcopy_attr(mmd, NULL,
20622 					    zc_cap->ill_zerocopy_flags)) {
20623 						freeb(md_pbuf_nxt);
20624 						TCP_STAT(tcps,
20625 						    tcp_mdt_allocfail);
20626 						/* out_of_mem */
20627 						goto legacy_send;
20628 					}
20629 					zcopy = B_TRUE;
20630 				}
20631 
20632 				/*
20633 				 * See comments above on the first call to
20634 				 * mmd_addpldbuf for explanation on the panic.
20635 				 */
20636 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20637 				if (pbuf_idx_nxt < 0) {
20638 					panic("tcp_multisend: "
20639 					    "next payload buffer logic error "
20640 					    "detected for tcp %p mmd %p "
20641 					    "pbuf %p (%d)\n",
20642 					    (void *)tcp, (void *)mmd,
20643 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20644 				}
20645 
20646 				ASSERT(max_pld > 0);
20647 				--max_pld;
20648 			} else if (spill > 0) {
20649 				/*
20650 				 * If there's a spillover, but the following
20651 				 * xmit_tail couldn't give us enough octets
20652 				 * to reach "len", then stop the current
20653 				 * Multidata creation and let the legacy
20654 				 * tcp_send() path take over.  We don't want
20655 				 * to send the tiny segment as part of this
20656 				 * Multidata for performance reasons; instead,
20657 				 * we let the legacy path deal with grouping
20658 				 * it with the subsequent small mblks.
20659 				 */
20660 				if (*usable >= len &&
20661 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20662 					max_pld = 0;
20663 					break;	/* done */
20664 				}
20665 
20666 				/*
20667 				 * We can't spillover, and we are near
20668 				 * the end of the current payload buffer,
20669 				 * so send what's left.
20670 				 */
20671 				ASSERT(*tail_unsent > 0);
20672 				len = *tail_unsent;
20673 			}
20674 
20675 			/* tail_unsent is negated if there is a spillover */
20676 			*tail_unsent -= len;
20677 			*usable -= len;
20678 			ASSERT(*usable >= 0);
20679 
20680 			if (*usable < mss)
20681 				seg_len = *usable;
20682 			/*
20683 			 * Sender SWS avoidance; see comments in tcp_send();
20684 			 * everything else is the same, except that we only
20685 			 * do this here if there is no more data to be sent
20686 			 * following the current xmit_tail.  We don't check
20687 			 * for 1-byte urgent data because we shouldn't get
20688 			 * here if TCP_URG_VALID is set.
20689 			 */
20690 			if (*usable > 0 && *usable < mss &&
20691 			    ((md_pbuf_nxt == NULL &&
20692 			    (*xmit_tail)->b_cont == NULL) ||
20693 			    (md_pbuf_nxt != NULL &&
20694 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20695 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20696 			    (tcp->tcp_unsent -
20697 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20698 			    !tcp->tcp_zero_win_probe) {
20699 				if ((*snxt + len) == tcp->tcp_snxt &&
20700 				    (*snxt + len) == tcp->tcp_suna) {
20701 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20702 				}
20703 				done = B_TRUE;
20704 			}
20705 
20706 			/*
20707 			 * Prime pump for IP's checksumming on our behalf;
20708 			 * include the adjustment for a source route if any.
20709 			 * Do this only for software/partial hardware checksum
20710 			 * offload, as this field gets zeroed out later for
20711 			 * the full hardware checksum offload case.
20712 			 */
20713 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20714 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20715 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20716 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20717 			}
20718 
20719 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20720 			*snxt += len;
20721 
20722 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20723 			/*
20724 			 * We set the PUSH bit only if TCP has no more buffered
20725 			 * data to be transmitted (or if sender SWS avoidance
20726 			 * takes place), as opposed to setting it for every
20727 			 * last packet in the burst.
20728 			 */
20729 			if (done ||
20730 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20731 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20732 
20733 			/*
20734 			 * Set FIN bit if this is our last segment; snxt
20735 			 * already includes its length, and it will not
20736 			 * be adjusted after this point.
20737 			 */
20738 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20739 			    *snxt == tcp->tcp_fss) {
20740 				if (!tcp->tcp_fin_acked) {
20741 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20742 					BUMP_MIB(&tcps->tcps_mib,
20743 					    tcpOutControl);
20744 				}
20745 				if (!tcp->tcp_fin_sent) {
20746 					tcp->tcp_fin_sent = B_TRUE;
20747 					/*
20748 					 * tcp state must be ESTABLISHED
20749 					 * in order for us to get here in
20750 					 * the first place.
20751 					 */
20752 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20753 
20754 					/*
20755 					 * Upon returning from this routine,
20756 					 * tcp_wput_data() will set tcp_snxt
20757 					 * to be equal to snxt + tcp_fin_sent.
20758 					 * This is essentially the same as
20759 					 * setting it to tcp_fss + 1.
20760 					 */
20761 				}
20762 			}
20763 
20764 			tcp->tcp_last_sent_len = (ushort_t)len;
20765 
20766 			len += tcp_hdr_len;
20767 			if (tcp->tcp_ipversion == IPV4_VERSION)
20768 				tcp->tcp_ipha->ipha_length = htons(len);
20769 			else
20770 				tcp->tcp_ip6h->ip6_plen = htons(len -
20771 				    ((char *)&tcp->tcp_ip6h[1] -
20772 				    tcp->tcp_iphc));
20773 
20774 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20775 
20776 			/* setup header fragment */
20777 			PDESC_HDR_ADD(pkt_info,
20778 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20779 			    tcp->tcp_mdt_hdr_head,		/* head room */
20780 			    tcp_hdr_len,			/* len */
20781 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20782 
20783 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20784 			    hdr_frag_sz);
20785 			ASSERT(MBLKIN(md_hbuf,
20786 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20787 			    PDESC_HDRSIZE(pkt_info)));
20788 
20789 			/* setup first payload fragment */
20790 			PDESC_PLD_INIT(pkt_info);
20791 			PDESC_PLD_SPAN_ADD(pkt_info,
20792 			    pbuf_idx,				/* index */
20793 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20794 			    tcp->tcp_last_sent_len);		/* len */
20795 
20796 			/* create a split-packet in case of a spillover */
20797 			if (md_pbuf_nxt != NULL) {
20798 				ASSERT(spill > 0);
20799 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20800 				ASSERT(!add_buffer);
20801 
20802 				md_pbuf = md_pbuf_nxt;
20803 				md_pbuf_nxt = NULL;
20804 				pbuf_idx = pbuf_idx_nxt;
20805 				pbuf_idx_nxt = -1;
20806 				cur_pld_off = spill;
20807 
20808 				/* trim out first payload fragment */
20809 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20810 
20811 				/* setup second payload fragment */
20812 				PDESC_PLD_SPAN_ADD(pkt_info,
20813 				    pbuf_idx,			/* index */
20814 				    md_pbuf->b_rptr,		/* start */
20815 				    spill);			/* len */
20816 
20817 				if ((*xmit_tail)->b_next == NULL) {
20818 					/*
20819 					 * Store the lbolt used for RTT
20820 					 * estimation. We can only record one
20821 					 * timestamp per mblk so we do it when
20822 					 * we reach the end of the payload
20823 					 * buffer.  Also we only take a new
20824 					 * timestamp sample when the previous
20825 					 * timed data from the same mblk has
20826 					 * been ack'ed.
20827 					 */
20828 					(*xmit_tail)->b_prev = local_time;
20829 					(*xmit_tail)->b_next =
20830 					    (mblk_t *)(uintptr_t)first_snxt;
20831 				}
20832 
20833 				first_snxt = *snxt - spill;
20834 
20835 				/*
20836 				 * Advance xmit_tail; usable could be 0 by
20837 				 * the time we got here, but we made sure
20838 				 * above that we would only spillover to
20839 				 * the next data block if usable includes
20840 				 * the spilled-over amount prior to the
20841 				 * subtraction.  Therefore, we are sure
20842 				 * that xmit_tail->b_cont can't be NULL.
20843 				 */
20844 				ASSERT((*xmit_tail)->b_cont != NULL);
20845 				*xmit_tail = (*xmit_tail)->b_cont;
20846 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20847 				    (uintptr_t)INT_MAX);
20848 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20849 			} else {
20850 				cur_pld_off += tcp->tcp_last_sent_len;
20851 			}
20852 
20853 			/*
20854 			 * Fill in the header using the template header, and
20855 			 * add options such as time-stamp, ECN and/or SACK,
20856 			 * as needed.
20857 			 */
20858 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20859 			    (clock_t)local_time, num_sack_blk);
20860 
20861 			/* take care of some IP header businesses */
20862 			if (af == AF_INET) {
20863 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20864 
20865 				ASSERT(OK_32PTR((uchar_t *)ipha));
20866 				ASSERT(PDESC_HDRL(pkt_info) >=
20867 				    IP_SIMPLE_HDR_LENGTH);
20868 				ASSERT(ipha->ipha_version_and_hdr_length ==
20869 				    IP_SIMPLE_HDR_VERSION);
20870 
20871 				/*
20872 				 * Assign ident value for current packet; see
20873 				 * related comments in ip_wput_ire() about the
20874 				 * contract private interface with clustering
20875 				 * group.
20876 				 */
20877 				clusterwide = B_FALSE;
20878 				if (cl_inet_ipident != NULL) {
20879 					ASSERT(cl_inet_isclusterwide != NULL);
20880 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20881 					    AF_INET,
20882 					    (uint8_t *)(uintptr_t)src)) {
20883 						ipha->ipha_ident =
20884 						    (*cl_inet_ipident)
20885 						    (IPPROTO_IP, AF_INET,
20886 						    (uint8_t *)(uintptr_t)src,
20887 						    (uint8_t *)(uintptr_t)dst);
20888 						clusterwide = B_TRUE;
20889 					}
20890 				}
20891 
20892 				if (!clusterwide) {
20893 					ipha->ipha_ident = (uint16_t)
20894 					    atomic_add_32_nv(
20895 						&ire->ire_ident, 1);
20896 				}
20897 #ifndef _BIG_ENDIAN
20898 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20899 				    (ipha->ipha_ident >> 8);
20900 #endif
20901 			} else {
20902 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20903 
20904 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20905 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20906 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20907 				ASSERT(PDESC_HDRL(pkt_info) >=
20908 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20909 				    TCP_CHECKSUM_SIZE));
20910 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20911 
20912 				if (tcp->tcp_ip_forward_progress) {
20913 					rconfirm = B_TRUE;
20914 					tcp->tcp_ip_forward_progress = B_FALSE;
20915 				}
20916 			}
20917 
20918 			/* at least one payload span, and at most two */
20919 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20920 
20921 			/* add the packet descriptor to Multidata */
20922 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20923 			    KM_NOSLEEP)) == NULL) {
20924 				/*
20925 				 * Any failure other than ENOMEM indicates
20926 				 * that we have passed in invalid pkt_info
20927 				 * or parameters to mmd_addpdesc, which must
20928 				 * not happen.
20929 				 *
20930 				 * EINVAL is a result of failure on boundary
20931 				 * checks against the pkt_info contents.  It
20932 				 * should not happen, and we panic because
20933 				 * either there's horrible heap corruption,
20934 				 * and/or programming mistake.
20935 				 */
20936 				if (err != ENOMEM) {
20937 					cmn_err(CE_PANIC, "tcp_multisend: "
20938 					    "pdesc logic error detected for "
20939 					    "tcp %p mmd %p pinfo %p (%d)\n",
20940 					    (void *)tcp, (void *)mmd,
20941 					    (void *)pkt_info, err);
20942 				}
20943 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20944 				goto legacy_send; /* out_of_mem */
20945 			}
20946 			ASSERT(pkt != NULL);
20947 
20948 			/* calculate IP header and TCP checksums */
20949 			if (af == AF_INET) {
20950 				/* calculate pseudo-header checksum */
20951 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20952 				    (src >> 16) + (src & 0xFFFF);
20953 
20954 				/* offset for TCP header checksum */
20955 				up = IPH_TCPH_CHECKSUMP(ipha,
20956 				    IP_SIMPLE_HDR_LENGTH);
20957 			} else {
20958 				up = (uint16_t *)&ip6h->ip6_src;
20959 
20960 				/* calculate pseudo-header checksum */
20961 				cksum = up[0] + up[1] + up[2] + up[3] +
20962 				    up[4] + up[5] + up[6] + up[7] +
20963 				    up[8] + up[9] + up[10] + up[11] +
20964 				    up[12] + up[13] + up[14] + up[15];
20965 
20966 				/* Fold the initial sum */
20967 				cksum = (cksum & 0xffff) + (cksum >> 16);
20968 
20969 				up = (uint16_t *)(((uchar_t *)ip6h) +
20970 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20971 			}
20972 
20973 			if (hwcksum_flags & HCK_FULLCKSUM) {
20974 				/* clear checksum field for hardware */
20975 				*up = 0;
20976 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20977 				uint32_t sum;
20978 
20979 				/* pseudo-header checksumming */
20980 				sum = *up + cksum + IP_TCP_CSUM_COMP;
20981 				sum = (sum & 0xFFFF) + (sum >> 16);
20982 				*up = (sum & 0xFFFF) + (sum >> 16);
20983 			} else {
20984 				/* software checksumming */
20985 				TCP_STAT(tcps, tcp_out_sw_cksum);
20986 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
20987 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
20988 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
20989 				    cksum + IP_TCP_CSUM_COMP);
20990 				if (*up == 0)
20991 					*up = 0xFFFF;
20992 			}
20993 
20994 			/* IPv4 header checksum */
20995 			if (af == AF_INET) {
20996 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
20997 					ipha->ipha_hdr_checksum = 0;
20998 				} else {
20999 					IP_HDR_CKSUM(ipha, cksum,
21000 					    ((uint32_t *)ipha)[0],
21001 					    ((uint16_t *)ipha)[4]);
21002 				}
21003 			}
21004 
21005 			if (af == AF_INET &&
21006 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
21007 			    af == AF_INET6 &&
21008 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
21009 				mblk_t	*mp, *mp1;
21010 				uchar_t	*hdr_rptr, *hdr_wptr;
21011 				uchar_t	*pld_rptr, *pld_wptr;
21012 
21013 				/*
21014 				 * We reconstruct a pseudo packet for the hooks
21015 				 * framework using mmd_transform_link().
21016 				 * If it is a split packet we pullup the
21017 				 * payload. FW_HOOKS expects a pkt comprising
21018 				 * of two mblks: a header and the payload.
21019 				 */
21020 				if ((mp = mmd_transform_link(pkt)) == NULL) {
21021 					TCP_STAT(tcps, tcp_mdt_allocfail);
21022 					goto legacy_send;
21023 				}
21024 
21025 				if (pkt_info->pld_cnt > 1) {
21026 					/* split payload, more than one pld */
21027 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
21028 					    NULL) {
21029 						freemsg(mp);
21030 						TCP_STAT(tcps,
21031 						    tcp_mdt_allocfail);
21032 						goto legacy_send;
21033 					}
21034 					freemsg(mp->b_cont);
21035 					mp->b_cont = mp1;
21036 				} else {
21037 					mp1 = mp->b_cont;
21038 				}
21039 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
21040 
21041 				/*
21042 				 * Remember the message offsets. This is so we
21043 				 * can detect changes when we return from the
21044 				 * FW_HOOKS callbacks.
21045 				 */
21046 				hdr_rptr = mp->b_rptr;
21047 				hdr_wptr = mp->b_wptr;
21048 				pld_rptr = mp->b_cont->b_rptr;
21049 				pld_wptr = mp->b_cont->b_wptr;
21050 
21051 				if (af == AF_INET) {
21052 					DTRACE_PROBE4(
21053 					    ip4__physical__out__start,
21054 					    ill_t *, NULL,
21055 					    ill_t *, ill,
21056 					    ipha_t *, ipha,
21057 					    mblk_t *, mp);
21058 					FW_HOOKS(
21059 					    ipst->ips_ip4_physical_out_event,
21060 					    ipst->ips_ipv4firewall_physical_out,
21061 					    NULL, ill, ipha, mp, mp, 0, ipst);
21062 					DTRACE_PROBE1(
21063 					    ip4__physical__out__end,
21064 					    mblk_t *, mp);
21065 				} else {
21066 					DTRACE_PROBE4(
21067 					    ip6__physical__out_start,
21068 					    ill_t *, NULL,
21069 					    ill_t *, ill,
21070 					    ip6_t *, ip6h,
21071 					    mblk_t *, mp);
21072 					FW_HOOKS6(
21073 					    ipst->ips_ip6_physical_out_event,
21074 					    ipst->ips_ipv6firewall_physical_out,
21075 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21076 					DTRACE_PROBE1(
21077 					    ip6__physical__out__end,
21078 					    mblk_t *, mp);
21079 				}
21080 
21081 				if (mp == NULL ||
21082 				    (mp1 = mp->b_cont) == NULL ||
21083 				    mp->b_rptr != hdr_rptr ||
21084 				    mp->b_wptr != hdr_wptr ||
21085 				    mp1->b_rptr != pld_rptr ||
21086 				    mp1->b_wptr != pld_wptr ||
21087 				    mp1->b_cont != NULL) {
21088 					/*
21089 					 * We abandon multidata processing and
21090 					 * return to the normal path, either
21091 					 * when a packet is blocked, or when
21092 					 * the boundaries of header buffer or
21093 					 * payload buffer have been changed by
21094 					 * FW_HOOKS[6].
21095 					 */
21096 					if (mp != NULL)
21097 						freemsg(mp);
21098 					goto legacy_send;
21099 				}
21100 				/* Finished with the pseudo packet */
21101 				freemsg(mp);
21102 			}
21103 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21104 			    ill, ipha, ip6h);
21105 			/* advance header offset */
21106 			cur_hdr_off += hdr_frag_sz;
21107 
21108 			obbytes += tcp->tcp_last_sent_len;
21109 			++obsegs;
21110 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21111 		    *tail_unsent > 0);
21112 
21113 		if ((*xmit_tail)->b_next == NULL) {
21114 			/*
21115 			 * Store the lbolt used for RTT estimation. We can only
21116 			 * record one timestamp per mblk so we do it when we
21117 			 * reach the end of the payload buffer. Also we only
21118 			 * take a new timestamp sample when the previous timed
21119 			 * data from the same mblk has been ack'ed.
21120 			 */
21121 			(*xmit_tail)->b_prev = local_time;
21122 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21123 		}
21124 
21125 		ASSERT(*tail_unsent >= 0);
21126 		if (*tail_unsent > 0) {
21127 			/*
21128 			 * We got here because we broke out of the above
21129 			 * loop due to of one of the following cases:
21130 			 *
21131 			 *   1. len < adjusted MSS (i.e. small),
21132 			 *   2. Sender SWS avoidance,
21133 			 *   3. max_pld is zero.
21134 			 *
21135 			 * We are done for this Multidata, so trim our
21136 			 * last payload buffer (if any) accordingly.
21137 			 */
21138 			if (md_pbuf != NULL)
21139 				md_pbuf->b_wptr -= *tail_unsent;
21140 		} else if (*usable > 0) {
21141 			*xmit_tail = (*xmit_tail)->b_cont;
21142 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21143 			    (uintptr_t)INT_MAX);
21144 			*tail_unsent = (int)MBLKL(*xmit_tail);
21145 			add_buffer = B_TRUE;
21146 		}
21147 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21148 	    (tcp_mdt_chain || max_pld > 0));
21149 
21150 	if (md_mp_head != NULL) {
21151 		/* send everything down */
21152 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21153 		    &rconfirm);
21154 	}
21155 
21156 #undef PREP_NEW_MULTIDATA
21157 #undef PREP_NEW_PBUF
21158 #undef IPVER
21159 
21160 	IRE_REFRELE(ire);
21161 	return (0);
21162 }
21163 
21164 /*
21165  * A wrapper function for sending one or more Multidata messages down to
21166  * the module below ip; this routine does not release the reference of the
21167  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21168  */
21169 static void
21170 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21171     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21172 {
21173 	uint64_t delta;
21174 	nce_t *nce;
21175 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21176 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21177 
21178 	ASSERT(ire != NULL && ill != NULL);
21179 	ASSERT(ire->ire_stq != NULL);
21180 	ASSERT(md_mp_head != NULL);
21181 	ASSERT(rconfirm != NULL);
21182 
21183 	/* adjust MIBs and IRE timestamp */
21184 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21185 	tcp->tcp_obsegs += obsegs;
21186 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21187 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21188 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21189 
21190 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21191 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21192 	} else {
21193 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21194 	}
21195 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21196 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21197 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21198 
21199 	ire->ire_ob_pkt_count += obsegs;
21200 	if (ire->ire_ipif != NULL)
21201 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21202 	ire->ire_last_used_time = lbolt;
21203 
21204 	if (ipst->ips_ipobs_enabled) {
21205 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21206 		pdesc_t *dl_pkt;
21207 		pdescinfo_t pinfo;
21208 		mblk_t *nmp;
21209 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21210 
21211 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21212 		    (dl_pkt != NULL);
21213 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21214 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21215 				continue;
21216 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21217 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21218 			freemsg(nmp);
21219 		}
21220 	}
21221 
21222 	/* send it down */
21223 	putnext(ire->ire_stq, md_mp_head);
21224 
21225 	/* we're done for TCP/IPv4 */
21226 	if (tcp->tcp_ipversion == IPV4_VERSION)
21227 		return;
21228 
21229 	nce = ire->ire_nce;
21230 
21231 	ASSERT(nce != NULL);
21232 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21233 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21234 
21235 	/* reachability confirmation? */
21236 	if (*rconfirm) {
21237 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21238 		if (nce->nce_state != ND_REACHABLE) {
21239 			mutex_enter(&nce->nce_lock);
21240 			nce->nce_state = ND_REACHABLE;
21241 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21242 			mutex_exit(&nce->nce_lock);
21243 			(void) untimeout(nce->nce_timeout_id);
21244 			if (ip_debug > 2) {
21245 				/* ip1dbg */
21246 				pr_addr_dbg("tcp_multisend_data: state "
21247 				    "for %s changed to REACHABLE\n",
21248 				    AF_INET6, &ire->ire_addr_v6);
21249 			}
21250 		}
21251 		/* reset transport reachability confirmation */
21252 		*rconfirm = B_FALSE;
21253 	}
21254 
21255 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21256 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21257 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21258 
21259 	if (delta > (uint64_t)ill->ill_reachable_time) {
21260 		mutex_enter(&nce->nce_lock);
21261 		switch (nce->nce_state) {
21262 		case ND_REACHABLE:
21263 		case ND_STALE:
21264 			/*
21265 			 * ND_REACHABLE is identical to ND_STALE in this
21266 			 * specific case. If reachable time has expired for
21267 			 * this neighbor (delta is greater than reachable
21268 			 * time), conceptually, the neighbor cache is no
21269 			 * longer in REACHABLE state, but already in STALE
21270 			 * state.  So the correct transition here is to
21271 			 * ND_DELAY.
21272 			 */
21273 			nce->nce_state = ND_DELAY;
21274 			mutex_exit(&nce->nce_lock);
21275 			NDP_RESTART_TIMER(nce,
21276 			    ipst->ips_delay_first_probe_time);
21277 			if (ip_debug > 3) {
21278 				/* ip2dbg */
21279 				pr_addr_dbg("tcp_multisend_data: state "
21280 				    "for %s changed to DELAY\n",
21281 				    AF_INET6, &ire->ire_addr_v6);
21282 			}
21283 			break;
21284 		case ND_DELAY:
21285 		case ND_PROBE:
21286 			mutex_exit(&nce->nce_lock);
21287 			/* Timers have already started */
21288 			break;
21289 		case ND_UNREACHABLE:
21290 			/*
21291 			 * ndp timer has detected that this nce is
21292 			 * unreachable and initiated deleting this nce
21293 			 * and all its associated IREs. This is a race
21294 			 * where we found the ire before it was deleted
21295 			 * and have just sent out a packet using this
21296 			 * unreachable nce.
21297 			 */
21298 			mutex_exit(&nce->nce_lock);
21299 			break;
21300 		default:
21301 			ASSERT(0);
21302 		}
21303 	}
21304 }
21305 
21306 /*
21307  * Derived from tcp_send_data().
21308  */
21309 static void
21310 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21311     int num_lso_seg)
21312 {
21313 	ipha_t		*ipha;
21314 	mblk_t		*ire_fp_mp;
21315 	uint_t		ire_fp_mp_len;
21316 	uint32_t	hcksum_txflags = 0;
21317 	ipaddr_t	src;
21318 	ipaddr_t	dst;
21319 	uint32_t	cksum;
21320 	uint16_t	*up;
21321 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21322 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21323 
21324 	ASSERT(DB_TYPE(mp) == M_DATA);
21325 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21326 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21327 	ASSERT(tcp->tcp_connp != NULL);
21328 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21329 
21330 	ipha = (ipha_t *)mp->b_rptr;
21331 	src = ipha->ipha_src;
21332 	dst = ipha->ipha_dst;
21333 
21334 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21335 
21336 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21337 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21338 	    num_lso_seg);
21339 #ifndef _BIG_ENDIAN
21340 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21341 #endif
21342 	if (tcp->tcp_snd_zcopy_aware) {
21343 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21344 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21345 			mp = tcp_zcopy_disable(tcp, mp);
21346 	}
21347 
21348 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21349 		ASSERT(ill->ill_hcksum_capab != NULL);
21350 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21351 	}
21352 
21353 	/*
21354 	 * Since the TCP checksum should be recalculated by h/w, we can just
21355 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21356 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21357 	 * The partial pseudo-header excludes TCP length, that was calculated
21358 	 * in tcp_send(), so to zero *up before further processing.
21359 	 */
21360 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21361 
21362 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21363 	*up = 0;
21364 
21365 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21366 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21367 
21368 	/*
21369 	 * Append LSO flags and mss to the mp.
21370 	 */
21371 	lso_info_set(mp, mss, HW_LSO);
21372 
21373 	ipha->ipha_fragment_offset_and_flags |=
21374 	    (uint32_t)htons(ire->ire_frag_flag);
21375 
21376 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21377 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21378 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21379 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21380 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21381 
21382 	UPDATE_OB_PKT_COUNT(ire);
21383 	ire->ire_last_used_time = lbolt;
21384 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21385 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21386 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21387 	    ntohs(ipha->ipha_length));
21388 
21389 	DTRACE_PROBE4(ip4__physical__out__start,
21390 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
21391 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
21392 	    ipst->ips_ipv4firewall_physical_out, NULL,
21393 	    ill, ipha, mp, mp, 0, ipst);
21394 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21395 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
21396 
21397 	if (mp != NULL) {
21398 		if (ipst->ips_ipobs_enabled) {
21399 			zoneid_t szone;
21400 
21401 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
21402 			    ipst, ALL_ZONES);
21403 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21404 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
21405 		}
21406 
21407 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0);
21408 	}
21409 }
21410 
21411 /*
21412  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21413  * scheme, and returns one of the following:
21414  *
21415  * -1 = failed allocation.
21416  *  0 = success; burst count reached, or usable send window is too small,
21417  *      and that we'd rather wait until later before sending again.
21418  *  1 = success; we are called from tcp_multisend(), and both usable send
21419  *      window and tail_unsent are greater than the MDT threshold, and thus
21420  *      Multidata Transmit should be used instead.
21421  */
21422 static int
21423 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21424     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21425     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21426     const int mdt_thres)
21427 {
21428 	int num_burst_seg = tcp->tcp_snd_burst;
21429 	ire_t		*ire = NULL;
21430 	ill_t		*ill = NULL;
21431 	mblk_t		*ire_fp_mp = NULL;
21432 	uint_t		ire_fp_mp_len = 0;
21433 	int		num_lso_seg = 1;
21434 	uint_t		lso_usable;
21435 	boolean_t	do_lso_send = B_FALSE;
21436 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21437 
21438 	/*
21439 	 * Check LSO capability before any further work. And the similar check
21440 	 * need to be done in for(;;) loop.
21441 	 * LSO will be deployed when therer is more than one mss of available
21442 	 * data and a burst transmission is allowed.
21443 	 */
21444 	if (tcp->tcp_lso &&
21445 	    (tcp->tcp_valid_bits == 0 ||
21446 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21447 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21448 		/*
21449 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21450 		 */
21451 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21452 			/*
21453 			 * Enable LSO with this transmission.
21454 			 * Since IRE has been hold in
21455 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21456 			 * should be called before return.
21457 			 */
21458 			do_lso_send = B_TRUE;
21459 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21460 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21461 			/* Round up to multiple of 4 */
21462 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21463 		} else {
21464 			do_lso_send = B_FALSE;
21465 			ill = NULL;
21466 		}
21467 	}
21468 
21469 	for (;;) {
21470 		struct datab	*db;
21471 		tcph_t		*tcph;
21472 		uint32_t	sum;
21473 		mblk_t		*mp, *mp1;
21474 		uchar_t		*rptr;
21475 		int		len;
21476 
21477 		/*
21478 		 * If we're called by tcp_multisend(), and the amount of
21479 		 * sendable data as well as the size of current xmit_tail
21480 		 * is beyond the MDT threshold, return to the caller and
21481 		 * let the large data transmit be done using MDT.
21482 		 */
21483 		if (*usable > 0 && *usable > mdt_thres &&
21484 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21485 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21486 			ASSERT(tcp->tcp_mdt);
21487 			return (1);	/* success; do large send */
21488 		}
21489 
21490 		if (num_burst_seg == 0)
21491 			break;		/* success; burst count reached */
21492 
21493 		/*
21494 		 * Calculate the maximum payload length we can send in *one*
21495 		 * time.
21496 		 */
21497 		if (do_lso_send) {
21498 			/*
21499 			 * Check whether need to do LSO any more.
21500 			 */
21501 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21502 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21503 				lso_usable = MIN(lso_usable,
21504 				    num_burst_seg * mss);
21505 
21506 				num_lso_seg = lso_usable / mss;
21507 				if (lso_usable % mss) {
21508 					num_lso_seg++;
21509 					tcp->tcp_last_sent_len = (ushort_t)
21510 					    (lso_usable % mss);
21511 				} else {
21512 					tcp->tcp_last_sent_len = (ushort_t)mss;
21513 				}
21514 			} else {
21515 				do_lso_send = B_FALSE;
21516 				num_lso_seg = 1;
21517 				lso_usable = mss;
21518 			}
21519 		}
21520 
21521 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21522 
21523 		/*
21524 		 * Adjust num_burst_seg here.
21525 		 */
21526 		num_burst_seg -= num_lso_seg;
21527 
21528 		len = mss;
21529 		if (len > *usable) {
21530 			ASSERT(do_lso_send == B_FALSE);
21531 
21532 			len = *usable;
21533 			if (len <= 0) {
21534 				/* Terminate the loop */
21535 				break;	/* success; too small */
21536 			}
21537 			/*
21538 			 * Sender silly-window avoidance.
21539 			 * Ignore this if we are going to send a
21540 			 * zero window probe out.
21541 			 *
21542 			 * TODO: force data into microscopic window?
21543 			 *	==> (!pushed || (unsent > usable))
21544 			 */
21545 			if (len < (tcp->tcp_max_swnd >> 1) &&
21546 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21547 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21548 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21549 				/*
21550 				 * If the retransmit timer is not running
21551 				 * we start it so that we will retransmit
21552 				 * in the case when the the receiver has
21553 				 * decremented the window.
21554 				 */
21555 				if (*snxt == tcp->tcp_snxt &&
21556 				    *snxt == tcp->tcp_suna) {
21557 					/*
21558 					 * We are not supposed to send
21559 					 * anything.  So let's wait a little
21560 					 * bit longer before breaking SWS
21561 					 * avoidance.
21562 					 *
21563 					 * What should the value be?
21564 					 * Suggestion: MAX(init rexmit time,
21565 					 * tcp->tcp_rto)
21566 					 */
21567 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21568 				}
21569 				break;	/* success; too small */
21570 			}
21571 		}
21572 
21573 		tcph = tcp->tcp_tcph;
21574 
21575 		/*
21576 		 * The reason to adjust len here is that we need to set flags
21577 		 * and calculate checksum.
21578 		 */
21579 		if (do_lso_send)
21580 			len = lso_usable;
21581 
21582 		*usable -= len; /* Approximate - can be adjusted later */
21583 		if (*usable > 0)
21584 			tcph->th_flags[0] = TH_ACK;
21585 		else
21586 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21587 
21588 		/*
21589 		 * Prime pump for IP's checksumming on our behalf
21590 		 * Include the adjustment for a source route if any.
21591 		 */
21592 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21593 		sum = (sum >> 16) + (sum & 0xFFFF);
21594 		U16_TO_ABE16(sum, tcph->th_sum);
21595 
21596 		U32_TO_ABE32(*snxt, tcph->th_seq);
21597 
21598 		/*
21599 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21600 		 * set.  For the case when TCP_FSS_VALID is the only valid
21601 		 * bit (normal active close), branch off only when we think
21602 		 * that the FIN flag needs to be set.  Note for this case,
21603 		 * that (snxt + len) may not reflect the actual seg_len,
21604 		 * as len may be further reduced in tcp_xmit_mp().  If len
21605 		 * gets modified, we will end up here again.
21606 		 */
21607 		if (tcp->tcp_valid_bits != 0 &&
21608 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21609 		    ((*snxt + len) == tcp->tcp_fss))) {
21610 			uchar_t		*prev_rptr;
21611 			uint32_t	prev_snxt = tcp->tcp_snxt;
21612 
21613 			if (*tail_unsent == 0) {
21614 				ASSERT((*xmit_tail)->b_cont != NULL);
21615 				*xmit_tail = (*xmit_tail)->b_cont;
21616 				prev_rptr = (*xmit_tail)->b_rptr;
21617 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21618 				    (*xmit_tail)->b_rptr);
21619 			} else {
21620 				prev_rptr = (*xmit_tail)->b_rptr;
21621 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21622 				    *tail_unsent;
21623 			}
21624 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21625 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21626 			/* Restore tcp_snxt so we get amount sent right. */
21627 			tcp->tcp_snxt = prev_snxt;
21628 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21629 				/*
21630 				 * If the previous timestamp is still in use,
21631 				 * don't stomp on it.
21632 				 */
21633 				if ((*xmit_tail)->b_next == NULL) {
21634 					(*xmit_tail)->b_prev = local_time;
21635 					(*xmit_tail)->b_next =
21636 					    (mblk_t *)(uintptr_t)(*snxt);
21637 				}
21638 			} else
21639 				(*xmit_tail)->b_rptr = prev_rptr;
21640 
21641 			if (mp == NULL) {
21642 				if (ire != NULL)
21643 					IRE_REFRELE(ire);
21644 				return (-1);
21645 			}
21646 			mp1 = mp->b_cont;
21647 
21648 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21649 				tcp->tcp_last_sent_len = (ushort_t)len;
21650 			while (mp1->b_cont) {
21651 				*xmit_tail = (*xmit_tail)->b_cont;
21652 				(*xmit_tail)->b_prev = local_time;
21653 				(*xmit_tail)->b_next =
21654 				    (mblk_t *)(uintptr_t)(*snxt);
21655 				mp1 = mp1->b_cont;
21656 			}
21657 			*snxt += len;
21658 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21659 			BUMP_LOCAL(tcp->tcp_obsegs);
21660 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21661 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21662 			tcp_send_data(tcp, q, mp);
21663 			continue;
21664 		}
21665 
21666 		*snxt += len;	/* Adjust later if we don't send all of len */
21667 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21668 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21669 
21670 		if (*tail_unsent) {
21671 			/* Are the bytes above us in flight? */
21672 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21673 			if (rptr != (*xmit_tail)->b_rptr) {
21674 				*tail_unsent -= len;
21675 				if (len <= mss) /* LSO is unusable */
21676 					tcp->tcp_last_sent_len = (ushort_t)len;
21677 				len += tcp_hdr_len;
21678 				if (tcp->tcp_ipversion == IPV4_VERSION)
21679 					tcp->tcp_ipha->ipha_length = htons(len);
21680 				else
21681 					tcp->tcp_ip6h->ip6_plen =
21682 					    htons(len -
21683 					    ((char *)&tcp->tcp_ip6h[1] -
21684 					    tcp->tcp_iphc));
21685 				mp = dupb(*xmit_tail);
21686 				if (mp == NULL) {
21687 					if (ire != NULL)
21688 						IRE_REFRELE(ire);
21689 					return (-1);	/* out_of_mem */
21690 				}
21691 				mp->b_rptr = rptr;
21692 				/*
21693 				 * If the old timestamp is no longer in use,
21694 				 * sample a new timestamp now.
21695 				 */
21696 				if ((*xmit_tail)->b_next == NULL) {
21697 					(*xmit_tail)->b_prev = local_time;
21698 					(*xmit_tail)->b_next =
21699 					    (mblk_t *)(uintptr_t)(*snxt-len);
21700 				}
21701 				goto must_alloc;
21702 			}
21703 		} else {
21704 			*xmit_tail = (*xmit_tail)->b_cont;
21705 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21706 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21707 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21708 			    (*xmit_tail)->b_rptr);
21709 		}
21710 
21711 		(*xmit_tail)->b_prev = local_time;
21712 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21713 
21714 		*tail_unsent -= len;
21715 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21716 			tcp->tcp_last_sent_len = (ushort_t)len;
21717 
21718 		len += tcp_hdr_len;
21719 		if (tcp->tcp_ipversion == IPV4_VERSION)
21720 			tcp->tcp_ipha->ipha_length = htons(len);
21721 		else
21722 			tcp->tcp_ip6h->ip6_plen = htons(len -
21723 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21724 
21725 		mp = dupb(*xmit_tail);
21726 		if (mp == NULL) {
21727 			if (ire != NULL)
21728 				IRE_REFRELE(ire);
21729 			return (-1);	/* out_of_mem */
21730 		}
21731 
21732 		len = tcp_hdr_len;
21733 		/*
21734 		 * There are four reasons to allocate a new hdr mblk:
21735 		 *  1) The bytes above us are in use by another packet
21736 		 *  2) We don't have good alignment
21737 		 *  3) The mblk is being shared
21738 		 *  4) We don't have enough room for a header
21739 		 */
21740 		rptr = mp->b_rptr - len;
21741 		if (!OK_32PTR(rptr) ||
21742 		    ((db = mp->b_datap), db->db_ref != 2) ||
21743 		    rptr < db->db_base + ire_fp_mp_len) {
21744 			/* NOTE: we assume allocb returns an OK_32PTR */
21745 
21746 		must_alloc:;
21747 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21748 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21749 			if (mp1 == NULL) {
21750 				freemsg(mp);
21751 				if (ire != NULL)
21752 					IRE_REFRELE(ire);
21753 				return (-1);	/* out_of_mem */
21754 			}
21755 			mp1->b_cont = mp;
21756 			mp = mp1;
21757 			/* Leave room for Link Level header */
21758 			len = tcp_hdr_len;
21759 			rptr =
21760 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21761 			mp->b_wptr = &rptr[len];
21762 		}
21763 
21764 		/*
21765 		 * Fill in the header using the template header, and add
21766 		 * options such as time-stamp, ECN and/or SACK, as needed.
21767 		 */
21768 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21769 
21770 		mp->b_rptr = rptr;
21771 
21772 		if (*tail_unsent) {
21773 			int spill = *tail_unsent;
21774 
21775 			mp1 = mp->b_cont;
21776 			if (mp1 == NULL)
21777 				mp1 = mp;
21778 
21779 			/*
21780 			 * If we're a little short, tack on more mblks until
21781 			 * there is no more spillover.
21782 			 */
21783 			while (spill < 0) {
21784 				mblk_t *nmp;
21785 				int nmpsz;
21786 
21787 				nmp = (*xmit_tail)->b_cont;
21788 				nmpsz = MBLKL(nmp);
21789 
21790 				/*
21791 				 * Excess data in mblk; can we split it?
21792 				 * If MDT is enabled for the connection,
21793 				 * keep on splitting as this is a transient
21794 				 * send path.
21795 				 */
21796 				if (!do_lso_send && !tcp->tcp_mdt &&
21797 				    (spill + nmpsz > 0)) {
21798 					/*
21799 					 * Don't split if stream head was
21800 					 * told to break up larger writes
21801 					 * into smaller ones.
21802 					 */
21803 					if (tcp->tcp_maxpsz > 0)
21804 						break;
21805 
21806 					/*
21807 					 * Next mblk is less than SMSS/2
21808 					 * rounded up to nearest 64-byte;
21809 					 * let it get sent as part of the
21810 					 * next segment.
21811 					 */
21812 					if (tcp->tcp_localnet &&
21813 					    !tcp->tcp_cork &&
21814 					    (nmpsz < roundup((mss >> 1), 64)))
21815 						break;
21816 				}
21817 
21818 				*xmit_tail = nmp;
21819 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21820 				/* Stash for rtt use later */
21821 				(*xmit_tail)->b_prev = local_time;
21822 				(*xmit_tail)->b_next =
21823 				    (mblk_t *)(uintptr_t)(*snxt - len);
21824 				mp1->b_cont = dupb(*xmit_tail);
21825 				mp1 = mp1->b_cont;
21826 
21827 				spill += nmpsz;
21828 				if (mp1 == NULL) {
21829 					*tail_unsent = spill;
21830 					freemsg(mp);
21831 					if (ire != NULL)
21832 						IRE_REFRELE(ire);
21833 					return (-1);	/* out_of_mem */
21834 				}
21835 			}
21836 
21837 			/* Trim back any surplus on the last mblk */
21838 			if (spill >= 0) {
21839 				mp1->b_wptr -= spill;
21840 				*tail_unsent = spill;
21841 			} else {
21842 				/*
21843 				 * We did not send everything we could in
21844 				 * order to remain within the b_cont limit.
21845 				 */
21846 				*usable -= spill;
21847 				*snxt += spill;
21848 				tcp->tcp_last_sent_len += spill;
21849 				UPDATE_MIB(&tcps->tcps_mib,
21850 				    tcpOutDataBytes, spill);
21851 				/*
21852 				 * Adjust the checksum
21853 				 */
21854 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21855 				sum += spill;
21856 				sum = (sum >> 16) + (sum & 0xFFFF);
21857 				U16_TO_ABE16(sum, tcph->th_sum);
21858 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21859 					sum = ntohs(
21860 					    ((ipha_t *)rptr)->ipha_length) +
21861 					    spill;
21862 					((ipha_t *)rptr)->ipha_length =
21863 					    htons(sum);
21864 				} else {
21865 					sum = ntohs(
21866 					    ((ip6_t *)rptr)->ip6_plen) +
21867 					    spill;
21868 					((ip6_t *)rptr)->ip6_plen =
21869 					    htons(sum);
21870 				}
21871 				*tail_unsent = 0;
21872 			}
21873 		}
21874 		if (tcp->tcp_ip_forward_progress) {
21875 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21876 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21877 			tcp->tcp_ip_forward_progress = B_FALSE;
21878 		}
21879 
21880 		if (do_lso_send) {
21881 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21882 			    num_lso_seg);
21883 			tcp->tcp_obsegs += num_lso_seg;
21884 
21885 			TCP_STAT(tcps, tcp_lso_times);
21886 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21887 		} else {
21888 			tcp_send_data(tcp, q, mp);
21889 			BUMP_LOCAL(tcp->tcp_obsegs);
21890 		}
21891 	}
21892 
21893 	if (ire != NULL)
21894 		IRE_REFRELE(ire);
21895 	return (0);
21896 }
21897 
21898 /* Unlink and return any mblk that looks like it contains a MDT info */
21899 static mblk_t *
21900 tcp_mdt_info_mp(mblk_t *mp)
21901 {
21902 	mblk_t	*prev_mp;
21903 
21904 	for (;;) {
21905 		prev_mp = mp;
21906 		/* no more to process? */
21907 		if ((mp = mp->b_cont) == NULL)
21908 			break;
21909 
21910 		switch (DB_TYPE(mp)) {
21911 		case M_CTL:
21912 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21913 				continue;
21914 			ASSERT(prev_mp != NULL);
21915 			prev_mp->b_cont = mp->b_cont;
21916 			mp->b_cont = NULL;
21917 			return (mp);
21918 		default:
21919 			break;
21920 		}
21921 	}
21922 	return (mp);
21923 }
21924 
21925 /* MDT info update routine, called when IP notifies us about MDT */
21926 static void
21927 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21928 {
21929 	boolean_t prev_state;
21930 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21931 
21932 	/*
21933 	 * IP is telling us to abort MDT on this connection?  We know
21934 	 * this because the capability is only turned off when IP
21935 	 * encounters some pathological cases, e.g. link-layer change
21936 	 * where the new driver doesn't support MDT, or in situation
21937 	 * where MDT usage on the link-layer has been switched off.
21938 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21939 	 * if the link-layer doesn't support MDT, and if it does, it
21940 	 * will indicate that the feature is to be turned on.
21941 	 */
21942 	prev_state = tcp->tcp_mdt;
21943 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21944 	if (!tcp->tcp_mdt && !first) {
21945 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21946 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21947 		    (void *)tcp->tcp_connp));
21948 	}
21949 
21950 	/*
21951 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21952 	 * so disable MDT otherwise.  The checks are done here
21953 	 * and in tcp_wput_data().
21954 	 */
21955 	if (tcp->tcp_mdt &&
21956 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21957 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21958 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21959 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21960 		tcp->tcp_mdt = B_FALSE;
21961 
21962 	if (tcp->tcp_mdt) {
21963 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21964 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21965 			    "version (%d), expected version is %d",
21966 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21967 			tcp->tcp_mdt = B_FALSE;
21968 			return;
21969 		}
21970 
21971 		/*
21972 		 * We need the driver to be able to handle at least three
21973 		 * spans per packet in order for tcp MDT to be utilized.
21974 		 * The first is for the header portion, while the rest are
21975 		 * needed to handle a packet that straddles across two
21976 		 * virtually non-contiguous buffers; a typical tcp packet
21977 		 * therefore consists of only two spans.  Note that we take
21978 		 * a zero as "don't care".
21979 		 */
21980 		if (mdt_capab->ill_mdt_span_limit > 0 &&
21981 		    mdt_capab->ill_mdt_span_limit < 3) {
21982 			tcp->tcp_mdt = B_FALSE;
21983 			return;
21984 		}
21985 
21986 		/* a zero means driver wants default value */
21987 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
21988 		    tcps->tcps_mdt_max_pbufs);
21989 		if (tcp->tcp_mdt_max_pld == 0)
21990 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
21991 
21992 		/* ensure 32-bit alignment */
21993 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
21994 		    mdt_capab->ill_mdt_hdr_head), 4);
21995 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
21996 		    mdt_capab->ill_mdt_hdr_tail), 4);
21997 
21998 		if (!first && !prev_state) {
21999 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
22000 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
22001 			    (void *)tcp->tcp_connp));
22002 		}
22003 	}
22004 }
22005 
22006 /* Unlink and return any mblk that looks like it contains a LSO info */
22007 static mblk_t *
22008 tcp_lso_info_mp(mblk_t *mp)
22009 {
22010 	mblk_t	*prev_mp;
22011 
22012 	for (;;) {
22013 		prev_mp = mp;
22014 		/* no more to process? */
22015 		if ((mp = mp->b_cont) == NULL)
22016 			break;
22017 
22018 		switch (DB_TYPE(mp)) {
22019 		case M_CTL:
22020 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
22021 				continue;
22022 			ASSERT(prev_mp != NULL);
22023 			prev_mp->b_cont = mp->b_cont;
22024 			mp->b_cont = NULL;
22025 			return (mp);
22026 		default:
22027 			break;
22028 		}
22029 	}
22030 
22031 	return (mp);
22032 }
22033 
22034 /* LSO info update routine, called when IP notifies us about LSO */
22035 static void
22036 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
22037 {
22038 	tcp_stack_t *tcps = tcp->tcp_tcps;
22039 
22040 	/*
22041 	 * IP is telling us to abort LSO on this connection?  We know
22042 	 * this because the capability is only turned off when IP
22043 	 * encounters some pathological cases, e.g. link-layer change
22044 	 * where the new NIC/driver doesn't support LSO, or in situation
22045 	 * where LSO usage on the link-layer has been switched off.
22046 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
22047 	 * if the link-layer doesn't support LSO, and if it does, it
22048 	 * will indicate that the feature is to be turned on.
22049 	 */
22050 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
22051 	TCP_STAT(tcps, tcp_lso_enabled);
22052 
22053 	/*
22054 	 * We currently only support LSO on simple TCP/IPv4,
22055 	 * so disable LSO otherwise.  The checks are done here
22056 	 * and in tcp_wput_data().
22057 	 */
22058 	if (tcp->tcp_lso &&
22059 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22060 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22061 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
22062 		tcp->tcp_lso = B_FALSE;
22063 		TCP_STAT(tcps, tcp_lso_disabled);
22064 	} else {
22065 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
22066 		    lso_capab->ill_lso_max);
22067 	}
22068 }
22069 
22070 static void
22071 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22072 {
22073 	conn_t *connp = tcp->tcp_connp;
22074 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22075 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22076 
22077 	ASSERT(ire != NULL);
22078 
22079 	/*
22080 	 * We may be in the fastpath here, and although we essentially do
22081 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22082 	 * we try to keep things as brief as possible.  After all, these
22083 	 * are only best-effort checks, and we do more thorough ones prior
22084 	 * to calling tcp_send()/tcp_multisend().
22085 	 */
22086 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22087 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22088 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22089 	    !(ire->ire_flags & RTF_MULTIRT) &&
22090 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22091 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22092 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22093 			/* Cache the result */
22094 			connp->conn_lso_ok = B_TRUE;
22095 
22096 			ASSERT(ill->ill_lso_capab != NULL);
22097 			if (!ill->ill_lso_capab->ill_lso_on) {
22098 				ill->ill_lso_capab->ill_lso_on = 1;
22099 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22100 				    "LSO for interface %s\n", (void *)connp,
22101 				    ill->ill_name));
22102 			}
22103 			tcp_lso_update(tcp, ill->ill_lso_capab);
22104 		} else if (ipst->ips_ip_multidata_outbound &&
22105 		    ILL_MDT_CAPABLE(ill)) {
22106 			/* Cache the result */
22107 			connp->conn_mdt_ok = B_TRUE;
22108 
22109 			ASSERT(ill->ill_mdt_capab != NULL);
22110 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22111 				ill->ill_mdt_capab->ill_mdt_on = 1;
22112 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22113 				    "MDT for interface %s\n", (void *)connp,
22114 				    ill->ill_name));
22115 			}
22116 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22117 		}
22118 	}
22119 
22120 	/*
22121 	 * The goal is to reduce the number of generated tcp segments by
22122 	 * setting the maxpsz multiplier to 0; this will have an affect on
22123 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22124 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22125 	 * of outbound segments and incoming ACKs, thus allowing for better
22126 	 * network and system performance.  In contrast the legacy behavior
22127 	 * may result in sending less than SMSS size, because the last mblk
22128 	 * for some packets may have more data than needed to make up SMSS,
22129 	 * and the legacy code refused to "split" it.
22130 	 *
22131 	 * We apply the new behavior on following situations:
22132 	 *
22133 	 *   1) Loopback connections,
22134 	 *   2) Connections in which the remote peer is not on local subnet,
22135 	 *   3) Local subnet connections over the bge interface (see below).
22136 	 *
22137 	 * Ideally, we would like this behavior to apply for interfaces other
22138 	 * than bge.  However, doing so would negatively impact drivers which
22139 	 * perform dynamic mapping and unmapping of DMA resources, which are
22140 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22141 	 * packet will be generated by tcp).  The bge driver does not suffer
22142 	 * from this, as it copies the mblks into pre-mapped buffers, and
22143 	 * therefore does not require more I/O resources than before.
22144 	 *
22145 	 * Otherwise, this behavior is present on all network interfaces when
22146 	 * the destination endpoint is non-local, since reducing the number
22147 	 * of packets in general is good for the network.
22148 	 *
22149 	 * TODO We need to remove this hard-coded conditional for bge once
22150 	 *	a better "self-tuning" mechanism, or a way to comprehend
22151 	 *	the driver transmit strategy is devised.  Until the solution
22152 	 *	is found and well understood, we live with this hack.
22153 	 */
22154 	if (!tcp_static_maxpsz &&
22155 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22156 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22157 		/* override the default value */
22158 		tcp->tcp_maxpsz = 0;
22159 
22160 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22161 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22162 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22163 	}
22164 
22165 	/* set the stream head parameters accordingly */
22166 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22167 }
22168 
22169 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22170 static void
22171 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22172 {
22173 	uchar_t	fval = *mp->b_rptr;
22174 	mblk_t	*tail;
22175 	queue_t	*q = tcp->tcp_wq;
22176 
22177 	/* TODO: How should flush interact with urgent data? */
22178 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22179 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22180 		/*
22181 		 * Flush only data that has not yet been put on the wire.  If
22182 		 * we flush data that we have already transmitted, life, as we
22183 		 * know it, may come to an end.
22184 		 */
22185 		tail = tcp->tcp_xmit_tail;
22186 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22187 		tcp->tcp_xmit_tail_unsent = 0;
22188 		tcp->tcp_unsent = 0;
22189 		if (tail->b_wptr != tail->b_rptr)
22190 			tail = tail->b_cont;
22191 		if (tail) {
22192 			mblk_t **excess = &tcp->tcp_xmit_head;
22193 			for (;;) {
22194 				mblk_t *mp1 = *excess;
22195 				if (mp1 == tail)
22196 					break;
22197 				tcp->tcp_xmit_tail = mp1;
22198 				tcp->tcp_xmit_last = mp1;
22199 				excess = &mp1->b_cont;
22200 			}
22201 			*excess = NULL;
22202 			tcp_close_mpp(&tail);
22203 			if (tcp->tcp_snd_zcopy_aware)
22204 				tcp_zcopy_notify(tcp);
22205 		}
22206 		/*
22207 		 * We have no unsent data, so unsent must be less than
22208 		 * tcp_xmit_lowater, so re-enable flow.
22209 		 */
22210 		mutex_enter(&tcp->tcp_non_sq_lock);
22211 		if (tcp->tcp_flow_stopped) {
22212 			tcp_clrqfull(tcp);
22213 		}
22214 		mutex_exit(&tcp->tcp_non_sq_lock);
22215 	}
22216 	/*
22217 	 * TODO: you can't just flush these, you have to increase rwnd for one
22218 	 * thing.  For another, how should urgent data interact?
22219 	 */
22220 	if (fval & FLUSHR) {
22221 		*mp->b_rptr = fval & ~FLUSHW;
22222 		/* XXX */
22223 		qreply(q, mp);
22224 		return;
22225 	}
22226 	freemsg(mp);
22227 }
22228 
22229 /*
22230  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22231  * messages.
22232  */
22233 static void
22234 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22235 {
22236 	mblk_t	*mp1;
22237 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22238 	STRUCT_HANDLE(strbuf, sb);
22239 	queue_t *q = tcp->tcp_wq;
22240 	int	error;
22241 	uint_t	addrlen;
22242 
22243 	/* Make sure it is one of ours. */
22244 	switch (iocp->ioc_cmd) {
22245 	case TI_GETMYNAME:
22246 	case TI_GETPEERNAME:
22247 		break;
22248 	default:
22249 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22250 		return;
22251 	}
22252 	switch (mi_copy_state(q, mp, &mp1)) {
22253 	case -1:
22254 		return;
22255 	case MI_COPY_CASE(MI_COPY_IN, 1):
22256 		break;
22257 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22258 		/* Copy out the strbuf. */
22259 		mi_copyout(q, mp);
22260 		return;
22261 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22262 		/* All done. */
22263 		mi_copy_done(q, mp, 0);
22264 		return;
22265 	default:
22266 		mi_copy_done(q, mp, EPROTO);
22267 		return;
22268 	}
22269 	/* Check alignment of the strbuf */
22270 	if (!OK_32PTR(mp1->b_rptr)) {
22271 		mi_copy_done(q, mp, EINVAL);
22272 		return;
22273 	}
22274 
22275 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22276 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22277 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22278 		mi_copy_done(q, mp, EINVAL);
22279 		return;
22280 	}
22281 
22282 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22283 	if (mp1 == NULL)
22284 		return;
22285 
22286 	switch (iocp->ioc_cmd) {
22287 	case TI_GETMYNAME:
22288 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22289 		break;
22290 	case TI_GETPEERNAME:
22291 		error = i_tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22292 		break;
22293 	}
22294 
22295 	if (error != 0) {
22296 		mi_copy_done(q, mp, error);
22297 	} else {
22298 		mp1->b_wptr += addrlen;
22299 		STRUCT_FSET(sb, len, addrlen);
22300 
22301 		/* Copy out the address */
22302 		mi_copyout(q, mp);
22303 	}
22304 }
22305 
22306 static void
22307 tcp_disable_direct_sockfs(tcp_t *tcp)
22308 {
22309 #ifdef	_ILP32
22310 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
22311 #else
22312 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22313 #endif
22314 	/*
22315 	 * Insert this socket into the acceptor hash.
22316 	 * We might need it for T_CONN_RES message
22317 	 */
22318 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22319 
22320 	if (tcp->tcp_fused) {
22321 		/*
22322 		 * This is a fused loopback tcp; disable
22323 		 * read-side synchronous streams interface
22324 		 * and drain any queued data.  It is okay
22325 		 * to do this for non-synchronous streams
22326 		 * fused tcp as well.
22327 		 */
22328 		tcp_fuse_disable_pair(tcp, B_FALSE);
22329 	}
22330 	tcp->tcp_issocket = B_FALSE;
22331 	tcp->tcp_sodirect = NULL;
22332 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
22333 }
22334 
22335 /*
22336  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22337  * messages.
22338  */
22339 /* ARGSUSED */
22340 static void
22341 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22342 {
22343 	conn_t 	*connp = (conn_t *)arg;
22344 	tcp_t	*tcp = connp->conn_tcp;
22345 	queue_t	*q = tcp->tcp_wq;
22346 	struct iocblk	*iocp;
22347 
22348 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22349 	/*
22350 	 * Try and ASSERT the minimum possible references on the
22351 	 * conn early enough. Since we are executing on write side,
22352 	 * the connection is obviously not detached and that means
22353 	 * there is a ref each for TCP and IP. Since we are behind
22354 	 * the squeue, the minimum references needed are 3. If the
22355 	 * conn is in classifier hash list, there should be an
22356 	 * extra ref for that (we check both the possibilities).
22357 	 */
22358 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22359 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22360 
22361 	iocp = (struct iocblk *)mp->b_rptr;
22362 	switch (iocp->ioc_cmd) {
22363 	case TCP_IOC_DEFAULT_Q:
22364 		/* Wants to be the default wq. */
22365 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22366 			iocp->ioc_error = EPERM;
22367 			iocp->ioc_count = 0;
22368 			mp->b_datap->db_type = M_IOCACK;
22369 			qreply(q, mp);
22370 			return;
22371 		}
22372 		tcp_def_q_set(tcp, mp);
22373 		return;
22374 	case _SIOCSOCKFALLBACK:
22375 		/*
22376 		 * Either sockmod is about to be popped and the socket
22377 		 * would now be treated as a plain stream, or a module
22378 		 * is about to be pushed so we could no longer use read-
22379 		 * side synchronous streams for fused loopback tcp.
22380 		 * Drain any queued data and disable direct sockfs
22381 		 * interface from now on.
22382 		 */
22383 		if (!tcp->tcp_issocket) {
22384 			DB_TYPE(mp) = M_IOCNAK;
22385 			iocp->ioc_error = EINVAL;
22386 		} else {
22387 			tcp_disable_direct_sockfs(tcp);
22388 			DB_TYPE(mp) = M_IOCACK;
22389 			iocp->ioc_error = 0;
22390 		}
22391 		iocp->ioc_count = 0;
22392 		iocp->ioc_rval = 0;
22393 		qreply(q, mp);
22394 		return;
22395 	}
22396 	CALL_IP_WPUT(connp, q, mp);
22397 }
22398 
22399 /*
22400  * This routine is called by tcp_wput() to handle all TPI requests.
22401  */
22402 /* ARGSUSED */
22403 static void
22404 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22405 {
22406 	conn_t 	*connp = (conn_t *)arg;
22407 	tcp_t	*tcp = connp->conn_tcp;
22408 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22409 	uchar_t *rptr;
22410 	t_scalar_t type;
22411 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22412 
22413 	/*
22414 	 * Try and ASSERT the minimum possible references on the
22415 	 * conn early enough. Since we are executing on write side,
22416 	 * the connection is obviously not detached and that means
22417 	 * there is a ref each for TCP and IP. Since we are behind
22418 	 * the squeue, the minimum references needed are 3. If the
22419 	 * conn is in classifier hash list, there should be an
22420 	 * extra ref for that (we check both the possibilities).
22421 	 */
22422 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22423 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22424 
22425 	rptr = mp->b_rptr;
22426 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22427 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22428 		type = ((union T_primitives *)rptr)->type;
22429 		if (type == T_EXDATA_REQ) {
22430 			tcp_output_urgent(connp, mp->b_cont, arg2);
22431 			freeb(mp);
22432 		} else if (type != T_DATA_REQ) {
22433 			goto non_urgent_data;
22434 		} else {
22435 			/* TODO: options, flags, ... from user */
22436 			/* Set length to zero for reclamation below */
22437 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22438 			freeb(mp);
22439 		}
22440 		return;
22441 	} else {
22442 		if (tcp->tcp_debug) {
22443 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22444 			    "tcp_wput_proto, dropping one...");
22445 		}
22446 		freemsg(mp);
22447 		return;
22448 	}
22449 
22450 non_urgent_data:
22451 
22452 	switch ((int)tprim->type) {
22453 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22454 		/*
22455 		 * save the kssl_ent_t from the next block, and convert this
22456 		 * back to a normal bind_req.
22457 		 */
22458 		if (mp->b_cont != NULL) {
22459 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22460 
22461 			if (tcp->tcp_kssl_ent != NULL) {
22462 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22463 				    KSSL_NO_PROXY);
22464 				tcp->tcp_kssl_ent = NULL;
22465 			}
22466 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22467 			    sizeof (kssl_ent_t));
22468 			kssl_hold_ent(tcp->tcp_kssl_ent);
22469 			freemsg(mp->b_cont);
22470 			mp->b_cont = NULL;
22471 		}
22472 		tprim->type = T_BIND_REQ;
22473 
22474 	/* FALLTHROUGH */
22475 	case O_T_BIND_REQ:	/* bind request */
22476 	case T_BIND_REQ:	/* new semantics bind request */
22477 		tcp_tpi_bind(tcp, mp);
22478 		break;
22479 	case T_UNBIND_REQ:	/* unbind request */
22480 		tcp_tpi_unbind(tcp, mp);
22481 		break;
22482 	case O_T_CONN_RES:	/* old connection response XXX */
22483 	case T_CONN_RES:	/* connection response */
22484 		tcp_tli_accept(tcp, mp);
22485 		break;
22486 	case T_CONN_REQ:	/* connection request */
22487 		tcp_tpi_connect(tcp, mp);
22488 		break;
22489 	case T_DISCON_REQ:	/* disconnect request */
22490 		tcp_disconnect(tcp, mp);
22491 		break;
22492 	case T_CAPABILITY_REQ:
22493 		tcp_capability_req(tcp, mp);	/* capability request */
22494 		break;
22495 	case T_INFO_REQ:	/* information request */
22496 		tcp_info_req(tcp, mp);
22497 		break;
22498 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22499 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22500 		    &tcp_opt_obj, B_TRUE);
22501 		break;
22502 	case T_OPTMGMT_REQ:
22503 		/*
22504 		 * Note:  no support for snmpcom_req() through new
22505 		 * T_OPTMGMT_REQ. See comments in ip.c
22506 		 */
22507 		/* Only IP is allowed to return meaningful value */
22508 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22509 		    B_TRUE);
22510 		break;
22511 
22512 	case T_UNITDATA_REQ:	/* unitdata request */
22513 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22514 		break;
22515 	case T_ORDREL_REQ:	/* orderly release req */
22516 		freemsg(mp);
22517 
22518 		if (tcp->tcp_fused)
22519 			tcp_unfuse(tcp);
22520 
22521 		if (tcp_xmit_end(tcp) != 0) {
22522 			/*
22523 			 * We were crossing FINs and got a reset from
22524 			 * the other side. Just ignore it.
22525 			 */
22526 			if (tcp->tcp_debug) {
22527 				(void) strlog(TCP_MOD_ID, 0, 1,
22528 				    SL_ERROR|SL_TRACE,
22529 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22530 				    "state %s",
22531 				    tcp_display(tcp, NULL,
22532 				    DISP_ADDR_AND_PORT));
22533 			}
22534 		}
22535 		break;
22536 	case T_ADDR_REQ:
22537 		tcp_addr_req(tcp, mp);
22538 		break;
22539 	default:
22540 		if (tcp->tcp_debug) {
22541 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22542 			    "tcp_wput_proto, bogus TPI msg, type %d",
22543 			    tprim->type);
22544 		}
22545 		/*
22546 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22547 		 * to recover.
22548 		 */
22549 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22550 		break;
22551 	}
22552 }
22553 
22554 /*
22555  * The TCP write service routine should never be called...
22556  */
22557 /* ARGSUSED */
22558 static void
22559 tcp_wsrv(queue_t *q)
22560 {
22561 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22562 
22563 	TCP_STAT(tcps, tcp_wsrv_called);
22564 }
22565 
22566 /* Non overlapping byte exchanger */
22567 static void
22568 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22569 {
22570 	uchar_t	uch;
22571 
22572 	while (len-- > 0) {
22573 		uch = a[len];
22574 		a[len] = b[len];
22575 		b[len] = uch;
22576 	}
22577 }
22578 
22579 /*
22580  * Send out a control packet on the tcp connection specified.  This routine
22581  * is typically called where we need a simple ACK or RST generated.
22582  */
22583 static void
22584 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22585 {
22586 	uchar_t		*rptr;
22587 	tcph_t		*tcph;
22588 	ipha_t		*ipha = NULL;
22589 	ip6_t		*ip6h = NULL;
22590 	uint32_t	sum;
22591 	int		tcp_hdr_len;
22592 	int		tcp_ip_hdr_len;
22593 	mblk_t		*mp;
22594 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22595 
22596 	/*
22597 	 * Save sum for use in source route later.
22598 	 */
22599 	ASSERT(tcp != NULL);
22600 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22601 	tcp_hdr_len = tcp->tcp_hdr_len;
22602 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22603 
22604 	/* If a text string is passed in with the request, pass it to strlog. */
22605 	if (str != NULL && tcp->tcp_debug) {
22606 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22607 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22608 		    str, seq, ack, ctl);
22609 	}
22610 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22611 	    BPRI_MED);
22612 	if (mp == NULL) {
22613 		return;
22614 	}
22615 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22616 	mp->b_rptr = rptr;
22617 	mp->b_wptr = &rptr[tcp_hdr_len];
22618 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22619 
22620 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22621 		ipha = (ipha_t *)rptr;
22622 		ipha->ipha_length = htons(tcp_hdr_len);
22623 	} else {
22624 		ip6h = (ip6_t *)rptr;
22625 		ASSERT(tcp != NULL);
22626 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22627 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22628 	}
22629 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22630 	tcph->th_flags[0] = (uint8_t)ctl;
22631 	if (ctl & TH_RST) {
22632 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22633 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22634 		/*
22635 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22636 		 */
22637 		if (tcp->tcp_snd_ts_ok &&
22638 		    tcp->tcp_state > TCPS_SYN_SENT) {
22639 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22640 			*(mp->b_wptr) = TCPOPT_EOL;
22641 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22642 				ipha->ipha_length = htons(tcp_hdr_len -
22643 				    TCPOPT_REAL_TS_LEN);
22644 			} else {
22645 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22646 				    TCPOPT_REAL_TS_LEN);
22647 			}
22648 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22649 			sum -= TCPOPT_REAL_TS_LEN;
22650 		}
22651 	}
22652 	if (ctl & TH_ACK) {
22653 		if (tcp->tcp_snd_ts_ok) {
22654 			U32_TO_BE32(lbolt,
22655 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22656 			U32_TO_BE32(tcp->tcp_ts_recent,
22657 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22658 		}
22659 
22660 		/* Update the latest receive window size in TCP header. */
22661 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22662 		    tcph->th_win);
22663 		tcp->tcp_rack = ack;
22664 		tcp->tcp_rack_cnt = 0;
22665 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22666 	}
22667 	BUMP_LOCAL(tcp->tcp_obsegs);
22668 	U32_TO_BE32(seq, tcph->th_seq);
22669 	U32_TO_BE32(ack, tcph->th_ack);
22670 	/*
22671 	 * Include the adjustment for a source route if any.
22672 	 */
22673 	sum = (sum >> 16) + (sum & 0xFFFF);
22674 	U16_TO_BE16(sum, tcph->th_sum);
22675 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22676 }
22677 
22678 /*
22679  * If this routine returns B_TRUE, TCP can generate a RST in response
22680  * to a segment.  If it returns B_FALSE, TCP should not respond.
22681  */
22682 static boolean_t
22683 tcp_send_rst_chk(tcp_stack_t *tcps)
22684 {
22685 	clock_t	now;
22686 
22687 	/*
22688 	 * TCP needs to protect itself from generating too many RSTs.
22689 	 * This can be a DoS attack by sending us random segments
22690 	 * soliciting RSTs.
22691 	 *
22692 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22693 	 * in each 1 second interval.  In this way, TCP still generate
22694 	 * RSTs in normal cases but when under attack, the impact is
22695 	 * limited.
22696 	 */
22697 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22698 		now = lbolt;
22699 		/* lbolt can wrap around. */
22700 		if ((tcps->tcps_last_rst_intrvl > now) ||
22701 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22702 		    1*SECONDS)) {
22703 			tcps->tcps_last_rst_intrvl = now;
22704 			tcps->tcps_rst_cnt = 1;
22705 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22706 			return (B_FALSE);
22707 		}
22708 	}
22709 	return (B_TRUE);
22710 }
22711 
22712 /*
22713  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22714  */
22715 static void
22716 tcp_ip_ire_mark_advice(tcp_t *tcp)
22717 {
22718 	mblk_t *mp;
22719 	ipic_t *ipic;
22720 
22721 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22722 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22723 		    &ipic);
22724 	} else {
22725 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22726 		    &ipic);
22727 	}
22728 	if (mp == NULL)
22729 		return;
22730 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22731 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22732 }
22733 
22734 /*
22735  * Return an IP advice ioctl mblk and set ipic to be the pointer
22736  * to the advice structure.
22737  */
22738 static mblk_t *
22739 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22740 {
22741 	struct iocblk *ioc;
22742 	mblk_t *mp, *mp1;
22743 
22744 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22745 	if (mp == NULL)
22746 		return (NULL);
22747 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22748 	*ipic = (ipic_t *)mp->b_rptr;
22749 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22750 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22751 
22752 	bcopy(addr, *ipic + 1, addr_len);
22753 
22754 	(*ipic)->ipic_addr_length = addr_len;
22755 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22756 
22757 	mp1 = mkiocb(IP_IOCTL);
22758 	if (mp1 == NULL) {
22759 		freemsg(mp);
22760 		return (NULL);
22761 	}
22762 	mp1->b_cont = mp;
22763 	ioc = (struct iocblk *)mp1->b_rptr;
22764 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22765 
22766 	return (mp1);
22767 }
22768 
22769 /*
22770  * Generate a reset based on an inbound packet, connp is set by caller
22771  * when RST is in response to an unexpected inbound packet for which
22772  * there is active tcp state in the system.
22773  *
22774  * IPSEC NOTE : Try to send the reply with the same protection as it came
22775  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22776  * the packet will go out at the same level of protection as it came in by
22777  * converting the IPSEC_IN to IPSEC_OUT.
22778  */
22779 static void
22780 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22781     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22782     tcp_stack_t *tcps, conn_t *connp)
22783 {
22784 	ipha_t		*ipha = NULL;
22785 	ip6_t		*ip6h = NULL;
22786 	ushort_t	len;
22787 	tcph_t		*tcph;
22788 	int		i;
22789 	mblk_t		*ipsec_mp;
22790 	boolean_t	mctl_present;
22791 	ipic_t		*ipic;
22792 	ipaddr_t	v4addr;
22793 	in6_addr_t	v6addr;
22794 	int		addr_len;
22795 	void		*addr;
22796 	queue_t		*q = tcps->tcps_g_q;
22797 	tcp_t		*tcp;
22798 	cred_t		*cr;
22799 	mblk_t		*nmp;
22800 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22801 
22802 	if (tcps->tcps_g_q == NULL) {
22803 		/*
22804 		 * For non-zero stackids the default queue isn't created
22805 		 * until the first open, thus there can be a need to send
22806 		 * a reset before then. But we can't do that, hence we just
22807 		 * drop the packet. Later during boot, when the default queue
22808 		 * has been setup, a retransmitted packet from the peer
22809 		 * will result in a reset.
22810 		 */
22811 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22812 		    GLOBAL_NETSTACKID);
22813 		freemsg(mp);
22814 		return;
22815 	}
22816 
22817 	if (connp != NULL)
22818 		tcp = connp->conn_tcp;
22819 	else
22820 		tcp = Q_TO_TCP(q);
22821 
22822 	if (!tcp_send_rst_chk(tcps)) {
22823 		tcps->tcps_rst_unsent++;
22824 		freemsg(mp);
22825 		return;
22826 	}
22827 
22828 	if (mp->b_datap->db_type == M_CTL) {
22829 		ipsec_mp = mp;
22830 		mp = mp->b_cont;
22831 		mctl_present = B_TRUE;
22832 	} else {
22833 		ipsec_mp = mp;
22834 		mctl_present = B_FALSE;
22835 	}
22836 
22837 	if (str && q && tcps->tcps_dbg) {
22838 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22839 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22840 		    "flags 0x%x",
22841 		    str, seq, ack, ctl);
22842 	}
22843 	if (mp->b_datap->db_ref != 1) {
22844 		mblk_t *mp1 = copyb(mp);
22845 		freemsg(mp);
22846 		mp = mp1;
22847 		if (!mp) {
22848 			if (mctl_present)
22849 				freeb(ipsec_mp);
22850 			return;
22851 		} else {
22852 			if (mctl_present) {
22853 				ipsec_mp->b_cont = mp;
22854 			} else {
22855 				ipsec_mp = mp;
22856 			}
22857 		}
22858 	} else if (mp->b_cont) {
22859 		freemsg(mp->b_cont);
22860 		mp->b_cont = NULL;
22861 	}
22862 	/*
22863 	 * We skip reversing source route here.
22864 	 * (for now we replace all IP options with EOL)
22865 	 */
22866 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22867 		ipha = (ipha_t *)mp->b_rptr;
22868 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22869 			mp->b_rptr[i] = IPOPT_EOL;
22870 		/*
22871 		 * Make sure that src address isn't flagrantly invalid.
22872 		 * Not all broadcast address checking for the src address
22873 		 * is possible, since we don't know the netmask of the src
22874 		 * addr.  No check for destination address is done, since
22875 		 * IP will not pass up a packet with a broadcast dest
22876 		 * address to TCP.  Similar checks are done below for IPv6.
22877 		 */
22878 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22879 		    CLASSD(ipha->ipha_src)) {
22880 			freemsg(ipsec_mp);
22881 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22882 			return;
22883 		}
22884 	} else {
22885 		ip6h = (ip6_t *)mp->b_rptr;
22886 
22887 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22888 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22889 			freemsg(ipsec_mp);
22890 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22891 			return;
22892 		}
22893 
22894 		/* Remove any extension headers assuming partial overlay */
22895 		if (ip_hdr_len > IPV6_HDR_LEN) {
22896 			uint8_t *to;
22897 
22898 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22899 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22900 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22901 			ip_hdr_len = IPV6_HDR_LEN;
22902 			ip6h = (ip6_t *)mp->b_rptr;
22903 			ip6h->ip6_nxt = IPPROTO_TCP;
22904 		}
22905 	}
22906 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22907 	if (tcph->th_flags[0] & TH_RST) {
22908 		freemsg(ipsec_mp);
22909 		return;
22910 	}
22911 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22912 	len = ip_hdr_len + sizeof (tcph_t);
22913 	mp->b_wptr = &mp->b_rptr[len];
22914 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22915 		ipha->ipha_length = htons(len);
22916 		/* Swap addresses */
22917 		v4addr = ipha->ipha_src;
22918 		ipha->ipha_src = ipha->ipha_dst;
22919 		ipha->ipha_dst = v4addr;
22920 		ipha->ipha_ident = 0;
22921 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22922 		addr_len = IP_ADDR_LEN;
22923 		addr = &v4addr;
22924 	} else {
22925 		/* No ip6i_t in this case */
22926 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22927 		/* Swap addresses */
22928 		v6addr = ip6h->ip6_src;
22929 		ip6h->ip6_src = ip6h->ip6_dst;
22930 		ip6h->ip6_dst = v6addr;
22931 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22932 		addr_len = IPV6_ADDR_LEN;
22933 		addr = &v6addr;
22934 	}
22935 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22936 	U32_TO_BE32(ack, tcph->th_ack);
22937 	U32_TO_BE32(seq, tcph->th_seq);
22938 	U16_TO_BE16(0, tcph->th_win);
22939 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22940 	tcph->th_flags[0] = (uint8_t)ctl;
22941 	if (ctl & TH_RST) {
22942 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22943 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22944 	}
22945 
22946 	/* IP trusts us to set up labels when required. */
22947 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
22948 	    crgetlabel(cr) != NULL) {
22949 		int err;
22950 
22951 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
22952 			err = tsol_check_label(cr, &mp,
22953 			    tcp->tcp_connp->conn_mac_exempt,
22954 			    tcps->tcps_netstack->netstack_ip);
22955 		else
22956 			err = tsol_check_label_v6(cr, &mp,
22957 			    tcp->tcp_connp->conn_mac_exempt,
22958 			    tcps->tcps_netstack->netstack_ip);
22959 		if (mctl_present)
22960 			ipsec_mp->b_cont = mp;
22961 		else
22962 			ipsec_mp = mp;
22963 		if (err != 0) {
22964 			freemsg(ipsec_mp);
22965 			return;
22966 		}
22967 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22968 			ipha = (ipha_t *)mp->b_rptr;
22969 		} else {
22970 			ip6h = (ip6_t *)mp->b_rptr;
22971 		}
22972 	}
22973 
22974 	if (mctl_present) {
22975 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22976 
22977 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
22978 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
22979 			return;
22980 		}
22981 	}
22982 	if (zoneid == ALL_ZONES)
22983 		zoneid = GLOBAL_ZONEID;
22984 
22985 	/* Add the zoneid so ip_output routes it properly */
22986 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
22987 		freemsg(ipsec_mp);
22988 		return;
22989 	}
22990 	ipsec_mp = nmp;
22991 
22992 	/*
22993 	 * NOTE:  one might consider tracing a TCP packet here, but
22994 	 * this function has no active TCP state and no tcp structure
22995 	 * that has a trace buffer.  If we traced here, we would have
22996 	 * to keep a local trace buffer in tcp_record_trace().
22997 	 *
22998 	 * TSol note: The mblk that contains the incoming packet was
22999 	 * reused by tcp_xmit_listener_reset, so it already contains
23000 	 * the right credentials and we don't need to call mblk_setcred.
23001 	 * Also the conn's cred is not right since it is associated
23002 	 * with tcps_g_q.
23003 	 */
23004 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
23005 
23006 	/*
23007 	 * Tell IP to mark the IRE used for this destination temporary.
23008 	 * This way, we can limit our exposure to DoS attack because IP
23009 	 * creates an IRE for each destination.  If there are too many,
23010 	 * the time to do any routing lookup will be extremely long.  And
23011 	 * the lookup can be in interrupt context.
23012 	 *
23013 	 * Note that in normal circumstances, this marking should not
23014 	 * affect anything.  It would be nice if only 1 message is
23015 	 * needed to inform IP that the IRE created for this RST should
23016 	 * not be added to the cache table.  But there is currently
23017 	 * not such communication mechanism between TCP and IP.  So
23018 	 * the best we can do now is to send the advice ioctl to IP
23019 	 * to mark the IRE temporary.
23020 	 */
23021 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
23022 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
23023 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23024 	}
23025 }
23026 
23027 /*
23028  * Initiate closedown sequence on an active connection.  (May be called as
23029  * writer.)  Return value zero for OK return, non-zero for error return.
23030  */
23031 static int
23032 tcp_xmit_end(tcp_t *tcp)
23033 {
23034 	ipic_t	*ipic;
23035 	mblk_t	*mp;
23036 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23037 
23038 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
23039 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
23040 		/*
23041 		 * Invalid state, only states TCPS_SYN_RCVD,
23042 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
23043 		 */
23044 		return (-1);
23045 	}
23046 
23047 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
23048 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
23049 	/*
23050 	 * If there is nothing more unsent, send the FIN now.
23051 	 * Otherwise, it will go out with the last segment.
23052 	 */
23053 	if (tcp->tcp_unsent == 0) {
23054 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
23055 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
23056 
23057 		if (mp) {
23058 			tcp_send_data(tcp, tcp->tcp_wq, mp);
23059 		} else {
23060 			/*
23061 			 * Couldn't allocate msg.  Pretend we got it out.
23062 			 * Wait for rexmit timeout.
23063 			 */
23064 			tcp->tcp_snxt = tcp->tcp_fss + 1;
23065 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23066 		}
23067 
23068 		/*
23069 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23070 		 * changed.
23071 		 */
23072 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23073 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23074 		}
23075 	} else {
23076 		/*
23077 		 * If tcp->tcp_cork is set, then the data will not get sent,
23078 		 * so we have to check that and unset it first.
23079 		 */
23080 		if (tcp->tcp_cork)
23081 			tcp->tcp_cork = B_FALSE;
23082 		tcp_wput_data(tcp, NULL, B_FALSE);
23083 	}
23084 
23085 	/*
23086 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23087 	 * is 0, don't update the cache.
23088 	 */
23089 	if (tcps->tcps_rtt_updates == 0 ||
23090 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23091 		return (0);
23092 
23093 	/*
23094 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23095 	 * different from the destination.
23096 	 */
23097 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23098 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23099 			return (0);
23100 		}
23101 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23102 		    &ipic);
23103 	} else {
23104 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23105 		    &tcp->tcp_ip6h->ip6_dst))) {
23106 			return (0);
23107 		}
23108 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23109 		    &ipic);
23110 	}
23111 
23112 	/* Record route attributes in the IRE for use by future connections. */
23113 	if (mp == NULL)
23114 		return (0);
23115 
23116 	/*
23117 	 * We do not have a good algorithm to update ssthresh at this time.
23118 	 * So don't do any update.
23119 	 */
23120 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23121 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23122 
23123 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23124 
23125 	return (0);
23126 }
23127 
23128 /*
23129  * Generate a "no listener here" RST in response to an "unknown" segment.
23130  * connp is set by caller when RST is in response to an unexpected
23131  * inbound packet for which there is active tcp state in the system.
23132  * Note that we are reusing the incoming mp to construct the outgoing RST.
23133  */
23134 void
23135 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23136     tcp_stack_t *tcps, conn_t *connp)
23137 {
23138 	uchar_t		*rptr;
23139 	uint32_t	seg_len;
23140 	tcph_t		*tcph;
23141 	uint32_t	seg_seq;
23142 	uint32_t	seg_ack;
23143 	uint_t		flags;
23144 	mblk_t		*ipsec_mp;
23145 	ipha_t 		*ipha;
23146 	ip6_t 		*ip6h;
23147 	boolean_t	mctl_present = B_FALSE;
23148 	boolean_t	check = B_TRUE;
23149 	boolean_t	policy_present;
23150 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23151 
23152 	TCP_STAT(tcps, tcp_no_listener);
23153 
23154 	ipsec_mp = mp;
23155 
23156 	if (mp->b_datap->db_type == M_CTL) {
23157 		ipsec_in_t *ii;
23158 
23159 		mctl_present = B_TRUE;
23160 		mp = mp->b_cont;
23161 
23162 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23163 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23164 		if (ii->ipsec_in_dont_check) {
23165 			check = B_FALSE;
23166 			if (!ii->ipsec_in_secure) {
23167 				freeb(ipsec_mp);
23168 				mctl_present = B_FALSE;
23169 				ipsec_mp = mp;
23170 			}
23171 		}
23172 	}
23173 
23174 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23175 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23176 		ipha = (ipha_t *)mp->b_rptr;
23177 		ip6h = NULL;
23178 	} else {
23179 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23180 		ipha = NULL;
23181 		ip6h = (ip6_t *)mp->b_rptr;
23182 	}
23183 
23184 	if (check && policy_present) {
23185 		/*
23186 		 * The conn_t parameter is NULL because we already know
23187 		 * nobody's home.
23188 		 */
23189 		ipsec_mp = ipsec_check_global_policy(
23190 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23191 		    tcps->tcps_netstack);
23192 		if (ipsec_mp == NULL)
23193 			return;
23194 	}
23195 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23196 		DTRACE_PROBE2(
23197 		    tx__ip__log__error__nolistener__tcp,
23198 		    char *, "Could not reply with RST to mp(1)",
23199 		    mblk_t *, mp);
23200 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23201 		freemsg(ipsec_mp);
23202 		return;
23203 	}
23204 
23205 	rptr = mp->b_rptr;
23206 
23207 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23208 	seg_seq = BE32_TO_U32(tcph->th_seq);
23209 	seg_ack = BE32_TO_U32(tcph->th_ack);
23210 	flags = tcph->th_flags[0];
23211 
23212 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23213 	if (flags & TH_RST) {
23214 		freemsg(ipsec_mp);
23215 	} else if (flags & TH_ACK) {
23216 		tcp_xmit_early_reset("no tcp, reset",
23217 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23218 		    connp);
23219 	} else {
23220 		if (flags & TH_SYN) {
23221 			seg_len++;
23222 		} else {
23223 			/*
23224 			 * Here we violate the RFC.  Note that a normal
23225 			 * TCP will never send a segment without the ACK
23226 			 * flag, except for RST or SYN segment.  This
23227 			 * segment is neither.  Just drop it on the
23228 			 * floor.
23229 			 */
23230 			freemsg(ipsec_mp);
23231 			tcps->tcps_rst_unsent++;
23232 			return;
23233 		}
23234 
23235 		tcp_xmit_early_reset("no tcp, reset/ack",
23236 		    ipsec_mp, 0, seg_seq + seg_len,
23237 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23238 	}
23239 }
23240 
23241 /*
23242  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23243  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23244  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23245  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23246  * otherwise it will dup partial mblks.)
23247  * Otherwise, an appropriate ACK packet will be generated.  This
23248  * routine is not usually called to send new data for the first time.  It
23249  * is mostly called out of the timer for retransmits, and to generate ACKs.
23250  *
23251  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23252  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23253  * of the original mblk chain will be returned in *offset and *end_mp.
23254  */
23255 mblk_t *
23256 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23257     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23258     boolean_t rexmit)
23259 {
23260 	int	data_length;
23261 	int32_t	off = 0;
23262 	uint_t	flags;
23263 	mblk_t	*mp1;
23264 	mblk_t	*mp2;
23265 	uchar_t	*rptr;
23266 	tcph_t	*tcph;
23267 	int32_t	num_sack_blk = 0;
23268 	int32_t	sack_opt_len = 0;
23269 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23270 
23271 	/* Allocate for our maximum TCP header + link-level */
23272 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23273 	    tcps->tcps_wroff_xtra, BPRI_MED);
23274 	if (!mp1)
23275 		return (NULL);
23276 	data_length = 0;
23277 
23278 	/*
23279 	 * Note that tcp_mss has been adjusted to take into account the
23280 	 * timestamp option if applicable.  Because SACK options do not
23281 	 * appear in every TCP segments and they are of variable lengths,
23282 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23283 	 * the actual segment length when we need to send a segment which
23284 	 * includes SACK options.
23285 	 */
23286 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23287 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23288 		    tcp->tcp_num_sack_blk);
23289 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23290 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23291 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23292 			max_to_send -= sack_opt_len;
23293 	}
23294 
23295 	if (offset != NULL) {
23296 		off = *offset;
23297 		/* We use offset as an indicator that end_mp is not NULL. */
23298 		*end_mp = NULL;
23299 	}
23300 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23301 		/* This could be faster with cooperation from downstream */
23302 		if (mp2 != mp1 && !sendall &&
23303 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23304 		    max_to_send)
23305 			/*
23306 			 * Don't send the next mblk since the whole mblk
23307 			 * does not fit.
23308 			 */
23309 			break;
23310 		mp2->b_cont = dupb(mp);
23311 		mp2 = mp2->b_cont;
23312 		if (!mp2) {
23313 			freemsg(mp1);
23314 			return (NULL);
23315 		}
23316 		mp2->b_rptr += off;
23317 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23318 		    (uintptr_t)INT_MAX);
23319 
23320 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23321 		if (data_length > max_to_send) {
23322 			mp2->b_wptr -= data_length - max_to_send;
23323 			data_length = max_to_send;
23324 			off = mp2->b_wptr - mp->b_rptr;
23325 			break;
23326 		} else {
23327 			off = 0;
23328 		}
23329 	}
23330 	if (offset != NULL) {
23331 		*offset = off;
23332 		*end_mp = mp;
23333 	}
23334 	if (seg_len != NULL) {
23335 		*seg_len = data_length;
23336 	}
23337 
23338 	/* Update the latest receive window size in TCP header. */
23339 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23340 	    tcp->tcp_tcph->th_win);
23341 
23342 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23343 	mp1->b_rptr = rptr;
23344 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23345 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23346 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23347 	U32_TO_ABE32(seq, tcph->th_seq);
23348 
23349 	/*
23350 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23351 	 * that this function was called from tcp_wput_data. Thus, when called
23352 	 * to retransmit data the setting of the PUSH bit may appear some
23353 	 * what random in that it might get set when it should not. This
23354 	 * should not pose any performance issues.
23355 	 */
23356 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23357 	    tcp->tcp_unsent == data_length)) {
23358 		flags = TH_ACK | TH_PUSH;
23359 	} else {
23360 		flags = TH_ACK;
23361 	}
23362 
23363 	if (tcp->tcp_ecn_ok) {
23364 		if (tcp->tcp_ecn_echo_on)
23365 			flags |= TH_ECE;
23366 
23367 		/*
23368 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23369 		 * There is no TCP flow control for non-data segments, and
23370 		 * only data segment is transmitted reliably.
23371 		 */
23372 		if (data_length > 0 && !rexmit) {
23373 			SET_ECT(tcp, rptr);
23374 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23375 				flags |= TH_CWR;
23376 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23377 			}
23378 		}
23379 	}
23380 
23381 	if (tcp->tcp_valid_bits) {
23382 		uint32_t u1;
23383 
23384 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23385 		    seq == tcp->tcp_iss) {
23386 			uchar_t	*wptr;
23387 
23388 			/*
23389 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23390 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23391 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23392 			 * our SYN is not ack'ed but the app closes this
23393 			 * TCP connection.
23394 			 */
23395 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23396 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23397 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23398 
23399 			/*
23400 			 * Tack on the MSS option.  It is always needed
23401 			 * for both active and passive open.
23402 			 *
23403 			 * MSS option value should be interface MTU - MIN
23404 			 * TCP/IP header according to RFC 793 as it means
23405 			 * the maximum segment size TCP can receive.  But
23406 			 * to get around some broken middle boxes/end hosts
23407 			 * out there, we allow the option value to be the
23408 			 * same as the MSS option size on the peer side.
23409 			 * In this way, the other side will not send
23410 			 * anything larger than they can receive.
23411 			 *
23412 			 * Note that for SYN_SENT state, the ndd param
23413 			 * tcp_use_smss_as_mss_opt has no effect as we
23414 			 * don't know the peer's MSS option value. So
23415 			 * the only case we need to take care of is in
23416 			 * SYN_RCVD state, which is done later.
23417 			 */
23418 			wptr = mp1->b_wptr;
23419 			wptr[0] = TCPOPT_MAXSEG;
23420 			wptr[1] = TCPOPT_MAXSEG_LEN;
23421 			wptr += 2;
23422 			u1 = tcp->tcp_if_mtu -
23423 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23424 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23425 			    TCP_MIN_HEADER_LENGTH;
23426 			U16_TO_BE16(u1, wptr);
23427 			mp1->b_wptr = wptr + 2;
23428 			/* Update the offset to cover the additional word */
23429 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23430 
23431 			/*
23432 			 * Note that the following way of filling in
23433 			 * TCP options are not optimal.  Some NOPs can
23434 			 * be saved.  But there is no need at this time
23435 			 * to optimize it.  When it is needed, we will
23436 			 * do it.
23437 			 */
23438 			switch (tcp->tcp_state) {
23439 			case TCPS_SYN_SENT:
23440 				flags = TH_SYN;
23441 
23442 				if (tcp->tcp_snd_ts_ok) {
23443 					uint32_t llbolt = (uint32_t)lbolt;
23444 
23445 					wptr = mp1->b_wptr;
23446 					wptr[0] = TCPOPT_NOP;
23447 					wptr[1] = TCPOPT_NOP;
23448 					wptr[2] = TCPOPT_TSTAMP;
23449 					wptr[3] = TCPOPT_TSTAMP_LEN;
23450 					wptr += 4;
23451 					U32_TO_BE32(llbolt, wptr);
23452 					wptr += 4;
23453 					ASSERT(tcp->tcp_ts_recent == 0);
23454 					U32_TO_BE32(0L, wptr);
23455 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23456 					tcph->th_offset_and_rsrvd[0] +=
23457 					    (3 << 4);
23458 				}
23459 
23460 				/*
23461 				 * Set up all the bits to tell other side
23462 				 * we are ECN capable.
23463 				 */
23464 				if (tcp->tcp_ecn_ok) {
23465 					flags |= (TH_ECE | TH_CWR);
23466 				}
23467 				break;
23468 			case TCPS_SYN_RCVD:
23469 				flags |= TH_SYN;
23470 
23471 				/*
23472 				 * Reset the MSS option value to be SMSS
23473 				 * We should probably add back the bytes
23474 				 * for timestamp option and IPsec.  We
23475 				 * don't do that as this is a workaround
23476 				 * for broken middle boxes/end hosts, it
23477 				 * is better for us to be more cautious.
23478 				 * They may not take these things into
23479 				 * account in their SMSS calculation.  Thus
23480 				 * the peer's calculated SMSS may be smaller
23481 				 * than what it can be.  This should be OK.
23482 				 */
23483 				if (tcps->tcps_use_smss_as_mss_opt) {
23484 					u1 = tcp->tcp_mss;
23485 					U16_TO_BE16(u1, wptr);
23486 				}
23487 
23488 				/*
23489 				 * If the other side is ECN capable, reply
23490 				 * that we are also ECN capable.
23491 				 */
23492 				if (tcp->tcp_ecn_ok)
23493 					flags |= TH_ECE;
23494 				break;
23495 			default:
23496 				/*
23497 				 * The above ASSERT() makes sure that this
23498 				 * must be FIN-WAIT-1 state.  Our SYN has
23499 				 * not been ack'ed so retransmit it.
23500 				 */
23501 				flags |= TH_SYN;
23502 				break;
23503 			}
23504 
23505 			if (tcp->tcp_snd_ws_ok) {
23506 				wptr = mp1->b_wptr;
23507 				wptr[0] =  TCPOPT_NOP;
23508 				wptr[1] =  TCPOPT_WSCALE;
23509 				wptr[2] =  TCPOPT_WS_LEN;
23510 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23511 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23512 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23513 			}
23514 
23515 			if (tcp->tcp_snd_sack_ok) {
23516 				wptr = mp1->b_wptr;
23517 				wptr[0] = TCPOPT_NOP;
23518 				wptr[1] = TCPOPT_NOP;
23519 				wptr[2] = TCPOPT_SACK_PERMITTED;
23520 				wptr[3] = TCPOPT_SACK_OK_LEN;
23521 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23522 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23523 			}
23524 
23525 			/* allocb() of adequate mblk assures space */
23526 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23527 			    (uintptr_t)INT_MAX);
23528 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23529 			/*
23530 			 * Get IP set to checksum on our behalf
23531 			 * Include the adjustment for a source route if any.
23532 			 */
23533 			u1 += tcp->tcp_sum;
23534 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23535 			U16_TO_BE16(u1, tcph->th_sum);
23536 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23537 		}
23538 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23539 		    (seq + data_length) == tcp->tcp_fss) {
23540 			if (!tcp->tcp_fin_acked) {
23541 				flags |= TH_FIN;
23542 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23543 			}
23544 			if (!tcp->tcp_fin_sent) {
23545 				tcp->tcp_fin_sent = B_TRUE;
23546 				switch (tcp->tcp_state) {
23547 				case TCPS_SYN_RCVD:
23548 				case TCPS_ESTABLISHED:
23549 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23550 					break;
23551 				case TCPS_CLOSE_WAIT:
23552 					tcp->tcp_state = TCPS_LAST_ACK;
23553 					break;
23554 				}
23555 				if (tcp->tcp_suna == tcp->tcp_snxt)
23556 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23557 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23558 			}
23559 		}
23560 		/*
23561 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23562 		 * is smaller than seq, u1 will become a very huge value.
23563 		 * So the comparison will fail.  Also note that tcp_urp
23564 		 * should be positive, see RFC 793 page 17.
23565 		 */
23566 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23567 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23568 		    u1 < (uint32_t)(64 * 1024)) {
23569 			flags |= TH_URG;
23570 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23571 			U32_TO_ABE16(u1, tcph->th_urp);
23572 		}
23573 	}
23574 	tcph->th_flags[0] = (uchar_t)flags;
23575 	tcp->tcp_rack = tcp->tcp_rnxt;
23576 	tcp->tcp_rack_cnt = 0;
23577 
23578 	if (tcp->tcp_snd_ts_ok) {
23579 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23580 			uint32_t llbolt = (uint32_t)lbolt;
23581 
23582 			U32_TO_BE32(llbolt,
23583 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23584 			U32_TO_BE32(tcp->tcp_ts_recent,
23585 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23586 		}
23587 	}
23588 
23589 	if (num_sack_blk > 0) {
23590 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23591 		sack_blk_t *tmp;
23592 		int32_t	i;
23593 
23594 		wptr[0] = TCPOPT_NOP;
23595 		wptr[1] = TCPOPT_NOP;
23596 		wptr[2] = TCPOPT_SACK;
23597 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23598 		    sizeof (sack_blk_t);
23599 		wptr += TCPOPT_REAL_SACK_LEN;
23600 
23601 		tmp = tcp->tcp_sack_list;
23602 		for (i = 0; i < num_sack_blk; i++) {
23603 			U32_TO_BE32(tmp[i].begin, wptr);
23604 			wptr += sizeof (tcp_seq);
23605 			U32_TO_BE32(tmp[i].end, wptr);
23606 			wptr += sizeof (tcp_seq);
23607 		}
23608 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23609 	}
23610 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23611 	data_length += (int)(mp1->b_wptr - rptr);
23612 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23613 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23614 	} else {
23615 		ip6_t *ip6 = (ip6_t *)(rptr +
23616 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23617 		    sizeof (ip6i_t) : 0));
23618 
23619 		ip6->ip6_plen = htons(data_length -
23620 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23621 	}
23622 
23623 	/*
23624 	 * Prime pump for IP
23625 	 * Include the adjustment for a source route if any.
23626 	 */
23627 	data_length -= tcp->tcp_ip_hdr_len;
23628 	data_length += tcp->tcp_sum;
23629 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23630 	U16_TO_ABE16(data_length, tcph->th_sum);
23631 	if (tcp->tcp_ip_forward_progress) {
23632 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23633 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23634 		tcp->tcp_ip_forward_progress = B_FALSE;
23635 	}
23636 	return (mp1);
23637 }
23638 
23639 /* This function handles the push timeout. */
23640 void
23641 tcp_push_timer(void *arg)
23642 {
23643 	conn_t	*connp = (conn_t *)arg;
23644 	tcp_t *tcp = connp->conn_tcp;
23645 	uint_t		flags;
23646 	sodirect_t	*sodp;
23647 
23648 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
23649 
23650 	ASSERT(tcp->tcp_listener == NULL);
23651 
23652 	ASSERT(!IPCL_IS_NONSTR(connp));
23653 
23654 	/*
23655 	 * We need to plug synchronous streams during our drain to prevent
23656 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23657 	 */
23658 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23659 	tcp->tcp_push_tid = 0;
23660 
23661 	SOD_PTR_ENTER(tcp, sodp);
23662 	if (sodp != NULL) {
23663 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23664 		/* sod_wakeup() does the mutex_exit() */
23665 	} else if (tcp->tcp_rcv_list != NULL) {
23666 		flags = tcp_rcv_drain(tcp);
23667 	}
23668 	if (flags == TH_ACK_NEEDED)
23669 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23670 
23671 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23672 }
23673 
23674 /*
23675  * This function handles delayed ACK timeout.
23676  */
23677 static void
23678 tcp_ack_timer(void *arg)
23679 {
23680 	conn_t	*connp = (conn_t *)arg;
23681 	tcp_t *tcp = connp->conn_tcp;
23682 	mblk_t *mp;
23683 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23684 
23685 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23686 
23687 	tcp->tcp_ack_tid = 0;
23688 
23689 	if (tcp->tcp_fused)
23690 		return;
23691 
23692 	/*
23693 	 * Do not send ACK if there is no outstanding unack'ed data.
23694 	 */
23695 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23696 		return;
23697 	}
23698 
23699 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23700 		/*
23701 		 * Make sure we don't allow deferred ACKs to result in
23702 		 * timer-based ACKing.  If we have held off an ACK
23703 		 * when there was more than an mss here, and the timer
23704 		 * goes off, we have to worry about the possibility
23705 		 * that the sender isn't doing slow-start, or is out
23706 		 * of step with us for some other reason.  We fall
23707 		 * permanently back in the direction of
23708 		 * ACK-every-other-packet as suggested in RFC 1122.
23709 		 */
23710 		if (tcp->tcp_rack_abs_max > 2)
23711 			tcp->tcp_rack_abs_max--;
23712 		tcp->tcp_rack_cur_max = 2;
23713 	}
23714 	mp = tcp_ack_mp(tcp);
23715 
23716 	if (mp != NULL) {
23717 		BUMP_LOCAL(tcp->tcp_obsegs);
23718 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23719 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23720 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23721 	}
23722 }
23723 
23724 
23725 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23726 static mblk_t *
23727 tcp_ack_mp(tcp_t *tcp)
23728 {
23729 	uint32_t	seq_no;
23730 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23731 
23732 	/*
23733 	 * There are a few cases to be considered while setting the sequence no.
23734 	 * Essentially, we can come here while processing an unacceptable pkt
23735 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23736 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23737 	 * If we are here for a zero window probe, stick with suna. In all
23738 	 * other cases, we check if suna + swnd encompasses snxt and set
23739 	 * the sequence number to snxt, if so. If snxt falls outside the
23740 	 * window (the receiver probably shrunk its window), we will go with
23741 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23742 	 * receiver.
23743 	 */
23744 	if (tcp->tcp_zero_win_probe) {
23745 		seq_no = tcp->tcp_suna;
23746 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23747 		ASSERT(tcp->tcp_swnd == 0);
23748 		seq_no = tcp->tcp_snxt;
23749 	} else {
23750 		seq_no = SEQ_GT(tcp->tcp_snxt,
23751 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23752 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23753 	}
23754 
23755 	if (tcp->tcp_valid_bits) {
23756 		/*
23757 		 * For the complex case where we have to send some
23758 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23759 		 */
23760 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23761 		    NULL, B_FALSE));
23762 	} else {
23763 		/* Generate a simple ACK */
23764 		int	data_length;
23765 		uchar_t	*rptr;
23766 		tcph_t	*tcph;
23767 		mblk_t	*mp1;
23768 		int32_t	tcp_hdr_len;
23769 		int32_t	tcp_tcp_hdr_len;
23770 		int32_t	num_sack_blk = 0;
23771 		int32_t sack_opt_len;
23772 
23773 		/*
23774 		 * Allocate space for TCP + IP headers
23775 		 * and link-level header
23776 		 */
23777 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23778 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23779 			    tcp->tcp_num_sack_blk);
23780 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23781 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23782 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23783 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23784 		} else {
23785 			tcp_hdr_len = tcp->tcp_hdr_len;
23786 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23787 		}
23788 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23789 		if (!mp1)
23790 			return (NULL);
23791 
23792 		/* Update the latest receive window size in TCP header. */
23793 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23794 		    tcp->tcp_tcph->th_win);
23795 		/* copy in prototype TCP + IP header */
23796 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23797 		mp1->b_rptr = rptr;
23798 		mp1->b_wptr = rptr + tcp_hdr_len;
23799 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23800 
23801 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23802 
23803 		/* Set the TCP sequence number. */
23804 		U32_TO_ABE32(seq_no, tcph->th_seq);
23805 
23806 		/* Set up the TCP flag field. */
23807 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23808 		if (tcp->tcp_ecn_echo_on)
23809 			tcph->th_flags[0] |= TH_ECE;
23810 
23811 		tcp->tcp_rack = tcp->tcp_rnxt;
23812 		tcp->tcp_rack_cnt = 0;
23813 
23814 		/* fill in timestamp option if in use */
23815 		if (tcp->tcp_snd_ts_ok) {
23816 			uint32_t llbolt = (uint32_t)lbolt;
23817 
23818 			U32_TO_BE32(llbolt,
23819 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23820 			U32_TO_BE32(tcp->tcp_ts_recent,
23821 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23822 		}
23823 
23824 		/* Fill in SACK options */
23825 		if (num_sack_blk > 0) {
23826 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23827 			sack_blk_t *tmp;
23828 			int32_t	i;
23829 
23830 			wptr[0] = TCPOPT_NOP;
23831 			wptr[1] = TCPOPT_NOP;
23832 			wptr[2] = TCPOPT_SACK;
23833 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23834 			    sizeof (sack_blk_t);
23835 			wptr += TCPOPT_REAL_SACK_LEN;
23836 
23837 			tmp = tcp->tcp_sack_list;
23838 			for (i = 0; i < num_sack_blk; i++) {
23839 				U32_TO_BE32(tmp[i].begin, wptr);
23840 				wptr += sizeof (tcp_seq);
23841 				U32_TO_BE32(tmp[i].end, wptr);
23842 				wptr += sizeof (tcp_seq);
23843 			}
23844 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23845 			    << 4);
23846 		}
23847 
23848 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23849 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23850 		} else {
23851 			/* Check for ip6i_t header in sticky hdrs */
23852 			ip6_t *ip6 = (ip6_t *)(rptr +
23853 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23854 			    sizeof (ip6i_t) : 0));
23855 
23856 			ip6->ip6_plen = htons(tcp_hdr_len -
23857 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23858 		}
23859 
23860 		/*
23861 		 * Prime pump for checksum calculation in IP.  Include the
23862 		 * adjustment for a source route if any.
23863 		 */
23864 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23865 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23866 		U16_TO_ABE16(data_length, tcph->th_sum);
23867 
23868 		if (tcp->tcp_ip_forward_progress) {
23869 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23870 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23871 			tcp->tcp_ip_forward_progress = B_FALSE;
23872 		}
23873 		return (mp1);
23874 	}
23875 }
23876 
23877 /*
23878  * Hash list insertion routine for tcp_t structures. Each hash bucket
23879  * contains a list of tcp_t entries, and each entry is bound to a unique
23880  * port. If there are multiple tcp_t's that are bound to the same port, then
23881  * one of them will be linked into the hash bucket list, and the rest will
23882  * hang off of that one entry. For each port, entries bound to a specific IP
23883  * address will be inserted before those those bound to INADDR_ANY.
23884  */
23885 static void
23886 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23887 {
23888 	tcp_t	**tcpp;
23889 	tcp_t	*tcpnext;
23890 	tcp_t	*tcphash;
23891 
23892 	if (tcp->tcp_ptpbhn != NULL) {
23893 		ASSERT(!caller_holds_lock);
23894 		tcp_bind_hash_remove(tcp);
23895 	}
23896 	tcpp = &tbf->tf_tcp;
23897 	if (!caller_holds_lock) {
23898 		mutex_enter(&tbf->tf_lock);
23899 	} else {
23900 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23901 	}
23902 	tcphash = tcpp[0];
23903 	tcpnext = NULL;
23904 	if (tcphash != NULL) {
23905 		/* Look for an entry using the same port */
23906 		while ((tcphash = tcpp[0]) != NULL &&
23907 		    tcp->tcp_lport != tcphash->tcp_lport)
23908 			tcpp = &(tcphash->tcp_bind_hash);
23909 
23910 		/* The port was not found, just add to the end */
23911 		if (tcphash == NULL)
23912 			goto insert;
23913 
23914 		/*
23915 		 * OK, there already exists an entry bound to the
23916 		 * same port.
23917 		 *
23918 		 * If the new tcp bound to the INADDR_ANY address
23919 		 * and the first one in the list is not bound to
23920 		 * INADDR_ANY we skip all entries until we find the
23921 		 * first one bound to INADDR_ANY.
23922 		 * This makes sure that applications binding to a
23923 		 * specific address get preference over those binding to
23924 		 * INADDR_ANY.
23925 		 */
23926 		tcpnext = tcphash;
23927 		tcphash = NULL;
23928 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
23929 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
23930 			while ((tcpnext = tcpp[0]) != NULL &&
23931 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
23932 				tcpp = &(tcpnext->tcp_bind_hash_port);
23933 
23934 			if (tcpnext) {
23935 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23936 				tcphash = tcpnext->tcp_bind_hash;
23937 				if (tcphash != NULL) {
23938 					tcphash->tcp_ptpbhn =
23939 					    &(tcp->tcp_bind_hash);
23940 					tcpnext->tcp_bind_hash = NULL;
23941 				}
23942 			}
23943 		} else {
23944 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
23945 			tcphash = tcpnext->tcp_bind_hash;
23946 			if (tcphash != NULL) {
23947 				tcphash->tcp_ptpbhn =
23948 				    &(tcp->tcp_bind_hash);
23949 				tcpnext->tcp_bind_hash = NULL;
23950 			}
23951 		}
23952 	}
23953 insert:
23954 	tcp->tcp_bind_hash_port = tcpnext;
23955 	tcp->tcp_bind_hash = tcphash;
23956 	tcp->tcp_ptpbhn = tcpp;
23957 	tcpp[0] = tcp;
23958 	if (!caller_holds_lock)
23959 		mutex_exit(&tbf->tf_lock);
23960 }
23961 
23962 /*
23963  * Hash list removal routine for tcp_t structures.
23964  */
23965 static void
23966 tcp_bind_hash_remove(tcp_t *tcp)
23967 {
23968 	tcp_t	*tcpnext;
23969 	kmutex_t *lockp;
23970 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23971 
23972 	if (tcp->tcp_ptpbhn == NULL)
23973 		return;
23974 
23975 	/*
23976 	 * Extract the lock pointer in case there are concurrent
23977 	 * hash_remove's for this instance.
23978 	 */
23979 	ASSERT(tcp->tcp_lport != 0);
23980 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
23981 
23982 	ASSERT(lockp != NULL);
23983 	mutex_enter(lockp);
23984 	if (tcp->tcp_ptpbhn) {
23985 		tcpnext = tcp->tcp_bind_hash_port;
23986 		if (tcpnext != NULL) {
23987 			tcp->tcp_bind_hash_port = NULL;
23988 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23989 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
23990 			if (tcpnext->tcp_bind_hash != NULL) {
23991 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
23992 				    &(tcpnext->tcp_bind_hash);
23993 				tcp->tcp_bind_hash = NULL;
23994 			}
23995 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
23996 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
23997 			tcp->tcp_bind_hash = NULL;
23998 		}
23999 		*tcp->tcp_ptpbhn = tcpnext;
24000 		tcp->tcp_ptpbhn = NULL;
24001 	}
24002 	mutex_exit(lockp);
24003 }
24004 
24005 
24006 /*
24007  * Hash list lookup routine for tcp_t structures.
24008  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24009  */
24010 static tcp_t *
24011 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24012 {
24013 	tf_t	*tf;
24014 	tcp_t	*tcp;
24015 
24016 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24017 	mutex_enter(&tf->tf_lock);
24018 	for (tcp = tf->tf_tcp; tcp != NULL;
24019 	    tcp = tcp->tcp_acceptor_hash) {
24020 		if (tcp->tcp_acceptor_id == id) {
24021 			CONN_INC_REF(tcp->tcp_connp);
24022 			mutex_exit(&tf->tf_lock);
24023 			return (tcp);
24024 		}
24025 	}
24026 	mutex_exit(&tf->tf_lock);
24027 	return (NULL);
24028 }
24029 
24030 
24031 /*
24032  * Hash list insertion routine for tcp_t structures.
24033  */
24034 void
24035 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24036 {
24037 	tf_t	*tf;
24038 	tcp_t	**tcpp;
24039 	tcp_t	*tcpnext;
24040 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24041 
24042 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24043 
24044 	if (tcp->tcp_ptpahn != NULL)
24045 		tcp_acceptor_hash_remove(tcp);
24046 	tcpp = &tf->tf_tcp;
24047 	mutex_enter(&tf->tf_lock);
24048 	tcpnext = tcpp[0];
24049 	if (tcpnext)
24050 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24051 	tcp->tcp_acceptor_hash = tcpnext;
24052 	tcp->tcp_ptpahn = tcpp;
24053 	tcpp[0] = tcp;
24054 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24055 	mutex_exit(&tf->tf_lock);
24056 }
24057 
24058 /*
24059  * Hash list removal routine for tcp_t structures.
24060  */
24061 static void
24062 tcp_acceptor_hash_remove(tcp_t *tcp)
24063 {
24064 	tcp_t	*tcpnext;
24065 	kmutex_t *lockp;
24066 
24067 	/*
24068 	 * Extract the lock pointer in case there are concurrent
24069 	 * hash_remove's for this instance.
24070 	 */
24071 	lockp = tcp->tcp_acceptor_lockp;
24072 
24073 	if (tcp->tcp_ptpahn == NULL)
24074 		return;
24075 
24076 	ASSERT(lockp != NULL);
24077 	mutex_enter(lockp);
24078 	if (tcp->tcp_ptpahn) {
24079 		tcpnext = tcp->tcp_acceptor_hash;
24080 		if (tcpnext) {
24081 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24082 			tcp->tcp_acceptor_hash = NULL;
24083 		}
24084 		*tcp->tcp_ptpahn = tcpnext;
24085 		tcp->tcp_ptpahn = NULL;
24086 	}
24087 	mutex_exit(lockp);
24088 	tcp->tcp_acceptor_lockp = NULL;
24089 }
24090 
24091 /* Data for fast netmask macro used by tcp_hsp_lookup */
24092 
24093 static ipaddr_t netmasks[] = {
24094 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24095 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24096 };
24097 
24098 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24099 
24100 /*
24101  * XXX This routine should go away and instead we should use the metrics
24102  * associated with the routes to determine the default sndspace and rcvspace.
24103  */
24104 static tcp_hsp_t *
24105 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24106 {
24107 	tcp_hsp_t *hsp = NULL;
24108 
24109 	/* Quick check without acquiring the lock. */
24110 	if (tcps->tcps_hsp_hash == NULL)
24111 		return (NULL);
24112 
24113 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24114 
24115 	/* This routine finds the best-matching HSP for address addr. */
24116 
24117 	if (tcps->tcps_hsp_hash) {
24118 		int i;
24119 		ipaddr_t srchaddr;
24120 		tcp_hsp_t *hsp_net;
24121 
24122 		/* We do three passes: host, network, and subnet. */
24123 
24124 		srchaddr = addr;
24125 
24126 		for (i = 1; i <= 3; i++) {
24127 			/* Look for exact match on srchaddr */
24128 
24129 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24130 			while (hsp) {
24131 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24132 				    hsp->tcp_hsp_addr == srchaddr)
24133 					break;
24134 				hsp = hsp->tcp_hsp_next;
24135 			}
24136 			ASSERT(hsp == NULL ||
24137 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24138 
24139 			/*
24140 			 * If this is the first pass:
24141 			 *   If we found a match, great, return it.
24142 			 *   If not, search for the network on the second pass.
24143 			 */
24144 
24145 			if (i == 1)
24146 				if (hsp)
24147 					break;
24148 				else
24149 				{
24150 					srchaddr = addr & netmask(addr);
24151 					continue;
24152 				}
24153 
24154 			/*
24155 			 * If this is the second pass:
24156 			 *   If we found a match, but there's a subnet mask,
24157 			 *    save the match but try again using the subnet
24158 			 *    mask on the third pass.
24159 			 *   Otherwise, return whatever we found.
24160 			 */
24161 
24162 			if (i == 2) {
24163 				if (hsp && hsp->tcp_hsp_subnet) {
24164 					hsp_net = hsp;
24165 					srchaddr = addr & hsp->tcp_hsp_subnet;
24166 					continue;
24167 				} else {
24168 					break;
24169 				}
24170 			}
24171 
24172 			/*
24173 			 * This must be the third pass.  If we didn't find
24174 			 * anything, return the saved network HSP instead.
24175 			 */
24176 
24177 			if (!hsp)
24178 				hsp = hsp_net;
24179 		}
24180 	}
24181 
24182 	rw_exit(&tcps->tcps_hsp_lock);
24183 	return (hsp);
24184 }
24185 
24186 /*
24187  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24188  * match lookup.
24189  */
24190 static tcp_hsp_t *
24191 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24192 {
24193 	tcp_hsp_t *hsp = NULL;
24194 
24195 	/* Quick check without acquiring the lock. */
24196 	if (tcps->tcps_hsp_hash == NULL)
24197 		return (NULL);
24198 
24199 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24200 
24201 	/* This routine finds the best-matching HSP for address addr. */
24202 
24203 	if (tcps->tcps_hsp_hash) {
24204 		int i;
24205 		in6_addr_t v6srchaddr;
24206 		tcp_hsp_t *hsp_net;
24207 
24208 		/* We do three passes: host, network, and subnet. */
24209 
24210 		v6srchaddr = *v6addr;
24211 
24212 		for (i = 1; i <= 3; i++) {
24213 			/* Look for exact match on srchaddr */
24214 
24215 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24216 			    V4_PART_OF_V6(v6srchaddr))];
24217 			while (hsp) {
24218 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24219 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24220 				    &v6srchaddr))
24221 					break;
24222 				hsp = hsp->tcp_hsp_next;
24223 			}
24224 
24225 			/*
24226 			 * If this is the first pass:
24227 			 *   If we found a match, great, return it.
24228 			 *   If not, search for the network on the second pass.
24229 			 */
24230 
24231 			if (i == 1)
24232 				if (hsp)
24233 					break;
24234 				else {
24235 					/* Assume a 64 bit mask */
24236 					v6srchaddr.s6_addr32[0] =
24237 					    v6addr->s6_addr32[0];
24238 					v6srchaddr.s6_addr32[1] =
24239 					    v6addr->s6_addr32[1];
24240 					v6srchaddr.s6_addr32[2] = 0;
24241 					v6srchaddr.s6_addr32[3] = 0;
24242 					continue;
24243 				}
24244 
24245 			/*
24246 			 * If this is the second pass:
24247 			 *   If we found a match, but there's a subnet mask,
24248 			 *    save the match but try again using the subnet
24249 			 *    mask on the third pass.
24250 			 *   Otherwise, return whatever we found.
24251 			 */
24252 
24253 			if (i == 2) {
24254 				ASSERT(hsp == NULL ||
24255 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24256 				if (hsp &&
24257 				    !IN6_IS_ADDR_UNSPECIFIED(
24258 				    &hsp->tcp_hsp_subnet_v6)) {
24259 					hsp_net = hsp;
24260 					V6_MASK_COPY(*v6addr,
24261 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24262 					continue;
24263 				} else {
24264 					break;
24265 				}
24266 			}
24267 
24268 			/*
24269 			 * This must be the third pass.  If we didn't find
24270 			 * anything, return the saved network HSP instead.
24271 			 */
24272 
24273 			if (!hsp)
24274 				hsp = hsp_net;
24275 		}
24276 	}
24277 
24278 	rw_exit(&tcps->tcps_hsp_lock);
24279 	return (hsp);
24280 }
24281 
24282 /*
24283  * Type three generator adapted from the random() function in 4.4 BSD:
24284  */
24285 
24286 /*
24287  * Copyright (c) 1983, 1993
24288  *	The Regents of the University of California.  All rights reserved.
24289  *
24290  * Redistribution and use in source and binary forms, with or without
24291  * modification, are permitted provided that the following conditions
24292  * are met:
24293  * 1. Redistributions of source code must retain the above copyright
24294  *    notice, this list of conditions and the following disclaimer.
24295  * 2. Redistributions in binary form must reproduce the above copyright
24296  *    notice, this list of conditions and the following disclaimer in the
24297  *    documentation and/or other materials provided with the distribution.
24298  * 3. All advertising materials mentioning features or use of this software
24299  *    must display the following acknowledgement:
24300  *	This product includes software developed by the University of
24301  *	California, Berkeley and its contributors.
24302  * 4. Neither the name of the University nor the names of its contributors
24303  *    may be used to endorse or promote products derived from this software
24304  *    without specific prior written permission.
24305  *
24306  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24307  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24308  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24309  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24310  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24311  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24312  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24313  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24314  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24315  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24316  * SUCH DAMAGE.
24317  */
24318 
24319 /* Type 3 -- x**31 + x**3 + 1 */
24320 #define	DEG_3		31
24321 #define	SEP_3		3
24322 
24323 
24324 /* Protected by tcp_random_lock */
24325 static int tcp_randtbl[DEG_3 + 1];
24326 
24327 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24328 static int *tcp_random_rptr = &tcp_randtbl[1];
24329 
24330 static int *tcp_random_state = &tcp_randtbl[1];
24331 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24332 
24333 kmutex_t tcp_random_lock;
24334 
24335 void
24336 tcp_random_init(void)
24337 {
24338 	int i;
24339 	hrtime_t hrt;
24340 	time_t wallclock;
24341 	uint64_t result;
24342 
24343 	/*
24344 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24345 	 * a longlong, which may contain resolution down to nanoseconds.
24346 	 * The current time will either be a 32-bit or a 64-bit quantity.
24347 	 * XOR the two together in a 64-bit result variable.
24348 	 * Convert the result to a 32-bit value by multiplying the high-order
24349 	 * 32-bits by the low-order 32-bits.
24350 	 */
24351 
24352 	hrt = gethrtime();
24353 	(void) drv_getparm(TIME, &wallclock);
24354 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24355 	mutex_enter(&tcp_random_lock);
24356 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24357 	    (result & 0xffffffff);
24358 
24359 	for (i = 1; i < DEG_3; i++)
24360 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24361 		    + 12345;
24362 	tcp_random_fptr = &tcp_random_state[SEP_3];
24363 	tcp_random_rptr = &tcp_random_state[0];
24364 	mutex_exit(&tcp_random_lock);
24365 	for (i = 0; i < 10 * DEG_3; i++)
24366 		(void) tcp_random();
24367 }
24368 
24369 /*
24370  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24371  * This range is selected to be approximately centered on TCP_ISS / 2,
24372  * and easy to compute. We get this value by generating a 32-bit random
24373  * number, selecting out the high-order 17 bits, and then adding one so
24374  * that we never return zero.
24375  */
24376 int
24377 tcp_random(void)
24378 {
24379 	int i;
24380 
24381 	mutex_enter(&tcp_random_lock);
24382 	*tcp_random_fptr += *tcp_random_rptr;
24383 
24384 	/*
24385 	 * The high-order bits are more random than the low-order bits,
24386 	 * so we select out the high-order 17 bits and add one so that
24387 	 * we never return zero.
24388 	 */
24389 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24390 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24391 		tcp_random_fptr = tcp_random_state;
24392 		++tcp_random_rptr;
24393 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24394 		tcp_random_rptr = tcp_random_state;
24395 
24396 	mutex_exit(&tcp_random_lock);
24397 	return (i);
24398 }
24399 
24400 static int
24401 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24402     int *t_errorp, int *sys_errorp)
24403 {
24404 	int error;
24405 	int is_absreq_failure;
24406 	t_scalar_t *opt_lenp;
24407 	t_scalar_t opt_offset;
24408 	int prim_type;
24409 	struct T_conn_req *tcreqp;
24410 	struct T_conn_res *tcresp;
24411 	cred_t *cr;
24412 
24413 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24414 
24415 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24416 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24417 	    prim_type == T_CONN_RES);
24418 
24419 	switch (prim_type) {
24420 	case T_CONN_REQ:
24421 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24422 		opt_offset = tcreqp->OPT_offset;
24423 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24424 		break;
24425 	case O_T_CONN_RES:
24426 	case T_CONN_RES:
24427 		tcresp = (struct T_conn_res *)mp->b_rptr;
24428 		opt_offset = tcresp->OPT_offset;
24429 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24430 		break;
24431 	}
24432 
24433 	*t_errorp = 0;
24434 	*sys_errorp = 0;
24435 	*do_disconnectp = 0;
24436 
24437 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24438 	    opt_offset, cr, &tcp_opt_obj,
24439 	    NULL, &is_absreq_failure);
24440 
24441 	switch (error) {
24442 	case  0:		/* no error */
24443 		ASSERT(is_absreq_failure == 0);
24444 		return (0);
24445 	case ENOPROTOOPT:
24446 		*t_errorp = TBADOPT;
24447 		break;
24448 	case EACCES:
24449 		*t_errorp = TACCES;
24450 		break;
24451 	default:
24452 		*t_errorp = TSYSERR; *sys_errorp = error;
24453 		break;
24454 	}
24455 	if (is_absreq_failure != 0) {
24456 		/*
24457 		 * The connection request should get the local ack
24458 		 * T_OK_ACK and then a T_DISCON_IND.
24459 		 */
24460 		*do_disconnectp = 1;
24461 	}
24462 	return (-1);
24463 }
24464 
24465 /*
24466  * Split this function out so that if the secret changes, I'm okay.
24467  *
24468  * Initialize the tcp_iss_cookie and tcp_iss_key.
24469  */
24470 
24471 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24472 
24473 static void
24474 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24475 {
24476 	struct {
24477 		int32_t current_time;
24478 		uint32_t randnum;
24479 		uint16_t pad;
24480 		uint8_t ether[6];
24481 		uint8_t passwd[PASSWD_SIZE];
24482 	} tcp_iss_cookie;
24483 	time_t t;
24484 
24485 	/*
24486 	 * Start with the current absolute time.
24487 	 */
24488 	(void) drv_getparm(TIME, &t);
24489 	tcp_iss_cookie.current_time = t;
24490 
24491 	/*
24492 	 * XXX - Need a more random number per RFC 1750, not this crap.
24493 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24494 	 */
24495 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24496 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24497 
24498 	/*
24499 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24500 	 * as a good template.
24501 	 */
24502 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24503 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24504 
24505 	/*
24506 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24507 	 */
24508 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24509 
24510 	/*
24511 	 * See 4010593 if this section becomes a problem again,
24512 	 * but the local ethernet address is useful here.
24513 	 */
24514 	(void) localetheraddr(NULL,
24515 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24516 
24517 	/*
24518 	 * Hash 'em all together.  The MD5Final is called per-connection.
24519 	 */
24520 	mutex_enter(&tcps->tcps_iss_key_lock);
24521 	MD5Init(&tcps->tcps_iss_key);
24522 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24523 	    sizeof (tcp_iss_cookie));
24524 	mutex_exit(&tcps->tcps_iss_key_lock);
24525 }
24526 
24527 /*
24528  * Set the RFC 1948 pass phrase
24529  */
24530 /* ARGSUSED */
24531 static int
24532 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24533     cred_t *cr)
24534 {
24535 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24536 
24537 	/*
24538 	 * Basically, value contains a new pass phrase.  Pass it along!
24539 	 */
24540 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24541 	return (0);
24542 }
24543 
24544 /* ARGSUSED */
24545 static int
24546 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24547 {
24548 	bzero(buf, sizeof (tcp_sack_info_t));
24549 	return (0);
24550 }
24551 
24552 /* ARGSUSED */
24553 static int
24554 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24555 {
24556 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24557 	return (0);
24558 }
24559 
24560 /*
24561  * Make sure we wait until the default queue is setup, yet allow
24562  * tcp_g_q_create() to open a TCP stream.
24563  * We need to allow tcp_g_q_create() do do an open
24564  * of tcp, hence we compare curhread.
24565  * All others have to wait until the tcps_g_q has been
24566  * setup.
24567  */
24568 void
24569 tcp_g_q_setup(tcp_stack_t *tcps)
24570 {
24571 	mutex_enter(&tcps->tcps_g_q_lock);
24572 	if (tcps->tcps_g_q != NULL) {
24573 		mutex_exit(&tcps->tcps_g_q_lock);
24574 		return;
24575 	}
24576 	if (tcps->tcps_g_q_creator == NULL) {
24577 		/* This thread will set it up */
24578 		tcps->tcps_g_q_creator = curthread;
24579 		mutex_exit(&tcps->tcps_g_q_lock);
24580 		tcp_g_q_create(tcps);
24581 		mutex_enter(&tcps->tcps_g_q_lock);
24582 		ASSERT(tcps->tcps_g_q_creator == curthread);
24583 		tcps->tcps_g_q_creator = NULL;
24584 		cv_signal(&tcps->tcps_g_q_cv);
24585 		ASSERT(tcps->tcps_g_q != NULL);
24586 		mutex_exit(&tcps->tcps_g_q_lock);
24587 		return;
24588 	}
24589 	/* Everybody but the creator has to wait */
24590 	if (tcps->tcps_g_q_creator != curthread) {
24591 		while (tcps->tcps_g_q == NULL)
24592 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24593 	}
24594 	mutex_exit(&tcps->tcps_g_q_lock);
24595 }
24596 
24597 #define	IP	"ip"
24598 
24599 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24600 
24601 /*
24602  * Create a default tcp queue here instead of in strplumb
24603  */
24604 void
24605 tcp_g_q_create(tcp_stack_t *tcps)
24606 {
24607 	int error;
24608 	ldi_handle_t	lh = NULL;
24609 	ldi_ident_t	li = NULL;
24610 	int		rval;
24611 	cred_t		*cr;
24612 	major_t IP_MAJ;
24613 
24614 #ifdef NS_DEBUG
24615 	(void) printf("tcp_g_q_create()\n");
24616 #endif
24617 
24618 	IP_MAJ = ddi_name_to_major(IP);
24619 
24620 	ASSERT(tcps->tcps_g_q_creator == curthread);
24621 
24622 	error = ldi_ident_from_major(IP_MAJ, &li);
24623 	if (error) {
24624 #ifdef DEBUG
24625 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24626 		    error);
24627 #endif
24628 		return;
24629 	}
24630 
24631 	cr = zone_get_kcred(netstackid_to_zoneid(
24632 	    tcps->tcps_netstack->netstack_stackid));
24633 	ASSERT(cr != NULL);
24634 	/*
24635 	 * We set the tcp default queue to IPv6 because IPv4 falls
24636 	 * back to IPv6 when it can't find a client, but
24637 	 * IPv6 does not fall back to IPv4.
24638 	 */
24639 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24640 	if (error) {
24641 #ifdef DEBUG
24642 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24643 		    error);
24644 #endif
24645 		goto out;
24646 	}
24647 
24648 	/*
24649 	 * This ioctl causes the tcp framework to cache a pointer to
24650 	 * this stream, so we don't want to close the stream after
24651 	 * this operation.
24652 	 * Use the kernel credentials that are for the zone we're in.
24653 	 */
24654 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24655 	    (intptr_t)0, FKIOCTL, cr, &rval);
24656 	if (error) {
24657 #ifdef DEBUG
24658 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24659 		    "error %d\n", error);
24660 #endif
24661 		goto out;
24662 	}
24663 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24664 	lh = NULL;
24665 out:
24666 	/* Close layered handles */
24667 	if (li)
24668 		ldi_ident_release(li);
24669 	/* Keep cred around until _inactive needs it */
24670 	tcps->tcps_g_q_cr = cr;
24671 }
24672 
24673 /*
24674  * We keep tcp_g_q set until all other tcp_t's in the zone
24675  * has gone away, and then when tcp_g_q_inactive() is called
24676  * we clear it.
24677  */
24678 void
24679 tcp_g_q_destroy(tcp_stack_t *tcps)
24680 {
24681 #ifdef NS_DEBUG
24682 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24683 	    tcps->tcps_netstack->netstack_stackid);
24684 #endif
24685 
24686 	if (tcps->tcps_g_q == NULL) {
24687 		return;	/* Nothing to cleanup */
24688 	}
24689 	/*
24690 	 * Drop reference corresponding to the default queue.
24691 	 * This reference was added from tcp_open when the default queue
24692 	 * was created, hence we compensate for this extra drop in
24693 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24694 	 * the default queue was the last one to be open, in which
24695 	 * case, then tcp_g_q_inactive will be
24696 	 * called as a result of the refrele.
24697 	 */
24698 	TCPS_REFRELE(tcps);
24699 }
24700 
24701 /*
24702  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24703  * Run by tcp_q_q_inactive using a taskq.
24704  */
24705 static void
24706 tcp_g_q_close(void *arg)
24707 {
24708 	tcp_stack_t *tcps = arg;
24709 	int error;
24710 	ldi_handle_t	lh = NULL;
24711 	ldi_ident_t	li = NULL;
24712 	cred_t		*cr;
24713 	major_t IP_MAJ;
24714 
24715 	IP_MAJ = ddi_name_to_major(IP);
24716 
24717 #ifdef NS_DEBUG
24718 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24719 	    tcps->tcps_netstack->netstack_stackid,
24720 	    tcps->tcps_netstack->netstack_refcnt);
24721 #endif
24722 	lh = tcps->tcps_g_q_lh;
24723 	if (lh == NULL)
24724 		return;	/* Nothing to cleanup */
24725 
24726 	ASSERT(tcps->tcps_refcnt == 1);
24727 	ASSERT(tcps->tcps_g_q != NULL);
24728 
24729 	error = ldi_ident_from_major(IP_MAJ, &li);
24730 	if (error) {
24731 #ifdef DEBUG
24732 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24733 		    error);
24734 #endif
24735 		return;
24736 	}
24737 
24738 	cr = tcps->tcps_g_q_cr;
24739 	tcps->tcps_g_q_cr = NULL;
24740 	ASSERT(cr != NULL);
24741 
24742 	/*
24743 	 * Make sure we can break the recursion when tcp_close decrements
24744 	 * the reference count causing g_q_inactive to be called again.
24745 	 */
24746 	tcps->tcps_g_q_lh = NULL;
24747 
24748 	/* close the default queue */
24749 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24750 	/*
24751 	 * At this point in time tcps and the rest of netstack_t might
24752 	 * have been deleted.
24753 	 */
24754 	tcps = NULL;
24755 
24756 	/* Close layered handles */
24757 	ldi_ident_release(li);
24758 	crfree(cr);
24759 }
24760 
24761 /*
24762  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24763  *
24764  * Have to ensure that the ldi routines are not used by an
24765  * interrupt thread by using a taskq.
24766  */
24767 void
24768 tcp_g_q_inactive(tcp_stack_t *tcps)
24769 {
24770 	if (tcps->tcps_g_q_lh == NULL)
24771 		return;	/* Nothing to cleanup */
24772 
24773 	ASSERT(tcps->tcps_refcnt == 0);
24774 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24775 
24776 	if (servicing_interrupt()) {
24777 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24778 		    (void *) tcps, TQ_SLEEP);
24779 	} else {
24780 		tcp_g_q_close(tcps);
24781 	}
24782 }
24783 
24784 /*
24785  * Called by IP when IP is loaded into the kernel
24786  */
24787 void
24788 tcp_ddi_g_init(void)
24789 {
24790 	tcp_timercache = kmem_cache_create("tcp_timercache",
24791 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24792 	    NULL, NULL, NULL, NULL, NULL, 0);
24793 
24794 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24795 	    sizeof (tcp_sack_info_t), 0,
24796 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24797 
24798 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24799 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24800 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24801 
24802 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24803 
24804 	/* Initialize the random number generator */
24805 	tcp_random_init();
24806 
24807 	/* A single callback independently of how many netstacks we have */
24808 	ip_squeue_init(tcp_squeue_add);
24809 
24810 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24811 
24812 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24813 	    TASKQ_PREPOPULATE);
24814 
24815 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24816 
24817 	/*
24818 	 * We want to be informed each time a stack is created or
24819 	 * destroyed in the kernel, so we can maintain the
24820 	 * set of tcp_stack_t's.
24821 	 */
24822 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24823 	    tcp_stack_fini);
24824 }
24825 
24826 
24827 #define	INET_NAME	"ip"
24828 
24829 /*
24830  * Initialize the TCP stack instance.
24831  */
24832 static void *
24833 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24834 {
24835 	tcp_stack_t	*tcps;
24836 	tcpparam_t	*pa;
24837 	int		i;
24838 	int		error = 0;
24839 	major_t		major;
24840 
24841 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24842 	tcps->tcps_netstack = ns;
24843 
24844 	/* Initialize locks */
24845 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24846 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24847 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24848 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24849 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24850 
24851 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24852 	tcps->tcps_g_epriv_ports[0] = 2049;
24853 	tcps->tcps_g_epriv_ports[1] = 4045;
24854 	tcps->tcps_min_anonpriv_port = 512;
24855 
24856 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24857 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24858 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24859 	    TCP_FANOUT_SIZE, KM_SLEEP);
24860 
24861 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24862 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24863 		    MUTEX_DEFAULT, NULL);
24864 	}
24865 
24866 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24867 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24868 		    MUTEX_DEFAULT, NULL);
24869 	}
24870 
24871 	/* TCP's IPsec code calls the packet dropper. */
24872 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24873 
24874 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24875 	tcps->tcps_params = pa;
24876 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24877 
24878 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24879 	    A_CNT(lcl_tcp_param_arr), tcps);
24880 
24881 	/*
24882 	 * Note: To really walk the device tree you need the devinfo
24883 	 * pointer to your device which is only available after probe/attach.
24884 	 * The following is safe only because it uses ddi_root_node()
24885 	 */
24886 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24887 	    tcp_opt_obj.odb_opt_arr_cnt);
24888 
24889 	/*
24890 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24891 	 * by the boot scripts.
24892 	 *
24893 	 * Use NULL name, as the name is caught by the new lockstats.
24894 	 *
24895 	 * Initialize with some random, non-guessable string, like the global
24896 	 * T_INFO_ACK.
24897 	 */
24898 
24899 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24900 	    sizeof (tcp_g_t_info_ack), tcps);
24901 
24902 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24903 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24904 
24905 	major = mod_name_to_major(INET_NAME);
24906 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24907 	ASSERT(error == 0);
24908 	return (tcps);
24909 }
24910 
24911 /*
24912  * Called when the IP module is about to be unloaded.
24913  */
24914 void
24915 tcp_ddi_g_destroy(void)
24916 {
24917 	tcp_g_kstat_fini(tcp_g_kstat);
24918 	tcp_g_kstat = NULL;
24919 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
24920 
24921 	mutex_destroy(&tcp_random_lock);
24922 
24923 	kmem_cache_destroy(tcp_timercache);
24924 	kmem_cache_destroy(tcp_sack_info_cache);
24925 	kmem_cache_destroy(tcp_iphc_cache);
24926 
24927 	netstack_unregister(NS_TCP);
24928 	taskq_destroy(tcp_taskq);
24929 }
24930 
24931 /*
24932  * Shut down the TCP stack instance.
24933  */
24934 /* ARGSUSED */
24935 static void
24936 tcp_stack_shutdown(netstackid_t stackid, void *arg)
24937 {
24938 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24939 
24940 	tcp_g_q_destroy(tcps);
24941 }
24942 
24943 /*
24944  * Free the TCP stack instance.
24945  */
24946 static void
24947 tcp_stack_fini(netstackid_t stackid, void *arg)
24948 {
24949 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
24950 	int i;
24951 
24952 	nd_free(&tcps->tcps_g_nd);
24953 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24954 	tcps->tcps_params = NULL;
24955 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
24956 	tcps->tcps_wroff_xtra_param = NULL;
24957 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
24958 	tcps->tcps_mdt_head_param = NULL;
24959 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
24960 	tcps->tcps_mdt_tail_param = NULL;
24961 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
24962 	tcps->tcps_mdt_max_pbufs_param = NULL;
24963 
24964 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24965 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
24966 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
24967 	}
24968 
24969 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24970 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
24971 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
24972 	}
24973 
24974 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
24975 	tcps->tcps_bind_fanout = NULL;
24976 
24977 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
24978 	tcps->tcps_acceptor_fanout = NULL;
24979 
24980 	mutex_destroy(&tcps->tcps_iss_key_lock);
24981 	rw_destroy(&tcps->tcps_hsp_lock);
24982 	mutex_destroy(&tcps->tcps_g_q_lock);
24983 	cv_destroy(&tcps->tcps_g_q_cv);
24984 	mutex_destroy(&tcps->tcps_epriv_port_lock);
24985 
24986 	ip_drop_unregister(&tcps->tcps_dropper);
24987 
24988 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
24989 	tcps->tcps_kstat = NULL;
24990 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
24991 
24992 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
24993 	tcps->tcps_mibkp = NULL;
24994 
24995 	ldi_ident_release(tcps->tcps_ldi_ident);
24996 	kmem_free(tcps, sizeof (*tcps));
24997 }
24998 
24999 /*
25000  * Generate ISS, taking into account NDD changes may happen halfway through.
25001  * (If the iss is not zero, set it.)
25002  */
25003 
25004 static void
25005 tcp_iss_init(tcp_t *tcp)
25006 {
25007 	MD5_CTX context;
25008 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25009 	uint32_t answer[4];
25010 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25011 
25012 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25013 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25014 	switch (tcps->tcps_strong_iss) {
25015 	case 2:
25016 		mutex_enter(&tcps->tcps_iss_key_lock);
25017 		context = tcps->tcps_iss_key;
25018 		mutex_exit(&tcps->tcps_iss_key_lock);
25019 		arg.ports = tcp->tcp_ports;
25020 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25021 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25022 			    &arg.src);
25023 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25024 			    &arg.dst);
25025 		} else {
25026 			arg.src = tcp->tcp_ip6h->ip6_src;
25027 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25028 		}
25029 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25030 		MD5Final((uchar_t *)answer, &context);
25031 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25032 		/*
25033 		 * Now that we've hashed into a unique per-connection sequence
25034 		 * space, add a random increment per strong_iss == 1.  So I
25035 		 * guess we'll have to...
25036 		 */
25037 		/* FALLTHRU */
25038 	case 1:
25039 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25040 		break;
25041 	default:
25042 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25043 		break;
25044 	}
25045 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25046 	tcp->tcp_fss = tcp->tcp_iss - 1;
25047 	tcp->tcp_suna = tcp->tcp_iss;
25048 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25049 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25050 	tcp->tcp_csuna = tcp->tcp_snxt;
25051 }
25052 
25053 /*
25054  * Exported routine for extracting active tcp connection status.
25055  *
25056  * This is used by the Solaris Cluster Networking software to
25057  * gather a list of connections that need to be forwarded to
25058  * specific nodes in the cluster when configuration changes occur.
25059  *
25060  * The callback is invoked for each tcp_t structure. Returning
25061  * non-zero from the callback routine terminates the search.
25062  */
25063 int
25064 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25065     void *arg)
25066 {
25067 	netstack_handle_t nh;
25068 	netstack_t *ns;
25069 	int ret = 0;
25070 
25071 	netstack_next_init(&nh);
25072 	while ((ns = netstack_next(&nh)) != NULL) {
25073 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25074 		    ns->netstack_tcp);
25075 		netstack_rele(ns);
25076 	}
25077 	netstack_next_fini(&nh);
25078 	return (ret);
25079 }
25080 
25081 static int
25082 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25083     tcp_stack_t *tcps)
25084 {
25085 	tcp_t *tcp;
25086 	cl_tcp_info_t	cl_tcpi;
25087 	connf_t	*connfp;
25088 	conn_t	*connp;
25089 	int	i;
25090 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25091 
25092 	ASSERT(callback != NULL);
25093 
25094 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25095 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25096 		connp = NULL;
25097 
25098 		while ((connp =
25099 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25100 
25101 			tcp = connp->conn_tcp;
25102 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25103 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25104 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25105 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25106 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25107 			/*
25108 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25109 			 * addresses. They are copied implicitly below as
25110 			 * mapped addresses.
25111 			 */
25112 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25113 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25114 				cl_tcpi.cl_tcpi_faddr =
25115 				    tcp->tcp_ipha->ipha_dst;
25116 			} else {
25117 				cl_tcpi.cl_tcpi_faddr_v6 =
25118 				    tcp->tcp_ip6h->ip6_dst;
25119 			}
25120 
25121 			/*
25122 			 * If the callback returns non-zero
25123 			 * we terminate the traversal.
25124 			 */
25125 			if ((*callback)(&cl_tcpi, arg) != 0) {
25126 				CONN_DEC_REF(tcp->tcp_connp);
25127 				return (1);
25128 			}
25129 		}
25130 	}
25131 
25132 	return (0);
25133 }
25134 
25135 /*
25136  * Macros used for accessing the different types of sockaddr
25137  * structures inside a tcp_ioc_abort_conn_t.
25138  */
25139 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25140 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25141 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25142 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25143 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25144 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25145 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25146 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25147 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25148 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25149 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25150 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25151 
25152 /*
25153  * Return the correct error code to mimic the behavior
25154  * of a connection reset.
25155  */
25156 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25157 		switch ((state)) {		\
25158 		case TCPS_SYN_SENT:		\
25159 		case TCPS_SYN_RCVD:		\
25160 			(err) = ECONNREFUSED;	\
25161 			break;			\
25162 		case TCPS_ESTABLISHED:		\
25163 		case TCPS_FIN_WAIT_1:		\
25164 		case TCPS_FIN_WAIT_2:		\
25165 		case TCPS_CLOSE_WAIT:		\
25166 			(err) = ECONNRESET;	\
25167 			break;			\
25168 		case TCPS_CLOSING:		\
25169 		case TCPS_LAST_ACK:		\
25170 		case TCPS_TIME_WAIT:		\
25171 			(err) = 0;		\
25172 			break;			\
25173 		default:			\
25174 			(err) = ENXIO;		\
25175 		}				\
25176 	}
25177 
25178 /*
25179  * Check if a tcp structure matches the info in acp.
25180  */
25181 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25182 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25183 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25184 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25185 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25186 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25187 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25188 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25189 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25190 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25191 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25192 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25193 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25194 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25195 	&(tcp)->tcp_ip_src_v6)) &&				\
25196 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25197 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25198 	&(tcp)->tcp_remote_v6)) &&				\
25199 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25200 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25201 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25202 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25203 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25204 	(acp)->ac_end >= (tcp)->tcp_state))
25205 
25206 #define	TCP_AC_MATCH(acp, tcp)					\
25207 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25208 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25209 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25210 
25211 /*
25212  * Build a message containing a tcp_ioc_abort_conn_t structure
25213  * which is filled in with information from acp and tp.
25214  */
25215 static mblk_t *
25216 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25217 {
25218 	mblk_t *mp;
25219 	tcp_ioc_abort_conn_t *tacp;
25220 
25221 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25222 	if (mp == NULL)
25223 		return (NULL);
25224 
25225 	mp->b_datap->db_type = M_CTL;
25226 
25227 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25228 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25229 	    sizeof (uint32_t));
25230 
25231 	tacp->ac_start = acp->ac_start;
25232 	tacp->ac_end = acp->ac_end;
25233 	tacp->ac_zoneid = acp->ac_zoneid;
25234 
25235 	if (acp->ac_local.ss_family == AF_INET) {
25236 		tacp->ac_local.ss_family = AF_INET;
25237 		tacp->ac_remote.ss_family = AF_INET;
25238 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25239 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25240 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25241 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25242 	} else {
25243 		tacp->ac_local.ss_family = AF_INET6;
25244 		tacp->ac_remote.ss_family = AF_INET6;
25245 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25246 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25247 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25248 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25249 	}
25250 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25251 	return (mp);
25252 }
25253 
25254 /*
25255  * Print a tcp_ioc_abort_conn_t structure.
25256  */
25257 static void
25258 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25259 {
25260 	char lbuf[128];
25261 	char rbuf[128];
25262 	sa_family_t af;
25263 	in_port_t lport, rport;
25264 	ushort_t logflags;
25265 
25266 	af = acp->ac_local.ss_family;
25267 
25268 	if (af == AF_INET) {
25269 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25270 		    lbuf, 128);
25271 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25272 		    rbuf, 128);
25273 		lport = ntohs(TCP_AC_V4LPORT(acp));
25274 		rport = ntohs(TCP_AC_V4RPORT(acp));
25275 	} else {
25276 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25277 		    lbuf, 128);
25278 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25279 		    rbuf, 128);
25280 		lport = ntohs(TCP_AC_V6LPORT(acp));
25281 		rport = ntohs(TCP_AC_V6RPORT(acp));
25282 	}
25283 
25284 	logflags = SL_TRACE | SL_NOTE;
25285 	/*
25286 	 * Don't print this message to the console if the operation was done
25287 	 * to a non-global zone.
25288 	 */
25289 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25290 		logflags |= SL_CONSOLE;
25291 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25292 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25293 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25294 	    acp->ac_start, acp->ac_end);
25295 }
25296 
25297 /*
25298  * Called inside tcp_rput when a message built using
25299  * tcp_ioctl_abort_build_msg is put into a queue.
25300  * Note that when we get here there is no wildcard in acp any more.
25301  */
25302 static void
25303 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25304 {
25305 	tcp_ioc_abort_conn_t *acp;
25306 
25307 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25308 	if (tcp->tcp_state <= acp->ac_end) {
25309 		/*
25310 		 * If we get here, we are already on the correct
25311 		 * squeue. This ioctl follows the following path
25312 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25313 		 * ->tcp_ioctl_abort->squeue_enter (if on a
25314 		 * different squeue)
25315 		 */
25316 		int errcode;
25317 
25318 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25319 		(void) tcp_clean_death(tcp, errcode, 26);
25320 	}
25321 	freemsg(mp);
25322 }
25323 
25324 /*
25325  * Abort all matching connections on a hash chain.
25326  */
25327 static int
25328 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25329     boolean_t exact, tcp_stack_t *tcps)
25330 {
25331 	int nmatch, err = 0;
25332 	tcp_t *tcp;
25333 	MBLKP mp, last, listhead = NULL;
25334 	conn_t	*tconnp;
25335 	connf_t	*connfp;
25336 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25337 
25338 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25339 
25340 startover:
25341 	nmatch = 0;
25342 
25343 	mutex_enter(&connfp->connf_lock);
25344 	for (tconnp = connfp->connf_head; tconnp != NULL;
25345 	    tconnp = tconnp->conn_next) {
25346 		tcp = tconnp->conn_tcp;
25347 		if (TCP_AC_MATCH(acp, tcp)) {
25348 			CONN_INC_REF(tcp->tcp_connp);
25349 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25350 			if (mp == NULL) {
25351 				err = ENOMEM;
25352 				CONN_DEC_REF(tcp->tcp_connp);
25353 				break;
25354 			}
25355 			mp->b_prev = (mblk_t *)tcp;
25356 
25357 			if (listhead == NULL) {
25358 				listhead = mp;
25359 				last = mp;
25360 			} else {
25361 				last->b_next = mp;
25362 				last = mp;
25363 			}
25364 			nmatch++;
25365 			if (exact)
25366 				break;
25367 		}
25368 
25369 		/* Avoid holding lock for too long. */
25370 		if (nmatch >= 500)
25371 			break;
25372 	}
25373 	mutex_exit(&connfp->connf_lock);
25374 
25375 	/* Pass mp into the correct tcp */
25376 	while ((mp = listhead) != NULL) {
25377 		listhead = listhead->b_next;
25378 		tcp = (tcp_t *)mp->b_prev;
25379 		mp->b_next = mp->b_prev = NULL;
25380 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
25381 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
25382 	}
25383 
25384 	*count += nmatch;
25385 	if (nmatch >= 500 && err == 0)
25386 		goto startover;
25387 	return (err);
25388 }
25389 
25390 /*
25391  * Abort all connections that matches the attributes specified in acp.
25392  */
25393 static int
25394 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25395 {
25396 	sa_family_t af;
25397 	uint32_t  ports;
25398 	uint16_t *pports;
25399 	int err = 0, count = 0;
25400 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25401 	int index = -1;
25402 	ushort_t logflags;
25403 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25404 
25405 	af = acp->ac_local.ss_family;
25406 
25407 	if (af == AF_INET) {
25408 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25409 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25410 			pports = (uint16_t *)&ports;
25411 			pports[1] = TCP_AC_V4LPORT(acp);
25412 			pports[0] = TCP_AC_V4RPORT(acp);
25413 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25414 		}
25415 	} else {
25416 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25417 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25418 			pports = (uint16_t *)&ports;
25419 			pports[1] = TCP_AC_V6LPORT(acp);
25420 			pports[0] = TCP_AC_V6RPORT(acp);
25421 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25422 		}
25423 	}
25424 
25425 	/*
25426 	 * For cases where remote addr, local port, and remote port are non-
25427 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25428 	 */
25429 	if (index != -1) {
25430 		err = tcp_ioctl_abort_bucket(acp, index,
25431 		    &count, exact, tcps);
25432 	} else {
25433 		/*
25434 		 * loop through all entries for wildcard case
25435 		 */
25436 		for (index = 0;
25437 		    index < ipst->ips_ipcl_conn_fanout_size;
25438 		    index++) {
25439 			err = tcp_ioctl_abort_bucket(acp, index,
25440 			    &count, exact, tcps);
25441 			if (err != 0)
25442 				break;
25443 		}
25444 	}
25445 
25446 	logflags = SL_TRACE | SL_NOTE;
25447 	/*
25448 	 * Don't print this message to the console if the operation was done
25449 	 * to a non-global zone.
25450 	 */
25451 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25452 		logflags |= SL_CONSOLE;
25453 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25454 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25455 	if (err == 0 && count == 0)
25456 		err = ENOENT;
25457 	return (err);
25458 }
25459 
25460 /*
25461  * Process the TCP_IOC_ABORT_CONN ioctl request.
25462  */
25463 static void
25464 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25465 {
25466 	int	err;
25467 	IOCP    iocp;
25468 	MBLKP   mp1;
25469 	sa_family_t laf, raf;
25470 	tcp_ioc_abort_conn_t *acp;
25471 	zone_t		*zptr;
25472 	conn_t		*connp = Q_TO_CONN(q);
25473 	zoneid_t	zoneid = connp->conn_zoneid;
25474 	tcp_t		*tcp = connp->conn_tcp;
25475 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25476 
25477 	iocp = (IOCP)mp->b_rptr;
25478 
25479 	if ((mp1 = mp->b_cont) == NULL ||
25480 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25481 		err = EINVAL;
25482 		goto out;
25483 	}
25484 
25485 	/* check permissions */
25486 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25487 		err = EPERM;
25488 		goto out;
25489 	}
25490 
25491 	if (mp1->b_cont != NULL) {
25492 		freemsg(mp1->b_cont);
25493 		mp1->b_cont = NULL;
25494 	}
25495 
25496 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25497 	laf = acp->ac_local.ss_family;
25498 	raf = acp->ac_remote.ss_family;
25499 
25500 	/* check that a zone with the supplied zoneid exists */
25501 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25502 		zptr = zone_find_by_id(zoneid);
25503 		if (zptr != NULL) {
25504 			zone_rele(zptr);
25505 		} else {
25506 			err = EINVAL;
25507 			goto out;
25508 		}
25509 	}
25510 
25511 	/*
25512 	 * For exclusive stacks we set the zoneid to zero
25513 	 * to make TCP operate as if in the global zone.
25514 	 */
25515 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25516 		acp->ac_zoneid = GLOBAL_ZONEID;
25517 
25518 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25519 	    acp->ac_start > acp->ac_end || laf != raf ||
25520 	    (laf != AF_INET && laf != AF_INET6)) {
25521 		err = EINVAL;
25522 		goto out;
25523 	}
25524 
25525 	tcp_ioctl_abort_dump(acp);
25526 	err = tcp_ioctl_abort(acp, tcps);
25527 
25528 out:
25529 	if (mp1 != NULL) {
25530 		freemsg(mp1);
25531 		mp->b_cont = NULL;
25532 	}
25533 
25534 	if (err != 0)
25535 		miocnak(q, mp, 0, err);
25536 	else
25537 		miocack(q, mp, 0, 0);
25538 }
25539 
25540 /*
25541  * tcp_time_wait_processing() handles processing of incoming packets when
25542  * the tcp is in the TIME_WAIT state.
25543  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25544  * on the time wait list.
25545  */
25546 void
25547 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25548     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25549 {
25550 	int32_t		bytes_acked;
25551 	int32_t		gap;
25552 	int32_t		rgap;
25553 	tcp_opt_t	tcpopt;
25554 	uint_t		flags;
25555 	uint32_t	new_swnd = 0;
25556 	conn_t		*connp;
25557 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25558 
25559 	BUMP_LOCAL(tcp->tcp_ibsegs);
25560 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25561 
25562 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25563 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25564 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25565 	if (tcp->tcp_snd_ts_ok) {
25566 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25567 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25568 			    tcp->tcp_rnxt, TH_ACK);
25569 			goto done;
25570 		}
25571 	}
25572 	gap = seg_seq - tcp->tcp_rnxt;
25573 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25574 	if (gap < 0) {
25575 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25576 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25577 		    (seg_len > -gap ? -gap : seg_len));
25578 		seg_len += gap;
25579 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25580 			if (flags & TH_RST) {
25581 				goto done;
25582 			}
25583 			if ((flags & TH_FIN) && seg_len == -1) {
25584 				/*
25585 				 * When TCP receives a duplicate FIN in
25586 				 * TIME_WAIT state, restart the 2 MSL timer.
25587 				 * See page 73 in RFC 793. Make sure this TCP
25588 				 * is already on the TIME_WAIT list. If not,
25589 				 * just restart the timer.
25590 				 */
25591 				if (TCP_IS_DETACHED(tcp)) {
25592 					if (tcp_time_wait_remove(tcp, NULL) ==
25593 					    B_TRUE) {
25594 						tcp_time_wait_append(tcp);
25595 						TCP_DBGSTAT(tcps,
25596 						    tcp_rput_time_wait);
25597 					}
25598 				} else {
25599 					ASSERT(tcp != NULL);
25600 					TCP_TIMER_RESTART(tcp,
25601 					    tcps->tcps_time_wait_interval);
25602 				}
25603 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25604 				    tcp->tcp_rnxt, TH_ACK);
25605 				goto done;
25606 			}
25607 			flags |=  TH_ACK_NEEDED;
25608 			seg_len = 0;
25609 			goto process_ack;
25610 		}
25611 
25612 		/* Fix seg_seq, and chew the gap off the front. */
25613 		seg_seq = tcp->tcp_rnxt;
25614 	}
25615 
25616 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25617 		/*
25618 		 * Make sure that when we accept the connection, pick
25619 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25620 		 * old connection.
25621 		 *
25622 		 * The next ISS generated is equal to tcp_iss_incr_extra
25623 		 * + ISS_INCR/2 + other components depending on the
25624 		 * value of tcp_strong_iss.  We pre-calculate the new
25625 		 * ISS here and compare with tcp_snxt to determine if
25626 		 * we need to make adjustment to tcp_iss_incr_extra.
25627 		 *
25628 		 * The above calculation is ugly and is a
25629 		 * waste of CPU cycles...
25630 		 */
25631 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25632 		int32_t adj;
25633 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25634 
25635 		switch (tcps->tcps_strong_iss) {
25636 		case 2: {
25637 			/* Add time and MD5 components. */
25638 			uint32_t answer[4];
25639 			struct {
25640 				uint32_t ports;
25641 				in6_addr_t src;
25642 				in6_addr_t dst;
25643 			} arg;
25644 			MD5_CTX context;
25645 
25646 			mutex_enter(&tcps->tcps_iss_key_lock);
25647 			context = tcps->tcps_iss_key;
25648 			mutex_exit(&tcps->tcps_iss_key_lock);
25649 			arg.ports = tcp->tcp_ports;
25650 			/* We use MAPPED addresses in tcp_iss_init */
25651 			arg.src = tcp->tcp_ip_src_v6;
25652 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25653 				IN6_IPADDR_TO_V4MAPPED(
25654 				    tcp->tcp_ipha->ipha_dst,
25655 				    &arg.dst);
25656 			} else {
25657 				arg.dst =
25658 				    tcp->tcp_ip6h->ip6_dst;
25659 			}
25660 			MD5Update(&context, (uchar_t *)&arg,
25661 			    sizeof (arg));
25662 			MD5Final((uchar_t *)answer, &context);
25663 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25664 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25665 			break;
25666 		}
25667 		case 1:
25668 			/* Add time component and min random (i.e. 1). */
25669 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25670 			break;
25671 		default:
25672 			/* Add only time component. */
25673 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25674 			break;
25675 		}
25676 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25677 			/*
25678 			 * New ISS not guaranteed to be ISS_INCR/2
25679 			 * ahead of the current tcp_snxt, so add the
25680 			 * difference to tcp_iss_incr_extra.
25681 			 */
25682 			tcps->tcps_iss_incr_extra += adj;
25683 		}
25684 		/*
25685 		 * If tcp_clean_death() can not perform the task now,
25686 		 * drop the SYN packet and let the other side re-xmit.
25687 		 * Otherwise pass the SYN packet back in, since the
25688 		 * old tcp state has been cleaned up or freed.
25689 		 */
25690 		if (tcp_clean_death(tcp, 0, 27) == -1)
25691 			goto done;
25692 		/*
25693 		 * We will come back to tcp_rput_data
25694 		 * on the global queue. Packets destined
25695 		 * for the global queue will be checked
25696 		 * with global policy. But the policy for
25697 		 * this packet has already been checked as
25698 		 * this was destined for the detached
25699 		 * connection. We need to bypass policy
25700 		 * check this time by attaching a dummy
25701 		 * ipsec_in with ipsec_in_dont_check set.
25702 		 */
25703 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25704 		if (connp != NULL) {
25705 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25706 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25707 			return;
25708 		}
25709 		goto done;
25710 	}
25711 
25712 	/*
25713 	 * rgap is the amount of stuff received out of window.  A negative
25714 	 * value is the amount out of window.
25715 	 */
25716 	if (rgap < 0) {
25717 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25718 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25719 		/* Fix seg_len and make sure there is something left. */
25720 		seg_len += rgap;
25721 		if (seg_len <= 0) {
25722 			if (flags & TH_RST) {
25723 				goto done;
25724 			}
25725 			flags |=  TH_ACK_NEEDED;
25726 			seg_len = 0;
25727 			goto process_ack;
25728 		}
25729 	}
25730 	/*
25731 	 * Check whether we can update tcp_ts_recent.  This test is
25732 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25733 	 * Extensions for High Performance: An Update", Internet Draft.
25734 	 */
25735 	if (tcp->tcp_snd_ts_ok &&
25736 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25737 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25738 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25739 		tcp->tcp_last_rcv_lbolt = lbolt64;
25740 	}
25741 
25742 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25743 		/* Always ack out of order packets */
25744 		flags |= TH_ACK_NEEDED;
25745 		seg_len = 0;
25746 	} else if (seg_len > 0) {
25747 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25748 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25749 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25750 	}
25751 	if (flags & TH_RST) {
25752 		(void) tcp_clean_death(tcp, 0, 28);
25753 		goto done;
25754 	}
25755 	if (flags & TH_SYN) {
25756 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25757 		    TH_RST|TH_ACK);
25758 		/*
25759 		 * Do not delete the TCP structure if it is in
25760 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25761 		 */
25762 		goto done;
25763 	}
25764 process_ack:
25765 	if (flags & TH_ACK) {
25766 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25767 		if (bytes_acked <= 0) {
25768 			if (bytes_acked == 0 && seg_len == 0 &&
25769 			    new_swnd == tcp->tcp_swnd)
25770 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25771 		} else {
25772 			/* Acks something not sent */
25773 			flags |= TH_ACK_NEEDED;
25774 		}
25775 	}
25776 	if (flags & TH_ACK_NEEDED) {
25777 		/*
25778 		 * Time to send an ack for some reason.
25779 		 */
25780 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25781 		    tcp->tcp_rnxt, TH_ACK);
25782 	}
25783 done:
25784 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25785 		DB_CKSUMSTART(mp) = 0;
25786 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25787 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25788 	}
25789 	freemsg(mp);
25790 }
25791 
25792 /*
25793  * TCP Timers Implementation.
25794  */
25795 timeout_id_t
25796 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25797 {
25798 	mblk_t *mp;
25799 	tcp_timer_t *tcpt;
25800 	tcp_t *tcp = connp->conn_tcp;
25801 
25802 	ASSERT(connp->conn_sqp != NULL);
25803 
25804 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
25805 
25806 	if (tcp->tcp_timercache == NULL) {
25807 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25808 	} else {
25809 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
25810 		mp = tcp->tcp_timercache;
25811 		tcp->tcp_timercache = mp->b_next;
25812 		mp->b_next = NULL;
25813 		ASSERT(mp->b_wptr == NULL);
25814 	}
25815 
25816 	CONN_INC_REF(connp);
25817 	tcpt = (tcp_timer_t *)mp->b_rptr;
25818 	tcpt->connp = connp;
25819 	tcpt->tcpt_proc = f;
25820 	/*
25821 	 * TCP timers are normal timeouts. Plus, they do not require more than
25822 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25823 	 * rounding up the expiration to the next resolution boundary, we can
25824 	 * batch timers in the callout subsystem to make TCP timers more
25825 	 * efficient. The roundup also protects short timers from expiring too
25826 	 * early before they have a chance to be cancelled.
25827 	 */
25828 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25829 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25830 
25831 	return ((timeout_id_t)mp);
25832 }
25833 
25834 static void
25835 tcp_timer_callback(void *arg)
25836 {
25837 	mblk_t *mp = (mblk_t *)arg;
25838 	tcp_timer_t *tcpt;
25839 	conn_t	*connp;
25840 
25841 	tcpt = (tcp_timer_t *)mp->b_rptr;
25842 	connp = tcpt->connp;
25843 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
25844 	    SQ_FILL, SQTAG_TCP_TIMER);
25845 }
25846 
25847 static void
25848 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25849 {
25850 	tcp_timer_t *tcpt;
25851 	conn_t *connp = (conn_t *)arg;
25852 	tcp_t *tcp = connp->conn_tcp;
25853 
25854 	tcpt = (tcp_timer_t *)mp->b_rptr;
25855 	ASSERT(connp == tcpt->connp);
25856 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25857 
25858 	/*
25859 	 * If the TCP has reached the closed state, don't proceed any
25860 	 * further. This TCP logically does not exist on the system.
25861 	 * tcpt_proc could for example access queues, that have already
25862 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25863 	 */
25864 	if (tcp->tcp_state != TCPS_CLOSED) {
25865 		(*tcpt->tcpt_proc)(connp);
25866 	} else {
25867 		tcp->tcp_timer_tid = 0;
25868 	}
25869 	tcp_timer_free(connp->conn_tcp, mp);
25870 }
25871 
25872 /*
25873  * There is potential race with untimeout and the handler firing at the same
25874  * time. The mblock may be freed by the handler while we are trying to use
25875  * it. But since both should execute on the same squeue, this race should not
25876  * occur.
25877  */
25878 clock_t
25879 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25880 {
25881 	mblk_t	*mp = (mblk_t *)id;
25882 	tcp_timer_t *tcpt;
25883 	clock_t delta;
25884 
25885 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25886 
25887 	if (mp == NULL)
25888 		return (-1);
25889 
25890 	tcpt = (tcp_timer_t *)mp->b_rptr;
25891 	ASSERT(tcpt->connp == connp);
25892 
25893 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25894 
25895 	if (delta >= 0) {
25896 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
25897 		tcp_timer_free(connp->conn_tcp, mp);
25898 		CONN_DEC_REF(connp);
25899 	}
25900 
25901 	return (delta);
25902 }
25903 
25904 /*
25905  * Allocate space for the timer event. The allocation looks like mblk, but it is
25906  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
25907  *
25908  * Dealing with failures: If we can't allocate from the timer cache we try
25909  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
25910  * points to b_rptr.
25911  * If we can't allocate anything using allocb_tryhard(), we perform a last
25912  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
25913  * save the actual allocation size in b_datap.
25914  */
25915 mblk_t *
25916 tcp_timermp_alloc(int kmflags)
25917 {
25918 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
25919 	    kmflags & ~KM_PANIC);
25920 
25921 	if (mp != NULL) {
25922 		mp->b_next = mp->b_prev = NULL;
25923 		mp->b_rptr = (uchar_t *)(&mp[1]);
25924 		mp->b_wptr = NULL;
25925 		mp->b_datap = NULL;
25926 		mp->b_queue = NULL;
25927 		mp->b_cont = NULL;
25928 	} else if (kmflags & KM_PANIC) {
25929 		/*
25930 		 * Failed to allocate memory for the timer. Try allocating from
25931 		 * dblock caches.
25932 		 */
25933 		/* ipclassifier calls this from a constructor - hence no tcps */
25934 		TCP_G_STAT(tcp_timermp_allocfail);
25935 		mp = allocb_tryhard(sizeof (tcp_timer_t));
25936 		if (mp == NULL) {
25937 			size_t size = 0;
25938 			/*
25939 			 * Memory is really low. Try tryhard allocation.
25940 			 *
25941 			 * ipclassifier calls this from a constructor -
25942 			 * hence no tcps
25943 			 */
25944 			TCP_G_STAT(tcp_timermp_allocdblfail);
25945 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
25946 			    sizeof (tcp_timer_t), &size, kmflags);
25947 			mp->b_rptr = (uchar_t *)(&mp[1]);
25948 			mp->b_next = mp->b_prev = NULL;
25949 			mp->b_wptr = (uchar_t *)-1;
25950 			mp->b_datap = (dblk_t *)size;
25951 			mp->b_queue = NULL;
25952 			mp->b_cont = NULL;
25953 		}
25954 		ASSERT(mp->b_wptr != NULL);
25955 	}
25956 	/* ipclassifier calls this from a constructor - hence no tcps */
25957 	TCP_G_DBGSTAT(tcp_timermp_alloced);
25958 
25959 	return (mp);
25960 }
25961 
25962 /*
25963  * Free per-tcp timer cache.
25964  * It can only contain entries from tcp_timercache.
25965  */
25966 void
25967 tcp_timermp_free(tcp_t *tcp)
25968 {
25969 	mblk_t *mp;
25970 
25971 	while ((mp = tcp->tcp_timercache) != NULL) {
25972 		ASSERT(mp->b_wptr == NULL);
25973 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
25974 		kmem_cache_free(tcp_timercache, mp);
25975 	}
25976 }
25977 
25978 /*
25979  * Free timer event. Put it on the per-tcp timer cache if there is not too many
25980  * events there already (currently at most two events are cached).
25981  * If the event is not allocated from the timer cache, free it right away.
25982  */
25983 static void
25984 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
25985 {
25986 	mblk_t *mp1 = tcp->tcp_timercache;
25987 
25988 	if (mp->b_wptr != NULL) {
25989 		/*
25990 		 * This allocation is not from a timer cache, free it right
25991 		 * away.
25992 		 */
25993 		if (mp->b_wptr != (uchar_t *)-1)
25994 			freeb(mp);
25995 		else
25996 			kmem_free(mp, (size_t)mp->b_datap);
25997 	} else if (mp1 == NULL || mp1->b_next == NULL) {
25998 		/* Cache this timer block for future allocations */
25999 		mp->b_rptr = (uchar_t *)(&mp[1]);
26000 		mp->b_next = mp1;
26001 		tcp->tcp_timercache = mp;
26002 	} else {
26003 		kmem_cache_free(tcp_timercache, mp);
26004 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
26005 	}
26006 }
26007 
26008 /*
26009  * End of TCP Timers implementation.
26010  */
26011 
26012 /*
26013  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26014  * on the specified backing STREAMS q. Note, the caller may make the
26015  * decision to call based on the tcp_t.tcp_flow_stopped value which
26016  * when check outside the q's lock is only an advisory check ...
26017  */
26018 void
26019 tcp_setqfull(tcp_t *tcp)
26020 {
26021 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26022 	conn_t	*connp = tcp->tcp_connp;
26023 
26024 	if (tcp->tcp_closed)
26025 		return;
26026 
26027 	if (IPCL_IS_NONSTR(connp)) {
26028 		(*connp->conn_upcalls->su_txq_full)
26029 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
26030 		tcp->tcp_flow_stopped = B_TRUE;
26031 	} else {
26032 		queue_t *q = tcp->tcp_wq;
26033 
26034 		if (!(q->q_flag & QFULL)) {
26035 			mutex_enter(QLOCK(q));
26036 			if (!(q->q_flag & QFULL)) {
26037 				/* still need to set QFULL */
26038 				q->q_flag |= QFULL;
26039 				tcp->tcp_flow_stopped = B_TRUE;
26040 				mutex_exit(QLOCK(q));
26041 				TCP_STAT(tcps, tcp_flwctl_on);
26042 			} else {
26043 				mutex_exit(QLOCK(q));
26044 			}
26045 		}
26046 	}
26047 }
26048 
26049 void
26050 tcp_clrqfull(tcp_t *tcp)
26051 {
26052 	conn_t  *connp = tcp->tcp_connp;
26053 
26054 	if (tcp->tcp_closed)
26055 		return;
26056 
26057 	if (IPCL_IS_NONSTR(connp)) {
26058 		(*connp->conn_upcalls->su_txq_full)
26059 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
26060 		tcp->tcp_flow_stopped = B_FALSE;
26061 	} else {
26062 		queue_t *q = tcp->tcp_wq;
26063 
26064 		if (q->q_flag & QFULL) {
26065 			mutex_enter(QLOCK(q));
26066 			if (q->q_flag & QFULL) {
26067 				q->q_flag &= ~QFULL;
26068 				tcp->tcp_flow_stopped = B_FALSE;
26069 				mutex_exit(QLOCK(q));
26070 				if (q->q_flag & QWANTW)
26071 					qbackenable(q, 0);
26072 			} else {
26073 				mutex_exit(QLOCK(q));
26074 			}
26075 		}
26076 	}
26077 }
26078 
26079 /*
26080  * kstats related to squeues i.e. not per IP instance
26081  */
26082 static void *
26083 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26084 {
26085 	kstat_t *ksp;
26086 
26087 	tcp_g_stat_t template = {
26088 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26089 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26090 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26091 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26092 	};
26093 
26094 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26095 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26096 	    KSTAT_FLAG_VIRTUAL);
26097 
26098 	if (ksp == NULL)
26099 		return (NULL);
26100 
26101 	bcopy(&template, tcp_g_statp, sizeof (template));
26102 	ksp->ks_data = (void *)tcp_g_statp;
26103 
26104 	kstat_install(ksp);
26105 	return (ksp);
26106 }
26107 
26108 static void
26109 tcp_g_kstat_fini(kstat_t *ksp)
26110 {
26111 	if (ksp != NULL) {
26112 		kstat_delete(ksp);
26113 	}
26114 }
26115 
26116 
26117 static void *
26118 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26119 {
26120 	kstat_t *ksp;
26121 
26122 	tcp_stat_t template = {
26123 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26124 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26125 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26126 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26127 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26128 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26129 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26130 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26131 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26132 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26133 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26134 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26135 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26136 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26137 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26138 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26139 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26140 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26141 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26142 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26143 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26144 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26145 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26146 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26147 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26148 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26149 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26150 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26151 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26152 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26153 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26154 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26155 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26156 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26157 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26158 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26159 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26160 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26161 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26162 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26163 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26164 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26165 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26166 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26167 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26168 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26169 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26170 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26171 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26172 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26173 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26174 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26175 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26176 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26177 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26178 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26179 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26180 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26181 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26182 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26183 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26184 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26185 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26186 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26187 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26188 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26189 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26190 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26191 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26192 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26193 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26194 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26195 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26196 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26197 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26198 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26199 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26200 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26201 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26202 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26203 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26204 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26205 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26206 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26207 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26208 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26209 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26210 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26211 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26212 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26213 	};
26214 
26215 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26216 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26217 	    KSTAT_FLAG_VIRTUAL, stackid);
26218 
26219 	if (ksp == NULL)
26220 		return (NULL);
26221 
26222 	bcopy(&template, tcps_statisticsp, sizeof (template));
26223 	ksp->ks_data = (void *)tcps_statisticsp;
26224 	ksp->ks_private = (void *)(uintptr_t)stackid;
26225 
26226 	kstat_install(ksp);
26227 	return (ksp);
26228 }
26229 
26230 static void
26231 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26232 {
26233 	if (ksp != NULL) {
26234 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26235 		kstat_delete_netstack(ksp, stackid);
26236 	}
26237 }
26238 
26239 /*
26240  * TCP Kstats implementation
26241  */
26242 static void *
26243 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26244 {
26245 	kstat_t	*ksp;
26246 
26247 	tcp_named_kstat_t template = {
26248 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26249 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26250 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26251 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26252 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26253 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26254 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26255 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26256 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26257 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26258 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26259 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26260 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26261 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26262 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26263 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26264 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26265 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26266 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26267 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26268 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26269 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26270 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26271 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26272 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26273 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26274 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26275 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26276 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26277 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26278 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26279 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26280 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26281 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26282 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26283 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26284 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26285 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26286 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26287 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26288 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26289 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26290 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26291 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26292 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26293 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26294 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26295 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26296 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26297 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26298 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26299 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26300 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26301 	};
26302 
26303 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26304 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26305 
26306 	if (ksp == NULL)
26307 		return (NULL);
26308 
26309 	template.rtoAlgorithm.value.ui32 = 4;
26310 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26311 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26312 	template.maxConn.value.i32 = -1;
26313 
26314 	bcopy(&template, ksp->ks_data, sizeof (template));
26315 	ksp->ks_update = tcp_kstat_update;
26316 	ksp->ks_private = (void *)(uintptr_t)stackid;
26317 
26318 	kstat_install(ksp);
26319 	return (ksp);
26320 }
26321 
26322 static void
26323 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26324 {
26325 	if (ksp != NULL) {
26326 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26327 		kstat_delete_netstack(ksp, stackid);
26328 	}
26329 }
26330 
26331 static int
26332 tcp_kstat_update(kstat_t *kp, int rw)
26333 {
26334 	tcp_named_kstat_t *tcpkp;
26335 	tcp_t		*tcp;
26336 	connf_t		*connfp;
26337 	conn_t		*connp;
26338 	int 		i;
26339 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26340 	netstack_t	*ns;
26341 	tcp_stack_t	*tcps;
26342 	ip_stack_t	*ipst;
26343 
26344 	if ((kp == NULL) || (kp->ks_data == NULL))
26345 		return (EIO);
26346 
26347 	if (rw == KSTAT_WRITE)
26348 		return (EACCES);
26349 
26350 	ns = netstack_find_by_stackid(stackid);
26351 	if (ns == NULL)
26352 		return (-1);
26353 	tcps = ns->netstack_tcp;
26354 	if (tcps == NULL) {
26355 		netstack_rele(ns);
26356 		return (-1);
26357 	}
26358 
26359 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26360 
26361 	tcpkp->currEstab.value.ui32 = 0;
26362 
26363 	ipst = ns->netstack_ip;
26364 
26365 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26366 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26367 		connp = NULL;
26368 		while ((connp =
26369 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26370 			tcp = connp->conn_tcp;
26371 			switch (tcp_snmp_state(tcp)) {
26372 			case MIB2_TCP_established:
26373 			case MIB2_TCP_closeWait:
26374 				tcpkp->currEstab.value.ui32++;
26375 				break;
26376 			}
26377 		}
26378 	}
26379 
26380 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26381 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26382 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26383 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26384 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26385 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26386 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26387 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26388 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26389 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26390 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26391 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26392 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26393 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26394 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26395 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26396 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26397 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26398 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26399 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26400 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26401 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26402 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26403 	tcpkp->inDataInorderSegs.value.ui32 =
26404 	    tcps->tcps_mib.tcpInDataInorderSegs;
26405 	tcpkp->inDataInorderBytes.value.ui32 =
26406 	    tcps->tcps_mib.tcpInDataInorderBytes;
26407 	tcpkp->inDataUnorderSegs.value.ui32 =
26408 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26409 	tcpkp->inDataUnorderBytes.value.ui32 =
26410 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26411 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26412 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26413 	tcpkp->inDataPartDupSegs.value.ui32 =
26414 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26415 	tcpkp->inDataPartDupBytes.value.ui32 =
26416 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26417 	tcpkp->inDataPastWinSegs.value.ui32 =
26418 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26419 	tcpkp->inDataPastWinBytes.value.ui32 =
26420 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26421 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26422 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26423 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26424 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26425 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26426 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26427 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26428 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26429 	tcpkp->timKeepaliveProbe.value.ui32 =
26430 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26431 	tcpkp->timKeepaliveDrop.value.ui32 =
26432 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26433 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26434 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26435 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26436 	tcpkp->outSackRetransSegs.value.ui32 =
26437 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26438 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26439 
26440 	netstack_rele(ns);
26441 	return (0);
26442 }
26443 
26444 void
26445 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26446 {
26447 	uint16_t	hdr_len;
26448 	ipha_t		*ipha;
26449 	uint8_t		*nexthdrp;
26450 	tcph_t		*tcph;
26451 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26452 
26453 	/* Already has an eager */
26454 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26455 		TCP_STAT(tcps, tcp_reinput_syn);
26456 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26457 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
26458 		return;
26459 	}
26460 
26461 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26462 	case IPV4_VERSION:
26463 		ipha = (ipha_t *)mp->b_rptr;
26464 		hdr_len = IPH_HDR_LENGTH(ipha);
26465 		break;
26466 	case IPV6_VERSION:
26467 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26468 		    &hdr_len, &nexthdrp)) {
26469 			CONN_DEC_REF(connp);
26470 			freemsg(mp);
26471 			return;
26472 		}
26473 		break;
26474 	}
26475 
26476 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26477 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26478 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26479 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26480 	}
26481 
26482 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26483 	    SQ_FILL, SQTAG_TCP_REINPUT);
26484 }
26485 
26486 static int
26487 tcp_squeue_switch(int val)
26488 {
26489 	int rval = SQ_FILL;
26490 
26491 	switch (val) {
26492 	case 1:
26493 		rval = SQ_NODRAIN;
26494 		break;
26495 	case 2:
26496 		rval = SQ_PROCESS;
26497 		break;
26498 	default:
26499 		break;
26500 	}
26501 	return (rval);
26502 }
26503 
26504 /*
26505  * This is called once for each squeue - globally for all stack
26506  * instances.
26507  */
26508 static void
26509 tcp_squeue_add(squeue_t *sqp)
26510 {
26511 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26512 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26513 
26514 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26515 	tcp_time_wait->tcp_time_wait_tid =
26516 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26517 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26518 	    CALLOUT_FLAG_ROUNDUP);
26519 	if (tcp_free_list_max_cnt == 0) {
26520 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26521 		    max_ncpus : boot_max_ncpus);
26522 
26523 		/*
26524 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26525 		 */
26526 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26527 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26528 	}
26529 	tcp_time_wait->tcp_free_list_cnt = 0;
26530 }
26531 
26532 static int
26533 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error)
26534 {
26535 	mblk_t	*ire_mp = NULL;
26536 	mblk_t	*syn_mp;
26537 	mblk_t	*mdti;
26538 	mblk_t	*lsoi;
26539 	int	retval;
26540 	tcph_t	*tcph;
26541 	uint32_t	mss;
26542 	queue_t	*q = tcp->tcp_rq;
26543 	conn_t	*connp = tcp->tcp_connp;
26544 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26545 
26546 	if (error == 0) {
26547 		/*
26548 		 * Adapt Multidata information, if any.  The
26549 		 * following tcp_mdt_update routine will free
26550 		 * the message.
26551 		 */
26552 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
26553 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
26554 			    b_rptr)->mdt_capab, B_TRUE);
26555 			freemsg(mdti);
26556 		}
26557 
26558 		/*
26559 		 * Check to update LSO information with tcp, and
26560 		 * tcp_lso_update routine will free the message.
26561 		 */
26562 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
26563 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
26564 			    b_rptr)->lso_capab);
26565 			freemsg(lsoi);
26566 		}
26567 
26568 		/* Get the IRE, if we had requested for it */
26569 		if (mp != NULL)
26570 			ire_mp = tcp_ire_mp(&mp);
26571 
26572 		if (tcp->tcp_hard_binding) {
26573 			tcp->tcp_hard_binding = B_FALSE;
26574 			tcp->tcp_hard_bound = B_TRUE;
26575 			CL_INET_CONNECT(tcp);
26576 		} else {
26577 			if (ire_mp != NULL)
26578 				freeb(ire_mp);
26579 			goto after_syn_sent;
26580 		}
26581 
26582 		retval = tcp_adapt_ire(tcp, ire_mp);
26583 		if (ire_mp != NULL)
26584 			freeb(ire_mp);
26585 		if (retval == 0) {
26586 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
26587 			    ENETUNREACH : EADDRNOTAVAIL);
26588 			goto ipcl_rm;
26589 		}
26590 		/*
26591 		 * Don't let an endpoint connect to itself.
26592 		 * Also checked in tcp_connect() but that
26593 		 * check can't handle the case when the
26594 		 * local IP address is INADDR_ANY.
26595 		 */
26596 		if (tcp->tcp_ipversion == IPV4_VERSION) {
26597 			if ((tcp->tcp_ipha->ipha_dst ==
26598 			    tcp->tcp_ipha->ipha_src) &&
26599 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26600 			    tcp->tcp_tcph->th_fport))) {
26601 				error = EADDRNOTAVAIL;
26602 				goto ipcl_rm;
26603 			}
26604 		} else {
26605 			if (IN6_ARE_ADDR_EQUAL(
26606 			    &tcp->tcp_ip6h->ip6_dst,
26607 			    &tcp->tcp_ip6h->ip6_src) &&
26608 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26609 			    tcp->tcp_tcph->th_fport))) {
26610 				error = EADDRNOTAVAIL;
26611 				goto ipcl_rm;
26612 			}
26613 		}
26614 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
26615 		/*
26616 		 * This should not be possible!  Just for
26617 		 * defensive coding...
26618 		 */
26619 		if (tcp->tcp_state != TCPS_SYN_SENT)
26620 			goto after_syn_sent;
26621 
26622 		if (is_system_labeled() &&
26623 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
26624 			error = EHOSTUNREACH;
26625 			goto ipcl_rm;
26626 		}
26627 
26628 		/*
26629 		 * tcp_adapt_ire() does not adjust
26630 		 * for TCP/IP header length.
26631 		 */
26632 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
26633 
26634 		/*
26635 		 * Just make sure our rwnd is at
26636 		 * least tcp_recv_hiwat_mss * MSS
26637 		 * large, and round up to the nearest
26638 		 * MSS.
26639 		 *
26640 		 * We do the round up here because
26641 		 * we need to get the interface
26642 		 * MTU first before we can do the
26643 		 * round up.
26644 		 */
26645 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
26646 		    tcps->tcps_recv_hiwat_minmss * mss);
26647 		if (!IPCL_IS_NONSTR(connp))
26648 			q->q_hiwat = tcp->tcp_rwnd;
26649 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
26650 		tcp_set_ws_value(tcp);
26651 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
26652 		    tcp->tcp_tcph->th_win);
26653 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
26654 			tcp->tcp_snd_ws_ok = B_TRUE;
26655 
26656 		/*
26657 		 * Set tcp_snd_ts_ok to true
26658 		 * so that tcp_xmit_mp will
26659 		 * include the timestamp
26660 		 * option in the SYN segment.
26661 		 */
26662 		if (tcps->tcps_tstamp_always ||
26663 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
26664 			tcp->tcp_snd_ts_ok = B_TRUE;
26665 		}
26666 
26667 		/*
26668 		 * tcp_snd_sack_ok can be set in
26669 		 * tcp_adapt_ire() if the sack metric
26670 		 * is set.  So check it here also.
26671 		 */
26672 		if (tcps->tcps_sack_permitted == 2 ||
26673 		    tcp->tcp_snd_sack_ok) {
26674 			if (tcp->tcp_sack_info == NULL) {
26675 				tcp->tcp_sack_info =
26676 				    kmem_cache_alloc(tcp_sack_info_cache,
26677 				    KM_SLEEP);
26678 			}
26679 			tcp->tcp_snd_sack_ok = B_TRUE;
26680 		}
26681 
26682 		/*
26683 		 * Should we use ECN?  Note that the current
26684 		 * default value (SunOS 5.9) of tcp_ecn_permitted
26685 		 * is 1.  The reason for doing this is that there
26686 		 * are equipments out there that will drop ECN
26687 		 * enabled IP packets.  Setting it to 1 avoids
26688 		 * compatibility problems.
26689 		 */
26690 		if (tcps->tcps_ecn_permitted == 2)
26691 			tcp->tcp_ecn_ok = B_TRUE;
26692 
26693 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
26694 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
26695 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
26696 		if (syn_mp) {
26697 			cred_t *cr;
26698 			pid_t pid;
26699 
26700 			/*
26701 			 * Obtain the credential from the
26702 			 * thread calling connect().
26703 			 * If none can be found, default to
26704 			 * the creator  of the socket.
26705 			 */
26706 			if (mp == NULL ||
26707 			    (cr = DB_CRED(mp)) == NULL) {
26708 				cr = tcp->tcp_cred;
26709 				pid = tcp->tcp_cpid;
26710 			} else {
26711 				pid = DB_CPID(mp);
26712 			}
26713 
26714 			mblk_setcred(syn_mp, cr);
26715 			DB_CPID(syn_mp) = pid;
26716 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
26717 		}
26718 	after_syn_sent:
26719 		/*
26720 		 * A trailer mblk indicates a waiting client upstream.
26721 		 * We complete here the processing begun in
26722 		 * either tcp_bind() or tcp_connect() by passing
26723 		 * upstream the reply message they supplied.
26724 		 */
26725 		if (mp != NULL) {
26726 			ASSERT(mp->b_cont == NULL);
26727 			freeb(mp);
26728 		}
26729 		return (error);
26730 	} else {
26731 		/* error */
26732 		if (tcp->tcp_debug) {
26733 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
26734 			    "tcp_post_ip_bind: error == %d", error);
26735 		}
26736 		if (mp != NULL) {
26737 			freeb(mp);
26738 		}
26739 	}
26740 
26741 ipcl_rm:
26742 	/*
26743 	 * Need to unbind with classifier since we were just
26744 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
26745 	 */
26746 	tcp->tcp_hard_bound = B_FALSE;
26747 	tcp->tcp_hard_binding = B_FALSE;
26748 
26749 	ipcl_hash_remove(connp);
26750 
26751 bind_failed:
26752 	tcp->tcp_state = TCPS_IDLE;
26753 	if (tcp->tcp_ipversion == IPV4_VERSION)
26754 		tcp->tcp_ipha->ipha_src = 0;
26755 	else
26756 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
26757 	/*
26758 	 * Copy of the src addr. in tcp_t is needed since
26759 	 * the lookup funcs. can only look at tcp_t
26760 	 */
26761 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
26762 
26763 	tcph = tcp->tcp_tcph;
26764 	tcph->th_lport[0] = 0;
26765 	tcph->th_lport[1] = 0;
26766 	tcp_bind_hash_remove(tcp);
26767 	bzero(&connp->u_port, sizeof (connp->u_port));
26768 	/* blow away saved option results if any */
26769 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26770 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26771 
26772 	conn_delete_ire(tcp->tcp_connp, NULL);
26773 
26774 	return (error);
26775 }
26776 
26777 static int
26778 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
26779     boolean_t bind_to_req_port_only, cred_t *cr)
26780 {
26781 	in_port_t	mlp_port;
26782 	mlp_type_t 	addrtype, mlptype;
26783 	boolean_t	user_specified;
26784 	in_port_t	allocated_port;
26785 	in_port_t	requested_port = *requested_port_ptr;
26786 	conn_t		*connp;
26787 	zone_t		*zone;
26788 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26789 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
26790 
26791 	/*
26792 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
26793 	 */
26794 	if (cr == NULL)
26795 		cr = tcp->tcp_cred;
26796 	/*
26797 	 * Get a valid port (within the anonymous range and should not
26798 	 * be a privileged one) to use if the user has not given a port.
26799 	 * If multiple threads are here, they may all start with
26800 	 * with the same initial port. But, it should be fine as long as
26801 	 * tcp_bindi will ensure that no two threads will be assigned
26802 	 * the same port.
26803 	 *
26804 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
26805 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
26806 	 * unless TCP_ANONPRIVBIND option is set.
26807 	 */
26808 	mlptype = mlptSingle;
26809 	mlp_port = requested_port;
26810 	if (requested_port == 0) {
26811 		requested_port = tcp->tcp_anon_priv_bind ?
26812 		    tcp_get_next_priv_port(tcp) :
26813 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
26814 		    tcp, B_TRUE);
26815 		if (requested_port == 0) {
26816 			return (-TNOADDR);
26817 		}
26818 		user_specified = B_FALSE;
26819 
26820 		/*
26821 		 * If the user went through one of the RPC interfaces to create
26822 		 * this socket and RPC is MLP in this zone, then give him an
26823 		 * anonymous MLP.
26824 		 */
26825 		connp = tcp->tcp_connp;
26826 		if (connp->conn_anon_mlp && is_system_labeled()) {
26827 			zone = crgetzone(cr);
26828 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26829 			    IPV6_VERSION, &v6addr,
26830 			    tcps->tcps_netstack->netstack_ip);
26831 			if (addrtype == mlptSingle) {
26832 				return (-TNOADDR);
26833 			}
26834 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26835 			    PMAPPORT, addrtype);
26836 			mlp_port = PMAPPORT;
26837 		}
26838 	} else {
26839 		int i;
26840 		boolean_t priv = B_FALSE;
26841 
26842 		/*
26843 		 * If the requested_port is in the well-known privileged range,
26844 		 * verify that the stream was opened by a privileged user.
26845 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26846 		 * but instead the code relies on:
26847 		 * - the fact that the address of the array and its size never
26848 		 *   changes
26849 		 * - the atomic assignment of the elements of the array
26850 		 */
26851 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26852 			priv = B_TRUE;
26853 		} else {
26854 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26855 				if (requested_port ==
26856 				    tcps->tcps_g_epriv_ports[i]) {
26857 					priv = B_TRUE;
26858 					break;
26859 				}
26860 			}
26861 		}
26862 		if (priv) {
26863 			if (secpolicy_net_privaddr(cr, requested_port,
26864 			    IPPROTO_TCP) != 0) {
26865 				if (tcp->tcp_debug) {
26866 					(void) strlog(TCP_MOD_ID, 0, 1,
26867 					    SL_ERROR|SL_TRACE,
26868 					    "tcp_bind: no priv for port %d",
26869 					    requested_port);
26870 				}
26871 				return (-TACCES);
26872 			}
26873 		}
26874 		user_specified = B_TRUE;
26875 
26876 		connp = tcp->tcp_connp;
26877 		if (is_system_labeled()) {
26878 			zone = crgetzone(cr);
26879 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26880 			    IPV6_VERSION, &v6addr,
26881 			    tcps->tcps_netstack->netstack_ip);
26882 			if (addrtype == mlptSingle) {
26883 				return (-TNOADDR);
26884 			}
26885 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26886 			    requested_port, addrtype);
26887 		}
26888 	}
26889 
26890 	if (mlptype != mlptSingle) {
26891 		if (secpolicy_net_bindmlp(cr) != 0) {
26892 			if (tcp->tcp_debug) {
26893 				(void) strlog(TCP_MOD_ID, 0, 1,
26894 				    SL_ERROR|SL_TRACE,
26895 				    "tcp_bind: no priv for multilevel port %d",
26896 				    requested_port);
26897 			}
26898 			return (-TACCES);
26899 		}
26900 
26901 		/*
26902 		 * If we're specifically binding a shared IP address and the
26903 		 * port is MLP on shared addresses, then check to see if this
26904 		 * zone actually owns the MLP.  Reject if not.
26905 		 */
26906 		if (mlptype == mlptShared && addrtype == mlptShared) {
26907 			/*
26908 			 * No need to handle exclusive-stack zones since
26909 			 * ALL_ZONES only applies to the shared stack.
26910 			 */
26911 			zoneid_t mlpzone;
26912 
26913 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
26914 			    htons(mlp_port));
26915 			if (connp->conn_zoneid != mlpzone) {
26916 				if (tcp->tcp_debug) {
26917 					(void) strlog(TCP_MOD_ID, 0, 1,
26918 					    SL_ERROR|SL_TRACE,
26919 					    "tcp_bind: attempt to bind port "
26920 					    "%d on shared addr in zone %d "
26921 					    "(should be %d)",
26922 					    mlp_port, connp->conn_zoneid,
26923 					    mlpzone);
26924 				}
26925 				return (-TACCES);
26926 			}
26927 		}
26928 
26929 		if (!user_specified) {
26930 			int err;
26931 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26932 			    requested_port, B_TRUE);
26933 			if (err != 0) {
26934 				if (tcp->tcp_debug) {
26935 					(void) strlog(TCP_MOD_ID, 0, 1,
26936 					    SL_ERROR|SL_TRACE,
26937 					    "tcp_bind: cannot establish anon "
26938 					    "MLP for port %d",
26939 					    requested_port);
26940 				}
26941 				return (err);
26942 			}
26943 			connp->conn_anon_port = B_TRUE;
26944 		}
26945 		connp->conn_mlp_type = mlptype;
26946 	}
26947 
26948 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
26949 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
26950 
26951 	if (allocated_port == 0) {
26952 		connp->conn_mlp_type = mlptSingle;
26953 		if (connp->conn_anon_port) {
26954 			connp->conn_anon_port = B_FALSE;
26955 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
26956 			    requested_port, B_FALSE);
26957 		}
26958 		if (bind_to_req_port_only) {
26959 			if (tcp->tcp_debug) {
26960 				(void) strlog(TCP_MOD_ID, 0, 1,
26961 				    SL_ERROR|SL_TRACE,
26962 				    "tcp_bind: requested addr busy");
26963 			}
26964 			return (-TADDRBUSY);
26965 		} else {
26966 			/* If we are out of ports, fail the bind. */
26967 			if (tcp->tcp_debug) {
26968 				(void) strlog(TCP_MOD_ID, 0, 1,
26969 				    SL_ERROR|SL_TRACE,
26970 				    "tcp_bind: out of ports?");
26971 			}
26972 			return (-TNOADDR);
26973 		}
26974 	}
26975 
26976 	/* Pass the allocated port back */
26977 	*requested_port_ptr = allocated_port;
26978 	return (0);
26979 }
26980 
26981 static int
26982 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
26983     boolean_t bind_to_req_port_only)
26984 {
26985 	tcp_t	*tcp = connp->conn_tcp;
26986 
26987 	sin_t	*sin;
26988 	sin6_t  *sin6;
26989 	sin6_t		sin6addr;
26990 	in_port_t requested_port;
26991 	ipaddr_t	v4addr;
26992 	in6_addr_t	v6addr;
26993 	uint_t	origipversion;
26994 	int	error = 0;
26995 
26996 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
26997 
26998 	if (tcp->tcp_state == TCPS_BOUND) {
26999 		return (0);
27000 	} else if (tcp->tcp_state > TCPS_BOUND) {
27001 		if (tcp->tcp_debug) {
27002 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27003 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27004 		}
27005 		return (-TOUTSTATE);
27006 	}
27007 	origipversion = tcp->tcp_ipversion;
27008 
27009 	if (sa != NULL && !OK_32PTR((char *)sa)) {
27010 		if (tcp->tcp_debug) {
27011 			(void) strlog(TCP_MOD_ID, 0, 1,
27012 			    SL_ERROR|SL_TRACE,
27013 			    "tcp_bind: bad address parameter, "
27014 			    "address %p, len %d",
27015 			    (void *)sa, len);
27016 		}
27017 		return (-TPROTO);
27018 	}
27019 
27020 	switch (len) {
27021 	case 0:		/* request for a generic port */
27022 		if (tcp->tcp_family == AF_INET) {
27023 			sin = (sin_t *)&sin6addr;
27024 			*sin = sin_null;
27025 			sin->sin_family = AF_INET;
27026 			tcp->tcp_ipversion = IPV4_VERSION;
27027 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
27028 		} else {
27029 			ASSERT(tcp->tcp_family == AF_INET6);
27030 			sin6 = (sin6_t *)&sin6addr;
27031 			*sin6 = sin6_null;
27032 			sin6->sin6_family = AF_INET6;
27033 			tcp->tcp_ipversion = IPV6_VERSION;
27034 			V6_SET_ZERO(v6addr);
27035 		}
27036 		requested_port = 0;
27037 		break;
27038 
27039 	case sizeof (sin_t):	/* Complete IPv4 address */
27040 		sin = (sin_t *)sa;
27041 		/*
27042 		 * With sockets sockfs will accept bogus sin_family in
27043 		 * bind() and replace it with the family used in the socket
27044 		 * call.
27045 		 */
27046 		if (sin->sin_family != AF_INET ||
27047 		    tcp->tcp_family != AF_INET) {
27048 			return (EAFNOSUPPORT);
27049 		}
27050 		requested_port = ntohs(sin->sin_port);
27051 		tcp->tcp_ipversion = IPV4_VERSION;
27052 		v4addr = sin->sin_addr.s_addr;
27053 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
27054 		break;
27055 
27056 	case sizeof (sin6_t): /* Complete IPv6 address */
27057 		sin6 = (sin6_t *)sa;
27058 		if (sin6->sin6_family != AF_INET6 ||
27059 		    tcp->tcp_family != AF_INET6) {
27060 			return (EAFNOSUPPORT);
27061 		}
27062 		requested_port = ntohs(sin6->sin6_port);
27063 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
27064 		    IPV4_VERSION : IPV6_VERSION;
27065 		v6addr = sin6->sin6_addr;
27066 		break;
27067 
27068 	default:
27069 		if (tcp->tcp_debug) {
27070 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27071 			    "tcp_bind: bad address length, %d", len);
27072 		}
27073 		return (EAFNOSUPPORT);
27074 		/* return (-TBADADDR); */
27075 	}
27076 
27077 	tcp->tcp_bound_source_v6 = v6addr;
27078 
27079 	/* Check for change in ipversion */
27080 	if (origipversion != tcp->tcp_ipversion) {
27081 		ASSERT(tcp->tcp_family == AF_INET6);
27082 		error = tcp->tcp_ipversion == IPV6_VERSION ?
27083 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
27084 		if (error) {
27085 			return (ENOMEM);
27086 		}
27087 	}
27088 
27089 	/*
27090 	 * Initialize family specific fields. Copy of the src addr.
27091 	 * in tcp_t is needed for the lookup funcs.
27092 	 */
27093 	if (tcp->tcp_ipversion == IPV6_VERSION) {
27094 		tcp->tcp_ip6h->ip6_src = v6addr;
27095 	} else {
27096 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
27097 	}
27098 	tcp->tcp_ip_src_v6 = v6addr;
27099 
27100 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
27101 
27102 	error = tcp_bind_select_lport(tcp, &requested_port,
27103 	    bind_to_req_port_only, cr);
27104 
27105 	return (error);
27106 }
27107 
27108 /*
27109  * Return unix error is tli error is TSYSERR, otherwise return a negative
27110  * tli error.
27111  */
27112 int
27113 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27114     boolean_t bind_to_req_port_only)
27115 {
27116 	int error;
27117 	tcp_t *tcp = connp->conn_tcp;
27118 
27119 	if (tcp->tcp_state >= TCPS_BOUND) {
27120 		if (tcp->tcp_debug) {
27121 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27122 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27123 		}
27124 		return (-TOUTSTATE);
27125 	}
27126 
27127 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
27128 	if (error != 0)
27129 		return (error);
27130 
27131 	ASSERT(tcp->tcp_state == TCPS_BOUND);
27132 
27133 	tcp->tcp_conn_req_max = 0;
27134 
27135 	/*
27136 	 * We need to make sure that the conn_recv is set to a non-null
27137 	 * value before we insert the conn into the classifier table.
27138 	 * This is to avoid a race with an incoming packet which does an
27139 	 * ipcl_classify().
27140 	 */
27141 	connp->conn_recv = tcp_conn_request;
27142 
27143 	if (tcp->tcp_family == AF_INET6) {
27144 		ASSERT(tcp->tcp_connp->conn_af_isv6);
27145 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27146 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
27147 	} else {
27148 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
27149 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
27150 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
27151 	}
27152 	return (tcp_post_ip_bind(tcp, NULL, error));
27153 }
27154 
27155 int
27156 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
27157     socklen_t len, cred_t *cr)
27158 {
27159 	int 		error;
27160 	conn_t		*connp = (conn_t *)proto_handle;
27161 	squeue_t	*sqp = connp->conn_sqp;
27162 
27163 	ASSERT(sqp != NULL);
27164 
27165 	error = squeue_synch_enter(sqp, connp, 0);
27166 	if (error != 0) {
27167 		/* failed to enter */
27168 		return (ENOSR);
27169 	}
27170 
27171 	/* binding to a NULL address really means unbind */
27172 	if (sa == NULL) {
27173 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
27174 			error = tcp_do_unbind(connp);
27175 		else
27176 			error = EINVAL;
27177 	} else {
27178 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
27179 	}
27180 
27181 	squeue_synch_exit(sqp, connp);
27182 
27183 	if (error < 0) {
27184 		if (error == -TOUTSTATE)
27185 			error = EINVAL;
27186 		else
27187 			error = proto_tlitosyserr(-error);
27188 	}
27189 
27190 	return (error);
27191 }
27192 
27193 /*
27194  * If the return value from this function is positive, it's a UNIX error.
27195  * Otherwise, if it's negative, then the absolute value is a TLI error.
27196  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
27197  */
27198 int
27199 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
27200     cred_t *cr, pid_t pid)
27201 {
27202 	tcp_t		*tcp = connp->conn_tcp;
27203 	sin_t		*sin = (sin_t *)sa;
27204 	sin6_t		*sin6 = (sin6_t *)sa;
27205 	ipaddr_t	*dstaddrp;
27206 	in_port_t	dstport;
27207 	uint_t		srcid;
27208 	int		error = 0;
27209 
27210 	switch (len) {
27211 	default:
27212 		/*
27213 		 * Should never happen
27214 		 */
27215 		return (EINVAL);
27216 
27217 	case sizeof (sin_t):
27218 		sin = (sin_t *)sa;
27219 		if (sin->sin_port == 0) {
27220 			return (-TBADADDR);
27221 		}
27222 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
27223 			return (EAFNOSUPPORT);
27224 		}
27225 		break;
27226 
27227 	case sizeof (sin6_t):
27228 		sin6 = (sin6_t *)sa;
27229 		if (sin6->sin6_port == 0) {
27230 			return (-TBADADDR);
27231 		}
27232 		break;
27233 	}
27234 	/*
27235 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
27236 	 * make sure that the template IP header in the tcp structure is an
27237 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
27238 	 * need to this before we call tcp_bindi() so that the port lookup
27239 	 * code will look for ports in the correct port space (IPv4 and
27240 	 * IPv6 have separate port spaces).
27241 	 */
27242 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
27243 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27244 		int err = 0;
27245 
27246 		err = tcp_header_init_ipv4(tcp);
27247 			if (err != 0) {
27248 				error = ENOMEM;
27249 				goto connect_failed;
27250 			}
27251 		if (tcp->tcp_lport != 0)
27252 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
27253 	}
27254 
27255 	switch (tcp->tcp_state) {
27256 	case TCPS_LISTEN:
27257 		/*
27258 		 * Listening sockets are not allowed to issue connect().
27259 		 */
27260 		if (IPCL_IS_NONSTR(connp))
27261 			return (EOPNOTSUPP);
27262 		/* FALLTHRU */
27263 	case TCPS_IDLE:
27264 		/*
27265 		 * We support quick connect, refer to comments in
27266 		 * tcp_connect_*()
27267 		 */
27268 		/* FALLTHRU */
27269 	case TCPS_BOUND:
27270 		/*
27271 		 * We must bump the generation before the operation start.
27272 		 * This is done to ensure that any upcall made later on sends
27273 		 * up the right generation to the socket.
27274 		 */
27275 		SOCK_CONNID_BUMP(tcp->tcp_connid);
27276 
27277 		if (tcp->tcp_family == AF_INET6) {
27278 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27279 				return (tcp_connect_ipv6(tcp,
27280 				    &sin6->sin6_addr,
27281 				    sin6->sin6_port, sin6->sin6_flowinfo,
27282 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
27283 				    cr, pid));
27284 			}
27285 			/*
27286 			 * Destination adress is mapped IPv6 address.
27287 			 * Source bound address should be unspecified or
27288 			 * IPv6 mapped address as well.
27289 			 */
27290 			if (!IN6_IS_ADDR_UNSPECIFIED(
27291 			    &tcp->tcp_bound_source_v6) &&
27292 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
27293 				return (EADDRNOTAVAIL);
27294 			}
27295 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
27296 			dstport = sin6->sin6_port;
27297 			srcid = sin6->__sin6_src_id;
27298 		} else {
27299 			dstaddrp = &sin->sin_addr.s_addr;
27300 			dstport = sin->sin_port;
27301 			srcid = 0;
27302 		}
27303 
27304 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
27305 		    pid);
27306 		break;
27307 	default:
27308 		return (-TOUTSTATE);
27309 	}
27310 	/*
27311 	 * Note: Code below is the "failure" case
27312 	 */
27313 connect_failed:
27314 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
27315 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
27316 	return (error);
27317 }
27318 
27319 int
27320 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
27321     socklen_t len, sock_connid_t *id, cred_t *cr)
27322 {
27323 	conn_t		*connp = (conn_t *)proto_handle;
27324 	tcp_t		*tcp = connp->conn_tcp;
27325 	squeue_t	*sqp = connp->conn_sqp;
27326 	int		error;
27327 
27328 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
27329 	if (error != 0) {
27330 		return (error);
27331 	}
27332 
27333 	error = squeue_synch_enter(sqp, connp, 0);
27334 	if (error != 0) {
27335 		/* failed to enter */
27336 		return (ENOSR);
27337 	}
27338 
27339 	/*
27340 	 * TCP supports quick connect, so no need to do an implicit bind
27341 	 */
27342 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
27343 	if (error == 0) {
27344 		*id = connp->conn_tcp->tcp_connid;
27345 	} else if (error < 0) {
27346 		if (error == -TOUTSTATE) {
27347 			switch (connp->conn_tcp->tcp_state) {
27348 			case TCPS_SYN_SENT:
27349 				error = EALREADY;
27350 				break;
27351 			case TCPS_ESTABLISHED:
27352 				error = EISCONN;
27353 				break;
27354 			case TCPS_LISTEN:
27355 				error = EOPNOTSUPP;
27356 				break;
27357 			default:
27358 				error = EINVAL;
27359 				break;
27360 			}
27361 		} else {
27362 			error = proto_tlitosyserr(-error);
27363 		}
27364 	}
27365 done:
27366 	squeue_synch_exit(sqp, connp);
27367 
27368 	return ((error == 0) ? EINPROGRESS : error);
27369 }
27370 
27371 /* ARGSUSED */
27372 sock_lower_handle_t
27373 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
27374     uint_t *smodep, int *errorp, int flags, cred_t *credp)
27375 {
27376 	conn_t		*connp;
27377 	boolean_t	isv6 = family == AF_INET6;
27378 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
27379 	    (proto != 0 && proto != IPPROTO_TCP)) {
27380 		*errorp = EPROTONOSUPPORT;
27381 		return (NULL);
27382 	}
27383 
27384 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
27385 	if (connp == NULL) {
27386 		return (NULL);
27387 	}
27388 
27389 	/*
27390 	 * Put the ref for TCP. Ref for IP was already put
27391 	 * by ipcl_conn_create. Also Make the conn_t globally
27392 	 * visible to walkers
27393 	 */
27394 	mutex_enter(&connp->conn_lock);
27395 	CONN_INC_REF_LOCKED(connp);
27396 	ASSERT(connp->conn_ref == 2);
27397 	connp->conn_state_flags &= ~CONN_INCIPIENT;
27398 
27399 	connp->conn_flags |= IPCL_NONSTR;
27400 	mutex_exit(&connp->conn_lock);
27401 
27402 	ASSERT(errorp != NULL);
27403 	*errorp = 0;
27404 	*sock_downcalls = &sock_tcp_downcalls;
27405 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP;
27406 
27407 	return ((sock_lower_handle_t)connp);
27408 }
27409 
27410 /* ARGSUSED */
27411 void
27412 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
27413     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
27414 {
27415 	conn_t *connp = (conn_t *)proto_handle;
27416 	struct sock_proto_props sopp;
27417 
27418 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
27419 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
27420 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
27421 
27422 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
27423 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
27424 	sopp.sopp_maxpsz = INFPSZ;
27425 	sopp.sopp_maxblk = INFPSZ;
27426 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
27427 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
27428 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
27429 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
27430 	    tcp_rinfo.mi_minpsz;
27431 
27432 	connp->conn_upcalls = sock_upcalls;
27433 	connp->conn_upper_handle = sock_handle;
27434 
27435 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
27436 }
27437 
27438 /* ARGSUSED */
27439 int
27440 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
27441 {
27442 	conn_t *connp = (conn_t *)proto_handle;
27443 
27444 	tcp_close_common(connp, flags);
27445 
27446 	ip_close_helper_stream(connp);
27447 
27448 	/*
27449 	 * Drop IP's reference on the conn. This is the last reference
27450 	 * on the connp if the state was less than established. If the
27451 	 * connection has gone into timewait state, then we will have
27452 	 * one ref for the TCP and one more ref (total of two) for the
27453 	 * classifier connected hash list (a timewait connections stays
27454 	 * in connected hash till closed).
27455 	 *
27456 	 * We can't assert the references because there might be other
27457 	 * transient reference places because of some walkers or queued
27458 	 * packets in squeue for the timewait state.
27459 	 */
27460 	CONN_DEC_REF(connp);
27461 	return (0);
27462 }
27463 
27464 /* ARGSUSED */
27465 int
27466 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
27467     cred_t *cr)
27468 {
27469 	tcp_t		*tcp;
27470 	uint32_t	msize;
27471 	conn_t *connp = (conn_t *)proto_handle;
27472 	int32_t		tcpstate;
27473 
27474 	ASSERT(connp->conn_ref >= 2);
27475 
27476 	if (msg->msg_controllen != 0) {
27477 		return (EOPNOTSUPP);
27478 
27479 	}
27480 	switch (DB_TYPE(mp)) {
27481 	case M_DATA:
27482 		tcp = connp->conn_tcp;
27483 		ASSERT(tcp != NULL);
27484 
27485 		tcpstate = tcp->tcp_state;
27486 		if (tcpstate < TCPS_ESTABLISHED) {
27487 			freemsg(mp);
27488 			return (ENOTCONN);
27489 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
27490 			freemsg(mp);
27491 			return (EPIPE);
27492 		}
27493 
27494 		if (is_system_labeled())
27495 			msg_setcredpid(mp, cr, curproc->p_pid);
27496 
27497 		/* XXX pass the size down and to the squeue */
27498 		msize = msgdsize(mp);
27499 
27500 		mutex_enter(&tcp->tcp_non_sq_lock);
27501 		tcp->tcp_squeue_bytes += msize;
27502 		/*
27503 		 * Squeue Flow Control
27504 		 */
27505 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
27506 			tcp_setqfull(tcp);
27507 		}
27508 		mutex_exit(&tcp->tcp_non_sq_lock);
27509 
27510 		/*
27511 		 * The application may pass in an address in the msghdr, but
27512 		 * we ignore the address on connection-oriented sockets.
27513 		 * Just like BSD this code does not generate an error for
27514 		 * TCP (a CONNREQUIRED socket) when sending to an address
27515 		 * passed in with sendto/sendmsg. Instead the data is
27516 		 * delivered on the connection as if no address had been
27517 		 * supplied.
27518 		 */
27519 		CONN_INC_REF(connp);
27520 
27521 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
27522 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
27523 			    tcp_output_urgent, connp, tcp_squeue_flag,
27524 			    SQTAG_TCP_OUTPUT);
27525 		} else {
27526 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
27527 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
27528 		}
27529 
27530 		return (0);
27531 
27532 	default:
27533 		ASSERT(0);
27534 	}
27535 
27536 	freemsg(mp);
27537 	return (0);
27538 }
27539 
27540 /* ARGSUSED */
27541 void
27542 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
27543 {
27544 	int len;
27545 	uint32_t msize;
27546 	conn_t *connp = (conn_t *)arg;
27547 	tcp_t *tcp = connp->conn_tcp;
27548 
27549 	msize = msgdsize(mp);
27550 
27551 	len = msize - 1;
27552 	if (len < 0) {
27553 		freemsg(mp);
27554 		return;
27555 	}
27556 
27557 	/*
27558 	 * Try to force urgent data out on the wire.
27559 	 * Even if we have unsent data this will
27560 	 * at least send the urgent flag.
27561 	 * XXX does not handle more flag correctly.
27562 	 */
27563 	len += tcp->tcp_unsent;
27564 	len += tcp->tcp_snxt;
27565 	tcp->tcp_urg = len;
27566 	tcp->tcp_valid_bits |= TCP_URG_VALID;
27567 
27568 	/* Bypass tcp protocol for fused tcp loopback */
27569 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
27570 		return;
27571 	tcp_wput_data(tcp, mp, B_TRUE);
27572 }
27573 
27574 /* ARGSUSED */
27575 int
27576 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27577     socklen_t *addrlen, cred_t *cr)
27578 {
27579 	sin_t   *sin;
27580 	sin6_t  *sin6;
27581 	conn_t	*connp = (conn_t *)proto_handle;
27582 	tcp_t	*tcp = connp->conn_tcp;
27583 
27584 	ASSERT(tcp != NULL);
27585 	if (tcp->tcp_state < TCPS_SYN_RCVD)
27586 		return (ENOTCONN);
27587 
27588 	addr->sa_family = tcp->tcp_family;
27589 	switch (tcp->tcp_family) {
27590 	case AF_INET:
27591 		if (*addrlen < sizeof (sin_t))
27592 			return (EINVAL);
27593 
27594 		sin = (sin_t *)addr;
27595 		*sin = sin_null;
27596 		sin->sin_family = AF_INET;
27597 		if (tcp->tcp_ipversion == IPV4_VERSION) {
27598 			IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
27599 			    sin->sin_addr.s_addr);
27600 		}
27601 		sin->sin_port = tcp->tcp_fport;
27602 		*addrlen = sizeof (struct sockaddr_in);
27603 		break;
27604 	case AF_INET6:
27605 		sin6 = (sin6_t *)addr;
27606 		*sin6 = sin6_null;
27607 		sin6->sin6_family = AF_INET6;
27608 
27609 		if (*addrlen < sizeof (struct sockaddr_in6))
27610 			return (EINVAL);
27611 
27612 		if (tcp->tcp_ipversion == IPV6_VERSION) {
27613 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
27614 			    ~IPV6_VERS_AND_FLOW_MASK;
27615 		}
27616 
27617 		sin6->sin6_addr = tcp->tcp_remote_v6;
27618 		sin6->sin6_port = tcp->tcp_fport;
27619 		*addrlen = sizeof (struct sockaddr_in6);
27620 		break;
27621 	}
27622 	return (0);
27623 }
27624 
27625 /* ARGSUSED */
27626 int
27627 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27628     socklen_t *addrlenp, cred_t *cr)
27629 {
27630 	sin_t   *sin;
27631 	sin6_t  *sin6;
27632 	conn_t	*connp = (conn_t *)proto_handle;
27633 	tcp_t	*tcp = connp->conn_tcp;
27634 
27635 	switch (tcp->tcp_family) {
27636 	case AF_INET:
27637 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
27638 		if (*addrlenp < sizeof (sin_t))
27639 			return (EINVAL);
27640 		sin = (sin_t *)addr;
27641 		*sin = sin_null;
27642 		sin->sin_family = AF_INET;
27643 		*addrlenp = sizeof (sin_t);
27644 		if (tcp->tcp_state >= TCPS_BOUND) {
27645 			sin->sin_addr.s_addr =  tcp->tcp_ipha->ipha_src;
27646 			sin->sin_port = tcp->tcp_lport;
27647 		}
27648 		break;
27649 
27650 	case AF_INET6:
27651 		if (*addrlenp < sizeof (sin6_t))
27652 			return (EINVAL);
27653 		sin6 = (sin6_t *)addr;
27654 		*sin6 = sin6_null;
27655 		sin6->sin6_family = AF_INET6;
27656 		*addrlenp = sizeof (sin6_t);
27657 		if (tcp->tcp_state >= TCPS_BOUND) {
27658 			sin6->sin6_port = tcp->tcp_lport;
27659 			if (tcp->tcp_ipversion == IPV4_VERSION) {
27660 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
27661 				    &sin6->sin6_addr);
27662 			} else {
27663 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
27664 			}
27665 		}
27666 		break;
27667 	}
27668 	return (0);
27669 }
27670 
27671 /*
27672  * tcp_fallback
27673  *
27674  * A direct socket is falling back to using STREAMS. Hanging
27675  * off of the queue is a temporary tcp_t, which was created using
27676  * tcp_open(). The tcp_open() was called as part of the regular
27677  * sockfs create path, i.e., the SO_SOCKSTR flag is passed down,
27678  * and therefore the temporary tcp_t is marked to be a socket
27679  * (i.e., IPCL_SOCKET, tcp_issocket). So the optimizations
27680  * introduced by FireEngine will be used.
27681  *
27682  * The tcp_t associated with the socket falling back will
27683  * still be marked as a socket, although the direct socket flag
27684  * (IPCL_NONSTR) is removed. A fall back to true TPI semantics
27685  * will not take place until a _SIOCSOCKFALLBACK ioctl is issued.
27686  *
27687  * If the above mentioned behavior, i.e., the tmp tcp_t is created
27688  * as a STREAMS/TPI endpoint, then we will need to do more work here.
27689  * Such as inserting the direct socket into the acceptor hash.
27690  */
27691 void
27692 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
27693     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27694 {
27695 	tcp_t			*tcp, *eager;
27696 	conn_t 			*connp = (conn_t *)proto_handle;
27697 	int			error;
27698 	struct T_capability_ack tca;
27699 	struct sockaddr_in6	laddr, faddr;
27700 	socklen_t 		laddrlen, faddrlen;
27701 	short			opts;
27702 	struct stroptions	*stropt;
27703 	mblk_t			*stropt_mp;
27704 	mblk_t			*mp;
27705 	mblk_t			*conn_ind_head = NULL;
27706 	mblk_t			*conn_ind_tail = NULL;
27707 	mblk_t			*ordrel_mp;
27708 	mblk_t			*fused_sigurp_mp;
27709 
27710 	tcp = connp->conn_tcp;
27711 	/*
27712 	 * No support for acceptor fallback
27713 	 */
27714 	ASSERT(q->q_qinfo != &tcp_acceptor_rinit);
27715 
27716 	stropt_mp = allocb_wait(sizeof (*stropt), BPRI_HI, STR_NOSIG, NULL);
27717 
27718 	/* Pre-allocate the T_ordrel_ind mblk. */
27719 	ASSERT(tcp->tcp_ordrel_mp == NULL);
27720 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
27721 	    STR_NOSIG, NULL);
27722 	ordrel_mp->b_datap->db_type = M_PROTO;
27723 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
27724 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
27725 
27726 	/* Pre-allocate the M_PCSIG anyway */
27727 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
27728 
27729 	/*
27730 	 * Enter the squeue so that no new packets can come in
27731 	 */
27732 	error = squeue_synch_enter(connp->conn_sqp, connp, 0);
27733 	if (error != 0) {
27734 		/* failed to enter, free all the pre-allocated messages. */
27735 		freeb(stropt_mp);
27736 		freeb(ordrel_mp);
27737 		freeb(fused_sigurp_mp);
27738 		return;
27739 	}
27740 
27741 	/* Disable I/OAT during fallback */
27742 	tcp->tcp_sodirect = NULL;
27743 
27744 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
27745 	connp->conn_minor_arena = WR(q)->q_ptr;
27746 
27747 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
27748 
27749 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
27750 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
27751 
27752 	WR(q)->q_qinfo = &tcp_sock_winit;
27753 
27754 	if (!direct_sockfs)
27755 		tcp_disable_direct_sockfs(tcp);
27756 
27757 	/*
27758 	 * free the helper stream
27759 	 */
27760 	ip_close_helper_stream(connp);
27761 
27762 	/*
27763 	 * Notify the STREAM head about options
27764 	 */
27765 	DB_TYPE(stropt_mp) = M_SETOPTS;
27766 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27767 	stropt_mp->b_wptr += sizeof (struct stroptions);
27768 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27769 	stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
27770 
27771 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
27772 	    tcp->tcp_tcps->tcps_wroff_xtra);
27773 	if (tcp->tcp_snd_sack_ok)
27774 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
27775 	stropt->so_hiwat = tcp->tcp_fused ?
27776 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
27777 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
27778 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
27779 
27780 	putnext(RD(q), stropt_mp);
27781 
27782 	/*
27783 	 * Collect the information needed to sync with the sonode
27784 	 */
27785 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
27786 
27787 	laddrlen = faddrlen = sizeof (sin6_t);
27788 	(void) tcp_getsockname(proto_handle, (struct sockaddr *)&laddr,
27789 	    &laddrlen, CRED());
27790 	error = tcp_getpeername(proto_handle, (struct sockaddr *)&faddr,
27791 	    &faddrlen, CRED());
27792 	if (error != 0)
27793 		faddrlen = 0;
27794 
27795 	opts = 0;
27796 	if (tcp->tcp_oobinline)
27797 		opts |= SO_OOBINLINE;
27798 	if (tcp->tcp_dontroute)
27799 		opts |= SO_DONTROUTE;
27800 
27801 	/*
27802 	 * Notify the socket that the protocol is now quiescent,
27803 	 * and it's therefore safe move data from the socket
27804 	 * to the stream head.
27805 	 */
27806 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
27807 	    (struct sockaddr *)&laddr, laddrlen,
27808 	    (struct sockaddr *)&faddr, faddrlen, opts);
27809 
27810 	while ((mp = tcp->tcp_rcv_list) != NULL) {
27811 		tcp->tcp_rcv_list = mp->b_next;
27812 		mp->b_next = NULL;
27813 		putnext(q, mp);
27814 	}
27815 	tcp->tcp_rcv_last_head = NULL;
27816 	tcp->tcp_rcv_last_tail = NULL;
27817 	tcp->tcp_rcv_cnt = 0;
27818 
27819 	/*
27820 	 * No longer a direct socket
27821 	 */
27822 	connp->conn_flags &= ~IPCL_NONSTR;
27823 
27824 	tcp->tcp_ordrel_mp = ordrel_mp;
27825 
27826 	if (tcp->tcp_fused) {
27827 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
27828 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
27829 	} else {
27830 		freeb(fused_sigurp_mp);
27831 	}
27832 
27833 	/*
27834 	 * Send T_CONN_IND messages for all ESTABLISHED connections.
27835 	 */
27836 	mutex_enter(&tcp->tcp_eager_lock);
27837 	for (eager = tcp->tcp_eager_next_q; eager != NULL;
27838 	    eager = eager->tcp_eager_next_q) {
27839 		mp = eager->tcp_conn.tcp_eager_conn_ind;
27840 
27841 		eager->tcp_conn.tcp_eager_conn_ind = NULL;
27842 		ASSERT(mp != NULL);
27843 		/*
27844 		 * TLI/XTI applications will get confused by
27845 		 * sending eager as an option since it violates
27846 		 * the option semantics. So remove the eager as
27847 		 * option since TLI/XTI app doesn't need it anyway.
27848 		 */
27849 		if (!TCP_IS_SOCKET(tcp)) {
27850 			struct T_conn_ind *conn_ind;
27851 
27852 			conn_ind = (struct T_conn_ind *)mp->b_rptr;
27853 			conn_ind->OPT_length = 0;
27854 			conn_ind->OPT_offset = 0;
27855 		}
27856 		if (conn_ind_head == NULL) {
27857 			conn_ind_head = mp;
27858 		} else {
27859 			conn_ind_tail->b_next = mp;
27860 		}
27861 		conn_ind_tail = mp;
27862 	}
27863 	mutex_exit(&tcp->tcp_eager_lock);
27864 
27865 	mp = conn_ind_head;
27866 	while (mp != NULL) {
27867 		mblk_t *nmp = mp->b_next;
27868 		mp->b_next = NULL;
27869 
27870 		putnext(tcp->tcp_rq, mp);
27871 		mp = nmp;
27872 	}
27873 
27874 	/*
27875 	 * There should be atleast two ref's (IP + TCP)
27876 	 */
27877 	ASSERT(connp->conn_ref >= 2);
27878 	squeue_synch_exit(connp->conn_sqp, connp);
27879 }
27880 
27881 /* ARGSUSED */
27882 static void
27883 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
27884 {
27885 	conn_t 	*connp = (conn_t *)arg;
27886 	tcp_t	*tcp = connp->conn_tcp;
27887 
27888 	freemsg(mp);
27889 
27890 	if (tcp->tcp_fused)
27891 		tcp_unfuse(tcp);
27892 
27893 	if (tcp_xmit_end(tcp) != 0) {
27894 		/*
27895 		 * We were crossing FINs and got a reset from
27896 		 * the other side. Just ignore it.
27897 		 */
27898 		if (tcp->tcp_debug) {
27899 			(void) strlog(TCP_MOD_ID, 0, 1,
27900 			    SL_ERROR|SL_TRACE,
27901 			    "tcp_shutdown_output() out of state %s",
27902 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27903 		}
27904 	}
27905 }
27906 
27907 /* ARGSUSED */
27908 int
27909 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27910 {
27911 	conn_t  *connp = (conn_t *)proto_handle;
27912 	tcp_t   *tcp = connp->conn_tcp;
27913 
27914 	/*
27915 	 * X/Open requires that we check the connected state.
27916 	 */
27917 	if (tcp->tcp_state < TCPS_SYN_SENT)
27918 		return (ENOTCONN);
27919 
27920 	/* shutdown the send side */
27921 	if (how != SHUT_RD) {
27922 		mblk_t *bp;
27923 
27924 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27925 		CONN_INC_REF(connp);
27926 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27927 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27928 
27929 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27930 		    SOCK_OPCTL_SHUT_SEND, 0);
27931 	}
27932 
27933 	/* shutdown the recv side */
27934 	if (how != SHUT_WR)
27935 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27936 		    SOCK_OPCTL_SHUT_RECV, 0);
27937 
27938 	return (0);
27939 }
27940 
27941 /*
27942  * SOP_LISTEN() calls into tcp_listen().
27943  */
27944 /* ARGSUSED */
27945 int
27946 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
27947 {
27948 	conn_t	*connp = (conn_t *)proto_handle;
27949 	int 	error;
27950 	squeue_t *sqp = connp->conn_sqp;
27951 
27952 	error = squeue_synch_enter(sqp, connp, 0);
27953 	if (error != 0) {
27954 		/* failed to enter */
27955 		return (ENOBUFS);
27956 	}
27957 
27958 	error = tcp_do_listen(connp, backlog, cr);
27959 	if (error == 0) {
27960 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27961 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
27962 	} else if (error < 0) {
27963 		if (error == -TOUTSTATE)
27964 			error = EINVAL;
27965 		else
27966 			error = proto_tlitosyserr(-error);
27967 	}
27968 	squeue_synch_exit(sqp, connp);
27969 	return (error);
27970 }
27971 
27972 static int
27973 tcp_do_listen(conn_t *connp, int backlog, cred_t *cr)
27974 {
27975 	tcp_t		*tcp = connp->conn_tcp;
27976 	sin_t		*sin;
27977 	sin6_t  	*sin6;
27978 	int		error = 0;
27979 	tcp_stack_t	*tcps = tcp->tcp_tcps;
27980 
27981 	if (tcp->tcp_state >= TCPS_BOUND) {
27982 		if ((tcp->tcp_state == TCPS_BOUND ||
27983 		    tcp->tcp_state == TCPS_LISTEN) &&
27984 		    backlog > 0) {
27985 			/*
27986 			 * Handle listen() increasing backlog.
27987 			 * This is more "liberal" then what the TPI spec
27988 			 * requires but is needed to avoid a t_unbind
27989 			 * when handling listen() since the port number
27990 			 * might be "stolen" between the unbind and bind.
27991 			 */
27992 			goto do_listen;
27993 		}
27994 		if (tcp->tcp_debug) {
27995 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27996 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27997 		}
27998 		return (-TOUTSTATE);
27999 	} else {
28000 		int32_t len;
28001 		sin6_t	addr;
28002 
28003 		/* Do an implicit bind: Request for a generic port. */
28004 		if (tcp->tcp_family == AF_INET) {
28005 			len = sizeof (sin_t);
28006 			sin = (sin_t *)&addr;
28007 			*sin = sin_null;
28008 			sin->sin_family = AF_INET;
28009 			tcp->tcp_ipversion = IPV4_VERSION;
28010 		} else {
28011 			ASSERT(tcp->tcp_family == AF_INET6);
28012 			len = sizeof (sin6_t);
28013 			sin6 = (sin6_t *)&addr;
28014 			*sin6 = sin6_null;
28015 			sin6->sin6_family = AF_INET6;
28016 			tcp->tcp_ipversion = IPV6_VERSION;
28017 		}
28018 
28019 		error = tcp_bind_check(connp, (struct sockaddr *)&addr, len,
28020 		    cr, B_FALSE);
28021 		if (error)
28022 			return (error);
28023 		/* Fall through and do the fanout insertion */
28024 	}
28025 
28026 do_listen:
28027 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
28028 	tcp->tcp_conn_req_max = backlog;
28029 	if (tcp->tcp_conn_req_max) {
28030 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
28031 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
28032 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
28033 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
28034 		/*
28035 		 * If this is a listener, do not reset the eager list
28036 		 * and other stuffs.  Note that we don't check if the
28037 		 * existing eager list meets the new tcp_conn_req_max
28038 		 * requirement.
28039 		 */
28040 		if (tcp->tcp_state != TCPS_LISTEN) {
28041 			tcp->tcp_state = TCPS_LISTEN;
28042 			/* Initialize the chain. Don't need the eager_lock */
28043 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
28044 			tcp->tcp_eager_next_drop_q0 = tcp;
28045 			tcp->tcp_eager_prev_drop_q0 = tcp;
28046 			tcp->tcp_second_ctimer_threshold =
28047 			    tcps->tcps_ip_abort_linterval;
28048 		}
28049 	}
28050 
28051 	/*
28052 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
28053 	 * processing continues in tcp_rput_other().
28054 	 *
28055 	 * We need to make sure that the conn_recv is set to a non-null
28056 	 * value before we insert the conn into the classifier table.
28057 	 * This is to avoid a race with an incoming packet which does an
28058 	 * ipcl_classify().
28059 	 */
28060 	connp->conn_recv = tcp_conn_request;
28061 	if (tcp->tcp_family == AF_INET) {
28062 		error = ip_proto_bind_laddr_v4(connp, NULL,
28063 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
28064 	} else {
28065 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
28066 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
28067 	}
28068 	return (tcp_post_ip_bind(tcp, NULL, error));
28069 }
28070 
28071 void
28072 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
28073 {
28074 	conn_t  *connp = (conn_t *)proto_handle;
28075 	tcp_t	*tcp = connp->conn_tcp;
28076 	tcp_stack_t	*tcps = tcp->tcp_tcps;
28077 	uint_t thwin;
28078 
28079 	(void) squeue_synch_enter(connp->conn_sqp, connp, 0);
28080 
28081 	/* Flow control condition has been removed. */
28082 	tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
28083 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
28084 	    << tcp->tcp_rcv_ws;
28085 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
28086 	/*
28087 	 * Send back a window update immediately if TCP is above
28088 	 * ESTABLISHED state and the increase of the rcv window
28089 	 * that the other side knows is at least 1 MSS after flow
28090 	 * control is lifted.
28091 	 */
28092 	if (tcp->tcp_state >= TCPS_ESTABLISHED &&
28093 	    (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss)) {
28094 		tcp_xmit_ctl(NULL, tcp,
28095 		    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
28096 		    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
28097 		BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
28098 	}
28099 
28100 	squeue_synch_exit(connp->conn_sqp, connp);
28101 }
28102 
28103 /* ARGSUSED */
28104 int
28105 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
28106     int mode, int32_t *rvalp, cred_t *cr)
28107 {
28108 	conn_t  	*connp = (conn_t *)proto_handle;
28109 	int		error;
28110 
28111 	switch (cmd) {
28112 		case ND_SET:
28113 		case ND_GET:
28114 		case TCP_IOC_DEFAULT_Q:
28115 		case _SIOCSOCKFALLBACK:
28116 		case TCP_IOC_ABORT_CONN:
28117 		case TI_GETPEERNAME:
28118 		case TI_GETMYNAME:
28119 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
28120 			    cmd));
28121 			error = EINVAL;
28122 			break;
28123 		default:
28124 			/*
28125 			 * Pass on to IP using helper stream
28126 			 */
28127 			error = ldi_ioctl(
28128 			    connp->conn_helper_info->ip_helper_stream_handle,
28129 			    cmd, arg, mode, cr, rvalp);
28130 			break;
28131 	}
28132 	return (error);
28133 }
28134 
28135 sock_downcalls_t sock_tcp_downcalls = {
28136 	tcp_activate,
28137 	tcp_accept,
28138 	tcp_bind,
28139 	tcp_listen,
28140 	tcp_connect,
28141 	tcp_getpeername,
28142 	tcp_getsockname,
28143 	tcp_getsockopt,
28144 	tcp_setsockopt,
28145 	tcp_sendmsg,
28146 	NULL,
28147 	NULL,
28148 	NULL,
28149 	tcp_shutdown,
28150 	tcp_clr_flowctrl,
28151 	tcp_ioctl,
28152 	tcp_close,
28153 };
28154