xref: /illumos-gate/usr/src/uts/common/inet/tcp/tcp.c (revision 3589c4f01c20349ca65899d209cdc0c17a641433)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #define	_SUN_TPI_VERSION 2
35 #include <sys/tihdr.h>
36 #include <sys/timod.h>
37 #include <sys/ddi.h>
38 #include <sys/sunddi.h>
39 #include <sys/suntpi.h>
40 #include <sys/xti_inet.h>
41 #include <sys/cmn_err.h>
42 #include <sys/debug.h>
43 #include <sys/sdt.h>
44 #include <sys/vtrace.h>
45 #include <sys/kmem.h>
46 #include <sys/ethernet.h>
47 #include <sys/cpuvar.h>
48 #include <sys/dlpi.h>
49 #include <sys/multidata.h>
50 #include <sys/multidata_impl.h>
51 #include <sys/pattr.h>
52 #include <sys/policy.h>
53 #include <sys/priv.h>
54 #include <sys/zone.h>
55 #include <sys/sunldi.h>
56 
57 #include <sys/errno.h>
58 #include <sys/signal.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/sockio.h>
62 #include <sys/isa_defs.h>
63 #include <sys/md5.h>
64 #include <sys/random.h>
65 #include <sys/sodirect.h>
66 #include <sys/uio.h>
67 #include <sys/systm.h>
68 #include <netinet/in.h>
69 #include <netinet/tcp.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <net/if.h>
73 #include <net/route.h>
74 #include <inet/ipsec_impl.h>
75 
76 #include <inet/common.h>
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip_ndp.h>
81 #include <inet/proto_set.h>
82 #include <inet/mib2.h>
83 #include <inet/nd.h>
84 #include <inet/optcom.h>
85 #include <inet/snmpcom.h>
86 #include <inet/kstatcom.h>
87 #include <inet/tcp.h>
88 #include <inet/tcp_impl.h>
89 #include <inet/udp_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 };
657 
658 #define	TCPOPT_BOUNDIF		0x00000001	/* set IPV6_BOUND_IF */
659 #define	TCPOPT_RECVPKTINFO	0x00000002	/* set IPV6_RECVPKTINFO */
660 
661 /*
662  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
663  */
664 
665 #ifdef _BIG_ENDIAN
666 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
667 	(TCPOPT_TSTAMP << 8) | 10)
668 #else
669 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
670 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
671 #endif
672 
673 /*
674  * Flags returned from tcp_parse_options.
675  */
676 #define	TCP_OPT_MSS_PRESENT	1
677 #define	TCP_OPT_WSCALE_PRESENT	2
678 #define	TCP_OPT_TSTAMP_PRESENT	4
679 #define	TCP_OPT_SACK_OK_PRESENT	8
680 #define	TCP_OPT_SACK_PRESENT	16
681 
682 /* TCP option length */
683 #define	TCPOPT_NOP_LEN		1
684 #define	TCPOPT_MAXSEG_LEN	4
685 #define	TCPOPT_WS_LEN		3
686 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
687 #define	TCPOPT_TSTAMP_LEN	10
688 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
689 #define	TCPOPT_SACK_OK_LEN	2
690 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
691 #define	TCPOPT_REAL_SACK_LEN	4
692 #define	TCPOPT_MAX_SACK_LEN	36
693 #define	TCPOPT_HEADER_LEN	2
694 
695 /* TCP cwnd burst factor. */
696 #define	TCP_CWND_INFINITE	65535
697 #define	TCP_CWND_SS		3
698 #define	TCP_CWND_NORMAL		5
699 
700 /* Maximum TCP initial cwin (start/restart). */
701 #define	TCP_MAX_INIT_CWND	8
702 
703 /*
704  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
705  * either tcp_slow_start_initial or tcp_slow_start_after idle
706  * depending on the caller.  If the upper layer has not used the
707  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
708  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
709  * If the upper layer has changed set the tcp_init_cwnd, just use
710  * it to calculate the tcp_cwnd.
711  */
712 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
713 {									\
714 	if ((tcp)->tcp_init_cwnd == 0) {				\
715 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
716 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
717 	} else {							\
718 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
719 	}								\
720 	tcp->tcp_cwnd_cnt = 0;						\
721 }
722 
723 /* TCP Timer control structure */
724 typedef struct tcpt_s {
725 	pfv_t	tcpt_pfv;	/* The routine we are to call */
726 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
727 } tcpt_t;
728 
729 /* Host Specific Parameter structure */
730 typedef struct tcp_hsp {
731 	struct tcp_hsp	*tcp_hsp_next;
732 	in6_addr_t	tcp_hsp_addr_v6;
733 	in6_addr_t	tcp_hsp_subnet_v6;
734 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
735 	int32_t		tcp_hsp_sendspace;
736 	int32_t		tcp_hsp_recvspace;
737 	int32_t		tcp_hsp_tstamp;
738 } tcp_hsp_t;
739 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
740 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
741 
742 /*
743  * Functions called directly via squeue having a prototype of edesc_t.
744  */
745 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
746 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
747 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
748 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
749 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
750 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
751 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
752 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
753 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
754 void		tcp_output_urgent(void *arg, mblk_t *mp, void *arg2);
755 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
756 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
757 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
758 
759 
760 /* Prototype for TCP functions */
761 static void	tcp_random_init(void);
762 int		tcp_random(void);
763 static void	tcp_tli_accept(tcp_t *tcp, mblk_t *mp);
764 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
765 		    tcp_t *eager);
766 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
767 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
768     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
769     boolean_t user_specified);
770 static void	tcp_closei_local(tcp_t *tcp);
771 static void	tcp_close_detached(tcp_t *tcp);
772 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
773 			mblk_t *idmp, mblk_t **defermp);
774 static void	tcp_tpi_connect(tcp_t *tcp, mblk_t *mp);
775 static int	tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp,
776 		    in_port_t dstport, uint_t srcid, cred_t *cr, pid_t pid);
777 static int 	tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp,
778 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
779 		    uint32_t scope_id, cred_t *cr, pid_t pid);
780 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
781 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
782 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
783 static char	*tcp_display(tcp_t *tcp, char *, char);
784 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
785 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
786 static void	tcp_eager_unlink(tcp_t *tcp);
787 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
788 		    int unixerr);
789 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
790 		    int tlierr, int unixerr);
791 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
792 		    cred_t *cr);
793 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
794 		    char *value, caddr_t cp, cred_t *cr);
795 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
796 		    char *value, caddr_t cp, cred_t *cr);
797 static int	tcp_tpistate(tcp_t *tcp);
798 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
799     int caller_holds_lock);
800 static void	tcp_bind_hash_remove(tcp_t *tcp);
801 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
802 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
803 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
804 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
805 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
806 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
807 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
808 void		tcp_g_q_setup(tcp_stack_t *);
809 void		tcp_g_q_create(tcp_stack_t *);
810 void		tcp_g_q_destroy(tcp_stack_t *);
811 static int	tcp_header_init_ipv4(tcp_t *tcp);
812 static int	tcp_header_init_ipv6(tcp_t *tcp);
813 int		tcp_init(tcp_t *tcp, queue_t *q);
814 static int	tcp_init_values(tcp_t *tcp);
815 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
816 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
817 static void	tcp_ip_notify(tcp_t *tcp);
818 static mblk_t	*tcp_ire_mp(mblk_t **mpp);
819 static void	tcp_iss_init(tcp_t *tcp);
820 static void	tcp_keepalive_killer(void *arg);
821 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
822 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
823 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
824 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
825 static boolean_t tcp_allow_connopt_set(int level, int name);
826 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
827 int		tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
828 int		tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level,
829 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
830 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
831 		    mblk_t *mblk);
832 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
833 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
834 		    uchar_t *ptr, uint_t len);
835 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
836 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
837     tcp_stack_t *);
838 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
839 		    caddr_t cp, cred_t *cr);
840 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
841 		    caddr_t cp, cred_t *cr);
842 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
843 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
844 		    caddr_t cp, cred_t *cr);
845 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
846 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
847 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
848 static void	tcp_reinit(tcp_t *tcp);
849 static void	tcp_reinit_values(tcp_t *tcp);
850 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
851 		    tcp_t *thisstream, cred_t *cr);
852 
853 static uint_t	tcp_rwnd_reopen(tcp_t *tcp);
854 static uint_t	tcp_rcv_drain(tcp_t *tcp);
855 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
856 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
857 static void	tcp_ss_rexmit(tcp_t *tcp);
858 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
859 static void	tcp_process_options(tcp_t *, tcph_t *);
860 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
861 static void	tcp_rsrv(queue_t *q);
862 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
863 static int	tcp_snmp_state(tcp_t *tcp);
864 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
865 		    cred_t *cr);
866 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
867 		    cred_t *cr);
868 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
869 		    cred_t *cr);
870 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
871 		    cred_t *cr);
872 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
873 		    cred_t *cr);
874 static void	tcp_timer(void *arg);
875 static void	tcp_timer_callback(void *);
876 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
877     boolean_t random);
878 static in_port_t tcp_get_next_priv_port(const tcp_t *);
879 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
880 static void	tcp_wput_fallback(queue_t *q, mblk_t *mp);
881 void		tcp_tpi_accept(queue_t *q, mblk_t *mp);
882 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
883 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
884 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
885 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
886 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
887 		    const int num_sack_blk, int *usable, uint_t *snxt,
888 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
889 		    const int mdt_thres);
890 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
891 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
892 		    const int num_sack_blk, int *usable, uint_t *snxt,
893 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
894 		    const int mdt_thres);
895 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
896 		    int num_sack_blk);
897 static void	tcp_wsrv(queue_t *q);
898 static int	tcp_xmit_end(tcp_t *tcp);
899 static void	tcp_ack_timer(void *arg);
900 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
901 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
902 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
903 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
904 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
905 		    uint32_t ack, int ctl);
906 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
907 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
908 static int	setmaxps(queue_t *q, int maxpsz);
909 static void	tcp_set_rto(tcp_t *, time_t);
910 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
911 		    boolean_t, boolean_t);
912 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
913 		    boolean_t ipsec_mctl);
914 static int	tcp_build_hdrs(tcp_t *);
915 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
916 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
917 		    tcph_t *tcph);
918 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
919 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
920 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
921 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
922 		    const boolean_t, const uint32_t, const uint32_t,
923 		    const uint32_t, const uint32_t, tcp_stack_t *);
924 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
925 		    const uint_t, const uint_t, boolean_t *);
926 static mblk_t	*tcp_lso_info_mp(mblk_t *);
927 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
928 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
929 extern mblk_t	*tcp_timermp_alloc(int);
930 extern void	tcp_timermp_free(tcp_t *);
931 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
932 static void	tcp_stop_lingering(tcp_t *tcp);
933 static void	tcp_close_linger_timeout(void *arg);
934 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
935 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
936 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
937 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
938 static void	tcp_g_kstat_fini(kstat_t *);
939 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
940 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
941 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
942 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
943 static int	tcp_kstat_update(kstat_t *kp, int rw);
944 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
945 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
946 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
947 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
948 			tcph_t *tcph, mblk_t *idmp);
949 static int	tcp_squeue_switch(int);
950 
951 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
952 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
953 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
954 static int	tcp_tpi_close(queue_t *, int);
955 static int	tcpclose_accept(queue_t *);
956 
957 static void	tcp_squeue_add(squeue_t *);
958 static boolean_t tcp_zcopy_check(tcp_t *);
959 static void	tcp_zcopy_notify(tcp_t *);
960 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
961 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
962 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
963 
964 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
965 
966 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
967 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
968 
969 static int tcp_accept(sock_lower_handle_t, sock_lower_handle_t,
970 	    sock_upper_handle_t, cred_t *);
971 static int tcp_listen(sock_lower_handle_t, int, cred_t *);
972 static int tcp_post_ip_bind(tcp_t *, mblk_t *, int, cred_t *, pid_t);
973 static int tcp_do_listen(conn_t *, int, cred_t *);
974 static int tcp_do_connect(conn_t *, const struct sockaddr *, socklen_t,
975     cred_t *, pid_t);
976 static int tcp_do_bind(conn_t *, struct sockaddr *, socklen_t, cred_t *,
977     boolean_t);
978 static int tcp_do_unbind(conn_t *);
979 static int tcp_bind_check(conn_t *, struct sockaddr *, socklen_t, cred_t *,
980     boolean_t);
981 
982 static void tcp_ulp_newconn(conn_t *, conn_t *, mblk_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)(netstackid_t stack_id, uint8_t protocol,
1362 			    sa_family_t addr_family, uint8_t *laddrp,
1363 			    in_port_t lport, void *args) = NULL;
1364 void (*cl_inet_unlisten)(netstackid_t stack_id, uint8_t protocol,
1365 			    sa_family_t addr_family, uint8_t *laddrp,
1366 			    in_port_t lport, void *args) = NULL;
1367 
1368 int (*cl_inet_connect2)(netstackid_t stack_id, uint8_t protocol,
1369 			    boolean_t is_outgoing,
1370 			    sa_family_t addr_family,
1371 			    uint8_t *laddrp, in_port_t lport,
1372 			    uint8_t *faddrp, in_port_t fport,
1373 			    void *args) = NULL;
1374 
1375 void (*cl_inet_disconnect)(netstackid_t stack_id, uint8_t protocol,
1376 			    sa_family_t addr_family, uint8_t *laddrp,
1377 			    in_port_t lport, uint8_t *faddrp,
1378 			    in_port_t fport, void *args) = NULL;
1379 
1380 /*
1381  * The following are defined in ip.c
1382  */
1383 extern int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
1384 			    sa_family_t addr_family, uint8_t *laddrp,
1385 			    void *args);
1386 extern uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
1387 			    sa_family_t addr_family, uint8_t *laddrp,
1388 			    uint8_t *faddrp, void *args);
1389 
1390 
1391 /*
1392  * int CL_INET_CONNECT(conn_t *cp, tcp_t *tcp, boolean_t is_outgoing, int err)
1393  */
1394 #define	CL_INET_CONNECT(connp, tcp, is_outgoing, err) {		\
1395 	(err) = 0;						\
1396 	if (cl_inet_connect2 != NULL) {				\
1397 		/*						\
1398 		 * Running in cluster mode - register active connection	\
1399 		 * information						\
1400 		 */							\
1401 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1402 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1403 				(err) = (*cl_inet_connect2)(		\
1404 				    (connp)->conn_netstack->netstack_stackid,\
1405 				    IPPROTO_TCP, is_outgoing, AF_INET,	\
1406 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1407 				    (in_port_t)(tcp)->tcp_lport,	\
1408 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1409 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1410 			}						\
1411 		} else {						\
1412 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1413 			    &(tcp)->tcp_ip6h->ip6_src)) {		\
1414 				(err) = (*cl_inet_connect2)(		\
1415 				    (connp)->conn_netstack->netstack_stackid,\
1416 				    IPPROTO_TCP, is_outgoing, AF_INET6,	\
1417 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1418 				    (in_port_t)(tcp)->tcp_lport,	\
1419 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1420 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1421 			}						\
1422 		}							\
1423 	}								\
1424 }
1425 
1426 #define	CL_INET_DISCONNECT(connp, tcp)	{				\
1427 	if (cl_inet_disconnect != NULL) {				\
1428 		/*							\
1429 		 * Running in cluster mode - deregister active		\
1430 		 * connection information				\
1431 		 */							\
1432 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1433 			if ((tcp)->tcp_ip_src != 0) {			\
1434 				(*cl_inet_disconnect)(			\
1435 				    (connp)->conn_netstack->netstack_stackid,\
1436 				    IPPROTO_TCP, AF_INET,		\
1437 				    (uint8_t *)(&((tcp)->tcp_ip_src)),	\
1438 				    (in_port_t)(tcp)->tcp_lport,	\
1439 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1440 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1441 			}						\
1442 		} else {						\
1443 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1444 			    &(tcp)->tcp_ip_src_v6)) {			\
1445 				(*cl_inet_disconnect)(			\
1446 				    (connp)->conn_netstack->netstack_stackid,\
1447 				    IPPROTO_TCP, AF_INET6,		\
1448 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1449 				    (in_port_t)(tcp)->tcp_lport,	\
1450 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1451 				    (in_port_t)(tcp)->tcp_fport, NULL);	\
1452 			}						\
1453 		}							\
1454 	}								\
1455 }
1456 
1457 /*
1458  * Cluster networking hook for traversing current connection list.
1459  * This routine is used to extract the current list of live connections
1460  * which must continue to to be dispatched to this node.
1461  */
1462 int cl_tcp_walk_list(netstackid_t stack_id,
1463     int (*callback)(cl_tcp_info_t *, void *), void *arg);
1464 
1465 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1466     void *arg, tcp_stack_t *tcps);
1467 
1468 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1469 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1470 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1471 	    ip6_t *, ip6h, int, 0);
1472 
1473 /*
1474  * Figure out the value of window scale opton.  Note that the rwnd is
1475  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1476  * We cannot find the scale value and then do a round up of tcp_rwnd
1477  * because the scale value may not be correct after that.
1478  *
1479  * Set the compiler flag to make this function inline.
1480  */
1481 static void
1482 tcp_set_ws_value(tcp_t *tcp)
1483 {
1484 	int i;
1485 	uint32_t rwnd = tcp->tcp_rwnd;
1486 
1487 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1488 	    i++, rwnd >>= 1)
1489 		;
1490 	tcp->tcp_rcv_ws = i;
1491 }
1492 
1493 /*
1494  * Remove a connection from the list of detached TIME_WAIT connections.
1495  * It returns B_FALSE if it can't remove the connection from the list
1496  * as the connection has already been removed from the list due to an
1497  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1498  */
1499 static boolean_t
1500 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1501 {
1502 	boolean_t	locked = B_FALSE;
1503 
1504 	if (tcp_time_wait == NULL) {
1505 		tcp_time_wait = *((tcp_squeue_priv_t **)
1506 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1507 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1508 		locked = B_TRUE;
1509 	} else {
1510 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1511 	}
1512 
1513 	if (tcp->tcp_time_wait_expire == 0) {
1514 		ASSERT(tcp->tcp_time_wait_next == NULL);
1515 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1516 		if (locked)
1517 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1518 		return (B_FALSE);
1519 	}
1520 	ASSERT(TCP_IS_DETACHED(tcp));
1521 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1522 
1523 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1524 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1525 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1526 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1527 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1528 			    NULL;
1529 		} else {
1530 			tcp_time_wait->tcp_time_wait_tail = NULL;
1531 		}
1532 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1533 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1534 		ASSERT(tcp->tcp_time_wait_next == NULL);
1535 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1536 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1537 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1538 	} else {
1539 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1540 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1541 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1542 		    tcp->tcp_time_wait_next;
1543 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1544 		    tcp->tcp_time_wait_prev;
1545 	}
1546 	tcp->tcp_time_wait_next = NULL;
1547 	tcp->tcp_time_wait_prev = NULL;
1548 	tcp->tcp_time_wait_expire = 0;
1549 
1550 	if (locked)
1551 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1552 	return (B_TRUE);
1553 }
1554 
1555 /*
1556  * Add a connection to the list of detached TIME_WAIT connections
1557  * and set its time to expire.
1558  */
1559 static void
1560 tcp_time_wait_append(tcp_t *tcp)
1561 {
1562 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1563 	tcp_squeue_priv_t *tcp_time_wait =
1564 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1565 	    SQPRIVATE_TCP));
1566 
1567 	tcp_timers_stop(tcp);
1568 
1569 	/* Freed above */
1570 	ASSERT(tcp->tcp_timer_tid == 0);
1571 	ASSERT(tcp->tcp_ack_tid == 0);
1572 
1573 	/* must have happened at the time of detaching the tcp */
1574 	ASSERT(tcp->tcp_ptpahn == NULL);
1575 	ASSERT(tcp->tcp_flow_stopped == 0);
1576 	ASSERT(tcp->tcp_time_wait_next == NULL);
1577 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1578 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1579 	ASSERT(tcp->tcp_listener == NULL);
1580 
1581 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1582 	/*
1583 	 * The value computed below in tcp->tcp_time_wait_expire may
1584 	 * appear negative or wrap around. That is ok since our
1585 	 * interest is only in the difference between the current lbolt
1586 	 * value and tcp->tcp_time_wait_expire. But the value should not
1587 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1588 	 * The corresponding comparison in tcp_time_wait_collector() uses
1589 	 * modular arithmetic.
1590 	 */
1591 	tcp->tcp_time_wait_expire +=
1592 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1593 	if (tcp->tcp_time_wait_expire == 0)
1594 		tcp->tcp_time_wait_expire = 1;
1595 
1596 	ASSERT(TCP_IS_DETACHED(tcp));
1597 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1598 	ASSERT(tcp->tcp_time_wait_next == NULL);
1599 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1600 	TCP_DBGSTAT(tcps, tcp_time_wait);
1601 
1602 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1603 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1604 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1605 		tcp_time_wait->tcp_time_wait_head = tcp;
1606 	} else {
1607 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1608 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1609 		    TCPS_TIME_WAIT);
1610 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1611 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1612 	}
1613 	tcp_time_wait->tcp_time_wait_tail = tcp;
1614 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1615 }
1616 
1617 /* ARGSUSED */
1618 void
1619 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1620 {
1621 	conn_t	*connp = (conn_t *)arg;
1622 	tcp_t	*tcp = connp->conn_tcp;
1623 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1624 
1625 	ASSERT(tcp != NULL);
1626 	if (tcp->tcp_state == TCPS_CLOSED) {
1627 		return;
1628 	}
1629 
1630 	ASSERT((tcp->tcp_family == AF_INET &&
1631 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1632 	    (tcp->tcp_family == AF_INET6 &&
1633 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1634 	    tcp->tcp_ipversion == IPV6_VERSION)));
1635 	ASSERT(!tcp->tcp_listener);
1636 
1637 	TCP_STAT(tcps, tcp_time_wait_reap);
1638 	ASSERT(TCP_IS_DETACHED(tcp));
1639 
1640 	/*
1641 	 * Because they have no upstream client to rebind or tcp_close()
1642 	 * them later, we axe the connection here and now.
1643 	 */
1644 	tcp_close_detached(tcp);
1645 }
1646 
1647 /*
1648  * Remove cached/latched IPsec references.
1649  */
1650 void
1651 tcp_ipsec_cleanup(tcp_t *tcp)
1652 {
1653 	conn_t		*connp = tcp->tcp_connp;
1654 
1655 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1656 
1657 	if (connp->conn_latch != NULL) {
1658 		IPLATCH_REFRELE(connp->conn_latch,
1659 		    connp->conn_netstack);
1660 		connp->conn_latch = NULL;
1661 	}
1662 	if (connp->conn_policy != NULL) {
1663 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1664 		connp->conn_policy = NULL;
1665 	}
1666 }
1667 
1668 /*
1669  * Cleaup before placing on free list.
1670  * Disassociate from the netstack/tcp_stack_t since the freelist
1671  * is per squeue and not per netstack.
1672  */
1673 void
1674 tcp_cleanup(tcp_t *tcp)
1675 {
1676 	mblk_t		*mp;
1677 	char		*tcp_iphc;
1678 	int		tcp_iphc_len;
1679 	int		tcp_hdr_grown;
1680 	tcp_sack_info_t	*tcp_sack_info;
1681 	conn_t		*connp = tcp->tcp_connp;
1682 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1683 	netstack_t	*ns = tcps->tcps_netstack;
1684 	mblk_t		*tcp_rsrv_mp;
1685 
1686 	tcp_bind_hash_remove(tcp);
1687 
1688 	/* Cleanup that which needs the netstack first */
1689 	tcp_ipsec_cleanup(tcp);
1690 
1691 	tcp_free(tcp);
1692 
1693 	/* Release any SSL context */
1694 	if (tcp->tcp_kssl_ent != NULL) {
1695 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1696 		tcp->tcp_kssl_ent = NULL;
1697 	}
1698 
1699 	if (tcp->tcp_kssl_ctx != NULL) {
1700 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1701 		tcp->tcp_kssl_ctx = NULL;
1702 	}
1703 	tcp->tcp_kssl_pending = B_FALSE;
1704 
1705 	conn_delete_ire(connp, NULL);
1706 
1707 	/*
1708 	 * Since we will bzero the entire structure, we need to
1709 	 * remove it and reinsert it in global hash list. We
1710 	 * know the walkers can't get to this conn because we
1711 	 * had set CONDEMNED flag earlier and checked reference
1712 	 * under conn_lock so walker won't pick it and when we
1713 	 * go the ipcl_globalhash_remove() below, no walker
1714 	 * can get to it.
1715 	 */
1716 	ipcl_globalhash_remove(connp);
1717 
1718 	/*
1719 	 * Now it is safe to decrement the reference counts.
1720 	 * This might be the last reference on the netstack and TCPS
1721 	 * in which case it will cause the tcp_g_q_close and
1722 	 * the freeing of the IP Instance.
1723 	 */
1724 	connp->conn_netstack = NULL;
1725 	netstack_rele(ns);
1726 	ASSERT(tcps != NULL);
1727 	tcp->tcp_tcps = NULL;
1728 	TCPS_REFRELE(tcps);
1729 
1730 	/* Save some state */
1731 	mp = tcp->tcp_timercache;
1732 
1733 	tcp_sack_info = tcp->tcp_sack_info;
1734 	tcp_iphc = tcp->tcp_iphc;
1735 	tcp_iphc_len = tcp->tcp_iphc_len;
1736 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1737 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1738 
1739 	if (connp->conn_cred != NULL) {
1740 		crfree(connp->conn_cred);
1741 		connp->conn_cred = NULL;
1742 	}
1743 	if (connp->conn_peercred != NULL) {
1744 		crfree(connp->conn_peercred);
1745 		connp->conn_peercred = NULL;
1746 	}
1747 	ipcl_conn_cleanup(connp);
1748 	connp->conn_flags = IPCL_TCPCONN;
1749 	bzero(tcp, sizeof (tcp_t));
1750 
1751 	/* restore the state */
1752 	tcp->tcp_timercache = mp;
1753 
1754 	tcp->tcp_sack_info = tcp_sack_info;
1755 	tcp->tcp_iphc = tcp_iphc;
1756 	tcp->tcp_iphc_len = tcp_iphc_len;
1757 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1758 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1759 
1760 	tcp->tcp_connp = connp;
1761 
1762 	ASSERT(connp->conn_tcp == tcp);
1763 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1764 	connp->conn_state_flags = CONN_INCIPIENT;
1765 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1766 	ASSERT(connp->conn_ref == 1);
1767 }
1768 
1769 /*
1770  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1771  * is done forwards from the head.
1772  * This walks all stack instances since
1773  * tcp_time_wait remains global across all stacks.
1774  */
1775 /* ARGSUSED */
1776 void
1777 tcp_time_wait_collector(void *arg)
1778 {
1779 	tcp_t *tcp;
1780 	clock_t now;
1781 	mblk_t *mp;
1782 	conn_t *connp;
1783 	kmutex_t *lock;
1784 	boolean_t removed;
1785 
1786 	squeue_t *sqp = (squeue_t *)arg;
1787 	tcp_squeue_priv_t *tcp_time_wait =
1788 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1789 
1790 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1791 	tcp_time_wait->tcp_time_wait_tid = 0;
1792 
1793 	if (tcp_time_wait->tcp_free_list != NULL &&
1794 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1795 		TCP_G_STAT(tcp_freelist_cleanup);
1796 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1797 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1798 			tcp->tcp_time_wait_next = NULL;
1799 			tcp_time_wait->tcp_free_list_cnt--;
1800 			ASSERT(tcp->tcp_tcps == NULL);
1801 			CONN_DEC_REF(tcp->tcp_connp);
1802 		}
1803 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1804 	}
1805 
1806 	/*
1807 	 * In order to reap time waits reliably, we should use a
1808 	 * source of time that is not adjustable by the user -- hence
1809 	 * the call to ddi_get_lbolt().
1810 	 */
1811 	now = ddi_get_lbolt();
1812 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1813 		/*
1814 		 * Compare times using modular arithmetic, since
1815 		 * lbolt can wrapover.
1816 		 */
1817 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1818 			break;
1819 		}
1820 
1821 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1822 		ASSERT(removed);
1823 
1824 		connp = tcp->tcp_connp;
1825 		ASSERT(connp->conn_fanout != NULL);
1826 		lock = &connp->conn_fanout->connf_lock;
1827 		/*
1828 		 * This is essentially a TW reclaim fast path optimization for
1829 		 * performance where the timewait collector checks under the
1830 		 * fanout lock (so that no one else can get access to the
1831 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1832 		 * the classifier hash list. If ref count is indeed 2, we can
1833 		 * just remove the conn under the fanout lock and avoid
1834 		 * cleaning up the conn under the squeue, provided that
1835 		 * clustering callbacks are not enabled. If clustering is
1836 		 * enabled, we need to make the clustering callback before
1837 		 * setting the CONDEMNED flag and after dropping all locks and
1838 		 * so we forego this optimization and fall back to the slow
1839 		 * path. Also please see the comments in tcp_closei_local
1840 		 * regarding the refcnt logic.
1841 		 *
1842 		 * Since we are holding the tcp_time_wait_lock, its better
1843 		 * not to block on the fanout_lock because other connections
1844 		 * can't add themselves to time_wait list. So we do a
1845 		 * tryenter instead of mutex_enter.
1846 		 */
1847 		if (mutex_tryenter(lock)) {
1848 			mutex_enter(&connp->conn_lock);
1849 			if ((connp->conn_ref == 2) &&
1850 			    (cl_inet_disconnect == NULL)) {
1851 				ipcl_hash_remove_locked(connp,
1852 				    connp->conn_fanout);
1853 				/*
1854 				 * Set the CONDEMNED flag now itself so that
1855 				 * the refcnt cannot increase due to any
1856 				 * walker. But we have still not cleaned up
1857 				 * conn_ire_cache. This is still ok since
1858 				 * we are going to clean it up in tcp_cleanup
1859 				 * immediately and any interface unplumb
1860 				 * thread will wait till the ire is blown away
1861 				 */
1862 				connp->conn_state_flags |= CONN_CONDEMNED;
1863 				mutex_exit(lock);
1864 				mutex_exit(&connp->conn_lock);
1865 				if (tcp_time_wait->tcp_free_list_cnt <
1866 				    tcp_free_list_max_cnt) {
1867 					/* Add to head of tcp_free_list */
1868 					mutex_exit(
1869 					    &tcp_time_wait->tcp_time_wait_lock);
1870 					tcp_cleanup(tcp);
1871 					ASSERT(connp->conn_latch == NULL);
1872 					ASSERT(connp->conn_policy == NULL);
1873 					ASSERT(tcp->tcp_tcps == NULL);
1874 					ASSERT(connp->conn_netstack == NULL);
1875 
1876 					mutex_enter(
1877 					    &tcp_time_wait->tcp_time_wait_lock);
1878 					tcp->tcp_time_wait_next =
1879 					    tcp_time_wait->tcp_free_list;
1880 					tcp_time_wait->tcp_free_list = tcp;
1881 					tcp_time_wait->tcp_free_list_cnt++;
1882 					continue;
1883 				} else {
1884 					/* Do not add to tcp_free_list */
1885 					mutex_exit(
1886 					    &tcp_time_wait->tcp_time_wait_lock);
1887 					tcp_bind_hash_remove(tcp);
1888 					conn_delete_ire(tcp->tcp_connp, NULL);
1889 					tcp_ipsec_cleanup(tcp);
1890 					CONN_DEC_REF(tcp->tcp_connp);
1891 				}
1892 			} else {
1893 				CONN_INC_REF_LOCKED(connp);
1894 				mutex_exit(lock);
1895 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1896 				mutex_exit(&connp->conn_lock);
1897 				/*
1898 				 * We can reuse the closemp here since conn has
1899 				 * detached (otherwise we wouldn't even be in
1900 				 * time_wait list). tcp_closemp_used can safely
1901 				 * be changed without taking a lock as no other
1902 				 * thread can concurrently access it at this
1903 				 * point in the connection lifecycle.
1904 				 */
1905 
1906 				if (tcp->tcp_closemp.b_prev == NULL)
1907 					tcp->tcp_closemp_used = B_TRUE;
1908 				else
1909 					cmn_err(CE_PANIC,
1910 					    "tcp_timewait_collector: "
1911 					    "concurrent use of tcp_closemp: "
1912 					    "connp %p tcp %p\n", (void *)connp,
1913 					    (void *)tcp);
1914 
1915 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1916 				mp = &tcp->tcp_closemp;
1917 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1918 				    tcp_timewait_output, connp,
1919 				    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1920 			}
1921 		} else {
1922 			mutex_enter(&connp->conn_lock);
1923 			CONN_INC_REF_LOCKED(connp);
1924 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1925 			mutex_exit(&connp->conn_lock);
1926 			/*
1927 			 * We can reuse the closemp here since conn has
1928 			 * detached (otherwise we wouldn't even be in
1929 			 * time_wait list). tcp_closemp_used can safely
1930 			 * be changed without taking a lock as no other
1931 			 * thread can concurrently access it at this
1932 			 * point in the connection lifecycle.
1933 			 */
1934 
1935 			if (tcp->tcp_closemp.b_prev == NULL)
1936 				tcp->tcp_closemp_used = B_TRUE;
1937 			else
1938 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1939 				    "concurrent use of tcp_closemp: "
1940 				    "connp %p tcp %p\n", (void *)connp,
1941 				    (void *)tcp);
1942 
1943 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1944 			mp = &tcp->tcp_closemp;
1945 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
1946 			    tcp_timewait_output, connp,
1947 			    SQ_FILL, SQTAG_TCP_TIMEWAIT);
1948 		}
1949 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1950 	}
1951 
1952 	if (tcp_time_wait->tcp_free_list != NULL)
1953 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1954 
1955 	tcp_time_wait->tcp_time_wait_tid =
1956 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1957 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1958 	    CALLOUT_FLAG_ROUNDUP);
1959 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1960 }
1961 
1962 /*
1963  * Reply to a clients T_CONN_RES TPI message. This function
1964  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1965  * on the acceptor STREAM and processed in tcp_wput_accept().
1966  * Read the block comment on top of tcp_conn_request().
1967  */
1968 static void
1969 tcp_tli_accept(tcp_t *listener, mblk_t *mp)
1970 {
1971 	tcp_t	*acceptor;
1972 	tcp_t	*eager;
1973 	tcp_t   *tcp;
1974 	struct T_conn_res	*tcr;
1975 	t_uscalar_t	acceptor_id;
1976 	t_scalar_t	seqnum;
1977 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1978 	struct tcp_options *tcpopt;
1979 	mblk_t	*ok_mp;
1980 	mblk_t	*mp1;
1981 	tcp_stack_t	*tcps = listener->tcp_tcps;
1982 
1983 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1984 		tcp_err_ack(listener, mp, TPROTO, 0);
1985 		return;
1986 	}
1987 	tcr = (struct T_conn_res *)mp->b_rptr;
1988 
1989 	/*
1990 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1991 	 * read side queue of the streams device underneath us i.e. the
1992 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1993 	 * look it up in the queue_hash.  Under LP64 it sends down the
1994 	 * minor_t of the accepting endpoint.
1995 	 *
1996 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1997 	 * fanout hash lock is held.
1998 	 * This prevents any thread from entering the acceptor queue from
1999 	 * below (since it has not been hard bound yet i.e. any inbound
2000 	 * packets will arrive on the listener or default tcp queue and
2001 	 * go through tcp_lookup).
2002 	 * The CONN_INC_REF will prevent the acceptor from closing.
2003 	 *
2004 	 * XXX It is still possible for a tli application to send down data
2005 	 * on the accepting stream while another thread calls t_accept.
2006 	 * This should not be a problem for well-behaved applications since
2007 	 * the T_OK_ACK is sent after the queue swapping is completed.
2008 	 *
2009 	 * If the accepting fd is the same as the listening fd, avoid
2010 	 * queue hash lookup since that will return an eager listener in a
2011 	 * already established state.
2012 	 */
2013 	acceptor_id = tcr->ACCEPTOR_id;
2014 	mutex_enter(&listener->tcp_eager_lock);
2015 	if (listener->tcp_acceptor_id == acceptor_id) {
2016 		eager = listener->tcp_eager_next_q;
2017 		/* only count how many T_CONN_INDs so don't count q0 */
2018 		if ((listener->tcp_conn_req_cnt_q != 1) ||
2019 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
2020 			mutex_exit(&listener->tcp_eager_lock);
2021 			tcp_err_ack(listener, mp, TBADF, 0);
2022 			return;
2023 		}
2024 		if (listener->tcp_conn_req_cnt_q0 != 0) {
2025 			/* Throw away all the eagers on q0. */
2026 			tcp_eager_cleanup(listener, 1);
2027 		}
2028 		if (listener->tcp_syn_defense) {
2029 			listener->tcp_syn_defense = B_FALSE;
2030 			if (listener->tcp_ip_addr_cache != NULL) {
2031 				kmem_free(listener->tcp_ip_addr_cache,
2032 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
2033 				listener->tcp_ip_addr_cache = NULL;
2034 			}
2035 		}
2036 		/*
2037 		 * Transfer tcp_conn_req_max to the eager so that when
2038 		 * a disconnect occurs we can revert the endpoint to the
2039 		 * listen state.
2040 		 */
2041 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
2042 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
2043 		/*
2044 		 * Get a reference on the acceptor just like the
2045 		 * tcp_acceptor_hash_lookup below.
2046 		 */
2047 		acceptor = listener;
2048 		CONN_INC_REF(acceptor->tcp_connp);
2049 	} else {
2050 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
2051 		if (acceptor == NULL) {
2052 			if (listener->tcp_debug) {
2053 				(void) strlog(TCP_MOD_ID, 0, 1,
2054 				    SL_ERROR|SL_TRACE,
2055 				    "tcp_accept: did not find acceptor 0x%x\n",
2056 				    acceptor_id);
2057 			}
2058 			mutex_exit(&listener->tcp_eager_lock);
2059 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2060 			return;
2061 		}
2062 		/*
2063 		 * Verify acceptor state. The acceptable states for an acceptor
2064 		 * include TCPS_IDLE and TCPS_BOUND.
2065 		 */
2066 		switch (acceptor->tcp_state) {
2067 		case TCPS_IDLE:
2068 			/* FALLTHRU */
2069 		case TCPS_BOUND:
2070 			break;
2071 		default:
2072 			CONN_DEC_REF(acceptor->tcp_connp);
2073 			mutex_exit(&listener->tcp_eager_lock);
2074 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2075 			return;
2076 		}
2077 	}
2078 
2079 	/* The listener must be in TCPS_LISTEN */
2080 	if (listener->tcp_state != TCPS_LISTEN) {
2081 		CONN_DEC_REF(acceptor->tcp_connp);
2082 		mutex_exit(&listener->tcp_eager_lock);
2083 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2084 		return;
2085 	}
2086 
2087 	/*
2088 	 * Rendezvous with an eager connection request packet hanging off
2089 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2090 	 * tcp structure when the connection packet arrived in
2091 	 * tcp_conn_request().
2092 	 */
2093 	seqnum = tcr->SEQ_number;
2094 	eager = listener;
2095 	do {
2096 		eager = eager->tcp_eager_next_q;
2097 		if (eager == NULL) {
2098 			CONN_DEC_REF(acceptor->tcp_connp);
2099 			mutex_exit(&listener->tcp_eager_lock);
2100 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2101 			return;
2102 		}
2103 	} while (eager->tcp_conn_req_seqnum != seqnum);
2104 	mutex_exit(&listener->tcp_eager_lock);
2105 
2106 	/*
2107 	 * At this point, both acceptor and listener have 2 ref
2108 	 * that they begin with. Acceptor has one additional ref
2109 	 * we placed in lookup while listener has 3 additional
2110 	 * ref for being behind the squeue (tcp_accept() is
2111 	 * done on listener's squeue); being in classifier hash;
2112 	 * and eager's ref on listener.
2113 	 */
2114 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2115 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2116 
2117 	/*
2118 	 * The eager at this point is set in its own squeue and
2119 	 * could easily have been killed (tcp_accept_finish will
2120 	 * deal with that) because of a TH_RST so we can only
2121 	 * ASSERT for a single ref.
2122 	 */
2123 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2124 
2125 	/* Pre allocate the stroptions mblk also */
2126 	opt_mp = allocb(MAX(sizeof (struct tcp_options),
2127 	    sizeof (struct T_conn_res)), BPRI_HI);
2128 	if (opt_mp == NULL) {
2129 		CONN_DEC_REF(acceptor->tcp_connp);
2130 		CONN_DEC_REF(eager->tcp_connp);
2131 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2132 		return;
2133 	}
2134 	DB_TYPE(opt_mp) = M_SETOPTS;
2135 	opt_mp->b_wptr += sizeof (struct tcp_options);
2136 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
2137 	tcpopt->to_flags = 0;
2138 
2139 	/*
2140 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2141 	 * from listener to acceptor.
2142 	 */
2143 	if (listener->tcp_bound_if != 0) {
2144 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
2145 		tcpopt->to_boundif = listener->tcp_bound_if;
2146 	}
2147 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2148 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
2149 	}
2150 
2151 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2152 	if ((mp1 = copymsg(mp)) == NULL) {
2153 		CONN_DEC_REF(acceptor->tcp_connp);
2154 		CONN_DEC_REF(eager->tcp_connp);
2155 		freemsg(opt_mp);
2156 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2157 		return;
2158 	}
2159 
2160 	tcr = (struct T_conn_res *)mp1->b_rptr;
2161 
2162 	/*
2163 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2164 	 * which allocates a larger mblk and appends the new
2165 	 * local address to the ok_ack.  The address is copied by
2166 	 * soaccept() for getsockname().
2167 	 */
2168 	{
2169 		int extra;
2170 
2171 		extra = (eager->tcp_family == AF_INET) ?
2172 		    sizeof (sin_t) : sizeof (sin6_t);
2173 
2174 		/*
2175 		 * Try to re-use mp, if possible.  Otherwise, allocate
2176 		 * an mblk and return it as ok_mp.  In any case, mp
2177 		 * is no longer usable upon return.
2178 		 */
2179 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2180 			CONN_DEC_REF(acceptor->tcp_connp);
2181 			CONN_DEC_REF(eager->tcp_connp);
2182 			freemsg(opt_mp);
2183 			/* Original mp has been freed by now, so use mp1 */
2184 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2185 			return;
2186 		}
2187 
2188 		mp = NULL;	/* We should never use mp after this point */
2189 
2190 		switch (extra) {
2191 		case sizeof (sin_t): {
2192 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2193 
2194 				ok_mp->b_wptr += extra;
2195 				sin->sin_family = AF_INET;
2196 				sin->sin_port = eager->tcp_lport;
2197 				sin->sin_addr.s_addr =
2198 				    eager->tcp_ipha->ipha_src;
2199 				break;
2200 			}
2201 		case sizeof (sin6_t): {
2202 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2203 
2204 				ok_mp->b_wptr += extra;
2205 				sin6->sin6_family = AF_INET6;
2206 				sin6->sin6_port = eager->tcp_lport;
2207 				if (eager->tcp_ipversion == IPV4_VERSION) {
2208 					sin6->sin6_flowinfo = 0;
2209 					IN6_IPADDR_TO_V4MAPPED(
2210 					    eager->tcp_ipha->ipha_src,
2211 					    &sin6->sin6_addr);
2212 				} else {
2213 					ASSERT(eager->tcp_ip6h != NULL);
2214 					sin6->sin6_flowinfo =
2215 					    eager->tcp_ip6h->ip6_vcf &
2216 					    ~IPV6_VERS_AND_FLOW_MASK;
2217 					sin6->sin6_addr =
2218 					    eager->tcp_ip6h->ip6_src;
2219 				}
2220 				sin6->sin6_scope_id = 0;
2221 				sin6->__sin6_src_id = 0;
2222 				break;
2223 			}
2224 		default:
2225 			break;
2226 		}
2227 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2228 	}
2229 
2230 	/*
2231 	 * If there are no options we know that the T_CONN_RES will
2232 	 * succeed. However, we can't send the T_OK_ACK upstream until
2233 	 * the tcp_accept_swap is done since it would be dangerous to
2234 	 * let the application start using the new fd prior to the swap.
2235 	 */
2236 	tcp_accept_swap(listener, acceptor, eager);
2237 
2238 	/*
2239 	 * tcp_accept_swap unlinks eager from listener but does not drop
2240 	 * the eager's reference on the listener.
2241 	 */
2242 	ASSERT(eager->tcp_listener == NULL);
2243 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2244 
2245 	/*
2246 	 * The eager is now associated with its own queue. Insert in
2247 	 * the hash so that the connection can be reused for a future
2248 	 * T_CONN_RES.
2249 	 */
2250 	tcp_acceptor_hash_insert(acceptor_id, eager);
2251 
2252 	/*
2253 	 * We now do the processing of options with T_CONN_RES.
2254 	 * We delay till now since we wanted to have queue to pass to
2255 	 * option processing routines that points back to the right
2256 	 * instance structure which does not happen until after
2257 	 * tcp_accept_swap().
2258 	 *
2259 	 * Note:
2260 	 * The sanity of the logic here assumes that whatever options
2261 	 * are appropriate to inherit from listner=>eager are done
2262 	 * before this point, and whatever were to be overridden (or not)
2263 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2264 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2265 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2266 	 * This may not be true at this point in time but can be fixed
2267 	 * independently. This option processing code starts with
2268 	 * the instantiated acceptor instance and the final queue at
2269 	 * this point.
2270 	 */
2271 
2272 	if (tcr->OPT_length != 0) {
2273 		/* Options to process */
2274 		int t_error = 0;
2275 		int sys_error = 0;
2276 		int do_disconnect = 0;
2277 
2278 		if (tcp_conprim_opt_process(eager, mp1,
2279 		    &do_disconnect, &t_error, &sys_error) < 0) {
2280 			eager->tcp_accept_error = 1;
2281 			if (do_disconnect) {
2282 				/*
2283 				 * An option failed which does not allow
2284 				 * connection to be accepted.
2285 				 *
2286 				 * We allow T_CONN_RES to succeed and
2287 				 * put a T_DISCON_IND on the eager queue.
2288 				 */
2289 				ASSERT(t_error == 0 && sys_error == 0);
2290 				eager->tcp_send_discon_ind = 1;
2291 			} else {
2292 				ASSERT(t_error != 0);
2293 				freemsg(ok_mp);
2294 				/*
2295 				 * Original mp was either freed or set
2296 				 * to ok_mp above, so use mp1 instead.
2297 				 */
2298 				tcp_err_ack(listener, mp1, t_error, sys_error);
2299 				goto finish;
2300 			}
2301 		}
2302 		/*
2303 		 * Most likely success in setting options (except if
2304 		 * eager->tcp_send_discon_ind set).
2305 		 * mp1 option buffer represented by OPT_length/offset
2306 		 * potentially modified and contains results of setting
2307 		 * options at this point
2308 		 */
2309 	}
2310 
2311 	/* We no longer need mp1, since all options processing has passed */
2312 	freemsg(mp1);
2313 
2314 	putnext(listener->tcp_rq, ok_mp);
2315 
2316 	mutex_enter(&listener->tcp_eager_lock);
2317 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2318 		tcp_t	*tail;
2319 		mblk_t	*conn_ind;
2320 
2321 		/*
2322 		 * This path should not be executed if listener and
2323 		 * acceptor streams are the same.
2324 		 */
2325 		ASSERT(listener != acceptor);
2326 
2327 		tcp = listener->tcp_eager_prev_q0;
2328 		/*
2329 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2330 		 * deferred T_conn_ind queue. We need to get to the head of
2331 		 * the queue in order to send up T_conn_ind the same order as
2332 		 * how the 3WHS is completed.
2333 		 */
2334 		while (tcp != listener) {
2335 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2336 				break;
2337 			else
2338 				tcp = tcp->tcp_eager_prev_q0;
2339 		}
2340 		ASSERT(tcp != listener);
2341 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2342 		ASSERT(conn_ind != NULL);
2343 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2344 
2345 		/* Move from q0 to q */
2346 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2347 		listener->tcp_conn_req_cnt_q0--;
2348 		listener->tcp_conn_req_cnt_q++;
2349 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2350 		    tcp->tcp_eager_prev_q0;
2351 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2352 		    tcp->tcp_eager_next_q0;
2353 		tcp->tcp_eager_prev_q0 = NULL;
2354 		tcp->tcp_eager_next_q0 = NULL;
2355 		tcp->tcp_conn_def_q0 = B_FALSE;
2356 
2357 		/* Make sure the tcp isn't in the list of droppables */
2358 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2359 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2360 
2361 		/*
2362 		 * Insert at end of the queue because sockfs sends
2363 		 * down T_CONN_RES in chronological order. Leaving
2364 		 * the older conn indications at front of the queue
2365 		 * helps reducing search time.
2366 		 */
2367 		tail = listener->tcp_eager_last_q;
2368 		if (tail != NULL)
2369 			tail->tcp_eager_next_q = tcp;
2370 		else
2371 			listener->tcp_eager_next_q = tcp;
2372 		listener->tcp_eager_last_q = tcp;
2373 		tcp->tcp_eager_next_q = NULL;
2374 		mutex_exit(&listener->tcp_eager_lock);
2375 		putnext(tcp->tcp_rq, conn_ind);
2376 	} else {
2377 		mutex_exit(&listener->tcp_eager_lock);
2378 	}
2379 
2380 	/*
2381 	 * Done with the acceptor - free it
2382 	 *
2383 	 * Note: from this point on, no access to listener should be made
2384 	 * as listener can be equal to acceptor.
2385 	 */
2386 finish:
2387 	ASSERT(acceptor->tcp_detached);
2388 	ASSERT(tcps->tcps_g_q != NULL);
2389 	ASSERT(!IPCL_IS_NONSTR(acceptor->tcp_connp));
2390 	acceptor->tcp_rq = tcps->tcps_g_q;
2391 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2392 	(void) tcp_clean_death(acceptor, 0, 2);
2393 	CONN_DEC_REF(acceptor->tcp_connp);
2394 
2395 	/*
2396 	 * In case we already received a FIN we have to make tcp_rput send
2397 	 * the ordrel_ind. This will also send up a window update if the window
2398 	 * has opened up.
2399 	 *
2400 	 * In the normal case of a successful connection acceptance
2401 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2402 	 * indication that this was just accepted. This tells tcp_rput to
2403 	 * pass up any data queued in tcp_rcv_list.
2404 	 *
2405 	 * In the fringe case where options sent with T_CONN_RES failed and
2406 	 * we required, we would be indicating a T_DISCON_IND to blow
2407 	 * away this connection.
2408 	 */
2409 
2410 	/*
2411 	 * XXX: we currently have a problem if XTI application closes the
2412 	 * acceptor stream in between. This problem exists in on10-gate also
2413 	 * and is well know but nothing can be done short of major rewrite
2414 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2415 	 * eager same squeue as listener (we can distinguish non socket
2416 	 * listeners at the time of handling a SYN in tcp_conn_request)
2417 	 * and do most of the work that tcp_accept_finish does here itself
2418 	 * and then get behind the acceptor squeue to access the acceptor
2419 	 * queue.
2420 	 */
2421 	/*
2422 	 * We already have a ref on tcp so no need to do one before squeue_enter
2423 	 */
2424 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, opt_mp, tcp_accept_finish,
2425 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_ACCEPT_FINISH);
2426 }
2427 
2428 /*
2429  * Swap information between the eager and acceptor for a TLI/XTI client.
2430  * The sockfs accept is done on the acceptor stream and control goes
2431  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2432  * called. In either case, both the eager and listener are in their own
2433  * perimeter (squeue) and the code has to deal with potential race.
2434  *
2435  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2436  */
2437 static void
2438 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2439 {
2440 	conn_t	*econnp, *aconnp;
2441 
2442 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2443 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2444 	ASSERT(!eager->tcp_hard_bound);
2445 	ASSERT(!TCP_IS_SOCKET(acceptor));
2446 	ASSERT(!TCP_IS_SOCKET(eager));
2447 	ASSERT(!TCP_IS_SOCKET(listener));
2448 
2449 	acceptor->tcp_detached = B_TRUE;
2450 	/*
2451 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2452 	 * the acceptor id.
2453 	 */
2454 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2455 
2456 	/* remove eager from listen list... */
2457 	mutex_enter(&listener->tcp_eager_lock);
2458 	tcp_eager_unlink(eager);
2459 	ASSERT(eager->tcp_eager_next_q == NULL &&
2460 	    eager->tcp_eager_last_q == NULL);
2461 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2462 	    eager->tcp_eager_prev_q0 == NULL);
2463 	mutex_exit(&listener->tcp_eager_lock);
2464 	eager->tcp_rq = acceptor->tcp_rq;
2465 	eager->tcp_wq = acceptor->tcp_wq;
2466 
2467 	econnp = eager->tcp_connp;
2468 	aconnp = acceptor->tcp_connp;
2469 
2470 	eager->tcp_rq->q_ptr = econnp;
2471 	eager->tcp_wq->q_ptr = econnp;
2472 
2473 	/*
2474 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2475 	 * which might be a different squeue from our peer TCP instance.
2476 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2477 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2478 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2479 	 * above reach global visibility prior to the clearing of tcp_detached.
2480 	 */
2481 	membar_producer();
2482 	eager->tcp_detached = B_FALSE;
2483 
2484 	ASSERT(eager->tcp_ack_tid == 0);
2485 
2486 	econnp->conn_dev = aconnp->conn_dev;
2487 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2488 	ASSERT(econnp->conn_minor_arena != NULL);
2489 	if (eager->tcp_cred != NULL)
2490 		crfree(eager->tcp_cred);
2491 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2492 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2493 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2494 
2495 	aconnp->conn_cred = NULL;
2496 
2497 	econnp->conn_zoneid = aconnp->conn_zoneid;
2498 	econnp->conn_allzones = aconnp->conn_allzones;
2499 
2500 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2501 	aconnp->conn_mac_exempt = B_FALSE;
2502 
2503 	ASSERT(aconnp->conn_peercred == NULL);
2504 
2505 	/* Do the IPC initialization */
2506 	CONN_INC_REF(econnp);
2507 
2508 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2509 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2510 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2511 
2512 	/* Done with old IPC. Drop its ref on its connp */
2513 	CONN_DEC_REF(aconnp);
2514 }
2515 
2516 
2517 /*
2518  * Adapt to the information, such as rtt and rtt_sd, provided from the
2519  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2520  *
2521  * Checks for multicast and broadcast destination address.
2522  * Returns zero on failure; non-zero if ok.
2523  *
2524  * Note that the MSS calculation here is based on the info given in
2525  * the IRE.  We do not do any calculation based on TCP options.  They
2526  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2527  * knows which options to use.
2528  *
2529  * Note on how TCP gets its parameters for a connection.
2530  *
2531  * When a tcp_t structure is allocated, it gets all the default parameters.
2532  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2533  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2534  * default.
2535  *
2536  * An incoming SYN with a multicast or broadcast destination address, is dropped
2537  * in 1 of 2 places.
2538  *
2539  * 1. If the packet was received over the wire it is dropped in
2540  * ip_rput_process_broadcast()
2541  *
2542  * 2. If the packet was received through internal IP loopback, i.e. the packet
2543  * was generated and received on the same machine, it is dropped in
2544  * ip_wput_local()
2545  *
2546  * An incoming SYN with a multicast or broadcast source address is always
2547  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2548  * reject an attempt to connect to a broadcast or multicast (destination)
2549  * address.
2550  */
2551 static int
2552 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2553 {
2554 	tcp_hsp_t	*hsp;
2555 	ire_t		*ire;
2556 	ire_t		*sire = NULL;
2557 	iulp_t		*ire_uinfo = NULL;
2558 	uint32_t	mss_max;
2559 	uint32_t	mss;
2560 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2561 	conn_t		*connp = tcp->tcp_connp;
2562 	boolean_t	ire_cacheable = B_FALSE;
2563 	zoneid_t	zoneid = connp->conn_zoneid;
2564 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2565 	    MATCH_IRE_SECATTR;
2566 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2567 	ill_t		*ill = NULL;
2568 	boolean_t	incoming = (ire_mp == NULL);
2569 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2570 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2571 
2572 	ASSERT(connp->conn_ire_cache == NULL);
2573 
2574 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2575 
2576 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2577 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2578 			return (0);
2579 		}
2580 		/*
2581 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2582 		 * for the destination with the nexthop as gateway.
2583 		 * ire_ctable_lookup() is used because this particular
2584 		 * ire, if it exists, will be marked private.
2585 		 * If that is not available, use the interface ire
2586 		 * for the nexthop.
2587 		 *
2588 		 * TSol: tcp_update_label will detect label mismatches based
2589 		 * only on the destination's label, but that would not
2590 		 * detect label mismatches based on the security attributes
2591 		 * of routes or next hop gateway. Hence we need to pass the
2592 		 * label to ire_ftable_lookup below in order to locate the
2593 		 * right prefix (and/or) ire cache. Similarly we also need
2594 		 * pass the label to the ire_cache_lookup below to locate
2595 		 * the right ire that also matches on the label.
2596 		 */
2597 		if (tcp->tcp_connp->conn_nexthop_set) {
2598 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2599 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2600 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2601 			    ipst);
2602 			if (ire == NULL) {
2603 				ire = ire_ftable_lookup(
2604 				    tcp->tcp_connp->conn_nexthop_v4,
2605 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2606 				    tsl, match_flags, ipst);
2607 				if (ire == NULL)
2608 					return (0);
2609 			} else {
2610 				ire_uinfo = &ire->ire_uinfo;
2611 			}
2612 		} else {
2613 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2614 			    zoneid, tsl, ipst);
2615 			if (ire != NULL) {
2616 				ire_cacheable = B_TRUE;
2617 				ire_uinfo = (ire_mp != NULL) ?
2618 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2619 				    &ire->ire_uinfo;
2620 
2621 			} else {
2622 				if (ire_mp == NULL) {
2623 					ire = ire_ftable_lookup(
2624 					    tcp->tcp_connp->conn_rem,
2625 					    0, 0, 0, NULL, &sire, zoneid, 0,
2626 					    tsl, (MATCH_IRE_RECURSIVE |
2627 					    MATCH_IRE_DEFAULT), ipst);
2628 					if (ire == NULL)
2629 						return (0);
2630 					ire_uinfo = (sire != NULL) ?
2631 					    &sire->ire_uinfo :
2632 					    &ire->ire_uinfo;
2633 				} else {
2634 					ire = (ire_t *)ire_mp->b_rptr;
2635 					ire_uinfo =
2636 					    &((ire_t *)
2637 					    ire_mp->b_rptr)->ire_uinfo;
2638 				}
2639 			}
2640 		}
2641 		ASSERT(ire != NULL);
2642 
2643 		if ((ire->ire_src_addr == INADDR_ANY) ||
2644 		    (ire->ire_type & IRE_BROADCAST)) {
2645 			/*
2646 			 * ire->ire_mp is non null when ire_mp passed in is used
2647 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2648 			 */
2649 			if (ire->ire_mp == NULL)
2650 				ire_refrele(ire);
2651 			if (sire != NULL)
2652 				ire_refrele(sire);
2653 			return (0);
2654 		}
2655 
2656 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2657 			ipaddr_t src_addr;
2658 
2659 			/*
2660 			 * ip_bind_connected() has stored the correct source
2661 			 * address in conn_src.
2662 			 */
2663 			src_addr = tcp->tcp_connp->conn_src;
2664 			tcp->tcp_ipha->ipha_src = src_addr;
2665 			/*
2666 			 * Copy of the src addr. in tcp_t is needed
2667 			 * for the lookup funcs.
2668 			 */
2669 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2670 		}
2671 		/*
2672 		 * Set the fragment bit so that IP will tell us if the MTU
2673 		 * should change. IP tells us the latest setting of
2674 		 * ip_path_mtu_discovery through ire_frag_flag.
2675 		 */
2676 		if (ipst->ips_ip_path_mtu_discovery) {
2677 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2678 			    htons(IPH_DF);
2679 		}
2680 		/*
2681 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2682 		 * for IP_NEXTHOP. No cache ire has been found for the
2683 		 * destination and we are working with the nexthop's
2684 		 * interface ire. Since we need to forward all packets
2685 		 * to the nexthop first, we "blindly" set tcp_localnet
2686 		 * to false, eventhough the destination may also be
2687 		 * onlink.
2688 		 */
2689 		if (ire_uinfo == NULL)
2690 			tcp->tcp_localnet = 0;
2691 		else
2692 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2693 	} else {
2694 		/*
2695 		 * For incoming connection ire_mp = NULL
2696 		 * For outgoing connection ire_mp != NULL
2697 		 * Technically we should check conn_incoming_ill
2698 		 * when ire_mp is NULL and conn_outgoing_ill when
2699 		 * ire_mp is non-NULL. But this is performance
2700 		 * critical path and for IPV*_BOUND_IF, outgoing
2701 		 * and incoming ill are always set to the same value.
2702 		 */
2703 		ill_t	*dst_ill = NULL;
2704 		ipif_t  *dst_ipif = NULL;
2705 
2706 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2707 
2708 		if (connp->conn_outgoing_ill != NULL) {
2709 			/* Outgoing or incoming path */
2710 			int   err;
2711 
2712 			dst_ill = conn_get_held_ill(connp,
2713 			    &connp->conn_outgoing_ill, &err);
2714 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2715 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2716 				return (0);
2717 			}
2718 			match_flags |= MATCH_IRE_ILL;
2719 			dst_ipif = dst_ill->ill_ipif;
2720 		}
2721 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2722 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2723 
2724 		if (ire != NULL) {
2725 			ire_cacheable = B_TRUE;
2726 			ire_uinfo = (ire_mp != NULL) ?
2727 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2728 			    &ire->ire_uinfo;
2729 		} else {
2730 			if (ire_mp == NULL) {
2731 				ire = ire_ftable_lookup_v6(
2732 				    &tcp->tcp_connp->conn_remv6,
2733 				    0, 0, 0, dst_ipif, &sire, zoneid,
2734 				    0, tsl, match_flags, ipst);
2735 				if (ire == NULL) {
2736 					if (dst_ill != NULL)
2737 						ill_refrele(dst_ill);
2738 					return (0);
2739 				}
2740 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2741 				    &ire->ire_uinfo;
2742 			} else {
2743 				ire = (ire_t *)ire_mp->b_rptr;
2744 				ire_uinfo =
2745 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2746 			}
2747 		}
2748 		if (dst_ill != NULL)
2749 			ill_refrele(dst_ill);
2750 
2751 		ASSERT(ire != NULL);
2752 		ASSERT(ire_uinfo != NULL);
2753 
2754 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2755 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2756 			/*
2757 			 * ire->ire_mp is non null when ire_mp passed in is used
2758 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2759 			 */
2760 			if (ire->ire_mp == NULL)
2761 				ire_refrele(ire);
2762 			if (sire != NULL)
2763 				ire_refrele(sire);
2764 			return (0);
2765 		}
2766 
2767 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2768 			in6_addr_t	src_addr;
2769 
2770 			/*
2771 			 * ip_bind_connected_v6() has stored the correct source
2772 			 * address per IPv6 addr. selection policy in
2773 			 * conn_src_v6.
2774 			 */
2775 			src_addr = tcp->tcp_connp->conn_srcv6;
2776 
2777 			tcp->tcp_ip6h->ip6_src = src_addr;
2778 			/*
2779 			 * Copy of the src addr. in tcp_t is needed
2780 			 * for the lookup funcs.
2781 			 */
2782 			tcp->tcp_ip_src_v6 = src_addr;
2783 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2784 			    &connp->conn_srcv6));
2785 		}
2786 		tcp->tcp_localnet =
2787 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2788 	}
2789 
2790 	/*
2791 	 * This allows applications to fail quickly when connections are made
2792 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2793 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2794 	 */
2795 	if ((ire->ire_flags & RTF_REJECT) &&
2796 	    (ire->ire_flags & RTF_PRIVATE))
2797 		goto error;
2798 
2799 	/*
2800 	 * Make use of the cached rtt and rtt_sd values to calculate the
2801 	 * initial RTO.  Note that they are already initialized in
2802 	 * tcp_init_values().
2803 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2804 	 * IP_NEXTHOP, but instead are using the interface ire for the
2805 	 * nexthop, then we do not use the ire_uinfo from that ire to
2806 	 * do any initializations.
2807 	 */
2808 	if (ire_uinfo != NULL) {
2809 		if (ire_uinfo->iulp_rtt != 0) {
2810 			clock_t	rto;
2811 
2812 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2813 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2814 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2815 			    tcps->tcps_rexmit_interval_extra +
2816 			    (tcp->tcp_rtt_sa >> 5);
2817 
2818 			if (rto > tcps->tcps_rexmit_interval_max) {
2819 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2820 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2821 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2822 			} else {
2823 				tcp->tcp_rto = rto;
2824 			}
2825 		}
2826 		if (ire_uinfo->iulp_ssthresh != 0)
2827 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2828 		else
2829 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2830 		if (ire_uinfo->iulp_spipe > 0) {
2831 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2832 			    tcps->tcps_max_buf);
2833 			if (tcps->tcps_snd_lowat_fraction != 0)
2834 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2835 				    tcps->tcps_snd_lowat_fraction;
2836 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2837 		}
2838 		/*
2839 		 * Note that up till now, acceptor always inherits receive
2840 		 * window from the listener.  But if there is a metrics
2841 		 * associated with a host, we should use that instead of
2842 		 * inheriting it from listener. Thus we need to pass this
2843 		 * info back to the caller.
2844 		 */
2845 		if (ire_uinfo->iulp_rpipe > 0) {
2846 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2847 			    tcps->tcps_max_buf);
2848 		}
2849 
2850 		if (ire_uinfo->iulp_rtomax > 0) {
2851 			tcp->tcp_second_timer_threshold =
2852 			    ire_uinfo->iulp_rtomax;
2853 		}
2854 
2855 		/*
2856 		 * Use the metric option settings, iulp_tstamp_ok and
2857 		 * iulp_wscale_ok, only for active open. What this means
2858 		 * is that if the other side uses timestamp or window
2859 		 * scale option, TCP will also use those options. That
2860 		 * is for passive open.  If the application sets a
2861 		 * large window, window scale is enabled regardless of
2862 		 * the value in iulp_wscale_ok.  This is the behavior
2863 		 * since 2.6.  So we keep it.
2864 		 * The only case left in passive open processing is the
2865 		 * check for SACK.
2866 		 * For ECN, it should probably be like SACK.  But the
2867 		 * current value is binary, so we treat it like the other
2868 		 * cases.  The metric only controls active open.For passive
2869 		 * open, the ndd param, tcp_ecn_permitted, controls the
2870 		 * behavior.
2871 		 */
2872 		if (!tcp_detached) {
2873 			/*
2874 			 * The if check means that the following can only
2875 			 * be turned on by the metrics only IRE, but not off.
2876 			 */
2877 			if (ire_uinfo->iulp_tstamp_ok)
2878 				tcp->tcp_snd_ts_ok = B_TRUE;
2879 			if (ire_uinfo->iulp_wscale_ok)
2880 				tcp->tcp_snd_ws_ok = B_TRUE;
2881 			if (ire_uinfo->iulp_sack == 2)
2882 				tcp->tcp_snd_sack_ok = B_TRUE;
2883 			if (ire_uinfo->iulp_ecn_ok)
2884 				tcp->tcp_ecn_ok = B_TRUE;
2885 		} else {
2886 			/*
2887 			 * Passive open.
2888 			 *
2889 			 * As above, the if check means that SACK can only be
2890 			 * turned on by the metric only IRE.
2891 			 */
2892 			if (ire_uinfo->iulp_sack > 0) {
2893 				tcp->tcp_snd_sack_ok = B_TRUE;
2894 			}
2895 		}
2896 	}
2897 
2898 
2899 	/*
2900 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2901 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2902 	 * length of all those options exceeds 28 bytes.  But because
2903 	 * of the tcp_mss_min check below, we may not have a problem if
2904 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2905 	 * the negative problem still exists.  And the check defeats PMTUd.
2906 	 * In fact, if PMTUd finds that the MSS should be smaller than
2907 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2908 	 * value.
2909 	 *
2910 	 * We do not deal with that now.  All those problems related to
2911 	 * PMTUd will be fixed later.
2912 	 */
2913 	ASSERT(ire->ire_max_frag != 0);
2914 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2915 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2916 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2917 			mss = MIN(mss, IPV6_MIN_MTU);
2918 		}
2919 	}
2920 
2921 	/* Sanity check for MSS value. */
2922 	if (tcp->tcp_ipversion == IPV4_VERSION)
2923 		mss_max = tcps->tcps_mss_max_ipv4;
2924 	else
2925 		mss_max = tcps->tcps_mss_max_ipv6;
2926 
2927 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2928 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2929 		/*
2930 		 * After receiving an ICMPv6 "packet too big" message with a
2931 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2932 		 * will insert a 8-byte fragment header in every packet; we
2933 		 * reduce the MSS by that amount here.
2934 		 */
2935 		mss -= sizeof (ip6_frag_t);
2936 	}
2937 
2938 	if (tcp->tcp_ipsec_overhead == 0)
2939 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2940 
2941 	mss -= tcp->tcp_ipsec_overhead;
2942 
2943 	if (mss < tcps->tcps_mss_min)
2944 		mss = tcps->tcps_mss_min;
2945 	if (mss > mss_max)
2946 		mss = mss_max;
2947 
2948 	/* Note that this is the maximum MSS, excluding all options. */
2949 	tcp->tcp_mss = mss;
2950 
2951 	/*
2952 	 * Initialize the ISS here now that we have the full connection ID.
2953 	 * The RFC 1948 method of initial sequence number generation requires
2954 	 * knowledge of the full connection ID before setting the ISS.
2955 	 */
2956 
2957 	tcp_iss_init(tcp);
2958 
2959 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2960 		tcp->tcp_loopback = B_TRUE;
2961 
2962 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2963 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2964 	} else {
2965 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2966 	}
2967 
2968 	if (hsp != NULL) {
2969 		/* Only modify if we're going to make them bigger */
2970 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2971 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2972 			if (tcps->tcps_snd_lowat_fraction != 0)
2973 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2974 				    tcps->tcps_snd_lowat_fraction;
2975 		}
2976 
2977 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2978 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2979 		}
2980 
2981 		/* Copy timestamp flag only for active open */
2982 		if (!tcp_detached)
2983 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2984 	}
2985 
2986 	if (sire != NULL)
2987 		IRE_REFRELE(sire);
2988 
2989 	/*
2990 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2991 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2992 	 */
2993 	if (tcp->tcp_loopback ||
2994 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2995 		/*
2996 		 * For incoming, see if this tcp may be MDT-capable.  For
2997 		 * outgoing, this process has been taken care of through
2998 		 * tcp_rput_other.
2999 		 */
3000 		tcp_ire_ill_check(tcp, ire, ill, incoming);
3001 		tcp->tcp_ire_ill_check_done = B_TRUE;
3002 	}
3003 
3004 	mutex_enter(&connp->conn_lock);
3005 	/*
3006 	 * Make sure that conn is not marked incipient
3007 	 * for incoming connections. A blind
3008 	 * removal of incipient flag is cheaper than
3009 	 * check and removal.
3010 	 */
3011 	connp->conn_state_flags &= ~CONN_INCIPIENT;
3012 
3013 	/*
3014 	 * Must not cache forwarding table routes
3015 	 * or recache an IRE after the conn_t has
3016 	 * had conn_ire_cache cleared and is flagged
3017 	 * unusable, (see the CONN_CACHE_IRE() macro).
3018 	 */
3019 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
3020 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
3021 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3022 			connp->conn_ire_cache = ire;
3023 			IRE_UNTRACE_REF(ire);
3024 			rw_exit(&ire->ire_bucket->irb_lock);
3025 			mutex_exit(&connp->conn_lock);
3026 			return (1);
3027 		}
3028 		rw_exit(&ire->ire_bucket->irb_lock);
3029 	}
3030 	mutex_exit(&connp->conn_lock);
3031 
3032 	if (ire->ire_mp == NULL)
3033 		ire_refrele(ire);
3034 	return (1);
3035 
3036 error:
3037 	if (ire->ire_mp == NULL)
3038 		ire_refrele(ire);
3039 	if (sire != NULL)
3040 		ire_refrele(sire);
3041 	return (0);
3042 }
3043 
3044 static void
3045 tcp_tpi_bind(tcp_t *tcp, mblk_t *mp)
3046 {
3047 	int	error;
3048 	conn_t	*connp = tcp->tcp_connp;
3049 	struct sockaddr	*sa;
3050 	mblk_t  *mp1;
3051 	struct T_bind_req *tbr;
3052 	int	backlog;
3053 	socklen_t	len;
3054 	sin_t	*sin;
3055 	sin6_t	*sin6;
3056 	cred_t		*cr;
3057 
3058 	/*
3059 	 * All Solaris components should pass a db_credp
3060 	 * for this TPI message, hence we ASSERT.
3061 	 * But in case there is some other M_PROTO that looks
3062 	 * like a TPI message sent by some other kernel
3063 	 * component, we check and return an error.
3064 	 */
3065 	cr = msg_getcred(mp, NULL);
3066 	ASSERT(cr != NULL);
3067 	if (cr == NULL) {
3068 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3069 		return;
3070 	}
3071 
3072 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3073 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3074 		if (tcp->tcp_debug) {
3075 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3076 			    "tcp_tpi_bind: bad req, len %u",
3077 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3078 		}
3079 		tcp_err_ack(tcp, mp, TPROTO, 0);
3080 		return;
3081 	}
3082 	/* Make sure the largest address fits */
3083 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3084 	if (mp1 == NULL) {
3085 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3086 		return;
3087 	}
3088 	mp = mp1;
3089 	tbr = (struct T_bind_req *)mp->b_rptr;
3090 
3091 	backlog = tbr->CONIND_number;
3092 	len = tbr->ADDR_length;
3093 
3094 	switch (len) {
3095 	case 0:		/* request for a generic port */
3096 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3097 		if (tcp->tcp_family == AF_INET) {
3098 			tbr->ADDR_length = sizeof (sin_t);
3099 			sin = (sin_t *)&tbr[1];
3100 			*sin = sin_null;
3101 			sin->sin_family = AF_INET;
3102 			sa = (struct sockaddr *)sin;
3103 			len = sizeof (sin_t);
3104 			mp->b_wptr = (uchar_t *)&sin[1];
3105 		} else {
3106 			ASSERT(tcp->tcp_family == AF_INET6);
3107 			tbr->ADDR_length = sizeof (sin6_t);
3108 			sin6 = (sin6_t *)&tbr[1];
3109 			*sin6 = sin6_null;
3110 			sin6->sin6_family = AF_INET6;
3111 			sa = (struct sockaddr *)sin6;
3112 			len = sizeof (sin6_t);
3113 			mp->b_wptr = (uchar_t *)&sin6[1];
3114 		}
3115 		break;
3116 
3117 	case sizeof (sin_t):    /* Complete IPv4 address */
3118 		sa = (struct sockaddr *)mi_offset_param(mp, tbr->ADDR_offset,
3119 		    sizeof (sin_t));
3120 		break;
3121 
3122 	case sizeof (sin6_t): /* Complete IPv6 address */
3123 		sa = (struct sockaddr *)mi_offset_param(mp,
3124 		    tbr->ADDR_offset, sizeof (sin6_t));
3125 		break;
3126 
3127 	default:
3128 		if (tcp->tcp_debug) {
3129 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3130 			    "tcp_tpi_bind: bad address length, %d",
3131 			    tbr->ADDR_length);
3132 		}
3133 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3134 		return;
3135 	}
3136 
3137 	error = tcp_bind_check(connp, sa, len, cr,
3138 	    tbr->PRIM_type != O_T_BIND_REQ);
3139 	if (error == 0) {
3140 		if (tcp->tcp_family == AF_INET) {
3141 			sin = (sin_t *)sa;
3142 			sin->sin_port = tcp->tcp_lport;
3143 		} else {
3144 			sin6 = (sin6_t *)sa;
3145 			sin6->sin6_port = tcp->tcp_lport;
3146 		}
3147 
3148 		if (backlog > 0) {
3149 			error = tcp_do_listen(connp, backlog, cr);
3150 		}
3151 	}
3152 done:
3153 	if (error > 0) {
3154 		tcp_err_ack(tcp, mp, TSYSERR, error);
3155 	} else if (error < 0) {
3156 		tcp_err_ack(tcp, mp, -error, 0);
3157 	} else {
3158 		mp->b_datap->db_type = M_PCPROTO;
3159 		tbr->PRIM_type = T_BIND_ACK;
3160 		putnext(tcp->tcp_rq, mp);
3161 	}
3162 }
3163 
3164 /*
3165  * If the "bind_to_req_port_only" parameter is set, if the requested port
3166  * number is available, return it, If not return 0
3167  *
3168  * If "bind_to_req_port_only" parameter is not set and
3169  * If the requested port number is available, return it.  If not, return
3170  * the first anonymous port we happen across.  If no anonymous ports are
3171  * available, return 0. addr is the requested local address, if any.
3172  *
3173  * In either case, when succeeding update the tcp_t to record the port number
3174  * and insert it in the bind hash table.
3175  *
3176  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3177  * without setting SO_REUSEADDR. This is needed so that they
3178  * can be viewed as two independent transport protocols.
3179  */
3180 static in_port_t
3181 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3182     int reuseaddr, boolean_t quick_connect,
3183     boolean_t bind_to_req_port_only, boolean_t user_specified)
3184 {
3185 	/* number of times we have run around the loop */
3186 	int count = 0;
3187 	/* maximum number of times to run around the loop */
3188 	int loopmax;
3189 	conn_t *connp = tcp->tcp_connp;
3190 	zoneid_t zoneid = connp->conn_zoneid;
3191 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3192 
3193 	/*
3194 	 * Lookup for free addresses is done in a loop and "loopmax"
3195 	 * influences how long we spin in the loop
3196 	 */
3197 	if (bind_to_req_port_only) {
3198 		/*
3199 		 * If the requested port is busy, don't bother to look
3200 		 * for a new one. Setting loop maximum count to 1 has
3201 		 * that effect.
3202 		 */
3203 		loopmax = 1;
3204 	} else {
3205 		/*
3206 		 * If the requested port is busy, look for a free one
3207 		 * in the anonymous port range.
3208 		 * Set loopmax appropriately so that one does not look
3209 		 * forever in the case all of the anonymous ports are in use.
3210 		 */
3211 		if (tcp->tcp_anon_priv_bind) {
3212 			/*
3213 			 * loopmax =
3214 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3215 			 */
3216 			loopmax = IPPORT_RESERVED -
3217 			    tcps->tcps_min_anonpriv_port;
3218 		} else {
3219 			loopmax = (tcps->tcps_largest_anon_port -
3220 			    tcps->tcps_smallest_anon_port + 1);
3221 		}
3222 	}
3223 	do {
3224 		uint16_t	lport;
3225 		tf_t		*tbf;
3226 		tcp_t		*ltcp;
3227 		conn_t		*lconnp;
3228 
3229 		lport = htons(port);
3230 
3231 		/*
3232 		 * Ensure that the tcp_t is not currently in the bind hash.
3233 		 * Hold the lock on the hash bucket to ensure that
3234 		 * the duplicate check plus the insertion is an atomic
3235 		 * operation.
3236 		 *
3237 		 * This function does an inline lookup on the bind hash list
3238 		 * Make sure that we access only members of tcp_t
3239 		 * and that we don't look at tcp_tcp, since we are not
3240 		 * doing a CONN_INC_REF.
3241 		 */
3242 		tcp_bind_hash_remove(tcp);
3243 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3244 		mutex_enter(&tbf->tf_lock);
3245 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3246 		    ltcp = ltcp->tcp_bind_hash) {
3247 			if (lport == ltcp->tcp_lport)
3248 				break;
3249 		}
3250 
3251 		for (; ltcp != NULL; ltcp = ltcp->tcp_bind_hash_port) {
3252 			boolean_t not_socket;
3253 			boolean_t exclbind;
3254 
3255 			lconnp = ltcp->tcp_connp;
3256 
3257 			/*
3258 			 * On a labeled system, we must treat bindings to ports
3259 			 * on shared IP addresses by sockets with MAC exemption
3260 			 * privilege as being in all zones, as there's
3261 			 * otherwise no way to identify the right receiver.
3262 			 */
3263 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3264 			    IPCL_ZONE_MATCH(connp,
3265 			    ltcp->tcp_connp->conn_zoneid)) &&
3266 			    !lconnp->conn_mac_exempt &&
3267 			    !connp->conn_mac_exempt)
3268 				continue;
3269 
3270 			/*
3271 			 * If TCP_EXCLBIND is set for either the bound or
3272 			 * binding endpoint, the semantics of bind
3273 			 * is changed according to the following.
3274 			 *
3275 			 * spec = specified address (v4 or v6)
3276 			 * unspec = unspecified address (v4 or v6)
3277 			 * A = specified addresses are different for endpoints
3278 			 *
3279 			 * bound	bind to		allowed
3280 			 * -------------------------------------
3281 			 * unspec	unspec		no
3282 			 * unspec	spec		no
3283 			 * spec		unspec		no
3284 			 * spec		spec		yes if A
3285 			 *
3286 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3287 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3288 			 *
3289 			 * Note:
3290 			 *
3291 			 * 1. Because of TLI semantics, an endpoint can go
3292 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3293 			 * TCPS_BOUND, depending on whether it is originally
3294 			 * a listener or not.  That is why we need to check
3295 			 * for states greater than or equal to TCPS_BOUND
3296 			 * here.
3297 			 *
3298 			 * 2. Ideally, we should only check for state equals
3299 			 * to TCPS_LISTEN. And the following check should be
3300 			 * added.
3301 			 *
3302 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3303 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3304 			 *		...
3305 			 * }
3306 			 *
3307 			 * The semantics will be changed to this.  If the
3308 			 * endpoint on the list is in state not equal to
3309 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3310 			 * set, let the bind succeed.
3311 			 *
3312 			 * Because of (1), we cannot do that for TLI
3313 			 * endpoints.  But we can do that for socket endpoints.
3314 			 * If in future, we can change this going back
3315 			 * semantics, we can use the above check for TLI also.
3316 			 */
3317 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3318 			    TCP_IS_SOCKET(tcp));
3319 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3320 
3321 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3322 			    (exclbind && (not_socket ||
3323 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3324 				if (V6_OR_V4_INADDR_ANY(
3325 				    ltcp->tcp_bound_source_v6) ||
3326 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3327 				    IN6_ARE_ADDR_EQUAL(laddr,
3328 				    &ltcp->tcp_bound_source_v6)) {
3329 					break;
3330 				}
3331 				continue;
3332 			}
3333 
3334 			/*
3335 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3336 			 * have disjoint port number spaces, if *_EXCLBIND
3337 			 * is not set and only if the application binds to a
3338 			 * specific port. We use the same autoassigned port
3339 			 * number space for IPv4 and IPv6 sockets.
3340 			 */
3341 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3342 			    bind_to_req_port_only)
3343 				continue;
3344 
3345 			/*
3346 			 * Ideally, we should make sure that the source
3347 			 * address, remote address, and remote port in the
3348 			 * four tuple for this tcp-connection is unique.
3349 			 * However, trying to find out the local source
3350 			 * address would require too much code duplication
3351 			 * with IP, since IP needs needs to have that code
3352 			 * to support userland TCP implementations.
3353 			 */
3354 			if (quick_connect &&
3355 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3356 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3357 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3358 			    &ltcp->tcp_remote_v6)))
3359 				continue;
3360 
3361 			if (!reuseaddr) {
3362 				/*
3363 				 * No socket option SO_REUSEADDR.
3364 				 * If existing port is bound to
3365 				 * a non-wildcard IP address
3366 				 * and the requesting stream is
3367 				 * bound to a distinct
3368 				 * different IP addresses
3369 				 * (non-wildcard, also), keep
3370 				 * going.
3371 				 */
3372 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3373 				    !V6_OR_V4_INADDR_ANY(
3374 				    ltcp->tcp_bound_source_v6) &&
3375 				    !IN6_ARE_ADDR_EQUAL(laddr,
3376 				    &ltcp->tcp_bound_source_v6))
3377 					continue;
3378 				if (ltcp->tcp_state >= TCPS_BOUND) {
3379 					/*
3380 					 * This port is being used and
3381 					 * its state is >= TCPS_BOUND,
3382 					 * so we can't bind to it.
3383 					 */
3384 					break;
3385 				}
3386 			} else {
3387 				/*
3388 				 * socket option SO_REUSEADDR is set on the
3389 				 * binding tcp_t.
3390 				 *
3391 				 * If two streams are bound to
3392 				 * same IP address or both addr
3393 				 * and bound source are wildcards
3394 				 * (INADDR_ANY), we want to stop
3395 				 * searching.
3396 				 * We have found a match of IP source
3397 				 * address and source port, which is
3398 				 * refused regardless of the
3399 				 * SO_REUSEADDR setting, so we break.
3400 				 */
3401 				if (IN6_ARE_ADDR_EQUAL(laddr,
3402 				    &ltcp->tcp_bound_source_v6) &&
3403 				    (ltcp->tcp_state == TCPS_LISTEN ||
3404 				    ltcp->tcp_state == TCPS_BOUND))
3405 					break;
3406 			}
3407 		}
3408 		if (ltcp != NULL) {
3409 			/* The port number is busy */
3410 			mutex_exit(&tbf->tf_lock);
3411 		} else {
3412 			/*
3413 			 * This port is ours. Insert in fanout and mark as
3414 			 * bound to prevent others from getting the port
3415 			 * number.
3416 			 */
3417 			tcp->tcp_state = TCPS_BOUND;
3418 			tcp->tcp_lport = htons(port);
3419 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3420 
3421 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3422 			    tcp->tcp_lport)] == tbf);
3423 			tcp_bind_hash_insert(tbf, tcp, 1);
3424 
3425 			mutex_exit(&tbf->tf_lock);
3426 
3427 			/*
3428 			 * We don't want tcp_next_port_to_try to "inherit"
3429 			 * a port number supplied by the user in a bind.
3430 			 */
3431 			if (user_specified)
3432 				return (port);
3433 
3434 			/*
3435 			 * This is the only place where tcp_next_port_to_try
3436 			 * is updated. After the update, it may or may not
3437 			 * be in the valid range.
3438 			 */
3439 			if (!tcp->tcp_anon_priv_bind)
3440 				tcps->tcps_next_port_to_try = port + 1;
3441 			return (port);
3442 		}
3443 
3444 		if (tcp->tcp_anon_priv_bind) {
3445 			port = tcp_get_next_priv_port(tcp);
3446 		} else {
3447 			if (count == 0 && user_specified) {
3448 				/*
3449 				 * We may have to return an anonymous port. So
3450 				 * get one to start with.
3451 				 */
3452 				port =
3453 				    tcp_update_next_port(
3454 				    tcps->tcps_next_port_to_try,
3455 				    tcp, B_TRUE);
3456 				user_specified = B_FALSE;
3457 			} else {
3458 				port = tcp_update_next_port(port + 1, tcp,
3459 				    B_FALSE);
3460 			}
3461 		}
3462 		if (port == 0)
3463 			break;
3464 
3465 		/*
3466 		 * Don't let this loop run forever in the case where
3467 		 * all of the anonymous ports are in use.
3468 		 */
3469 	} while (++count < loopmax);
3470 	return (0);
3471 }
3472 
3473 /*
3474  * tcp_clean_death / tcp_close_detached must not be called more than once
3475  * on a tcp. Thus every function that potentially calls tcp_clean_death
3476  * must check for the tcp state before calling tcp_clean_death.
3477  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3478  * tcp_timer_handler, all check for the tcp state.
3479  */
3480 /* ARGSUSED */
3481 void
3482 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3483 {
3484 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3485 
3486 	freemsg(mp);
3487 	if (tcp->tcp_state > TCPS_BOUND)
3488 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3489 		    ETIMEDOUT, 5);
3490 }
3491 
3492 /*
3493  * We are dying for some reason.  Try to do it gracefully.  (May be called
3494  * as writer.)
3495  *
3496  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3497  * done by a service procedure).
3498  * TBD - Should the return value distinguish between the tcp_t being
3499  * freed and it being reinitialized?
3500  */
3501 static int
3502 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3503 {
3504 	mblk_t	*mp;
3505 	queue_t	*q;
3506 	conn_t	*connp = tcp->tcp_connp;
3507 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3508 	sodirect_t	*sodp;
3509 
3510 	TCP_CLD_STAT(tag);
3511 
3512 #if TCP_TAG_CLEAN_DEATH
3513 	tcp->tcp_cleandeathtag = tag;
3514 #endif
3515 
3516 	if (tcp->tcp_fused)
3517 		tcp_unfuse(tcp);
3518 
3519 	if (tcp->tcp_linger_tid != 0 &&
3520 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3521 		tcp_stop_lingering(tcp);
3522 	}
3523 
3524 	ASSERT(tcp != NULL);
3525 	ASSERT((tcp->tcp_family == AF_INET &&
3526 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3527 	    (tcp->tcp_family == AF_INET6 &&
3528 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3529 	    tcp->tcp_ipversion == IPV6_VERSION)));
3530 
3531 	if (TCP_IS_DETACHED(tcp)) {
3532 		if (tcp->tcp_hard_binding) {
3533 			/*
3534 			 * Its an eager that we are dealing with. We close the
3535 			 * eager but in case a conn_ind has already gone to the
3536 			 * listener, let tcp_accept_finish() send a discon_ind
3537 			 * to the listener and drop the last reference. If the
3538 			 * listener doesn't even know about the eager i.e. the
3539 			 * conn_ind hasn't gone up, blow away the eager and drop
3540 			 * the last reference as well. If the conn_ind has gone
3541 			 * up, state should be BOUND. tcp_accept_finish
3542 			 * will figure out that the connection has received a
3543 			 * RST and will send a DISCON_IND to the application.
3544 			 */
3545 			tcp_closei_local(tcp);
3546 			if (!tcp->tcp_tconnind_started) {
3547 				CONN_DEC_REF(connp);
3548 			} else {
3549 				tcp->tcp_state = TCPS_BOUND;
3550 			}
3551 		} else {
3552 			tcp_close_detached(tcp);
3553 		}
3554 		return (0);
3555 	}
3556 
3557 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3558 
3559 	/* If sodirect, not anymore */
3560 	SOD_PTR_ENTER(tcp, sodp);
3561 	if (sodp != NULL) {
3562 		tcp->tcp_sodirect = NULL;
3563 		mutex_exit(sodp->sod_lockp);
3564 	}
3565 
3566 	q = tcp->tcp_rq;
3567 
3568 	/* Trash all inbound data */
3569 	if (!IPCL_IS_NONSTR(connp)) {
3570 		ASSERT(q != NULL);
3571 		flushq(q, FLUSHALL);
3572 	}
3573 
3574 	/*
3575 	 * If we are at least part way open and there is error
3576 	 * (err==0 implies no error)
3577 	 * notify our client by a T_DISCON_IND.
3578 	 */
3579 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3580 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3581 		    !TCP_IS_SOCKET(tcp)) {
3582 			/*
3583 			 * Send M_FLUSH according to TPI. Because sockets will
3584 			 * (and must) ignore FLUSHR we do that only for TPI
3585 			 * endpoints and sockets in STREAMS mode.
3586 			 */
3587 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3588 		}
3589 		if (tcp->tcp_debug) {
3590 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3591 			    "tcp_clean_death: discon err %d", err);
3592 		}
3593 		if (IPCL_IS_NONSTR(connp)) {
3594 			/* Direct socket, use upcall */
3595 			(*connp->conn_upcalls->su_disconnected)(
3596 			    connp->conn_upper_handle, tcp->tcp_connid, err);
3597 		} else {
3598 			mp = mi_tpi_discon_ind(NULL, err, 0);
3599 			if (mp != NULL) {
3600 				putnext(q, mp);
3601 			} else {
3602 				if (tcp->tcp_debug) {
3603 					(void) strlog(TCP_MOD_ID, 0, 1,
3604 					    SL_ERROR|SL_TRACE,
3605 					    "tcp_clean_death, sending M_ERROR");
3606 				}
3607 				(void) putnextctl1(q, M_ERROR, EPROTO);
3608 			}
3609 		}
3610 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3611 			/* SYN_SENT or SYN_RCVD */
3612 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3613 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3614 			/* ESTABLISHED or CLOSE_WAIT */
3615 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3616 		}
3617 	}
3618 
3619 	tcp_reinit(tcp);
3620 	if (IPCL_IS_NONSTR(connp))
3621 		(void) tcp_do_unbind(connp);
3622 
3623 	return (-1);
3624 }
3625 
3626 /*
3627  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3628  * to expire, stop the wait and finish the close.
3629  */
3630 static void
3631 tcp_stop_lingering(tcp_t *tcp)
3632 {
3633 	clock_t	delta = 0;
3634 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3635 
3636 	tcp->tcp_linger_tid = 0;
3637 	if (tcp->tcp_state > TCPS_LISTEN) {
3638 		tcp_acceptor_hash_remove(tcp);
3639 		mutex_enter(&tcp->tcp_non_sq_lock);
3640 		if (tcp->tcp_flow_stopped) {
3641 			tcp_clrqfull(tcp);
3642 		}
3643 		mutex_exit(&tcp->tcp_non_sq_lock);
3644 
3645 		if (tcp->tcp_timer_tid != 0) {
3646 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3647 			tcp->tcp_timer_tid = 0;
3648 		}
3649 		/*
3650 		 * Need to cancel those timers which will not be used when
3651 		 * TCP is detached.  This has to be done before the tcp_wq
3652 		 * is set to the global queue.
3653 		 */
3654 		tcp_timers_stop(tcp);
3655 
3656 		tcp->tcp_detached = B_TRUE;
3657 		ASSERT(tcps->tcps_g_q != NULL);
3658 		tcp->tcp_rq = tcps->tcps_g_q;
3659 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3660 
3661 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3662 			tcp_time_wait_append(tcp);
3663 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3664 			goto finish;
3665 		}
3666 
3667 		/*
3668 		 * If delta is zero the timer event wasn't executed and was
3669 		 * successfully canceled. In this case we need to restart it
3670 		 * with the minimal delta possible.
3671 		 */
3672 		if (delta >= 0) {
3673 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3674 			    delta ? delta : 1);
3675 		}
3676 	} else {
3677 		tcp_closei_local(tcp);
3678 		CONN_DEC_REF(tcp->tcp_connp);
3679 	}
3680 finish:
3681 	/* Signal closing thread that it can complete close */
3682 	mutex_enter(&tcp->tcp_closelock);
3683 	tcp->tcp_detached = B_TRUE;
3684 	ASSERT(tcps->tcps_g_q != NULL);
3685 
3686 	tcp->tcp_rq = tcps->tcps_g_q;
3687 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3688 
3689 	tcp->tcp_closed = 1;
3690 	cv_signal(&tcp->tcp_closecv);
3691 	mutex_exit(&tcp->tcp_closelock);
3692 }
3693 
3694 /*
3695  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3696  * expires.
3697  */
3698 static void
3699 tcp_close_linger_timeout(void *arg)
3700 {
3701 	conn_t	*connp = (conn_t *)arg;
3702 	tcp_t 	*tcp = connp->conn_tcp;
3703 
3704 	tcp->tcp_client_errno = ETIMEDOUT;
3705 	tcp_stop_lingering(tcp);
3706 }
3707 
3708 static void
3709 tcp_close_common(conn_t *connp, int flags)
3710 {
3711 	tcp_t		*tcp = connp->conn_tcp;
3712 	mblk_t 		*mp = &tcp->tcp_closemp;
3713 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
3714 	mblk_t		*bp;
3715 
3716 	ASSERT(connp->conn_ref >= 2);
3717 
3718 	/*
3719 	 * Mark the conn as closing. ill_pending_mp_add will not
3720 	 * add any mp to the pending mp list, after this conn has
3721 	 * started closing. Same for sq_pending_mp_add
3722 	 */
3723 	mutex_enter(&connp->conn_lock);
3724 	connp->conn_state_flags |= CONN_CLOSING;
3725 	if (connp->conn_oper_pending_ill != NULL)
3726 		conn_ioctl_cleanup_reqd = B_TRUE;
3727 	CONN_INC_REF_LOCKED(connp);
3728 	mutex_exit(&connp->conn_lock);
3729 	tcp->tcp_closeflags = (uint8_t)flags;
3730 	ASSERT(connp->conn_ref >= 3);
3731 
3732 	/*
3733 	 * tcp_closemp_used is used below without any protection of a lock
3734 	 * as we don't expect any one else to use it concurrently at this
3735 	 * point otherwise it would be a major defect.
3736 	 */
3737 
3738 	if (mp->b_prev == NULL)
3739 		tcp->tcp_closemp_used = B_TRUE;
3740 	else
3741 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
3742 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
3743 
3744 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
3745 
3746 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_close_output, connp,
3747 	    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3748 
3749 	mutex_enter(&tcp->tcp_closelock);
3750 	while (!tcp->tcp_closed) {
3751 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
3752 			/*
3753 			 * The cv_wait_sig() was interrupted. We now do the
3754 			 * following:
3755 			 *
3756 			 * 1) If the endpoint was lingering, we allow this
3757 			 * to be interrupted by cancelling the linger timeout
3758 			 * and closing normally.
3759 			 *
3760 			 * 2) Revert to calling cv_wait()
3761 			 *
3762 			 * We revert to using cv_wait() to avoid an
3763 			 * infinite loop which can occur if the calling
3764 			 * thread is higher priority than the squeue worker
3765 			 * thread and is bound to the same cpu.
3766 			 */
3767 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
3768 				mutex_exit(&tcp->tcp_closelock);
3769 				/* Entering squeue, bump ref count. */
3770 				CONN_INC_REF(connp);
3771 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
3772 				SQUEUE_ENTER_ONE(connp->conn_sqp, bp,
3773 				    tcp_linger_interrupted, connp,
3774 				    tcp_squeue_flag, SQTAG_IP_TCP_CLOSE);
3775 				mutex_enter(&tcp->tcp_closelock);
3776 			}
3777 			break;
3778 		}
3779 	}
3780 	while (!tcp->tcp_closed)
3781 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
3782 	mutex_exit(&tcp->tcp_closelock);
3783 
3784 	/*
3785 	 * In the case of listener streams that have eagers in the q or q0
3786 	 * we wait for the eagers to drop their reference to us. tcp_rq and
3787 	 * tcp_wq of the eagers point to our queues. By waiting for the
3788 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
3789 	 * up their queue pointers and also dropped their references to us.
3790 	 */
3791 	if (tcp->tcp_wait_for_eagers) {
3792 		mutex_enter(&connp->conn_lock);
3793 		while (connp->conn_ref != 1) {
3794 			cv_wait(&connp->conn_cv, &connp->conn_lock);
3795 		}
3796 		mutex_exit(&connp->conn_lock);
3797 	}
3798 	/*
3799 	 * ioctl cleanup. The mp is queued in the
3800 	 * ill_pending_mp or in the sq_pending_mp.
3801 	 */
3802 	if (conn_ioctl_cleanup_reqd)
3803 		conn_ioctl_cleanup(connp);
3804 
3805 	tcp->tcp_cpid = -1;
3806 }
3807 
3808 static int
3809 tcp_tpi_close(queue_t *q, int flags)
3810 {
3811 	conn_t		*connp;
3812 
3813 	ASSERT(WR(q)->q_next == NULL);
3814 
3815 	if (flags & SO_FALLBACK) {
3816 		/*
3817 		 * stream is being closed while in fallback
3818 		 * simply free the resources that were allocated
3819 		 */
3820 		inet_minor_free(WR(q)->q_ptr, (dev_t)(RD(q)->q_ptr));
3821 		qprocsoff(q);
3822 		goto done;
3823 	}
3824 
3825 	connp = Q_TO_CONN(q);
3826 	/*
3827 	 * We are being closed as /dev/tcp or /dev/tcp6.
3828 	 */
3829 	tcp_close_common(connp, flags);
3830 
3831 	qprocsoff(q);
3832 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
3833 
3834 	/*
3835 	 * Drop IP's reference on the conn. This is the last reference
3836 	 * on the connp if the state was less than established. If the
3837 	 * connection has gone into timewait state, then we will have
3838 	 * one ref for the TCP and one more ref (total of two) for the
3839 	 * classifier connected hash list (a timewait connections stays
3840 	 * in connected hash till closed).
3841 	 *
3842 	 * We can't assert the references because there might be other
3843 	 * transient reference places because of some walkers or queued
3844 	 * packets in squeue for the timewait state.
3845 	 */
3846 	CONN_DEC_REF(connp);
3847 done:
3848 	q->q_ptr = WR(q)->q_ptr = NULL;
3849 	return (0);
3850 }
3851 
3852 static int
3853 tcpclose_accept(queue_t *q)
3854 {
3855 	vmem_t	*minor_arena;
3856 	dev_t	conn_dev;
3857 
3858 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
3859 
3860 	/*
3861 	 * We had opened an acceptor STREAM for sockfs which is
3862 	 * now being closed due to some error.
3863 	 */
3864 	qprocsoff(q);
3865 
3866 	minor_arena = (vmem_t *)WR(q)->q_ptr;
3867 	conn_dev = (dev_t)RD(q)->q_ptr;
3868 	ASSERT(minor_arena != NULL);
3869 	ASSERT(conn_dev != 0);
3870 	inet_minor_free(minor_arena, conn_dev);
3871 	q->q_ptr = WR(q)->q_ptr = NULL;
3872 	return (0);
3873 }
3874 
3875 /*
3876  * Called by tcp_close() routine via squeue when lingering is
3877  * interrupted by a signal.
3878  */
3879 
3880 /* ARGSUSED */
3881 static void
3882 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
3883 {
3884 	conn_t	*connp = (conn_t *)arg;
3885 	tcp_t	*tcp = connp->conn_tcp;
3886 
3887 	freeb(mp);
3888 	if (tcp->tcp_linger_tid != 0 &&
3889 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3890 		tcp_stop_lingering(tcp);
3891 		tcp->tcp_client_errno = EINTR;
3892 	}
3893 }
3894 
3895 /*
3896  * Called by streams close routine via squeues when our client blows off her
3897  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
3898  * connection politely" When SO_LINGER is set (with a non-zero linger time and
3899  * it is not a nonblocking socket) then this routine sleeps until the FIN is
3900  * acked.
3901  *
3902  * NOTE: tcp_close potentially returns error when lingering.
3903  * However, the stream head currently does not pass these errors
3904  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
3905  * errors to the application (from tsleep()) and not errors
3906  * like ECONNRESET caused by receiving a reset packet.
3907  */
3908 
3909 /* ARGSUSED */
3910 static void
3911 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
3912 {
3913 	char	*msg;
3914 	conn_t	*connp = (conn_t *)arg;
3915 	tcp_t	*tcp = connp->conn_tcp;
3916 	clock_t	delta = 0;
3917 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3918 
3919 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
3920 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
3921 
3922 	mutex_enter(&tcp->tcp_eager_lock);
3923 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
3924 		/* Cleanup for listener */
3925 		tcp_eager_cleanup(tcp, 0);
3926 		tcp->tcp_wait_for_eagers = 1;
3927 	}
3928 	mutex_exit(&tcp->tcp_eager_lock);
3929 
3930 	connp->conn_mdt_ok = B_FALSE;
3931 	tcp->tcp_mdt = B_FALSE;
3932 
3933 	connp->conn_lso_ok = B_FALSE;
3934 	tcp->tcp_lso = B_FALSE;
3935 
3936 	msg = NULL;
3937 	switch (tcp->tcp_state) {
3938 	case TCPS_CLOSED:
3939 	case TCPS_IDLE:
3940 	case TCPS_BOUND:
3941 	case TCPS_LISTEN:
3942 		break;
3943 	case TCPS_SYN_SENT:
3944 		msg = "tcp_close, during connect";
3945 		break;
3946 	case TCPS_SYN_RCVD:
3947 		/*
3948 		 * Close during the connect 3-way handshake
3949 		 * but here there may or may not be pending data
3950 		 * already on queue. Process almost same as in
3951 		 * the ESTABLISHED state.
3952 		 */
3953 		/* FALLTHRU */
3954 	default:
3955 		if (tcp->tcp_sodirect != NULL) {
3956 			/* Ok, no more sodirect */
3957 			tcp->tcp_sodirect = NULL;
3958 		}
3959 
3960 		if (tcp->tcp_fused)
3961 			tcp_unfuse(tcp);
3962 
3963 		/*
3964 		 * If SO_LINGER has set a zero linger time, abort the
3965 		 * connection with a reset.
3966 		 */
3967 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
3968 			msg = "tcp_close, zero lingertime";
3969 			break;
3970 		}
3971 
3972 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
3973 		/*
3974 		 * Abort connection if there is unread data queued.
3975 		 */
3976 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
3977 			msg = "tcp_close, unread data";
3978 			break;
3979 		}
3980 		/*
3981 		 * tcp_hard_bound is now cleared thus all packets go through
3982 		 * tcp_lookup. This fact is used by tcp_detach below.
3983 		 *
3984 		 * We have done a qwait() above which could have possibly
3985 		 * drained more messages in turn causing transition to a
3986 		 * different state. Check whether we have to do the rest
3987 		 * of the processing or not.
3988 		 */
3989 		if (tcp->tcp_state <= TCPS_LISTEN)
3990 			break;
3991 
3992 		/*
3993 		 * Transmit the FIN before detaching the tcp_t.
3994 		 * After tcp_detach returns this queue/perimeter
3995 		 * no longer owns the tcp_t thus others can modify it.
3996 		 */
3997 		(void) tcp_xmit_end(tcp);
3998 
3999 		/*
4000 		 * If lingering on close then wait until the fin is acked,
4001 		 * the SO_LINGER time passes, or a reset is sent/received.
4002 		 */
4003 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4004 		    !(tcp->tcp_fin_acked) &&
4005 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4006 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4007 				tcp->tcp_client_errno = EWOULDBLOCK;
4008 			} else if (tcp->tcp_client_errno == 0) {
4009 
4010 				ASSERT(tcp->tcp_linger_tid == 0);
4011 
4012 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4013 				    tcp_close_linger_timeout,
4014 				    tcp->tcp_lingertime * hz);
4015 
4016 				/* tcp_close_linger_timeout will finish close */
4017 				if (tcp->tcp_linger_tid == 0)
4018 					tcp->tcp_client_errno = ENOSR;
4019 				else
4020 					return;
4021 			}
4022 
4023 			/*
4024 			 * Check if we need to detach or just close
4025 			 * the instance.
4026 			 */
4027 			if (tcp->tcp_state <= TCPS_LISTEN)
4028 				break;
4029 		}
4030 
4031 		/*
4032 		 * Make sure that no other thread will access the tcp_rq of
4033 		 * this instance (through lookups etc.) as tcp_rq will go
4034 		 * away shortly.
4035 		 */
4036 		tcp_acceptor_hash_remove(tcp);
4037 
4038 		mutex_enter(&tcp->tcp_non_sq_lock);
4039 		if (tcp->tcp_flow_stopped) {
4040 			tcp_clrqfull(tcp);
4041 		}
4042 		mutex_exit(&tcp->tcp_non_sq_lock);
4043 
4044 		if (tcp->tcp_timer_tid != 0) {
4045 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4046 			tcp->tcp_timer_tid = 0;
4047 		}
4048 		/*
4049 		 * Need to cancel those timers which will not be used when
4050 		 * TCP is detached.  This has to be done before the tcp_wq
4051 		 * is set to the global queue.
4052 		 */
4053 		tcp_timers_stop(tcp);
4054 
4055 		tcp->tcp_detached = B_TRUE;
4056 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4057 			tcp_time_wait_append(tcp);
4058 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4059 			ASSERT(connp->conn_ref >= 3);
4060 			goto finish;
4061 		}
4062 
4063 		/*
4064 		 * If delta is zero the timer event wasn't executed and was
4065 		 * successfully canceled. In this case we need to restart it
4066 		 * with the minimal delta possible.
4067 		 */
4068 		if (delta >= 0)
4069 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4070 			    delta ? delta : 1);
4071 
4072 		ASSERT(connp->conn_ref >= 3);
4073 		goto finish;
4074 	}
4075 
4076 	/* Detach did not complete. Still need to remove q from stream. */
4077 	if (msg) {
4078 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4079 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4080 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4081 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4082 		    tcp->tcp_state == TCPS_SYN_RCVD)
4083 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4084 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4085 	}
4086 
4087 	tcp_closei_local(tcp);
4088 	CONN_DEC_REF(connp);
4089 	ASSERT(connp->conn_ref >= 2);
4090 
4091 finish:
4092 	/*
4093 	 * Although packets are always processed on the correct
4094 	 * tcp's perimeter and access is serialized via squeue's,
4095 	 * IP still needs a queue when sending packets in time_wait
4096 	 * state so use WR(tcps_g_q) till ip_output() can be
4097 	 * changed to deal with just connp. For read side, we
4098 	 * could have set tcp_rq to NULL but there are some cases
4099 	 * in tcp_rput_data() from early days of this code which
4100 	 * do a putnext without checking if tcp is closed. Those
4101 	 * need to be identified before both tcp_rq and tcp_wq
4102 	 * can be set to NULL and tcps_g_q can disappear forever.
4103 	 */
4104 	mutex_enter(&tcp->tcp_closelock);
4105 	/*
4106 	 * Don't change the queues in the case of a listener that has
4107 	 * eagers in its q or q0. It could surprise the eagers.
4108 	 * Instead wait for the eagers outside the squeue.
4109 	 */
4110 	if (!tcp->tcp_wait_for_eagers) {
4111 		tcp->tcp_detached = B_TRUE;
4112 		/*
4113 		 * When default queue is closing we set tcps_g_q to NULL
4114 		 * after the close is done.
4115 		 */
4116 		ASSERT(tcps->tcps_g_q != NULL);
4117 		tcp->tcp_rq = tcps->tcps_g_q;
4118 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4119 	}
4120 
4121 	/* Signal tcp_close() to finish closing. */
4122 	tcp->tcp_closed = 1;
4123 	cv_signal(&tcp->tcp_closecv);
4124 	mutex_exit(&tcp->tcp_closelock);
4125 }
4126 
4127 
4128 /*
4129  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4130  * Some stream heads get upset if they see these later on as anything but NULL.
4131  */
4132 static void
4133 tcp_close_mpp(mblk_t **mpp)
4134 {
4135 	mblk_t	*mp;
4136 
4137 	if ((mp = *mpp) != NULL) {
4138 		do {
4139 			mp->b_next = NULL;
4140 			mp->b_prev = NULL;
4141 		} while ((mp = mp->b_cont) != NULL);
4142 
4143 		mp = *mpp;
4144 		*mpp = NULL;
4145 		freemsg(mp);
4146 	}
4147 }
4148 
4149 /* Do detached close. */
4150 static void
4151 tcp_close_detached(tcp_t *tcp)
4152 {
4153 	if (tcp->tcp_fused)
4154 		tcp_unfuse(tcp);
4155 
4156 	/*
4157 	 * Clustering code serializes TCP disconnect callbacks and
4158 	 * cluster tcp list walks by blocking a TCP disconnect callback
4159 	 * if a cluster tcp list walk is in progress. This ensures
4160 	 * accurate accounting of TCPs in the cluster code even though
4161 	 * the TCP list walk itself is not atomic.
4162 	 */
4163 	tcp_closei_local(tcp);
4164 	CONN_DEC_REF(tcp->tcp_connp);
4165 }
4166 
4167 /*
4168  * Stop all TCP timers, and free the timer mblks if requested.
4169  */
4170 void
4171 tcp_timers_stop(tcp_t *tcp)
4172 {
4173 	if (tcp->tcp_timer_tid != 0) {
4174 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4175 		tcp->tcp_timer_tid = 0;
4176 	}
4177 	if (tcp->tcp_ka_tid != 0) {
4178 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4179 		tcp->tcp_ka_tid = 0;
4180 	}
4181 	if (tcp->tcp_ack_tid != 0) {
4182 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4183 		tcp->tcp_ack_tid = 0;
4184 	}
4185 	if (tcp->tcp_push_tid != 0) {
4186 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4187 		tcp->tcp_push_tid = 0;
4188 	}
4189 }
4190 
4191 /*
4192  * The tcp_t is going away. Remove it from all lists and set it
4193  * to TCPS_CLOSED. The freeing up of memory is deferred until
4194  * tcp_inactive. This is needed since a thread in tcp_rput might have
4195  * done a CONN_INC_REF on this structure before it was removed from the
4196  * hashes.
4197  */
4198 static void
4199 tcp_closei_local(tcp_t *tcp)
4200 {
4201 	ire_t 	*ire;
4202 	conn_t	*connp = tcp->tcp_connp;
4203 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4204 
4205 	if (!TCP_IS_SOCKET(tcp))
4206 		tcp_acceptor_hash_remove(tcp);
4207 
4208 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4209 	tcp->tcp_ibsegs = 0;
4210 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4211 	tcp->tcp_obsegs = 0;
4212 
4213 	/*
4214 	 * If we are an eager connection hanging off a listener that
4215 	 * hasn't formally accepted the connection yet, get off his
4216 	 * list and blow off any data that we have accumulated.
4217 	 */
4218 	if (tcp->tcp_listener != NULL) {
4219 		tcp_t	*listener = tcp->tcp_listener;
4220 		mutex_enter(&listener->tcp_eager_lock);
4221 		/*
4222 		 * tcp_tconnind_started == B_TRUE means that the
4223 		 * conn_ind has already gone to listener. At
4224 		 * this point, eager will be closed but we
4225 		 * leave it in listeners eager list so that
4226 		 * if listener decides to close without doing
4227 		 * accept, we can clean this up. In tcp_wput_accept
4228 		 * we take care of the case of accept on closed
4229 		 * eager.
4230 		 */
4231 		if (!tcp->tcp_tconnind_started) {
4232 			tcp_eager_unlink(tcp);
4233 			mutex_exit(&listener->tcp_eager_lock);
4234 			/*
4235 			 * We don't want to have any pointers to the
4236 			 * listener queue, after we have released our
4237 			 * reference on the listener
4238 			 */
4239 			ASSERT(tcps->tcps_g_q != NULL);
4240 			tcp->tcp_rq = tcps->tcps_g_q;
4241 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4242 			CONN_DEC_REF(listener->tcp_connp);
4243 		} else {
4244 			mutex_exit(&listener->tcp_eager_lock);
4245 		}
4246 	}
4247 
4248 	/* Stop all the timers */
4249 	tcp_timers_stop(tcp);
4250 
4251 	if (tcp->tcp_state == TCPS_LISTEN) {
4252 		if (tcp->tcp_ip_addr_cache) {
4253 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4254 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4255 			tcp->tcp_ip_addr_cache = NULL;
4256 		}
4257 	}
4258 	mutex_enter(&tcp->tcp_non_sq_lock);
4259 	if (tcp->tcp_flow_stopped)
4260 		tcp_clrqfull(tcp);
4261 	mutex_exit(&tcp->tcp_non_sq_lock);
4262 
4263 	tcp_bind_hash_remove(tcp);
4264 	/*
4265 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4266 	 * is trying to remove this tcp from the time wait list, we will
4267 	 * block in tcp_time_wait_remove while trying to acquire the
4268 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4269 	 * requires the ipcl_hash_remove to be ordered after the
4270 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4271 	 */
4272 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4273 		(void) tcp_time_wait_remove(tcp, NULL);
4274 	CL_INET_DISCONNECT(connp, tcp);
4275 	ipcl_hash_remove(connp);
4276 
4277 	/*
4278 	 * Delete the cached ire in conn_ire_cache and also mark
4279 	 * the conn as CONDEMNED
4280 	 */
4281 	mutex_enter(&connp->conn_lock);
4282 	connp->conn_state_flags |= CONN_CONDEMNED;
4283 	ire = connp->conn_ire_cache;
4284 	connp->conn_ire_cache = NULL;
4285 	mutex_exit(&connp->conn_lock);
4286 	if (ire != NULL)
4287 		IRE_REFRELE_NOTR(ire);
4288 
4289 	/* Need to cleanup any pending ioctls */
4290 	ASSERT(tcp->tcp_time_wait_next == NULL);
4291 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4292 	ASSERT(tcp->tcp_time_wait_expire == 0);
4293 	tcp->tcp_state = TCPS_CLOSED;
4294 
4295 	/* Release any SSL context */
4296 	if (tcp->tcp_kssl_ent != NULL) {
4297 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4298 		tcp->tcp_kssl_ent = NULL;
4299 	}
4300 	if (tcp->tcp_kssl_ctx != NULL) {
4301 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4302 		tcp->tcp_kssl_ctx = NULL;
4303 	}
4304 	tcp->tcp_kssl_pending = B_FALSE;
4305 
4306 	tcp_ipsec_cleanup(tcp);
4307 }
4308 
4309 /*
4310  * tcp is dying (called from ipcl_conn_destroy and error cases).
4311  * Free the tcp_t in either case.
4312  */
4313 void
4314 tcp_free(tcp_t *tcp)
4315 {
4316 	mblk_t	*mp;
4317 	ip6_pkt_t	*ipp;
4318 
4319 	ASSERT(tcp != NULL);
4320 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4321 
4322 	tcp->tcp_rq = NULL;
4323 	tcp->tcp_wq = NULL;
4324 
4325 	tcp_close_mpp(&tcp->tcp_xmit_head);
4326 	tcp_close_mpp(&tcp->tcp_reass_head);
4327 	if (tcp->tcp_rcv_list != NULL) {
4328 		/* Free b_next chain */
4329 		tcp_close_mpp(&tcp->tcp_rcv_list);
4330 	}
4331 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4332 		freemsg(mp);
4333 	}
4334 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4335 		freemsg(mp);
4336 	}
4337 
4338 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4339 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4340 		freeb(tcp->tcp_fused_sigurg_mp);
4341 		tcp->tcp_fused_sigurg_mp = NULL;
4342 	}
4343 
4344 	if (tcp->tcp_ordrel_mp != NULL) {
4345 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
4346 		freeb(tcp->tcp_ordrel_mp);
4347 		tcp->tcp_ordrel_mp = NULL;
4348 	}
4349 
4350 	if (tcp->tcp_sack_info != NULL) {
4351 		if (tcp->tcp_notsack_list != NULL) {
4352 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4353 		}
4354 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4355 	}
4356 
4357 	if (tcp->tcp_hopopts != NULL) {
4358 		mi_free(tcp->tcp_hopopts);
4359 		tcp->tcp_hopopts = NULL;
4360 		tcp->tcp_hopoptslen = 0;
4361 	}
4362 	ASSERT(tcp->tcp_hopoptslen == 0);
4363 	if (tcp->tcp_dstopts != NULL) {
4364 		mi_free(tcp->tcp_dstopts);
4365 		tcp->tcp_dstopts = NULL;
4366 		tcp->tcp_dstoptslen = 0;
4367 	}
4368 	ASSERT(tcp->tcp_dstoptslen == 0);
4369 	if (tcp->tcp_rtdstopts != NULL) {
4370 		mi_free(tcp->tcp_rtdstopts);
4371 		tcp->tcp_rtdstopts = NULL;
4372 		tcp->tcp_rtdstoptslen = 0;
4373 	}
4374 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4375 	if (tcp->tcp_rthdr != NULL) {
4376 		mi_free(tcp->tcp_rthdr);
4377 		tcp->tcp_rthdr = NULL;
4378 		tcp->tcp_rthdrlen = 0;
4379 	}
4380 	ASSERT(tcp->tcp_rthdrlen == 0);
4381 
4382 	ipp = &tcp->tcp_sticky_ipp;
4383 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4384 	    IPPF_RTHDR))
4385 		ip6_pkt_free(ipp);
4386 
4387 	/*
4388 	 * Free memory associated with the tcp/ip header template.
4389 	 */
4390 
4391 	if (tcp->tcp_iphc != NULL)
4392 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4393 
4394 	/*
4395 	 * Following is really a blowing away a union.
4396 	 * It happens to have exactly two members of identical size
4397 	 * the following code is enough.
4398 	 */
4399 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4400 }
4401 
4402 
4403 /*
4404  * Put a connection confirmation message upstream built from the
4405  * address information within 'iph' and 'tcph'.  Report our success or failure.
4406  */
4407 static boolean_t
4408 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4409     mblk_t **defermp)
4410 {
4411 	sin_t	sin;
4412 	sin6_t	sin6;
4413 	mblk_t	*mp;
4414 	char	*optp = NULL;
4415 	int	optlen = 0;
4416 
4417 	if (defermp != NULL)
4418 		*defermp = NULL;
4419 
4420 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4421 		/*
4422 		 * Return in T_CONN_CON results of option negotiation through
4423 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4424 		 * negotiation, then what is received from remote end needs
4425 		 * to be taken into account but there is no such thing (yet?)
4426 		 * in our TCP/IP.
4427 		 * Note: We do not use mi_offset_param() here as
4428 		 * tcp_opts_conn_req contents do not directly come from
4429 		 * an application and are either generated in kernel or
4430 		 * from user input that was already verified.
4431 		 */
4432 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4433 		optp = (char *)(mp->b_rptr +
4434 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4435 		optlen = (int)
4436 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4437 	}
4438 
4439 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4440 		ipha_t *ipha = (ipha_t *)iphdr;
4441 
4442 		/* packet is IPv4 */
4443 		if (tcp->tcp_family == AF_INET) {
4444 			sin = sin_null;
4445 			sin.sin_addr.s_addr = ipha->ipha_src;
4446 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4447 			sin.sin_family = AF_INET;
4448 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4449 			    (int)sizeof (sin_t), optp, optlen);
4450 		} else {
4451 			sin6 = sin6_null;
4452 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4453 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4454 			sin6.sin6_family = AF_INET6;
4455 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4456 			    (int)sizeof (sin6_t), optp, optlen);
4457 
4458 		}
4459 	} else {
4460 		ip6_t	*ip6h = (ip6_t *)iphdr;
4461 
4462 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4463 		ASSERT(tcp->tcp_family == AF_INET6);
4464 		sin6 = sin6_null;
4465 		sin6.sin6_addr = ip6h->ip6_src;
4466 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4467 		sin6.sin6_family = AF_INET6;
4468 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4469 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4470 		    (int)sizeof (sin6_t), optp, optlen);
4471 	}
4472 
4473 	if (!mp)
4474 		return (B_FALSE);
4475 
4476 	mblk_copycred(mp, idmp);
4477 
4478 	if (defermp == NULL) {
4479 		conn_t *connp = tcp->tcp_connp;
4480 		if (IPCL_IS_NONSTR(connp)) {
4481 			cred_t *cr;
4482 			pid_t cpid;
4483 
4484 			cr = msg_getcred(mp, &cpid);
4485 			(*connp->conn_upcalls->su_connected)
4486 			    (connp->conn_upper_handle, tcp->tcp_connid, cr,
4487 			    cpid);
4488 			freemsg(mp);
4489 		} else {
4490 			putnext(tcp->tcp_rq, mp);
4491 		}
4492 	} else {
4493 		*defermp = mp;
4494 	}
4495 
4496 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4497 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4498 	return (B_TRUE);
4499 }
4500 
4501 /*
4502  * Defense for the SYN attack -
4503  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4504  *    one from the list of droppable eagers. This list is a subset of q0.
4505  *    see comments before the definition of MAKE_DROPPABLE().
4506  * 2. Don't drop a SYN request before its first timeout. This gives every
4507  *    request at least til the first timeout to complete its 3-way handshake.
4508  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4509  *    requests currently on the queue that has timed out. This will be used
4510  *    as an indicator of whether an attack is under way, so that appropriate
4511  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4512  *    either when eager goes into ESTABLISHED, or gets freed up.)
4513  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4514  *    # of timeout drops back to <= q0len/32 => SYN alert off
4515  */
4516 static boolean_t
4517 tcp_drop_q0(tcp_t *tcp)
4518 {
4519 	tcp_t	*eager;
4520 	mblk_t	*mp;
4521 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4522 
4523 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4524 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4525 
4526 	/* Pick oldest eager from the list of droppable eagers */
4527 	eager = tcp->tcp_eager_prev_drop_q0;
4528 
4529 	/* If list is empty. return B_FALSE */
4530 	if (eager == tcp) {
4531 		return (B_FALSE);
4532 	}
4533 
4534 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4535 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4536 		return (B_FALSE);
4537 
4538 	/*
4539 	 * Take this eager out from the list of droppable eagers since we are
4540 	 * going to drop it.
4541 	 */
4542 	MAKE_UNDROPPABLE(eager);
4543 
4544 	if (tcp->tcp_debug) {
4545 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4546 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4547 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4548 		    tcp->tcp_conn_req_cnt_q0,
4549 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4550 	}
4551 
4552 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4553 
4554 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4555 	CONN_INC_REF(eager->tcp_connp);
4556 
4557 	/* Mark the IRE created for this SYN request temporary */
4558 	tcp_ip_ire_mark_advice(eager);
4559 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
4560 	    tcp_clean_death_wrapper, eager->tcp_connp,
4561 	    SQ_FILL, SQTAG_TCP_DROP_Q0);
4562 
4563 	return (B_TRUE);
4564 }
4565 
4566 int
4567 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4568     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4569 {
4570 	tcp_t 		*ltcp = lconnp->conn_tcp;
4571 	tcp_t		*tcp = connp->conn_tcp;
4572 	mblk_t		*tpi_mp;
4573 	ipha_t		*ipha;
4574 	ip6_t		*ip6h;
4575 	sin6_t 		sin6;
4576 	in6_addr_t 	v6dst;
4577 	int		err;
4578 	int		ifindex = 0;
4579 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4580 
4581 	if (ipvers == IPV4_VERSION) {
4582 		ipha = (ipha_t *)mp->b_rptr;
4583 
4584 		connp->conn_send = ip_output;
4585 		connp->conn_recv = tcp_input;
4586 
4587 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4588 		    &connp->conn_bound_source_v6);
4589 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4590 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4591 
4592 		sin6 = sin6_null;
4593 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4594 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4595 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4596 		sin6.sin6_family = AF_INET6;
4597 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4598 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4599 		if (tcp->tcp_recvdstaddr) {
4600 			sin6_t	sin6d;
4601 
4602 			sin6d = sin6_null;
4603 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4604 			    &sin6d.sin6_addr);
4605 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4606 			sin6d.sin6_family = AF_INET;
4607 			tpi_mp = mi_tpi_extconn_ind(NULL,
4608 			    (char *)&sin6d, sizeof (sin6_t),
4609 			    (char *)&tcp,
4610 			    (t_scalar_t)sizeof (intptr_t),
4611 			    (char *)&sin6d, sizeof (sin6_t),
4612 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4613 		} else {
4614 			tpi_mp = mi_tpi_conn_ind(NULL,
4615 			    (char *)&sin6, sizeof (sin6_t),
4616 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4617 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4618 		}
4619 	} else {
4620 		ip6h = (ip6_t *)mp->b_rptr;
4621 
4622 		connp->conn_send = ip_output_v6;
4623 		connp->conn_recv = tcp_input;
4624 
4625 		connp->conn_bound_source_v6 = ip6h->ip6_dst;
4626 		connp->conn_srcv6 = ip6h->ip6_dst;
4627 		connp->conn_remv6 = ip6h->ip6_src;
4628 
4629 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4630 		ifindex = (int)DB_CKSUMSTUFF(mp);
4631 		DB_CKSUMSTUFF(mp) = 0;
4632 
4633 		sin6 = sin6_null;
4634 		sin6.sin6_addr = ip6h->ip6_src;
4635 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4636 		sin6.sin6_family = AF_INET6;
4637 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4638 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4639 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4640 
4641 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4642 			/* Pass up the scope_id of remote addr */
4643 			sin6.sin6_scope_id = ifindex;
4644 		} else {
4645 			sin6.sin6_scope_id = 0;
4646 		}
4647 		if (tcp->tcp_recvdstaddr) {
4648 			sin6_t	sin6d;
4649 
4650 			sin6d = sin6_null;
4651 			sin6.sin6_addr = ip6h->ip6_dst;
4652 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4653 			sin6d.sin6_family = AF_INET;
4654 			tpi_mp = mi_tpi_extconn_ind(NULL,
4655 			    (char *)&sin6d, sizeof (sin6_t),
4656 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4657 			    (char *)&sin6d, sizeof (sin6_t),
4658 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4659 		} else {
4660 			tpi_mp = mi_tpi_conn_ind(NULL,
4661 			    (char *)&sin6, sizeof (sin6_t),
4662 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4663 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4664 		}
4665 	}
4666 
4667 	if (tpi_mp == NULL)
4668 		return (ENOMEM);
4669 
4670 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4671 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4672 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4673 	connp->conn_fully_bound = B_FALSE;
4674 
4675 	/* Inherit information from the "parent" */
4676 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4677 	tcp->tcp_family = ltcp->tcp_family;
4678 
4679 	tcp->tcp_wq = ltcp->tcp_wq;
4680 	tcp->tcp_rq = ltcp->tcp_rq;
4681 
4682 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4683 	tcp->tcp_detached = B_TRUE;
4684 	SOCK_CONNID_INIT(tcp->tcp_connid);
4685 	if ((err = tcp_init_values(tcp)) != 0) {
4686 		freemsg(tpi_mp);
4687 		return (err);
4688 	}
4689 
4690 	if (ipvers == IPV4_VERSION) {
4691 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4692 			freemsg(tpi_mp);
4693 			return (err);
4694 		}
4695 		ASSERT(tcp->tcp_ipha != NULL);
4696 	} else {
4697 		/* ifindex must be already set */
4698 		ASSERT(ifindex != 0);
4699 
4700 		if (ltcp->tcp_bound_if != 0)
4701 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4702 		else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src))
4703 			tcp->tcp_bound_if = ifindex;
4704 
4705 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4706 		tcp->tcp_recvifindex = 0;
4707 		tcp->tcp_recvhops = 0xffffffffU;
4708 		ASSERT(tcp->tcp_ip6h != NULL);
4709 	}
4710 
4711 	tcp->tcp_lport = ltcp->tcp_lport;
4712 
4713 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4714 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4715 			/*
4716 			 * Listener had options of some sort; eager inherits.
4717 			 * Free up the eager template and allocate one
4718 			 * of the right size.
4719 			 */
4720 			if (tcp->tcp_hdr_grown) {
4721 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4722 			} else {
4723 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4724 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4725 			}
4726 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4727 			    KM_NOSLEEP);
4728 			if (tcp->tcp_iphc == NULL) {
4729 				tcp->tcp_iphc_len = 0;
4730 				freemsg(tpi_mp);
4731 				return (ENOMEM);
4732 			}
4733 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
4734 			tcp->tcp_hdr_grown = B_TRUE;
4735 		}
4736 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4737 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4738 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4739 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
4740 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
4741 
4742 		/*
4743 		 * Copy the IP+TCP header template from listener to eager
4744 		 */
4745 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4746 		if (tcp->tcp_ipversion == IPV6_VERSION) {
4747 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
4748 			    IPPROTO_RAW) {
4749 				tcp->tcp_ip6h =
4750 				    (ip6_t *)(tcp->tcp_iphc +
4751 				    sizeof (ip6i_t));
4752 			} else {
4753 				tcp->tcp_ip6h =
4754 				    (ip6_t *)(tcp->tcp_iphc);
4755 			}
4756 			tcp->tcp_ipha = NULL;
4757 		} else {
4758 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4759 			tcp->tcp_ip6h = NULL;
4760 		}
4761 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4762 		    tcp->tcp_ip_hdr_len);
4763 	} else {
4764 		/*
4765 		 * only valid case when ipversion of listener and
4766 		 * eager differ is when listener is IPv6 and
4767 		 * eager is IPv4.
4768 		 * Eager header template has been initialized to the
4769 		 * maximum v4 header sizes, which includes space for
4770 		 * TCP and IP options.
4771 		 */
4772 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
4773 		    (tcp->tcp_ipversion == IPV4_VERSION));
4774 		ASSERT(tcp->tcp_iphc_len >=
4775 		    TCP_MAX_COMBINED_HEADER_LENGTH);
4776 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4777 		/* copy IP header fields individually */
4778 		tcp->tcp_ipha->ipha_ttl =
4779 		    ltcp->tcp_ip6h->ip6_hops;
4780 		bcopy(ltcp->tcp_tcph->th_lport,
4781 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
4782 	}
4783 
4784 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4785 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
4786 	    sizeof (in_port_t));
4787 
4788 	if (ltcp->tcp_lport == 0) {
4789 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
4790 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
4791 		    sizeof (in_port_t));
4792 	}
4793 
4794 	if (tcp->tcp_ipversion == IPV4_VERSION) {
4795 		ASSERT(ipha != NULL);
4796 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4797 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4798 
4799 		/* Source routing option copyover (reverse it) */
4800 		if (tcps->tcps_rev_src_routes)
4801 			tcp_opt_reverse(tcp, ipha);
4802 	} else {
4803 		ASSERT(ip6h != NULL);
4804 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
4805 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
4806 	}
4807 
4808 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4809 	ASSERT(!tcp->tcp_tconnind_started);
4810 	/*
4811 	 * If the SYN contains a credential, it's a loopback packet; attach
4812 	 * the credential to the TPI message.
4813 	 */
4814 	mblk_copycred(tpi_mp, idmp);
4815 
4816 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4817 
4818 	/* Inherit the listener's SSL protection state */
4819 
4820 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4821 		kssl_hold_ent(tcp->tcp_kssl_ent);
4822 		tcp->tcp_kssl_pending = B_TRUE;
4823 	}
4824 
4825 	/* Inherit the listener's non-STREAMS flag */
4826 	if (IPCL_IS_NONSTR(lconnp)) {
4827 		connp->conn_flags |= IPCL_NONSTR;
4828 	}
4829 
4830 	return (0);
4831 }
4832 
4833 
4834 int
4835 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
4836     tcph_t *tcph, mblk_t *idmp)
4837 {
4838 	tcp_t 		*ltcp = lconnp->conn_tcp;
4839 	tcp_t		*tcp = connp->conn_tcp;
4840 	sin_t		sin;
4841 	mblk_t		*tpi_mp = NULL;
4842 	int		err;
4843 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4844 
4845 	sin = sin_null;
4846 	sin.sin_addr.s_addr = ipha->ipha_src;
4847 	sin.sin_port = *(uint16_t *)tcph->th_lport;
4848 	sin.sin_family = AF_INET;
4849 	if (ltcp->tcp_recvdstaddr) {
4850 		sin_t	sind;
4851 
4852 		sind = sin_null;
4853 		sind.sin_addr.s_addr = ipha->ipha_dst;
4854 		sind.sin_port = *(uint16_t *)tcph->th_fport;
4855 		sind.sin_family = AF_INET;
4856 		tpi_mp = mi_tpi_extconn_ind(NULL,
4857 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
4858 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
4859 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4860 	} else {
4861 		tpi_mp = mi_tpi_conn_ind(NULL,
4862 		    (char *)&sin, sizeof (sin_t),
4863 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4864 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4865 	}
4866 
4867 	if (tpi_mp == NULL) {
4868 		return (ENOMEM);
4869 	}
4870 
4871 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
4872 	connp->conn_send = ip_output;
4873 	connp->conn_recv = tcp_input;
4874 	connp->conn_fully_bound = B_FALSE;
4875 
4876 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_bound_source_v6);
4877 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4878 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4879 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4880 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4881 
4882 	/* Inherit information from the "parent" */
4883 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4884 	tcp->tcp_family = ltcp->tcp_family;
4885 	tcp->tcp_wq = ltcp->tcp_wq;
4886 	tcp->tcp_rq = ltcp->tcp_rq;
4887 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
4888 	tcp->tcp_detached = B_TRUE;
4889 	SOCK_CONNID_INIT(tcp->tcp_connid);
4890 	if ((err = tcp_init_values(tcp)) != 0) {
4891 		freemsg(tpi_mp);
4892 		return (err);
4893 	}
4894 
4895 	/*
4896 	 * Let's make sure that eager tcp template has enough space to
4897 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
4898 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
4899 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
4900 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
4901 	 * extension headers or with ip6i_t struct). Note that bcopy() below
4902 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
4903 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
4904 	 */
4905 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
4906 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
4907 
4908 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
4909 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
4910 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
4911 	tcp->tcp_ttl = ltcp->tcp_ttl;
4912 	tcp->tcp_tos = ltcp->tcp_tos;
4913 
4914 	/* Copy the IP+TCP header template from listener to eager */
4915 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
4916 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
4917 	tcp->tcp_ip6h = NULL;
4918 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
4919 	    tcp->tcp_ip_hdr_len);
4920 
4921 	/* Initialize the IP addresses and Ports */
4922 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
4923 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
4924 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
4925 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
4926 
4927 	/* Source routing option copyover (reverse it) */
4928 	if (tcps->tcps_rev_src_routes)
4929 		tcp_opt_reverse(tcp, ipha);
4930 
4931 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
4932 	ASSERT(!tcp->tcp_tconnind_started);
4933 
4934 	/*
4935 	 * If the SYN contains a credential, it's a loopback packet; attach
4936 	 * the credential to the TPI message.
4937 	 */
4938 	mblk_copycred(tpi_mp, idmp);
4939 
4940 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
4941 
4942 	/* Inherit the listener's SSL protection state */
4943 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
4944 		kssl_hold_ent(tcp->tcp_kssl_ent);
4945 		tcp->tcp_kssl_pending = B_TRUE;
4946 	}
4947 
4948 	/* Inherit the listener's non-STREAMS flag */
4949 	if (IPCL_IS_NONSTR(lconnp)) {
4950 		connp->conn_flags |= IPCL_NONSTR;
4951 	}
4952 
4953 	return (0);
4954 }
4955 
4956 /*
4957  * sets up conn for ipsec.
4958  * if the first mblk is M_CTL it is consumed and mpp is updated.
4959  * in case of error mpp is freed.
4960  */
4961 conn_t *
4962 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
4963 {
4964 	conn_t 		*connp = tcp->tcp_connp;
4965 	conn_t 		*econnp;
4966 	squeue_t 	*new_sqp;
4967 	mblk_t 		*first_mp = *mpp;
4968 	mblk_t		*mp = *mpp;
4969 	boolean_t	mctl_present = B_FALSE;
4970 	uint_t		ipvers;
4971 
4972 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
4973 	if (econnp == NULL) {
4974 		freemsg(first_mp);
4975 		return (NULL);
4976 	}
4977 	if (DB_TYPE(mp) == M_CTL) {
4978 		if (mp->b_cont == NULL ||
4979 		    mp->b_cont->b_datap->db_type != M_DATA) {
4980 			freemsg(first_mp);
4981 			return (NULL);
4982 		}
4983 		mp = mp->b_cont;
4984 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
4985 			freemsg(first_mp);
4986 			return (NULL);
4987 		}
4988 
4989 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
4990 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4991 		mctl_present = B_TRUE;
4992 	} else {
4993 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
4994 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
4995 	}
4996 
4997 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
4998 	DB_CKSUMSTART(mp) = 0;
4999 
5000 	ASSERT(OK_32PTR(mp->b_rptr));
5001 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5002 	if (ipvers == IPV4_VERSION) {
5003 		uint16_t  	*up;
5004 		uint32_t	ports;
5005 		ipha_t		*ipha;
5006 
5007 		ipha = (ipha_t *)mp->b_rptr;
5008 		up = (uint16_t *)((uchar_t *)ipha +
5009 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5010 		ports = *(uint32_t *)up;
5011 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5012 		    ipha->ipha_dst, ipha->ipha_src, ports);
5013 	} else {
5014 		uint16_t  	*up;
5015 		uint32_t	ports;
5016 		uint16_t	ip_hdr_len;
5017 		uint8_t		*nexthdrp;
5018 		ip6_t 		*ip6h;
5019 		tcph_t		*tcph;
5020 
5021 		ip6h = (ip6_t *)mp->b_rptr;
5022 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5023 			ip_hdr_len = IPV6_HDR_LEN;
5024 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5025 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5026 			CONN_DEC_REF(econnp);
5027 			freemsg(first_mp);
5028 			return (NULL);
5029 		}
5030 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5031 		up = (uint16_t *)tcph->th_lport;
5032 		ports = *(uint32_t *)up;
5033 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5034 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5035 	}
5036 
5037 	/*
5038 	 * The caller already ensured that there is a sqp present.
5039 	 */
5040 	econnp->conn_sqp = new_sqp;
5041 	econnp->conn_initial_sqp = new_sqp;
5042 
5043 	if (connp->conn_policy != NULL) {
5044 		ipsec_in_t *ii;
5045 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5046 		ASSERT(ii->ipsec_in_policy == NULL);
5047 		IPPH_REFHOLD(connp->conn_policy);
5048 		ii->ipsec_in_policy = connp->conn_policy;
5049 
5050 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5051 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5052 			CONN_DEC_REF(econnp);
5053 			freemsg(first_mp);
5054 			return (NULL);
5055 		}
5056 	}
5057 
5058 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5059 		CONN_DEC_REF(econnp);
5060 		freemsg(first_mp);
5061 		return (NULL);
5062 	}
5063 
5064 	/*
5065 	 * If we know we have some policy, pass the "IPSEC"
5066 	 * options size TCP uses this adjust the MSS.
5067 	 */
5068 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5069 	if (mctl_present) {
5070 		freeb(first_mp);
5071 		*mpp = mp;
5072 	}
5073 
5074 	return (econnp);
5075 }
5076 
5077 /*
5078  * tcp_get_conn/tcp_free_conn
5079  *
5080  * tcp_get_conn is used to get a clean tcp connection structure.
5081  * It tries to reuse the connections put on the freelist by the
5082  * time_wait_collector failing which it goes to kmem_cache. This
5083  * way has two benefits compared to just allocating from and
5084  * freeing to kmem_cache.
5085  * 1) The time_wait_collector can free (which includes the cleanup)
5086  * outside the squeue. So when the interrupt comes, we have a clean
5087  * connection sitting in the freelist. Obviously, this buys us
5088  * performance.
5089  *
5090  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5091  * has multiple disadvantages - tying up the squeue during alloc, and the
5092  * fact that IPSec policy initialization has to happen here which
5093  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5094  * But allocating the conn/tcp in IP land is also not the best since
5095  * we can't check the 'q' and 'q0' which are protected by squeue and
5096  * blindly allocate memory which might have to be freed here if we are
5097  * not allowed to accept the connection. By using the freelist and
5098  * putting the conn/tcp back in freelist, we don't pay a penalty for
5099  * allocating memory without checking 'q/q0' and freeing it if we can't
5100  * accept the connection.
5101  *
5102  * Care should be taken to put the conn back in the same squeue's freelist
5103  * from which it was allocated. Best results are obtained if conn is
5104  * allocated from listener's squeue and freed to the same. Time wait
5105  * collector will free up the freelist is the connection ends up sitting
5106  * there for too long.
5107  */
5108 void *
5109 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5110 {
5111 	tcp_t			*tcp = NULL;
5112 	conn_t			*connp = NULL;
5113 	squeue_t		*sqp = (squeue_t *)arg;
5114 	tcp_squeue_priv_t 	*tcp_time_wait;
5115 	netstack_t		*ns;
5116 
5117 	tcp_time_wait =
5118 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5119 
5120 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5121 	tcp = tcp_time_wait->tcp_free_list;
5122 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5123 	if (tcp != NULL) {
5124 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5125 		tcp_time_wait->tcp_free_list_cnt--;
5126 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5127 		tcp->tcp_time_wait_next = NULL;
5128 		connp = tcp->tcp_connp;
5129 		connp->conn_flags |= IPCL_REUSED;
5130 
5131 		ASSERT(tcp->tcp_tcps == NULL);
5132 		ASSERT(connp->conn_netstack == NULL);
5133 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5134 		ns = tcps->tcps_netstack;
5135 		netstack_hold(ns);
5136 		connp->conn_netstack = ns;
5137 		tcp->tcp_tcps = tcps;
5138 		TCPS_REFHOLD(tcps);
5139 		ipcl_globalhash_insert(connp);
5140 		return ((void *)connp);
5141 	}
5142 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5143 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5144 	    tcps->tcps_netstack)) == NULL)
5145 		return (NULL);
5146 	tcp = connp->conn_tcp;
5147 	/*
5148 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5149 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5150 	 */
5151 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5152 		ipcl_conn_destroy(connp);
5153 		return (NULL);
5154 	}
5155 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5156 	tcp->tcp_tcps = tcps;
5157 	TCPS_REFHOLD(tcps);
5158 
5159 	return ((void *)connp);
5160 }
5161 
5162 /*
5163  * Update the cached label for the given tcp_t.  This should be called once per
5164  * connection, and before any packets are sent or tcp_process_options is
5165  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5166  */
5167 static boolean_t
5168 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5169 {
5170 	conn_t *connp = tcp->tcp_connp;
5171 
5172 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5173 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5174 		int added;
5175 
5176 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5177 		    connp->conn_mac_exempt,
5178 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5179 			return (B_FALSE);
5180 
5181 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5182 		if (added == -1)
5183 			return (B_FALSE);
5184 		tcp->tcp_hdr_len += added;
5185 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5186 		tcp->tcp_ip_hdr_len += added;
5187 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5188 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5189 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5190 			    tcp->tcp_hdr_len);
5191 			if (added == -1)
5192 				return (B_FALSE);
5193 			tcp->tcp_hdr_len += added;
5194 			tcp->tcp_tcph = (tcph_t *)
5195 			    ((uchar_t *)tcp->tcp_tcph + added);
5196 			tcp->tcp_ip_hdr_len += added;
5197 		}
5198 	} else {
5199 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5200 
5201 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5202 		    connp->conn_mac_exempt,
5203 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5204 			return (B_FALSE);
5205 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5206 		    &tcp->tcp_label_len, optbuf) != 0)
5207 			return (B_FALSE);
5208 		if (tcp_build_hdrs(tcp) != 0)
5209 			return (B_FALSE);
5210 	}
5211 
5212 	connp->conn_ulp_labeled = 1;
5213 
5214 	return (B_TRUE);
5215 }
5216 
5217 /* BEGIN CSTYLED */
5218 /*
5219  *
5220  * The sockfs ACCEPT path:
5221  * =======================
5222  *
5223  * The eager is now established in its own perimeter as soon as SYN is
5224  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5225  * completes the accept processing on the acceptor STREAM. The sending
5226  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5227  * listener but a TLI/XTI listener completes the accept processing
5228  * on the listener perimeter.
5229  *
5230  * Common control flow for 3 way handshake:
5231  * ----------------------------------------
5232  *
5233  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5234  *					-> tcp_conn_request()
5235  *
5236  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5237  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5238  *
5239  * Sockfs ACCEPT Path:
5240  * -------------------
5241  *
5242  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5243  * as STREAM entry point)
5244  *
5245  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5246  *
5247  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5248  * association (we are not behind eager's squeue but sockfs is protecting us
5249  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5250  * is changed to point at tcp_wput().
5251  *
5252  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5253  * listener (done on listener's perimeter).
5254  *
5255  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5256  * accept.
5257  *
5258  * TLI/XTI client ACCEPT path:
5259  * ---------------------------
5260  *
5261  * soaccept() sends T_CONN_RES on the listener STREAM.
5262  *
5263  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5264  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5265  *
5266  * Locks:
5267  * ======
5268  *
5269  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5270  * and listeners->tcp_eager_next_q.
5271  *
5272  * Referencing:
5273  * ============
5274  *
5275  * 1) We start out in tcp_conn_request by eager placing a ref on
5276  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5277  *
5278  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5279  * doing so we place a ref on the eager. This ref is finally dropped at the
5280  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5281  * reference is dropped by the squeue framework.
5282  *
5283  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5284  *
5285  * The reference must be released by the same entity that added the reference
5286  * In the above scheme, the eager is the entity that adds and releases the
5287  * references. Note that tcp_accept_finish executes in the squeue of the eager
5288  * (albeit after it is attached to the acceptor stream). Though 1. executes
5289  * in the listener's squeue, the eager is nascent at this point and the
5290  * reference can be considered to have been added on behalf of the eager.
5291  *
5292  * Eager getting a Reset or listener closing:
5293  * ==========================================
5294  *
5295  * Once the listener and eager are linked, the listener never does the unlink.
5296  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5297  * a message on all eager perimeter. The eager then does the unlink, clears
5298  * any pointers to the listener's queue and drops the reference to the
5299  * listener. The listener waits in tcp_close outside the squeue until its
5300  * refcount has dropped to 1. This ensures that the listener has waited for
5301  * all eagers to clear their association with the listener.
5302  *
5303  * Similarly, if eager decides to go away, it can unlink itself and close.
5304  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5305  * the reference to eager is still valid because of the extra ref we put
5306  * in tcp_send_conn_ind.
5307  *
5308  * Listener can always locate the eager under the protection
5309  * of the listener->tcp_eager_lock, and then do a refhold
5310  * on the eager during the accept processing.
5311  *
5312  * The acceptor stream accesses the eager in the accept processing
5313  * based on the ref placed on eager before sending T_conn_ind.
5314  * The only entity that can negate this refhold is a listener close
5315  * which is mutually exclusive with an active acceptor stream.
5316  *
5317  * Eager's reference on the listener
5318  * ===================================
5319  *
5320  * If the accept happens (even on a closed eager) the eager drops its
5321  * reference on the listener at the start of tcp_accept_finish. If the
5322  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5323  * the reference is dropped in tcp_closei_local. If the listener closes,
5324  * the reference is dropped in tcp_eager_kill. In all cases the reference
5325  * is dropped while executing in the eager's context (squeue).
5326  */
5327 /* END CSTYLED */
5328 
5329 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5330 
5331 /*
5332  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5333  * tcp_rput_data will not see any SYN packets.
5334  */
5335 /* ARGSUSED */
5336 void
5337 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5338 {
5339 	tcph_t		*tcph;
5340 	uint32_t	seg_seq;
5341 	tcp_t		*eager;
5342 	uint_t		ipvers;
5343 	ipha_t		*ipha;
5344 	ip6_t		*ip6h;
5345 	int		err;
5346 	conn_t		*econnp = NULL;
5347 	squeue_t	*new_sqp;
5348 	mblk_t		*mp1;
5349 	uint_t 		ip_hdr_len;
5350 	conn_t		*connp = (conn_t *)arg;
5351 	tcp_t		*tcp = connp->conn_tcp;
5352 	cred_t		*credp;
5353 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5354 	ip_stack_t	*ipst;
5355 
5356 	if (tcp->tcp_state != TCPS_LISTEN)
5357 		goto error2;
5358 
5359 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5360 
5361 	mutex_enter(&tcp->tcp_eager_lock);
5362 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5363 		mutex_exit(&tcp->tcp_eager_lock);
5364 		TCP_STAT(tcps, tcp_listendrop);
5365 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5366 		if (tcp->tcp_debug) {
5367 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5368 			    "tcp_conn_request: listen backlog (max=%d) "
5369 			    "overflow (%d pending) on %s",
5370 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5371 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5372 		}
5373 		goto error2;
5374 	}
5375 
5376 	if (tcp->tcp_conn_req_cnt_q0 >=
5377 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5378 		/*
5379 		 * Q0 is full. Drop a pending half-open req from the queue
5380 		 * to make room for the new SYN req. Also mark the time we
5381 		 * drop a SYN.
5382 		 *
5383 		 * A more aggressive defense against SYN attack will
5384 		 * be to set the "tcp_syn_defense" flag now.
5385 		 */
5386 		TCP_STAT(tcps, tcp_listendropq0);
5387 		tcp->tcp_last_rcv_lbolt = lbolt64;
5388 		if (!tcp_drop_q0(tcp)) {
5389 			mutex_exit(&tcp->tcp_eager_lock);
5390 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5391 			if (tcp->tcp_debug) {
5392 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5393 				    "tcp_conn_request: listen half-open queue "
5394 				    "(max=%d) full (%d pending) on %s",
5395 				    tcps->tcps_conn_req_max_q0,
5396 				    tcp->tcp_conn_req_cnt_q0,
5397 				    tcp_display(tcp, NULL,
5398 				    DISP_PORT_ONLY));
5399 			}
5400 			goto error2;
5401 		}
5402 	}
5403 	mutex_exit(&tcp->tcp_eager_lock);
5404 
5405 	/*
5406 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5407 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5408 	 * link local address.  If IPSec is enabled, db_struioflag has
5409 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5410 	 * otherwise an error case if neither of them is set.
5411 	 */
5412 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5413 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5414 		DB_CKSUMSTART(mp) = 0;
5415 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5416 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5417 		if (econnp == NULL)
5418 			goto error2;
5419 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5420 		econnp->conn_sqp = new_sqp;
5421 		econnp->conn_initial_sqp = new_sqp;
5422 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5423 		/*
5424 		 * mp is updated in tcp_get_ipsec_conn().
5425 		 */
5426 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5427 		if (econnp == NULL) {
5428 			/*
5429 			 * mp freed by tcp_get_ipsec_conn.
5430 			 */
5431 			return;
5432 		}
5433 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5434 	} else {
5435 		goto error2;
5436 	}
5437 
5438 	ASSERT(DB_TYPE(mp) == M_DATA);
5439 
5440 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5441 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5442 	ASSERT(OK_32PTR(mp->b_rptr));
5443 	if (ipvers == IPV4_VERSION) {
5444 		ipha = (ipha_t *)mp->b_rptr;
5445 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5446 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5447 	} else {
5448 		ip6h = (ip6_t *)mp->b_rptr;
5449 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5450 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5451 	}
5452 
5453 	if (tcp->tcp_family == AF_INET) {
5454 		ASSERT(ipvers == IPV4_VERSION);
5455 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5456 	} else {
5457 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5458 	}
5459 
5460 	if (err)
5461 		goto error3;
5462 
5463 	eager = econnp->conn_tcp;
5464 
5465 	/*
5466 	 * Pre-allocate the T_ordrel_ind mblk for TPI socket so that at close
5467 	 * time, we will always have that to send up.  Otherwise, we need to do
5468 	 * special handling in case the allocation fails at that time.
5469 	 */
5470 	ASSERT(eager->tcp_ordrel_mp == NULL);
5471 	if (!IPCL_IS_NONSTR(econnp) &&
5472 	    (eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5473 		goto error3;
5474 
5475 	/* Inherit various TCP parameters from the listener */
5476 	eager->tcp_naglim = tcp->tcp_naglim;
5477 	eager->tcp_first_timer_threshold =
5478 	    tcp->tcp_first_timer_threshold;
5479 	eager->tcp_second_timer_threshold =
5480 	    tcp->tcp_second_timer_threshold;
5481 
5482 	eager->tcp_first_ctimer_threshold =
5483 	    tcp->tcp_first_ctimer_threshold;
5484 	eager->tcp_second_ctimer_threshold =
5485 	    tcp->tcp_second_ctimer_threshold;
5486 
5487 	/*
5488 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5489 	 * If it does not, the eager's receive window will be set to the
5490 	 * listener's receive window later in this function.
5491 	 */
5492 	eager->tcp_rwnd = 0;
5493 
5494 	/*
5495 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5496 	 * calling tcp_process_options() where tcp_mss_set() is called
5497 	 * to set the initial cwnd.
5498 	 */
5499 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5500 
5501 	/*
5502 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5503 	 * zone id before the accept is completed in tcp_wput_accept().
5504 	 */
5505 	econnp->conn_zoneid = connp->conn_zoneid;
5506 	econnp->conn_allzones = connp->conn_allzones;
5507 
5508 	/* Copy nexthop information from listener to eager */
5509 	if (connp->conn_nexthop_set) {
5510 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5511 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5512 	}
5513 
5514 	/*
5515 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5516 	 * eager is accepted
5517 	 */
5518 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5519 	crhold(credp);
5520 
5521 	/*
5522 	 * If the caller has the process-wide flag set, then default to MAC
5523 	 * exempt mode.  This allows read-down to unlabeled hosts.
5524 	 */
5525 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5526 		econnp->conn_mac_exempt = B_TRUE;
5527 
5528 	if (is_system_labeled()) {
5529 		cred_t *cr;
5530 
5531 		if (connp->conn_mlp_type != mlptSingle) {
5532 			cr = econnp->conn_peercred = msg_getcred(mp, NULL);
5533 			if (cr != NULL)
5534 				crhold(cr);
5535 			else
5536 				cr = econnp->conn_cred;
5537 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5538 			    econnp, cred_t *, cr)
5539 		} else {
5540 			cr = econnp->conn_cred;
5541 			DTRACE_PROBE2(syn_accept, conn_t *,
5542 			    econnp, cred_t *, cr)
5543 		}
5544 
5545 		if (!tcp_update_label(eager, cr)) {
5546 			DTRACE_PROBE3(
5547 			    tx__ip__log__error__connrequest__tcp,
5548 			    char *, "eager connp(1) label on SYN mp(2) failed",
5549 			    conn_t *, econnp, mblk_t *, mp);
5550 			goto error3;
5551 		}
5552 	}
5553 
5554 	eager->tcp_hard_binding = B_TRUE;
5555 
5556 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5557 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5558 
5559 	CL_INET_CONNECT(connp, eager, B_FALSE, err);
5560 	if (err != 0) {
5561 		tcp_bind_hash_remove(eager);
5562 		goto error3;
5563 	}
5564 
5565 	/*
5566 	 * No need to check for multicast destination since ip will only pass
5567 	 * up multicasts to those that have expressed interest
5568 	 * TODO: what about rejecting broadcasts?
5569 	 * Also check that source is not a multicast or broadcast address.
5570 	 */
5571 	eager->tcp_state = TCPS_SYN_RCVD;
5572 
5573 
5574 	/*
5575 	 * There should be no ire in the mp as we are being called after
5576 	 * receiving the SYN.
5577 	 */
5578 	ASSERT(tcp_ire_mp(&mp) == NULL);
5579 
5580 	/*
5581 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5582 	 */
5583 
5584 	if (tcp_adapt_ire(eager, NULL) == 0) {
5585 		/* Undo the bind_hash_insert */
5586 		tcp_bind_hash_remove(eager);
5587 		goto error3;
5588 	}
5589 
5590 	/* Process all TCP options. */
5591 	tcp_process_options(eager, tcph);
5592 
5593 	/* Is the other end ECN capable? */
5594 	if (tcps->tcps_ecn_permitted >= 1 &&
5595 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5596 		eager->tcp_ecn_ok = B_TRUE;
5597 	}
5598 
5599 	/*
5600 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5601 	 * window size changed via SO_RCVBUF option.  First round up the
5602 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5603 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5604 	 * setting.
5605 	 *
5606 	 * Note if there is a rpipe metric associated with the remote host,
5607 	 * we should not inherit receive window size from listener.
5608 	 */
5609 	eager->tcp_rwnd = MSS_ROUNDUP(
5610 	    (eager->tcp_rwnd == 0 ? tcp->tcp_recv_hiwater:
5611 	    eager->tcp_rwnd), eager->tcp_mss);
5612 	if (eager->tcp_snd_ws_ok)
5613 		tcp_set_ws_value(eager);
5614 	/*
5615 	 * Note that this is the only place tcp_rwnd_set() is called for
5616 	 * accepting a connection.  We need to call it here instead of
5617 	 * after the 3-way handshake because we need to tell the other
5618 	 * side our rwnd in the SYN-ACK segment.
5619 	 */
5620 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5621 
5622 	/*
5623 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5624 	 * via soaccept()->soinheritoptions() which essentially applies
5625 	 * all the listener options to the new STREAM. The options that we
5626 	 * need to take care of are:
5627 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5628 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5629 	 * SO_SNDBUF, SO_RCVBUF.
5630 	 *
5631 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5632 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5633 	 *		tcp_maxpsz_set() gets called later from
5634 	 *		tcp_accept_finish(), the option takes effect.
5635 	 *
5636 	 */
5637 	/* Set the TCP options */
5638 	eager->tcp_recv_hiwater = tcp->tcp_recv_hiwater;
5639 	eager->tcp_recv_lowater = tcp->tcp_recv_lowater;
5640 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5641 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5642 	eager->tcp_oobinline = tcp->tcp_oobinline;
5643 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5644 	eager->tcp_broadcast = tcp->tcp_broadcast;
5645 	eager->tcp_useloopback = tcp->tcp_useloopback;
5646 	eager->tcp_dontroute = tcp->tcp_dontroute;
5647 	eager->tcp_debug = tcp->tcp_debug;
5648 	eager->tcp_linger = tcp->tcp_linger;
5649 	eager->tcp_lingertime = tcp->tcp_lingertime;
5650 	if (tcp->tcp_ka_enabled)
5651 		eager->tcp_ka_enabled = 1;
5652 
5653 	/* Set the IP options */
5654 	econnp->conn_broadcast = connp->conn_broadcast;
5655 	econnp->conn_loopback = connp->conn_loopback;
5656 	econnp->conn_dontroute = connp->conn_dontroute;
5657 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5658 
5659 	/* Put a ref on the listener for the eager. */
5660 	CONN_INC_REF(connp);
5661 	mutex_enter(&tcp->tcp_eager_lock);
5662 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5663 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5664 	tcp->tcp_eager_next_q0 = eager;
5665 	eager->tcp_eager_prev_q0 = tcp;
5666 
5667 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5668 	eager->tcp_listener = tcp;
5669 	eager->tcp_saved_listener = tcp;
5670 
5671 	/*
5672 	 * Tag this detached tcp vector for later retrieval
5673 	 * by our listener client in tcp_accept().
5674 	 */
5675 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5676 	tcp->tcp_conn_req_cnt_q0++;
5677 	if (++tcp->tcp_conn_req_seqnum == -1) {
5678 		/*
5679 		 * -1 is "special" and defined in TPI as something
5680 		 * that should never be used in T_CONN_IND
5681 		 */
5682 		++tcp->tcp_conn_req_seqnum;
5683 	}
5684 	mutex_exit(&tcp->tcp_eager_lock);
5685 
5686 	if (tcp->tcp_syn_defense) {
5687 		/* Don't drop the SYN that comes from a good IP source */
5688 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5689 		if (addr_cache != NULL && eager->tcp_remote ==
5690 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5691 			eager->tcp_dontdrop = B_TRUE;
5692 		}
5693 	}
5694 
5695 	/*
5696 	 * We need to insert the eager in its own perimeter but as soon
5697 	 * as we do that, we expose the eager to the classifier and
5698 	 * should not touch any field outside the eager's perimeter.
5699 	 * So do all the work necessary before inserting the eager
5700 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5701 	 * will succeed but undo everything if it fails.
5702 	 */
5703 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5704 	eager->tcp_irs = seg_seq;
5705 	eager->tcp_rack = seg_seq;
5706 	eager->tcp_rnxt = seg_seq + 1;
5707 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5708 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5709 	eager->tcp_state = TCPS_SYN_RCVD;
5710 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5711 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5712 	if (mp1 == NULL) {
5713 		/*
5714 		 * Increment the ref count as we are going to
5715 		 * enqueueing an mp in squeue
5716 		 */
5717 		CONN_INC_REF(econnp);
5718 		goto error;
5719 	}
5720 
5721 	/*
5722 	 * Note that in theory this should use the current pid
5723 	 * so that getpeerucred on the client returns the actual listener
5724 	 * that does accept. But accept() hasn't been called yet. We could use
5725 	 * the pid of the process that did bind/listen on the server.
5726 	 * However, with common usage like inetd() the bind/listen can be done
5727 	 * by a different process than the accept().
5728 	 * Hence we do the simple thing of using the open pid here.
5729 	 * Note that db_credp is set later in tcp_send_data().
5730 	 */
5731 	mblk_setcred(mp1, credp, tcp->tcp_cpid);
5732 	eager->tcp_cpid = tcp->tcp_cpid;
5733 	eager->tcp_open_time = lbolt64;
5734 
5735 	/*
5736 	 * We need to start the rto timer. In normal case, we start
5737 	 * the timer after sending the packet on the wire (or at
5738 	 * least believing that packet was sent by waiting for
5739 	 * CALL_IP_WPUT() to return). Since this is the first packet
5740 	 * being sent on the wire for the eager, our initial tcp_rto
5741 	 * is at least tcp_rexmit_interval_min which is a fairly
5742 	 * large value to allow the algorithm to adjust slowly to large
5743 	 * fluctuations of RTT during first few transmissions.
5744 	 *
5745 	 * Starting the timer first and then sending the packet in this
5746 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5747 	 * is of the order of several 100ms and starting the timer
5748 	 * first and then sending the packet will result in difference
5749 	 * of few micro seconds.
5750 	 *
5751 	 * Without this optimization, we are forced to hold the fanout
5752 	 * lock across the ipcl_bind_insert() and sending the packet
5753 	 * so that we don't race against an incoming packet (maybe RST)
5754 	 * for this eager.
5755 	 *
5756 	 * It is necessary to acquire an extra reference on the eager
5757 	 * at this point and hold it until after tcp_send_data() to
5758 	 * ensure against an eager close race.
5759 	 */
5760 
5761 	CONN_INC_REF(eager->tcp_connp);
5762 
5763 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
5764 
5765 	/*
5766 	 * Insert the eager in its own perimeter now. We are ready to deal
5767 	 * with any packets on eager.
5768 	 */
5769 	if (eager->tcp_ipversion == IPV4_VERSION) {
5770 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
5771 			goto error;
5772 		}
5773 	} else {
5774 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
5775 			goto error;
5776 		}
5777 	}
5778 
5779 	/* mark conn as fully-bound */
5780 	econnp->conn_fully_bound = B_TRUE;
5781 
5782 	/* Send the SYN-ACK */
5783 	tcp_send_data(eager, eager->tcp_wq, mp1);
5784 	CONN_DEC_REF(eager->tcp_connp);
5785 	freemsg(mp);
5786 
5787 	return;
5788 error:
5789 	freemsg(mp1);
5790 	eager->tcp_closemp_used = B_TRUE;
5791 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
5792 	mp1 = &eager->tcp_closemp;
5793 	SQUEUE_ENTER_ONE(econnp->conn_sqp, mp1, tcp_eager_kill,
5794 	    econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_2);
5795 
5796 	/*
5797 	 * If a connection already exists, send the mp to that connections so
5798 	 * that it can be appropriately dealt with.
5799 	 */
5800 	ipst = tcps->tcps_netstack->netstack_ip;
5801 
5802 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
5803 		if (!IPCL_IS_CONNECTED(econnp)) {
5804 			/*
5805 			 * Something bad happened. ipcl_conn_insert()
5806 			 * failed because a connection already existed
5807 			 * in connected hash but we can't find it
5808 			 * anymore (someone blew it away). Just
5809 			 * free this message and hopefully remote
5810 			 * will retransmit at which time the SYN can be
5811 			 * treated as a new connection or dealth with
5812 			 * a TH_RST if a connection already exists.
5813 			 */
5814 			CONN_DEC_REF(econnp);
5815 			freemsg(mp);
5816 		} else {
5817 			SQUEUE_ENTER_ONE(econnp->conn_sqp, mp,
5818 			    tcp_input, econnp, SQ_FILL, SQTAG_TCP_CONN_REQ_1);
5819 		}
5820 	} else {
5821 		/* Nobody wants this packet */
5822 		freemsg(mp);
5823 	}
5824 	return;
5825 error3:
5826 	CONN_DEC_REF(econnp);
5827 error2:
5828 	freemsg(mp);
5829 }
5830 
5831 /*
5832  * In an ideal case of vertical partition in NUMA architecture, its
5833  * beneficial to have the listener and all the incoming connections
5834  * tied to the same squeue. The other constraint is that incoming
5835  * connections should be tied to the squeue attached to interrupted
5836  * CPU for obvious locality reason so this leaves the listener to
5837  * be tied to the same squeue. Our only problem is that when listener
5838  * is binding, the CPU that will get interrupted by the NIC whose
5839  * IP address the listener is binding to is not even known. So
5840  * the code below allows us to change that binding at the time the
5841  * CPU is interrupted by virtue of incoming connection's squeue.
5842  *
5843  * This is usefull only in case of a listener bound to a specific IP
5844  * address. For other kind of listeners, they get bound the
5845  * very first time and there is no attempt to rebind them.
5846  */
5847 void
5848 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
5849 {
5850 	conn_t		*connp = (conn_t *)arg;
5851 	squeue_t	*sqp = (squeue_t *)arg2;
5852 	squeue_t	*new_sqp;
5853 	uint32_t	conn_flags;
5854 
5855 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5856 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5857 	} else {
5858 		goto done;
5859 	}
5860 
5861 	if (connp->conn_fanout == NULL)
5862 		goto done;
5863 
5864 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
5865 		mutex_enter(&connp->conn_fanout->connf_lock);
5866 		mutex_enter(&connp->conn_lock);
5867 		/*
5868 		 * No one from read or write side can access us now
5869 		 * except for already queued packets on this squeue.
5870 		 * But since we haven't changed the squeue yet, they
5871 		 * can't execute. If they are processed after we have
5872 		 * changed the squeue, they are sent back to the
5873 		 * correct squeue down below.
5874 		 * But a listner close can race with processing of
5875 		 * incoming SYN. If incoming SYN processing changes
5876 		 * the squeue then the listener close which is waiting
5877 		 * to enter the squeue would operate on the wrong
5878 		 * squeue. Hence we don't change the squeue here unless
5879 		 * the refcount is exactly the minimum refcount. The
5880 		 * minimum refcount of 4 is counted as - 1 each for
5881 		 * TCP and IP, 1 for being in the classifier hash, and
5882 		 * 1 for the mblk being processed.
5883 		 */
5884 
5885 		if (connp->conn_ref != 4 ||
5886 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
5887 			mutex_exit(&connp->conn_lock);
5888 			mutex_exit(&connp->conn_fanout->connf_lock);
5889 			goto done;
5890 		}
5891 		if (connp->conn_sqp != new_sqp) {
5892 			while (connp->conn_sqp != new_sqp)
5893 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
5894 		}
5895 
5896 		do {
5897 			conn_flags = connp->conn_flags;
5898 			conn_flags |= IPCL_FULLY_BOUND;
5899 			(void) cas32(&connp->conn_flags, connp->conn_flags,
5900 			    conn_flags);
5901 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
5902 
5903 		mutex_exit(&connp->conn_fanout->connf_lock);
5904 		mutex_exit(&connp->conn_lock);
5905 	}
5906 
5907 done:
5908 	if (connp->conn_sqp != sqp) {
5909 		CONN_INC_REF(connp);
5910 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
5911 		    SQ_FILL, SQTAG_TCP_CONN_REQ_UNBOUND);
5912 	} else {
5913 		tcp_conn_request(connp, mp, sqp);
5914 	}
5915 }
5916 
5917 /*
5918  * Successful connect request processing begins when our client passes
5919  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
5920  * our T_OK_ACK reply message upstream.  The control flow looks like this:
5921  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_tpi_connect() -> IP
5922  *   upstream <- tcp_rput()		<- IP
5923  * After various error checks are completed, tcp_tpi_connect() lays
5924  * the target address and port into the composite header template,
5925  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
5926  * request followed by an IRE request, and passes the three mblk message
5927  * down to IP looking like this:
5928  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
5929  * Processing continues in tcp_rput() when we receive the following message:
5930  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
5931  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
5932  * to fire off the connection request, and then passes the T_OK_ACK mblk
5933  * upstream that we filled in below.  There are, of course, numerous
5934  * error conditions along the way which truncate the processing described
5935  * above.
5936  */
5937 static void
5938 tcp_tpi_connect(tcp_t *tcp, mblk_t *mp)
5939 {
5940 	sin_t		*sin;
5941 	queue_t		*q = tcp->tcp_wq;
5942 	struct T_conn_req	*tcr;
5943 	struct sockaddr	*sa;
5944 	socklen_t	len;
5945 	int		error;
5946 	cred_t		*cr;
5947 	pid_t		cpid;
5948 
5949 	/*
5950 	 * All Solaris components should pass a db_credp
5951 	 * for this TPI message, hence we ASSERT.
5952 	 * But in case there is some other M_PROTO that looks
5953 	 * like a TPI message sent by some other kernel
5954 	 * component, we check and return an error.
5955 	 */
5956 	cr = msg_getcred(mp, &cpid);
5957 	ASSERT(cr != NULL);
5958 	if (cr == NULL) {
5959 		tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
5960 		return;
5961 	}
5962 
5963 	tcr = (struct T_conn_req *)mp->b_rptr;
5964 
5965 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
5966 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
5967 		tcp_err_ack(tcp, mp, TPROTO, 0);
5968 		return;
5969 	}
5970 
5971 	/*
5972 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5973 	 * will always have that to send up.  Otherwise, we need to do
5974 	 * special handling in case the allocation fails at that time.
5975 	 * If the end point is TPI, the tcp_t can be reused and the
5976 	 * tcp_ordrel_mp may be allocated already.
5977 	 */
5978 	if (tcp->tcp_ordrel_mp == NULL) {
5979 		if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
5980 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
5981 			return;
5982 		}
5983 	}
5984 
5985 	/*
5986 	 * Determine packet type based on type of address passed in
5987 	 * the request should contain an IPv4 or IPv6 address.
5988 	 * Make sure that address family matches the type of
5989 	 * family of the the address passed down
5990 	 */
5991 	switch (tcr->DEST_length) {
5992 	default:
5993 		tcp_err_ack(tcp, mp, TBADADDR, 0);
5994 		return;
5995 
5996 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
5997 		/*
5998 		 * XXX: The check for valid DEST_length was not there
5999 		 * in earlier releases and some buggy
6000 		 * TLI apps (e.g Sybase) got away with not feeding
6001 		 * in sin_zero part of address.
6002 		 * We allow that bug to keep those buggy apps humming.
6003 		 * Test suites require the check on DEST_length.
6004 		 * We construct a new mblk with valid DEST_length
6005 		 * free the original so the rest of the code does
6006 		 * not have to keep track of this special shorter
6007 		 * length address case.
6008 		 */
6009 		mblk_t *nmp;
6010 		struct T_conn_req *ntcr;
6011 		sin_t *nsin;
6012 
6013 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6014 		    tcr->OPT_length, BPRI_HI);
6015 		if (nmp == NULL) {
6016 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6017 			return;
6018 		}
6019 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6020 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6021 		ntcr->PRIM_type = T_CONN_REQ;
6022 		ntcr->DEST_length = sizeof (sin_t);
6023 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6024 
6025 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6026 		*nsin = sin_null;
6027 		/* Get pointer to shorter address to copy from original mp */
6028 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6029 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6030 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6031 			freemsg(nmp);
6032 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6033 			return;
6034 		}
6035 		nsin->sin_family = sin->sin_family;
6036 		nsin->sin_port = sin->sin_port;
6037 		nsin->sin_addr = sin->sin_addr;
6038 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6039 		nmp->b_wptr = (uchar_t *)&nsin[1];
6040 		if (tcr->OPT_length != 0) {
6041 			ntcr->OPT_length = tcr->OPT_length;
6042 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6043 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6044 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6045 			    tcr->OPT_length);
6046 			nmp->b_wptr += tcr->OPT_length;
6047 		}
6048 		freemsg(mp);	/* original mp freed */
6049 		mp = nmp;	/* re-initialize original variables */
6050 		tcr = ntcr;
6051 	}
6052 	/* FALLTHRU */
6053 
6054 	case sizeof (sin_t):
6055 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6056 		    sizeof (sin_t));
6057 		len = sizeof (sin_t);
6058 		break;
6059 
6060 	case sizeof (sin6_t):
6061 		sa = (struct sockaddr *)mi_offset_param(mp, tcr->DEST_offset,
6062 		    sizeof (sin6_t));
6063 		len = sizeof (sin6_t);
6064 		break;
6065 	}
6066 
6067 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
6068 	if (error != 0) {
6069 		tcp_err_ack(tcp, mp, TSYSERR, error);
6070 		return;
6071 	}
6072 
6073 	/*
6074 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6075 	 * should key on their sequence number and cut them loose.
6076 	 */
6077 
6078 	/*
6079 	 * If options passed in, feed it for verification and handling
6080 	 */
6081 	if (tcr->OPT_length != 0) {
6082 		mblk_t	*ok_mp;
6083 		mblk_t	*discon_mp;
6084 		mblk_t  *conn_opts_mp;
6085 		int t_error, sys_error, do_disconnect;
6086 
6087 		conn_opts_mp = NULL;
6088 
6089 		if (tcp_conprim_opt_process(tcp, mp,
6090 		    &do_disconnect, &t_error, &sys_error) < 0) {
6091 			if (do_disconnect) {
6092 				ASSERT(t_error == 0 && sys_error == 0);
6093 				discon_mp = mi_tpi_discon_ind(NULL,
6094 				    ECONNREFUSED, 0);
6095 				if (!discon_mp) {
6096 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6097 					    TSYSERR, ENOMEM);
6098 					return;
6099 				}
6100 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6101 				if (!ok_mp) {
6102 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6103 					    TSYSERR, ENOMEM);
6104 					return;
6105 				}
6106 				qreply(q, ok_mp);
6107 				qreply(q, discon_mp); /* no flush! */
6108 			} else {
6109 				ASSERT(t_error != 0);
6110 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6111 				    sys_error);
6112 			}
6113 			return;
6114 		}
6115 		/*
6116 		 * Success in setting options, the mp option buffer represented
6117 		 * by OPT_length/offset has been potentially modified and
6118 		 * contains results of option processing. We copy it in
6119 		 * another mp to save it for potentially influencing returning
6120 		 * it in T_CONN_CONN.
6121 		 */
6122 		if (tcr->OPT_length != 0) { /* there are resulting options */
6123 			conn_opts_mp = copyb(mp);
6124 			if (!conn_opts_mp) {
6125 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6126 				    TSYSERR, ENOMEM);
6127 				return;
6128 			}
6129 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6130 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6131 			/*
6132 			 * Note:
6133 			 * These resulting option negotiation can include any
6134 			 * end-to-end negotiation options but there no such
6135 			 * thing (yet?) in our TCP/IP.
6136 			 */
6137 		}
6138 	}
6139 
6140 	/* call the non-TPI version */
6141 	error = tcp_do_connect(tcp->tcp_connp, sa, len, cr, cpid);
6142 	if (error < 0) {
6143 		mp = mi_tpi_err_ack_alloc(mp, -error, 0);
6144 	} else if (error > 0) {
6145 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
6146 	} else {
6147 		mp = mi_tpi_ok_ack_alloc(mp);
6148 	}
6149 
6150 	/*
6151 	 * Note: Code below is the "failure" case
6152 	 */
6153 	/* return error ack and blow away saved option results if any */
6154 connect_failed:
6155 	if (mp != NULL)
6156 		putnext(tcp->tcp_rq, mp);
6157 	else {
6158 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6159 		    TSYSERR, ENOMEM);
6160 	}
6161 }
6162 
6163 /*
6164  * Handle connect to IPv4 destinations, including connections for AF_INET6
6165  * sockets connecting to IPv4 mapped IPv6 destinations.
6166  */
6167 static int
6168 tcp_connect_ipv4(tcp_t *tcp, ipaddr_t *dstaddrp, in_port_t dstport,
6169     uint_t srcid, cred_t *cr, pid_t pid)
6170 {
6171 	tcph_t	*tcph;
6172 	mblk_t	*mp;
6173 	ipaddr_t dstaddr = *dstaddrp;
6174 	int32_t	oldstate;
6175 	uint16_t lport;
6176 	int	error = 0;
6177 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6178 
6179 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6180 
6181 	/* Check for attempt to connect to INADDR_ANY */
6182 	if (dstaddr == INADDR_ANY)  {
6183 		/*
6184 		 * SunOS 4.x and 4.3 BSD allow an application
6185 		 * to connect a TCP socket to INADDR_ANY.
6186 		 * When they do this, the kernel picks the
6187 		 * address of one interface and uses it
6188 		 * instead.  The kernel usually ends up
6189 		 * picking the address of the loopback
6190 		 * interface.  This is an undocumented feature.
6191 		 * However, we provide the same thing here
6192 		 * in order to have source and binary
6193 		 * compatibility with SunOS 4.x.
6194 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6195 		 * generate the T_CONN_CON.
6196 		 */
6197 		dstaddr = htonl(INADDR_LOOPBACK);
6198 		*dstaddrp = dstaddr;
6199 	}
6200 
6201 	/* Handle __sin6_src_id if socket not bound to an IP address */
6202 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6203 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6204 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6205 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6206 		    tcp->tcp_ipha->ipha_src);
6207 	}
6208 
6209 	/*
6210 	 * Don't let an endpoint connect to itself.  Note that
6211 	 * the test here does not catch the case where the
6212 	 * source IP addr was left unspecified by the user. In
6213 	 * this case, the source addr is set in tcp_adapt_ire()
6214 	 * using the reply to the T_BIND message that we send
6215 	 * down to IP here and the check is repeated in tcp_rput_other.
6216 	 */
6217 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6218 	    dstport == tcp->tcp_lport) {
6219 		error = -TBADADDR;
6220 		goto failed;
6221 	}
6222 
6223 	tcp->tcp_ipha->ipha_dst = dstaddr;
6224 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6225 
6226 	/*
6227 	 * Massage a source route if any putting the first hop
6228 	 * in iph_dst. Compute a starting value for the checksum which
6229 	 * takes into account that the original iph_dst should be
6230 	 * included in the checksum but that ip will include the
6231 	 * first hop in the source route in the tcp checksum.
6232 	 */
6233 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6234 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6235 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6236 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6237 	if ((int)tcp->tcp_sum < 0)
6238 		tcp->tcp_sum--;
6239 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6240 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6241 	    (tcp->tcp_sum >> 16));
6242 	tcph = tcp->tcp_tcph;
6243 	*(uint16_t *)tcph->th_fport = dstport;
6244 	tcp->tcp_fport = dstport;
6245 
6246 	oldstate = tcp->tcp_state;
6247 	/*
6248 	 * At this point the remote destination address and remote port fields
6249 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6250 	 * have to see which state tcp was in so we can take apropriate action.
6251 	 */
6252 	if (oldstate == TCPS_IDLE) {
6253 		/*
6254 		 * We support a quick connect capability here, allowing
6255 		 * clients to transition directly from IDLE to SYN_SENT
6256 		 * tcp_bindi will pick an unused port, insert the connection
6257 		 * in the bind hash and transition to BOUND state.
6258 		 */
6259 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6260 		    tcp, B_TRUE);
6261 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6262 		    B_FALSE, B_FALSE);
6263 		if (lport == 0) {
6264 			error = -TNOADDR;
6265 			goto failed;
6266 		}
6267 	}
6268 	tcp->tcp_state = TCPS_SYN_SENT;
6269 
6270 	mp = allocb(sizeof (ire_t), BPRI_HI);
6271 	if (mp == NULL) {
6272 		tcp->tcp_state = oldstate;
6273 		error = ENOMEM;
6274 		goto failed;
6275 	}
6276 
6277 	mp->b_wptr += sizeof (ire_t);
6278 	mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6279 	tcp->tcp_hard_binding = 1;
6280 
6281 	/*
6282 	 * We need to make sure that the conn_recv is set to a non-null
6283 	 * value before we insert the conn_t into the classifier table.
6284 	 * This is to avoid a race with an incoming packet which does
6285 	 * an ipcl_classify().
6286 	 */
6287 	tcp->tcp_connp->conn_recv = tcp_input;
6288 
6289 	if (tcp->tcp_family == AF_INET) {
6290 		error = ip_proto_bind_connected_v4(tcp->tcp_connp, &mp,
6291 		    IPPROTO_TCP, &tcp->tcp_ipha->ipha_src, tcp->tcp_lport,
6292 		    tcp->tcp_remote, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6293 	} else {
6294 		in6_addr_t v6src;
6295 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6296 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6297 		} else {
6298 			v6src = tcp->tcp_ip6h->ip6_src;
6299 		}
6300 		error = ip_proto_bind_connected_v6(tcp->tcp_connp, &mp,
6301 		    IPPROTO_TCP, &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6302 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6303 	}
6304 	BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6305 	tcp->tcp_active_open = 1;
6306 
6307 
6308 	return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6309 failed:
6310 	/* return error ack and blow away saved option results if any */
6311 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6312 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6313 	return (error);
6314 }
6315 
6316 /*
6317  * Handle connect to IPv6 destinations.
6318  */
6319 static int
6320 tcp_connect_ipv6(tcp_t *tcp, in6_addr_t *dstaddrp, in_port_t dstport,
6321     uint32_t flowinfo, uint_t srcid, uint32_t scope_id, cred_t *cr, pid_t pid)
6322 {
6323 	tcph_t	*tcph;
6324 	mblk_t	*mp;
6325 	ip6_rthdr_t *rth;
6326 	int32_t  oldstate;
6327 	uint16_t lport;
6328 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6329 	int	error = 0;
6330 	conn_t	*connp = tcp->tcp_connp;
6331 
6332 	ASSERT(tcp->tcp_family == AF_INET6);
6333 
6334 	/*
6335 	 * If we're here, it means that the destination address is a native
6336 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6337 	 * reason why it might not be IPv6 is if the socket was bound to an
6338 	 * IPv4-mapped IPv6 address.
6339 	 */
6340 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6341 		return (-TBADADDR);
6342 	}
6343 
6344 	/*
6345 	 * Interpret a zero destination to mean loopback.
6346 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6347 	 * generate the T_CONN_CON.
6348 	 */
6349 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6350 		*dstaddrp = ipv6_loopback;
6351 	}
6352 
6353 	/* Handle __sin6_src_id if socket not bound to an IP address */
6354 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6355 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6356 		    connp->conn_zoneid, tcps->tcps_netstack);
6357 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6358 	}
6359 
6360 	/*
6361 	 * Take care of the scope_id now and add ip6i_t
6362 	 * if ip6i_t is not already allocated through TCP
6363 	 * sticky options. At this point tcp_ip6h does not
6364 	 * have dst info, thus use dstaddrp.
6365 	 */
6366 	if (scope_id != 0 &&
6367 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6368 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6369 		ip6i_t  *ip6i;
6370 
6371 		ipp->ipp_ifindex = scope_id;
6372 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6373 
6374 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6375 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6376 			/* Already allocated */
6377 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6378 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6379 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6380 		} else {
6381 			int reterr;
6382 
6383 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6384 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6385 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6386 			reterr = tcp_build_hdrs(tcp);
6387 			if (reterr != 0)
6388 				goto failed;
6389 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6390 		}
6391 	}
6392 
6393 	/*
6394 	 * Don't let an endpoint connect to itself.  Note that
6395 	 * the test here does not catch the case where the
6396 	 * source IP addr was left unspecified by the user. In
6397 	 * this case, the source addr is set in tcp_adapt_ire()
6398 	 * using the reply to the T_BIND message that we send
6399 	 * down to IP here and the check is repeated in tcp_rput_other.
6400 	 */
6401 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6402 	    (dstport == tcp->tcp_lport)) {
6403 		error = -TBADADDR;
6404 		goto failed;
6405 	}
6406 
6407 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6408 	tcp->tcp_remote_v6 = *dstaddrp;
6409 	tcp->tcp_ip6h->ip6_vcf =
6410 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6411 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6412 
6413 	/*
6414 	 * Massage a routing header (if present) putting the first hop
6415 	 * in ip6_dst. Compute a starting value for the checksum which
6416 	 * takes into account that the original ip6_dst should be
6417 	 * included in the checksum but that ip will include the
6418 	 * first hop in the source route in the tcp checksum.
6419 	 */
6420 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6421 	if (rth != NULL) {
6422 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6423 		    tcps->tcps_netstack);
6424 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6425 		    (tcp->tcp_sum >> 16));
6426 	} else {
6427 		tcp->tcp_sum = 0;
6428 	}
6429 
6430 	tcph = tcp->tcp_tcph;
6431 	*(uint16_t *)tcph->th_fport = dstport;
6432 	tcp->tcp_fport = dstport;
6433 
6434 	oldstate = tcp->tcp_state;
6435 	/*
6436 	 * At this point the remote destination address and remote port fields
6437 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6438 	 * have to see which state tcp was in so we can take apropriate action.
6439 	 */
6440 	if (oldstate == TCPS_IDLE) {
6441 		/*
6442 		 * We support a quick connect capability here, allowing
6443 		 * clients to transition directly from IDLE to SYN_SENT
6444 		 * tcp_bindi will pick an unused port, insert the connection
6445 		 * in the bind hash and transition to BOUND state.
6446 		 */
6447 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6448 		    tcp, B_TRUE);
6449 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6450 		    B_FALSE, B_FALSE);
6451 		if (lport == 0) {
6452 			error = -TNOADDR;
6453 			goto failed;
6454 		}
6455 	}
6456 	tcp->tcp_state = TCPS_SYN_SENT;
6457 
6458 	mp = allocb(sizeof (ire_t), BPRI_HI);
6459 	if (mp != NULL) {
6460 		in6_addr_t v6src;
6461 
6462 		mp->b_wptr += sizeof (ire_t);
6463 		mp->b_datap->db_type = IRE_DB_REQ_TYPE;
6464 
6465 		tcp->tcp_hard_binding = 1;
6466 
6467 		/*
6468 		 * We need to make sure that the conn_recv is set to a non-null
6469 		 * value before we insert the conn_t into the classifier table.
6470 		 * This is to avoid a race with an incoming packet which does
6471 		 * an ipcl_classify().
6472 		 */
6473 		tcp->tcp_connp->conn_recv = tcp_input;
6474 
6475 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6476 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6src);
6477 		} else {
6478 			v6src = tcp->tcp_ip6h->ip6_src;
6479 		}
6480 		error = ip_proto_bind_connected_v6(connp, &mp, IPPROTO_TCP,
6481 		    &v6src, tcp->tcp_lport, &tcp->tcp_remote_v6,
6482 		    &tcp->tcp_sticky_ipp, tcp->tcp_fport, B_TRUE, B_TRUE, cr);
6483 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6484 		tcp->tcp_active_open = 1;
6485 
6486 		return (tcp_post_ip_bind(tcp, mp, error, cr, pid));
6487 	}
6488 	/* Error case */
6489 	tcp->tcp_state = oldstate;
6490 	error = ENOMEM;
6491 
6492 failed:
6493 	/* return error ack and blow away saved option results if any */
6494 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6495 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6496 	return (error);
6497 }
6498 
6499 /*
6500  * We need a stream q for detached closing tcp connections
6501  * to use.  Our client hereby indicates that this q is the
6502  * one to use.
6503  */
6504 static void
6505 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6506 {
6507 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6508 	queue_t	*q = tcp->tcp_wq;
6509 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6510 
6511 #ifdef NS_DEBUG
6512 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6513 	    tcps->tcps_netstack->netstack_stackid);
6514 #endif
6515 	mp->b_datap->db_type = M_IOCACK;
6516 	iocp->ioc_count = 0;
6517 	mutex_enter(&tcps->tcps_g_q_lock);
6518 	if (tcps->tcps_g_q != NULL) {
6519 		mutex_exit(&tcps->tcps_g_q_lock);
6520 		iocp->ioc_error = EALREADY;
6521 	} else {
6522 		int error = 0;
6523 		conn_t *connp = tcp->tcp_connp;
6524 		ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
6525 
6526 		tcps->tcps_g_q = tcp->tcp_rq;
6527 		mutex_exit(&tcps->tcps_g_q_lock);
6528 		iocp->ioc_error = 0;
6529 		iocp->ioc_rval = 0;
6530 		/*
6531 		 * We are passing tcp_sticky_ipp as NULL
6532 		 * as it is not useful for tcp_default queue
6533 		 *
6534 		 * Set conn_recv just in case.
6535 		 */
6536 		tcp->tcp_connp->conn_recv = tcp_conn_request;
6537 
6538 		ASSERT(connp->conn_af_isv6);
6539 		connp->conn_ulp = IPPROTO_TCP;
6540 
6541 		if (ipst->ips_ipcl_proto_fanout_v6[IPPROTO_TCP].connf_head !=
6542 		    NULL || connp->conn_mac_exempt) {
6543 			error = -TBADADDR;
6544 		} else {
6545 			connp->conn_srcv6 = ipv6_all_zeros;
6546 			ipcl_proto_insert_v6(connp, IPPROTO_TCP);
6547 		}
6548 
6549 		(void) tcp_post_ip_bind(tcp, NULL, error, NULL, 0);
6550 	}
6551 	qreply(q, mp);
6552 }
6553 
6554 static int
6555 tcp_disconnect_common(tcp_t *tcp, t_scalar_t seqnum)
6556 {
6557 	tcp_t	*ltcp = NULL;
6558 	conn_t	*connp;
6559 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6560 
6561 	/*
6562 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6563 	 * when the stream is in BOUND state. Do not send a reset,
6564 	 * since the destination IP address is not valid, and it can
6565 	 * be the initialized value of all zeros (broadcast address).
6566 	 *
6567 	 * XXX There won't be any pending bind request to IP.
6568 	 */
6569 	if (tcp->tcp_state <= TCPS_BOUND) {
6570 		if (tcp->tcp_debug) {
6571 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6572 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6573 		}
6574 		return (TOUTSTATE);
6575 	}
6576 
6577 
6578 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6579 
6580 		/*
6581 		 * According to TPI, for non-listeners, ignore seqnum
6582 		 * and disconnect.
6583 		 * Following interpretation of -1 seqnum is historical
6584 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6585 		 * a valid seqnum should not be -1).
6586 		 *
6587 		 *	-1 means disconnect everything
6588 		 *	regardless even on a listener.
6589 		 */
6590 
6591 		int old_state = tcp->tcp_state;
6592 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6593 
6594 		/*
6595 		 * The connection can't be on the tcp_time_wait_head list
6596 		 * since it is not detached.
6597 		 */
6598 		ASSERT(tcp->tcp_time_wait_next == NULL);
6599 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6600 		ASSERT(tcp->tcp_time_wait_expire == 0);
6601 		ltcp = NULL;
6602 		/*
6603 		 * If it used to be a listener, check to make sure no one else
6604 		 * has taken the port before switching back to LISTEN state.
6605 		 */
6606 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6607 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6608 			    tcp->tcp_ipha->ipha_src,
6609 			    tcp->tcp_connp->conn_zoneid, ipst);
6610 			if (connp != NULL)
6611 				ltcp = connp->conn_tcp;
6612 		} else {
6613 			/* Allow tcp_bound_if listeners? */
6614 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6615 			    &tcp->tcp_ip6h->ip6_src, 0,
6616 			    tcp->tcp_connp->conn_zoneid, ipst);
6617 			if (connp != NULL)
6618 				ltcp = connp->conn_tcp;
6619 		}
6620 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6621 			tcp->tcp_state = TCPS_LISTEN;
6622 		} else if (old_state > TCPS_BOUND) {
6623 			tcp->tcp_conn_req_max = 0;
6624 			tcp->tcp_state = TCPS_BOUND;
6625 		}
6626 		if (ltcp != NULL)
6627 			CONN_DEC_REF(ltcp->tcp_connp);
6628 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6629 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6630 		} else if (old_state == TCPS_ESTABLISHED ||
6631 		    old_state == TCPS_CLOSE_WAIT) {
6632 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6633 		}
6634 
6635 		if (tcp->tcp_fused)
6636 			tcp_unfuse(tcp);
6637 
6638 		mutex_enter(&tcp->tcp_eager_lock);
6639 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6640 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6641 			tcp_eager_cleanup(tcp, 0);
6642 		}
6643 		mutex_exit(&tcp->tcp_eager_lock);
6644 
6645 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6646 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6647 
6648 		tcp_reinit(tcp);
6649 
6650 		return (0);
6651 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
6652 		return (TBADSEQ);
6653 	}
6654 	return (0);
6655 }
6656 
6657 /*
6658  * Our client hereby directs us to reject the connection request
6659  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6660  * of sending the appropriate RST, not an ICMP error.
6661  */
6662 static void
6663 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6664 {
6665 	t_scalar_t seqnum;
6666 	int	error;
6667 
6668 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6669 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6670 		tcp_err_ack(tcp, mp, TPROTO, 0);
6671 		return;
6672 	}
6673 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6674 	error = tcp_disconnect_common(tcp, seqnum);
6675 	if (error != 0)
6676 		tcp_err_ack(tcp, mp, error, 0);
6677 	else {
6678 		if (tcp->tcp_state >= TCPS_ESTABLISHED) {
6679 			/* Send M_FLUSH according to TPI */
6680 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6681 		}
6682 		mp = mi_tpi_ok_ack_alloc(mp);
6683 		if (mp)
6684 			putnext(tcp->tcp_rq, mp);
6685 	}
6686 }
6687 
6688 /*
6689  * Diagnostic routine used to return a string associated with the tcp state.
6690  * Note that if the caller does not supply a buffer, it will use an internal
6691  * static string.  This means that if multiple threads call this function at
6692  * the same time, output can be corrupted...  Note also that this function
6693  * does not check the size of the supplied buffer.  The caller has to make
6694  * sure that it is big enough.
6695  */
6696 static char *
6697 tcp_display(tcp_t *tcp, char *sup_buf, char format)
6698 {
6699 	char		buf1[30];
6700 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
6701 	char		*buf;
6702 	char		*cp;
6703 	in6_addr_t	local, remote;
6704 	char		local_addrbuf[INET6_ADDRSTRLEN];
6705 	char		remote_addrbuf[INET6_ADDRSTRLEN];
6706 
6707 	if (sup_buf != NULL)
6708 		buf = sup_buf;
6709 	else
6710 		buf = priv_buf;
6711 
6712 	if (tcp == NULL)
6713 		return ("NULL_TCP");
6714 	switch (tcp->tcp_state) {
6715 	case TCPS_CLOSED:
6716 		cp = "TCP_CLOSED";
6717 		break;
6718 	case TCPS_IDLE:
6719 		cp = "TCP_IDLE";
6720 		break;
6721 	case TCPS_BOUND:
6722 		cp = "TCP_BOUND";
6723 		break;
6724 	case TCPS_LISTEN:
6725 		cp = "TCP_LISTEN";
6726 		break;
6727 	case TCPS_SYN_SENT:
6728 		cp = "TCP_SYN_SENT";
6729 		break;
6730 	case TCPS_SYN_RCVD:
6731 		cp = "TCP_SYN_RCVD";
6732 		break;
6733 	case TCPS_ESTABLISHED:
6734 		cp = "TCP_ESTABLISHED";
6735 		break;
6736 	case TCPS_CLOSE_WAIT:
6737 		cp = "TCP_CLOSE_WAIT";
6738 		break;
6739 	case TCPS_FIN_WAIT_1:
6740 		cp = "TCP_FIN_WAIT_1";
6741 		break;
6742 	case TCPS_CLOSING:
6743 		cp = "TCP_CLOSING";
6744 		break;
6745 	case TCPS_LAST_ACK:
6746 		cp = "TCP_LAST_ACK";
6747 		break;
6748 	case TCPS_FIN_WAIT_2:
6749 		cp = "TCP_FIN_WAIT_2";
6750 		break;
6751 	case TCPS_TIME_WAIT:
6752 		cp = "TCP_TIME_WAIT";
6753 		break;
6754 	default:
6755 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
6756 		cp = buf1;
6757 		break;
6758 	}
6759 	switch (format) {
6760 	case DISP_ADDR_AND_PORT:
6761 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6762 			/*
6763 			 * Note that we use the remote address in the tcp_b
6764 			 * structure.  This means that it will print out
6765 			 * the real destination address, not the next hop's
6766 			 * address if source routing is used.
6767 			 */
6768 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
6769 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
6770 
6771 		} else {
6772 			local = tcp->tcp_ip_src_v6;
6773 			remote = tcp->tcp_remote_v6;
6774 		}
6775 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
6776 		    sizeof (local_addrbuf));
6777 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
6778 		    sizeof (remote_addrbuf));
6779 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
6780 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
6781 		    ntohs(tcp->tcp_fport), cp);
6782 		break;
6783 	case DISP_PORT_ONLY:
6784 	default:
6785 		(void) mi_sprintf(buf, "[%u, %u] %s",
6786 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
6787 		break;
6788 	}
6789 
6790 	return (buf);
6791 }
6792 
6793 /*
6794  * Called via squeue to get on to eager's perimeter. It sends a
6795  * TH_RST if eager is in the fanout table. The listener wants the
6796  * eager to disappear either by means of tcp_eager_blowoff() or
6797  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
6798  * called (via squeue) if the eager cannot be inserted in the
6799  * fanout table in tcp_conn_request().
6800  */
6801 /* ARGSUSED */
6802 void
6803 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
6804 {
6805 	conn_t	*econnp = (conn_t *)arg;
6806 	tcp_t	*eager = econnp->conn_tcp;
6807 	tcp_t	*listener = eager->tcp_listener;
6808 	tcp_stack_t	*tcps = eager->tcp_tcps;
6809 
6810 	/*
6811 	 * We could be called because listener is closing. Since
6812 	 * the eager is using listener's queue's, its not safe.
6813 	 * Better use the default queue just to send the TH_RST
6814 	 * out.
6815 	 */
6816 	ASSERT(tcps->tcps_g_q != NULL);
6817 	eager->tcp_rq = tcps->tcps_g_q;
6818 	eager->tcp_wq = WR(tcps->tcps_g_q);
6819 
6820 	/*
6821 	 * An eager's conn_fanout will be NULL if it's a duplicate
6822 	 * for an existing 4-tuples in the conn fanout table.
6823 	 * We don't want to send an RST out in such case.
6824 	 */
6825 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
6826 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
6827 		    eager, eager->tcp_snxt, 0, TH_RST);
6828 	}
6829 
6830 	/* We are here because listener wants this eager gone */
6831 	if (listener != NULL) {
6832 		mutex_enter(&listener->tcp_eager_lock);
6833 		tcp_eager_unlink(eager);
6834 		if (eager->tcp_tconnind_started) {
6835 			/*
6836 			 * The eager has sent a conn_ind up to the
6837 			 * listener but listener decides to close
6838 			 * instead. We need to drop the extra ref
6839 			 * placed on eager in tcp_rput_data() before
6840 			 * sending the conn_ind to listener.
6841 			 */
6842 			CONN_DEC_REF(econnp);
6843 		}
6844 		mutex_exit(&listener->tcp_eager_lock);
6845 		CONN_DEC_REF(listener->tcp_connp);
6846 	}
6847 
6848 	if (eager->tcp_state > TCPS_BOUND)
6849 		tcp_close_detached(eager);
6850 }
6851 
6852 /*
6853  * Reset any eager connection hanging off this listener marked
6854  * with 'seqnum' and then reclaim it's resources.
6855  */
6856 static boolean_t
6857 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
6858 {
6859 	tcp_t	*eager;
6860 	mblk_t 	*mp;
6861 	tcp_stack_t	*tcps = listener->tcp_tcps;
6862 
6863 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
6864 	eager = listener;
6865 	mutex_enter(&listener->tcp_eager_lock);
6866 	do {
6867 		eager = eager->tcp_eager_next_q;
6868 		if (eager == NULL) {
6869 			mutex_exit(&listener->tcp_eager_lock);
6870 			return (B_FALSE);
6871 		}
6872 	} while (eager->tcp_conn_req_seqnum != seqnum);
6873 
6874 	if (eager->tcp_closemp_used) {
6875 		mutex_exit(&listener->tcp_eager_lock);
6876 		return (B_TRUE);
6877 	}
6878 	eager->tcp_closemp_used = B_TRUE;
6879 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6880 	CONN_INC_REF(eager->tcp_connp);
6881 	mutex_exit(&listener->tcp_eager_lock);
6882 	mp = &eager->tcp_closemp;
6883 	SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
6884 	    eager->tcp_connp, SQ_FILL, SQTAG_TCP_EAGER_BLOWOFF);
6885 	return (B_TRUE);
6886 }
6887 
6888 /*
6889  * Reset any eager connection hanging off this listener
6890  * and then reclaim it's resources.
6891  */
6892 static void
6893 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
6894 {
6895 	tcp_t	*eager;
6896 	mblk_t	*mp;
6897 	tcp_stack_t	*tcps = listener->tcp_tcps;
6898 
6899 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6900 
6901 	if (!q0_only) {
6902 		/* First cleanup q */
6903 		TCP_STAT(tcps, tcp_eager_blowoff_q);
6904 		eager = listener->tcp_eager_next_q;
6905 		while (eager != NULL) {
6906 			if (!eager->tcp_closemp_used) {
6907 				eager->tcp_closemp_used = B_TRUE;
6908 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6909 				CONN_INC_REF(eager->tcp_connp);
6910 				mp = &eager->tcp_closemp;
6911 				SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6912 				    tcp_eager_kill, eager->tcp_connp,
6913 				    SQ_FILL, SQTAG_TCP_EAGER_CLEANUP);
6914 			}
6915 			eager = eager->tcp_eager_next_q;
6916 		}
6917 	}
6918 	/* Then cleanup q0 */
6919 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
6920 	eager = listener->tcp_eager_next_q0;
6921 	while (eager != listener) {
6922 		if (!eager->tcp_closemp_used) {
6923 			eager->tcp_closemp_used = B_TRUE;
6924 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6925 			CONN_INC_REF(eager->tcp_connp);
6926 			mp = &eager->tcp_closemp;
6927 			SQUEUE_ENTER_ONE(eager->tcp_connp->conn_sqp, mp,
6928 			    tcp_eager_kill, eager->tcp_connp, SQ_FILL,
6929 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
6930 		}
6931 		eager = eager->tcp_eager_next_q0;
6932 	}
6933 }
6934 
6935 /*
6936  * If we are an eager connection hanging off a listener that hasn't
6937  * formally accepted the connection yet, get off his list and blow off
6938  * any data that we have accumulated.
6939  */
6940 static void
6941 tcp_eager_unlink(tcp_t *tcp)
6942 {
6943 	tcp_t	*listener = tcp->tcp_listener;
6944 
6945 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
6946 	ASSERT(listener != NULL);
6947 	if (tcp->tcp_eager_next_q0 != NULL) {
6948 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
6949 
6950 		/* Remove the eager tcp from q0 */
6951 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
6952 		    tcp->tcp_eager_prev_q0;
6953 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
6954 		    tcp->tcp_eager_next_q0;
6955 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
6956 		listener->tcp_conn_req_cnt_q0--;
6957 
6958 		tcp->tcp_eager_next_q0 = NULL;
6959 		tcp->tcp_eager_prev_q0 = NULL;
6960 
6961 		/*
6962 		 * Take the eager out, if it is in the list of droppable
6963 		 * eagers.
6964 		 */
6965 		MAKE_UNDROPPABLE(tcp);
6966 
6967 		if (tcp->tcp_syn_rcvd_timeout != 0) {
6968 			/* we have timed out before */
6969 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
6970 			listener->tcp_syn_rcvd_timeout--;
6971 		}
6972 	} else {
6973 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
6974 		tcp_t	*prev = NULL;
6975 
6976 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
6977 			if (tcpp[0] == tcp) {
6978 				if (listener->tcp_eager_last_q == tcp) {
6979 					/*
6980 					 * If we are unlinking the last
6981 					 * element on the list, adjust
6982 					 * tail pointer. Set tail pointer
6983 					 * to nil when list is empty.
6984 					 */
6985 					ASSERT(tcp->tcp_eager_next_q == NULL);
6986 					if (listener->tcp_eager_last_q ==
6987 					    listener->tcp_eager_next_q) {
6988 						listener->tcp_eager_last_q =
6989 						    NULL;
6990 					} else {
6991 						/*
6992 						 * We won't get here if there
6993 						 * is only one eager in the
6994 						 * list.
6995 						 */
6996 						ASSERT(prev != NULL);
6997 						listener->tcp_eager_last_q =
6998 						    prev;
6999 					}
7000 				}
7001 				tcpp[0] = tcp->tcp_eager_next_q;
7002 				tcp->tcp_eager_next_q = NULL;
7003 				tcp->tcp_eager_last_q = NULL;
7004 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7005 				listener->tcp_conn_req_cnt_q--;
7006 				break;
7007 			}
7008 			prev = tcpp[0];
7009 		}
7010 	}
7011 	tcp->tcp_listener = NULL;
7012 }
7013 
7014 /* Shorthand to generate and send TPI error acks to our client */
7015 static void
7016 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7017 {
7018 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7019 		putnext(tcp->tcp_rq, mp);
7020 }
7021 
7022 /* Shorthand to generate and send TPI error acks to our client */
7023 static void
7024 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7025     int t_error, int sys_error)
7026 {
7027 	struct T_error_ack	*teackp;
7028 
7029 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7030 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7031 		teackp = (struct T_error_ack *)mp->b_rptr;
7032 		teackp->ERROR_prim = primitive;
7033 		teackp->TLI_error = t_error;
7034 		teackp->UNIX_error = sys_error;
7035 		putnext(tcp->tcp_rq, mp);
7036 	}
7037 }
7038 
7039 /*
7040  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7041  * but instead the code relies on:
7042  * - the fact that the address of the array and its size never changes
7043  * - the atomic assignment of the elements of the array
7044  */
7045 /* ARGSUSED */
7046 static int
7047 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7048 {
7049 	int i;
7050 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7051 
7052 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7053 		if (tcps->tcps_g_epriv_ports[i] != 0)
7054 			(void) mi_mpprintf(mp, "%d ",
7055 			    tcps->tcps_g_epriv_ports[i]);
7056 	}
7057 	return (0);
7058 }
7059 
7060 /*
7061  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7062  * threads from changing it at the same time.
7063  */
7064 /* ARGSUSED */
7065 static int
7066 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7067     cred_t *cr)
7068 {
7069 	long	new_value;
7070 	int	i;
7071 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7072 
7073 	/*
7074 	 * Fail the request if the new value does not lie within the
7075 	 * port number limits.
7076 	 */
7077 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7078 	    new_value <= 0 || new_value >= 65536) {
7079 		return (EINVAL);
7080 	}
7081 
7082 	mutex_enter(&tcps->tcps_epriv_port_lock);
7083 	/* Check if the value is already in the list */
7084 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7085 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7086 			mutex_exit(&tcps->tcps_epriv_port_lock);
7087 			return (EEXIST);
7088 		}
7089 	}
7090 	/* Find an empty slot */
7091 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7092 		if (tcps->tcps_g_epriv_ports[i] == 0)
7093 			break;
7094 	}
7095 	if (i == tcps->tcps_g_num_epriv_ports) {
7096 		mutex_exit(&tcps->tcps_epriv_port_lock);
7097 		return (EOVERFLOW);
7098 	}
7099 	/* Set the new value */
7100 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7101 	mutex_exit(&tcps->tcps_epriv_port_lock);
7102 	return (0);
7103 }
7104 
7105 /*
7106  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7107  * threads from changing it at the same time.
7108  */
7109 /* ARGSUSED */
7110 static int
7111 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7112     cred_t *cr)
7113 {
7114 	long	new_value;
7115 	int	i;
7116 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7117 
7118 	/*
7119 	 * Fail the request if the new value does not lie within the
7120 	 * port number limits.
7121 	 */
7122 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7123 	    new_value >= 65536) {
7124 		return (EINVAL);
7125 	}
7126 
7127 	mutex_enter(&tcps->tcps_epriv_port_lock);
7128 	/* Check that the value is already in the list */
7129 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7130 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7131 			break;
7132 	}
7133 	if (i == tcps->tcps_g_num_epriv_ports) {
7134 		mutex_exit(&tcps->tcps_epriv_port_lock);
7135 		return (ESRCH);
7136 	}
7137 	/* Clear the value */
7138 	tcps->tcps_g_epriv_ports[i] = 0;
7139 	mutex_exit(&tcps->tcps_epriv_port_lock);
7140 	return (0);
7141 }
7142 
7143 /* Return the TPI/TLI equivalent of our current tcp_state */
7144 static int
7145 tcp_tpistate(tcp_t *tcp)
7146 {
7147 	switch (tcp->tcp_state) {
7148 	case TCPS_IDLE:
7149 		return (TS_UNBND);
7150 	case TCPS_LISTEN:
7151 		/*
7152 		 * Return whether there are outstanding T_CONN_IND waiting
7153 		 * for the matching T_CONN_RES. Therefore don't count q0.
7154 		 */
7155 		if (tcp->tcp_conn_req_cnt_q > 0)
7156 			return (TS_WRES_CIND);
7157 		else
7158 			return (TS_IDLE);
7159 	case TCPS_BOUND:
7160 		return (TS_IDLE);
7161 	case TCPS_SYN_SENT:
7162 		return (TS_WCON_CREQ);
7163 	case TCPS_SYN_RCVD:
7164 		/*
7165 		 * Note: assumption: this has to the active open SYN_RCVD.
7166 		 * The passive instance is detached in SYN_RCVD stage of
7167 		 * incoming connection processing so we cannot get request
7168 		 * for T_info_ack on it.
7169 		 */
7170 		return (TS_WACK_CRES);
7171 	case TCPS_ESTABLISHED:
7172 		return (TS_DATA_XFER);
7173 	case TCPS_CLOSE_WAIT:
7174 		return (TS_WREQ_ORDREL);
7175 	case TCPS_FIN_WAIT_1:
7176 		return (TS_WIND_ORDREL);
7177 	case TCPS_FIN_WAIT_2:
7178 		return (TS_WIND_ORDREL);
7179 
7180 	case TCPS_CLOSING:
7181 	case TCPS_LAST_ACK:
7182 	case TCPS_TIME_WAIT:
7183 	case TCPS_CLOSED:
7184 		/*
7185 		 * Following TS_WACK_DREQ7 is a rendition of "not
7186 		 * yet TS_IDLE" TPI state. There is no best match to any
7187 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7188 		 * choose a value chosen that will map to TLI/XTI level
7189 		 * state of TSTATECHNG (state is process of changing) which
7190 		 * captures what this dummy state represents.
7191 		 */
7192 		return (TS_WACK_DREQ7);
7193 	default:
7194 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7195 		    tcp->tcp_state, tcp_display(tcp, NULL,
7196 		    DISP_PORT_ONLY));
7197 		return (TS_UNBND);
7198 	}
7199 }
7200 
7201 static void
7202 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7203 {
7204 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7205 
7206 	if (tcp->tcp_family == AF_INET6)
7207 		*tia = tcp_g_t_info_ack_v6;
7208 	else
7209 		*tia = tcp_g_t_info_ack;
7210 	tia->CURRENT_state = tcp_tpistate(tcp);
7211 	tia->OPT_size = tcp_max_optsize;
7212 	if (tcp->tcp_mss == 0) {
7213 		/* Not yet set - tcp_open does not set mss */
7214 		if (tcp->tcp_ipversion == IPV4_VERSION)
7215 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7216 		else
7217 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7218 	} else {
7219 		tia->TIDU_size = tcp->tcp_mss;
7220 	}
7221 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7222 }
7223 
7224 static void
7225 tcp_do_capability_ack(tcp_t *tcp, struct T_capability_ack *tcap,
7226     t_uscalar_t cap_bits1)
7227 {
7228 	tcap->CAP_bits1 = 0;
7229 
7230 	if (cap_bits1 & TC1_INFO) {
7231 		tcp_copy_info(&tcap->INFO_ack, tcp);
7232 		tcap->CAP_bits1 |= TC1_INFO;
7233 	}
7234 
7235 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7236 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7237 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7238 	}
7239 
7240 }
7241 
7242 /*
7243  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7244  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7245  * tcp_g_t_info_ack.  The current state of the stream is copied from
7246  * tcp_state.
7247  */
7248 static void
7249 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7250 {
7251 	t_uscalar_t		cap_bits1;
7252 	struct T_capability_ack	*tcap;
7253 
7254 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7255 		freemsg(mp);
7256 		return;
7257 	}
7258 
7259 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7260 
7261 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7262 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7263 	if (mp == NULL)
7264 		return;
7265 
7266 	tcap = (struct T_capability_ack *)mp->b_rptr;
7267 	tcp_do_capability_ack(tcp, tcap, cap_bits1);
7268 
7269 	putnext(tcp->tcp_rq, mp);
7270 }
7271 
7272 /*
7273  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7274  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7275  * The current state of the stream is copied from tcp_state.
7276  */
7277 static void
7278 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7279 {
7280 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7281 	    T_INFO_ACK);
7282 	if (!mp) {
7283 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7284 		return;
7285 	}
7286 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7287 	putnext(tcp->tcp_rq, mp);
7288 }
7289 
7290 /* Respond to the TPI addr request */
7291 static void
7292 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7293 {
7294 	sin_t	*sin;
7295 	mblk_t	*ackmp;
7296 	struct T_addr_ack *taa;
7297 
7298 	/* Make it large enough for worst case */
7299 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7300 	    2 * sizeof (sin6_t), 1);
7301 	if (ackmp == NULL) {
7302 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7303 		return;
7304 	}
7305 
7306 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7307 		tcp_addr_req_ipv6(tcp, ackmp);
7308 		return;
7309 	}
7310 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7311 
7312 	bzero(taa, sizeof (struct T_addr_ack));
7313 	ackmp->b_wptr = (uchar_t *)&taa[1];
7314 
7315 	taa->PRIM_type = T_ADDR_ACK;
7316 	ackmp->b_datap->db_type = M_PCPROTO;
7317 
7318 	/*
7319 	 * Note: Following code assumes 32 bit alignment of basic
7320 	 * data structures like sin_t and struct T_addr_ack.
7321 	 */
7322 	if (tcp->tcp_state >= TCPS_BOUND) {
7323 		/*
7324 		 * Fill in local address
7325 		 */
7326 		taa->LOCADDR_length = sizeof (sin_t);
7327 		taa->LOCADDR_offset = sizeof (*taa);
7328 
7329 		sin = (sin_t *)&taa[1];
7330 
7331 		/* Fill zeroes and then intialize non-zero fields */
7332 		*sin = sin_null;
7333 
7334 		sin->sin_family = AF_INET;
7335 
7336 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7337 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7338 
7339 		ackmp->b_wptr = (uchar_t *)&sin[1];
7340 
7341 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7342 			/*
7343 			 * Fill in Remote address
7344 			 */
7345 			taa->REMADDR_length = sizeof (sin_t);
7346 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7347 			    taa->LOCADDR_length);
7348 
7349 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7350 			*sin = sin_null;
7351 			sin->sin_family = AF_INET;
7352 			sin->sin_addr.s_addr = tcp->tcp_remote;
7353 			sin->sin_port = tcp->tcp_fport;
7354 
7355 			ackmp->b_wptr = (uchar_t *)&sin[1];
7356 		}
7357 	}
7358 	putnext(tcp->tcp_rq, ackmp);
7359 }
7360 
7361 /* Assumes that tcp_addr_req gets enough space and alignment */
7362 static void
7363 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7364 {
7365 	sin6_t	*sin6;
7366 	struct T_addr_ack *taa;
7367 
7368 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7369 	ASSERT(OK_32PTR(ackmp->b_rptr));
7370 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7371 	    2 * sizeof (sin6_t));
7372 
7373 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7374 
7375 	bzero(taa, sizeof (struct T_addr_ack));
7376 	ackmp->b_wptr = (uchar_t *)&taa[1];
7377 
7378 	taa->PRIM_type = T_ADDR_ACK;
7379 	ackmp->b_datap->db_type = M_PCPROTO;
7380 
7381 	/*
7382 	 * Note: Following code assumes 32 bit alignment of basic
7383 	 * data structures like sin6_t and struct T_addr_ack.
7384 	 */
7385 	if (tcp->tcp_state >= TCPS_BOUND) {
7386 		/*
7387 		 * Fill in local address
7388 		 */
7389 		taa->LOCADDR_length = sizeof (sin6_t);
7390 		taa->LOCADDR_offset = sizeof (*taa);
7391 
7392 		sin6 = (sin6_t *)&taa[1];
7393 		*sin6 = sin6_null;
7394 
7395 		sin6->sin6_family = AF_INET6;
7396 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7397 		sin6->sin6_port = tcp->tcp_lport;
7398 
7399 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7400 
7401 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7402 			/*
7403 			 * Fill in Remote address
7404 			 */
7405 			taa->REMADDR_length = sizeof (sin6_t);
7406 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7407 			    taa->LOCADDR_length);
7408 
7409 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7410 			*sin6 = sin6_null;
7411 			sin6->sin6_family = AF_INET6;
7412 			sin6->sin6_flowinfo =
7413 			    tcp->tcp_ip6h->ip6_vcf &
7414 			    ~IPV6_VERS_AND_FLOW_MASK;
7415 			sin6->sin6_addr = tcp->tcp_remote_v6;
7416 			sin6->sin6_port = tcp->tcp_fport;
7417 
7418 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7419 		}
7420 	}
7421 	putnext(tcp->tcp_rq, ackmp);
7422 }
7423 
7424 /*
7425  * Handle reinitialization of a tcp structure.
7426  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7427  */
7428 static void
7429 tcp_reinit(tcp_t *tcp)
7430 {
7431 	mblk_t	*mp;
7432 	int 	err;
7433 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7434 
7435 	TCP_STAT(tcps, tcp_reinit_calls);
7436 
7437 	/* tcp_reinit should never be called for detached tcp_t's */
7438 	ASSERT(tcp->tcp_listener == NULL);
7439 	ASSERT((tcp->tcp_family == AF_INET &&
7440 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7441 	    (tcp->tcp_family == AF_INET6 &&
7442 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7443 	    tcp->tcp_ipversion == IPV6_VERSION)));
7444 
7445 	/* Cancel outstanding timers */
7446 	tcp_timers_stop(tcp);
7447 
7448 	/*
7449 	 * Reset everything in the state vector, after updating global
7450 	 * MIB data from instance counters.
7451 	 */
7452 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7453 	tcp->tcp_ibsegs = 0;
7454 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7455 	tcp->tcp_obsegs = 0;
7456 
7457 	tcp_close_mpp(&tcp->tcp_xmit_head);
7458 	if (tcp->tcp_snd_zcopy_aware)
7459 		tcp_zcopy_notify(tcp);
7460 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7461 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7462 	mutex_enter(&tcp->tcp_non_sq_lock);
7463 	if (tcp->tcp_flow_stopped &&
7464 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7465 		tcp_clrqfull(tcp);
7466 	}
7467 	mutex_exit(&tcp->tcp_non_sq_lock);
7468 	tcp_close_mpp(&tcp->tcp_reass_head);
7469 	tcp->tcp_reass_tail = NULL;
7470 	if (tcp->tcp_rcv_list != NULL) {
7471 		/* Free b_next chain */
7472 		tcp_close_mpp(&tcp->tcp_rcv_list);
7473 		tcp->tcp_rcv_last_head = NULL;
7474 		tcp->tcp_rcv_last_tail = NULL;
7475 		tcp->tcp_rcv_cnt = 0;
7476 	}
7477 	tcp->tcp_rcv_last_tail = NULL;
7478 
7479 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7480 		freemsg(mp);
7481 		tcp->tcp_urp_mp = NULL;
7482 	}
7483 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7484 		freemsg(mp);
7485 		tcp->tcp_urp_mark_mp = NULL;
7486 	}
7487 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7488 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7489 		freeb(tcp->tcp_fused_sigurg_mp);
7490 		tcp->tcp_fused_sigurg_mp = NULL;
7491 	}
7492 	if (tcp->tcp_ordrel_mp != NULL) {
7493 		ASSERT(!IPCL_IS_NONSTR(tcp->tcp_connp));
7494 		freeb(tcp->tcp_ordrel_mp);
7495 		tcp->tcp_ordrel_mp = NULL;
7496 	}
7497 
7498 	/*
7499 	 * Following is a union with two members which are
7500 	 * identical types and size so the following cleanup
7501 	 * is enough.
7502 	 */
7503 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7504 
7505 	CL_INET_DISCONNECT(tcp->tcp_connp, tcp);
7506 
7507 	/*
7508 	 * The connection can't be on the tcp_time_wait_head list
7509 	 * since it is not detached.
7510 	 */
7511 	ASSERT(tcp->tcp_time_wait_next == NULL);
7512 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7513 	ASSERT(tcp->tcp_time_wait_expire == 0);
7514 
7515 	if (tcp->tcp_kssl_pending) {
7516 		tcp->tcp_kssl_pending = B_FALSE;
7517 
7518 		/* Don't reset if the initialized by bind. */
7519 		if (tcp->tcp_kssl_ent != NULL) {
7520 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7521 			    KSSL_NO_PROXY);
7522 		}
7523 	}
7524 	if (tcp->tcp_kssl_ctx != NULL) {
7525 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7526 		tcp->tcp_kssl_ctx = NULL;
7527 	}
7528 
7529 	/*
7530 	 * Reset/preserve other values
7531 	 */
7532 	tcp_reinit_values(tcp);
7533 	ipcl_hash_remove(tcp->tcp_connp);
7534 	conn_delete_ire(tcp->tcp_connp, NULL);
7535 	tcp_ipsec_cleanup(tcp);
7536 
7537 	if (tcp->tcp_conn_req_max != 0) {
7538 		/*
7539 		 * This is the case when a TLI program uses the same
7540 		 * transport end point to accept a connection.  This
7541 		 * makes the TCP both a listener and acceptor.  When
7542 		 * this connection is closed, we need to set the state
7543 		 * back to TCPS_LISTEN.  Make sure that the eager list
7544 		 * is reinitialized.
7545 		 *
7546 		 * Note that this stream is still bound to the four
7547 		 * tuples of the previous connection in IP.  If a new
7548 		 * SYN with different foreign address comes in, IP will
7549 		 * not find it and will send it to the global queue.  In
7550 		 * the global queue, TCP will do a tcp_lookup_listener()
7551 		 * to find this stream.  This works because this stream
7552 		 * is only removed from connected hash.
7553 		 *
7554 		 */
7555 		tcp->tcp_state = TCPS_LISTEN;
7556 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7557 		tcp->tcp_eager_next_drop_q0 = tcp;
7558 		tcp->tcp_eager_prev_drop_q0 = tcp;
7559 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7560 		if (tcp->tcp_family == AF_INET6) {
7561 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7562 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7563 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7564 		} else {
7565 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7566 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7567 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7568 		}
7569 	} else {
7570 		tcp->tcp_state = TCPS_BOUND;
7571 	}
7572 
7573 	/*
7574 	 * Initialize to default values
7575 	 * Can't fail since enough header template space already allocated
7576 	 * at open().
7577 	 */
7578 	err = tcp_init_values(tcp);
7579 	ASSERT(err == 0);
7580 	/* Restore state in tcp_tcph */
7581 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7582 	if (tcp->tcp_ipversion == IPV4_VERSION)
7583 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7584 	else
7585 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7586 	/*
7587 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7588 	 * since the lookup funcs can only lookup on tcp_t
7589 	 */
7590 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7591 
7592 	ASSERT(tcp->tcp_ptpbhn != NULL);
7593 	if (!IPCL_IS_NONSTR(tcp->tcp_connp))
7594 		tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7595 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
7596 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
7597 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7598 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7599 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7600 }
7601 
7602 /*
7603  * Force values to zero that need be zero.
7604  * Do not touch values asociated with the BOUND or LISTEN state
7605  * since the connection will end up in that state after the reinit.
7606  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7607  * structure!
7608  */
7609 static void
7610 tcp_reinit_values(tcp)
7611 	tcp_t *tcp;
7612 {
7613 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7614 
7615 #ifndef	lint
7616 #define	DONTCARE(x)
7617 #define	PRESERVE(x)
7618 #else
7619 #define	DONTCARE(x)	((x) = (x))
7620 #define	PRESERVE(x)	((x) = (x))
7621 #endif	/* lint */
7622 
7623 	PRESERVE(tcp->tcp_bind_hash_port);
7624 	PRESERVE(tcp->tcp_bind_hash);
7625 	PRESERVE(tcp->tcp_ptpbhn);
7626 	PRESERVE(tcp->tcp_acceptor_hash);
7627 	PRESERVE(tcp->tcp_ptpahn);
7628 
7629 	/* Should be ASSERT NULL on these with new code! */
7630 	ASSERT(tcp->tcp_time_wait_next == NULL);
7631 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7632 	ASSERT(tcp->tcp_time_wait_expire == 0);
7633 	PRESERVE(tcp->tcp_state);
7634 	PRESERVE(tcp->tcp_rq);
7635 	PRESERVE(tcp->tcp_wq);
7636 
7637 	ASSERT(tcp->tcp_xmit_head == NULL);
7638 	ASSERT(tcp->tcp_xmit_last == NULL);
7639 	ASSERT(tcp->tcp_unsent == 0);
7640 	ASSERT(tcp->tcp_xmit_tail == NULL);
7641 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7642 
7643 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7644 	tcp->tcp_suna = 0;			/* Displayed in mib */
7645 	tcp->tcp_swnd = 0;
7646 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7647 
7648 	ASSERT(tcp->tcp_ibsegs == 0);
7649 	ASSERT(tcp->tcp_obsegs == 0);
7650 
7651 	if (tcp->tcp_iphc != NULL) {
7652 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7653 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7654 	}
7655 
7656 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7657 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7658 	DONTCARE(tcp->tcp_ipha);
7659 	DONTCARE(tcp->tcp_ip6h);
7660 	DONTCARE(tcp->tcp_ip_hdr_len);
7661 	DONTCARE(tcp->tcp_tcph);
7662 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7663 	tcp->tcp_valid_bits = 0;
7664 
7665 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7666 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7667 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7668 	tcp->tcp_last_rcv_lbolt = 0;
7669 
7670 	tcp->tcp_init_cwnd = 0;
7671 
7672 	tcp->tcp_urp_last_valid = 0;
7673 	tcp->tcp_hard_binding = 0;
7674 	tcp->tcp_hard_bound = 0;
7675 	PRESERVE(tcp->tcp_cred);
7676 	PRESERVE(tcp->tcp_cpid);
7677 	PRESERVE(tcp->tcp_open_time);
7678 	PRESERVE(tcp->tcp_exclbind);
7679 
7680 	tcp->tcp_fin_acked = 0;
7681 	tcp->tcp_fin_rcvd = 0;
7682 	tcp->tcp_fin_sent = 0;
7683 	tcp->tcp_ordrel_done = 0;
7684 
7685 	tcp->tcp_debug = 0;
7686 	tcp->tcp_dontroute = 0;
7687 	tcp->tcp_broadcast = 0;
7688 
7689 	tcp->tcp_useloopback = 0;
7690 	tcp->tcp_reuseaddr = 0;
7691 	tcp->tcp_oobinline = 0;
7692 	tcp->tcp_dgram_errind = 0;
7693 
7694 	tcp->tcp_detached = 0;
7695 	tcp->tcp_bind_pending = 0;
7696 	tcp->tcp_unbind_pending = 0;
7697 
7698 	tcp->tcp_snd_ws_ok = B_FALSE;
7699 	tcp->tcp_snd_ts_ok = B_FALSE;
7700 	tcp->tcp_linger = 0;
7701 	tcp->tcp_ka_enabled = 0;
7702 	tcp->tcp_zero_win_probe = 0;
7703 
7704 	tcp->tcp_loopback = 0;
7705 	tcp->tcp_refuse = 0;
7706 	tcp->tcp_localnet = 0;
7707 	tcp->tcp_syn_defense = 0;
7708 	tcp->tcp_set_timer = 0;
7709 
7710 	tcp->tcp_active_open = 0;
7711 	tcp->tcp_rexmit = B_FALSE;
7712 	tcp->tcp_xmit_zc_clean = B_FALSE;
7713 
7714 	tcp->tcp_snd_sack_ok = B_FALSE;
7715 	PRESERVE(tcp->tcp_recvdstaddr);
7716 	tcp->tcp_hwcksum = B_FALSE;
7717 
7718 	tcp->tcp_ire_ill_check_done = B_FALSE;
7719 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
7720 
7721 	tcp->tcp_mdt = B_FALSE;
7722 	tcp->tcp_mdt_hdr_head = 0;
7723 	tcp->tcp_mdt_hdr_tail = 0;
7724 
7725 	tcp->tcp_conn_def_q0 = 0;
7726 	tcp->tcp_ip_forward_progress = B_FALSE;
7727 	tcp->tcp_anon_priv_bind = 0;
7728 	tcp->tcp_ecn_ok = B_FALSE;
7729 
7730 	tcp->tcp_cwr = B_FALSE;
7731 	tcp->tcp_ecn_echo_on = B_FALSE;
7732 
7733 	if (tcp->tcp_sack_info != NULL) {
7734 		if (tcp->tcp_notsack_list != NULL) {
7735 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
7736 		}
7737 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
7738 		tcp->tcp_sack_info = NULL;
7739 	}
7740 
7741 	tcp->tcp_rcv_ws = 0;
7742 	tcp->tcp_snd_ws = 0;
7743 	tcp->tcp_ts_recent = 0;
7744 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
7745 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
7746 	tcp->tcp_if_mtu = 0;
7747 
7748 	ASSERT(tcp->tcp_reass_head == NULL);
7749 	ASSERT(tcp->tcp_reass_tail == NULL);
7750 
7751 	tcp->tcp_cwnd_cnt = 0;
7752 
7753 	ASSERT(tcp->tcp_rcv_list == NULL);
7754 	ASSERT(tcp->tcp_rcv_last_head == NULL);
7755 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
7756 	ASSERT(tcp->tcp_rcv_cnt == 0);
7757 
7758 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
7759 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
7760 	tcp->tcp_csuna = 0;
7761 
7762 	tcp->tcp_rto = 0;			/* Displayed in MIB */
7763 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
7764 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
7765 	tcp->tcp_rtt_update = 0;
7766 
7767 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7768 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
7769 
7770 	tcp->tcp_rack = 0;			/* Displayed in mib */
7771 	tcp->tcp_rack_cnt = 0;
7772 	tcp->tcp_rack_cur_max = 0;
7773 	tcp->tcp_rack_abs_max = 0;
7774 
7775 	tcp->tcp_max_swnd = 0;
7776 
7777 	ASSERT(tcp->tcp_listener == NULL);
7778 
7779 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
7780 
7781 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
7782 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
7783 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
7784 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
7785 
7786 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
7787 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
7788 	PRESERVE(tcp->tcp_conn_req_max);
7789 	PRESERVE(tcp->tcp_conn_req_seqnum);
7790 
7791 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
7792 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
7793 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
7794 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
7795 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
7796 
7797 	tcp->tcp_lingertime = 0;
7798 
7799 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
7800 	ASSERT(tcp->tcp_urp_mp == NULL);
7801 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
7802 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
7803 
7804 	ASSERT(tcp->tcp_eager_next_q == NULL);
7805 	ASSERT(tcp->tcp_eager_last_q == NULL);
7806 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
7807 	    tcp->tcp_eager_prev_q0 == NULL) ||
7808 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
7809 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
7810 
7811 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
7812 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
7813 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
7814 
7815 	tcp->tcp_client_errno = 0;
7816 
7817 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
7818 
7819 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
7820 
7821 	PRESERVE(tcp->tcp_bound_source_v6);
7822 	tcp->tcp_last_sent_len = 0;
7823 	tcp->tcp_dupack_cnt = 0;
7824 
7825 	tcp->tcp_fport = 0;			/* Displayed in MIB */
7826 	PRESERVE(tcp->tcp_lport);
7827 
7828 	PRESERVE(tcp->tcp_acceptor_lockp);
7829 
7830 	ASSERT(tcp->tcp_ordrel_mp == NULL);
7831 	PRESERVE(tcp->tcp_acceptor_id);
7832 	DONTCARE(tcp->tcp_ipsec_overhead);
7833 
7834 	PRESERVE(tcp->tcp_family);
7835 	if (tcp->tcp_family == AF_INET6) {
7836 		tcp->tcp_ipversion = IPV6_VERSION;
7837 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
7838 	} else {
7839 		tcp->tcp_ipversion = IPV4_VERSION;
7840 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
7841 	}
7842 
7843 	tcp->tcp_bound_if = 0;
7844 	tcp->tcp_ipv6_recvancillary = 0;
7845 	tcp->tcp_recvifindex = 0;
7846 	tcp->tcp_recvhops = 0;
7847 	tcp->tcp_closed = 0;
7848 	tcp->tcp_cleandeathtag = 0;
7849 	if (tcp->tcp_hopopts != NULL) {
7850 		mi_free(tcp->tcp_hopopts);
7851 		tcp->tcp_hopopts = NULL;
7852 		tcp->tcp_hopoptslen = 0;
7853 	}
7854 	ASSERT(tcp->tcp_hopoptslen == 0);
7855 	if (tcp->tcp_dstopts != NULL) {
7856 		mi_free(tcp->tcp_dstopts);
7857 		tcp->tcp_dstopts = NULL;
7858 		tcp->tcp_dstoptslen = 0;
7859 	}
7860 	ASSERT(tcp->tcp_dstoptslen == 0);
7861 	if (tcp->tcp_rtdstopts != NULL) {
7862 		mi_free(tcp->tcp_rtdstopts);
7863 		tcp->tcp_rtdstopts = NULL;
7864 		tcp->tcp_rtdstoptslen = 0;
7865 	}
7866 	ASSERT(tcp->tcp_rtdstoptslen == 0);
7867 	if (tcp->tcp_rthdr != NULL) {
7868 		mi_free(tcp->tcp_rthdr);
7869 		tcp->tcp_rthdr = NULL;
7870 		tcp->tcp_rthdrlen = 0;
7871 	}
7872 	ASSERT(tcp->tcp_rthdrlen == 0);
7873 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
7874 
7875 	/* Reset fusion-related fields */
7876 	tcp->tcp_fused = B_FALSE;
7877 	tcp->tcp_unfusable = B_FALSE;
7878 	tcp->tcp_fused_sigurg = B_FALSE;
7879 	tcp->tcp_direct_sockfs = B_FALSE;
7880 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7881 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7882 	tcp->tcp_loopback_peer = NULL;
7883 	tcp->tcp_fuse_rcv_hiwater = 0;
7884 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7885 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7886 
7887 	tcp->tcp_lso = B_FALSE;
7888 
7889 	tcp->tcp_in_ack_unsent = 0;
7890 	tcp->tcp_cork = B_FALSE;
7891 	tcp->tcp_tconnind_started = B_FALSE;
7892 
7893 	PRESERVE(tcp->tcp_squeue_bytes);
7894 
7895 	ASSERT(tcp->tcp_kssl_ctx == NULL);
7896 	ASSERT(!tcp->tcp_kssl_pending);
7897 	PRESERVE(tcp->tcp_kssl_ent);
7898 
7899 	/* Sodirect */
7900 	tcp->tcp_sodirect = NULL;
7901 
7902 	tcp->tcp_closemp_used = B_FALSE;
7903 
7904 	PRESERVE(tcp->tcp_rsrv_mp);
7905 	PRESERVE(tcp->tcp_rsrv_mp_lock);
7906 
7907 #ifdef DEBUG
7908 	DONTCARE(tcp->tcmp_stk[0]);
7909 #endif
7910 
7911 	PRESERVE(tcp->tcp_connid);
7912 
7913 
7914 #undef	DONTCARE
7915 #undef	PRESERVE
7916 }
7917 
7918 /*
7919  * Allocate necessary resources and initialize state vector.
7920  * Guaranteed not to fail so that when an error is returned,
7921  * the caller doesn't need to do any additional cleanup.
7922  */
7923 int
7924 tcp_init(tcp_t *tcp, queue_t *q)
7925 {
7926 	int	err;
7927 
7928 	tcp->tcp_rq = q;
7929 	tcp->tcp_wq = WR(q);
7930 	tcp->tcp_state = TCPS_IDLE;
7931 	if ((err = tcp_init_values(tcp)) != 0)
7932 		tcp_timers_stop(tcp);
7933 	return (err);
7934 }
7935 
7936 static int
7937 tcp_init_values(tcp_t *tcp)
7938 {
7939 	int	err;
7940 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7941 
7942 	ASSERT((tcp->tcp_family == AF_INET &&
7943 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7944 	    (tcp->tcp_family == AF_INET6 &&
7945 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7946 	    tcp->tcp_ipversion == IPV6_VERSION)));
7947 
7948 	/*
7949 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
7950 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
7951 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
7952 	 * during first few transmissions of a connection as seen in slow
7953 	 * links.
7954 	 */
7955 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
7956 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
7957 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
7958 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
7959 	    tcps->tcps_conn_grace_period;
7960 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
7961 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
7962 	tcp->tcp_timer_backoff = 0;
7963 	tcp->tcp_ms_we_have_waited = 0;
7964 	tcp->tcp_last_recv_time = lbolt;
7965 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
7966 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
7967 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
7968 
7969 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
7970 
7971 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
7972 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
7973 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
7974 	/*
7975 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
7976 	 * passive open.
7977 	 */
7978 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
7979 
7980 	tcp->tcp_naglim = tcps->tcps_naglim_def;
7981 
7982 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
7983 
7984 	tcp->tcp_mdt_hdr_head = 0;
7985 	tcp->tcp_mdt_hdr_tail = 0;
7986 
7987 	/* Reset fusion-related fields */
7988 	tcp->tcp_fused = B_FALSE;
7989 	tcp->tcp_unfusable = B_FALSE;
7990 	tcp->tcp_fused_sigurg = B_FALSE;
7991 	tcp->tcp_direct_sockfs = B_FALSE;
7992 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
7993 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
7994 	tcp->tcp_loopback_peer = NULL;
7995 	tcp->tcp_fuse_rcv_hiwater = 0;
7996 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
7997 	tcp->tcp_fuse_rcv_unread_cnt = 0;
7998 
7999 	/* Sodirect */
8000 	tcp->tcp_sodirect = NULL;
8001 
8002 	/* Initialize the header template */
8003 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8004 		err = tcp_header_init_ipv4(tcp);
8005 	} else {
8006 		err = tcp_header_init_ipv6(tcp);
8007 	}
8008 	if (err)
8009 		return (err);
8010 
8011 	/*
8012 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8013 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8014 	 */
8015 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8016 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8017 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8018 
8019 	tcp->tcp_cork = B_FALSE;
8020 	/*
8021 	 * Init the tcp_debug option.  This value determines whether TCP
8022 	 * calls strlog() to print out debug messages.  Doing this
8023 	 * initialization here means that this value is not inherited thru
8024 	 * tcp_reinit().
8025 	 */
8026 	tcp->tcp_debug = tcps->tcps_dbg;
8027 
8028 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8029 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8030 
8031 	return (0);
8032 }
8033 
8034 /*
8035  * Initialize the IPv4 header. Loses any record of any IP options.
8036  */
8037 static int
8038 tcp_header_init_ipv4(tcp_t *tcp)
8039 {
8040 	tcph_t		*tcph;
8041 	uint32_t	sum;
8042 	conn_t		*connp;
8043 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8044 
8045 	/*
8046 	 * This is a simple initialization. If there's
8047 	 * already a template, it should never be too small,
8048 	 * so reuse it.  Otherwise, allocate space for the new one.
8049 	 */
8050 	if (tcp->tcp_iphc == NULL) {
8051 		ASSERT(tcp->tcp_iphc_len == 0);
8052 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8053 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8054 		if (tcp->tcp_iphc == NULL) {
8055 			tcp->tcp_iphc_len = 0;
8056 			return (ENOMEM);
8057 		}
8058 	}
8059 
8060 	/* options are gone; may need a new label */
8061 	connp = tcp->tcp_connp;
8062 	connp->conn_mlp_type = mlptSingle;
8063 	connp->conn_ulp_labeled = !is_system_labeled();
8064 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8065 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8066 	tcp->tcp_ip6h = NULL;
8067 	tcp->tcp_ipversion = IPV4_VERSION;
8068 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8069 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8070 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8071 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8072 	tcp->tcp_ipha->ipha_version_and_hdr_length
8073 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8074 	tcp->tcp_ipha->ipha_ident = 0;
8075 
8076 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8077 	tcp->tcp_tos = 0;
8078 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8079 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8080 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8081 
8082 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8083 	tcp->tcp_tcph = tcph;
8084 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8085 	/*
8086 	 * IP wants our header length in the checksum field to
8087 	 * allow it to perform a single pseudo-header+checksum
8088 	 * calculation on behalf of TCP.
8089 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8090 	 */
8091 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8092 	sum = (sum >> 16) + (sum & 0xFFFF);
8093 	U16_TO_ABE16(sum, tcph->th_sum);
8094 	return (0);
8095 }
8096 
8097 /*
8098  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8099  */
8100 static int
8101 tcp_header_init_ipv6(tcp_t *tcp)
8102 {
8103 	tcph_t	*tcph;
8104 	uint32_t	sum;
8105 	conn_t	*connp;
8106 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8107 
8108 	/*
8109 	 * This is a simple initialization. If there's
8110 	 * already a template, it should never be too small,
8111 	 * so reuse it. Otherwise, allocate space for the new one.
8112 	 * Ensure that there is enough space to "downgrade" the tcp_t
8113 	 * to an IPv4 tcp_t. This requires having space for a full load
8114 	 * of IPv4 options, as well as a full load of TCP options
8115 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8116 	 * than a v6 header and a TCP header with a full load of TCP options
8117 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8118 	 * We want to avoid reallocation in the "downgraded" case when
8119 	 * processing outbound IPv4 options.
8120 	 */
8121 	if (tcp->tcp_iphc == NULL) {
8122 		ASSERT(tcp->tcp_iphc_len == 0);
8123 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8124 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8125 		if (tcp->tcp_iphc == NULL) {
8126 			tcp->tcp_iphc_len = 0;
8127 			return (ENOMEM);
8128 		}
8129 	}
8130 
8131 	/* options are gone; may need a new label */
8132 	connp = tcp->tcp_connp;
8133 	connp->conn_mlp_type = mlptSingle;
8134 	connp->conn_ulp_labeled = !is_system_labeled();
8135 
8136 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8137 	tcp->tcp_ipversion = IPV6_VERSION;
8138 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8139 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8140 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8141 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8142 	tcp->tcp_ipha = NULL;
8143 
8144 	/* Initialize the header template */
8145 
8146 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8147 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8148 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8149 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8150 
8151 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8152 	tcp->tcp_tcph = tcph;
8153 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8154 	/*
8155 	 * IP wants our header length in the checksum field to
8156 	 * allow it to perform a single psuedo-header+checksum
8157 	 * calculation on behalf of TCP.
8158 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8159 	 */
8160 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8161 	sum = (sum >> 16) + (sum & 0xFFFF);
8162 	U16_TO_ABE16(sum, tcph->th_sum);
8163 	return (0);
8164 }
8165 
8166 /* At minimum we need 8 bytes in the TCP header for the lookup */
8167 #define	ICMP_MIN_TCP_HDR	8
8168 
8169 /*
8170  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8171  * passed up by IP. The message is always received on the correct tcp_t.
8172  * Assumes that IP has pulled up everything up to and including the ICMP header.
8173  */
8174 void
8175 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8176 {
8177 	icmph_t *icmph;
8178 	ipha_t	*ipha;
8179 	int	iph_hdr_length;
8180 	tcph_t	*tcph;
8181 	boolean_t ipsec_mctl = B_FALSE;
8182 	boolean_t secure;
8183 	mblk_t *first_mp = mp;
8184 	int32_t new_mss;
8185 	uint32_t ratio;
8186 	size_t mp_size = MBLKL(mp);
8187 	uint32_t seg_seq;
8188 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8189 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8190 
8191 	/* Assume IP provides aligned packets - otherwise toss */
8192 	if (!OK_32PTR(mp->b_rptr)) {
8193 		freemsg(mp);
8194 		return;
8195 	}
8196 
8197 	/*
8198 	 * Since ICMP errors are normal data marked with M_CTL when sent
8199 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8200 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8201 	 */
8202 	if ((mp_size == sizeof (ipsec_info_t)) &&
8203 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8204 		ASSERT(mp->b_cont != NULL);
8205 		mp = mp->b_cont;
8206 		/* IP should have done this */
8207 		ASSERT(OK_32PTR(mp->b_rptr));
8208 		mp_size = MBLKL(mp);
8209 		ipsec_mctl = B_TRUE;
8210 	}
8211 
8212 	/*
8213 	 * Verify that we have a complete outer IP header. If not, drop it.
8214 	 */
8215 	if (mp_size < sizeof (ipha_t)) {
8216 noticmpv4:
8217 		freemsg(first_mp);
8218 		return;
8219 	}
8220 
8221 	ipha = (ipha_t *)mp->b_rptr;
8222 	/*
8223 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8224 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8225 	 */
8226 	switch (IPH_HDR_VERSION(ipha)) {
8227 	case IPV6_VERSION:
8228 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8229 		return;
8230 	case IPV4_VERSION:
8231 		break;
8232 	default:
8233 		goto noticmpv4;
8234 	}
8235 
8236 	/* Skip past the outer IP and ICMP headers */
8237 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8238 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8239 	/*
8240 	 * If we don't have the correct outer IP header length or if the ULP
8241 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8242 	 * send it upstream.
8243 	 */
8244 	if (iph_hdr_length < sizeof (ipha_t) ||
8245 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8246 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8247 		goto noticmpv4;
8248 	}
8249 	ipha = (ipha_t *)&icmph[1];
8250 
8251 	/* Skip past the inner IP and find the ULP header */
8252 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8253 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8254 	/*
8255 	 * If we don't have the correct inner IP header length or if the ULP
8256 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8257 	 * bytes of TCP header, drop it.
8258 	 */
8259 	if (iph_hdr_length < sizeof (ipha_t) ||
8260 	    ipha->ipha_protocol != IPPROTO_TCP ||
8261 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8262 		goto noticmpv4;
8263 	}
8264 
8265 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8266 		if (ipsec_mctl) {
8267 			secure = ipsec_in_is_secure(first_mp);
8268 		} else {
8269 			secure = B_FALSE;
8270 		}
8271 		if (secure) {
8272 			/*
8273 			 * If we are willing to accept this in clear
8274 			 * we don't have to verify policy.
8275 			 */
8276 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8277 				if (!tcp_check_policy(tcp, first_mp,
8278 				    ipha, NULL, secure, ipsec_mctl)) {
8279 					/*
8280 					 * tcp_check_policy called
8281 					 * ip_drop_packet() on failure.
8282 					 */
8283 					return;
8284 				}
8285 			}
8286 		}
8287 	} else if (ipsec_mctl) {
8288 		/*
8289 		 * This is a hard_bound connection. IP has already
8290 		 * verified policy. We don't have to do it again.
8291 		 */
8292 		freeb(first_mp);
8293 		first_mp = mp;
8294 		ipsec_mctl = B_FALSE;
8295 	}
8296 
8297 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8298 	/*
8299 	 * TCP SHOULD check that the TCP sequence number contained in
8300 	 * payload of the ICMP error message is within the range
8301 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8302 	 */
8303 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8304 		/*
8305 		 * The ICMP message is bogus, just drop it.  But if this is
8306 		 * an ICMP too big message, IP has already changed
8307 		 * the ire_max_frag to the bogus value.  We need to change
8308 		 * it back.
8309 		 */
8310 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8311 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8312 			conn_t *connp = tcp->tcp_connp;
8313 			ire_t *ire;
8314 			int flag;
8315 
8316 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8317 				flag = tcp->tcp_ipha->
8318 				    ipha_fragment_offset_and_flags;
8319 			} else {
8320 				flag = 0;
8321 			}
8322 			mutex_enter(&connp->conn_lock);
8323 			if ((ire = connp->conn_ire_cache) != NULL) {
8324 				mutex_enter(&ire->ire_lock);
8325 				mutex_exit(&connp->conn_lock);
8326 				ire->ire_max_frag = tcp->tcp_if_mtu;
8327 				ire->ire_frag_flag |= flag;
8328 				mutex_exit(&ire->ire_lock);
8329 			} else {
8330 				mutex_exit(&connp->conn_lock);
8331 			}
8332 		}
8333 		goto noticmpv4;
8334 	}
8335 
8336 	switch (icmph->icmph_type) {
8337 	case ICMP_DEST_UNREACHABLE:
8338 		switch (icmph->icmph_code) {
8339 		case ICMP_FRAGMENTATION_NEEDED:
8340 			/*
8341 			 * Reduce the MSS based on the new MTU.  This will
8342 			 * eliminate any fragmentation locally.
8343 			 * N.B.  There may well be some funny side-effects on
8344 			 * the local send policy and the remote receive policy.
8345 			 * Pending further research, we provide
8346 			 * tcp_ignore_path_mtu just in case this proves
8347 			 * disastrous somewhere.
8348 			 *
8349 			 * After updating the MSS, retransmit part of the
8350 			 * dropped segment using the new mss by calling
8351 			 * tcp_wput_data().  Need to adjust all those
8352 			 * params to make sure tcp_wput_data() work properly.
8353 			 */
8354 			if (tcps->tcps_ignore_path_mtu ||
8355 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8356 				break;
8357 
8358 			/*
8359 			 * Decrease the MSS by time stamp options
8360 			 * IP options and IPSEC options. tcp_hdr_len
8361 			 * includes time stamp option and IP option
8362 			 * length.  Note that new_mss may be negative
8363 			 * if tcp_ipsec_overhead is large and the
8364 			 * icmph_du_mtu is the minimum value, which is 68.
8365 			 */
8366 			new_mss = ntohs(icmph->icmph_du_mtu) -
8367 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8368 
8369 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8370 			    new_mss);
8371 
8372 			/*
8373 			 * Only update the MSS if the new one is
8374 			 * smaller than the previous one.  This is
8375 			 * to avoid problems when getting multiple
8376 			 * ICMP errors for the same MTU.
8377 			 */
8378 			if (new_mss >= tcp->tcp_mss)
8379 				break;
8380 
8381 			/*
8382 			 * Note that we are using the template header's DF
8383 			 * bit in the fast path sending.  So we need to compare
8384 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8385 			 * And stop doing IPv4 PMTUd if new_mss is less than
8386 			 * MAX(tcps_mss_min, ip_pmtu_min).
8387 			 */
8388 			if (new_mss < tcps->tcps_mss_min ||
8389 			    new_mss < ipst->ips_ip_pmtu_min) {
8390 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8391 				    0;
8392 			}
8393 
8394 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8395 			ASSERT(ratio >= 1);
8396 			tcp_mss_set(tcp, new_mss, B_TRUE);
8397 
8398 			/*
8399 			 * Make sure we have something to
8400 			 * send.
8401 			 */
8402 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8403 			    (tcp->tcp_xmit_head != NULL)) {
8404 				/*
8405 				 * Shrink tcp_cwnd in
8406 				 * proportion to the old MSS/new MSS.
8407 				 */
8408 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8409 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8410 				    (tcp->tcp_unsent == 0)) {
8411 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8412 				} else {
8413 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8414 				}
8415 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8416 				tcp->tcp_rexmit = B_TRUE;
8417 				tcp->tcp_dupack_cnt = 0;
8418 				tcp->tcp_snd_burst = TCP_CWND_SS;
8419 				tcp_ss_rexmit(tcp);
8420 			}
8421 			break;
8422 		case ICMP_PORT_UNREACHABLE:
8423 		case ICMP_PROTOCOL_UNREACHABLE:
8424 			switch (tcp->tcp_state) {
8425 			case TCPS_SYN_SENT:
8426 			case TCPS_SYN_RCVD:
8427 				/*
8428 				 * ICMP can snipe away incipient
8429 				 * TCP connections as long as
8430 				 * seq number is same as initial
8431 				 * send seq number.
8432 				 */
8433 				if (seg_seq == tcp->tcp_iss) {
8434 					(void) tcp_clean_death(tcp,
8435 					    ECONNREFUSED, 6);
8436 				}
8437 				break;
8438 			}
8439 			break;
8440 		case ICMP_HOST_UNREACHABLE:
8441 		case ICMP_NET_UNREACHABLE:
8442 			/* Record the error in case we finally time out. */
8443 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8444 				tcp->tcp_client_errno = EHOSTUNREACH;
8445 			else
8446 				tcp->tcp_client_errno = ENETUNREACH;
8447 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8448 				if (tcp->tcp_listener != NULL &&
8449 				    tcp->tcp_listener->tcp_syn_defense) {
8450 					/*
8451 					 * Ditch the half-open connection if we
8452 					 * suspect a SYN attack is under way.
8453 					 */
8454 					tcp_ip_ire_mark_advice(tcp);
8455 					(void) tcp_clean_death(tcp,
8456 					    tcp->tcp_client_errno, 7);
8457 				}
8458 			}
8459 			break;
8460 		default:
8461 			break;
8462 		}
8463 		break;
8464 	case ICMP_SOURCE_QUENCH: {
8465 		/*
8466 		 * use a global boolean to control
8467 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8468 		 * The default is false.
8469 		 */
8470 		if (tcp_icmp_source_quench) {
8471 			/*
8472 			 * Reduce the sending rate as if we got a
8473 			 * retransmit timeout
8474 			 */
8475 			uint32_t npkt;
8476 
8477 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8478 			    tcp->tcp_mss;
8479 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8480 			tcp->tcp_cwnd = tcp->tcp_mss;
8481 			tcp->tcp_cwnd_cnt = 0;
8482 		}
8483 		break;
8484 	}
8485 	}
8486 	freemsg(first_mp);
8487 }
8488 
8489 /*
8490  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8491  * error messages passed up by IP.
8492  * Assumes that IP has pulled up all the extension headers as well
8493  * as the ICMPv6 header.
8494  */
8495 static void
8496 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8497 {
8498 	icmp6_t *icmp6;
8499 	ip6_t	*ip6h;
8500 	uint16_t	iph_hdr_length;
8501 	tcpha_t	*tcpha;
8502 	uint8_t	*nexthdrp;
8503 	uint32_t new_mss;
8504 	uint32_t ratio;
8505 	boolean_t secure;
8506 	mblk_t *first_mp = mp;
8507 	size_t mp_size;
8508 	uint32_t seg_seq;
8509 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8510 
8511 	/*
8512 	 * The caller has determined if this is an IPSEC_IN packet and
8513 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8514 	 */
8515 	if (ipsec_mctl)
8516 		mp = mp->b_cont;
8517 
8518 	mp_size = MBLKL(mp);
8519 
8520 	/*
8521 	 * Verify that we have a complete IP header. If not, send it upstream.
8522 	 */
8523 	if (mp_size < sizeof (ip6_t)) {
8524 noticmpv6:
8525 		freemsg(first_mp);
8526 		return;
8527 	}
8528 
8529 	/*
8530 	 * Verify this is an ICMPV6 packet, else send it upstream.
8531 	 */
8532 	ip6h = (ip6_t *)mp->b_rptr;
8533 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8534 		iph_hdr_length = IPV6_HDR_LEN;
8535 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8536 	    &nexthdrp) ||
8537 	    *nexthdrp != IPPROTO_ICMPV6) {
8538 		goto noticmpv6;
8539 	}
8540 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8541 	ip6h = (ip6_t *)&icmp6[1];
8542 	/*
8543 	 * Verify if we have a complete ICMP and inner IP header.
8544 	 */
8545 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8546 		goto noticmpv6;
8547 
8548 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8549 		goto noticmpv6;
8550 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8551 	/*
8552 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8553 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8554 	 * packet.
8555 	 */
8556 	if ((*nexthdrp != IPPROTO_TCP) ||
8557 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8558 		goto noticmpv6;
8559 	}
8560 
8561 	/*
8562 	 * ICMP errors come on the right queue or come on
8563 	 * listener/global queue for detached connections and
8564 	 * get switched to the right queue. If it comes on the
8565 	 * right queue, policy check has already been done by IP
8566 	 * and thus free the first_mp without verifying the policy.
8567 	 * If it has come for a non-hard bound connection, we need
8568 	 * to verify policy as IP may not have done it.
8569 	 */
8570 	if (!tcp->tcp_hard_bound) {
8571 		if (ipsec_mctl) {
8572 			secure = ipsec_in_is_secure(first_mp);
8573 		} else {
8574 			secure = B_FALSE;
8575 		}
8576 		if (secure) {
8577 			/*
8578 			 * If we are willing to accept this in clear
8579 			 * we don't have to verify policy.
8580 			 */
8581 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8582 				if (!tcp_check_policy(tcp, first_mp,
8583 				    NULL, ip6h, secure, ipsec_mctl)) {
8584 					/*
8585 					 * tcp_check_policy called
8586 					 * ip_drop_packet() on failure.
8587 					 */
8588 					return;
8589 				}
8590 			}
8591 		}
8592 	} else if (ipsec_mctl) {
8593 		/*
8594 		 * This is a hard_bound connection. IP has already
8595 		 * verified policy. We don't have to do it again.
8596 		 */
8597 		freeb(first_mp);
8598 		first_mp = mp;
8599 		ipsec_mctl = B_FALSE;
8600 	}
8601 
8602 	seg_seq = ntohl(tcpha->tha_seq);
8603 	/*
8604 	 * TCP SHOULD check that the TCP sequence number contained in
8605 	 * payload of the ICMP error message is within the range
8606 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8607 	 */
8608 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8609 		/*
8610 		 * If the ICMP message is bogus, should we kill the
8611 		 * connection, or should we just drop the bogus ICMP
8612 		 * message? It would probably make more sense to just
8613 		 * drop the message so that if this one managed to get
8614 		 * in, the real connection should not suffer.
8615 		 */
8616 		goto noticmpv6;
8617 	}
8618 
8619 	switch (icmp6->icmp6_type) {
8620 	case ICMP6_PACKET_TOO_BIG:
8621 		/*
8622 		 * Reduce the MSS based on the new MTU.  This will
8623 		 * eliminate any fragmentation locally.
8624 		 * N.B.  There may well be some funny side-effects on
8625 		 * the local send policy and the remote receive policy.
8626 		 * Pending further research, we provide
8627 		 * tcp_ignore_path_mtu just in case this proves
8628 		 * disastrous somewhere.
8629 		 *
8630 		 * After updating the MSS, retransmit part of the
8631 		 * dropped segment using the new mss by calling
8632 		 * tcp_wput_data().  Need to adjust all those
8633 		 * params to make sure tcp_wput_data() work properly.
8634 		 */
8635 		if (tcps->tcps_ignore_path_mtu)
8636 			break;
8637 
8638 		/*
8639 		 * Decrease the MSS by time stamp options
8640 		 * IP options and IPSEC options. tcp_hdr_len
8641 		 * includes time stamp option and IP option
8642 		 * length.
8643 		 */
8644 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8645 		    tcp->tcp_ipsec_overhead;
8646 
8647 		/*
8648 		 * Only update the MSS if the new one is
8649 		 * smaller than the previous one.  This is
8650 		 * to avoid problems when getting multiple
8651 		 * ICMP errors for the same MTU.
8652 		 */
8653 		if (new_mss >= tcp->tcp_mss)
8654 			break;
8655 
8656 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8657 		ASSERT(ratio >= 1);
8658 		tcp_mss_set(tcp, new_mss, B_TRUE);
8659 
8660 		/*
8661 		 * Make sure we have something to
8662 		 * send.
8663 		 */
8664 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8665 		    (tcp->tcp_xmit_head != NULL)) {
8666 			/*
8667 			 * Shrink tcp_cwnd in
8668 			 * proportion to the old MSS/new MSS.
8669 			 */
8670 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8671 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8672 			    (tcp->tcp_unsent == 0)) {
8673 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8674 			} else {
8675 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8676 			}
8677 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8678 			tcp->tcp_rexmit = B_TRUE;
8679 			tcp->tcp_dupack_cnt = 0;
8680 			tcp->tcp_snd_burst = TCP_CWND_SS;
8681 			tcp_ss_rexmit(tcp);
8682 		}
8683 		break;
8684 
8685 	case ICMP6_DST_UNREACH:
8686 		switch (icmp6->icmp6_code) {
8687 		case ICMP6_DST_UNREACH_NOPORT:
8688 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8689 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8690 			    (seg_seq == tcp->tcp_iss)) {
8691 				(void) tcp_clean_death(tcp,
8692 				    ECONNREFUSED, 8);
8693 			}
8694 			break;
8695 
8696 		case ICMP6_DST_UNREACH_ADMIN:
8697 		case ICMP6_DST_UNREACH_NOROUTE:
8698 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
8699 		case ICMP6_DST_UNREACH_ADDR:
8700 			/* Record the error in case we finally time out. */
8701 			tcp->tcp_client_errno = EHOSTUNREACH;
8702 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
8703 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
8704 			    (seg_seq == tcp->tcp_iss)) {
8705 				if (tcp->tcp_listener != NULL &&
8706 				    tcp->tcp_listener->tcp_syn_defense) {
8707 					/*
8708 					 * Ditch the half-open connection if we
8709 					 * suspect a SYN attack is under way.
8710 					 */
8711 					tcp_ip_ire_mark_advice(tcp);
8712 					(void) tcp_clean_death(tcp,
8713 					    tcp->tcp_client_errno, 9);
8714 				}
8715 			}
8716 
8717 
8718 			break;
8719 		default:
8720 			break;
8721 		}
8722 		break;
8723 
8724 	case ICMP6_PARAM_PROB:
8725 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
8726 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
8727 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
8728 		    (uchar_t *)nexthdrp) {
8729 			if (tcp->tcp_state == TCPS_SYN_SENT ||
8730 			    tcp->tcp_state == TCPS_SYN_RCVD) {
8731 				(void) tcp_clean_death(tcp,
8732 				    ECONNREFUSED, 10);
8733 			}
8734 			break;
8735 		}
8736 		break;
8737 
8738 	case ICMP6_TIME_EXCEEDED:
8739 	default:
8740 		break;
8741 	}
8742 	freemsg(first_mp);
8743 }
8744 
8745 /*
8746  * Notify IP that we are having trouble with this connection.  IP should
8747  * blow the IRE away and start over.
8748  */
8749 static void
8750 tcp_ip_notify(tcp_t *tcp)
8751 {
8752 	struct iocblk	*iocp;
8753 	ipid_t	*ipid;
8754 	mblk_t	*mp;
8755 
8756 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
8757 	if (tcp->tcp_ipversion == IPV6_VERSION)
8758 		return;
8759 
8760 	mp = mkiocb(IP_IOCTL);
8761 	if (mp == NULL)
8762 		return;
8763 
8764 	iocp = (struct iocblk *)mp->b_rptr;
8765 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
8766 
8767 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
8768 	if (!mp->b_cont) {
8769 		freeb(mp);
8770 		return;
8771 	}
8772 
8773 	ipid = (ipid_t *)mp->b_cont->b_rptr;
8774 	mp->b_cont->b_wptr += iocp->ioc_count;
8775 	bzero(ipid, sizeof (*ipid));
8776 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
8777 	ipid->ipid_ire_type = IRE_CACHE;
8778 	ipid->ipid_addr_offset = sizeof (ipid_t);
8779 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
8780 	/*
8781 	 * Note: in the case of source routing we want to blow away the
8782 	 * route to the first source route hop.
8783 	 */
8784 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
8785 	    sizeof (tcp->tcp_ipha->ipha_dst));
8786 
8787 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
8788 }
8789 
8790 /* Unlink and return any mblk that looks like it contains an ire */
8791 static mblk_t *
8792 tcp_ire_mp(mblk_t **mpp)
8793 {
8794 	mblk_t 	*mp = *mpp;
8795 	mblk_t	*prev_mp = NULL;
8796 
8797 	for (;;) {
8798 		switch (DB_TYPE(mp)) {
8799 		case IRE_DB_TYPE:
8800 		case IRE_DB_REQ_TYPE:
8801 			if (mp == *mpp) {
8802 				*mpp = mp->b_cont;
8803 			} else {
8804 				prev_mp->b_cont = mp->b_cont;
8805 			}
8806 			mp->b_cont = NULL;
8807 			return (mp);
8808 		default:
8809 			break;
8810 		}
8811 		prev_mp = mp;
8812 		mp = mp->b_cont;
8813 		if (mp == NULL)
8814 			break;
8815 	}
8816 	return (mp);
8817 }
8818 
8819 /*
8820  * Timer callback routine for keepalive probe.  We do a fake resend of
8821  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
8822  * check to see if we have heard anything from the other end for the last
8823  * RTO period.  If we have, set the timer to expire for another
8824  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
8825  * RTO << 1 and check again when it expires.  Keep exponentially increasing
8826  * the timeout if we have not heard from the other side.  If for more than
8827  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
8828  * kill the connection unless the keepalive abort threshold is 0.  In
8829  * that case, we will probe "forever."
8830  */
8831 static void
8832 tcp_keepalive_killer(void *arg)
8833 {
8834 	mblk_t	*mp;
8835 	conn_t	*connp = (conn_t *)arg;
8836 	tcp_t  	*tcp = connp->conn_tcp;
8837 	int32_t	firetime;
8838 	int32_t	idletime;
8839 	int32_t	ka_intrvl;
8840 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8841 
8842 	tcp->tcp_ka_tid = 0;
8843 
8844 	if (tcp->tcp_fused)
8845 		return;
8846 
8847 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
8848 	ka_intrvl = tcp->tcp_ka_interval;
8849 
8850 	/*
8851 	 * Keepalive probe should only be sent if the application has not
8852 	 * done a close on the connection.
8853 	 */
8854 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
8855 		return;
8856 	}
8857 	/* Timer fired too early, restart it. */
8858 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
8859 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8860 		    MSEC_TO_TICK(ka_intrvl));
8861 		return;
8862 	}
8863 
8864 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
8865 	/*
8866 	 * If we have not heard from the other side for a long
8867 	 * time, kill the connection unless the keepalive abort
8868 	 * threshold is 0.  In that case, we will probe "forever."
8869 	 */
8870 	if (tcp->tcp_ka_abort_thres != 0 &&
8871 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
8872 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
8873 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
8874 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
8875 		return;
8876 	}
8877 
8878 	if (tcp->tcp_snxt == tcp->tcp_suna &&
8879 	    idletime >= ka_intrvl) {
8880 		/* Fake resend of last ACKed byte. */
8881 		mblk_t	*mp1 = allocb(1, BPRI_LO);
8882 
8883 		if (mp1 != NULL) {
8884 			*mp1->b_wptr++ = '\0';
8885 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
8886 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
8887 			freeb(mp1);
8888 			/*
8889 			 * if allocation failed, fall through to start the
8890 			 * timer back.
8891 			 */
8892 			if (mp != NULL) {
8893 				tcp_send_data(tcp, tcp->tcp_wq, mp);
8894 				BUMP_MIB(&tcps->tcps_mib,
8895 				    tcpTimKeepaliveProbe);
8896 				if (tcp->tcp_ka_last_intrvl != 0) {
8897 					int max;
8898 					/*
8899 					 * We should probe again at least
8900 					 * in ka_intrvl, but not more than
8901 					 * tcp_rexmit_interval_max.
8902 					 */
8903 					max = tcps->tcps_rexmit_interval_max;
8904 					firetime = MIN(ka_intrvl - 1,
8905 					    tcp->tcp_ka_last_intrvl << 1);
8906 					if (firetime > max)
8907 						firetime = max;
8908 				} else {
8909 					firetime = tcp->tcp_rto;
8910 				}
8911 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
8912 				    tcp_keepalive_killer,
8913 				    MSEC_TO_TICK(firetime));
8914 				tcp->tcp_ka_last_intrvl = firetime;
8915 				return;
8916 			}
8917 		}
8918 	} else {
8919 		tcp->tcp_ka_last_intrvl = 0;
8920 	}
8921 
8922 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
8923 	if ((firetime = ka_intrvl - idletime) < 0) {
8924 		firetime = ka_intrvl;
8925 	}
8926 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
8927 	    MSEC_TO_TICK(firetime));
8928 }
8929 
8930 int
8931 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
8932 {
8933 	queue_t	*q = tcp->tcp_rq;
8934 	int32_t	mss = tcp->tcp_mss;
8935 	int	maxpsz;
8936 	conn_t	*connp = tcp->tcp_connp;
8937 
8938 	if (TCP_IS_DETACHED(tcp))
8939 		return (mss);
8940 	if (tcp->tcp_fused) {
8941 		maxpsz = tcp_fuse_maxpsz_set(tcp);
8942 		mss = INFPSZ;
8943 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
8944 		/*
8945 		 * Set the sd_qn_maxpsz according to the socket send buffer
8946 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
8947 		 * instruct the stream head to copyin user data into contiguous
8948 		 * kernel-allocated buffers without breaking it up into smaller
8949 		 * chunks.  We round up the buffer size to the nearest SMSS.
8950 		 */
8951 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
8952 		if (tcp->tcp_kssl_ctx == NULL)
8953 			mss = INFPSZ;
8954 		else
8955 			mss = SSL3_MAX_RECORD_LEN;
8956 	} else {
8957 		/*
8958 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
8959 		 * (and a multiple of the mss).  This instructs the stream
8960 		 * head to break down larger than SMSS writes into SMSS-
8961 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
8962 		 */
8963 		/* XXX tune this with ndd tcp_maxpsz_multiplier */
8964 		maxpsz = tcp->tcp_maxpsz * mss;
8965 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
8966 			maxpsz = tcp->tcp_xmit_hiwater/2;
8967 			/* Round up to nearest mss */
8968 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
8969 		}
8970 	}
8971 
8972 	(void) proto_set_maxpsz(q, connp, maxpsz);
8973 	if (!(IPCL_IS_NONSTR(connp))) {
8974 		/* XXX do it in set_maxpsz()? */
8975 		tcp->tcp_wq->q_maxpsz = maxpsz;
8976 	}
8977 
8978 	if (set_maxblk)
8979 		(void) proto_set_tx_maxblk(q, connp, mss);
8980 	return (mss);
8981 }
8982 
8983 /*
8984  * Extract option values from a tcp header.  We put any found values into the
8985  * tcpopt struct and return a bitmask saying which options were found.
8986  */
8987 static int
8988 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
8989 {
8990 	uchar_t		*endp;
8991 	int		len;
8992 	uint32_t	mss;
8993 	uchar_t		*up = (uchar_t *)tcph;
8994 	int		found = 0;
8995 	int32_t		sack_len;
8996 	tcp_seq		sack_begin, sack_end;
8997 	tcp_t		*tcp;
8998 
8999 	endp = up + TCP_HDR_LENGTH(tcph);
9000 	up += TCP_MIN_HEADER_LENGTH;
9001 	while (up < endp) {
9002 		len = endp - up;
9003 		switch (*up) {
9004 		case TCPOPT_EOL:
9005 			break;
9006 
9007 		case TCPOPT_NOP:
9008 			up++;
9009 			continue;
9010 
9011 		case TCPOPT_MAXSEG:
9012 			if (len < TCPOPT_MAXSEG_LEN ||
9013 			    up[1] != TCPOPT_MAXSEG_LEN)
9014 				break;
9015 
9016 			mss = BE16_TO_U16(up+2);
9017 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9018 			tcpopt->tcp_opt_mss = mss;
9019 			found |= TCP_OPT_MSS_PRESENT;
9020 
9021 			up += TCPOPT_MAXSEG_LEN;
9022 			continue;
9023 
9024 		case TCPOPT_WSCALE:
9025 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9026 				break;
9027 
9028 			if (up[2] > TCP_MAX_WINSHIFT)
9029 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9030 			else
9031 				tcpopt->tcp_opt_wscale = up[2];
9032 			found |= TCP_OPT_WSCALE_PRESENT;
9033 
9034 			up += TCPOPT_WS_LEN;
9035 			continue;
9036 
9037 		case TCPOPT_SACK_PERMITTED:
9038 			if (len < TCPOPT_SACK_OK_LEN ||
9039 			    up[1] != TCPOPT_SACK_OK_LEN)
9040 				break;
9041 			found |= TCP_OPT_SACK_OK_PRESENT;
9042 			up += TCPOPT_SACK_OK_LEN;
9043 			continue;
9044 
9045 		case TCPOPT_SACK:
9046 			if (len <= 2 || up[1] <= 2 || len < up[1])
9047 				break;
9048 
9049 			/* If TCP is not interested in SACK blks... */
9050 			if ((tcp = tcpopt->tcp) == NULL) {
9051 				up += up[1];
9052 				continue;
9053 			}
9054 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9055 			up += TCPOPT_HEADER_LEN;
9056 
9057 			/*
9058 			 * If the list is empty, allocate one and assume
9059 			 * nothing is sack'ed.
9060 			 */
9061 			ASSERT(tcp->tcp_sack_info != NULL);
9062 			if (tcp->tcp_notsack_list == NULL) {
9063 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9064 				    tcp->tcp_suna, tcp->tcp_snxt,
9065 				    &(tcp->tcp_num_notsack_blk),
9066 				    &(tcp->tcp_cnt_notsack_list));
9067 
9068 				/*
9069 				 * Make sure tcp_notsack_list is not NULL.
9070 				 * This happens when kmem_alloc(KM_NOSLEEP)
9071 				 * returns NULL.
9072 				 */
9073 				if (tcp->tcp_notsack_list == NULL) {
9074 					up += sack_len;
9075 					continue;
9076 				}
9077 				tcp->tcp_fack = tcp->tcp_suna;
9078 			}
9079 
9080 			while (sack_len > 0) {
9081 				if (up + 8 > endp) {
9082 					up = endp;
9083 					break;
9084 				}
9085 				sack_begin = BE32_TO_U32(up);
9086 				up += 4;
9087 				sack_end = BE32_TO_U32(up);
9088 				up += 4;
9089 				sack_len -= 8;
9090 				/*
9091 				 * Bounds checking.  Make sure the SACK
9092 				 * info is within tcp_suna and tcp_snxt.
9093 				 * If this SACK blk is out of bound, ignore
9094 				 * it but continue to parse the following
9095 				 * blks.
9096 				 */
9097 				if (SEQ_LEQ(sack_end, sack_begin) ||
9098 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9099 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9100 					continue;
9101 				}
9102 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9103 				    sack_begin, sack_end,
9104 				    &(tcp->tcp_num_notsack_blk),
9105 				    &(tcp->tcp_cnt_notsack_list));
9106 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9107 					tcp->tcp_fack = sack_end;
9108 				}
9109 			}
9110 			found |= TCP_OPT_SACK_PRESENT;
9111 			continue;
9112 
9113 		case TCPOPT_TSTAMP:
9114 			if (len < TCPOPT_TSTAMP_LEN ||
9115 			    up[1] != TCPOPT_TSTAMP_LEN)
9116 				break;
9117 
9118 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9119 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9120 
9121 			found |= TCP_OPT_TSTAMP_PRESENT;
9122 
9123 			up += TCPOPT_TSTAMP_LEN;
9124 			continue;
9125 
9126 		default:
9127 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9128 				break;
9129 			up += up[1];
9130 			continue;
9131 		}
9132 		break;
9133 	}
9134 	return (found);
9135 }
9136 
9137 /*
9138  * Set the mss associated with a particular tcp based on its current value,
9139  * and a new one passed in. Observe minimums and maximums, and reset
9140  * other state variables that we want to view as multiples of mss.
9141  *
9142  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9143  * highwater marks etc. need to be initialized or adjusted.
9144  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9145  *    packet arrives.
9146  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9147  *    ICMP6_PACKET_TOO_BIG arrives.
9148  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9149  *    to increase the MSS to use the extra bytes available.
9150  *
9151  * Callers except tcp_paws_check() ensure that they only reduce mss.
9152  */
9153 static void
9154 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9155 {
9156 	uint32_t	mss_max;
9157 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9158 
9159 	if (tcp->tcp_ipversion == IPV4_VERSION)
9160 		mss_max = tcps->tcps_mss_max_ipv4;
9161 	else
9162 		mss_max = tcps->tcps_mss_max_ipv6;
9163 
9164 	if (mss < tcps->tcps_mss_min)
9165 		mss = tcps->tcps_mss_min;
9166 	if (mss > mss_max)
9167 		mss = mss_max;
9168 	/*
9169 	 * Unless naglim has been set by our client to
9170 	 * a non-mss value, force naglim to track mss.
9171 	 * This can help to aggregate small writes.
9172 	 */
9173 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9174 		tcp->tcp_naglim = mss;
9175 	/*
9176 	 * TCP should be able to buffer at least 4 MSS data for obvious
9177 	 * performance reason.
9178 	 */
9179 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9180 		tcp->tcp_xmit_hiwater = mss << 2;
9181 
9182 	if (do_ss) {
9183 		/*
9184 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9185 		 * changing due to a reduction in MTU, presumably as a
9186 		 * result of a new path component, reset cwnd to its
9187 		 * "initial" value, as a multiple of the new mss.
9188 		 */
9189 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9190 	} else {
9191 		/*
9192 		 * Called by tcp_paws_check(), the mss increased
9193 		 * marginally to allow use of space previously taken
9194 		 * by the timestamp option. It would be inappropriate
9195 		 * to apply slow start or tcp_init_cwnd values to
9196 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9197 		 */
9198 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9199 		tcp->tcp_cwnd_cnt = 0;
9200 	}
9201 	tcp->tcp_mss = mss;
9202 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9203 }
9204 
9205 /* For /dev/tcp aka AF_INET open */
9206 static int
9207 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9208 {
9209 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9210 }
9211 
9212 /* For /dev/tcp6 aka AF_INET6 open */
9213 static int
9214 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9215 {
9216 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9217 }
9218 
9219 static conn_t *
9220 tcp_create_common(queue_t *q, cred_t *credp, boolean_t isv6,
9221     boolean_t issocket, int *errorp)
9222 {
9223 	tcp_t		*tcp = NULL;
9224 	conn_t		*connp;
9225 	int		err;
9226 	zoneid_t	zoneid;
9227 	tcp_stack_t	*tcps;
9228 	squeue_t	*sqp;
9229 
9230 	ASSERT(errorp != NULL);
9231 	/*
9232 	 * Find the proper zoneid and netstack.
9233 	 */
9234 	/*
9235 	 * Special case for install: miniroot needs to be able to
9236 	 * access files via NFS as though it were always in the
9237 	 * global zone.
9238 	 */
9239 	if (credp == kcred && nfs_global_client_only != 0) {
9240 		zoneid = GLOBAL_ZONEID;
9241 		tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9242 		    netstack_tcp;
9243 		ASSERT(tcps != NULL);
9244 	} else {
9245 		netstack_t *ns;
9246 
9247 		ns = netstack_find_by_cred(credp);
9248 		ASSERT(ns != NULL);
9249 		tcps = ns->netstack_tcp;
9250 		ASSERT(tcps != NULL);
9251 
9252 		/*
9253 		 * For exclusive stacks we set the zoneid to zero
9254 		 * to make TCP operate as if in the global zone.
9255 		 */
9256 		if (tcps->tcps_netstack->netstack_stackid !=
9257 		    GLOBAL_NETSTACKID)
9258 			zoneid = GLOBAL_ZONEID;
9259 		else
9260 			zoneid = crgetzoneid(credp);
9261 	}
9262 	/*
9263 	 * For stackid zero this is done from strplumb.c, but
9264 	 * non-zero stackids are handled here.
9265 	 */
9266 	if (tcps->tcps_g_q == NULL &&
9267 	    tcps->tcps_netstack->netstack_stackid !=
9268 	    GLOBAL_NETSTACKID) {
9269 		tcp_g_q_setup(tcps);
9270 	}
9271 
9272 	sqp = IP_SQUEUE_GET((uint_t)gethrtime());
9273 	connp = (conn_t *)tcp_get_conn(sqp, tcps);
9274 	/*
9275 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9276 	 * so we drop it by one.
9277 	 */
9278 	netstack_rele(tcps->tcps_netstack);
9279 	if (connp == NULL) {
9280 		*errorp = ENOSR;
9281 		return (NULL);
9282 	}
9283 	connp->conn_sqp = sqp;
9284 	connp->conn_initial_sqp = connp->conn_sqp;
9285 	tcp = connp->conn_tcp;
9286 
9287 	if (isv6) {
9288 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9289 		connp->conn_send = ip_output_v6;
9290 		connp->conn_af_isv6 = B_TRUE;
9291 		connp->conn_pkt_isv6 = B_TRUE;
9292 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9293 		tcp->tcp_ipversion = IPV6_VERSION;
9294 		tcp->tcp_family = AF_INET6;
9295 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9296 	} else {
9297 		connp->conn_flags |= IPCL_TCP4;
9298 		connp->conn_send = ip_output;
9299 		connp->conn_af_isv6 = B_FALSE;
9300 		connp->conn_pkt_isv6 = B_FALSE;
9301 		tcp->tcp_ipversion = IPV4_VERSION;
9302 		tcp->tcp_family = AF_INET;
9303 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9304 	}
9305 
9306 	/*
9307 	 * TCP keeps a copy of cred for cache locality reasons but
9308 	 * we put a reference only once. If connp->conn_cred
9309 	 * becomes invalid, tcp_cred should also be set to NULL.
9310 	 */
9311 	tcp->tcp_cred = connp->conn_cred = credp;
9312 	crhold(connp->conn_cred);
9313 	tcp->tcp_cpid = curproc->p_pid;
9314 	tcp->tcp_open_time = lbolt64;
9315 	connp->conn_zoneid = zoneid;
9316 	connp->conn_mlp_type = mlptSingle;
9317 	connp->conn_ulp_labeled = !is_system_labeled();
9318 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9319 	ASSERT(tcp->tcp_tcps == tcps);
9320 
9321 	/*
9322 	 * If the caller has the process-wide flag set, then default to MAC
9323 	 * exempt mode.  This allows read-down to unlabeled hosts.
9324 	 */
9325 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9326 		connp->conn_mac_exempt = B_TRUE;
9327 
9328 	connp->conn_dev = NULL;
9329 	if (issocket) {
9330 		connp->conn_flags |= IPCL_SOCKET;
9331 		tcp->tcp_issocket = 1;
9332 	}
9333 
9334 	tcp->tcp_recv_hiwater = tcps->tcps_recv_hiwat;
9335 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9336 	tcp->tcp_recv_lowater = tcp_rinfo.mi_lowat;
9337 
9338 	/* Non-zero default values */
9339 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9340 
9341 	if (q == NULL) {
9342 		/*
9343 		 * Create a helper stream for non-STREAMS socket.
9344 		 */
9345 		err = ip_create_helper_stream(connp, tcps->tcps_ldi_ident);
9346 		if (err != 0) {
9347 			ip1dbg(("tcp_create_common: create of IP helper stream "
9348 			    "failed\n"));
9349 			CONN_DEC_REF(connp);
9350 			*errorp = err;
9351 			return (NULL);
9352 		}
9353 		q = connp->conn_rq;
9354 	} else {
9355 		RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9356 	}
9357 
9358 	SOCK_CONNID_INIT(tcp->tcp_connid);
9359 	err = tcp_init(tcp, q);
9360 	if (err != 0) {
9361 		CONN_DEC_REF(connp);
9362 		*errorp = err;
9363 		return (NULL);
9364 	}
9365 
9366 	return (connp);
9367 }
9368 
9369 static int
9370 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9371     boolean_t isv6)
9372 {
9373 	tcp_t		*tcp = NULL;
9374 	conn_t		*connp = NULL;
9375 	int		err;
9376 	vmem_t		*minor_arena = NULL;
9377 	dev_t		conn_dev;
9378 	boolean_t	issocket;
9379 
9380 	if (q->q_ptr != NULL)
9381 		return (0);
9382 
9383 	if (sflag == MODOPEN)
9384 		return (EINVAL);
9385 
9386 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9387 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9388 		minor_arena = ip_minor_arena_la;
9389 	} else {
9390 		/*
9391 		 * Either minor numbers in the large arena were exhausted
9392 		 * or a non socket application is doing the open.
9393 		 * Try to allocate from the small arena.
9394 		 */
9395 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9396 			return (EBUSY);
9397 		}
9398 		minor_arena = ip_minor_arena_sa;
9399 	}
9400 
9401 	ASSERT(minor_arena != NULL);
9402 
9403 	*devp = makedevice(getmajor(*devp), (minor_t)conn_dev);
9404 
9405 	if (flag & SO_FALLBACK) {
9406 		/*
9407 		 * Non streams socket needs a stream to fallback to
9408 		 */
9409 		RD(q)->q_ptr = (void *)conn_dev;
9410 		WR(q)->q_qinfo = &tcp_fallback_sock_winit;
9411 		WR(q)->q_ptr = (void *)minor_arena;
9412 		qprocson(q);
9413 		return (0);
9414 	} else if (flag & SO_ACCEPTOR) {
9415 		q->q_qinfo = &tcp_acceptor_rinit;
9416 		/*
9417 		 * the conn_dev and minor_arena will be subsequently used by
9418 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9419 		 * minor device number for this connection from the q_ptr.
9420 		 */
9421 		RD(q)->q_ptr = (void *)conn_dev;
9422 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9423 		WR(q)->q_ptr = (void *)minor_arena;
9424 		qprocson(q);
9425 		return (0);
9426 	}
9427 
9428 	issocket = flag & SO_SOCKSTR;
9429 	connp = tcp_create_common(q, credp, isv6, issocket, &err);
9430 
9431 	if (connp == NULL) {
9432 		inet_minor_free(minor_arena, conn_dev);
9433 		q->q_ptr = WR(q)->q_ptr = NULL;
9434 		return (err);
9435 	}
9436 
9437 	q->q_ptr = WR(q)->q_ptr = connp;
9438 
9439 	connp->conn_dev = conn_dev;
9440 	connp->conn_minor_arena = minor_arena;
9441 
9442 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9443 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9444 
9445 	if (issocket) {
9446 		WR(q)->q_qinfo = &tcp_sock_winit;
9447 	} else {
9448 		tcp = connp->conn_tcp;
9449 #ifdef  _ILP32
9450 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9451 #else
9452 		tcp->tcp_acceptor_id = conn_dev;
9453 #endif  /* _ILP32 */
9454 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9455 	}
9456 
9457 	/*
9458 	 * Put the ref for TCP. Ref for IP was already put
9459 	 * by ipcl_conn_create. Also Make the conn_t globally
9460 	 * visible to walkers
9461 	 */
9462 	mutex_enter(&connp->conn_lock);
9463 	CONN_INC_REF_LOCKED(connp);
9464 	ASSERT(connp->conn_ref == 2);
9465 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9466 	mutex_exit(&connp->conn_lock);
9467 
9468 	qprocson(q);
9469 	return (0);
9470 }
9471 
9472 /*
9473  * Some TCP options can be "set" by requesting them in the option
9474  * buffer. This is needed for XTI feature test though we do not
9475  * allow it in general. We interpret that this mechanism is more
9476  * applicable to OSI protocols and need not be allowed in general.
9477  * This routine filters out options for which it is not allowed (most)
9478  * and lets through those (few) for which it is. [ The XTI interface
9479  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9480  * ever implemented will have to be allowed here ].
9481  */
9482 static boolean_t
9483 tcp_allow_connopt_set(int level, int name)
9484 {
9485 
9486 	switch (level) {
9487 	case IPPROTO_TCP:
9488 		switch (name) {
9489 		case TCP_NODELAY:
9490 			return (B_TRUE);
9491 		default:
9492 			return (B_FALSE);
9493 		}
9494 		/*NOTREACHED*/
9495 	default:
9496 		return (B_FALSE);
9497 	}
9498 	/*NOTREACHED*/
9499 }
9500 
9501 /*
9502  * this routine gets default values of certain options whose default
9503  * values are maintained by protocol specific code
9504  */
9505 /* ARGSUSED */
9506 int
9507 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9508 {
9509 	int32_t	*i1 = (int32_t *)ptr;
9510 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9511 
9512 	switch (level) {
9513 	case IPPROTO_TCP:
9514 		switch (name) {
9515 		case TCP_NOTIFY_THRESHOLD:
9516 			*i1 = tcps->tcps_ip_notify_interval;
9517 			break;
9518 		case TCP_ABORT_THRESHOLD:
9519 			*i1 = tcps->tcps_ip_abort_interval;
9520 			break;
9521 		case TCP_CONN_NOTIFY_THRESHOLD:
9522 			*i1 = tcps->tcps_ip_notify_cinterval;
9523 			break;
9524 		case TCP_CONN_ABORT_THRESHOLD:
9525 			*i1 = tcps->tcps_ip_abort_cinterval;
9526 			break;
9527 		default:
9528 			return (-1);
9529 		}
9530 		break;
9531 	case IPPROTO_IP:
9532 		switch (name) {
9533 		case IP_TTL:
9534 			*i1 = tcps->tcps_ipv4_ttl;
9535 			break;
9536 		default:
9537 			return (-1);
9538 		}
9539 		break;
9540 	case IPPROTO_IPV6:
9541 		switch (name) {
9542 		case IPV6_UNICAST_HOPS:
9543 			*i1 = tcps->tcps_ipv6_hoplimit;
9544 			break;
9545 		default:
9546 			return (-1);
9547 		}
9548 		break;
9549 	default:
9550 		return (-1);
9551 	}
9552 	return (sizeof (int));
9553 }
9554 
9555 static int
9556 tcp_opt_get(conn_t *connp, int level, int name, uchar_t *ptr)
9557 {
9558 	int		*i1 = (int *)ptr;
9559 	tcp_t		*tcp = connp->conn_tcp;
9560 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9561 
9562 	switch (level) {
9563 	case SOL_SOCKET:
9564 		switch (name) {
9565 		case SO_LINGER:	{
9566 			struct linger *lgr = (struct linger *)ptr;
9567 
9568 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9569 			lgr->l_linger = tcp->tcp_lingertime;
9570 			}
9571 			return (sizeof (struct linger));
9572 		case SO_DEBUG:
9573 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9574 			break;
9575 		case SO_KEEPALIVE:
9576 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9577 			break;
9578 		case SO_DONTROUTE:
9579 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9580 			break;
9581 		case SO_USELOOPBACK:
9582 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9583 			break;
9584 		case SO_BROADCAST:
9585 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9586 			break;
9587 		case SO_REUSEADDR:
9588 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
9589 			break;
9590 		case SO_OOBINLINE:
9591 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
9592 			break;
9593 		case SO_DGRAM_ERRIND:
9594 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
9595 			break;
9596 		case SO_TYPE:
9597 			*i1 = SOCK_STREAM;
9598 			break;
9599 		case SO_SNDBUF:
9600 			*i1 = tcp->tcp_xmit_hiwater;
9601 			break;
9602 		case SO_RCVBUF:
9603 			*i1 = tcp->tcp_recv_hiwater;
9604 			break;
9605 		case SO_SND_COPYAVOID:
9606 			*i1 = tcp->tcp_snd_zcopy_on ?
9607 			    SO_SND_COPYAVOID : 0;
9608 			break;
9609 		case SO_ALLZONES:
9610 			*i1 = connp->conn_allzones ? 1 : 0;
9611 			break;
9612 		case SO_ANON_MLP:
9613 			*i1 = connp->conn_anon_mlp;
9614 			break;
9615 		case SO_MAC_EXEMPT:
9616 			*i1 = connp->conn_mac_exempt;
9617 			break;
9618 		case SO_EXCLBIND:
9619 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
9620 			break;
9621 		case SO_PROTOTYPE:
9622 			*i1 = IPPROTO_TCP;
9623 			break;
9624 		case SO_DOMAIN:
9625 			*i1 = tcp->tcp_family;
9626 			break;
9627 		case SO_ACCEPTCONN:
9628 			*i1 = (tcp->tcp_state == TCPS_LISTEN);
9629 		default:
9630 			return (-1);
9631 		}
9632 		break;
9633 	case IPPROTO_TCP:
9634 		switch (name) {
9635 		case TCP_NODELAY:
9636 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
9637 			break;
9638 		case TCP_MAXSEG:
9639 			*i1 = tcp->tcp_mss;
9640 			break;
9641 		case TCP_NOTIFY_THRESHOLD:
9642 			*i1 = (int)tcp->tcp_first_timer_threshold;
9643 			break;
9644 		case TCP_ABORT_THRESHOLD:
9645 			*i1 = tcp->tcp_second_timer_threshold;
9646 			break;
9647 		case TCP_CONN_NOTIFY_THRESHOLD:
9648 			*i1 = tcp->tcp_first_ctimer_threshold;
9649 			break;
9650 		case TCP_CONN_ABORT_THRESHOLD:
9651 			*i1 = tcp->tcp_second_ctimer_threshold;
9652 			break;
9653 		case TCP_RECVDSTADDR:
9654 			*i1 = tcp->tcp_recvdstaddr;
9655 			break;
9656 		case TCP_ANONPRIVBIND:
9657 			*i1 = tcp->tcp_anon_priv_bind;
9658 			break;
9659 		case TCP_EXCLBIND:
9660 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
9661 			break;
9662 		case TCP_INIT_CWND:
9663 			*i1 = tcp->tcp_init_cwnd;
9664 			break;
9665 		case TCP_KEEPALIVE_THRESHOLD:
9666 			*i1 = tcp->tcp_ka_interval;
9667 			break;
9668 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
9669 			*i1 = tcp->tcp_ka_abort_thres;
9670 			break;
9671 		case TCP_CORK:
9672 			*i1 = tcp->tcp_cork;
9673 			break;
9674 		default:
9675 			return (-1);
9676 		}
9677 		break;
9678 	case IPPROTO_IP:
9679 		if (tcp->tcp_family != AF_INET)
9680 			return (-1);
9681 		switch (name) {
9682 		case IP_OPTIONS:
9683 		case T_IP_OPTIONS: {
9684 			/*
9685 			 * This is compatible with BSD in that in only return
9686 			 * the reverse source route with the final destination
9687 			 * as the last entry. The first 4 bytes of the option
9688 			 * will contain the final destination.
9689 			 */
9690 			int	opt_len;
9691 
9692 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
9693 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
9694 			ASSERT(opt_len >= 0);
9695 			/* Caller ensures enough space */
9696 			if (opt_len > 0) {
9697 				/*
9698 				 * TODO: Do we have to handle getsockopt on an
9699 				 * initiator as well?
9700 				 */
9701 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
9702 			}
9703 			return (0);
9704 			}
9705 		case IP_TOS:
9706 		case T_IP_TOS:
9707 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
9708 			break;
9709 		case IP_TTL:
9710 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
9711 			break;
9712 		case IP_NEXTHOP:
9713 			/* Handled at IP level */
9714 			return (-EINVAL);
9715 		default:
9716 			return (-1);
9717 		}
9718 		break;
9719 	case IPPROTO_IPV6:
9720 		/*
9721 		 * IPPROTO_IPV6 options are only supported for sockets
9722 		 * that are using IPv6 on the wire.
9723 		 */
9724 		if (tcp->tcp_ipversion != IPV6_VERSION) {
9725 			return (-1);
9726 		}
9727 		switch (name) {
9728 		case IPV6_UNICAST_HOPS:
9729 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
9730 			break;	/* goto sizeof (int) option return */
9731 		case IPV6_BOUND_IF:
9732 			/* Zero if not set */
9733 			*i1 = tcp->tcp_bound_if;
9734 			break;	/* goto sizeof (int) option return */
9735 		case IPV6_RECVPKTINFO:
9736 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
9737 				*i1 = 1;
9738 			else
9739 				*i1 = 0;
9740 			break;	/* goto sizeof (int) option return */
9741 		case IPV6_RECVTCLASS:
9742 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
9743 				*i1 = 1;
9744 			else
9745 				*i1 = 0;
9746 			break;	/* goto sizeof (int) option return */
9747 		case IPV6_RECVHOPLIMIT:
9748 			if (tcp->tcp_ipv6_recvancillary &
9749 			    TCP_IPV6_RECVHOPLIMIT)
9750 				*i1 = 1;
9751 			else
9752 				*i1 = 0;
9753 			break;	/* goto sizeof (int) option return */
9754 		case IPV6_RECVHOPOPTS:
9755 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
9756 				*i1 = 1;
9757 			else
9758 				*i1 = 0;
9759 			break;	/* goto sizeof (int) option return */
9760 		case IPV6_RECVDSTOPTS:
9761 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
9762 				*i1 = 1;
9763 			else
9764 				*i1 = 0;
9765 			break;	/* goto sizeof (int) option return */
9766 		case _OLD_IPV6_RECVDSTOPTS:
9767 			if (tcp->tcp_ipv6_recvancillary &
9768 			    TCP_OLD_IPV6_RECVDSTOPTS)
9769 				*i1 = 1;
9770 			else
9771 				*i1 = 0;
9772 			break;	/* goto sizeof (int) option return */
9773 		case IPV6_RECVRTHDR:
9774 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
9775 				*i1 = 1;
9776 			else
9777 				*i1 = 0;
9778 			break;	/* goto sizeof (int) option return */
9779 		case IPV6_RECVRTHDRDSTOPTS:
9780 			if (tcp->tcp_ipv6_recvancillary &
9781 			    TCP_IPV6_RECVRTDSTOPTS)
9782 				*i1 = 1;
9783 			else
9784 				*i1 = 0;
9785 			break;	/* goto sizeof (int) option return */
9786 		case IPV6_PKTINFO: {
9787 			/* XXX assumes that caller has room for max size! */
9788 			struct in6_pktinfo *pkti;
9789 
9790 			pkti = (struct in6_pktinfo *)ptr;
9791 			if (ipp->ipp_fields & IPPF_IFINDEX)
9792 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
9793 			else
9794 				pkti->ipi6_ifindex = 0;
9795 			if (ipp->ipp_fields & IPPF_ADDR)
9796 				pkti->ipi6_addr = ipp->ipp_addr;
9797 			else
9798 				pkti->ipi6_addr = ipv6_all_zeros;
9799 			return (sizeof (struct in6_pktinfo));
9800 		}
9801 		case IPV6_TCLASS:
9802 			if (ipp->ipp_fields & IPPF_TCLASS)
9803 				*i1 = ipp->ipp_tclass;
9804 			else
9805 				*i1 = IPV6_FLOW_TCLASS(
9806 				    IPV6_DEFAULT_VERS_AND_FLOW);
9807 			break;	/* goto sizeof (int) option return */
9808 		case IPV6_NEXTHOP: {
9809 			sin6_t *sin6 = (sin6_t *)ptr;
9810 
9811 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
9812 				return (0);
9813 			*sin6 = sin6_null;
9814 			sin6->sin6_family = AF_INET6;
9815 			sin6->sin6_addr = ipp->ipp_nexthop;
9816 			return (sizeof (sin6_t));
9817 		}
9818 		case IPV6_HOPOPTS:
9819 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
9820 				return (0);
9821 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
9822 				return (0);
9823 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
9824 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
9825 			if (tcp->tcp_label_len > 0) {
9826 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
9827 				ptr[1] = (ipp->ipp_hopoptslen -
9828 				    tcp->tcp_label_len + 7) / 8 - 1;
9829 			}
9830 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
9831 		case IPV6_RTHDRDSTOPTS:
9832 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
9833 				return (0);
9834 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
9835 			return (ipp->ipp_rtdstoptslen);
9836 		case IPV6_RTHDR:
9837 			if (!(ipp->ipp_fields & IPPF_RTHDR))
9838 				return (0);
9839 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
9840 			return (ipp->ipp_rthdrlen);
9841 		case IPV6_DSTOPTS:
9842 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
9843 				return (0);
9844 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
9845 			return (ipp->ipp_dstoptslen);
9846 		case IPV6_SRC_PREFERENCES:
9847 			return (ip6_get_src_preferences(connp,
9848 			    (uint32_t *)ptr));
9849 		case IPV6_PATHMTU: {
9850 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
9851 
9852 			if (tcp->tcp_state < TCPS_ESTABLISHED)
9853 				return (-1);
9854 
9855 			return (ip_fill_mtuinfo(&connp->conn_remv6,
9856 			    connp->conn_fport, mtuinfo,
9857 			    connp->conn_netstack));
9858 		}
9859 		default:
9860 			return (-1);
9861 		}
9862 		break;
9863 	default:
9864 		return (-1);
9865 	}
9866 	return (sizeof (int));
9867 }
9868 
9869 /*
9870  * TCP routine to get the values of options.
9871  */
9872 int
9873 tcp_tpi_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
9874 {
9875 	return (tcp_opt_get(Q_TO_CONN(q), level, name, ptr));
9876 }
9877 
9878 /* returns UNIX error, the optlen is a value-result arg */
9879 int
9880 tcp_getsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
9881     void *optvalp, socklen_t *optlen, cred_t *cr)
9882 {
9883 	conn_t		*connp = (conn_t *)proto_handle;
9884 	squeue_t	*sqp = connp->conn_sqp;
9885 	int		error;
9886 	t_uscalar_t	max_optbuf_len;
9887 	void		*optvalp_buf;
9888 	int		len;
9889 
9890 	ASSERT(connp->conn_upper_handle != NULL);
9891 
9892 	error = proto_opt_check(level, option_name, *optlen, &max_optbuf_len,
9893 	    tcp_opt_obj.odb_opt_des_arr,
9894 	    tcp_opt_obj.odb_opt_arr_cnt,
9895 	    tcp_opt_obj.odb_topmost_tpiprovider,
9896 	    B_FALSE, B_TRUE, cr);
9897 	if (error != 0) {
9898 		if (error < 0) {
9899 			error = proto_tlitosyserr(-error);
9900 		}
9901 		return (error);
9902 	}
9903 
9904 	optvalp_buf = kmem_alloc(max_optbuf_len, KM_SLEEP);
9905 
9906 	error = squeue_synch_enter(sqp, connp, 0);
9907 	if (error == ENOMEM) {
9908 		return (ENOMEM);
9909 	}
9910 
9911 	len = tcp_opt_get(connp, level, option_name, optvalp_buf);
9912 	squeue_synch_exit(sqp, connp);
9913 
9914 	if (len < 0) {
9915 		/*
9916 		 * Pass on to IP
9917 		 */
9918 		kmem_free(optvalp_buf, max_optbuf_len);
9919 		return (ip_get_options(connp, level, option_name,
9920 		    optvalp, optlen, cr));
9921 	} else {
9922 		/*
9923 		 * update optlen and copy option value
9924 		 */
9925 		t_uscalar_t size = MIN(len, *optlen);
9926 		bcopy(optvalp_buf, optvalp, size);
9927 		bcopy(&size, optlen, sizeof (size));
9928 
9929 		kmem_free(optvalp_buf, max_optbuf_len);
9930 		return (0);
9931 	}
9932 }
9933 
9934 /*
9935  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
9936  * Parameters are assumed to be verified by the caller.
9937  */
9938 /* ARGSUSED */
9939 int
9940 tcp_opt_set(conn_t *connp, uint_t optset_context, int level, int name,
9941     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
9942     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
9943 {
9944 	tcp_t	*tcp = connp->conn_tcp;
9945 	int	*i1 = (int *)invalp;
9946 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
9947 	boolean_t checkonly;
9948 	int	reterr;
9949 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9950 
9951 	switch (optset_context) {
9952 	case SETFN_OPTCOM_CHECKONLY:
9953 		checkonly = B_TRUE;
9954 		/*
9955 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
9956 		 * inlen != 0 implies value supplied and
9957 		 * 	we have to "pretend" to set it.
9958 		 * inlen == 0 implies that there is no
9959 		 * 	value part in T_CHECK request and just validation
9960 		 * done elsewhere should be enough, we just return here.
9961 		 */
9962 		if (inlen == 0) {
9963 			*outlenp = 0;
9964 			return (0);
9965 		}
9966 		break;
9967 	case SETFN_OPTCOM_NEGOTIATE:
9968 		checkonly = B_FALSE;
9969 		break;
9970 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
9971 	case SETFN_CONN_NEGOTIATE:
9972 		checkonly = B_FALSE;
9973 		/*
9974 		 * Negotiating local and "association-related" options
9975 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
9976 		 * primitives is allowed by XTI, but we choose
9977 		 * to not implement this style negotiation for Internet
9978 		 * protocols (We interpret it is a must for OSI world but
9979 		 * optional for Internet protocols) for all options.
9980 		 * [ Will do only for the few options that enable test
9981 		 * suites that our XTI implementation of this feature
9982 		 * works for transports that do allow it ]
9983 		 */
9984 		if (!tcp_allow_connopt_set(level, name)) {
9985 			*outlenp = 0;
9986 			return (EINVAL);
9987 		}
9988 		break;
9989 	default:
9990 		/*
9991 		 * We should never get here
9992 		 */
9993 		*outlenp = 0;
9994 		return (EINVAL);
9995 	}
9996 
9997 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
9998 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
9999 
10000 	/*
10001 	 * For TCP, we should have no ancillary data sent down
10002 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10003 	 * has to be zero.
10004 	 */
10005 	ASSERT(thisdg_attrs == NULL);
10006 
10007 	/*
10008 	 * For fixed length options, no sanity check
10009 	 * of passed in length is done. It is assumed *_optcom_req()
10010 	 * routines do the right thing.
10011 	 */
10012 	switch (level) {
10013 	case SOL_SOCKET:
10014 		switch (name) {
10015 		case SO_LINGER: {
10016 			struct linger *lgr = (struct linger *)invalp;
10017 
10018 			if (!checkonly) {
10019 				if (lgr->l_onoff) {
10020 					tcp->tcp_linger = 1;
10021 					tcp->tcp_lingertime = lgr->l_linger;
10022 				} else {
10023 					tcp->tcp_linger = 0;
10024 					tcp->tcp_lingertime = 0;
10025 				}
10026 				/* struct copy */
10027 				*(struct linger *)outvalp = *lgr;
10028 			} else {
10029 				if (!lgr->l_onoff) {
10030 					((struct linger *)
10031 					    outvalp)->l_onoff = 0;
10032 					((struct linger *)
10033 					    outvalp)->l_linger = 0;
10034 				} else {
10035 					/* struct copy */
10036 					*(struct linger *)outvalp = *lgr;
10037 				}
10038 			}
10039 			*outlenp = sizeof (struct linger);
10040 			return (0);
10041 		}
10042 		case SO_DEBUG:
10043 			if (!checkonly)
10044 				tcp->tcp_debug = onoff;
10045 			break;
10046 		case SO_KEEPALIVE:
10047 			if (checkonly) {
10048 				/* check only case */
10049 				break;
10050 			}
10051 
10052 			if (!onoff) {
10053 				if (tcp->tcp_ka_enabled) {
10054 					if (tcp->tcp_ka_tid != 0) {
10055 						(void) TCP_TIMER_CANCEL(tcp,
10056 						    tcp->tcp_ka_tid);
10057 						tcp->tcp_ka_tid = 0;
10058 					}
10059 					tcp->tcp_ka_enabled = 0;
10060 				}
10061 				break;
10062 			}
10063 			if (!tcp->tcp_ka_enabled) {
10064 				/* Crank up the keepalive timer */
10065 				tcp->tcp_ka_last_intrvl = 0;
10066 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10067 				    tcp_keepalive_killer,
10068 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10069 				tcp->tcp_ka_enabled = 1;
10070 			}
10071 			break;
10072 		case SO_DONTROUTE:
10073 			/*
10074 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10075 			 * only of interest to IP.  We track them here only so
10076 			 * that we can report their current value.
10077 			 */
10078 			if (!checkonly) {
10079 				tcp->tcp_dontroute = onoff;
10080 				tcp->tcp_connp->conn_dontroute = onoff;
10081 			}
10082 			break;
10083 		case SO_USELOOPBACK:
10084 			if (!checkonly) {
10085 				tcp->tcp_useloopback = onoff;
10086 				tcp->tcp_connp->conn_loopback = onoff;
10087 			}
10088 			break;
10089 		case SO_BROADCAST:
10090 			if (!checkonly) {
10091 				tcp->tcp_broadcast = onoff;
10092 				tcp->tcp_connp->conn_broadcast = onoff;
10093 			}
10094 			break;
10095 		case SO_REUSEADDR:
10096 			if (!checkonly) {
10097 				tcp->tcp_reuseaddr = onoff;
10098 				tcp->tcp_connp->conn_reuseaddr = onoff;
10099 			}
10100 			break;
10101 		case SO_OOBINLINE:
10102 			if (!checkonly) {
10103 				tcp->tcp_oobinline = onoff;
10104 				if (IPCL_IS_NONSTR(tcp->tcp_connp))
10105 					proto_set_rx_oob_opt(connp, onoff);
10106 			}
10107 			break;
10108 		case SO_DGRAM_ERRIND:
10109 			if (!checkonly)
10110 				tcp->tcp_dgram_errind = onoff;
10111 			break;
10112 		case SO_SNDBUF: {
10113 			if (*i1 > tcps->tcps_max_buf) {
10114 				*outlenp = 0;
10115 				return (ENOBUFS);
10116 			}
10117 			if (checkonly)
10118 				break;
10119 
10120 			tcp->tcp_xmit_hiwater = *i1;
10121 			if (tcps->tcps_snd_lowat_fraction != 0)
10122 				tcp->tcp_xmit_lowater =
10123 				    tcp->tcp_xmit_hiwater /
10124 				    tcps->tcps_snd_lowat_fraction;
10125 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10126 			/*
10127 			 * If we are flow-controlled, recheck the condition.
10128 			 * There are apps that increase SO_SNDBUF size when
10129 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10130 			 * control condition to be lifted right away.
10131 			 */
10132 			mutex_enter(&tcp->tcp_non_sq_lock);
10133 			if (tcp->tcp_flow_stopped &&
10134 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10135 				tcp_clrqfull(tcp);
10136 			}
10137 			mutex_exit(&tcp->tcp_non_sq_lock);
10138 			break;
10139 		}
10140 		case SO_RCVBUF:
10141 			if (*i1 > tcps->tcps_max_buf) {
10142 				*outlenp = 0;
10143 				return (ENOBUFS);
10144 			}
10145 			/* Silently ignore zero */
10146 			if (!checkonly && *i1 != 0) {
10147 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10148 				(void) tcp_rwnd_set(tcp, *i1);
10149 			}
10150 			/*
10151 			 * XXX should we return the rwnd here
10152 			 * and tcp_opt_get ?
10153 			 */
10154 			break;
10155 		case SO_SND_COPYAVOID:
10156 			if (!checkonly) {
10157 				/* we only allow enable at most once for now */
10158 				if (tcp->tcp_loopback ||
10159 				    (tcp->tcp_kssl_ctx != NULL) ||
10160 				    (!tcp->tcp_snd_zcopy_aware &&
10161 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10162 					*outlenp = 0;
10163 					return (EOPNOTSUPP);
10164 				}
10165 				tcp->tcp_snd_zcopy_aware = 1;
10166 			}
10167 			break;
10168 		case SO_RCVTIMEO:
10169 		case SO_SNDTIMEO:
10170 			/*
10171 			 * Pass these two options in order for third part
10172 			 * protocol usage. Here just return directly.
10173 			 */
10174 			return (0);
10175 		case SO_ALLZONES:
10176 			/* Pass option along to IP level for handling */
10177 			return (-EINVAL);
10178 		case SO_ANON_MLP:
10179 			/* Pass option along to IP level for handling */
10180 			return (-EINVAL);
10181 		case SO_MAC_EXEMPT:
10182 			/* Pass option along to IP level for handling */
10183 			return (-EINVAL);
10184 		case SO_EXCLBIND:
10185 			if (!checkonly)
10186 				tcp->tcp_exclbind = onoff;
10187 			break;
10188 		default:
10189 			*outlenp = 0;
10190 			return (EINVAL);
10191 		}
10192 		break;
10193 	case IPPROTO_TCP:
10194 		switch (name) {
10195 		case TCP_NODELAY:
10196 			if (!checkonly)
10197 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10198 			break;
10199 		case TCP_NOTIFY_THRESHOLD:
10200 			if (!checkonly)
10201 				tcp->tcp_first_timer_threshold = *i1;
10202 			break;
10203 		case TCP_ABORT_THRESHOLD:
10204 			if (!checkonly)
10205 				tcp->tcp_second_timer_threshold = *i1;
10206 			break;
10207 		case TCP_CONN_NOTIFY_THRESHOLD:
10208 			if (!checkonly)
10209 				tcp->tcp_first_ctimer_threshold = *i1;
10210 			break;
10211 		case TCP_CONN_ABORT_THRESHOLD:
10212 			if (!checkonly)
10213 				tcp->tcp_second_ctimer_threshold = *i1;
10214 			break;
10215 		case TCP_RECVDSTADDR:
10216 			if (tcp->tcp_state > TCPS_LISTEN)
10217 				return (EOPNOTSUPP);
10218 			if (!checkonly)
10219 				tcp->tcp_recvdstaddr = onoff;
10220 			break;
10221 		case TCP_ANONPRIVBIND:
10222 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10223 			    IPPROTO_TCP)) != 0) {
10224 				*outlenp = 0;
10225 				return (reterr);
10226 			}
10227 			if (!checkonly) {
10228 				tcp->tcp_anon_priv_bind = onoff;
10229 			}
10230 			break;
10231 		case TCP_EXCLBIND:
10232 			if (!checkonly)
10233 				tcp->tcp_exclbind = onoff;
10234 			break;	/* goto sizeof (int) option return */
10235 		case TCP_INIT_CWND: {
10236 			uint32_t init_cwnd = *((uint32_t *)invalp);
10237 
10238 			if (checkonly)
10239 				break;
10240 
10241 			/*
10242 			 * Only allow socket with network configuration
10243 			 * privilege to set the initial cwnd to be larger
10244 			 * than allowed by RFC 3390.
10245 			 */
10246 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10247 				tcp->tcp_init_cwnd = init_cwnd;
10248 				break;
10249 			}
10250 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10251 				*outlenp = 0;
10252 				return (reterr);
10253 			}
10254 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10255 				*outlenp = 0;
10256 				return (EINVAL);
10257 			}
10258 			tcp->tcp_init_cwnd = init_cwnd;
10259 			break;
10260 		}
10261 		case TCP_KEEPALIVE_THRESHOLD:
10262 			if (checkonly)
10263 				break;
10264 
10265 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10266 			    *i1 > tcps->tcps_keepalive_interval_high) {
10267 				*outlenp = 0;
10268 				return (EINVAL);
10269 			}
10270 			if (*i1 != tcp->tcp_ka_interval) {
10271 				tcp->tcp_ka_interval = *i1;
10272 				/*
10273 				 * Check if we need to restart the
10274 				 * keepalive timer.
10275 				 */
10276 				if (tcp->tcp_ka_tid != 0) {
10277 					ASSERT(tcp->tcp_ka_enabled);
10278 					(void) TCP_TIMER_CANCEL(tcp,
10279 					    tcp->tcp_ka_tid);
10280 					tcp->tcp_ka_last_intrvl = 0;
10281 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10282 					    tcp_keepalive_killer,
10283 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10284 				}
10285 			}
10286 			break;
10287 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10288 			if (!checkonly) {
10289 				if (*i1 <
10290 				    tcps->tcps_keepalive_abort_interval_low ||
10291 				    *i1 >
10292 				    tcps->tcps_keepalive_abort_interval_high) {
10293 					*outlenp = 0;
10294 					return (EINVAL);
10295 				}
10296 				tcp->tcp_ka_abort_thres = *i1;
10297 			}
10298 			break;
10299 		case TCP_CORK:
10300 			if (!checkonly) {
10301 				/*
10302 				 * if tcp->tcp_cork was set and is now
10303 				 * being unset, we have to make sure that
10304 				 * the remaining data gets sent out. Also
10305 				 * unset tcp->tcp_cork so that tcp_wput_data()
10306 				 * can send data even if it is less than mss
10307 				 */
10308 				if (tcp->tcp_cork && onoff == 0 &&
10309 				    tcp->tcp_unsent > 0) {
10310 					tcp->tcp_cork = B_FALSE;
10311 					tcp_wput_data(tcp, NULL, B_FALSE);
10312 				}
10313 				tcp->tcp_cork = onoff;
10314 			}
10315 			break;
10316 		default:
10317 			*outlenp = 0;
10318 			return (EINVAL);
10319 		}
10320 		break;
10321 	case IPPROTO_IP:
10322 		if (tcp->tcp_family != AF_INET) {
10323 			*outlenp = 0;
10324 			return (ENOPROTOOPT);
10325 		}
10326 		switch (name) {
10327 		case IP_OPTIONS:
10328 		case T_IP_OPTIONS:
10329 			reterr = tcp_opt_set_header(tcp, checkonly,
10330 			    invalp, inlen);
10331 			if (reterr) {
10332 				*outlenp = 0;
10333 				return (reterr);
10334 			}
10335 			/* OK return - copy input buffer into output buffer */
10336 			if (invalp != outvalp) {
10337 				/* don't trust bcopy for identical src/dst */
10338 				bcopy(invalp, outvalp, inlen);
10339 			}
10340 			*outlenp = inlen;
10341 			return (0);
10342 		case IP_TOS:
10343 		case T_IP_TOS:
10344 			if (!checkonly) {
10345 				tcp->tcp_ipha->ipha_type_of_service =
10346 				    (uchar_t)*i1;
10347 				tcp->tcp_tos = (uchar_t)*i1;
10348 			}
10349 			break;
10350 		case IP_TTL:
10351 			if (!checkonly) {
10352 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10353 				tcp->tcp_ttl = (uchar_t)*i1;
10354 			}
10355 			break;
10356 		case IP_BOUND_IF:
10357 		case IP_NEXTHOP:
10358 			/* Handled at the IP level */
10359 			return (-EINVAL);
10360 		case IP_SEC_OPT:
10361 			/*
10362 			 * We should not allow policy setting after
10363 			 * we start listening for connections.
10364 			 */
10365 			if (tcp->tcp_state == TCPS_LISTEN) {
10366 				return (EINVAL);
10367 			} else {
10368 				/* Handled at the IP level */
10369 				return (-EINVAL);
10370 			}
10371 		default:
10372 			*outlenp = 0;
10373 			return (EINVAL);
10374 		}
10375 		break;
10376 	case IPPROTO_IPV6: {
10377 		ip6_pkt_t		*ipp;
10378 
10379 		/*
10380 		 * IPPROTO_IPV6 options are only supported for sockets
10381 		 * that are using IPv6 on the wire.
10382 		 */
10383 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10384 			*outlenp = 0;
10385 			return (ENOPROTOOPT);
10386 		}
10387 		/*
10388 		 * Only sticky options; no ancillary data
10389 		 */
10390 		ipp = &tcp->tcp_sticky_ipp;
10391 
10392 		switch (name) {
10393 		case IPV6_UNICAST_HOPS:
10394 			/* -1 means use default */
10395 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10396 				*outlenp = 0;
10397 				return (EINVAL);
10398 			}
10399 			if (!checkonly) {
10400 				if (*i1 == -1) {
10401 					tcp->tcp_ip6h->ip6_hops =
10402 					    ipp->ipp_unicast_hops =
10403 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10404 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10405 					/* Pass modified value to IP. */
10406 					*i1 = tcp->tcp_ip6h->ip6_hops;
10407 				} else {
10408 					tcp->tcp_ip6h->ip6_hops =
10409 					    ipp->ipp_unicast_hops =
10410 					    (uint8_t)*i1;
10411 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10412 				}
10413 				reterr = tcp_build_hdrs(tcp);
10414 				if (reterr != 0)
10415 					return (reterr);
10416 			}
10417 			break;
10418 		case IPV6_BOUND_IF:
10419 			if (!checkonly) {
10420 				tcp->tcp_bound_if = *i1;
10421 				PASS_OPT_TO_IP(connp);
10422 			}
10423 			break;
10424 		/*
10425 		 * Set boolean switches for ancillary data delivery
10426 		 */
10427 		case IPV6_RECVPKTINFO:
10428 			if (!checkonly) {
10429 				if (onoff)
10430 					tcp->tcp_ipv6_recvancillary |=
10431 					    TCP_IPV6_RECVPKTINFO;
10432 				else
10433 					tcp->tcp_ipv6_recvancillary &=
10434 					    ~TCP_IPV6_RECVPKTINFO;
10435 				/* Force it to be sent up with the next msg */
10436 				tcp->tcp_recvifindex = 0;
10437 				PASS_OPT_TO_IP(connp);
10438 			}
10439 			break;
10440 		case IPV6_RECVTCLASS:
10441 			if (!checkonly) {
10442 				if (onoff)
10443 					tcp->tcp_ipv6_recvancillary |=
10444 					    TCP_IPV6_RECVTCLASS;
10445 				else
10446 					tcp->tcp_ipv6_recvancillary &=
10447 					    ~TCP_IPV6_RECVTCLASS;
10448 				PASS_OPT_TO_IP(connp);
10449 			}
10450 			break;
10451 		case IPV6_RECVHOPLIMIT:
10452 			if (!checkonly) {
10453 				if (onoff)
10454 					tcp->tcp_ipv6_recvancillary |=
10455 					    TCP_IPV6_RECVHOPLIMIT;
10456 				else
10457 					tcp->tcp_ipv6_recvancillary &=
10458 					    ~TCP_IPV6_RECVHOPLIMIT;
10459 				/* Force it to be sent up with the next msg */
10460 				tcp->tcp_recvhops = 0xffffffffU;
10461 				PASS_OPT_TO_IP(connp);
10462 			}
10463 			break;
10464 		case IPV6_RECVHOPOPTS:
10465 			if (!checkonly) {
10466 				if (onoff)
10467 					tcp->tcp_ipv6_recvancillary |=
10468 					    TCP_IPV6_RECVHOPOPTS;
10469 				else
10470 					tcp->tcp_ipv6_recvancillary &=
10471 					    ~TCP_IPV6_RECVHOPOPTS;
10472 				PASS_OPT_TO_IP(connp);
10473 			}
10474 			break;
10475 		case IPV6_RECVDSTOPTS:
10476 			if (!checkonly) {
10477 				if (onoff)
10478 					tcp->tcp_ipv6_recvancillary |=
10479 					    TCP_IPV6_RECVDSTOPTS;
10480 				else
10481 					tcp->tcp_ipv6_recvancillary &=
10482 					    ~TCP_IPV6_RECVDSTOPTS;
10483 				PASS_OPT_TO_IP(connp);
10484 			}
10485 			break;
10486 		case _OLD_IPV6_RECVDSTOPTS:
10487 			if (!checkonly) {
10488 				if (onoff)
10489 					tcp->tcp_ipv6_recvancillary |=
10490 					    TCP_OLD_IPV6_RECVDSTOPTS;
10491 				else
10492 					tcp->tcp_ipv6_recvancillary &=
10493 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10494 			}
10495 			break;
10496 		case IPV6_RECVRTHDR:
10497 			if (!checkonly) {
10498 				if (onoff)
10499 					tcp->tcp_ipv6_recvancillary |=
10500 					    TCP_IPV6_RECVRTHDR;
10501 				else
10502 					tcp->tcp_ipv6_recvancillary &=
10503 					    ~TCP_IPV6_RECVRTHDR;
10504 				PASS_OPT_TO_IP(connp);
10505 			}
10506 			break;
10507 		case IPV6_RECVRTHDRDSTOPTS:
10508 			if (!checkonly) {
10509 				if (onoff)
10510 					tcp->tcp_ipv6_recvancillary |=
10511 					    TCP_IPV6_RECVRTDSTOPTS;
10512 				else
10513 					tcp->tcp_ipv6_recvancillary &=
10514 					    ~TCP_IPV6_RECVRTDSTOPTS;
10515 				PASS_OPT_TO_IP(connp);
10516 			}
10517 			break;
10518 		case IPV6_PKTINFO:
10519 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10520 				return (EINVAL);
10521 			if (checkonly)
10522 				break;
10523 
10524 			if (inlen == 0) {
10525 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10526 			} else {
10527 				struct in6_pktinfo *pkti;
10528 
10529 				pkti = (struct in6_pktinfo *)invalp;
10530 				/*
10531 				 * RFC 3542 states that ipi6_addr must be
10532 				 * the unspecified address when setting the
10533 				 * IPV6_PKTINFO sticky socket option on a
10534 				 * TCP socket.
10535 				 */
10536 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10537 					return (EINVAL);
10538 				/*
10539 				 * IP will validate the source address and
10540 				 * interface index.
10541 				 */
10542 				if (IPCL_IS_NONSTR(tcp->tcp_connp)) {
10543 					reterr = ip_set_options(tcp->tcp_connp,
10544 					    level, name, invalp, inlen, cr);
10545 				} else {
10546 					reterr = ip6_set_pktinfo(cr,
10547 					    tcp->tcp_connp, pkti);
10548 				}
10549 				if (reterr != 0)
10550 					return (reterr);
10551 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10552 				ipp->ipp_addr = pkti->ipi6_addr;
10553 				if (ipp->ipp_ifindex != 0)
10554 					ipp->ipp_fields |= IPPF_IFINDEX;
10555 				else
10556 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10557 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10558 					ipp->ipp_fields |= IPPF_ADDR;
10559 				else
10560 					ipp->ipp_fields &= ~IPPF_ADDR;
10561 			}
10562 			reterr = tcp_build_hdrs(tcp);
10563 			if (reterr != 0)
10564 				return (reterr);
10565 			break;
10566 		case IPV6_TCLASS:
10567 			if (inlen != 0 && inlen != sizeof (int))
10568 				return (EINVAL);
10569 			if (checkonly)
10570 				break;
10571 
10572 			if (inlen == 0) {
10573 				ipp->ipp_fields &= ~IPPF_TCLASS;
10574 			} else {
10575 				if (*i1 > 255 || *i1 < -1)
10576 					return (EINVAL);
10577 				if (*i1 == -1) {
10578 					ipp->ipp_tclass = 0;
10579 					*i1 = 0;
10580 				} else {
10581 					ipp->ipp_tclass = *i1;
10582 				}
10583 				ipp->ipp_fields |= IPPF_TCLASS;
10584 			}
10585 			reterr = tcp_build_hdrs(tcp);
10586 			if (reterr != 0)
10587 				return (reterr);
10588 			break;
10589 		case IPV6_NEXTHOP:
10590 			/*
10591 			 * IP will verify that the nexthop is reachable
10592 			 * and fail for sticky options.
10593 			 */
10594 			if (inlen != 0 && inlen != sizeof (sin6_t))
10595 				return (EINVAL);
10596 			if (checkonly)
10597 				break;
10598 
10599 			if (inlen == 0) {
10600 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10601 			} else {
10602 				sin6_t *sin6 = (sin6_t *)invalp;
10603 
10604 				if (sin6->sin6_family != AF_INET6)
10605 					return (EAFNOSUPPORT);
10606 				if (IN6_IS_ADDR_V4MAPPED(
10607 				    &sin6->sin6_addr))
10608 					return (EADDRNOTAVAIL);
10609 				ipp->ipp_nexthop = sin6->sin6_addr;
10610 				if (!IN6_IS_ADDR_UNSPECIFIED(
10611 				    &ipp->ipp_nexthop))
10612 					ipp->ipp_fields |= IPPF_NEXTHOP;
10613 				else
10614 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10615 			}
10616 			reterr = tcp_build_hdrs(tcp);
10617 			if (reterr != 0)
10618 				return (reterr);
10619 			PASS_OPT_TO_IP(connp);
10620 			break;
10621 		case IPV6_HOPOPTS: {
10622 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10623 
10624 			/*
10625 			 * Sanity checks - minimum size, size a multiple of
10626 			 * eight bytes, and matching size passed in.
10627 			 */
10628 			if (inlen != 0 &&
10629 			    inlen != (8 * (hopts->ip6h_len + 1)))
10630 				return (EINVAL);
10631 
10632 			if (checkonly)
10633 				break;
10634 
10635 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10636 			    (uchar_t **)&ipp->ipp_hopopts,
10637 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10638 			if (reterr != 0)
10639 				return (reterr);
10640 			if (ipp->ipp_hopoptslen == 0)
10641 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10642 			else
10643 				ipp->ipp_fields |= IPPF_HOPOPTS;
10644 			reterr = tcp_build_hdrs(tcp);
10645 			if (reterr != 0)
10646 				return (reterr);
10647 			break;
10648 		}
10649 		case IPV6_RTHDRDSTOPTS: {
10650 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10651 
10652 			/*
10653 			 * Sanity checks - minimum size, size a multiple of
10654 			 * eight bytes, and matching size passed in.
10655 			 */
10656 			if (inlen != 0 &&
10657 			    inlen != (8 * (dopts->ip6d_len + 1)))
10658 				return (EINVAL);
10659 
10660 			if (checkonly)
10661 				break;
10662 
10663 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10664 			    (uchar_t **)&ipp->ipp_rtdstopts,
10665 			    &ipp->ipp_rtdstoptslen, 0);
10666 			if (reterr != 0)
10667 				return (reterr);
10668 			if (ipp->ipp_rtdstoptslen == 0)
10669 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
10670 			else
10671 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
10672 			reterr = tcp_build_hdrs(tcp);
10673 			if (reterr != 0)
10674 				return (reterr);
10675 			break;
10676 		}
10677 		case IPV6_DSTOPTS: {
10678 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10679 
10680 			/*
10681 			 * Sanity checks - minimum size, size a multiple of
10682 			 * eight bytes, and matching size passed in.
10683 			 */
10684 			if (inlen != 0 &&
10685 			    inlen != (8 * (dopts->ip6d_len + 1)))
10686 				return (EINVAL);
10687 
10688 			if (checkonly)
10689 				break;
10690 
10691 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10692 			    (uchar_t **)&ipp->ipp_dstopts,
10693 			    &ipp->ipp_dstoptslen, 0);
10694 			if (reterr != 0)
10695 				return (reterr);
10696 			if (ipp->ipp_dstoptslen == 0)
10697 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
10698 			else
10699 				ipp->ipp_fields |= IPPF_DSTOPTS;
10700 			reterr = tcp_build_hdrs(tcp);
10701 			if (reterr != 0)
10702 				return (reterr);
10703 			break;
10704 		}
10705 		case IPV6_RTHDR: {
10706 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
10707 
10708 			/*
10709 			 * Sanity checks - minimum size, size a multiple of
10710 			 * eight bytes, and matching size passed in.
10711 			 */
10712 			if (inlen != 0 &&
10713 			    inlen != (8 * (rt->ip6r_len + 1)))
10714 				return (EINVAL);
10715 
10716 			if (checkonly)
10717 				break;
10718 
10719 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10720 			    (uchar_t **)&ipp->ipp_rthdr,
10721 			    &ipp->ipp_rthdrlen, 0);
10722 			if (reterr != 0)
10723 				return (reterr);
10724 			if (ipp->ipp_rthdrlen == 0)
10725 				ipp->ipp_fields &= ~IPPF_RTHDR;
10726 			else
10727 				ipp->ipp_fields |= IPPF_RTHDR;
10728 			reterr = tcp_build_hdrs(tcp);
10729 			if (reterr != 0)
10730 				return (reterr);
10731 			break;
10732 		}
10733 		case IPV6_V6ONLY:
10734 			if (!checkonly) {
10735 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
10736 			}
10737 			break;
10738 		case IPV6_USE_MIN_MTU:
10739 			if (inlen != sizeof (int))
10740 				return (EINVAL);
10741 
10742 			if (*i1 < -1 || *i1 > 1)
10743 				return (EINVAL);
10744 
10745 			if (checkonly)
10746 				break;
10747 
10748 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
10749 			ipp->ipp_use_min_mtu = *i1;
10750 			break;
10751 		case IPV6_SEC_OPT:
10752 			/*
10753 			 * We should not allow policy setting after
10754 			 * we start listening for connections.
10755 			 */
10756 			if (tcp->tcp_state == TCPS_LISTEN) {
10757 				return (EINVAL);
10758 			} else {
10759 				/* Handled at the IP level */
10760 				return (-EINVAL);
10761 			}
10762 		case IPV6_SRC_PREFERENCES:
10763 			if (inlen != sizeof (uint32_t))
10764 				return (EINVAL);
10765 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
10766 			    *(uint32_t *)invalp);
10767 			if (reterr != 0) {
10768 				*outlenp = 0;
10769 				return (reterr);
10770 			}
10771 			break;
10772 		default:
10773 			*outlenp = 0;
10774 			return (EINVAL);
10775 		}
10776 		break;
10777 	}		/* end IPPROTO_IPV6 */
10778 	default:
10779 		*outlenp = 0;
10780 		return (EINVAL);
10781 	}
10782 	/*
10783 	 * Common case of OK return with outval same as inval
10784 	 */
10785 	if (invalp != outvalp) {
10786 		/* don't trust bcopy for identical src/dst */
10787 		(void) bcopy(invalp, outvalp, inlen);
10788 	}
10789 	*outlenp = inlen;
10790 	return (0);
10791 }
10792 
10793 /* ARGSUSED */
10794 int
10795 tcp_tpi_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10796     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10797     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10798 {
10799 	conn_t	*connp =  Q_TO_CONN(q);
10800 
10801 	return (tcp_opt_set(connp, optset_context, level, name, inlen, invalp,
10802 	    outlenp, outvalp, thisdg_attrs, cr, mblk));
10803 }
10804 
10805 int
10806 tcp_setsockopt(sock_lower_handle_t proto_handle, int level, int option_name,
10807     const void *optvalp, socklen_t optlen, cred_t *cr)
10808 {
10809 	conn_t		*connp = (conn_t *)proto_handle;
10810 	squeue_t	*sqp = connp->conn_sqp;
10811 	int		error;
10812 
10813 	ASSERT(connp->conn_upper_handle != NULL);
10814 	/*
10815 	 * Entering the squeue synchronously can result in a context switch,
10816 	 * which can cause a rather sever performance degradation. So we try to
10817 	 * handle whatever options we can without entering the squeue.
10818 	 */
10819 	if (level == IPPROTO_TCP) {
10820 		switch (option_name) {
10821 		case TCP_NODELAY:
10822 			if (optlen != sizeof (int32_t))
10823 				return (EINVAL);
10824 			mutex_enter(&connp->conn_tcp->tcp_non_sq_lock);
10825 			connp->conn_tcp->tcp_naglim = *(int *)optvalp ? 1 :
10826 			    connp->conn_tcp->tcp_mss;
10827 			mutex_exit(&connp->conn_tcp->tcp_non_sq_lock);
10828 			return (0);
10829 		default:
10830 			break;
10831 		}
10832 	}
10833 
10834 	error = squeue_synch_enter(sqp, connp, 0);
10835 	if (error == ENOMEM) {
10836 		return (ENOMEM);
10837 	}
10838 
10839 	error = proto_opt_check(level, option_name, optlen, NULL,
10840 	    tcp_opt_obj.odb_opt_des_arr,
10841 	    tcp_opt_obj.odb_opt_arr_cnt,
10842 	    tcp_opt_obj.odb_topmost_tpiprovider,
10843 	    B_TRUE, B_FALSE, cr);
10844 
10845 	if (error != 0) {
10846 		if (error < 0) {
10847 			error = proto_tlitosyserr(-error);
10848 		}
10849 		squeue_synch_exit(sqp, connp);
10850 		return (error);
10851 	}
10852 
10853 	error = tcp_opt_set(connp, SETFN_OPTCOM_NEGOTIATE, level, option_name,
10854 	    optlen, (uchar_t *)optvalp, (uint_t *)&optlen, (uchar_t *)optvalp,
10855 	    NULL, cr, NULL);
10856 	squeue_synch_exit(sqp, connp);
10857 
10858 	if (error < 0) {
10859 		/*
10860 		 * Pass on to ip
10861 		 */
10862 		error = ip_set_options(connp, level, option_name, optvalp,
10863 		    optlen, cr);
10864 	}
10865 	return (error);
10866 }
10867 
10868 /*
10869  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
10870  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
10871  * headers, and the maximum size tcp header (to avoid reallocation
10872  * on the fly for additional tcp options).
10873  * Returns failure if can't allocate memory.
10874  */
10875 static int
10876 tcp_build_hdrs(tcp_t *tcp)
10877 {
10878 	char	*hdrs;
10879 	uint_t	hdrs_len;
10880 	ip6i_t	*ip6i;
10881 	char	buf[TCP_MAX_HDR_LENGTH];
10882 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
10883 	in6_addr_t src, dst;
10884 	tcp_stack_t	*tcps = tcp->tcp_tcps;
10885 	conn_t *connp = tcp->tcp_connp;
10886 
10887 	/*
10888 	 * save the existing tcp header and source/dest IP addresses
10889 	 */
10890 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
10891 	src = tcp->tcp_ip6h->ip6_src;
10892 	dst = tcp->tcp_ip6h->ip6_dst;
10893 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
10894 	ASSERT(hdrs_len != 0);
10895 	if (hdrs_len > tcp->tcp_iphc_len) {
10896 		/* Need to reallocate */
10897 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
10898 		if (hdrs == NULL)
10899 			return (ENOMEM);
10900 		if (tcp->tcp_iphc != NULL) {
10901 			if (tcp->tcp_hdr_grown) {
10902 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
10903 			} else {
10904 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
10905 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
10906 			}
10907 			tcp->tcp_iphc_len = 0;
10908 		}
10909 		ASSERT(tcp->tcp_iphc_len == 0);
10910 		tcp->tcp_iphc = hdrs;
10911 		tcp->tcp_iphc_len = hdrs_len;
10912 		tcp->tcp_hdr_grown = B_TRUE;
10913 	}
10914 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
10915 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
10916 
10917 	/* Set header fields not in ipp */
10918 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
10919 		ip6i = (ip6i_t *)tcp->tcp_iphc;
10920 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
10921 	} else {
10922 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
10923 	}
10924 	/*
10925 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
10926 	 *
10927 	 * tcp->tcp_tcp_hdr_len doesn't change here.
10928 	 */
10929 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
10930 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
10931 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
10932 
10933 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
10934 
10935 	tcp->tcp_ip6h->ip6_src = src;
10936 	tcp->tcp_ip6h->ip6_dst = dst;
10937 
10938 	/*
10939 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
10940 	 * the default value for TCP.
10941 	 */
10942 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
10943 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
10944 
10945 	/*
10946 	 * If we're setting extension headers after a connection
10947 	 * has been established, and if we have a routing header
10948 	 * among the extension headers, call ip_massage_options_v6 to
10949 	 * manipulate the routing header/ip6_dst set the checksum
10950 	 * difference in the tcp header template.
10951 	 * (This happens in tcp_connect_ipv6 if the routing header
10952 	 * is set prior to the connect.)
10953 	 * Set the tcp_sum to zero first in case we've cleared a
10954 	 * routing header or don't have one at all.
10955 	 */
10956 	tcp->tcp_sum = 0;
10957 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
10958 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
10959 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
10960 		    (uint8_t *)tcp->tcp_tcph);
10961 		if (rth != NULL) {
10962 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
10963 			    rth, tcps->tcps_netstack);
10964 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
10965 			    (tcp->tcp_sum >> 16));
10966 		}
10967 	}
10968 
10969 	/* Try to get everything in a single mblk */
10970 	(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
10971 	    hdrs_len + tcps->tcps_wroff_xtra);
10972 	return (0);
10973 }
10974 
10975 /*
10976  * Transfer any source route option from ipha to buf/dst in reversed form.
10977  */
10978 static int
10979 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
10980 {
10981 	ipoptp_t	opts;
10982 	uchar_t		*opt;
10983 	uint8_t		optval;
10984 	uint8_t		optlen;
10985 	uint32_t	len = 0;
10986 
10987 	for (optval = ipoptp_first(&opts, ipha);
10988 	    optval != IPOPT_EOL;
10989 	    optval = ipoptp_next(&opts)) {
10990 		opt = opts.ipoptp_cur;
10991 		optlen = opts.ipoptp_len;
10992 		switch (optval) {
10993 			int	off1, off2;
10994 		case IPOPT_SSRR:
10995 		case IPOPT_LSRR:
10996 
10997 			/* Reverse source route */
10998 			/*
10999 			 * First entry should be the next to last one in the
11000 			 * current source route (the last entry is our
11001 			 * address.)
11002 			 * The last entry should be the final destination.
11003 			 */
11004 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11005 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11006 			off1 = IPOPT_MINOFF_SR - 1;
11007 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11008 			if (off2 < 0) {
11009 				/* No entries in source route */
11010 				break;
11011 			}
11012 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11013 			/*
11014 			 * Note: use src since ipha has not had its src
11015 			 * and dst reversed (it is in the state it was
11016 			 * received.
11017 			 */
11018 			bcopy(&ipha->ipha_src, buf + off2,
11019 			    IP_ADDR_LEN);
11020 			off2 -= IP_ADDR_LEN;
11021 
11022 			while (off2 > 0) {
11023 				bcopy(opt + off2, buf + off1,
11024 				    IP_ADDR_LEN);
11025 				off1 += IP_ADDR_LEN;
11026 				off2 -= IP_ADDR_LEN;
11027 			}
11028 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11029 			buf += optlen;
11030 			len += optlen;
11031 			break;
11032 		}
11033 	}
11034 done:
11035 	/* Pad the resulting options */
11036 	while (len & 0x3) {
11037 		*buf++ = IPOPT_EOL;
11038 		len++;
11039 	}
11040 	return (len);
11041 }
11042 
11043 
11044 /*
11045  * Extract and revert a source route from ipha (if any)
11046  * and then update the relevant fields in both tcp_t and the standard header.
11047  */
11048 static void
11049 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11050 {
11051 	char	buf[TCP_MAX_HDR_LENGTH];
11052 	uint_t	tcph_len;
11053 	int	len;
11054 
11055 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11056 	len = IPH_HDR_LENGTH(ipha);
11057 	if (len == IP_SIMPLE_HDR_LENGTH)
11058 		/* Nothing to do */
11059 		return;
11060 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11061 	    (len & 0x3))
11062 		return;
11063 
11064 	tcph_len = tcp->tcp_tcp_hdr_len;
11065 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11066 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11067 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11068 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11069 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11070 	len += IP_SIMPLE_HDR_LENGTH;
11071 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11072 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11073 	if ((int)tcp->tcp_sum < 0)
11074 		tcp->tcp_sum--;
11075 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11076 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11077 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11078 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11079 	tcp->tcp_ip_hdr_len = len;
11080 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11081 	    (IP_VERSION << 4) | (len >> 2);
11082 	len += tcph_len;
11083 	tcp->tcp_hdr_len = len;
11084 }
11085 
11086 /*
11087  * Copy the standard header into its new location,
11088  * lay in the new options and then update the relevant
11089  * fields in both tcp_t and the standard header.
11090  */
11091 static int
11092 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11093 {
11094 	uint_t	tcph_len;
11095 	uint8_t	*ip_optp;
11096 	tcph_t	*new_tcph;
11097 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11098 	conn_t	*connp = tcp->tcp_connp;
11099 
11100 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11101 		return (EINVAL);
11102 
11103 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11104 		return (EINVAL);
11105 
11106 	if (checkonly) {
11107 		/*
11108 		 * do not really set, just pretend to - T_CHECK
11109 		 */
11110 		return (0);
11111 	}
11112 
11113 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11114 	if (tcp->tcp_label_len > 0) {
11115 		int padlen;
11116 		uint8_t opt;
11117 
11118 		/* convert list termination to no-ops */
11119 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11120 		ip_optp += ip_optp[IPOPT_OLEN];
11121 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11122 		while (--padlen >= 0)
11123 			*ip_optp++ = opt;
11124 	}
11125 	tcph_len = tcp->tcp_tcp_hdr_len;
11126 	new_tcph = (tcph_t *)(ip_optp + len);
11127 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11128 	tcp->tcp_tcph = new_tcph;
11129 	bcopy(ptr, ip_optp, len);
11130 
11131 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11132 
11133 	tcp->tcp_ip_hdr_len = len;
11134 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11135 	    (IP_VERSION << 4) | (len >> 2);
11136 	tcp->tcp_hdr_len = len + tcph_len;
11137 	if (!TCP_IS_DETACHED(tcp)) {
11138 		/* Always allocate room for all options. */
11139 		(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
11140 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11141 	}
11142 	return (0);
11143 }
11144 
11145 /* Get callback routine passed to nd_load by tcp_param_register */
11146 /* ARGSUSED */
11147 static int
11148 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11149 {
11150 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11151 
11152 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11153 	return (0);
11154 }
11155 
11156 /*
11157  * Walk through the param array specified registering each element with the
11158  * named dispatch handler.
11159  */
11160 static boolean_t
11161 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11162 {
11163 	for (; cnt-- > 0; tcppa++) {
11164 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11165 			if (!nd_load(ndp, tcppa->tcp_param_name,
11166 			    tcp_param_get, tcp_param_set,
11167 			    (caddr_t)tcppa)) {
11168 				nd_free(ndp);
11169 				return (B_FALSE);
11170 			}
11171 		}
11172 	}
11173 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11174 	    KM_SLEEP);
11175 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11176 	    sizeof (tcpparam_t));
11177 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11178 	    tcp_param_get, tcp_param_set_aligned,
11179 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11180 		nd_free(ndp);
11181 		return (B_FALSE);
11182 	}
11183 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11184 	    KM_SLEEP);
11185 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11186 	    sizeof (tcpparam_t));
11187 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11188 	    tcp_param_get, tcp_param_set_aligned,
11189 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11190 		nd_free(ndp);
11191 		return (B_FALSE);
11192 	}
11193 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11194 	    KM_SLEEP);
11195 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11196 	    sizeof (tcpparam_t));
11197 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11198 	    tcp_param_get, tcp_param_set_aligned,
11199 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11200 		nd_free(ndp);
11201 		return (B_FALSE);
11202 	}
11203 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11204 	    KM_SLEEP);
11205 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11206 	    sizeof (tcpparam_t));
11207 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11208 	    tcp_param_get, tcp_param_set_aligned,
11209 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11210 		nd_free(ndp);
11211 		return (B_FALSE);
11212 	}
11213 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11214 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11215 		nd_free(ndp);
11216 		return (B_FALSE);
11217 	}
11218 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11219 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11220 		nd_free(ndp);
11221 		return (B_FALSE);
11222 	}
11223 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11224 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11225 		nd_free(ndp);
11226 		return (B_FALSE);
11227 	}
11228 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11229 	    NULL)) {
11230 		nd_free(ndp);
11231 		return (B_FALSE);
11232 	}
11233 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11234 	    NULL, NULL)) {
11235 		nd_free(ndp);
11236 		return (B_FALSE);
11237 	}
11238 	if (!nd_load(ndp, "tcp_listen_hash",
11239 	    tcp_listen_hash_report, NULL, NULL)) {
11240 		nd_free(ndp);
11241 		return (B_FALSE);
11242 	}
11243 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11244 	    NULL, NULL)) {
11245 		nd_free(ndp);
11246 		return (B_FALSE);
11247 	}
11248 	if (!nd_load(ndp, "tcp_acceptor_hash",
11249 	    tcp_acceptor_hash_report, NULL, NULL)) {
11250 		nd_free(ndp);
11251 		return (B_FALSE);
11252 	}
11253 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11254 	    tcp_1948_phrase_set, NULL)) {
11255 		nd_free(ndp);
11256 		return (B_FALSE);
11257 	}
11258 	/*
11259 	 * Dummy ndd variables - only to convey obsolescence information
11260 	 * through printing of their name (no get or set routines)
11261 	 * XXX Remove in future releases ?
11262 	 */
11263 	if (!nd_load(ndp,
11264 	    "tcp_close_wait_interval(obsoleted - "
11265 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11266 		nd_free(ndp);
11267 		return (B_FALSE);
11268 	}
11269 	return (B_TRUE);
11270 }
11271 
11272 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11273 /* ARGSUSED */
11274 static int
11275 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11276     cred_t *cr)
11277 {
11278 	long new_value;
11279 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11280 
11281 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11282 	    new_value < tcppa->tcp_param_min ||
11283 	    new_value > tcppa->tcp_param_max) {
11284 		return (EINVAL);
11285 	}
11286 	/*
11287 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11288 	 * round it up.  For future 64 bit requirement, we actually make it
11289 	 * a multiple of 8.
11290 	 */
11291 	if (new_value & 0x7) {
11292 		new_value = (new_value & ~0x7) + 0x8;
11293 	}
11294 	tcppa->tcp_param_val = new_value;
11295 	return (0);
11296 }
11297 
11298 /* Set callback routine passed to nd_load by tcp_param_register */
11299 /* ARGSUSED */
11300 static int
11301 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11302 {
11303 	long	new_value;
11304 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11305 
11306 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11307 	    new_value < tcppa->tcp_param_min ||
11308 	    new_value > tcppa->tcp_param_max) {
11309 		return (EINVAL);
11310 	}
11311 	tcppa->tcp_param_val = new_value;
11312 	return (0);
11313 }
11314 
11315 /*
11316  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11317  * is filled, return as much as we can.  The message passed in may be
11318  * multi-part, chained using b_cont.  "start" is the starting sequence
11319  * number for this piece.
11320  */
11321 static mblk_t *
11322 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11323 {
11324 	uint32_t	end;
11325 	mblk_t		*mp1;
11326 	mblk_t		*mp2;
11327 	mblk_t		*next_mp;
11328 	uint32_t	u1;
11329 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11330 
11331 	/* Walk through all the new pieces. */
11332 	do {
11333 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11334 		    (uintptr_t)INT_MAX);
11335 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11336 		next_mp = mp->b_cont;
11337 		if (start == end) {
11338 			/* Empty.  Blast it. */
11339 			freeb(mp);
11340 			continue;
11341 		}
11342 		mp->b_cont = NULL;
11343 		TCP_REASS_SET_SEQ(mp, start);
11344 		TCP_REASS_SET_END(mp, end);
11345 		mp1 = tcp->tcp_reass_tail;
11346 		if (!mp1) {
11347 			tcp->tcp_reass_tail = mp;
11348 			tcp->tcp_reass_head = mp;
11349 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11350 			UPDATE_MIB(&tcps->tcps_mib,
11351 			    tcpInDataUnorderBytes, end - start);
11352 			continue;
11353 		}
11354 		/* New stuff completely beyond tail? */
11355 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11356 			/* Link it on end. */
11357 			mp1->b_cont = mp;
11358 			tcp->tcp_reass_tail = mp;
11359 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11360 			UPDATE_MIB(&tcps->tcps_mib,
11361 			    tcpInDataUnorderBytes, end - start);
11362 			continue;
11363 		}
11364 		mp1 = tcp->tcp_reass_head;
11365 		u1 = TCP_REASS_SEQ(mp1);
11366 		/* New stuff at the front? */
11367 		if (SEQ_LT(start, u1)) {
11368 			/* Yes... Check for overlap. */
11369 			mp->b_cont = mp1;
11370 			tcp->tcp_reass_head = mp;
11371 			tcp_reass_elim_overlap(tcp, mp);
11372 			continue;
11373 		}
11374 		/*
11375 		 * The new piece fits somewhere between the head and tail.
11376 		 * We find our slot, where mp1 precedes us and mp2 trails.
11377 		 */
11378 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11379 			u1 = TCP_REASS_SEQ(mp2);
11380 			if (SEQ_LEQ(start, u1))
11381 				break;
11382 		}
11383 		/* Link ourselves in */
11384 		mp->b_cont = mp2;
11385 		mp1->b_cont = mp;
11386 
11387 		/* Trim overlap with following mblk(s) first */
11388 		tcp_reass_elim_overlap(tcp, mp);
11389 
11390 		/* Trim overlap with preceding mblk */
11391 		tcp_reass_elim_overlap(tcp, mp1);
11392 
11393 	} while (start = end, mp = next_mp);
11394 	mp1 = tcp->tcp_reass_head;
11395 	/* Anything ready to go? */
11396 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11397 		return (NULL);
11398 	/* Eat what we can off the queue */
11399 	for (;;) {
11400 		mp = mp1->b_cont;
11401 		end = TCP_REASS_END(mp1);
11402 		TCP_REASS_SET_SEQ(mp1, 0);
11403 		TCP_REASS_SET_END(mp1, 0);
11404 		if (!mp) {
11405 			tcp->tcp_reass_tail = NULL;
11406 			break;
11407 		}
11408 		if (end != TCP_REASS_SEQ(mp)) {
11409 			mp1->b_cont = NULL;
11410 			break;
11411 		}
11412 		mp1 = mp;
11413 	}
11414 	mp1 = tcp->tcp_reass_head;
11415 	tcp->tcp_reass_head = mp;
11416 	return (mp1);
11417 }
11418 
11419 /* Eliminate any overlap that mp may have over later mblks */
11420 static void
11421 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11422 {
11423 	uint32_t	end;
11424 	mblk_t		*mp1;
11425 	uint32_t	u1;
11426 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11427 
11428 	end = TCP_REASS_END(mp);
11429 	while ((mp1 = mp->b_cont) != NULL) {
11430 		u1 = TCP_REASS_SEQ(mp1);
11431 		if (!SEQ_GT(end, u1))
11432 			break;
11433 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11434 			mp->b_wptr -= end - u1;
11435 			TCP_REASS_SET_END(mp, u1);
11436 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11437 			UPDATE_MIB(&tcps->tcps_mib,
11438 			    tcpInDataPartDupBytes, end - u1);
11439 			break;
11440 		}
11441 		mp->b_cont = mp1->b_cont;
11442 		TCP_REASS_SET_SEQ(mp1, 0);
11443 		TCP_REASS_SET_END(mp1, 0);
11444 		freeb(mp1);
11445 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11446 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11447 	}
11448 	if (!mp1)
11449 		tcp->tcp_reass_tail = mp;
11450 }
11451 
11452 static uint_t
11453 tcp_rwnd_reopen(tcp_t *tcp)
11454 {
11455 	uint_t ret = 0;
11456 	uint_t thwin;
11457 
11458 	/* Learn the latest rwnd information that we sent to the other side. */
11459 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11460 	    << tcp->tcp_rcv_ws;
11461 	/* This is peer's calculated send window (our receive window). */
11462 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11463 	/*
11464 	 * Increase the receive window to max.  But we need to do receiver
11465 	 * SWS avoidance.  This means that we need to check the increase of
11466 	 * of receive window is at least 1 MSS.
11467 	 */
11468 	if (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss) {
11469 		/*
11470 		 * If the window that the other side knows is less than max
11471 		 * deferred acks segments, send an update immediately.
11472 		 */
11473 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11474 			BUMP_MIB(&tcp->tcp_tcps->tcps_mib, tcpOutWinUpdate);
11475 			ret = TH_ACK_NEEDED;
11476 		}
11477 		tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
11478 	}
11479 	return (ret);
11480 }
11481 
11482 /*
11483  * Send up all messages queued on tcp_rcv_list.
11484  */
11485 static uint_t
11486 tcp_rcv_drain(tcp_t *tcp)
11487 {
11488 	mblk_t *mp;
11489 	uint_t ret = 0;
11490 #ifdef DEBUG
11491 	uint_t cnt = 0;
11492 #endif
11493 	queue_t	*q = tcp->tcp_rq;
11494 
11495 	/* Can't drain on an eager connection */
11496 	if (tcp->tcp_listener != NULL)
11497 		return (ret);
11498 
11499 	/* Can't be a non-STREAMS connection or sodirect enabled */
11500 	ASSERT((!IPCL_IS_NONSTR(tcp->tcp_connp)) && SOD_NOT_ENABLED(tcp));
11501 
11502 	/* No need for the push timer now. */
11503 	if (tcp->tcp_push_tid != 0) {
11504 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11505 		tcp->tcp_push_tid = 0;
11506 	}
11507 
11508 	/*
11509 	 * Handle two cases here: we are currently fused or we were
11510 	 * previously fused and have some urgent data to be delivered
11511 	 * upstream.  The latter happens because we either ran out of
11512 	 * memory or were detached and therefore sending the SIGURG was
11513 	 * deferred until this point.  In either case we pass control
11514 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11515 	 * some work.
11516 	 */
11517 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11518 		ASSERT(IPCL_IS_NONSTR(tcp->tcp_connp) ||
11519 		    tcp->tcp_fused_sigurg_mp != NULL);
11520 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11521 		    &tcp->tcp_fused_sigurg_mp))
11522 			return (ret);
11523 	}
11524 
11525 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11526 		tcp->tcp_rcv_list = mp->b_next;
11527 		mp->b_next = NULL;
11528 #ifdef DEBUG
11529 		cnt += msgdsize(mp);
11530 #endif
11531 		/* Does this need SSL processing first? */
11532 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11533 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11534 			    mblk_t *, mp);
11535 			tcp_kssl_input(tcp, mp);
11536 			continue;
11537 		}
11538 		putnext(q, mp);
11539 	}
11540 #ifdef DEBUG
11541 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11542 #endif
11543 	tcp->tcp_rcv_last_head = NULL;
11544 	tcp->tcp_rcv_last_tail = NULL;
11545 	tcp->tcp_rcv_cnt = 0;
11546 
11547 	if (canputnext(q))
11548 		return (tcp_rwnd_reopen(tcp));
11549 
11550 	return (ret);
11551 }
11552 
11553 /*
11554  * Queue data on tcp_rcv_list which is a b_next chain.
11555  * tcp_rcv_last_head/tail is the last element of this chain.
11556  * Each element of the chain is a b_cont chain.
11557  *
11558  * M_DATA messages are added to the current element.
11559  * Other messages are added as new (b_next) elements.
11560  */
11561 void
11562 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11563 {
11564 	ASSERT(seg_len == msgdsize(mp));
11565 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11566 
11567 	if (tcp->tcp_rcv_list == NULL) {
11568 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11569 		tcp->tcp_rcv_list = mp;
11570 		tcp->tcp_rcv_last_head = mp;
11571 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11572 		tcp->tcp_rcv_last_tail->b_cont = mp;
11573 	} else {
11574 		tcp->tcp_rcv_last_head->b_next = mp;
11575 		tcp->tcp_rcv_last_head = mp;
11576 	}
11577 
11578 	while (mp->b_cont)
11579 		mp = mp->b_cont;
11580 
11581 	tcp->tcp_rcv_last_tail = mp;
11582 	tcp->tcp_rcv_cnt += seg_len;
11583 	tcp->tcp_rwnd -= seg_len;
11584 }
11585 
11586 /*
11587  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11588  * above, in addition when uioa is enabled schedule an asynchronous uio
11589  * prior to enqueuing. They implement the combinhed semantics of the
11590  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11591  * canputnext(), i.e. flow-control with backenable.
11592  *
11593  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11594  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11595  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11596  *
11597  * Must be called with sodp->sod_lockp held and will return with the lock
11598  * released.
11599  */
11600 static uint_t
11601 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11602 {
11603 	queue_t		*q = tcp->tcp_rq;
11604 	uint_t		thwin;
11605 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11606 	uint_t		ret = 0;
11607 
11608 	/* Can't be an eager connection */
11609 	ASSERT(tcp->tcp_listener == NULL);
11610 
11611 	/* Caller must have lock held */
11612 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11613 
11614 	/* Sodirect mode so must not be a tcp_rcv_list */
11615 	ASSERT(tcp->tcp_rcv_list == NULL);
11616 
11617 	if (SOD_QFULL(sodp)) {
11618 		/* Q is full, mark Q for need backenable */
11619 		SOD_QSETBE(sodp);
11620 	}
11621 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11622 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11623 	    << tcp->tcp_rcv_ws;
11624 	/* This is peer's calculated send window (our available rwnd). */
11625 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11626 	/*
11627 	 * Increase the receive window to max.  But we need to do receiver
11628 	 * SWS avoidance.  This means that we need to check the increase of
11629 	 * of receive window is at least 1 MSS.
11630 	 */
11631 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11632 		/*
11633 		 * If the window that the other side knows is less than max
11634 		 * deferred acks segments, send an update immediately.
11635 		 */
11636 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11637 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11638 			ret = TH_ACK_NEEDED;
11639 		}
11640 		tcp->tcp_rwnd = q->q_hiwat;
11641 	}
11642 
11643 	if (!SOD_QEMPTY(sodp)) {
11644 		/* Wakeup to socket */
11645 		sodp->sod_state &= SOD_WAKE_CLR;
11646 		sodp->sod_state |= SOD_WAKE_DONE;
11647 		(sodp->sod_wakeup)(sodp);
11648 		/* wakeup() does the mutex_ext() */
11649 	} else {
11650 		/* Q is empty, no need to wake */
11651 		sodp->sod_state &= SOD_WAKE_CLR;
11652 		sodp->sod_state |= SOD_WAKE_NOT;
11653 		mutex_exit(sodp->sod_lockp);
11654 	}
11655 
11656 	/* No need for the push timer now. */
11657 	if (tcp->tcp_push_tid != 0) {
11658 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11659 		tcp->tcp_push_tid = 0;
11660 	}
11661 
11662 	return (ret);
11663 }
11664 
11665 /*
11666  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11667  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11668  * to the user-land buffer and flag the mblk_t as such.
11669  *
11670  * Also, handle tcp_rwnd.
11671  */
11672 uint_t
11673 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11674 {
11675 	uioa_t		*uioap = &sodp->sod_uioa;
11676 	boolean_t	qfull;
11677 	uint_t		thwin;
11678 
11679 	/* Can't be an eager connection */
11680 	ASSERT(tcp->tcp_listener == NULL);
11681 
11682 	/* Caller must have lock held */
11683 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11684 
11685 	/* Sodirect mode so must not be a tcp_rcv_list */
11686 	ASSERT(tcp->tcp_rcv_list == NULL);
11687 
11688 	/* Passed in segment length must be equal to mblk_t chain data size */
11689 	ASSERT(seg_len == msgdsize(mp));
11690 
11691 	if (DB_TYPE(mp) != M_DATA) {
11692 		/* Only process M_DATA mblk_t's */
11693 		goto enq;
11694 	}
11695 	if (uioap->uioa_state & UIOA_ENABLED) {
11696 		/* Uioa is enabled */
11697 		mblk_t		*mp1 = mp;
11698 		mblk_t		*lmp = NULL;
11699 
11700 		if (seg_len > uioap->uio_resid) {
11701 			/*
11702 			 * There isn't enough uio space for the mblk_t chain
11703 			 * so disable uioa such that this and any additional
11704 			 * mblk_t data is handled by the socket and schedule
11705 			 * the socket for wakeup to finish this uioa.
11706 			 */
11707 			uioap->uioa_state &= UIOA_CLR;
11708 			uioap->uioa_state |= UIOA_FINI;
11709 			if (sodp->sod_state & SOD_WAKE_NOT) {
11710 				sodp->sod_state &= SOD_WAKE_CLR;
11711 				sodp->sod_state |= SOD_WAKE_NEED;
11712 			}
11713 			goto enq;
11714 		}
11715 		do {
11716 			uint32_t	len = MBLKL(mp1);
11717 
11718 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11719 				/* Scheduled, mark dblk_t as such */
11720 				DB_FLAGS(mp1) |= DBLK_UIOA;
11721 			} else {
11722 				/* Error, turn off async processing */
11723 				uioap->uioa_state &= UIOA_CLR;
11724 				uioap->uioa_state |= UIOA_FINI;
11725 				break;
11726 			}
11727 			lmp = mp1;
11728 		} while ((mp1 = mp1->b_cont) != NULL);
11729 
11730 		if (mp1 != NULL || uioap->uio_resid == 0) {
11731 			/*
11732 			 * Not all mblk_t(s) uioamoved (error) or all uio
11733 			 * space has been consumed so schedule the socket
11734 			 * for wakeup to finish this uio.
11735 			 */
11736 			sodp->sod_state &= SOD_WAKE_CLR;
11737 			sodp->sod_state |= SOD_WAKE_NEED;
11738 
11739 			/* Break the mblk chain if neccessary. */
11740 			if (mp1 != NULL && lmp != NULL) {
11741 				mp->b_next = mp1;
11742 				lmp->b_cont = NULL;
11743 			}
11744 		}
11745 	} else if (uioap->uioa_state & UIOA_FINI) {
11746 		/*
11747 		 * Post UIO_ENABLED waiting for socket to finish processing
11748 		 * so just enqueue and update tcp_rwnd.
11749 		 */
11750 		if (SOD_QFULL(sodp))
11751 			tcp->tcp_rwnd -= seg_len;
11752 	} else if (sodp->sod_want > 0) {
11753 		/*
11754 		 * Uioa isn't enabled but sodirect has a pending read().
11755 		 */
11756 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11757 			if (sodp->sod_state & SOD_WAKE_NOT) {
11758 				/* Schedule socket for wakeup */
11759 				sodp->sod_state &= SOD_WAKE_CLR;
11760 				sodp->sod_state |= SOD_WAKE_NEED;
11761 			}
11762 			tcp->tcp_rwnd -= seg_len;
11763 		}
11764 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
11765 		/*
11766 		 * No pending sodirect read() so used the default
11767 		 * TCP push logic to guess that a push is needed.
11768 		 */
11769 		if (sodp->sod_state & SOD_WAKE_NOT) {
11770 			/* Schedule socket for wakeup */
11771 			sodp->sod_state &= SOD_WAKE_CLR;
11772 			sodp->sod_state |= SOD_WAKE_NEED;
11773 		}
11774 		tcp->tcp_rwnd -= seg_len;
11775 	} else {
11776 		/* Just update tcp_rwnd */
11777 		tcp->tcp_rwnd -= seg_len;
11778 	}
11779 enq:
11780 	qfull = SOD_QFULL(sodp);
11781 
11782 	(sodp->sod_enqueue)(sodp, mp);
11783 
11784 	if (! qfull && SOD_QFULL(sodp)) {
11785 		/* Wasn't QFULL, now QFULL, need back-enable */
11786 		SOD_QSETBE(sodp);
11787 	}
11788 
11789 	/*
11790 	 * Check to see if remote avail swnd < mss due to delayed ACK,
11791 	 * first get advertised rwnd.
11792 	 */
11793 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
11794 	/* Minus delayed ACK count */
11795 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11796 	if (thwin < tcp->tcp_mss) {
11797 		/* Remote avail swnd < mss, need ACK now */
11798 		return (TH_ACK_NEEDED);
11799 	}
11800 
11801 	return (0);
11802 }
11803 
11804 /*
11805  * DEFAULT TCP ENTRY POINT via squeue on READ side.
11806  *
11807  * This is the default entry function into TCP on the read side. TCP is
11808  * always entered via squeue i.e. using squeue's for mutual exclusion.
11809  * When classifier does a lookup to find the tcp, it also puts a reference
11810  * on the conn structure associated so the tcp is guaranteed to exist
11811  * when we come here. We still need to check the state because it might
11812  * as well has been closed. The squeue processing function i.e. squeue_enter,
11813  * is responsible for doing the CONN_DEC_REF.
11814  *
11815  * Apart from the default entry point, IP also sends packets directly to
11816  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
11817  * connections.
11818  */
11819 boolean_t tcp_outbound_squeue_switch = B_FALSE;
11820 void
11821 tcp_input(void *arg, mblk_t *mp, void *arg2)
11822 {
11823 	conn_t	*connp = (conn_t *)arg;
11824 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
11825 
11826 	/* arg2 is the sqp */
11827 	ASSERT(arg2 != NULL);
11828 	ASSERT(mp != NULL);
11829 
11830 	/*
11831 	 * Don't accept any input on a closed tcp as this TCP logically does
11832 	 * not exist on the system. Don't proceed further with this TCP.
11833 	 * For eg. this packet could trigger another close of this tcp
11834 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
11835 	 * tcp_clean_death / tcp_closei_local must be called at most once
11836 	 * on a TCP. In this case we need to refeed the packet into the
11837 	 * classifier and figure out where the packet should go. Need to
11838 	 * preserve the recv_ill somehow. Until we figure that out, for
11839 	 * now just drop the packet if we can't classify the packet.
11840 	 */
11841 	if (tcp->tcp_state == TCPS_CLOSED ||
11842 	    tcp->tcp_state == TCPS_BOUND) {
11843 		conn_t	*new_connp;
11844 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
11845 
11846 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
11847 		if (new_connp != NULL) {
11848 			tcp_reinput(new_connp, mp, arg2);
11849 			return;
11850 		}
11851 		/* We failed to classify. For now just drop the packet */
11852 		freemsg(mp);
11853 		return;
11854 	}
11855 
11856 	if (DB_TYPE(mp) != M_DATA) {
11857 		tcp_rput_common(tcp, mp);
11858 		return;
11859 	}
11860 
11861 	if (mp->b_datap->db_struioflag & STRUIO_CONNECT) {
11862 		squeue_t	*final_sqp;
11863 
11864 		mp->b_datap->db_struioflag &= ~STRUIO_CONNECT;
11865 		final_sqp = (squeue_t *)DB_CKSUMSTART(mp);
11866 		DB_CKSUMSTART(mp) = 0;
11867 		if (tcp->tcp_state == TCPS_SYN_SENT &&
11868 		    connp->conn_final_sqp == NULL &&
11869 		    tcp_outbound_squeue_switch) {
11870 			ASSERT(connp->conn_initial_sqp == connp->conn_sqp);
11871 			connp->conn_final_sqp = final_sqp;
11872 			if (connp->conn_final_sqp != connp->conn_sqp) {
11873 				CONN_INC_REF(connp);
11874 				SQUEUE_SWITCH(connp, connp->conn_final_sqp);
11875 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
11876 				    tcp_rput_data, connp, ip_squeue_flag,
11877 				    SQTAG_CONNECT_FINISH);
11878 				return;
11879 			}
11880 		}
11881 	}
11882 	tcp_rput_data(connp, mp, arg2);
11883 }
11884 
11885 /*
11886  * The read side put procedure.
11887  * The packets passed up by ip are assume to be aligned according to
11888  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
11889  */
11890 static void
11891 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
11892 {
11893 	/*
11894 	 * tcp_rput_data() does not expect M_CTL except for the case
11895 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
11896 	 * type. Need to make sure that any other M_CTLs don't make
11897 	 * it to tcp_rput_data since it is not expecting any and doesn't
11898 	 * check for it.
11899 	 */
11900 	if (DB_TYPE(mp) == M_CTL) {
11901 		switch (*(uint32_t *)(mp->b_rptr)) {
11902 		case TCP_IOC_ABORT_CONN:
11903 			/*
11904 			 * Handle connection abort request.
11905 			 */
11906 			tcp_ioctl_abort_handler(tcp, mp);
11907 			return;
11908 		case IPSEC_IN:
11909 			/*
11910 			 * Only secure icmp arrive in TCP and they
11911 			 * don't go through data path.
11912 			 */
11913 			tcp_icmp_error(tcp, mp);
11914 			return;
11915 		case IN_PKTINFO:
11916 			/*
11917 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
11918 			 * sockets that are receiving IPv4 traffic. tcp
11919 			 */
11920 			ASSERT(tcp->tcp_family == AF_INET6);
11921 			ASSERT(tcp->tcp_ipv6_recvancillary &
11922 			    TCP_IPV6_RECVPKTINFO);
11923 			tcp_rput_data(tcp->tcp_connp, mp,
11924 			    tcp->tcp_connp->conn_sqp);
11925 			return;
11926 		case MDT_IOC_INFO_UPDATE:
11927 			/*
11928 			 * Handle Multidata information update; the
11929 			 * following routine will free the message.
11930 			 */
11931 			if (tcp->tcp_connp->conn_mdt_ok) {
11932 				tcp_mdt_update(tcp,
11933 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
11934 				    B_FALSE);
11935 			}
11936 			freemsg(mp);
11937 			return;
11938 		case LSO_IOC_INFO_UPDATE:
11939 			/*
11940 			 * Handle LSO information update; the following
11941 			 * routine will free the message.
11942 			 */
11943 			if (tcp->tcp_connp->conn_lso_ok) {
11944 				tcp_lso_update(tcp,
11945 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
11946 			}
11947 			freemsg(mp);
11948 			return;
11949 		default:
11950 			/*
11951 			 * tcp_icmp_err() will process the M_CTL packets.
11952 			 * Non-ICMP packets, if any, will be discarded in
11953 			 * tcp_icmp_err(). We will process the ICMP packet
11954 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
11955 			 * incoming ICMP packet may result in changing
11956 			 * the tcp_mss, which we would need if we have
11957 			 * packets to retransmit.
11958 			 */
11959 			tcp_icmp_error(tcp, mp);
11960 			return;
11961 		}
11962 	}
11963 
11964 	/* No point processing the message if tcp is already closed */
11965 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
11966 		freemsg(mp);
11967 		return;
11968 	}
11969 
11970 	tcp_rput_other(tcp, mp);
11971 }
11972 
11973 
11974 /* The minimum of smoothed mean deviation in RTO calculation. */
11975 #define	TCP_SD_MIN	400
11976 
11977 /*
11978  * Set RTO for this connection.  The formula is from Jacobson and Karels'
11979  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
11980  * are the same as those in Appendix A.2 of that paper.
11981  *
11982  * m = new measurement
11983  * sa = smoothed RTT average (8 * average estimates).
11984  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
11985  */
11986 static void
11987 tcp_set_rto(tcp_t *tcp, clock_t rtt)
11988 {
11989 	long m = TICK_TO_MSEC(rtt);
11990 	clock_t sa = tcp->tcp_rtt_sa;
11991 	clock_t sv = tcp->tcp_rtt_sd;
11992 	clock_t rto;
11993 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11994 
11995 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
11996 	tcp->tcp_rtt_update++;
11997 
11998 	/* tcp_rtt_sa is not 0 means this is a new sample. */
11999 	if (sa != 0) {
12000 		/*
12001 		 * Update average estimator:
12002 		 *	new rtt = 7/8 old rtt + 1/8 Error
12003 		 */
12004 
12005 		/* m is now Error in estimate. */
12006 		m -= sa >> 3;
12007 		if ((sa += m) <= 0) {
12008 			/*
12009 			 * Don't allow the smoothed average to be negative.
12010 			 * We use 0 to denote reinitialization of the
12011 			 * variables.
12012 			 */
12013 			sa = 1;
12014 		}
12015 
12016 		/*
12017 		 * Update deviation estimator:
12018 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
12019 		 */
12020 		if (m < 0)
12021 			m = -m;
12022 		m -= sv >> 2;
12023 		sv += m;
12024 	} else {
12025 		/*
12026 		 * This follows BSD's implementation.  So the reinitialized
12027 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12028 		 * link is bandwidth dominated, doubling the window size
12029 		 * during slow start means doubling the RTT.  We want to be
12030 		 * more conservative when we reinitialize our estimates.  3
12031 		 * is just a convenient number.
12032 		 */
12033 		sa = m << 3;
12034 		sv = m << 1;
12035 	}
12036 	if (sv < TCP_SD_MIN) {
12037 		/*
12038 		 * We do not know that if sa captures the delay ACK
12039 		 * effect as in a long train of segments, a receiver
12040 		 * does not delay its ACKs.  So set the minimum of sv
12041 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12042 		 * of BSD DATO.  That means the minimum of mean
12043 		 * deviation is 100 ms.
12044 		 *
12045 		 */
12046 		sv = TCP_SD_MIN;
12047 	}
12048 	tcp->tcp_rtt_sa = sa;
12049 	tcp->tcp_rtt_sd = sv;
12050 	/*
12051 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12052 	 *
12053 	 * Add tcp_rexmit_interval extra in case of extreme environment
12054 	 * where the algorithm fails to work.  The default value of
12055 	 * tcp_rexmit_interval_extra should be 0.
12056 	 *
12057 	 * As we use a finer grained clock than BSD and update
12058 	 * RTO for every ACKs, add in another .25 of RTT to the
12059 	 * deviation of RTO to accomodate burstiness of 1/4 of
12060 	 * window size.
12061 	 */
12062 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12063 
12064 	if (rto > tcps->tcps_rexmit_interval_max) {
12065 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12066 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12067 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12068 	} else {
12069 		tcp->tcp_rto = rto;
12070 	}
12071 
12072 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12073 	tcp->tcp_timer_backoff = 0;
12074 }
12075 
12076 /*
12077  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12078  * send queue which starts at the given seq. no.
12079  *
12080  * Parameters:
12081  *	tcp_t *tcp: the tcp instance pointer.
12082  *	uint32_t seq: the starting seq. no of the requested segment.
12083  *	int32_t *off: after the execution, *off will be the offset to
12084  *		the returned mblk which points to the requested seq no.
12085  *		It is the caller's responsibility to send in a non-null off.
12086  *
12087  * Return:
12088  *	A mblk_t pointer pointing to the requested segment in send queue.
12089  */
12090 static mblk_t *
12091 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12092 {
12093 	int32_t	cnt;
12094 	mblk_t	*mp;
12095 
12096 	/* Defensive coding.  Make sure we don't send incorrect data. */
12097 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12098 		return (NULL);
12099 
12100 	cnt = seq - tcp->tcp_suna;
12101 	mp = tcp->tcp_xmit_head;
12102 	while (cnt > 0 && mp != NULL) {
12103 		cnt -= mp->b_wptr - mp->b_rptr;
12104 		if (cnt < 0) {
12105 			cnt += mp->b_wptr - mp->b_rptr;
12106 			break;
12107 		}
12108 		mp = mp->b_cont;
12109 	}
12110 	ASSERT(mp != NULL);
12111 	*off = cnt;
12112 	return (mp);
12113 }
12114 
12115 /*
12116  * This function handles all retransmissions if SACK is enabled for this
12117  * connection.  First it calculates how many segments can be retransmitted
12118  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12119  * segments.  A segment is eligible if sack_cnt for that segment is greater
12120  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12121  * all eligible segments, it checks to see if TCP can send some new segments
12122  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12123  *
12124  * Parameters:
12125  *	tcp_t *tcp: the tcp structure of the connection.
12126  *	uint_t *flags: in return, appropriate value will be set for
12127  *	tcp_rput_data().
12128  */
12129 static void
12130 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12131 {
12132 	notsack_blk_t	*notsack_blk;
12133 	int32_t		usable_swnd;
12134 	int32_t		mss;
12135 	uint32_t	seg_len;
12136 	mblk_t		*xmit_mp;
12137 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12138 
12139 	ASSERT(tcp->tcp_sack_info != NULL);
12140 	ASSERT(tcp->tcp_notsack_list != NULL);
12141 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12142 
12143 	/* Defensive coding in case there is a bug... */
12144 	if (tcp->tcp_notsack_list == NULL) {
12145 		return;
12146 	}
12147 	notsack_blk = tcp->tcp_notsack_list;
12148 	mss = tcp->tcp_mss;
12149 
12150 	/*
12151 	 * Limit the num of outstanding data in the network to be
12152 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12153 	 */
12154 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12155 
12156 	/* At least retransmit 1 MSS of data. */
12157 	if (usable_swnd <= 0) {
12158 		usable_swnd = mss;
12159 	}
12160 
12161 	/* Make sure no new RTT samples will be taken. */
12162 	tcp->tcp_csuna = tcp->tcp_snxt;
12163 
12164 	notsack_blk = tcp->tcp_notsack_list;
12165 	while (usable_swnd > 0) {
12166 		mblk_t		*snxt_mp, *tmp_mp;
12167 		tcp_seq		begin = tcp->tcp_sack_snxt;
12168 		tcp_seq		end;
12169 		int32_t		off;
12170 
12171 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12172 			if (SEQ_GT(notsack_blk->end, begin) &&
12173 			    (notsack_blk->sack_cnt >=
12174 			    tcps->tcps_dupack_fast_retransmit)) {
12175 				end = notsack_blk->end;
12176 				if (SEQ_LT(begin, notsack_blk->begin)) {
12177 					begin = notsack_blk->begin;
12178 				}
12179 				break;
12180 			}
12181 		}
12182 		/*
12183 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12184 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12185 		 * set to tcp_cwnd_ssthresh.
12186 		 */
12187 		if (notsack_blk == NULL) {
12188 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12189 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12190 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12191 				ASSERT(tcp->tcp_cwnd > 0);
12192 				return;
12193 			} else {
12194 				usable_swnd = usable_swnd / mss;
12195 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12196 				    MAX(usable_swnd * mss, mss);
12197 				*flags |= TH_XMIT_NEEDED;
12198 				return;
12199 			}
12200 		}
12201 
12202 		/*
12203 		 * Note that we may send more than usable_swnd allows here
12204 		 * because of round off, but no more than 1 MSS of data.
12205 		 */
12206 		seg_len = end - begin;
12207 		if (seg_len > mss)
12208 			seg_len = mss;
12209 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12210 		ASSERT(snxt_mp != NULL);
12211 		/* This should not happen.  Defensive coding again... */
12212 		if (snxt_mp == NULL) {
12213 			return;
12214 		}
12215 
12216 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12217 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12218 		if (xmit_mp == NULL)
12219 			return;
12220 
12221 		usable_swnd -= seg_len;
12222 		tcp->tcp_pipe += seg_len;
12223 		tcp->tcp_sack_snxt = begin + seg_len;
12224 
12225 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12226 
12227 		/*
12228 		 * Update the send timestamp to avoid false retransmission.
12229 		 */
12230 		snxt_mp->b_prev = (mblk_t *)lbolt;
12231 
12232 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12233 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12234 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12235 		/*
12236 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12237 		 * This happens when new data sent during fast recovery is
12238 		 * also lost.  If TCP retransmits those new data, it needs
12239 		 * to extend SACK recover phase to avoid starting another
12240 		 * fast retransmit/recovery unnecessarily.
12241 		 */
12242 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12243 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12244 		}
12245 	}
12246 }
12247 
12248 /*
12249  * This function handles policy checking at TCP level for non-hard_bound/
12250  * detached connections.
12251  */
12252 static boolean_t
12253 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12254     boolean_t secure, boolean_t mctl_present)
12255 {
12256 	ipsec_latch_t *ipl = NULL;
12257 	ipsec_action_t *act = NULL;
12258 	mblk_t *data_mp;
12259 	ipsec_in_t *ii;
12260 	const char *reason;
12261 	kstat_named_t *counter;
12262 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12263 	ipsec_stack_t	*ipss;
12264 	ip_stack_t	*ipst;
12265 
12266 	ASSERT(mctl_present || !secure);
12267 
12268 	ASSERT((ipha == NULL && ip6h != NULL) ||
12269 	    (ip6h == NULL && ipha != NULL));
12270 
12271 	/*
12272 	 * We don't necessarily have an ipsec_in_act action to verify
12273 	 * policy because of assymetrical policy where we have only
12274 	 * outbound policy and no inbound policy (possible with global
12275 	 * policy).
12276 	 */
12277 	if (!secure) {
12278 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12279 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12280 			return (B_TRUE);
12281 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12282 		    "tcp_check_policy", ipha, ip6h, secure,
12283 		    tcps->tcps_netstack);
12284 		ipss = tcps->tcps_netstack->netstack_ipsec;
12285 
12286 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12287 		    DROPPER(ipss, ipds_tcp_clear),
12288 		    &tcps->tcps_dropper);
12289 		return (B_FALSE);
12290 	}
12291 
12292 	/*
12293 	 * We have a secure packet.
12294 	 */
12295 	if (act == NULL) {
12296 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12297 		    "tcp_check_policy", ipha, ip6h, secure,
12298 		    tcps->tcps_netstack);
12299 		ipss = tcps->tcps_netstack->netstack_ipsec;
12300 
12301 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12302 		    DROPPER(ipss, ipds_tcp_secure),
12303 		    &tcps->tcps_dropper);
12304 		return (B_FALSE);
12305 	}
12306 
12307 	/*
12308 	 * XXX This whole routine is currently incorrect.  ipl should
12309 	 * be set to the latch pointer, but is currently not set, so
12310 	 * we initialize it to NULL to avoid picking up random garbage.
12311 	 */
12312 	if (ipl == NULL)
12313 		return (B_TRUE);
12314 
12315 	data_mp = first_mp->b_cont;
12316 
12317 	ii = (ipsec_in_t *)first_mp->b_rptr;
12318 
12319 	ipst = tcps->tcps_netstack->netstack_ip;
12320 
12321 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12322 	    &counter, tcp->tcp_connp)) {
12323 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12324 		return (B_TRUE);
12325 	}
12326 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12327 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12328 	    reason);
12329 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12330 
12331 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12332 	    &tcps->tcps_dropper);
12333 	return (B_FALSE);
12334 }
12335 
12336 /*
12337  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12338  * retransmission after a timeout.
12339  *
12340  * To limit the number of duplicate segments, we limit the number of segment
12341  * to be sent in one time to tcp_snd_burst, the burst variable.
12342  */
12343 static void
12344 tcp_ss_rexmit(tcp_t *tcp)
12345 {
12346 	uint32_t	snxt;
12347 	uint32_t	smax;
12348 	int32_t		win;
12349 	int32_t		mss;
12350 	int32_t		off;
12351 	int32_t		burst = tcp->tcp_snd_burst;
12352 	mblk_t		*snxt_mp;
12353 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12354 
12355 	/*
12356 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12357 	 * all unack'ed segments.
12358 	 */
12359 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12360 		smax = tcp->tcp_rexmit_max;
12361 		snxt = tcp->tcp_rexmit_nxt;
12362 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12363 			snxt = tcp->tcp_suna;
12364 		}
12365 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12366 		win -= snxt - tcp->tcp_suna;
12367 		mss = tcp->tcp_mss;
12368 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12369 
12370 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12371 		    (burst > 0) && (snxt_mp != NULL)) {
12372 			mblk_t	*xmit_mp;
12373 			mblk_t	*old_snxt_mp = snxt_mp;
12374 			uint32_t cnt = mss;
12375 
12376 			if (win < cnt) {
12377 				cnt = win;
12378 			}
12379 			if (SEQ_GT(snxt + cnt, smax)) {
12380 				cnt = smax - snxt;
12381 			}
12382 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12383 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12384 			if (xmit_mp == NULL)
12385 				return;
12386 
12387 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12388 
12389 			snxt += cnt;
12390 			win -= cnt;
12391 			/*
12392 			 * Update the send timestamp to avoid false
12393 			 * retransmission.
12394 			 */
12395 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12396 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12397 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12398 
12399 			tcp->tcp_rexmit_nxt = snxt;
12400 			burst--;
12401 		}
12402 		/*
12403 		 * If we have transmitted all we have at the time
12404 		 * we started the retranmission, we can leave
12405 		 * the rest of the job to tcp_wput_data().  But we
12406 		 * need to check the send window first.  If the
12407 		 * win is not 0, go on with tcp_wput_data().
12408 		 */
12409 		if (SEQ_LT(snxt, smax) || win == 0) {
12410 			return;
12411 		}
12412 	}
12413 	/* Only call tcp_wput_data() if there is data to be sent. */
12414 	if (tcp->tcp_unsent) {
12415 		tcp_wput_data(tcp, NULL, B_FALSE);
12416 	}
12417 }
12418 
12419 /*
12420  * Process all TCP option in SYN segment.  Note that this function should
12421  * be called after tcp_adapt_ire() is called so that the necessary info
12422  * from IRE is already set in the tcp structure.
12423  *
12424  * This function sets up the correct tcp_mss value according to the
12425  * MSS option value and our header size.  It also sets up the window scale
12426  * and timestamp values, and initialize SACK info blocks.  But it does not
12427  * change receive window size after setting the tcp_mss value.  The caller
12428  * should do the appropriate change.
12429  */
12430 void
12431 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12432 {
12433 	int options;
12434 	tcp_opt_t tcpopt;
12435 	uint32_t mss_max;
12436 	char *tmp_tcph;
12437 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12438 
12439 	tcpopt.tcp = NULL;
12440 	options = tcp_parse_options(tcph, &tcpopt);
12441 
12442 	/*
12443 	 * Process MSS option.  Note that MSS option value does not account
12444 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12445 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12446 	 * IPv6.
12447 	 */
12448 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12449 		if (tcp->tcp_ipversion == IPV4_VERSION)
12450 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12451 		else
12452 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12453 	} else {
12454 		if (tcp->tcp_ipversion == IPV4_VERSION)
12455 			mss_max = tcps->tcps_mss_max_ipv4;
12456 		else
12457 			mss_max = tcps->tcps_mss_max_ipv6;
12458 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12459 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12460 		else if (tcpopt.tcp_opt_mss > mss_max)
12461 			tcpopt.tcp_opt_mss = mss_max;
12462 	}
12463 
12464 	/* Process Window Scale option. */
12465 	if (options & TCP_OPT_WSCALE_PRESENT) {
12466 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12467 		tcp->tcp_snd_ws_ok = B_TRUE;
12468 	} else {
12469 		tcp->tcp_snd_ws = B_FALSE;
12470 		tcp->tcp_snd_ws_ok = B_FALSE;
12471 		tcp->tcp_rcv_ws = B_FALSE;
12472 	}
12473 
12474 	/* Process Timestamp option. */
12475 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12476 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12477 		tmp_tcph = (char *)tcp->tcp_tcph;
12478 
12479 		tcp->tcp_snd_ts_ok = B_TRUE;
12480 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12481 		tcp->tcp_last_rcv_lbolt = lbolt64;
12482 		ASSERT(OK_32PTR(tmp_tcph));
12483 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12484 
12485 		/* Fill in our template header with basic timestamp option. */
12486 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12487 		tmp_tcph[0] = TCPOPT_NOP;
12488 		tmp_tcph[1] = TCPOPT_NOP;
12489 		tmp_tcph[2] = TCPOPT_TSTAMP;
12490 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12491 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12492 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12493 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12494 	} else {
12495 		tcp->tcp_snd_ts_ok = B_FALSE;
12496 	}
12497 
12498 	/*
12499 	 * Process SACK options.  If SACK is enabled for this connection,
12500 	 * then allocate the SACK info structure.  Note the following ways
12501 	 * when tcp_snd_sack_ok is set to true.
12502 	 *
12503 	 * For active connection: in tcp_adapt_ire() called in
12504 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12505 	 * is checked.
12506 	 *
12507 	 * For passive connection: in tcp_adapt_ire() called in
12508 	 * tcp_accept_comm().
12509 	 *
12510 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12511 	 * That check makes sure that if we did not send a SACK OK option,
12512 	 * we will not enable SACK for this connection even though the other
12513 	 * side sends us SACK OK option.  For active connection, the SACK
12514 	 * info structure has already been allocated.  So we need to free
12515 	 * it if SACK is disabled.
12516 	 */
12517 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12518 	    (tcp->tcp_snd_sack_ok ||
12519 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12520 		/* This should be true only in the passive case. */
12521 		if (tcp->tcp_sack_info == NULL) {
12522 			ASSERT(TCP_IS_DETACHED(tcp));
12523 			tcp->tcp_sack_info =
12524 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12525 		}
12526 		if (tcp->tcp_sack_info == NULL) {
12527 			tcp->tcp_snd_sack_ok = B_FALSE;
12528 		} else {
12529 			tcp->tcp_snd_sack_ok = B_TRUE;
12530 			if (tcp->tcp_snd_ts_ok) {
12531 				tcp->tcp_max_sack_blk = 3;
12532 			} else {
12533 				tcp->tcp_max_sack_blk = 4;
12534 			}
12535 		}
12536 	} else {
12537 		/*
12538 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12539 		 * no SACK info will be used for this
12540 		 * connection.  This assumes that SACK usage
12541 		 * permission is negotiated.  This may need
12542 		 * to be changed once this is clarified.
12543 		 */
12544 		if (tcp->tcp_sack_info != NULL) {
12545 			ASSERT(tcp->tcp_notsack_list == NULL);
12546 			kmem_cache_free(tcp_sack_info_cache,
12547 			    tcp->tcp_sack_info);
12548 			tcp->tcp_sack_info = NULL;
12549 		}
12550 		tcp->tcp_snd_sack_ok = B_FALSE;
12551 	}
12552 
12553 	/*
12554 	 * Now we know the exact TCP/IP header length, subtract
12555 	 * that from tcp_mss to get our side's MSS.
12556 	 */
12557 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12558 	/*
12559 	 * Here we assume that the other side's header size will be equal to
12560 	 * our header size.  We calculate the real MSS accordingly.  Need to
12561 	 * take into additional stuffs IPsec puts in.
12562 	 *
12563 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12564 	 */
12565 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12566 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12567 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12568 
12569 	/*
12570 	 * Set MSS to the smaller one of both ends of the connection.
12571 	 * We should not have called tcp_mss_set() before, but our
12572 	 * side of the MSS should have been set to a proper value
12573 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12574 	 * STREAM head parameters properly.
12575 	 *
12576 	 * If we have a larger-than-16-bit window but the other side
12577 	 * didn't want to do window scale, tcp_rwnd_set() will take
12578 	 * care of that.
12579 	 */
12580 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12581 }
12582 
12583 /*
12584  * Sends the T_CONN_IND to the listener. The caller calls this
12585  * functions via squeue to get inside the listener's perimeter
12586  * once the 3 way hand shake is done a T_CONN_IND needs to be
12587  * sent. As an optimization, the caller can call this directly
12588  * if listener's perimeter is same as eager's.
12589  */
12590 /* ARGSUSED */
12591 void
12592 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12593 {
12594 	conn_t			*lconnp = (conn_t *)arg;
12595 	tcp_t			*listener = lconnp->conn_tcp;
12596 	tcp_t			*tcp;
12597 	struct T_conn_ind	*conn_ind;
12598 	ipaddr_t 		*addr_cache;
12599 	boolean_t		need_send_conn_ind = B_FALSE;
12600 	tcp_stack_t		*tcps = listener->tcp_tcps;
12601 
12602 	/* retrieve the eager */
12603 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12604 	ASSERT(conn_ind->OPT_offset != 0 &&
12605 	    conn_ind->OPT_length == sizeof (intptr_t));
12606 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12607 	    conn_ind->OPT_length);
12608 
12609 	/*
12610 	 * TLI/XTI applications will get confused by
12611 	 * sending eager as an option since it violates
12612 	 * the option semantics. So remove the eager as
12613 	 * option since TLI/XTI app doesn't need it anyway.
12614 	 */
12615 	if (!TCP_IS_SOCKET(listener)) {
12616 		conn_ind->OPT_length = 0;
12617 		conn_ind->OPT_offset = 0;
12618 	}
12619 	if (listener->tcp_state == TCPS_CLOSED ||
12620 	    TCP_IS_DETACHED(listener)) {
12621 		/*
12622 		 * If listener has closed, it would have caused a
12623 		 * a cleanup/blowoff to happen for the eager. We
12624 		 * just need to return.
12625 		 */
12626 		freemsg(mp);
12627 		return;
12628 	}
12629 
12630 
12631 	/*
12632 	 * if the conn_req_q is full defer passing up the
12633 	 * T_CONN_IND until space is availabe after t_accept()
12634 	 * processing
12635 	 */
12636 	mutex_enter(&listener->tcp_eager_lock);
12637 
12638 	/*
12639 	 * Take the eager out, if it is in the list of droppable eagers
12640 	 * as we are here because the 3W handshake is over.
12641 	 */
12642 	MAKE_UNDROPPABLE(tcp);
12643 
12644 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12645 		tcp_t *tail;
12646 
12647 		/*
12648 		 * The eager already has an extra ref put in tcp_rput_data
12649 		 * so that it stays till accept comes back even though it
12650 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12651 		 */
12652 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12653 		listener->tcp_conn_req_cnt_q0--;
12654 		listener->tcp_conn_req_cnt_q++;
12655 
12656 		/* Move from SYN_RCVD to ESTABLISHED list  */
12657 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12658 		    tcp->tcp_eager_prev_q0;
12659 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12660 		    tcp->tcp_eager_next_q0;
12661 		tcp->tcp_eager_prev_q0 = NULL;
12662 		tcp->tcp_eager_next_q0 = NULL;
12663 
12664 		/*
12665 		 * Insert at end of the queue because sockfs
12666 		 * sends down T_CONN_RES in chronological
12667 		 * order. Leaving the older conn indications
12668 		 * at front of the queue helps reducing search
12669 		 * time.
12670 		 */
12671 		tail = listener->tcp_eager_last_q;
12672 		if (tail != NULL)
12673 			tail->tcp_eager_next_q = tcp;
12674 		else
12675 			listener->tcp_eager_next_q = tcp;
12676 		listener->tcp_eager_last_q = tcp;
12677 		tcp->tcp_eager_next_q = NULL;
12678 		/*
12679 		 * Delay sending up the T_conn_ind until we are
12680 		 * done with the eager. Once we have have sent up
12681 		 * the T_conn_ind, the accept can potentially complete
12682 		 * any time and release the refhold we have on the eager.
12683 		 */
12684 		need_send_conn_ind = B_TRUE;
12685 	} else {
12686 		/*
12687 		 * Defer connection on q0 and set deferred
12688 		 * connection bit true
12689 		 */
12690 		tcp->tcp_conn_def_q0 = B_TRUE;
12691 
12692 		/* take tcp out of q0 ... */
12693 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12694 		    tcp->tcp_eager_next_q0;
12695 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12696 		    tcp->tcp_eager_prev_q0;
12697 
12698 		/* ... and place it at the end of q0 */
12699 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12700 		tcp->tcp_eager_next_q0 = listener;
12701 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12702 		listener->tcp_eager_prev_q0 = tcp;
12703 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12704 	}
12705 
12706 	/* we have timed out before */
12707 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12708 		tcp->tcp_syn_rcvd_timeout = 0;
12709 		listener->tcp_syn_rcvd_timeout--;
12710 		if (listener->tcp_syn_defense &&
12711 		    listener->tcp_syn_rcvd_timeout <=
12712 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12713 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12714 		    listener->tcp_last_rcv_lbolt)) {
12715 			/*
12716 			 * Turn off the defense mode if we
12717 			 * believe the SYN attack is over.
12718 			 */
12719 			listener->tcp_syn_defense = B_FALSE;
12720 			if (listener->tcp_ip_addr_cache) {
12721 				kmem_free((void *)listener->tcp_ip_addr_cache,
12722 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12723 				listener->tcp_ip_addr_cache = NULL;
12724 			}
12725 		}
12726 	}
12727 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12728 	if (addr_cache != NULL) {
12729 		/*
12730 		 * We have finished a 3-way handshake with this
12731 		 * remote host. This proves the IP addr is good.
12732 		 * Cache it!
12733 		 */
12734 		addr_cache[IP_ADDR_CACHE_HASH(
12735 		    tcp->tcp_remote)] = tcp->tcp_remote;
12736 	}
12737 	mutex_exit(&listener->tcp_eager_lock);
12738 	if (need_send_conn_ind)
12739 		tcp_ulp_newconn(lconnp, tcp->tcp_connp, mp);
12740 }
12741 
12742 /*
12743  * Send the newconn notification to ulp. The eager is blown off if the
12744  * notification fails.
12745  */
12746 static void
12747 tcp_ulp_newconn(conn_t *lconnp, conn_t *econnp, mblk_t *mp)
12748 {
12749 	if (IPCL_IS_NONSTR(lconnp)) {
12750 		cred_t	*cr;
12751 		pid_t	cpid;
12752 
12753 		cr = msg_getcred(mp, &cpid);
12754 
12755 		ASSERT(econnp->conn_tcp->tcp_listener == lconnp->conn_tcp);
12756 		ASSERT(econnp->conn_tcp->tcp_saved_listener ==
12757 		    lconnp->conn_tcp);
12758 
12759 		/* Keep the message around in case of a fallback to TPI */
12760 		econnp->conn_tcp->tcp_conn.tcp_eager_conn_ind = mp;
12761 
12762 		/*
12763 		 * Notify the ULP about the newconn. It is guaranteed that no
12764 		 * tcp_accept() call will be made for the eager if the
12765 		 * notification fails, so it's safe to blow it off in that
12766 		 * case.
12767 		 *
12768 		 * The upper handle will be assigned when tcp_accept() is
12769 		 * called.
12770 		 */
12771 		if ((*lconnp->conn_upcalls->su_newconn)
12772 		    (lconnp->conn_upper_handle,
12773 		    (sock_lower_handle_t)econnp,
12774 		    &sock_tcp_downcalls, cr, cpid,
12775 		    &econnp->conn_upcalls) == NULL) {
12776 			/* Failed to allocate a socket */
12777 			BUMP_MIB(&lconnp->conn_tcp->tcp_tcps->tcps_mib,
12778 			    tcpEstabResets);
12779 			(void) tcp_eager_blowoff(lconnp->conn_tcp,
12780 			    econnp->conn_tcp->tcp_conn_req_seqnum);
12781 		}
12782 	} else {
12783 		putnext(lconnp->conn_tcp->tcp_rq, mp);
12784 	}
12785 }
12786 
12787 mblk_t *
12788 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12789     uint_t *ifindexp, ip6_pkt_t *ippp)
12790 {
12791 	ip_pktinfo_t	*pinfo;
12792 	ip6_t		*ip6h;
12793 	uchar_t		*rptr;
12794 	mblk_t		*first_mp = mp;
12795 	boolean_t	mctl_present = B_FALSE;
12796 	uint_t 		ifindex = 0;
12797 	ip6_pkt_t	ipp;
12798 	uint_t		ipvers;
12799 	uint_t		ip_hdr_len;
12800 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12801 
12802 	rptr = mp->b_rptr;
12803 	ASSERT(OK_32PTR(rptr));
12804 	ASSERT(tcp != NULL);
12805 	ipp.ipp_fields = 0;
12806 
12807 	switch DB_TYPE(mp) {
12808 	case M_CTL:
12809 		mp = mp->b_cont;
12810 		if (mp == NULL) {
12811 			freemsg(first_mp);
12812 			return (NULL);
12813 		}
12814 		if (DB_TYPE(mp) != M_DATA) {
12815 			freemsg(first_mp);
12816 			return (NULL);
12817 		}
12818 		mctl_present = B_TRUE;
12819 		break;
12820 	case M_DATA:
12821 		break;
12822 	default:
12823 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12824 		freemsg(mp);
12825 		return (NULL);
12826 	}
12827 	ipvers = IPH_HDR_VERSION(rptr);
12828 	if (ipvers == IPV4_VERSION) {
12829 		if (tcp == NULL) {
12830 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
12831 			goto done;
12832 		}
12833 
12834 		ipp.ipp_fields |= IPPF_HOPLIMIT;
12835 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
12836 
12837 		/*
12838 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
12839 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
12840 		 */
12841 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
12842 		    mctl_present) {
12843 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
12844 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
12845 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
12846 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
12847 				ipp.ipp_fields |= IPPF_IFINDEX;
12848 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
12849 				ifindex = pinfo->ip_pkt_ifindex;
12850 			}
12851 			freeb(first_mp);
12852 			mctl_present = B_FALSE;
12853 		}
12854 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
12855 	} else {
12856 		ip6h = (ip6_t *)rptr;
12857 
12858 		ASSERT(ipvers == IPV6_VERSION);
12859 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
12860 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
12861 		ipp.ipp_hoplimit = ip6h->ip6_hops;
12862 
12863 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
12864 			uint8_t	nexthdrp;
12865 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
12866 
12867 			/* Look for ifindex information */
12868 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
12869 				ip6i_t *ip6i = (ip6i_t *)ip6h;
12870 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
12871 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12872 					freemsg(first_mp);
12873 					return (NULL);
12874 				}
12875 
12876 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
12877 					ASSERT(ip6i->ip6i_ifindex != 0);
12878 					ipp.ipp_fields |= IPPF_IFINDEX;
12879 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
12880 					ifindex = ip6i->ip6i_ifindex;
12881 				}
12882 				rptr = (uchar_t *)&ip6i[1];
12883 				mp->b_rptr = rptr;
12884 				if (rptr == mp->b_wptr) {
12885 					mblk_t *mp1;
12886 					mp1 = mp->b_cont;
12887 					freeb(mp);
12888 					mp = mp1;
12889 					rptr = mp->b_rptr;
12890 				}
12891 				if (MBLKL(mp) < IPV6_HDR_LEN +
12892 				    sizeof (tcph_t)) {
12893 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12894 					freemsg(first_mp);
12895 					return (NULL);
12896 				}
12897 				ip6h = (ip6_t *)rptr;
12898 			}
12899 
12900 			/*
12901 			 * Find any potentially interesting extension headers
12902 			 * as well as the length of the IPv6 + extension
12903 			 * headers.
12904 			 */
12905 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
12906 			/* Verify if this is a TCP packet */
12907 			if (nexthdrp != IPPROTO_TCP) {
12908 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
12909 				freemsg(first_mp);
12910 				return (NULL);
12911 			}
12912 		} else {
12913 			ip_hdr_len = IPV6_HDR_LEN;
12914 		}
12915 	}
12916 
12917 done:
12918 	if (ipversp != NULL)
12919 		*ipversp = ipvers;
12920 	if (ip_hdr_lenp != NULL)
12921 		*ip_hdr_lenp = ip_hdr_len;
12922 	if (ippp != NULL)
12923 		*ippp = ipp;
12924 	if (ifindexp != NULL)
12925 		*ifindexp = ifindex;
12926 	if (mctl_present) {
12927 		freeb(first_mp);
12928 	}
12929 	return (mp);
12930 }
12931 
12932 /*
12933  * Handle M_DATA messages from IP. Its called directly from IP via
12934  * squeue for AF_INET type sockets fast path. No M_CTL are expected
12935  * in this path.
12936  *
12937  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
12938  * v4 and v6), we are called through tcp_input() and a M_CTL can
12939  * be present for options but tcp_find_pktinfo() deals with it. We
12940  * only expect M_DATA packets after tcp_find_pktinfo() is done.
12941  *
12942  * The first argument is always the connp/tcp to which the mp belongs.
12943  * There are no exceptions to this rule. The caller has already put
12944  * a reference on this connp/tcp and once tcp_rput_data() returns,
12945  * the squeue will do the refrele.
12946  *
12947  * The TH_SYN for the listener directly go to tcp_conn_request via
12948  * squeue.
12949  *
12950  * sqp: NULL = recursive, sqp != NULL means called from squeue
12951  */
12952 void
12953 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
12954 {
12955 	int32_t		bytes_acked;
12956 	int32_t		gap;
12957 	mblk_t		*mp1;
12958 	uint_t		flags;
12959 	uint32_t	new_swnd = 0;
12960 	uchar_t		*iphdr;
12961 	uchar_t		*rptr;
12962 	int32_t		rgap;
12963 	uint32_t	seg_ack;
12964 	int		seg_len;
12965 	uint_t		ip_hdr_len;
12966 	uint32_t	seg_seq;
12967 	tcph_t		*tcph;
12968 	int		urp;
12969 	tcp_opt_t	tcpopt;
12970 	uint_t		ipvers;
12971 	ip6_pkt_t	ipp;
12972 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
12973 	uint32_t	cwnd;
12974 	uint32_t	add;
12975 	int		npkt;
12976 	int		mss;
12977 	conn_t		*connp = (conn_t *)arg;
12978 	squeue_t	*sqp = (squeue_t *)arg2;
12979 	tcp_t		*tcp = connp->conn_tcp;
12980 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12981 
12982 	/*
12983 	 * RST from fused tcp loopback peer should trigger an unfuse.
12984 	 */
12985 	if (tcp->tcp_fused) {
12986 		TCP_STAT(tcps, tcp_fusion_aborted);
12987 		tcp_unfuse(tcp);
12988 	}
12989 
12990 	iphdr = mp->b_rptr;
12991 	rptr = mp->b_rptr;
12992 	ASSERT(OK_32PTR(rptr));
12993 
12994 	/*
12995 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
12996 	 * processing here. For rest call tcp_find_pktinfo to fill up the
12997 	 * necessary information.
12998 	 */
12999 	if (IPCL_IS_TCP4(connp)) {
13000 		ipvers = IPV4_VERSION;
13001 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13002 	} else {
13003 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
13004 		    NULL, &ipp);
13005 		if (mp == NULL) {
13006 			TCP_STAT(tcps, tcp_rput_v6_error);
13007 			return;
13008 		}
13009 		iphdr = mp->b_rptr;
13010 		rptr = mp->b_rptr;
13011 	}
13012 	ASSERT(DB_TYPE(mp) == M_DATA);
13013 	ASSERT(mp->b_next == NULL);
13014 
13015 	tcph = (tcph_t *)&rptr[ip_hdr_len];
13016 	seg_seq = ABE32_TO_U32(tcph->th_seq);
13017 	seg_ack = ABE32_TO_U32(tcph->th_ack);
13018 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
13019 	seg_len = (int)(mp->b_wptr - rptr) -
13020 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
13021 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
13022 		do {
13023 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13024 			    (uintptr_t)INT_MAX);
13025 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
13026 		} while ((mp1 = mp1->b_cont) != NULL &&
13027 		    mp1->b_datap->db_type == M_DATA);
13028 	}
13029 
13030 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
13031 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
13032 		    seg_len, tcph);
13033 		return;
13034 	}
13035 
13036 	if (sqp != NULL) {
13037 		/*
13038 		 * This is the correct place to update tcp_last_recv_time. Note
13039 		 * that it is also updated for tcp structure that belongs to
13040 		 * global and listener queues which do not really need updating.
13041 		 * But that should not cause any harm.  And it is updated for
13042 		 * all kinds of incoming segments, not only for data segments.
13043 		 */
13044 		tcp->tcp_last_recv_time = lbolt;
13045 	}
13046 
13047 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13048 
13049 	BUMP_LOCAL(tcp->tcp_ibsegs);
13050 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13051 
13052 	if ((flags & TH_URG) && sqp != NULL) {
13053 		/*
13054 		 * TCP can't handle urgent pointers that arrive before
13055 		 * the connection has been accept()ed since it can't
13056 		 * buffer OOB data.  Discard segment if this happens.
13057 		 *
13058 		 * We can't just rely on a non-null tcp_listener to indicate
13059 		 * that the accept() has completed since unlinking of the
13060 		 * eager and completion of the accept are not atomic.
13061 		 * tcp_detached, when it is not set (B_FALSE) indicates
13062 		 * that the accept() has completed.
13063 		 *
13064 		 * Nor can it reassemble urgent pointers, so discard
13065 		 * if it's not the next segment expected.
13066 		 *
13067 		 * Otherwise, collapse chain into one mblk (discard if
13068 		 * that fails).  This makes sure the headers, retransmitted
13069 		 * data, and new data all are in the same mblk.
13070 		 */
13071 		ASSERT(mp != NULL);
13072 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13073 			freemsg(mp);
13074 			return;
13075 		}
13076 		/* Update pointers into message */
13077 		iphdr = rptr = mp->b_rptr;
13078 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13079 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13080 			/*
13081 			 * Since we can't handle any data with this urgent
13082 			 * pointer that is out of sequence, we expunge
13083 			 * the data.  This allows us to still register
13084 			 * the urgent mark and generate the M_PCSIG,
13085 			 * which we can do.
13086 			 */
13087 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13088 			seg_len = 0;
13089 		}
13090 	}
13091 
13092 	switch (tcp->tcp_state) {
13093 	case TCPS_SYN_SENT:
13094 		if (flags & TH_ACK) {
13095 			/*
13096 			 * Note that our stack cannot send data before a
13097 			 * connection is established, therefore the
13098 			 * following check is valid.  Otherwise, it has
13099 			 * to be changed.
13100 			 */
13101 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13102 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13103 				freemsg(mp);
13104 				if (flags & TH_RST)
13105 					return;
13106 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13107 				    tcp, seg_ack, 0, TH_RST);
13108 				return;
13109 			}
13110 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13111 		}
13112 		if (flags & TH_RST) {
13113 			freemsg(mp);
13114 			if (flags & TH_ACK)
13115 				(void) tcp_clean_death(tcp,
13116 				    ECONNREFUSED, 13);
13117 			return;
13118 		}
13119 		if (!(flags & TH_SYN)) {
13120 			freemsg(mp);
13121 			return;
13122 		}
13123 
13124 		/* Process all TCP options. */
13125 		tcp_process_options(tcp, tcph);
13126 		/*
13127 		 * The following changes our rwnd to be a multiple of the
13128 		 * MIN(peer MSS, our MSS) for performance reason.
13129 		 */
13130 		(void) tcp_rwnd_set(tcp,
13131 		    MSS_ROUNDUP(tcp->tcp_recv_hiwater, tcp->tcp_mss));
13132 
13133 		/* Is the other end ECN capable? */
13134 		if (tcp->tcp_ecn_ok) {
13135 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13136 				tcp->tcp_ecn_ok = B_FALSE;
13137 			}
13138 		}
13139 		/*
13140 		 * Clear ECN flags because it may interfere with later
13141 		 * processing.
13142 		 */
13143 		flags &= ~(TH_ECE|TH_CWR);
13144 
13145 		tcp->tcp_irs = seg_seq;
13146 		tcp->tcp_rack = seg_seq;
13147 		tcp->tcp_rnxt = seg_seq + 1;
13148 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13149 		if (!TCP_IS_DETACHED(tcp)) {
13150 			/* Allocate room for SACK options if needed. */
13151 			if (tcp->tcp_snd_sack_ok) {
13152 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13153 				    tcp->tcp_hdr_len +
13154 				    TCPOPT_MAX_SACK_LEN +
13155 				    (tcp->tcp_loopback ? 0 :
13156 				    tcps->tcps_wroff_xtra));
13157 			} else {
13158 				(void) proto_set_tx_wroff(tcp->tcp_rq, connp,
13159 				    tcp->tcp_hdr_len +
13160 				    (tcp->tcp_loopback ? 0 :
13161 				    tcps->tcps_wroff_xtra));
13162 			}
13163 		}
13164 		if (flags & TH_ACK) {
13165 			/*
13166 			 * If we can't get the confirmation upstream, pretend
13167 			 * we didn't even see this one.
13168 			 *
13169 			 * XXX: how can we pretend we didn't see it if we
13170 			 * have updated rnxt et. al.
13171 			 *
13172 			 * For loopback we defer sending up the T_CONN_CON
13173 			 * until after some checks below.
13174 			 */
13175 			mp1 = NULL;
13176 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13177 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13178 				freemsg(mp);
13179 				return;
13180 			}
13181 			/* SYN was acked - making progress */
13182 			if (tcp->tcp_ipversion == IPV6_VERSION)
13183 				tcp->tcp_ip_forward_progress = B_TRUE;
13184 
13185 			/* One for the SYN */
13186 			tcp->tcp_suna = tcp->tcp_iss + 1;
13187 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13188 			tcp->tcp_state = TCPS_ESTABLISHED;
13189 
13190 			/*
13191 			 * If SYN was retransmitted, need to reset all
13192 			 * retransmission info.  This is because this
13193 			 * segment will be treated as a dup ACK.
13194 			 */
13195 			if (tcp->tcp_rexmit) {
13196 				tcp->tcp_rexmit = B_FALSE;
13197 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13198 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13199 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13200 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13201 				tcp->tcp_ms_we_have_waited = 0;
13202 
13203 				/*
13204 				 * Set tcp_cwnd back to 1 MSS, per
13205 				 * recommendation from
13206 				 * draft-floyd-incr-init-win-01.txt,
13207 				 * Increasing TCP's Initial Window.
13208 				 */
13209 				tcp->tcp_cwnd = tcp->tcp_mss;
13210 			}
13211 
13212 			tcp->tcp_swl1 = seg_seq;
13213 			tcp->tcp_swl2 = seg_ack;
13214 
13215 			new_swnd = BE16_TO_U16(tcph->th_win);
13216 			tcp->tcp_swnd = new_swnd;
13217 			if (new_swnd > tcp->tcp_max_swnd)
13218 				tcp->tcp_max_swnd = new_swnd;
13219 
13220 			/*
13221 			 * Always send the three-way handshake ack immediately
13222 			 * in order to make the connection complete as soon as
13223 			 * possible on the accepting host.
13224 			 */
13225 			flags |= TH_ACK_NEEDED;
13226 
13227 			/*
13228 			 * Special case for loopback.  At this point we have
13229 			 * received SYN-ACK from the remote endpoint.  In
13230 			 * order to ensure that both endpoints reach the
13231 			 * fused state prior to any data exchange, the final
13232 			 * ACK needs to be sent before we indicate T_CONN_CON
13233 			 * to the module upstream.
13234 			 */
13235 			if (tcp->tcp_loopback) {
13236 				mblk_t *ack_mp;
13237 
13238 				ASSERT(!tcp->tcp_unfusable);
13239 				ASSERT(mp1 != NULL);
13240 				/*
13241 				 * For loopback, we always get a pure SYN-ACK
13242 				 * and only need to send back the final ACK
13243 				 * with no data (this is because the other
13244 				 * tcp is ours and we don't do T/TCP).  This
13245 				 * final ACK triggers the passive side to
13246 				 * perform fusion in ESTABLISHED state.
13247 				 */
13248 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13249 					if (tcp->tcp_ack_tid != 0) {
13250 						(void) TCP_TIMER_CANCEL(tcp,
13251 						    tcp->tcp_ack_tid);
13252 						tcp->tcp_ack_tid = 0;
13253 					}
13254 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13255 					BUMP_LOCAL(tcp->tcp_obsegs);
13256 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13257 
13258 					if (!IPCL_IS_NONSTR(connp)) {
13259 						/* Send up T_CONN_CON */
13260 						putnext(tcp->tcp_rq, mp1);
13261 					} else {
13262 						cred_t	*cr;
13263 						pid_t	cpid;
13264 
13265 						cr = msg_getcred(mp1, &cpid);
13266 						(*connp->conn_upcalls->
13267 						    su_connected)
13268 						    (connp->conn_upper_handle,
13269 						    tcp->tcp_connid, cr, cpid);
13270 						freemsg(mp1);
13271 					}
13272 
13273 					freemsg(mp);
13274 					return;
13275 				}
13276 				/*
13277 				 * Forget fusion; we need to handle more
13278 				 * complex cases below.  Send the deferred
13279 				 * T_CONN_CON message upstream and proceed
13280 				 * as usual.  Mark this tcp as not capable
13281 				 * of fusion.
13282 				 */
13283 				TCP_STAT(tcps, tcp_fusion_unfusable);
13284 				tcp->tcp_unfusable = B_TRUE;
13285 				if (!IPCL_IS_NONSTR(connp)) {
13286 					putnext(tcp->tcp_rq, mp1);
13287 				} else {
13288 					cred_t	*cr;
13289 					pid_t	cpid;
13290 
13291 					cr = msg_getcred(mp1, &cpid);
13292 					(*connp->conn_upcalls->su_connected)
13293 					    (connp->conn_upper_handle,
13294 					    tcp->tcp_connid, cr, cpid);
13295 					freemsg(mp1);
13296 				}
13297 			}
13298 
13299 			/*
13300 			 * Check to see if there is data to be sent.  If
13301 			 * yes, set the transmit flag.  Then check to see
13302 			 * if received data processing needs to be done.
13303 			 * If not, go straight to xmit_check.  This short
13304 			 * cut is OK as we don't support T/TCP.
13305 			 */
13306 			if (tcp->tcp_unsent)
13307 				flags |= TH_XMIT_NEEDED;
13308 
13309 			if (seg_len == 0 && !(flags & TH_URG)) {
13310 				freemsg(mp);
13311 				goto xmit_check;
13312 			}
13313 
13314 			flags &= ~TH_SYN;
13315 			seg_seq++;
13316 			break;
13317 		}
13318 		tcp->tcp_state = TCPS_SYN_RCVD;
13319 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13320 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13321 		if (mp1) {
13322 			/*
13323 			 * See comment in tcp_conn_request() for why we use
13324 			 * the open() time pid here.
13325 			 */
13326 			DB_CPID(mp1) = tcp->tcp_cpid;
13327 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13328 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13329 		}
13330 		freemsg(mp);
13331 		return;
13332 	case TCPS_SYN_RCVD:
13333 		if (flags & TH_ACK) {
13334 			/*
13335 			 * In this state, a SYN|ACK packet is either bogus
13336 			 * because the other side must be ACKing our SYN which
13337 			 * indicates it has seen the ACK for their SYN and
13338 			 * shouldn't retransmit it or we're crossing SYNs
13339 			 * on active open.
13340 			 */
13341 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13342 				freemsg(mp);
13343 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13344 				    tcp, seg_ack, 0, TH_RST);
13345 				return;
13346 			}
13347 			/*
13348 			 * NOTE: RFC 793 pg. 72 says this should be
13349 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13350 			 * but that would mean we have an ack that ignored
13351 			 * our SYN.
13352 			 */
13353 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13354 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13355 				freemsg(mp);
13356 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13357 				    tcp, seg_ack, 0, TH_RST);
13358 				return;
13359 			}
13360 		}
13361 		break;
13362 	case TCPS_LISTEN:
13363 		/*
13364 		 * Only a TLI listener can come through this path when a
13365 		 * acceptor is going back to be a listener and a packet
13366 		 * for the acceptor hits the classifier. For a socket
13367 		 * listener, this can never happen because a listener
13368 		 * can never accept connection on itself and hence a
13369 		 * socket acceptor can not go back to being a listener.
13370 		 */
13371 		ASSERT(!TCP_IS_SOCKET(tcp));
13372 		/*FALLTHRU*/
13373 	case TCPS_CLOSED:
13374 	case TCPS_BOUND: {
13375 		conn_t	*new_connp;
13376 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13377 
13378 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13379 		if (new_connp != NULL) {
13380 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13381 			return;
13382 		}
13383 		/* We failed to classify. For now just drop the packet */
13384 		freemsg(mp);
13385 		return;
13386 	}
13387 	case TCPS_IDLE:
13388 		/*
13389 		 * Handle the case where the tcp_clean_death() has happened
13390 		 * on a connection (application hasn't closed yet) but a packet
13391 		 * was already queued on squeue before tcp_clean_death()
13392 		 * was processed. Calling tcp_clean_death() twice on same
13393 		 * connection can result in weird behaviour.
13394 		 */
13395 		freemsg(mp);
13396 		return;
13397 	default:
13398 		break;
13399 	}
13400 
13401 	/*
13402 	 * Already on the correct queue/perimeter.
13403 	 * If this is a detached connection and not an eager
13404 	 * connection hanging off a listener then new data
13405 	 * (past the FIN) will cause a reset.
13406 	 * We do a special check here where it
13407 	 * is out of the main line, rather than check
13408 	 * if we are detached every time we see new
13409 	 * data down below.
13410 	 */
13411 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13412 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13413 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13414 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13415 
13416 		freemsg(mp);
13417 		/*
13418 		 * This could be an SSL closure alert. We're detached so just
13419 		 * acknowledge it this last time.
13420 		 */
13421 		if (tcp->tcp_kssl_ctx != NULL) {
13422 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13423 			tcp->tcp_kssl_ctx = NULL;
13424 
13425 			tcp->tcp_rnxt += seg_len;
13426 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13427 			flags |= TH_ACK_NEEDED;
13428 			goto ack_check;
13429 		}
13430 
13431 		tcp_xmit_ctl("new data when detached", tcp,
13432 		    tcp->tcp_snxt, 0, TH_RST);
13433 		(void) tcp_clean_death(tcp, EPROTO, 12);
13434 		return;
13435 	}
13436 
13437 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13438 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13439 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13440 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13441 
13442 	if (tcp->tcp_snd_ts_ok) {
13443 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13444 			/*
13445 			 * This segment is not acceptable.
13446 			 * Drop it and send back an ACK.
13447 			 */
13448 			freemsg(mp);
13449 			flags |= TH_ACK_NEEDED;
13450 			goto ack_check;
13451 		}
13452 	} else if (tcp->tcp_snd_sack_ok) {
13453 		ASSERT(tcp->tcp_sack_info != NULL);
13454 		tcpopt.tcp = tcp;
13455 		/*
13456 		 * SACK info in already updated in tcp_parse_options.  Ignore
13457 		 * all other TCP options...
13458 		 */
13459 		(void) tcp_parse_options(tcph, &tcpopt);
13460 	}
13461 try_again:;
13462 	mss = tcp->tcp_mss;
13463 	gap = seg_seq - tcp->tcp_rnxt;
13464 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13465 	/*
13466 	 * gap is the amount of sequence space between what we expect to see
13467 	 * and what we got for seg_seq.  A positive value for gap means
13468 	 * something got lost.  A negative value means we got some old stuff.
13469 	 */
13470 	if (gap < 0) {
13471 		/* Old stuff present.  Is the SYN in there? */
13472 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13473 		    (seg_len != 0)) {
13474 			flags &= ~TH_SYN;
13475 			seg_seq++;
13476 			urp--;
13477 			/* Recompute the gaps after noting the SYN. */
13478 			goto try_again;
13479 		}
13480 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13481 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13482 		    (seg_len > -gap ? -gap : seg_len));
13483 		/* Remove the old stuff from seg_len. */
13484 		seg_len += gap;
13485 		/*
13486 		 * Anything left?
13487 		 * Make sure to check for unack'd FIN when rest of data
13488 		 * has been previously ack'd.
13489 		 */
13490 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13491 			/*
13492 			 * Resets are only valid if they lie within our offered
13493 			 * window.  If the RST bit is set, we just ignore this
13494 			 * segment.
13495 			 */
13496 			if (flags & TH_RST) {
13497 				freemsg(mp);
13498 				return;
13499 			}
13500 
13501 			/*
13502 			 * The arriving of dup data packets indicate that we
13503 			 * may have postponed an ack for too long, or the other
13504 			 * side's RTT estimate is out of shape. Start acking
13505 			 * more often.
13506 			 */
13507 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13508 			    tcp->tcp_rack_cnt >= 1 &&
13509 			    tcp->tcp_rack_abs_max > 2) {
13510 				tcp->tcp_rack_abs_max--;
13511 			}
13512 			tcp->tcp_rack_cur_max = 1;
13513 
13514 			/*
13515 			 * This segment is "unacceptable".  None of its
13516 			 * sequence space lies within our advertized window.
13517 			 *
13518 			 * Adjust seg_len to the original value for tracing.
13519 			 */
13520 			seg_len -= gap;
13521 			if (tcp->tcp_debug) {
13522 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13523 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13524 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13525 				    "seg_len %d, rnxt %u, snxt %u, %s",
13526 				    gap, rgap, flags, seg_seq, seg_ack,
13527 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13528 				    tcp_display(tcp, NULL,
13529 				    DISP_ADDR_AND_PORT));
13530 			}
13531 
13532 			/*
13533 			 * Arrange to send an ACK in response to the
13534 			 * unacceptable segment per RFC 793 page 69. There
13535 			 * is only one small difference between ours and the
13536 			 * acceptability test in the RFC - we accept ACK-only
13537 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13538 			 * will be generated.
13539 			 *
13540 			 * Note that we have to ACK an ACK-only packet at least
13541 			 * for stacks that send 0-length keep-alives with
13542 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13543 			 * section 4.2.3.6. As long as we don't ever generate
13544 			 * an unacceptable packet in response to an incoming
13545 			 * packet that is unacceptable, it should not cause
13546 			 * "ACK wars".
13547 			 */
13548 			flags |=  TH_ACK_NEEDED;
13549 
13550 			/*
13551 			 * Continue processing this segment in order to use the
13552 			 * ACK information it contains, but skip all other
13553 			 * sequence-number processing.	Processing the ACK
13554 			 * information is necessary in order to
13555 			 * re-synchronize connections that may have lost
13556 			 * synchronization.
13557 			 *
13558 			 * We clear seg_len and flag fields related to
13559 			 * sequence number processing as they are not
13560 			 * to be trusted for an unacceptable segment.
13561 			 */
13562 			seg_len = 0;
13563 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13564 			goto process_ack;
13565 		}
13566 
13567 		/* Fix seg_seq, and chew the gap off the front. */
13568 		seg_seq = tcp->tcp_rnxt;
13569 		urp += gap;
13570 		do {
13571 			mblk_t	*mp2;
13572 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13573 			    (uintptr_t)UINT_MAX);
13574 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13575 			if (gap > 0) {
13576 				mp->b_rptr = mp->b_wptr - gap;
13577 				break;
13578 			}
13579 			mp2 = mp;
13580 			mp = mp->b_cont;
13581 			freeb(mp2);
13582 		} while (gap < 0);
13583 		/*
13584 		 * If the urgent data has already been acknowledged, we
13585 		 * should ignore TH_URG below
13586 		 */
13587 		if (urp < 0)
13588 			flags &= ~TH_URG;
13589 	}
13590 	/*
13591 	 * rgap is the amount of stuff received out of window.  A negative
13592 	 * value is the amount out of window.
13593 	 */
13594 	if (rgap < 0) {
13595 		mblk_t	*mp2;
13596 
13597 		if (tcp->tcp_rwnd == 0) {
13598 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13599 		} else {
13600 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13601 			UPDATE_MIB(&tcps->tcps_mib,
13602 			    tcpInDataPastWinBytes, -rgap);
13603 		}
13604 
13605 		/*
13606 		 * seg_len does not include the FIN, so if more than
13607 		 * just the FIN is out of window, we act like we don't
13608 		 * see it.  (If just the FIN is out of window, rgap
13609 		 * will be zero and we will go ahead and acknowledge
13610 		 * the FIN.)
13611 		 */
13612 		flags &= ~TH_FIN;
13613 
13614 		/* Fix seg_len and make sure there is something left. */
13615 		seg_len += rgap;
13616 		if (seg_len <= 0) {
13617 			/*
13618 			 * Resets are only valid if they lie within our offered
13619 			 * window.  If the RST bit is set, we just ignore this
13620 			 * segment.
13621 			 */
13622 			if (flags & TH_RST) {
13623 				freemsg(mp);
13624 				return;
13625 			}
13626 
13627 			/* Per RFC 793, we need to send back an ACK. */
13628 			flags |= TH_ACK_NEEDED;
13629 
13630 			/*
13631 			 * Send SIGURG as soon as possible i.e. even
13632 			 * if the TH_URG was delivered in a window probe
13633 			 * packet (which will be unacceptable).
13634 			 *
13635 			 * We generate a signal if none has been generated
13636 			 * for this connection or if this is a new urgent
13637 			 * byte. Also send a zero-length "unmarked" message
13638 			 * to inform SIOCATMARK that this is not the mark.
13639 			 *
13640 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13641 			 * is sent up. This plus the check for old data
13642 			 * (gap >= 0) handles the wraparound of the sequence
13643 			 * number space without having to always track the
13644 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13645 			 * this max in its rcv_up variable).
13646 			 *
13647 			 * This prevents duplicate SIGURGS due to a "late"
13648 			 * zero-window probe when the T_EXDATA_IND has already
13649 			 * been sent up.
13650 			 */
13651 			if ((flags & TH_URG) &&
13652 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13653 			    tcp->tcp_urp_last))) {
13654 				if (IPCL_IS_NONSTR(connp)) {
13655 					if (!TCP_IS_DETACHED(tcp)) {
13656 						(*connp->conn_upcalls->
13657 						    su_signal_oob)
13658 						    (connp->conn_upper_handle,
13659 						    urp);
13660 					}
13661 				} else {
13662 					mp1 = allocb(0, BPRI_MED);
13663 					if (mp1 == NULL) {
13664 						freemsg(mp);
13665 						return;
13666 					}
13667 					if (!TCP_IS_DETACHED(tcp) &&
13668 					    !putnextctl1(tcp->tcp_rq,
13669 					    M_PCSIG, SIGURG)) {
13670 						/* Try again on the rexmit. */
13671 						freemsg(mp1);
13672 						freemsg(mp);
13673 						return;
13674 					}
13675 					/*
13676 					 * If the next byte would be the mark
13677 					 * then mark with MARKNEXT else mark
13678 					 * with NOTMARKNEXT.
13679 					 */
13680 					if (gap == 0 && urp == 0)
13681 						mp1->b_flag |= MSGMARKNEXT;
13682 					else
13683 						mp1->b_flag |= MSGNOTMARKNEXT;
13684 					freemsg(tcp->tcp_urp_mark_mp);
13685 					tcp->tcp_urp_mark_mp = mp1;
13686 					flags |= TH_SEND_URP_MARK;
13687 				}
13688 				tcp->tcp_urp_last_valid = B_TRUE;
13689 				tcp->tcp_urp_last = urp + seg_seq;
13690 			}
13691 			/*
13692 			 * If this is a zero window probe, continue to
13693 			 * process the ACK part.  But we need to set seg_len
13694 			 * to 0 to avoid data processing.  Otherwise just
13695 			 * drop the segment and send back an ACK.
13696 			 */
13697 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13698 				flags &= ~(TH_SYN | TH_URG);
13699 				seg_len = 0;
13700 				goto process_ack;
13701 			} else {
13702 				freemsg(mp);
13703 				goto ack_check;
13704 			}
13705 		}
13706 		/* Pitch out of window stuff off the end. */
13707 		rgap = seg_len;
13708 		mp2 = mp;
13709 		do {
13710 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13711 			    (uintptr_t)INT_MAX);
13712 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13713 			if (rgap < 0) {
13714 				mp2->b_wptr += rgap;
13715 				if ((mp1 = mp2->b_cont) != NULL) {
13716 					mp2->b_cont = NULL;
13717 					freemsg(mp1);
13718 				}
13719 				break;
13720 			}
13721 		} while ((mp2 = mp2->b_cont) != NULL);
13722 	}
13723 ok:;
13724 	/*
13725 	 * TCP should check ECN info for segments inside the window only.
13726 	 * Therefore the check should be done here.
13727 	 */
13728 	if (tcp->tcp_ecn_ok) {
13729 		if (flags & TH_CWR) {
13730 			tcp->tcp_ecn_echo_on = B_FALSE;
13731 		}
13732 		/*
13733 		 * Note that both ECN_CE and CWR can be set in the
13734 		 * same segment.  In this case, we once again turn
13735 		 * on ECN_ECHO.
13736 		 */
13737 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13738 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13739 
13740 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13741 				tcp->tcp_ecn_echo_on = B_TRUE;
13742 			}
13743 		} else {
13744 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13745 
13746 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13747 			    htonl(IPH_ECN_CE << 20)) {
13748 				tcp->tcp_ecn_echo_on = B_TRUE;
13749 			}
13750 		}
13751 	}
13752 
13753 	/*
13754 	 * Check whether we can update tcp_ts_recent.  This test is
13755 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13756 	 * Extensions for High Performance: An Update", Internet Draft.
13757 	 */
13758 	if (tcp->tcp_snd_ts_ok &&
13759 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13760 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13761 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13762 		tcp->tcp_last_rcv_lbolt = lbolt64;
13763 	}
13764 
13765 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13766 		/*
13767 		 * FIN in an out of order segment.  We record this in
13768 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13769 		 * Clear the FIN so that any check on FIN flag will fail.
13770 		 * Remember that FIN also counts in the sequence number
13771 		 * space.  So we need to ack out of order FIN only segments.
13772 		 */
13773 		if (flags & TH_FIN) {
13774 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13775 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13776 			flags &= ~TH_FIN;
13777 			flags |= TH_ACK_NEEDED;
13778 		}
13779 		if (seg_len > 0) {
13780 			/* Fill in the SACK blk list. */
13781 			if (tcp->tcp_snd_sack_ok) {
13782 				ASSERT(tcp->tcp_sack_info != NULL);
13783 				tcp_sack_insert(tcp->tcp_sack_list,
13784 				    seg_seq, seg_seq + seg_len,
13785 				    &(tcp->tcp_num_sack_blk));
13786 			}
13787 
13788 			/*
13789 			 * Attempt reassembly and see if we have something
13790 			 * ready to go.
13791 			 */
13792 			mp = tcp_reass(tcp, mp, seg_seq);
13793 			/* Always ack out of order packets */
13794 			flags |= TH_ACK_NEEDED | TH_PUSH;
13795 			if (mp) {
13796 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13797 				    (uintptr_t)INT_MAX);
13798 				seg_len = mp->b_cont ? msgdsize(mp) :
13799 				    (int)(mp->b_wptr - mp->b_rptr);
13800 				seg_seq = tcp->tcp_rnxt;
13801 				/*
13802 				 * A gap is filled and the seq num and len
13803 				 * of the gap match that of a previously
13804 				 * received FIN, put the FIN flag back in.
13805 				 */
13806 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13807 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13808 					flags |= TH_FIN;
13809 					tcp->tcp_valid_bits &=
13810 					    ~TCP_OFO_FIN_VALID;
13811 				}
13812 			} else {
13813 				/*
13814 				 * Keep going even with NULL mp.
13815 				 * There may be a useful ACK or something else
13816 				 * we don't want to miss.
13817 				 *
13818 				 * But TCP should not perform fast retransmit
13819 				 * because of the ack number.  TCP uses
13820 				 * seg_len == 0 to determine if it is a pure
13821 				 * ACK.  And this is not a pure ACK.
13822 				 */
13823 				seg_len = 0;
13824 				ofo_seg = B_TRUE;
13825 			}
13826 		}
13827 	} else if (seg_len > 0) {
13828 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13829 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13830 		/*
13831 		 * If an out of order FIN was received before, and the seq
13832 		 * num and len of the new segment match that of the FIN,
13833 		 * put the FIN flag back in.
13834 		 */
13835 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13836 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13837 			flags |= TH_FIN;
13838 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13839 		}
13840 	}
13841 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13842 	if (flags & TH_RST) {
13843 		freemsg(mp);
13844 		switch (tcp->tcp_state) {
13845 		case TCPS_SYN_RCVD:
13846 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13847 			break;
13848 		case TCPS_ESTABLISHED:
13849 		case TCPS_FIN_WAIT_1:
13850 		case TCPS_FIN_WAIT_2:
13851 		case TCPS_CLOSE_WAIT:
13852 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13853 			break;
13854 		case TCPS_CLOSING:
13855 		case TCPS_LAST_ACK:
13856 			(void) tcp_clean_death(tcp, 0, 16);
13857 			break;
13858 		default:
13859 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13860 			(void) tcp_clean_death(tcp, ENXIO, 17);
13861 			break;
13862 		}
13863 		return;
13864 	}
13865 	if (flags & TH_SYN) {
13866 		/*
13867 		 * See RFC 793, Page 71
13868 		 *
13869 		 * The seq number must be in the window as it should
13870 		 * be "fixed" above.  If it is outside window, it should
13871 		 * be already rejected.  Note that we allow seg_seq to be
13872 		 * rnxt + rwnd because we want to accept 0 window probe.
13873 		 */
13874 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
13875 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
13876 		freemsg(mp);
13877 		/*
13878 		 * If the ACK flag is not set, just use our snxt as the
13879 		 * seq number of the RST segment.
13880 		 */
13881 		if (!(flags & TH_ACK)) {
13882 			seg_ack = tcp->tcp_snxt;
13883 		}
13884 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
13885 		    TH_RST|TH_ACK);
13886 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13887 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
13888 		return;
13889 	}
13890 	/*
13891 	 * urp could be -1 when the urp field in the packet is 0
13892 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
13893 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
13894 	 */
13895 	if (flags & TH_URG && urp >= 0) {
13896 		if (!tcp->tcp_urp_last_valid ||
13897 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
13898 			if (IPCL_IS_NONSTR(connp)) {
13899 				if (!TCP_IS_DETACHED(tcp)) {
13900 					(*connp->conn_upcalls->su_signal_oob)
13901 					    (connp->conn_upper_handle, urp);
13902 				}
13903 			} else {
13904 				/*
13905 				 * If we haven't generated the signal yet for
13906 				 * this urgent pointer value, do it now.  Also,
13907 				 * send up a zero-length M_DATA indicating
13908 				 * whether or not this is the mark. The latter
13909 				 * is not needed when a T_EXDATA_IND is sent up.
13910 				 * However, if there are allocation failures
13911 				 * this code relies on the sender retransmitting
13912 				 * and the socket code for determining the mark
13913 				 * should not block waiting for the peer to
13914 				 * transmit. Thus, for simplicity we always
13915 				 * send up the mark indication.
13916 				 */
13917 				mp1 = allocb(0, BPRI_MED);
13918 				if (mp1 == NULL) {
13919 					freemsg(mp);
13920 					return;
13921 				}
13922 				if (!TCP_IS_DETACHED(tcp) &&
13923 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13924 				    SIGURG)) {
13925 					/* Try again on the rexmit. */
13926 					freemsg(mp1);
13927 					freemsg(mp);
13928 					return;
13929 				}
13930 				/*
13931 				 * Mark with NOTMARKNEXT for now.
13932 				 * The code below will change this to MARKNEXT
13933 				 * if we are at the mark.
13934 				 *
13935 				 * If there are allocation failures (e.g. in
13936 				 * dupmsg below) the next time tcp_rput_data
13937 				 * sees the urgent segment it will send up the
13938 				 * MSGMARKNEXT message.
13939 				 */
13940 				mp1->b_flag |= MSGNOTMARKNEXT;
13941 				freemsg(tcp->tcp_urp_mark_mp);
13942 				tcp->tcp_urp_mark_mp = mp1;
13943 				flags |= TH_SEND_URP_MARK;
13944 #ifdef DEBUG
13945 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13946 				    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
13947 				    "last %x, %s",
13948 				    seg_seq, urp, tcp->tcp_urp_last,
13949 				    tcp_display(tcp, NULL, DISP_PORT_ONLY));
13950 #endif /* DEBUG */
13951 			}
13952 			tcp->tcp_urp_last_valid = B_TRUE;
13953 			tcp->tcp_urp_last = urp + seg_seq;
13954 		} else if (tcp->tcp_urp_mark_mp != NULL) {
13955 			/*
13956 			 * An allocation failure prevented the previous
13957 			 * tcp_rput_data from sending up the allocated
13958 			 * MSG*MARKNEXT message - send it up this time
13959 			 * around.
13960 			 */
13961 			flags |= TH_SEND_URP_MARK;
13962 		}
13963 
13964 		/*
13965 		 * If the urgent byte is in this segment, make sure that it is
13966 		 * all by itself.  This makes it much easier to deal with the
13967 		 * possibility of an allocation failure on the T_exdata_ind.
13968 		 * Note that seg_len is the number of bytes in the segment, and
13969 		 * urp is the offset into the segment of the urgent byte.
13970 		 * urp < seg_len means that the urgent byte is in this segment.
13971 		 */
13972 		if (urp < seg_len) {
13973 			if (seg_len != 1) {
13974 				uint32_t  tmp_rnxt;
13975 				/*
13976 				 * Break it up and feed it back in.
13977 				 * Re-attach the IP header.
13978 				 */
13979 				mp->b_rptr = iphdr;
13980 				if (urp > 0) {
13981 					/*
13982 					 * There is stuff before the urgent
13983 					 * byte.
13984 					 */
13985 					mp1 = dupmsg(mp);
13986 					if (!mp1) {
13987 						/*
13988 						 * Trim from urgent byte on.
13989 						 * The rest will come back.
13990 						 */
13991 						(void) adjmsg(mp,
13992 						    urp - seg_len);
13993 						tcp_rput_data(connp,
13994 						    mp, NULL);
13995 						return;
13996 					}
13997 					(void) adjmsg(mp1, urp - seg_len);
13998 					/* Feed this piece back in. */
13999 					tmp_rnxt = tcp->tcp_rnxt;
14000 					tcp_rput_data(connp, mp1, NULL);
14001 					/*
14002 					 * If the data passed back in was not
14003 					 * processed (ie: bad ACK) sending
14004 					 * the remainder back in will cause a
14005 					 * loop. In this case, drop the
14006 					 * packet and let the sender try
14007 					 * sending a good packet.
14008 					 */
14009 					if (tmp_rnxt == tcp->tcp_rnxt) {
14010 						freemsg(mp);
14011 						return;
14012 					}
14013 				}
14014 				if (urp != seg_len - 1) {
14015 					uint32_t  tmp_rnxt;
14016 					/*
14017 					 * There is stuff after the urgent
14018 					 * byte.
14019 					 */
14020 					mp1 = dupmsg(mp);
14021 					if (!mp1) {
14022 						/*
14023 						 * Trim everything beyond the
14024 						 * urgent byte.  The rest will
14025 						 * come back.
14026 						 */
14027 						(void) adjmsg(mp,
14028 						    urp + 1 - seg_len);
14029 						tcp_rput_data(connp,
14030 						    mp, NULL);
14031 						return;
14032 					}
14033 					(void) adjmsg(mp1, urp + 1 - seg_len);
14034 					tmp_rnxt = tcp->tcp_rnxt;
14035 					tcp_rput_data(connp, mp1, NULL);
14036 					/*
14037 					 * If the data passed back in was not
14038 					 * processed (ie: bad ACK) sending
14039 					 * the remainder back in will cause a
14040 					 * loop. In this case, drop the
14041 					 * packet and let the sender try
14042 					 * sending a good packet.
14043 					 */
14044 					if (tmp_rnxt == tcp->tcp_rnxt) {
14045 						freemsg(mp);
14046 						return;
14047 					}
14048 				}
14049 				tcp_rput_data(connp, mp, NULL);
14050 				return;
14051 			}
14052 			/*
14053 			 * This segment contains only the urgent byte.  We
14054 			 * have to allocate the T_exdata_ind, if we can.
14055 			 */
14056 			if (IPCL_IS_NONSTR(connp)) {
14057 				int error;
14058 
14059 				(*connp->conn_upcalls->su_recv)
14060 				    (connp->conn_upper_handle, mp, seg_len,
14061 				    MSG_OOB, &error, NULL);
14062 				/*
14063 				 * We should never be in middle of a
14064 				 * fallback, the squeue guarantees that.
14065 				 */
14066 				ASSERT(error != EOPNOTSUPP);
14067 				mp = NULL;
14068 				goto update_ack;
14069 			} else if (!tcp->tcp_urp_mp) {
14070 				struct T_exdata_ind *tei;
14071 				mp1 = allocb(sizeof (struct T_exdata_ind),
14072 				    BPRI_MED);
14073 				if (!mp1) {
14074 					/*
14075 					 * Sigh... It'll be back.
14076 					 * Generate any MSG*MARK message now.
14077 					 */
14078 					freemsg(mp);
14079 					seg_len = 0;
14080 					if (flags & TH_SEND_URP_MARK) {
14081 
14082 
14083 						ASSERT(tcp->tcp_urp_mark_mp);
14084 						tcp->tcp_urp_mark_mp->b_flag &=
14085 						    ~MSGNOTMARKNEXT;
14086 						tcp->tcp_urp_mark_mp->b_flag |=
14087 						    MSGMARKNEXT;
14088 					}
14089 					goto ack_check;
14090 				}
14091 				mp1->b_datap->db_type = M_PROTO;
14092 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14093 				tei->PRIM_type = T_EXDATA_IND;
14094 				tei->MORE_flag = 0;
14095 				mp1->b_wptr = (uchar_t *)&tei[1];
14096 				tcp->tcp_urp_mp = mp1;
14097 #ifdef DEBUG
14098 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14099 				    "tcp_rput: allocated exdata_ind %s",
14100 				    tcp_display(tcp, NULL,
14101 				    DISP_PORT_ONLY));
14102 #endif /* DEBUG */
14103 				/*
14104 				 * There is no need to send a separate MSG*MARK
14105 				 * message since the T_EXDATA_IND will be sent
14106 				 * now.
14107 				 */
14108 				flags &= ~TH_SEND_URP_MARK;
14109 				freemsg(tcp->tcp_urp_mark_mp);
14110 				tcp->tcp_urp_mark_mp = NULL;
14111 			}
14112 			/*
14113 			 * Now we are all set.  On the next putnext upstream,
14114 			 * tcp_urp_mp will be non-NULL and will get prepended
14115 			 * to what has to be this piece containing the urgent
14116 			 * byte.  If for any reason we abort this segment below,
14117 			 * if it comes back, we will have this ready, or it
14118 			 * will get blown off in close.
14119 			 */
14120 		} else if (urp == seg_len) {
14121 			/*
14122 			 * The urgent byte is the next byte after this sequence
14123 			 * number. If there is data it is marked with
14124 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14125 			 * since it is not needed. Otherwise, if the code
14126 			 * above just allocated a zero-length tcp_urp_mark_mp
14127 			 * message, that message is tagged with MSGMARKNEXT.
14128 			 * Sending up these MSGMARKNEXT messages makes
14129 			 * SIOCATMARK work correctly even though
14130 			 * the T_EXDATA_IND will not be sent up until the
14131 			 * urgent byte arrives.
14132 			 */
14133 			if (seg_len != 0) {
14134 				flags |= TH_MARKNEXT_NEEDED;
14135 				freemsg(tcp->tcp_urp_mark_mp);
14136 				tcp->tcp_urp_mark_mp = NULL;
14137 				flags &= ~TH_SEND_URP_MARK;
14138 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14139 				flags |= TH_SEND_URP_MARK;
14140 				tcp->tcp_urp_mark_mp->b_flag &=
14141 				    ~MSGNOTMARKNEXT;
14142 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14143 			}
14144 #ifdef DEBUG
14145 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14146 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14147 			    seg_len, flags,
14148 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14149 #endif /* DEBUG */
14150 		}
14151 #ifdef DEBUG
14152 		else {
14153 			/* Data left until we hit mark */
14154 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14155 			    "tcp_rput: URP %d bytes left, %s",
14156 			    urp - seg_len, tcp_display(tcp, NULL,
14157 			    DISP_PORT_ONLY));
14158 		}
14159 #endif /* DEBUG */
14160 	}
14161 
14162 process_ack:
14163 	if (!(flags & TH_ACK)) {
14164 		freemsg(mp);
14165 		goto xmit_check;
14166 	}
14167 	}
14168 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14169 
14170 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14171 		tcp->tcp_ip_forward_progress = B_TRUE;
14172 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14173 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14174 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14175 			/* 3-way handshake complete - pass up the T_CONN_IND */
14176 			tcp_t	*listener = tcp->tcp_listener;
14177 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14178 
14179 			tcp->tcp_tconnind_started = B_TRUE;
14180 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14181 			/*
14182 			 * We are here means eager is fine but it can
14183 			 * get a TH_RST at any point between now and till
14184 			 * accept completes and disappear. We need to
14185 			 * ensure that reference to eager is valid after
14186 			 * we get out of eager's perimeter. So we do
14187 			 * an extra refhold.
14188 			 */
14189 			CONN_INC_REF(connp);
14190 
14191 			/*
14192 			 * The listener also exists because of the refhold
14193 			 * done in tcp_conn_request. Its possible that it
14194 			 * might have closed. We will check that once we
14195 			 * get inside listeners context.
14196 			 */
14197 			CONN_INC_REF(listener->tcp_connp);
14198 			if (listener->tcp_connp->conn_sqp ==
14199 			    connp->conn_sqp) {
14200 				/*
14201 				 * We optimize by not calling an SQUEUE_ENTER
14202 				 * on the listener since we know that the
14203 				 * listener and eager squeues are the same.
14204 				 * We are able to make this check safely only
14205 				 * because neither the eager nor the listener
14206 				 * can change its squeue. Only an active connect
14207 				 * can change its squeue
14208 				 */
14209 				tcp_send_conn_ind(listener->tcp_connp, mp,
14210 				    listener->tcp_connp->conn_sqp);
14211 				CONN_DEC_REF(listener->tcp_connp);
14212 			} else if (!tcp->tcp_loopback) {
14213 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14214 				    mp, tcp_send_conn_ind,
14215 				    listener->tcp_connp, SQ_FILL,
14216 				    SQTAG_TCP_CONN_IND);
14217 			} else {
14218 				SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp,
14219 				    mp, tcp_send_conn_ind,
14220 				    listener->tcp_connp, SQ_PROCESS,
14221 				    SQTAG_TCP_CONN_IND);
14222 			}
14223 		}
14224 
14225 		if (tcp->tcp_active_open) {
14226 			/*
14227 			 * We are seeing the final ack in the three way
14228 			 * hand shake of a active open'ed connection
14229 			 * so we must send up a T_CONN_CON
14230 			 */
14231 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14232 				freemsg(mp);
14233 				return;
14234 			}
14235 			/*
14236 			 * Don't fuse the loopback endpoints for
14237 			 * simultaneous active opens.
14238 			 */
14239 			if (tcp->tcp_loopback) {
14240 				TCP_STAT(tcps, tcp_fusion_unfusable);
14241 				tcp->tcp_unfusable = B_TRUE;
14242 			}
14243 		}
14244 
14245 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14246 		bytes_acked--;
14247 		/* SYN was acked - making progress */
14248 		if (tcp->tcp_ipversion == IPV6_VERSION)
14249 			tcp->tcp_ip_forward_progress = B_TRUE;
14250 
14251 		/*
14252 		 * If SYN was retransmitted, need to reset all
14253 		 * retransmission info as this segment will be
14254 		 * treated as a dup ACK.
14255 		 */
14256 		if (tcp->tcp_rexmit) {
14257 			tcp->tcp_rexmit = B_FALSE;
14258 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14259 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14260 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14261 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14262 			tcp->tcp_ms_we_have_waited = 0;
14263 			tcp->tcp_cwnd = mss;
14264 		}
14265 
14266 		/*
14267 		 * We set the send window to zero here.
14268 		 * This is needed if there is data to be
14269 		 * processed already on the queue.
14270 		 * Later (at swnd_update label), the
14271 		 * "new_swnd > tcp_swnd" condition is satisfied
14272 		 * the XMIT_NEEDED flag is set in the current
14273 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14274 		 * called if there is already data on queue in
14275 		 * this state.
14276 		 */
14277 		tcp->tcp_swnd = 0;
14278 
14279 		if (new_swnd > tcp->tcp_max_swnd)
14280 			tcp->tcp_max_swnd = new_swnd;
14281 		tcp->tcp_swl1 = seg_seq;
14282 		tcp->tcp_swl2 = seg_ack;
14283 		tcp->tcp_state = TCPS_ESTABLISHED;
14284 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14285 
14286 		/* Fuse when both sides are in ESTABLISHED state */
14287 		if (tcp->tcp_loopback && do_tcp_fusion)
14288 			tcp_fuse(tcp, iphdr, tcph);
14289 
14290 	}
14291 	/* This code follows 4.4BSD-Lite2 mostly. */
14292 	if (bytes_acked < 0)
14293 		goto est;
14294 
14295 	/*
14296 	 * If TCP is ECN capable and the congestion experience bit is
14297 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14298 	 * done once per window (or more loosely, per RTT).
14299 	 */
14300 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14301 		tcp->tcp_cwr = B_FALSE;
14302 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14303 		if (!tcp->tcp_cwr) {
14304 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14305 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14306 			tcp->tcp_cwnd = npkt * mss;
14307 			/*
14308 			 * If the cwnd is 0, use the timer to clock out
14309 			 * new segments.  This is required by the ECN spec.
14310 			 */
14311 			if (npkt == 0) {
14312 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14313 				/*
14314 				 * This makes sure that when the ACK comes
14315 				 * back, we will increase tcp_cwnd by 1 MSS.
14316 				 */
14317 				tcp->tcp_cwnd_cnt = 0;
14318 			}
14319 			tcp->tcp_cwr = B_TRUE;
14320 			/*
14321 			 * This marks the end of the current window of in
14322 			 * flight data.  That is why we don't use
14323 			 * tcp_suna + tcp_swnd.  Only data in flight can
14324 			 * provide ECN info.
14325 			 */
14326 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14327 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14328 		}
14329 	}
14330 
14331 	mp1 = tcp->tcp_xmit_head;
14332 	if (bytes_acked == 0) {
14333 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14334 			int dupack_cnt;
14335 
14336 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14337 			/*
14338 			 * Fast retransmit.  When we have seen exactly three
14339 			 * identical ACKs while we have unacked data
14340 			 * outstanding we take it as a hint that our peer
14341 			 * dropped something.
14342 			 *
14343 			 * If TCP is retransmitting, don't do fast retransmit.
14344 			 */
14345 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14346 			    ! tcp->tcp_rexmit) {
14347 				/* Do Limited Transmit */
14348 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14349 				    tcps->tcps_dupack_fast_retransmit) {
14350 					/*
14351 					 * RFC 3042
14352 					 *
14353 					 * What we need to do is temporarily
14354 					 * increase tcp_cwnd so that new
14355 					 * data can be sent if it is allowed
14356 					 * by the receive window (tcp_rwnd).
14357 					 * tcp_wput_data() will take care of
14358 					 * the rest.
14359 					 *
14360 					 * If the connection is SACK capable,
14361 					 * only do limited xmit when there
14362 					 * is SACK info.
14363 					 *
14364 					 * Note how tcp_cwnd is incremented.
14365 					 * The first dup ACK will increase
14366 					 * it by 1 MSS.  The second dup ACK
14367 					 * will increase it by 2 MSS.  This
14368 					 * means that only 1 new segment will
14369 					 * be sent for each dup ACK.
14370 					 */
14371 					if (tcp->tcp_unsent > 0 &&
14372 					    (!tcp->tcp_snd_sack_ok ||
14373 					    (tcp->tcp_snd_sack_ok &&
14374 					    tcp->tcp_notsack_list != NULL))) {
14375 						tcp->tcp_cwnd += mss <<
14376 						    (tcp->tcp_dupack_cnt - 1);
14377 						flags |= TH_LIMIT_XMIT;
14378 					}
14379 				} else if (dupack_cnt ==
14380 				    tcps->tcps_dupack_fast_retransmit) {
14381 
14382 				/*
14383 				 * If we have reduced tcp_ssthresh
14384 				 * because of ECN, do not reduce it again
14385 				 * unless it is already one window of data
14386 				 * away.  After one window of data, tcp_cwr
14387 				 * should then be cleared.  Note that
14388 				 * for non ECN capable connection, tcp_cwr
14389 				 * should always be false.
14390 				 *
14391 				 * Adjust cwnd since the duplicate
14392 				 * ack indicates that a packet was
14393 				 * dropped (due to congestion.)
14394 				 */
14395 				if (!tcp->tcp_cwr) {
14396 					npkt = ((tcp->tcp_snxt -
14397 					    tcp->tcp_suna) >> 1) / mss;
14398 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14399 					    mss;
14400 					tcp->tcp_cwnd = (npkt +
14401 					    tcp->tcp_dupack_cnt) * mss;
14402 				}
14403 				if (tcp->tcp_ecn_ok) {
14404 					tcp->tcp_cwr = B_TRUE;
14405 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14406 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14407 				}
14408 
14409 				/*
14410 				 * We do Hoe's algorithm.  Refer to her
14411 				 * paper "Improving the Start-up Behavior
14412 				 * of a Congestion Control Scheme for TCP,"
14413 				 * appeared in SIGCOMM'96.
14414 				 *
14415 				 * Save highest seq no we have sent so far.
14416 				 * Be careful about the invisible FIN byte.
14417 				 */
14418 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14419 				    (tcp->tcp_unsent == 0)) {
14420 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14421 				} else {
14422 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14423 				}
14424 
14425 				/*
14426 				 * Do not allow bursty traffic during.
14427 				 * fast recovery.  Refer to Fall and Floyd's
14428 				 * paper "Simulation-based Comparisons of
14429 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14430 				 * This is a best current practise.
14431 				 */
14432 				tcp->tcp_snd_burst = TCP_CWND_SS;
14433 
14434 				/*
14435 				 * For SACK:
14436 				 * Calculate tcp_pipe, which is the
14437 				 * estimated number of bytes in
14438 				 * network.
14439 				 *
14440 				 * tcp_fack is the highest sack'ed seq num
14441 				 * TCP has received.
14442 				 *
14443 				 * tcp_pipe is explained in the above quoted
14444 				 * Fall and Floyd's paper.  tcp_fack is
14445 				 * explained in Mathis and Mahdavi's
14446 				 * "Forward Acknowledgment: Refining TCP
14447 				 * Congestion Control" in SIGCOMM '96.
14448 				 */
14449 				if (tcp->tcp_snd_sack_ok) {
14450 					ASSERT(tcp->tcp_sack_info != NULL);
14451 					if (tcp->tcp_notsack_list != NULL) {
14452 						tcp->tcp_pipe = tcp->tcp_snxt -
14453 						    tcp->tcp_fack;
14454 						tcp->tcp_sack_snxt = seg_ack;
14455 						flags |= TH_NEED_SACK_REXMIT;
14456 					} else {
14457 						/*
14458 						 * Always initialize tcp_pipe
14459 						 * even though we don't have
14460 						 * any SACK info.  If later
14461 						 * we get SACK info and
14462 						 * tcp_pipe is not initialized,
14463 						 * funny things will happen.
14464 						 */
14465 						tcp->tcp_pipe =
14466 						    tcp->tcp_cwnd_ssthresh;
14467 					}
14468 				} else {
14469 					flags |= TH_REXMIT_NEEDED;
14470 				} /* tcp_snd_sack_ok */
14471 
14472 				} else {
14473 					/*
14474 					 * Here we perform congestion
14475 					 * avoidance, but NOT slow start.
14476 					 * This is known as the Fast
14477 					 * Recovery Algorithm.
14478 					 */
14479 					if (tcp->tcp_snd_sack_ok &&
14480 					    tcp->tcp_notsack_list != NULL) {
14481 						flags |= TH_NEED_SACK_REXMIT;
14482 						tcp->tcp_pipe -= mss;
14483 						if (tcp->tcp_pipe < 0)
14484 							tcp->tcp_pipe = 0;
14485 					} else {
14486 					/*
14487 					 * We know that one more packet has
14488 					 * left the pipe thus we can update
14489 					 * cwnd.
14490 					 */
14491 					cwnd = tcp->tcp_cwnd + mss;
14492 					if (cwnd > tcp->tcp_cwnd_max)
14493 						cwnd = tcp->tcp_cwnd_max;
14494 					tcp->tcp_cwnd = cwnd;
14495 					if (tcp->tcp_unsent > 0)
14496 						flags |= TH_XMIT_NEEDED;
14497 					}
14498 				}
14499 			}
14500 		} else if (tcp->tcp_zero_win_probe) {
14501 			/*
14502 			 * If the window has opened, need to arrange
14503 			 * to send additional data.
14504 			 */
14505 			if (new_swnd != 0) {
14506 				/* tcp_suna != tcp_snxt */
14507 				/* Packet contains a window update */
14508 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14509 				tcp->tcp_zero_win_probe = 0;
14510 				tcp->tcp_timer_backoff = 0;
14511 				tcp->tcp_ms_we_have_waited = 0;
14512 
14513 				/*
14514 				 * Transmit starting with tcp_suna since
14515 				 * the one byte probe is not ack'ed.
14516 				 * If TCP has sent more than one identical
14517 				 * probe, tcp_rexmit will be set.  That means
14518 				 * tcp_ss_rexmit() will send out the one
14519 				 * byte along with new data.  Otherwise,
14520 				 * fake the retransmission.
14521 				 */
14522 				flags |= TH_XMIT_NEEDED;
14523 				if (!tcp->tcp_rexmit) {
14524 					tcp->tcp_rexmit = B_TRUE;
14525 					tcp->tcp_dupack_cnt = 0;
14526 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14527 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14528 				}
14529 			}
14530 		}
14531 		goto swnd_update;
14532 	}
14533 
14534 	/*
14535 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14536 	 * If the ACK value acks something that we have not yet sent, it might
14537 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14538 	 * other side.
14539 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14540 	 * state is handled above, so we can always just drop the segment and
14541 	 * send an ACK here.
14542 	 *
14543 	 * Should we send ACKs in response to ACK only segments?
14544 	 */
14545 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14546 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14547 		/* drop the received segment */
14548 		freemsg(mp);
14549 
14550 		/*
14551 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14552 		 * greater than 0, check if the number of such
14553 		 * bogus ACks is greater than that count.  If yes,
14554 		 * don't send back any ACK.  This prevents TCP from
14555 		 * getting into an ACK storm if somehow an attacker
14556 		 * successfully spoofs an acceptable segment to our
14557 		 * peer.
14558 		 */
14559 		if (tcp_drop_ack_unsent_cnt > 0 &&
14560 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14561 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14562 			return;
14563 		}
14564 		mp = tcp_ack_mp(tcp);
14565 		if (mp != NULL) {
14566 			BUMP_LOCAL(tcp->tcp_obsegs);
14567 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14568 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14569 		}
14570 		return;
14571 	}
14572 
14573 	/*
14574 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14575 	 * blocks that are covered by this ACK.
14576 	 */
14577 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14578 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14579 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14580 	}
14581 
14582 	/*
14583 	 * If we got an ACK after fast retransmit, check to see
14584 	 * if it is a partial ACK.  If it is not and the congestion
14585 	 * window was inflated to account for the other side's
14586 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14587 	 */
14588 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14589 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14590 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14591 			tcp->tcp_dupack_cnt = 0;
14592 			/*
14593 			 * Restore the orig tcp_cwnd_ssthresh after
14594 			 * fast retransmit phase.
14595 			 */
14596 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14597 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14598 			}
14599 			tcp->tcp_rexmit_max = seg_ack;
14600 			tcp->tcp_cwnd_cnt = 0;
14601 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14602 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14603 
14604 			/*
14605 			 * Remove all notsack info to avoid confusion with
14606 			 * the next fast retrasnmit/recovery phase.
14607 			 */
14608 			if (tcp->tcp_snd_sack_ok &&
14609 			    tcp->tcp_notsack_list != NULL) {
14610 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14611 			}
14612 		} else {
14613 			if (tcp->tcp_snd_sack_ok &&
14614 			    tcp->tcp_notsack_list != NULL) {
14615 				flags |= TH_NEED_SACK_REXMIT;
14616 				tcp->tcp_pipe -= mss;
14617 				if (tcp->tcp_pipe < 0)
14618 					tcp->tcp_pipe = 0;
14619 			} else {
14620 				/*
14621 				 * Hoe's algorithm:
14622 				 *
14623 				 * Retransmit the unack'ed segment and
14624 				 * restart fast recovery.  Note that we
14625 				 * need to scale back tcp_cwnd to the
14626 				 * original value when we started fast
14627 				 * recovery.  This is to prevent overly
14628 				 * aggressive behaviour in sending new
14629 				 * segments.
14630 				 */
14631 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14632 				    tcps->tcps_dupack_fast_retransmit * mss;
14633 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14634 				flags |= TH_REXMIT_NEEDED;
14635 			}
14636 		}
14637 	} else {
14638 		tcp->tcp_dupack_cnt = 0;
14639 		if (tcp->tcp_rexmit) {
14640 			/*
14641 			 * TCP is retranmitting.  If the ACK ack's all
14642 			 * outstanding data, update tcp_rexmit_max and
14643 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14644 			 * to the correct value.
14645 			 *
14646 			 * Note that SEQ_LEQ() is used.  This is to avoid
14647 			 * unnecessary fast retransmit caused by dup ACKs
14648 			 * received when TCP does slow start retransmission
14649 			 * after a time out.  During this phase, TCP may
14650 			 * send out segments which are already received.
14651 			 * This causes dup ACKs to be sent back.
14652 			 */
14653 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14654 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14655 					tcp->tcp_rexmit_nxt = seg_ack;
14656 				}
14657 				if (seg_ack != tcp->tcp_rexmit_max) {
14658 					flags |= TH_XMIT_NEEDED;
14659 				}
14660 			} else {
14661 				tcp->tcp_rexmit = B_FALSE;
14662 				tcp->tcp_xmit_zc_clean = B_FALSE;
14663 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14664 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14665 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14666 			}
14667 			tcp->tcp_ms_we_have_waited = 0;
14668 		}
14669 	}
14670 
14671 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14672 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14673 	tcp->tcp_suna = seg_ack;
14674 	if (tcp->tcp_zero_win_probe != 0) {
14675 		tcp->tcp_zero_win_probe = 0;
14676 		tcp->tcp_timer_backoff = 0;
14677 	}
14678 
14679 	/*
14680 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14681 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14682 	 * will not reach here.
14683 	 */
14684 	if (mp1 == NULL) {
14685 		goto fin_acked;
14686 	}
14687 
14688 	/*
14689 	 * Update the congestion window.
14690 	 *
14691 	 * If TCP is not ECN capable or TCP is ECN capable but the
14692 	 * congestion experience bit is not set, increase the tcp_cwnd as
14693 	 * usual.
14694 	 */
14695 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14696 		cwnd = tcp->tcp_cwnd;
14697 		add = mss;
14698 
14699 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14700 			/*
14701 			 * This is to prevent an increase of less than 1 MSS of
14702 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14703 			 * may send out tinygrams in order to preserve mblk
14704 			 * boundaries.
14705 			 *
14706 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14707 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14708 			 * increased by 1 MSS for every RTTs.
14709 			 */
14710 			if (tcp->tcp_cwnd_cnt <= 0) {
14711 				tcp->tcp_cwnd_cnt = cwnd + add;
14712 			} else {
14713 				tcp->tcp_cwnd_cnt -= add;
14714 				add = 0;
14715 			}
14716 		}
14717 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14718 	}
14719 
14720 	/* See if the latest urgent data has been acknowledged */
14721 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14722 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14723 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14724 
14725 	/* Can we update the RTT estimates? */
14726 	if (tcp->tcp_snd_ts_ok) {
14727 		/* Ignore zero timestamp echo-reply. */
14728 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14729 			tcp_set_rto(tcp, (int32_t)lbolt -
14730 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14731 		}
14732 
14733 		/* If needed, restart the timer. */
14734 		if (tcp->tcp_set_timer == 1) {
14735 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14736 			tcp->tcp_set_timer = 0;
14737 		}
14738 		/*
14739 		 * Update tcp_csuna in case the other side stops sending
14740 		 * us timestamps.
14741 		 */
14742 		tcp->tcp_csuna = tcp->tcp_snxt;
14743 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14744 		/*
14745 		 * An ACK sequence we haven't seen before, so get the RTT
14746 		 * and update the RTO. But first check if the timestamp is
14747 		 * valid to use.
14748 		 */
14749 		if ((mp1->b_next != NULL) &&
14750 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14751 			tcp_set_rto(tcp, (int32_t)lbolt -
14752 			    (int32_t)(intptr_t)mp1->b_prev);
14753 		else
14754 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14755 
14756 		/* Remeber the last sequence to be ACKed */
14757 		tcp->tcp_csuna = seg_ack;
14758 		if (tcp->tcp_set_timer == 1) {
14759 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14760 			tcp->tcp_set_timer = 0;
14761 		}
14762 	} else {
14763 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14764 	}
14765 
14766 	/* Eat acknowledged bytes off the xmit queue. */
14767 	for (;;) {
14768 		mblk_t	*mp2;
14769 		uchar_t	*wptr;
14770 
14771 		wptr = mp1->b_wptr;
14772 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14773 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14774 		if (bytes_acked < 0) {
14775 			mp1->b_rptr = wptr + bytes_acked;
14776 			/*
14777 			 * Set a new timestamp if all the bytes timed by the
14778 			 * old timestamp have been ack'ed.
14779 			 */
14780 			if (SEQ_GT(seg_ack,
14781 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14782 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14783 				mp1->b_next = NULL;
14784 			}
14785 			break;
14786 		}
14787 		mp1->b_next = NULL;
14788 		mp1->b_prev = NULL;
14789 		mp2 = mp1;
14790 		mp1 = mp1->b_cont;
14791 
14792 		/*
14793 		 * This notification is required for some zero-copy
14794 		 * clients to maintain a copy semantic. After the data
14795 		 * is ack'ed, client is safe to modify or reuse the buffer.
14796 		 */
14797 		if (tcp->tcp_snd_zcopy_aware &&
14798 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14799 			tcp_zcopy_notify(tcp);
14800 		freeb(mp2);
14801 		if (bytes_acked == 0) {
14802 			if (mp1 == NULL) {
14803 				/* Everything is ack'ed, clear the tail. */
14804 				tcp->tcp_xmit_tail = NULL;
14805 				/*
14806 				 * Cancel the timer unless we are still
14807 				 * waiting for an ACK for the FIN packet.
14808 				 */
14809 				if (tcp->tcp_timer_tid != 0 &&
14810 				    tcp->tcp_snxt == tcp->tcp_suna) {
14811 					(void) TCP_TIMER_CANCEL(tcp,
14812 					    tcp->tcp_timer_tid);
14813 					tcp->tcp_timer_tid = 0;
14814 				}
14815 				goto pre_swnd_update;
14816 			}
14817 			if (mp2 != tcp->tcp_xmit_tail)
14818 				break;
14819 			tcp->tcp_xmit_tail = mp1;
14820 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14821 			    (uintptr_t)INT_MAX);
14822 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14823 			    mp1->b_rptr);
14824 			break;
14825 		}
14826 		if (mp1 == NULL) {
14827 			/*
14828 			 * More was acked but there is nothing more
14829 			 * outstanding.  This means that the FIN was
14830 			 * just acked or that we're talking to a clown.
14831 			 */
14832 fin_acked:
14833 			ASSERT(tcp->tcp_fin_sent);
14834 			tcp->tcp_xmit_tail = NULL;
14835 			if (tcp->tcp_fin_sent) {
14836 				/* FIN was acked - making progress */
14837 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14838 				    !tcp->tcp_fin_acked)
14839 					tcp->tcp_ip_forward_progress = B_TRUE;
14840 				tcp->tcp_fin_acked = B_TRUE;
14841 				if (tcp->tcp_linger_tid != 0 &&
14842 				    TCP_TIMER_CANCEL(tcp,
14843 				    tcp->tcp_linger_tid) >= 0) {
14844 					tcp_stop_lingering(tcp);
14845 					freemsg(mp);
14846 					mp = NULL;
14847 				}
14848 			} else {
14849 				/*
14850 				 * We should never get here because
14851 				 * we have already checked that the
14852 				 * number of bytes ack'ed should be
14853 				 * smaller than or equal to what we
14854 				 * have sent so far (it is the
14855 				 * acceptability check of the ACK).
14856 				 * We can only get here if the send
14857 				 * queue is corrupted.
14858 				 *
14859 				 * Terminate the connection and
14860 				 * panic the system.  It is better
14861 				 * for us to panic instead of
14862 				 * continuing to avoid other disaster.
14863 				 */
14864 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14865 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14866 				panic("Memory corruption "
14867 				    "detected for connection %s.",
14868 				    tcp_display(tcp, NULL,
14869 				    DISP_ADDR_AND_PORT));
14870 				/*NOTREACHED*/
14871 			}
14872 			goto pre_swnd_update;
14873 		}
14874 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14875 	}
14876 	if (tcp->tcp_unsent) {
14877 		flags |= TH_XMIT_NEEDED;
14878 	}
14879 pre_swnd_update:
14880 	tcp->tcp_xmit_head = mp1;
14881 swnd_update:
14882 	/*
14883 	 * The following check is different from most other implementations.
14884 	 * For bi-directional transfer, when segments are dropped, the
14885 	 * "normal" check will not accept a window update in those
14886 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14887 	 * segments which are outside receiver's window.  As TCP accepts
14888 	 * the ack in those retransmitted segments, if the window update in
14889 	 * the same segment is not accepted, TCP will incorrectly calculates
14890 	 * that it can send more segments.  This can create a deadlock
14891 	 * with the receiver if its window becomes zero.
14892 	 */
14893 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14894 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14895 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14896 		/*
14897 		 * The criteria for update is:
14898 		 *
14899 		 * 1. the segment acknowledges some data.  Or
14900 		 * 2. the segment is new, i.e. it has a higher seq num. Or
14901 		 * 3. the segment is not old and the advertised window is
14902 		 * larger than the previous advertised window.
14903 		 */
14904 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
14905 			flags |= TH_XMIT_NEEDED;
14906 		tcp->tcp_swnd = new_swnd;
14907 		if (new_swnd > tcp->tcp_max_swnd)
14908 			tcp->tcp_max_swnd = new_swnd;
14909 		tcp->tcp_swl1 = seg_seq;
14910 		tcp->tcp_swl2 = seg_ack;
14911 	}
14912 est:
14913 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
14914 
14915 		switch (tcp->tcp_state) {
14916 		case TCPS_FIN_WAIT_1:
14917 			if (tcp->tcp_fin_acked) {
14918 				tcp->tcp_state = TCPS_FIN_WAIT_2;
14919 				/*
14920 				 * We implement the non-standard BSD/SunOS
14921 				 * FIN_WAIT_2 flushing algorithm.
14922 				 * If there is no user attached to this
14923 				 * TCP endpoint, then this TCP struct
14924 				 * could hang around forever in FIN_WAIT_2
14925 				 * state if the peer forgets to send us
14926 				 * a FIN.  To prevent this, we wait only
14927 				 * 2*MSL (a convenient time value) for
14928 				 * the FIN to arrive.  If it doesn't show up,
14929 				 * we flush the TCP endpoint.  This algorithm,
14930 				 * though a violation of RFC-793, has worked
14931 				 * for over 10 years in BSD systems.
14932 				 * Note: SunOS 4.x waits 675 seconds before
14933 				 * flushing the FIN_WAIT_2 connection.
14934 				 */
14935 				TCP_TIMER_RESTART(tcp,
14936 				    tcps->tcps_fin_wait_2_flush_interval);
14937 			}
14938 			break;
14939 		case TCPS_FIN_WAIT_2:
14940 			break;	/* Shutdown hook? */
14941 		case TCPS_LAST_ACK:
14942 			freemsg(mp);
14943 			if (tcp->tcp_fin_acked) {
14944 				(void) tcp_clean_death(tcp, 0, 19);
14945 				return;
14946 			}
14947 			goto xmit_check;
14948 		case TCPS_CLOSING:
14949 			if (tcp->tcp_fin_acked) {
14950 				tcp->tcp_state = TCPS_TIME_WAIT;
14951 				/*
14952 				 * Unconditionally clear the exclusive binding
14953 				 * bit so this TIME-WAIT connection won't
14954 				 * interfere with new ones.
14955 				 */
14956 				tcp->tcp_exclbind = 0;
14957 				if (!TCP_IS_DETACHED(tcp)) {
14958 					TCP_TIMER_RESTART(tcp,
14959 					    tcps->tcps_time_wait_interval);
14960 				} else {
14961 					tcp_time_wait_append(tcp);
14962 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
14963 				}
14964 			}
14965 			/*FALLTHRU*/
14966 		case TCPS_CLOSE_WAIT:
14967 			freemsg(mp);
14968 			goto xmit_check;
14969 		default:
14970 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14971 			break;
14972 		}
14973 	}
14974 	if (flags & TH_FIN) {
14975 		/* Make sure we ack the fin */
14976 		flags |= TH_ACK_NEEDED;
14977 		if (!tcp->tcp_fin_rcvd) {
14978 			tcp->tcp_fin_rcvd = B_TRUE;
14979 			tcp->tcp_rnxt++;
14980 			tcph = tcp->tcp_tcph;
14981 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
14982 
14983 			/*
14984 			 * Generate the ordrel_ind at the end unless we
14985 			 * are an eager guy.
14986 			 * In the eager case tcp_rsrv will do this when run
14987 			 * after tcp_accept is done.
14988 			 */
14989 			if (tcp->tcp_listener == NULL &&
14990 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
14991 				flags |= TH_ORDREL_NEEDED;
14992 			switch (tcp->tcp_state) {
14993 			case TCPS_SYN_RCVD:
14994 			case TCPS_ESTABLISHED:
14995 				tcp->tcp_state = TCPS_CLOSE_WAIT;
14996 				/* Keepalive? */
14997 				break;
14998 			case TCPS_FIN_WAIT_1:
14999 				if (!tcp->tcp_fin_acked) {
15000 					tcp->tcp_state = TCPS_CLOSING;
15001 					break;
15002 				}
15003 				/* FALLTHRU */
15004 			case TCPS_FIN_WAIT_2:
15005 				tcp->tcp_state = TCPS_TIME_WAIT;
15006 				/*
15007 				 * Unconditionally clear the exclusive binding
15008 				 * bit so this TIME-WAIT connection won't
15009 				 * interfere with new ones.
15010 				 */
15011 				tcp->tcp_exclbind = 0;
15012 				if (!TCP_IS_DETACHED(tcp)) {
15013 					TCP_TIMER_RESTART(tcp,
15014 					    tcps->tcps_time_wait_interval);
15015 				} else {
15016 					tcp_time_wait_append(tcp);
15017 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15018 				}
15019 				if (seg_len) {
15020 					/*
15021 					 * implies data piggybacked on FIN.
15022 					 * break to handle data.
15023 					 */
15024 					break;
15025 				}
15026 				freemsg(mp);
15027 				goto ack_check;
15028 			}
15029 		}
15030 	}
15031 	if (mp == NULL)
15032 		goto xmit_check;
15033 	if (seg_len == 0) {
15034 		freemsg(mp);
15035 		goto xmit_check;
15036 	}
15037 	if (mp->b_rptr == mp->b_wptr) {
15038 		/*
15039 		 * The header has been consumed, so we remove the
15040 		 * zero-length mblk here.
15041 		 */
15042 		mp1 = mp;
15043 		mp = mp->b_cont;
15044 		freeb(mp1);
15045 	}
15046 update_ack:
15047 	tcph = tcp->tcp_tcph;
15048 	tcp->tcp_rack_cnt++;
15049 	{
15050 		uint32_t cur_max;
15051 
15052 		cur_max = tcp->tcp_rack_cur_max;
15053 		if (tcp->tcp_rack_cnt >= cur_max) {
15054 			/*
15055 			 * We have more unacked data than we should - send
15056 			 * an ACK now.
15057 			 */
15058 			flags |= TH_ACK_NEEDED;
15059 			cur_max++;
15060 			if (cur_max > tcp->tcp_rack_abs_max)
15061 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15062 			else
15063 				tcp->tcp_rack_cur_max = cur_max;
15064 		} else if (TCP_IS_DETACHED(tcp)) {
15065 			/* We don't have an ACK timer for detached TCP. */
15066 			flags |= TH_ACK_NEEDED;
15067 		} else if (seg_len < mss) {
15068 			/*
15069 			 * If we get a segment that is less than an mss, and we
15070 			 * already have unacknowledged data, and the amount
15071 			 * unacknowledged is not a multiple of mss, then we
15072 			 * better generate an ACK now.  Otherwise, this may be
15073 			 * the tail piece of a transaction, and we would rather
15074 			 * wait for the response.
15075 			 */
15076 			uint32_t udif;
15077 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15078 			    (uintptr_t)INT_MAX);
15079 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15080 			if (udif && (udif % mss))
15081 				flags |= TH_ACK_NEEDED;
15082 			else
15083 				flags |= TH_ACK_TIMER_NEEDED;
15084 		} else {
15085 			/* Start delayed ack timer */
15086 			flags |= TH_ACK_TIMER_NEEDED;
15087 		}
15088 	}
15089 	tcp->tcp_rnxt += seg_len;
15090 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15091 
15092 	if (mp == NULL)
15093 		goto xmit_check;
15094 
15095 	/* Update SACK list */
15096 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15097 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15098 		    &(tcp->tcp_num_sack_blk));
15099 	}
15100 
15101 	if (tcp->tcp_urp_mp) {
15102 		tcp->tcp_urp_mp->b_cont = mp;
15103 		mp = tcp->tcp_urp_mp;
15104 		tcp->tcp_urp_mp = NULL;
15105 		/* Ready for a new signal. */
15106 		tcp->tcp_urp_last_valid = B_FALSE;
15107 #ifdef DEBUG
15108 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15109 		    "tcp_rput: sending exdata_ind %s",
15110 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15111 #endif /* DEBUG */
15112 	}
15113 
15114 	/*
15115 	 * Check for ancillary data changes compared to last segment.
15116 	 */
15117 	if (tcp->tcp_ipv6_recvancillary != 0) {
15118 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15119 		ASSERT(mp != NULL);
15120 	}
15121 
15122 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15123 		/*
15124 		 * Side queue inbound data until the accept happens.
15125 		 * tcp_accept/tcp_rput drains this when the accept happens.
15126 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15127 		 * T_EXDATA_IND) it is queued on b_next.
15128 		 * XXX Make urgent data use this. Requires:
15129 		 *	Removing tcp_listener check for TH_URG
15130 		 *	Making M_PCPROTO and MARK messages skip the eager case
15131 		 */
15132 
15133 		if (tcp->tcp_kssl_pending) {
15134 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15135 			    mblk_t *, mp);
15136 			tcp_kssl_input(tcp, mp);
15137 		} else {
15138 			tcp_rcv_enqueue(tcp, mp, seg_len);
15139 		}
15140 	} else {
15141 		sodirect_t	*sodp = tcp->tcp_sodirect;
15142 
15143 		/*
15144 		 * If an sodirect connection and an enabled sodirect_t then
15145 		 * sodp will be set to point to the tcp_t/sonode_t shared
15146 		 * sodirect_t and the sodirect_t's lock will be held.
15147 		 */
15148 		if (sodp != NULL) {
15149 			mutex_enter(sodp->sod_lockp);
15150 			if (!(sodp->sod_state & SOD_ENABLED) ||
15151 			    (tcp->tcp_kssl_ctx != NULL &&
15152 			    DB_TYPE(mp) == M_DATA)) {
15153 				sodp = NULL;
15154 			}
15155 			mutex_exit(sodp->sod_lockp);
15156 		}
15157 		if (mp->b_datap->db_type != M_DATA ||
15158 		    (flags & TH_MARKNEXT_NEEDED)) {
15159 			if (IPCL_IS_NONSTR(connp)) {
15160 				int error;
15161 
15162 				if ((*connp->conn_upcalls->su_recv)
15163 				    (connp->conn_upper_handle, mp,
15164 				    seg_len, 0, &error, NULL) <= 0) {
15165 					/*
15166 					 * We should never be in middle of a
15167 					 * fallback, the squeue guarantees that.
15168 					 */
15169 					ASSERT(error != EOPNOTSUPP);
15170 					if (error == ENOSPC)
15171 						tcp->tcp_rwnd -= seg_len;
15172 				}
15173 			} else if (sodp != NULL) {
15174 				mutex_enter(sodp->sod_lockp);
15175 				SOD_UIOAFINI(sodp);
15176 				if (!SOD_QEMPTY(sodp) &&
15177 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15178 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15179 					/* sod_wakeup() did the mutex_exit() */
15180 				} else {
15181 					mutex_exit(sodp->sod_lockp);
15182 				}
15183 			} else if (tcp->tcp_rcv_list != NULL) {
15184 				flags |= tcp_rcv_drain(tcp);
15185 			}
15186 			ASSERT(tcp->tcp_rcv_list == NULL ||
15187 			    tcp->tcp_fused_sigurg);
15188 
15189 			if (flags & TH_MARKNEXT_NEEDED) {
15190 #ifdef DEBUG
15191 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15192 				    "tcp_rput: sending MSGMARKNEXT %s",
15193 				    tcp_display(tcp, NULL,
15194 				    DISP_PORT_ONLY));
15195 #endif /* DEBUG */
15196 				mp->b_flag |= MSGMARKNEXT;
15197 				flags &= ~TH_MARKNEXT_NEEDED;
15198 			}
15199 
15200 			/* Does this need SSL processing first? */
15201 			if ((tcp->tcp_kssl_ctx != NULL) &&
15202 			    (DB_TYPE(mp) == M_DATA)) {
15203 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15204 				    mblk_t *, mp);
15205 				tcp_kssl_input(tcp, mp);
15206 			} else if (!IPCL_IS_NONSTR(connp)) {
15207 				/* Already handled non-STREAMS case. */
15208 				putnext(tcp->tcp_rq, mp);
15209 				if (!canputnext(tcp->tcp_rq))
15210 					tcp->tcp_rwnd -= seg_len;
15211 			}
15212 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15213 		    (DB_TYPE(mp) == M_DATA)) {
15214 			/* Does this need SSL processing first? */
15215 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2, mblk_t *, mp);
15216 			tcp_kssl_input(tcp, mp);
15217 		} else if (IPCL_IS_NONSTR(connp)) {
15218 			/* Non-STREAMS socket */
15219 			boolean_t push = flags & (TH_PUSH|TH_FIN);
15220 			int	error;
15221 
15222 			if ((*connp->conn_upcalls->su_recv)(
15223 			    connp->conn_upper_handle,
15224 			    mp, seg_len, 0, &error, &push) <= 0) {
15225 				/*
15226 				 * We should never be in middle of a
15227 				 * fallback, the squeue guarantees that.
15228 				 */
15229 				ASSERT(error != EOPNOTSUPP);
15230 				if (error == ENOSPC)
15231 					tcp->tcp_rwnd -= seg_len;
15232 			} else if (push) {
15233 				/*
15234 				 * PUSH bit set and sockfs is not
15235 				 * flow controlled
15236 				 */
15237 				flags |= tcp_rwnd_reopen(tcp);
15238 			}
15239 		} else if (sodp != NULL) {
15240 			/*
15241 			 * Sodirect so all mblk_t's are queued on the
15242 			 * socket directly, check for wakeup of blocked
15243 			 * reader (if any), and last if flow-controled.
15244 			 */
15245 			mutex_enter(sodp->sod_lockp);
15246 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15247 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15248 			    (flags & (TH_PUSH|TH_FIN))) {
15249 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15250 				/* sod_wakeup() did the mutex_exit() */
15251 			} else {
15252 				if (SOD_QFULL(sodp)) {
15253 					/* Q is full, need backenable */
15254 					SOD_QSETBE(sodp);
15255 				}
15256 				mutex_exit(sodp->sod_lockp);
15257 			}
15258 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15259 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_recv_hiwater >> 3) {
15260 			if (tcp->tcp_rcv_list != NULL) {
15261 				/*
15262 				 * Enqueue the new segment first and then
15263 				 * call tcp_rcv_drain() to send all data
15264 				 * up.  The other way to do this is to
15265 				 * send all queued data up and then call
15266 				 * putnext() to send the new segment up.
15267 				 * This way can remove the else part later
15268 				 * on.
15269 				 *
15270 				 * We don't do this to avoid one more call to
15271 				 * canputnext() as tcp_rcv_drain() needs to
15272 				 * call canputnext().
15273 				 */
15274 				tcp_rcv_enqueue(tcp, mp, seg_len);
15275 				flags |= tcp_rcv_drain(tcp);
15276 			} else {
15277 				putnext(tcp->tcp_rq, mp);
15278 				if (!canputnext(tcp->tcp_rq))
15279 					tcp->tcp_rwnd -= seg_len;
15280 			}
15281 		} else {
15282 			/*
15283 			 * Enqueue all packets when processing an mblk
15284 			 * from the co queue and also enqueue normal packets.
15285 			 * For packets which belong to SSL stream do SSL
15286 			 * processing first.
15287 			 */
15288 			tcp_rcv_enqueue(tcp, mp, seg_len);
15289 		}
15290 		/*
15291 		 * Make sure the timer is running if we have data waiting
15292 		 * for a push bit. This provides resiliency against
15293 		 * implementations that do not correctly generate push bits.
15294 		 *
15295 		 * Note, for sodirect if Q isn't empty and there's not a
15296 		 * pending wakeup then we need a timer. Also note that sodp
15297 		 * is assumed to be still valid after exit()ing the sod_lockp
15298 		 * above and while the SOD state can change it can only change
15299 		 * such that the Q is empty now even though data was added
15300 		 * above.
15301 		 */
15302 		if (!IPCL_IS_NONSTR(connp) &&
15303 		    ((sodp != NULL && !SOD_QEMPTY(sodp) &&
15304 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15305 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15306 		    tcp->tcp_push_tid == 0) {
15307 			/*
15308 			 * The connection may be closed at this point, so don't
15309 			 * do anything for a detached tcp.
15310 			 */
15311 			if (!TCP_IS_DETACHED(tcp))
15312 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15313 				    tcp_push_timer,
15314 				    MSEC_TO_TICK(
15315 				    tcps->tcps_push_timer_interval));
15316 		}
15317 	}
15318 
15319 xmit_check:
15320 	/* Is there anything left to do? */
15321 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15322 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15323 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15324 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15325 		goto done;
15326 
15327 	/* Any transmit work to do and a non-zero window? */
15328 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15329 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15330 		if (flags & TH_REXMIT_NEEDED) {
15331 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15332 
15333 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15334 			if (snd_size > mss)
15335 				snd_size = mss;
15336 			if (snd_size > tcp->tcp_swnd)
15337 				snd_size = tcp->tcp_swnd;
15338 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15339 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15340 			    B_TRUE);
15341 
15342 			if (mp1 != NULL) {
15343 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15344 				tcp->tcp_csuna = tcp->tcp_snxt;
15345 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15346 				UPDATE_MIB(&tcps->tcps_mib,
15347 				    tcpRetransBytes, snd_size);
15348 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15349 			}
15350 		}
15351 		if (flags & TH_NEED_SACK_REXMIT) {
15352 			tcp_sack_rxmit(tcp, &flags);
15353 		}
15354 		/*
15355 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15356 		 * out new segment.  Note that tcp_rexmit should not be
15357 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15358 		 */
15359 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15360 			if (!tcp->tcp_rexmit) {
15361 				tcp_wput_data(tcp, NULL, B_FALSE);
15362 			} else {
15363 				tcp_ss_rexmit(tcp);
15364 			}
15365 		}
15366 		/*
15367 		 * Adjust tcp_cwnd back to normal value after sending
15368 		 * new data segments.
15369 		 */
15370 		if (flags & TH_LIMIT_XMIT) {
15371 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15372 			/*
15373 			 * This will restart the timer.  Restarting the
15374 			 * timer is used to avoid a timeout before the
15375 			 * limited transmitted segment's ACK gets back.
15376 			 */
15377 			if (tcp->tcp_xmit_head != NULL)
15378 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15379 		}
15380 
15381 		/* Anything more to do? */
15382 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15383 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15384 			goto done;
15385 	}
15386 ack_check:
15387 	if (flags & TH_SEND_URP_MARK) {
15388 		ASSERT(tcp->tcp_urp_mark_mp);
15389 		ASSERT(!IPCL_IS_NONSTR(connp));
15390 		/*
15391 		 * Send up any queued data and then send the mark message
15392 		 */
15393 		sodirect_t *sodp;
15394 
15395 		SOD_PTR_ENTER(tcp, sodp);
15396 
15397 		mp1 = tcp->tcp_urp_mark_mp;
15398 		tcp->tcp_urp_mark_mp = NULL;
15399 		if (sodp != NULL) {
15400 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15401 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15402 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15403 			}
15404 			ASSERT(tcp->tcp_rcv_list == NULL);
15405 
15406 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15407 			/* sod_wakeup() does the mutex_exit() */
15408 		} else if (tcp->tcp_rcv_list != NULL) {
15409 			flags |= tcp_rcv_drain(tcp);
15410 
15411 			ASSERT(tcp->tcp_rcv_list == NULL ||
15412 			    tcp->tcp_fused_sigurg);
15413 
15414 		}
15415 		putnext(tcp->tcp_rq, mp1);
15416 #ifdef DEBUG
15417 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15418 		    "tcp_rput: sending zero-length %s %s",
15419 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15420 		    "MSGNOTMARKNEXT"),
15421 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15422 #endif /* DEBUG */
15423 		flags &= ~TH_SEND_URP_MARK;
15424 	}
15425 	if (flags & TH_ACK_NEEDED) {
15426 		/*
15427 		 * Time to send an ack for some reason.
15428 		 */
15429 		mp1 = tcp_ack_mp(tcp);
15430 
15431 		if (mp1 != NULL) {
15432 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15433 			BUMP_LOCAL(tcp->tcp_obsegs);
15434 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15435 		}
15436 		if (tcp->tcp_ack_tid != 0) {
15437 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15438 			tcp->tcp_ack_tid = 0;
15439 		}
15440 	}
15441 	if (flags & TH_ACK_TIMER_NEEDED) {
15442 		/*
15443 		 * Arrange for deferred ACK or push wait timeout.
15444 		 * Start timer if it is not already running.
15445 		 */
15446 		if (tcp->tcp_ack_tid == 0) {
15447 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15448 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15449 			    (clock_t)tcps->tcps_local_dack_interval :
15450 			    (clock_t)tcps->tcps_deferred_ack_interval));
15451 		}
15452 	}
15453 	if (flags & TH_ORDREL_NEEDED) {
15454 		/*
15455 		 * Send up the ordrel_ind unless we are an eager guy.
15456 		 * In the eager case tcp_rsrv will do this when run
15457 		 * after tcp_accept is done.
15458 		 */
15459 		sodirect_t *sodp;
15460 
15461 		ASSERT(tcp->tcp_listener == NULL);
15462 
15463 		if (IPCL_IS_NONSTR(connp)) {
15464 			ASSERT(tcp->tcp_ordrel_mp == NULL);
15465 			tcp->tcp_ordrel_done = B_TRUE;
15466 			(*connp->conn_upcalls->su_opctl)
15467 			    (connp->conn_upper_handle, SOCK_OPCTL_SHUT_RECV, 0);
15468 			goto done;
15469 		}
15470 
15471 		SOD_PTR_ENTER(tcp, sodp);
15472 		if (sodp != NULL) {
15473 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15474 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15475 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15476 			}
15477 			/* No more sodirect */
15478 			tcp->tcp_sodirect = NULL;
15479 			if (!SOD_QEMPTY(sodp)) {
15480 				/* Mblk(s) to process, notify */
15481 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15482 				/* sod_wakeup() does the mutex_exit() */
15483 			} else {
15484 				/* Nothing to process */
15485 				mutex_exit(sodp->sod_lockp);
15486 			}
15487 		} else if (tcp->tcp_rcv_list != NULL) {
15488 			/*
15489 			 * Push any mblk(s) enqueued from co processing.
15490 			 */
15491 			flags |= tcp_rcv_drain(tcp);
15492 
15493 			ASSERT(tcp->tcp_rcv_list == NULL ||
15494 			    tcp->tcp_fused_sigurg);
15495 		}
15496 
15497 		mp1 = tcp->tcp_ordrel_mp;
15498 		tcp->tcp_ordrel_mp = NULL;
15499 		tcp->tcp_ordrel_done = B_TRUE;
15500 		putnext(tcp->tcp_rq, mp1);
15501 	}
15502 done:
15503 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15504 }
15505 
15506 /*
15507  * This function does PAWS protection check. Returns B_TRUE if the
15508  * segment passes the PAWS test, else returns B_FALSE.
15509  */
15510 boolean_t
15511 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15512 {
15513 	uint8_t	flags;
15514 	int	options;
15515 	uint8_t *up;
15516 
15517 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15518 	/*
15519 	 * If timestamp option is aligned nicely, get values inline,
15520 	 * otherwise call general routine to parse.  Only do that
15521 	 * if timestamp is the only option.
15522 	 */
15523 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15524 	    TCPOPT_REAL_TS_LEN &&
15525 	    OK_32PTR((up = ((uint8_t *)tcph) +
15526 	    TCP_MIN_HEADER_LENGTH)) &&
15527 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15528 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15529 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15530 
15531 		options = TCP_OPT_TSTAMP_PRESENT;
15532 	} else {
15533 		if (tcp->tcp_snd_sack_ok) {
15534 			tcpoptp->tcp = tcp;
15535 		} else {
15536 			tcpoptp->tcp = NULL;
15537 		}
15538 		options = tcp_parse_options(tcph, tcpoptp);
15539 	}
15540 
15541 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15542 		/*
15543 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15544 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15545 		 */
15546 		if ((flags & TH_RST) == 0 &&
15547 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15548 		    tcp->tcp_ts_recent)) {
15549 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15550 			    PAWS_TIMEOUT)) {
15551 				/* This segment is not acceptable. */
15552 				return (B_FALSE);
15553 			} else {
15554 				/*
15555 				 * Connection has been idle for
15556 				 * too long.  Reset the timestamp
15557 				 * and assume the segment is valid.
15558 				 */
15559 				tcp->tcp_ts_recent =
15560 				    tcpoptp->tcp_opt_ts_val;
15561 			}
15562 		}
15563 	} else {
15564 		/*
15565 		 * If we don't get a timestamp on every packet, we
15566 		 * figure we can't really trust 'em, so we stop sending
15567 		 * and parsing them.
15568 		 */
15569 		tcp->tcp_snd_ts_ok = B_FALSE;
15570 
15571 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15572 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15573 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15574 		/*
15575 		 * Adjust the tcp_mss accordingly. We also need to
15576 		 * adjust tcp_cwnd here in accordance with the new mss.
15577 		 * But we avoid doing a slow start here so as to not
15578 		 * to lose on the transfer rate built up so far.
15579 		 */
15580 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15581 		if (tcp->tcp_snd_sack_ok) {
15582 			ASSERT(tcp->tcp_sack_info != NULL);
15583 			tcp->tcp_max_sack_blk = 4;
15584 		}
15585 	}
15586 	return (B_TRUE);
15587 }
15588 
15589 /*
15590  * Attach ancillary data to a received TCP segments for the
15591  * ancillary pieces requested by the application that are
15592  * different than they were in the previous data segment.
15593  *
15594  * Save the "current" values once memory allocation is ok so that
15595  * when memory allocation fails we can just wait for the next data segment.
15596  */
15597 static mblk_t *
15598 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15599 {
15600 	struct T_optdata_ind *todi;
15601 	int optlen;
15602 	uchar_t *optptr;
15603 	struct T_opthdr *toh;
15604 	uint_t addflag;	/* Which pieces to add */
15605 	mblk_t *mp1;
15606 
15607 	optlen = 0;
15608 	addflag = 0;
15609 	/* If app asked for pktinfo and the index has changed ... */
15610 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15611 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15612 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15613 		optlen += sizeof (struct T_opthdr) +
15614 		    sizeof (struct in6_pktinfo);
15615 		addflag |= TCP_IPV6_RECVPKTINFO;
15616 	}
15617 	/* If app asked for hoplimit and it has changed ... */
15618 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15619 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15620 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15621 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15622 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15623 	}
15624 	/* If app asked for tclass and it has changed ... */
15625 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15626 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15627 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15628 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15629 		addflag |= TCP_IPV6_RECVTCLASS;
15630 	}
15631 	/*
15632 	 * If app asked for hopbyhop headers and it has changed ...
15633 	 * For security labels, note that (1) security labels can't change on
15634 	 * a connected socket at all, (2) we're connected to at most one peer,
15635 	 * (3) if anything changes, then it must be some other extra option.
15636 	 */
15637 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15638 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15639 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15640 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15641 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15642 		    tcp->tcp_label_len;
15643 		addflag |= TCP_IPV6_RECVHOPOPTS;
15644 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15645 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15646 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15647 			return (mp);
15648 	}
15649 	/* If app asked for dst headers before routing headers ... */
15650 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15651 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15652 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15653 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15654 		optlen += sizeof (struct T_opthdr) +
15655 		    ipp->ipp_rtdstoptslen;
15656 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15657 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15658 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15659 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15660 			return (mp);
15661 	}
15662 	/* If app asked for routing headers and it has changed ... */
15663 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15664 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15665 	    (ipp->ipp_fields & IPPF_RTHDR),
15666 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15667 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15668 		addflag |= TCP_IPV6_RECVRTHDR;
15669 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15670 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15671 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15672 			return (mp);
15673 	}
15674 	/* If app asked for dest headers and it has changed ... */
15675 	if ((tcp->tcp_ipv6_recvancillary &
15676 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15677 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15678 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15679 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15680 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15681 		addflag |= TCP_IPV6_RECVDSTOPTS;
15682 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15683 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15684 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15685 			return (mp);
15686 	}
15687 
15688 	if (optlen == 0) {
15689 		/* Nothing to add */
15690 		return (mp);
15691 	}
15692 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15693 	if (mp1 == NULL) {
15694 		/*
15695 		 * Defer sending ancillary data until the next TCP segment
15696 		 * arrives.
15697 		 */
15698 		return (mp);
15699 	}
15700 	mp1->b_cont = mp;
15701 	mp = mp1;
15702 	mp->b_wptr += sizeof (*todi) + optlen;
15703 	mp->b_datap->db_type = M_PROTO;
15704 	todi = (struct T_optdata_ind *)mp->b_rptr;
15705 	todi->PRIM_type = T_OPTDATA_IND;
15706 	todi->DATA_flag = 1;	/* MORE data */
15707 	todi->OPT_length = optlen;
15708 	todi->OPT_offset = sizeof (*todi);
15709 	optptr = (uchar_t *)&todi[1];
15710 	/*
15711 	 * If app asked for pktinfo and the index has changed ...
15712 	 * Note that the local address never changes for the connection.
15713 	 */
15714 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15715 		struct in6_pktinfo *pkti;
15716 
15717 		toh = (struct T_opthdr *)optptr;
15718 		toh->level = IPPROTO_IPV6;
15719 		toh->name = IPV6_PKTINFO;
15720 		toh->len = sizeof (*toh) + sizeof (*pkti);
15721 		toh->status = 0;
15722 		optptr += sizeof (*toh);
15723 		pkti = (struct in6_pktinfo *)optptr;
15724 		if (tcp->tcp_ipversion == IPV6_VERSION)
15725 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15726 		else
15727 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15728 			    &pkti->ipi6_addr);
15729 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15730 		optptr += sizeof (*pkti);
15731 		ASSERT(OK_32PTR(optptr));
15732 		/* Save as "last" value */
15733 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15734 	}
15735 	/* If app asked for hoplimit and it has changed ... */
15736 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15737 		toh = (struct T_opthdr *)optptr;
15738 		toh->level = IPPROTO_IPV6;
15739 		toh->name = IPV6_HOPLIMIT;
15740 		toh->len = sizeof (*toh) + sizeof (uint_t);
15741 		toh->status = 0;
15742 		optptr += sizeof (*toh);
15743 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15744 		optptr += sizeof (uint_t);
15745 		ASSERT(OK_32PTR(optptr));
15746 		/* Save as "last" value */
15747 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15748 	}
15749 	/* If app asked for tclass and it has changed ... */
15750 	if (addflag & TCP_IPV6_RECVTCLASS) {
15751 		toh = (struct T_opthdr *)optptr;
15752 		toh->level = IPPROTO_IPV6;
15753 		toh->name = IPV6_TCLASS;
15754 		toh->len = sizeof (*toh) + sizeof (uint_t);
15755 		toh->status = 0;
15756 		optptr += sizeof (*toh);
15757 		*(uint_t *)optptr = ipp->ipp_tclass;
15758 		optptr += sizeof (uint_t);
15759 		ASSERT(OK_32PTR(optptr));
15760 		/* Save as "last" value */
15761 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15762 	}
15763 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15764 		toh = (struct T_opthdr *)optptr;
15765 		toh->level = IPPROTO_IPV6;
15766 		toh->name = IPV6_HOPOPTS;
15767 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15768 		    tcp->tcp_label_len;
15769 		toh->status = 0;
15770 		optptr += sizeof (*toh);
15771 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15772 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15773 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15774 		ASSERT(OK_32PTR(optptr));
15775 		/* Save as last value */
15776 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15777 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15778 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15779 	}
15780 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15781 		toh = (struct T_opthdr *)optptr;
15782 		toh->level = IPPROTO_IPV6;
15783 		toh->name = IPV6_RTHDRDSTOPTS;
15784 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15785 		toh->status = 0;
15786 		optptr += sizeof (*toh);
15787 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15788 		optptr += ipp->ipp_rtdstoptslen;
15789 		ASSERT(OK_32PTR(optptr));
15790 		/* Save as last value */
15791 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15792 		    &tcp->tcp_rtdstoptslen,
15793 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15794 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15795 	}
15796 	if (addflag & TCP_IPV6_RECVRTHDR) {
15797 		toh = (struct T_opthdr *)optptr;
15798 		toh->level = IPPROTO_IPV6;
15799 		toh->name = IPV6_RTHDR;
15800 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15801 		toh->status = 0;
15802 		optptr += sizeof (*toh);
15803 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15804 		optptr += ipp->ipp_rthdrlen;
15805 		ASSERT(OK_32PTR(optptr));
15806 		/* Save as last value */
15807 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15808 		    (ipp->ipp_fields & IPPF_RTHDR),
15809 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15810 	}
15811 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15812 		toh = (struct T_opthdr *)optptr;
15813 		toh->level = IPPROTO_IPV6;
15814 		toh->name = IPV6_DSTOPTS;
15815 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15816 		toh->status = 0;
15817 		optptr += sizeof (*toh);
15818 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15819 		optptr += ipp->ipp_dstoptslen;
15820 		ASSERT(OK_32PTR(optptr));
15821 		/* Save as last value */
15822 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15823 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15824 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15825 	}
15826 	ASSERT(optptr == mp->b_wptr);
15827 	return (mp);
15828 }
15829 
15830 /*
15831  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15832  * messages.
15833  */
15834 void
15835 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15836 {
15837 	uchar_t	*rptr = mp->b_rptr;
15838 	queue_t	*q = tcp->tcp_rq;
15839 	struct T_error_ack *tea;
15840 
15841 	switch (mp->b_datap->db_type) {
15842 	case M_PROTO:
15843 	case M_PCPROTO:
15844 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15845 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15846 			break;
15847 		tea = (struct T_error_ack *)rptr;
15848 		ASSERT(tea->PRIM_type != T_BIND_ACK);
15849 		ASSERT(tea->ERROR_prim != O_T_BIND_REQ &&
15850 		    tea->ERROR_prim != T_BIND_REQ);
15851 		switch (tea->PRIM_type) {
15852 		case T_ERROR_ACK:
15853 			if (tcp->tcp_debug) {
15854 				(void) strlog(TCP_MOD_ID, 0, 1,
15855 				    SL_TRACE|SL_ERROR,
15856 				    "tcp_rput_other: case T_ERROR_ACK, "
15857 				    "ERROR_prim == %d",
15858 				    tea->ERROR_prim);
15859 			}
15860 			switch (tea->ERROR_prim) {
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 	/*
17335 	 * Attach credentials to retransmitted initial SYNs.
17336 	 * In theory we should use the credentials from the connect()
17337 	 * call to ensure that getpeerucred() on the peer will be correct.
17338 	 * But we assume that SYN's are not dropped for loopback connections.
17339 	 */
17340 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17341 		mblk_setcred(mp, tcp->tcp_cred, tcp->tcp_cpid);
17342 	}
17343 
17344 	tcp->tcp_csuna = tcp->tcp_snxt;
17345 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17346 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17347 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17348 
17349 }
17350 
17351 static int
17352 tcp_do_unbind(conn_t *connp)
17353 {
17354 	tcp_t *tcp = connp->conn_tcp;
17355 	int error = 0;
17356 
17357 	switch (tcp->tcp_state) {
17358 	case TCPS_BOUND:
17359 	case TCPS_LISTEN:
17360 		break;
17361 	default:
17362 		return (-TOUTSTATE);
17363 	}
17364 
17365 	/*
17366 	 * Need to clean up all the eagers since after the unbind, segments
17367 	 * will no longer be delivered to this listener stream.
17368 	 */
17369 	mutex_enter(&tcp->tcp_eager_lock);
17370 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17371 		tcp_eager_cleanup(tcp, 0);
17372 	}
17373 	mutex_exit(&tcp->tcp_eager_lock);
17374 
17375 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17376 		tcp->tcp_ipha->ipha_src = 0;
17377 	} else {
17378 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17379 	}
17380 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17381 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17382 	tcp_bind_hash_remove(tcp);
17383 	tcp->tcp_state = TCPS_IDLE;
17384 	tcp->tcp_mdt = B_FALSE;
17385 
17386 	connp = tcp->tcp_connp;
17387 	connp->conn_mdt_ok = B_FALSE;
17388 	ipcl_hash_remove(connp);
17389 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17390 
17391 	return (error);
17392 }
17393 
17394 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17395 static void
17396 tcp_tpi_unbind(tcp_t *tcp, mblk_t *mp)
17397 {
17398 	int error = tcp_do_unbind(tcp->tcp_connp);
17399 
17400 	if (error > 0) {
17401 		tcp_err_ack(tcp, mp, TSYSERR, error);
17402 	} else if (error < 0) {
17403 		tcp_err_ack(tcp, mp, -error, 0);
17404 	} else {
17405 		/* Send M_FLUSH according to TPI */
17406 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17407 
17408 		mp = mi_tpi_ok_ack_alloc(mp);
17409 		putnext(tcp->tcp_rq, mp);
17410 	}
17411 }
17412 
17413 /*
17414  * Don't let port fall into the privileged range.
17415  * Since the extra privileged ports can be arbitrary we also
17416  * ensure that we exclude those from consideration.
17417  * tcp_g_epriv_ports is not sorted thus we loop over it until
17418  * there are no changes.
17419  *
17420  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17421  * but instead the code relies on:
17422  * - the fact that the address of the array and its size never changes
17423  * - the atomic assignment of the elements of the array
17424  *
17425  * Returns 0 if there are no more ports available.
17426  *
17427  * TS note: skip multilevel ports.
17428  */
17429 static in_port_t
17430 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17431 {
17432 	int i;
17433 	boolean_t restart = B_FALSE;
17434 	tcp_stack_t *tcps = tcp->tcp_tcps;
17435 
17436 	if (random && tcp_random_anon_port != 0) {
17437 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17438 		    sizeof (in_port_t));
17439 		/*
17440 		 * Unless changed by a sys admin, the smallest anon port
17441 		 * is 32768 and the largest anon port is 65535.  It is
17442 		 * very likely (50%) for the random port to be smaller
17443 		 * than the smallest anon port.  When that happens,
17444 		 * add port % (anon port range) to the smallest anon
17445 		 * port to get the random port.  It should fall into the
17446 		 * valid anon port range.
17447 		 */
17448 		if (port < tcps->tcps_smallest_anon_port) {
17449 			port = tcps->tcps_smallest_anon_port +
17450 			    port % (tcps->tcps_largest_anon_port -
17451 			    tcps->tcps_smallest_anon_port);
17452 		}
17453 	}
17454 
17455 retry:
17456 	if (port < tcps->tcps_smallest_anon_port)
17457 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17458 
17459 	if (port > tcps->tcps_largest_anon_port) {
17460 		if (restart)
17461 			return (0);
17462 		restart = B_TRUE;
17463 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17464 	}
17465 
17466 	if (port < tcps->tcps_smallest_nonpriv_port)
17467 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17468 
17469 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17470 		if (port == tcps->tcps_g_epriv_ports[i]) {
17471 			port++;
17472 			/*
17473 			 * Make sure whether the port is in the
17474 			 * valid range.
17475 			 */
17476 			goto retry;
17477 		}
17478 	}
17479 	if (is_system_labeled() &&
17480 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17481 	    IPPROTO_TCP, B_TRUE)) != 0) {
17482 		port = i;
17483 		goto retry;
17484 	}
17485 	return (port);
17486 }
17487 
17488 /*
17489  * Return the next anonymous port in the privileged port range for
17490  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17491  * downwards.  This is the same behavior as documented in the userland
17492  * library call rresvport(3N).
17493  *
17494  * TS note: skip multilevel ports.
17495  */
17496 static in_port_t
17497 tcp_get_next_priv_port(const tcp_t *tcp)
17498 {
17499 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17500 	in_port_t nextport;
17501 	boolean_t restart = B_FALSE;
17502 	tcp_stack_t *tcps = tcp->tcp_tcps;
17503 retry:
17504 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17505 	    next_priv_port >= IPPORT_RESERVED) {
17506 		next_priv_port = IPPORT_RESERVED - 1;
17507 		if (restart)
17508 			return (0);
17509 		restart = B_TRUE;
17510 	}
17511 	if (is_system_labeled() &&
17512 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17513 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17514 		next_priv_port = nextport;
17515 		goto retry;
17516 	}
17517 	return (next_priv_port--);
17518 }
17519 
17520 /* The write side r/w procedure. */
17521 
17522 #if CCS_STATS
17523 struct {
17524 	struct {
17525 		int64_t count, bytes;
17526 	} tot, hit;
17527 } wrw_stats;
17528 #endif
17529 
17530 /*
17531  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17532  * messages.
17533  */
17534 /* ARGSUSED */
17535 static void
17536 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17537 {
17538 	conn_t	*connp = (conn_t *)arg;
17539 	tcp_t	*tcp = connp->conn_tcp;
17540 	queue_t	*q = tcp->tcp_wq;
17541 
17542 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17543 	/*
17544 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17545 	 * Once the close starts, streamhead and sockfs will not let any data
17546 	 * packets come down (close ensures that there are no threads using the
17547 	 * queue and no new threads will come down) but since qprocsoff()
17548 	 * hasn't happened yet, a M_FLUSH or some non data message might
17549 	 * get reflected back (in response to our own FLUSHRW) and get
17550 	 * processed after tcp_close() is done. The conn would still be valid
17551 	 * because a ref would have added but we need to check the state
17552 	 * before actually processing the packet.
17553 	 */
17554 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17555 		freemsg(mp);
17556 		return;
17557 	}
17558 
17559 	switch (DB_TYPE(mp)) {
17560 	case M_IOCDATA:
17561 		tcp_wput_iocdata(tcp, mp);
17562 		break;
17563 	case M_FLUSH:
17564 		tcp_wput_flush(tcp, mp);
17565 		break;
17566 	default:
17567 		CALL_IP_WPUT(connp, q, mp);
17568 		break;
17569 	}
17570 }
17571 
17572 /*
17573  * The TCP fast path write put procedure.
17574  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17575  */
17576 /* ARGSUSED */
17577 void
17578 tcp_output(void *arg, mblk_t *mp, void *arg2)
17579 {
17580 	int		len;
17581 	int		hdrlen;
17582 	int		plen;
17583 	mblk_t		*mp1;
17584 	uchar_t		*rptr;
17585 	uint32_t	snxt;
17586 	tcph_t		*tcph;
17587 	struct datab	*db;
17588 	uint32_t	suna;
17589 	uint32_t	mss;
17590 	ipaddr_t	*dst;
17591 	ipaddr_t	*src;
17592 	uint32_t	sum;
17593 	int		usable;
17594 	conn_t		*connp = (conn_t *)arg;
17595 	tcp_t		*tcp = connp->conn_tcp;
17596 	uint32_t	msize;
17597 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17598 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17599 
17600 	/*
17601 	 * Try and ASSERT the minimum possible references on the
17602 	 * conn early enough. Since we are executing on write side,
17603 	 * the connection is obviously not detached and that means
17604 	 * there is a ref each for TCP and IP. Since we are behind
17605 	 * the squeue, the minimum references needed are 3. If the
17606 	 * conn is in classifier hash list, there should be an
17607 	 * extra ref for that (we check both the possibilities).
17608 	 */
17609 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17610 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17611 
17612 	ASSERT(DB_TYPE(mp) == M_DATA);
17613 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17614 
17615 	mutex_enter(&tcp->tcp_non_sq_lock);
17616 	tcp->tcp_squeue_bytes -= msize;
17617 	mutex_exit(&tcp->tcp_non_sq_lock);
17618 
17619 	/* Check to see if this connection wants to be re-fused. */
17620 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17621 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17622 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17623 			    &tcp->tcp_saved_tcph);
17624 		} else {
17625 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17626 			    &tcp->tcp_saved_tcph);
17627 		}
17628 	}
17629 	/* Bypass tcp protocol for fused tcp loopback */
17630 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17631 		return;
17632 
17633 	mss = tcp->tcp_mss;
17634 	if (tcp->tcp_xmit_zc_clean)
17635 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17636 
17637 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17638 	len = (int)(mp->b_wptr - mp->b_rptr);
17639 
17640 	/*
17641 	 * Criteria for fast path:
17642 	 *
17643 	 *   1. no unsent data
17644 	 *   2. single mblk in request
17645 	 *   3. connection established
17646 	 *   4. data in mblk
17647 	 *   5. len <= mss
17648 	 *   6. no tcp_valid bits
17649 	 */
17650 	if ((tcp->tcp_unsent != 0) ||
17651 	    (tcp->tcp_cork) ||
17652 	    (mp->b_cont != NULL) ||
17653 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17654 	    (len == 0) ||
17655 	    (len > mss) ||
17656 	    (tcp->tcp_valid_bits != 0)) {
17657 		tcp_wput_data(tcp, mp, B_FALSE);
17658 		return;
17659 	}
17660 
17661 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17662 	ASSERT(tcp->tcp_fin_sent == 0);
17663 
17664 	/* queue new packet onto retransmission queue */
17665 	if (tcp->tcp_xmit_head == NULL) {
17666 		tcp->tcp_xmit_head = mp;
17667 	} else {
17668 		tcp->tcp_xmit_last->b_cont = mp;
17669 	}
17670 	tcp->tcp_xmit_last = mp;
17671 	tcp->tcp_xmit_tail = mp;
17672 
17673 	/* find out how much we can send */
17674 	/* BEGIN CSTYLED */
17675 	/*
17676 	 *    un-acked	   usable
17677 	 *  |--------------|-----------------|
17678 	 *  tcp_suna       tcp_snxt	  tcp_suna+tcp_swnd
17679 	 */
17680 	/* END CSTYLED */
17681 
17682 	/* start sending from tcp_snxt */
17683 	snxt = tcp->tcp_snxt;
17684 
17685 	/*
17686 	 * Check to see if this connection has been idled for some
17687 	 * time and no ACK is expected.  If it is, we need to slow
17688 	 * start again to get back the connection's "self-clock" as
17689 	 * described in VJ's paper.
17690 	 *
17691 	 * Refer to the comment in tcp_mss_set() for the calculation
17692 	 * of tcp_cwnd after idle.
17693 	 */
17694 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17695 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17696 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17697 	}
17698 
17699 	usable = tcp->tcp_swnd;		/* tcp window size */
17700 	if (usable > tcp->tcp_cwnd)
17701 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
17702 	usable -= snxt;		/* subtract stuff already sent */
17703 	suna = tcp->tcp_suna;
17704 	usable += suna;
17705 	/* usable can be < 0 if the congestion window is smaller */
17706 	if (len > usable) {
17707 		/* Can't send complete M_DATA in one shot */
17708 		goto slow;
17709 	}
17710 
17711 	mutex_enter(&tcp->tcp_non_sq_lock);
17712 	if (tcp->tcp_flow_stopped &&
17713 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
17714 		tcp_clrqfull(tcp);
17715 	}
17716 	mutex_exit(&tcp->tcp_non_sq_lock);
17717 
17718 	/*
17719 	 * determine if anything to send (Nagle).
17720 	 *
17721 	 *   1. len < tcp_mss (i.e. small)
17722 	 *   2. unacknowledged data present
17723 	 *   3. len < nagle limit
17724 	 *   4. last packet sent < nagle limit (previous packet sent)
17725 	 */
17726 	if ((len < mss) && (snxt != suna) &&
17727 	    (len < (int)tcp->tcp_naglim) &&
17728 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
17729 		/*
17730 		 * This was the first unsent packet and normally
17731 		 * mss < xmit_hiwater so there is no need to worry
17732 		 * about flow control. The next packet will go
17733 		 * through the flow control check in tcp_wput_data().
17734 		 */
17735 		/* leftover work from above */
17736 		tcp->tcp_unsent = len;
17737 		tcp->tcp_xmit_tail_unsent = len;
17738 
17739 		return;
17740 	}
17741 
17742 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
17743 
17744 	if (snxt == suna) {
17745 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
17746 	}
17747 
17748 	/* we have always sent something */
17749 	tcp->tcp_rack_cnt = 0;
17750 
17751 	tcp->tcp_snxt = snxt + len;
17752 	tcp->tcp_rack = tcp->tcp_rnxt;
17753 
17754 	if ((mp1 = dupb(mp)) == 0)
17755 		goto no_memory;
17756 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
17757 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
17758 
17759 	/* adjust tcp header information */
17760 	tcph = tcp->tcp_tcph;
17761 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
17762 
17763 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
17764 	sum = (sum >> 16) + (sum & 0xFFFF);
17765 	U16_TO_ABE16(sum, tcph->th_sum);
17766 
17767 	U32_TO_ABE32(snxt, tcph->th_seq);
17768 
17769 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
17770 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
17771 	BUMP_LOCAL(tcp->tcp_obsegs);
17772 
17773 	/* Update the latest receive window size in TCP header. */
17774 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
17775 	    tcph->th_win);
17776 
17777 	tcp->tcp_last_sent_len = (ushort_t)len;
17778 
17779 	plen = len + tcp->tcp_hdr_len;
17780 
17781 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17782 		tcp->tcp_ipha->ipha_length = htons(plen);
17783 	} else {
17784 		tcp->tcp_ip6h->ip6_plen = htons(plen -
17785 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
17786 	}
17787 
17788 	/* see if we need to allocate a mblk for the headers */
17789 	hdrlen = tcp->tcp_hdr_len;
17790 	rptr = mp1->b_rptr - hdrlen;
17791 	db = mp1->b_datap;
17792 	if ((db->db_ref != 2) || rptr < db->db_base ||
17793 	    (!OK_32PTR(rptr))) {
17794 		/* NOTE: we assume allocb returns an OK_32PTR */
17795 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
17796 		    tcps->tcps_wroff_xtra, BPRI_MED);
17797 		if (!mp) {
17798 			freemsg(mp1);
17799 			goto no_memory;
17800 		}
17801 		mp->b_cont = mp1;
17802 		mp1 = mp;
17803 		/* Leave room for Link Level header */
17804 		/* hdrlen = tcp->tcp_hdr_len; */
17805 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
17806 		mp1->b_wptr = &rptr[hdrlen];
17807 	}
17808 	mp1->b_rptr = rptr;
17809 
17810 	/* Fill in the timestamp option. */
17811 	if (tcp->tcp_snd_ts_ok) {
17812 		U32_TO_BE32((uint32_t)lbolt,
17813 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
17814 		U32_TO_BE32(tcp->tcp_ts_recent,
17815 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
17816 	} else {
17817 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
17818 	}
17819 
17820 	/* copy header into outgoing packet */
17821 	dst = (ipaddr_t *)rptr;
17822 	src = (ipaddr_t *)tcp->tcp_iphc;
17823 	dst[0] = src[0];
17824 	dst[1] = src[1];
17825 	dst[2] = src[2];
17826 	dst[3] = src[3];
17827 	dst[4] = src[4];
17828 	dst[5] = src[5];
17829 	dst[6] = src[6];
17830 	dst[7] = src[7];
17831 	dst[8] = src[8];
17832 	dst[9] = src[9];
17833 	if (hdrlen -= 40) {
17834 		hdrlen >>= 2;
17835 		dst += 10;
17836 		src += 10;
17837 		do {
17838 			*dst++ = *src++;
17839 		} while (--hdrlen);
17840 	}
17841 
17842 	/*
17843 	 * Set the ECN info in the TCP header.  Note that this
17844 	 * is not the template header.
17845 	 */
17846 	if (tcp->tcp_ecn_ok) {
17847 		SET_ECT(tcp, rptr);
17848 
17849 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
17850 		if (tcp->tcp_ecn_echo_on)
17851 			tcph->th_flags[0] |= TH_ECE;
17852 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
17853 			tcph->th_flags[0] |= TH_CWR;
17854 			tcp->tcp_ecn_cwr_sent = B_TRUE;
17855 		}
17856 	}
17857 
17858 	if (tcp->tcp_ip_forward_progress) {
17859 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
17860 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
17861 		tcp->tcp_ip_forward_progress = B_FALSE;
17862 	}
17863 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
17864 	return;
17865 
17866 	/*
17867 	 * If we ran out of memory, we pretend to have sent the packet
17868 	 * and that it was lost on the wire.
17869 	 */
17870 no_memory:
17871 	return;
17872 
17873 slow:
17874 	/* leftover work from above */
17875 	tcp->tcp_unsent = len;
17876 	tcp->tcp_xmit_tail_unsent = len;
17877 	tcp_wput_data(tcp, NULL, B_FALSE);
17878 }
17879 
17880 /* ARGSUSED */
17881 void
17882 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
17883 {
17884 	conn_t			*connp = (conn_t *)arg;
17885 	tcp_t			*tcp = connp->conn_tcp;
17886 	queue_t			*q = tcp->tcp_rq;
17887 	struct tcp_options	*tcpopt;
17888 	tcp_stack_t		*tcps = tcp->tcp_tcps;
17889 
17890 	/* socket options */
17891 	uint_t 			sopp_flags;
17892 	ssize_t			sopp_rxhiwat;
17893 	ssize_t			sopp_maxblk;
17894 	ushort_t		sopp_wroff;
17895 	ushort_t		sopp_tail;
17896 	ushort_t		sopp_copyopt;
17897 
17898 	tcpopt = (struct tcp_options *)mp->b_rptr;
17899 
17900 	/*
17901 	 * Drop the eager's ref on the listener, that was placed when
17902 	 * this eager began life in tcp_conn_request.
17903 	 */
17904 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
17905 	if (IPCL_IS_NONSTR(connp)) {
17906 		/* Safe to free conn_ind message */
17907 		freemsg(tcp->tcp_conn.tcp_eager_conn_ind);
17908 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
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, NULL);
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, NULL);
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 					 * We should never be in middle of a
18181 					 * fallback, the squeue guarantees that.
18182 					 */
18183 					ASSERT(error != EOPNOTSUPP);
18184 				}
18185 			}
18186 			tcp->tcp_rcv_last_head = NULL;
18187 			tcp->tcp_rcv_last_tail = NULL;
18188 			tcp->tcp_rcv_cnt = 0;
18189 		} else {
18190 			/* We drain directly in case of fused tcp loopback */
18191 			sodirect_t *sodp;
18192 
18193 			if (!tcp->tcp_fused && canputnext(q)) {
18194 				tcp->tcp_rwnd = q->q_hiwat;
18195 				if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18196 				    tcp_rwnd_reopen(tcp) == TH_ACK_NEEDED) {
18197 					tcp_xmit_ctl(NULL,
18198 					    tcp, (tcp->tcp_swnd == 0) ?
18199 					    tcp->tcp_suna : tcp->tcp_snxt,
18200 					    tcp->tcp_rnxt, TH_ACK);
18201 				}
18202 			}
18203 
18204 			SOD_PTR_ENTER(tcp, sodp);
18205 			if (sodp != NULL) {
18206 				/* Sodirect, move from rcv_list */
18207 				ASSERT(!tcp->tcp_fused);
18208 				while ((mp = tcp->tcp_rcv_list) != NULL) {
18209 					tcp->tcp_rcv_list = mp->b_next;
18210 					mp->b_next = NULL;
18211 					(void) tcp_rcv_sod_enqueue(tcp, sodp,
18212 					    mp, msgdsize(mp));
18213 				}
18214 				tcp->tcp_rcv_last_head = NULL;
18215 				tcp->tcp_rcv_last_tail = NULL;
18216 				tcp->tcp_rcv_cnt = 0;
18217 				(void) tcp_rcv_sod_wakeup(tcp, sodp);
18218 				/* sod_wakeup() did the mutex_exit() */
18219 			} else {
18220 				/* Not sodirect, drain */
18221 				(void) tcp_rcv_drain(tcp);
18222 			}
18223 		}
18224 
18225 		/*
18226 		 * For fused tcp loopback, back-enable peer endpoint
18227 		 * if it's currently flow-controlled.
18228 		 */
18229 		if (tcp->tcp_fused) {
18230 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18231 
18232 			ASSERT(peer_tcp != NULL);
18233 			ASSERT(peer_tcp->tcp_fused);
18234 			/*
18235 			 * In order to change the peer's tcp_flow_stopped,
18236 			 * we need to take locks for both end points. The
18237 			 * highest address is taken first.
18238 			 */
18239 			if (peer_tcp > tcp) {
18240 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18241 				mutex_enter(&tcp->tcp_non_sq_lock);
18242 			} else {
18243 				mutex_enter(&tcp->tcp_non_sq_lock);
18244 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18245 			}
18246 			if (peer_tcp->tcp_flow_stopped) {
18247 				tcp_clrqfull(peer_tcp);
18248 				TCP_STAT(tcps, tcp_fusion_backenabled);
18249 			}
18250 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18251 			mutex_exit(&tcp->tcp_non_sq_lock);
18252 		}
18253 	}
18254 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18255 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18256 		tcp->tcp_ordrel_done = B_TRUE;
18257 		if (IPCL_IS_NONSTR(connp)) {
18258 			ASSERT(tcp->tcp_ordrel_mp == NULL);
18259 			(*connp->conn_upcalls->su_opctl)(
18260 			    connp->conn_upper_handle,
18261 			    SOCK_OPCTL_SHUT_RECV, 0);
18262 		} else {
18263 			mp = tcp->tcp_ordrel_mp;
18264 			tcp->tcp_ordrel_mp = NULL;
18265 			putnext(q, mp);
18266 		}
18267 	}
18268 	if (tcp->tcp_hard_binding) {
18269 		tcp->tcp_hard_binding = B_FALSE;
18270 		tcp->tcp_hard_bound = B_TRUE;
18271 	}
18272 
18273 	/* We can enable synchronous streams for STREAMS tcp endpoint now */
18274 	if (tcp->tcp_fused && !IPCL_IS_NONSTR(connp) &&
18275 	    tcp->tcp_loopback_peer != NULL &&
18276 	    !IPCL_IS_NONSTR(tcp->tcp_loopback_peer->tcp_connp)) {
18277 		tcp_fuse_syncstr_enable_pair(tcp);
18278 	}
18279 
18280 	if (tcp->tcp_ka_enabled) {
18281 		tcp->tcp_ka_last_intrvl = 0;
18282 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18283 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18284 	}
18285 
18286 	/*
18287 	 * At this point, eager is fully established and will
18288 	 * have the following references -
18289 	 *
18290 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18291 	 * 1 reference for the squeue which will be dropped by the squeue as
18292 	 *	soon as this function returns.
18293 	 * There will be 1 additonal reference for being in classifier
18294 	 *	hash list provided something bad hasn't happened.
18295 	 */
18296 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18297 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18298 }
18299 
18300 /*
18301  * The function called through squeue to get behind listener's perimeter to
18302  * send a deffered conn_ind.
18303  */
18304 /* ARGSUSED */
18305 void
18306 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18307 {
18308 	conn_t	*connp = (conn_t *)arg;
18309 	tcp_t *listener = connp->conn_tcp;
18310 	struct T_conn_ind *conn_ind;
18311 	tcp_t *tcp;
18312 
18313 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
18314 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18315 	    conn_ind->OPT_length);
18316 
18317 	if (listener->tcp_state == TCPS_CLOSED ||
18318 	    TCP_IS_DETACHED(listener)) {
18319 		/*
18320 		 * If listener has closed, it would have caused a
18321 		 * a cleanup/blowoff to happen for the eager.
18322 		 *
18323 		 * We need to drop the ref on eager that was put
18324 		 * tcp_rput_data() before trying to send the conn_ind
18325 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18326 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18327 		 * listener is closed so we drop the ref.
18328 		 */
18329 		CONN_DEC_REF(tcp->tcp_connp);
18330 		freemsg(mp);
18331 		return;
18332 	}
18333 
18334 	tcp_ulp_newconn(connp, tcp->tcp_connp, mp);
18335 }
18336 
18337 /* ARGSUSED */
18338 static int
18339 tcp_accept_common(conn_t *lconnp, conn_t *econnp, cred_t *cr)
18340 {
18341 	tcp_t *listener, *eager;
18342 	mblk_t *opt_mp;
18343 	struct tcp_options *tcpopt;
18344 
18345 	listener = lconnp->conn_tcp;
18346 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18347 	eager = econnp->conn_tcp;
18348 	ASSERT(eager->tcp_listener != NULL);
18349 
18350 	ASSERT(eager->tcp_rq != NULL);
18351 
18352 	/* If tcp_fused and sodirect enabled disable it */
18353 	if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18354 		/* Fused, disable sodirect */
18355 		mutex_enter(eager->tcp_sodirect->sod_lockp);
18356 		SOD_DISABLE(eager->tcp_sodirect);
18357 		mutex_exit(eager->tcp_sodirect->sod_lockp);
18358 		eager->tcp_sodirect = NULL;
18359 	}
18360 
18361 	opt_mp = allocb(sizeof (struct tcp_options), BPRI_HI);
18362 	if (opt_mp == NULL) {
18363 		return (-TPROTO);
18364 	}
18365 	bzero((char *)opt_mp->b_rptr, sizeof (struct tcp_options));
18366 	eager->tcp_issocket = B_TRUE;
18367 
18368 	econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18369 	econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18370 	ASSERT(econnp->conn_netstack ==
18371 	    listener->tcp_connp->conn_netstack);
18372 	ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18373 
18374 	/* Put the ref for IP */
18375 	CONN_INC_REF(econnp);
18376 
18377 	/*
18378 	 * We should have minimum of 3 references on the conn
18379 	 * at this point. One each for TCP and IP and one for
18380 	 * the T_conn_ind that was sent up when the 3-way handshake
18381 	 * completed. In the normal case we would also have another
18382 	 * reference (making a total of 4) for the conn being in the
18383 	 * classifier hash list. However the eager could have received
18384 	 * an RST subsequently and tcp_closei_local could have removed
18385 	 * the eager from the classifier hash list, hence we can't
18386 	 * assert that reference.
18387 	 */
18388 	ASSERT(econnp->conn_ref >= 3);
18389 
18390 	opt_mp->b_datap->db_type = M_SETOPTS;
18391 	opt_mp->b_wptr += sizeof (struct tcp_options);
18392 
18393 	/*
18394 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18395 	 * from listener to acceptor.
18396 	 */
18397 	tcpopt = (struct tcp_options *)opt_mp->b_rptr;
18398 	tcpopt->to_flags = 0;
18399 
18400 	if (listener->tcp_bound_if != 0) {
18401 		tcpopt->to_flags |= TCPOPT_BOUNDIF;
18402 		tcpopt->to_boundif = listener->tcp_bound_if;
18403 	}
18404 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18405 		tcpopt->to_flags |= TCPOPT_RECVPKTINFO;
18406 	}
18407 
18408 	mutex_enter(&listener->tcp_eager_lock);
18409 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18410 
18411 		tcp_t *tail;
18412 		tcp_t *tcp;
18413 		mblk_t *mp1;
18414 
18415 		tcp = listener->tcp_eager_prev_q0;
18416 		/*
18417 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
18418 		 * deferred T_conn_ind queue. We need to get to the head
18419 		 * of the queue in order to send up T_conn_ind the same
18420 		 * order as how the 3WHS is completed.
18421 		 */
18422 		while (tcp != listener) {
18423 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18424 			    !tcp->tcp_kssl_pending)
18425 				break;
18426 			else
18427 				tcp = tcp->tcp_eager_prev_q0;
18428 		}
18429 		/* None of the pending eagers can be sent up now */
18430 		if (tcp == listener)
18431 			goto no_more_eagers;
18432 
18433 		mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18434 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18435 		/* Move from q0 to q */
18436 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18437 		listener->tcp_conn_req_cnt_q0--;
18438 		listener->tcp_conn_req_cnt_q++;
18439 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18440 		    tcp->tcp_eager_prev_q0;
18441 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18442 		    tcp->tcp_eager_next_q0;
18443 		tcp->tcp_eager_prev_q0 = NULL;
18444 		tcp->tcp_eager_next_q0 = NULL;
18445 		tcp->tcp_conn_def_q0 = B_FALSE;
18446 
18447 		/* Make sure the tcp isn't in the list of droppables */
18448 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18449 		    tcp->tcp_eager_prev_drop_q0 == NULL);
18450 
18451 		/*
18452 		 * Insert at end of the queue because sockfs sends
18453 		 * down T_CONN_RES in chronological order. Leaving
18454 		 * the older conn indications at front of the queue
18455 		 * helps reducing search time.
18456 		 */
18457 		tail = listener->tcp_eager_last_q;
18458 		if (tail != NULL) {
18459 			tail->tcp_eager_next_q = tcp;
18460 		} else {
18461 			listener->tcp_eager_next_q = tcp;
18462 		}
18463 		listener->tcp_eager_last_q = tcp;
18464 		tcp->tcp_eager_next_q = NULL;
18465 
18466 		/* Need to get inside the listener perimeter */
18467 		CONN_INC_REF(listener->tcp_connp);
18468 		SQUEUE_ENTER_ONE(listener->tcp_connp->conn_sqp, mp1,
18469 		    tcp_send_pending, listener->tcp_connp, SQ_FILL,
18470 		    SQTAG_TCP_SEND_PENDING);
18471 	}
18472 no_more_eagers:
18473 	tcp_eager_unlink(eager);
18474 	mutex_exit(&listener->tcp_eager_lock);
18475 
18476 	/*
18477 	 * At this point, the eager is detached from the listener
18478 	 * but we still have an extra refs on eager (apart from the
18479 	 * usual tcp references). The ref was placed in tcp_rput_data
18480 	 * before sending the conn_ind in tcp_send_conn_ind.
18481 	 * The ref will be dropped in tcp_accept_finish().
18482 	 */
18483 	SQUEUE_ENTER_ONE(econnp->conn_sqp, opt_mp, tcp_accept_finish,
18484 	    econnp, SQ_NODRAIN, SQTAG_TCP_ACCEPT_FINISH_Q0);
18485 	return (0);
18486 }
18487 
18488 int
18489 tcp_accept(sock_lower_handle_t lproto_handle,
18490     sock_lower_handle_t eproto_handle, sock_upper_handle_t sock_handle,
18491     cred_t *cr)
18492 {
18493 	conn_t *lconnp, *econnp;
18494 	tcp_t *listener, *eager;
18495 	tcp_stack_t	*tcps;
18496 
18497 	lconnp = (conn_t *)lproto_handle;
18498 	listener = lconnp->conn_tcp;
18499 	ASSERT(listener->tcp_state == TCPS_LISTEN);
18500 	econnp = (conn_t *)eproto_handle;
18501 	eager = econnp->conn_tcp;
18502 	ASSERT(eager->tcp_listener != NULL);
18503 	tcps = eager->tcp_tcps;
18504 
18505 	/*
18506 	 * It is OK to manipulate these fields outside the eager's squeue
18507 	 * because they will not start being used until tcp_accept_finish
18508 	 * has been called.
18509 	 */
18510 	ASSERT(lconnp->conn_upper_handle != NULL);
18511 	ASSERT(econnp->conn_upper_handle == NULL);
18512 	econnp->conn_upper_handle = sock_handle;
18513 	econnp->conn_upcalls = lconnp->conn_upcalls;
18514 	ASSERT(IPCL_IS_NONSTR(econnp));
18515 	/*
18516 	 * Create helper stream if it is a non-TPI TCP connection.
18517 	 */
18518 	if (ip_create_helper_stream(econnp, tcps->tcps_ldi_ident)) {
18519 		ip1dbg(("tcp_accept: create of IP helper stream"
18520 		    " failed\n"));
18521 		return (EPROTO);
18522 	}
18523 	eager->tcp_rq = econnp->conn_rq;
18524 	eager->tcp_wq = econnp->conn_wq;
18525 
18526 	ASSERT(eager->tcp_rq != NULL);
18527 
18528 	eager->tcp_sodirect = SOD_SOTOSODP(sock_handle);
18529 	return (tcp_accept_common(lconnp, econnp, cr));
18530 }
18531 
18532 
18533 /*
18534  * This is the STREAMS entry point for T_CONN_RES coming down on
18535  * Acceptor STREAM when  sockfs listener does accept processing.
18536  * Read the block comment on top of tcp_conn_request().
18537  */
18538 void
18539 tcp_tpi_accept(queue_t *q, mblk_t *mp)
18540 {
18541 	queue_t *rq = RD(q);
18542 	struct T_conn_res *conn_res;
18543 	tcp_t *eager;
18544 	tcp_t *listener;
18545 	struct T_ok_ack *ok;
18546 	t_scalar_t PRIM_type;
18547 	conn_t *econnp;
18548 	cred_t *cr;
18549 
18550 	ASSERT(DB_TYPE(mp) == M_PROTO);
18551 
18552 	/*
18553 	 * All Solaris components should pass a db_credp
18554 	 * for this TPI message, hence we ASSERT.
18555 	 * But in case there is some other M_PROTO that looks
18556 	 * like a TPI message sent by some other kernel
18557 	 * component, we check and return an error.
18558 	 */
18559 	cr = msg_getcred(mp, NULL);
18560 	ASSERT(cr != NULL);
18561 	if (cr == NULL) {
18562 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
18563 		if (mp != NULL)
18564 			putnext(rq, mp);
18565 		return;
18566 	}
18567 	conn_res = (struct T_conn_res *)mp->b_rptr;
18568 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18569 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18570 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18571 		if (mp != NULL)
18572 			putnext(rq, mp);
18573 		return;
18574 	}
18575 	switch (conn_res->PRIM_type) {
18576 	case O_T_CONN_RES:
18577 	case T_CONN_RES:
18578 		/*
18579 		 * We pass up an err ack if allocb fails. This will
18580 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18581 		 * tcp_eager_blowoff to be called. sockfs will then call
18582 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18583 		 * we need to do the allocb up here because we have to
18584 		 * make sure rq->q_qinfo->qi_qclose still points to the
18585 		 * correct function (tcpclose_accept) in case allocb
18586 		 * fails.
18587 		 */
18588 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18589 		    &eager, conn_res->OPT_length);
18590 		PRIM_type = conn_res->PRIM_type;
18591 		mp->b_datap->db_type = M_PCPROTO;
18592 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18593 		ok = (struct T_ok_ack *)mp->b_rptr;
18594 		ok->PRIM_type = T_OK_ACK;
18595 		ok->CORRECT_prim = PRIM_type;
18596 		econnp = eager->tcp_connp;
18597 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18598 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18599 		eager->tcp_rq = rq;
18600 		eager->tcp_wq = q;
18601 		rq->q_ptr = econnp;
18602 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18603 		q->q_ptr = econnp;
18604 		q->q_qinfo = &tcp_winit;
18605 		listener = eager->tcp_listener;
18606 
18607 		/*
18608 		 * TCP is _D_SODIRECT and sockfs is directly above so
18609 		 * save shared sodirect_t pointer (if any).
18610 		 */
18611 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18612 		if (tcp_accept_common(listener->tcp_connp,
18613 		    econnp, cr) < 0) {
18614 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18615 			if (mp != NULL)
18616 				putnext(rq, mp);
18617 			return;
18618 		}
18619 
18620 		/*
18621 		 * Send the new local address also up to sockfs. There
18622 		 * should already be enough space in the mp that came
18623 		 * down from soaccept().
18624 		 */
18625 		if (eager->tcp_family == AF_INET) {
18626 			sin_t *sin;
18627 
18628 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18629 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18630 			sin = (sin_t *)mp->b_wptr;
18631 			mp->b_wptr += sizeof (sin_t);
18632 			sin->sin_family = AF_INET;
18633 			sin->sin_port = eager->tcp_lport;
18634 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18635 		} else {
18636 			sin6_t *sin6;
18637 
18638 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18639 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18640 			sin6 = (sin6_t *)mp->b_wptr;
18641 			mp->b_wptr += sizeof (sin6_t);
18642 			sin6->sin6_family = AF_INET6;
18643 			sin6->sin6_port = eager->tcp_lport;
18644 			if (eager->tcp_ipversion == IPV4_VERSION) {
18645 				sin6->sin6_flowinfo = 0;
18646 				IN6_IPADDR_TO_V4MAPPED(
18647 				    eager->tcp_ipha->ipha_src,
18648 				    &sin6->sin6_addr);
18649 			} else {
18650 				ASSERT(eager->tcp_ip6h != NULL);
18651 				sin6->sin6_flowinfo =
18652 				    eager->tcp_ip6h->ip6_vcf &
18653 				    ~IPV6_VERS_AND_FLOW_MASK;
18654 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18655 			}
18656 			sin6->sin6_scope_id = 0;
18657 			sin6->__sin6_src_id = 0;
18658 		}
18659 
18660 		putnext(rq, mp);
18661 		return;
18662 	default:
18663 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18664 		if (mp != NULL)
18665 			putnext(rq, mp);
18666 		return;
18667 	}
18668 }
18669 
18670 static int
18671 tcp_do_getsockname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18672 {
18673 	sin_t *sin = (sin_t *)sa;
18674 	sin6_t *sin6 = (sin6_t *)sa;
18675 
18676 	switch (tcp->tcp_family) {
18677 	case AF_INET:
18678 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18679 
18680 		if (*salenp < sizeof (sin_t))
18681 			return (EINVAL);
18682 
18683 		*sin = sin_null;
18684 		sin->sin_family = AF_INET;
18685 		if (tcp->tcp_state >= TCPS_BOUND) {
18686 			sin->sin_port = tcp->tcp_lport;
18687 			sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18688 		}
18689 		*salenp = sizeof (sin_t);
18690 		break;
18691 
18692 	case AF_INET6:
18693 		if (*salenp < sizeof (sin6_t))
18694 			return (EINVAL);
18695 
18696 		*sin6 = sin6_null;
18697 		sin6->sin6_family = AF_INET6;
18698 		if (tcp->tcp_state >= TCPS_BOUND) {
18699 			sin6->sin6_port = tcp->tcp_lport;
18700 			if (tcp->tcp_ipversion == IPV4_VERSION) {
18701 				IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18702 				    &sin6->sin6_addr);
18703 			} else {
18704 				sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18705 			}
18706 		}
18707 		*salenp = sizeof (sin6_t);
18708 		break;
18709 	}
18710 
18711 	return (0);
18712 }
18713 
18714 static int
18715 tcp_do_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18716 {
18717 	sin_t *sin = (sin_t *)sa;
18718 	sin6_t *sin6 = (sin6_t *)sa;
18719 
18720 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18721 		return (ENOTCONN);
18722 
18723 	switch (tcp->tcp_family) {
18724 	case AF_INET:
18725 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18726 
18727 		if (*salenp < sizeof (sin_t))
18728 			return (EINVAL);
18729 
18730 		*sin = sin_null;
18731 		sin->sin_family = AF_INET;
18732 		sin->sin_port = tcp->tcp_fport;
18733 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18734 		    sin->sin_addr.s_addr);
18735 		*salenp = sizeof (sin_t);
18736 		break;
18737 
18738 	case AF_INET6:
18739 		if (*salenp < sizeof (sin6_t))
18740 			return (EINVAL);
18741 
18742 		*sin6 = sin6_null;
18743 		sin6->sin6_family = AF_INET6;
18744 		sin6->sin6_port = tcp->tcp_fport;
18745 		sin6->sin6_addr = tcp->tcp_remote_v6;
18746 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18747 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18748 			    ~IPV6_VERS_AND_FLOW_MASK;
18749 		}
18750 		*salenp = sizeof (sin6_t);
18751 		break;
18752 	}
18753 
18754 	return (0);
18755 }
18756 
18757 /*
18758  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18759  */
18760 static void
18761 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18762 {
18763 	void	*data;
18764 	mblk_t	*datamp = mp->b_cont;
18765 	tcp_t	*tcp = Q_TO_TCP(q);
18766 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18767 
18768 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18769 		cmdp->cb_error = EPROTO;
18770 		qreply(q, mp);
18771 		return;
18772 	}
18773 
18774 	data = datamp->b_rptr;
18775 
18776 	switch (cmdp->cb_cmd) {
18777 	case TI_GETPEERNAME:
18778 		cmdp->cb_error = tcp_do_getpeername(tcp, data, &cmdp->cb_len);
18779 		break;
18780 	case TI_GETMYNAME:
18781 		cmdp->cb_error = tcp_do_getsockname(tcp, data, &cmdp->cb_len);
18782 		break;
18783 	default:
18784 		cmdp->cb_error = EINVAL;
18785 		break;
18786 	}
18787 
18788 	qreply(q, mp);
18789 }
18790 
18791 void
18792 tcp_wput(queue_t *q, mblk_t *mp)
18793 {
18794 	conn_t	*connp = Q_TO_CONN(q);
18795 	tcp_t	*tcp;
18796 	void (*output_proc)();
18797 	t_scalar_t type;
18798 	uchar_t *rptr;
18799 	struct iocblk	*iocp;
18800 	size_t size;
18801 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18802 
18803 	ASSERT(connp->conn_ref >= 2);
18804 
18805 	switch (DB_TYPE(mp)) {
18806 	case M_DATA:
18807 		tcp = connp->conn_tcp;
18808 		ASSERT(tcp != NULL);
18809 
18810 		size = msgdsize(mp);
18811 
18812 		mutex_enter(&tcp->tcp_non_sq_lock);
18813 		tcp->tcp_squeue_bytes += size;
18814 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18815 			tcp_setqfull(tcp);
18816 		}
18817 		mutex_exit(&tcp->tcp_non_sq_lock);
18818 
18819 		CONN_INC_REF(connp);
18820 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output, connp,
18821 		    tcp_squeue_flag, SQTAG_TCP_OUTPUT);
18822 		return;
18823 
18824 	case M_CMD:
18825 		tcp_wput_cmdblk(q, mp);
18826 		return;
18827 
18828 	case M_PROTO:
18829 	case M_PCPROTO:
18830 		/*
18831 		 * if it is a snmp message, don't get behind the squeue
18832 		 */
18833 		tcp = connp->conn_tcp;
18834 		rptr = mp->b_rptr;
18835 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18836 			type = ((union T_primitives *)rptr)->type;
18837 		} else {
18838 			if (tcp->tcp_debug) {
18839 				(void) strlog(TCP_MOD_ID, 0, 1,
18840 				    SL_ERROR|SL_TRACE,
18841 				    "tcp_wput_proto, dropping one...");
18842 			}
18843 			freemsg(mp);
18844 			return;
18845 		}
18846 		if (type == T_SVR4_OPTMGMT_REQ) {
18847 			/*
18848 			 * All Solaris components should pass a db_credp
18849 			 * for this TPI message, hence we ASSERT.
18850 			 * But in case there is some other M_PROTO that looks
18851 			 * like a TPI message sent by some other kernel
18852 			 * component, we check and return an error.
18853 			 */
18854 			cred_t	*cr = msg_getcred(mp, NULL);
18855 
18856 			ASSERT(cr != NULL);
18857 			if (cr == NULL) {
18858 				tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
18859 				return;
18860 			}
18861 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18862 			    cr)) {
18863 				/*
18864 				 * This was a SNMP request
18865 				 */
18866 				return;
18867 			} else {
18868 				output_proc = tcp_wput_proto;
18869 			}
18870 		} else {
18871 			output_proc = tcp_wput_proto;
18872 		}
18873 		break;
18874 	case M_IOCTL:
18875 		/*
18876 		 * Most ioctls can be processed right away without going via
18877 		 * squeues - process them right here. Those that do require
18878 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18879 		 * are processed by tcp_wput_ioctl().
18880 		 */
18881 		iocp = (struct iocblk *)mp->b_rptr;
18882 		tcp = connp->conn_tcp;
18883 
18884 		switch (iocp->ioc_cmd) {
18885 		case TCP_IOC_ABORT_CONN:
18886 			tcp_ioctl_abort_conn(q, mp);
18887 			return;
18888 		case TI_GETPEERNAME:
18889 		case TI_GETMYNAME:
18890 			mi_copyin(q, mp, NULL,
18891 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18892 			return;
18893 		case ND_SET:
18894 			/* nd_getset does the necessary checks */
18895 		case ND_GET:
18896 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18897 				CALL_IP_WPUT(connp, q, mp);
18898 				return;
18899 			}
18900 			qreply(q, mp);
18901 			return;
18902 		case TCP_IOC_DEFAULT_Q:
18903 			/*
18904 			 * Wants to be the default wq. Check the credentials
18905 			 * first, the rest is executed via squeue.
18906 			 */
18907 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
18908 				iocp->ioc_error = EPERM;
18909 				iocp->ioc_count = 0;
18910 				mp->b_datap->db_type = M_IOCACK;
18911 				qreply(q, mp);
18912 				return;
18913 			}
18914 			output_proc = tcp_wput_ioctl;
18915 			break;
18916 		default:
18917 			output_proc = tcp_wput_ioctl;
18918 			break;
18919 		}
18920 		break;
18921 	default:
18922 		output_proc = tcp_wput_nondata;
18923 		break;
18924 	}
18925 
18926 	CONN_INC_REF(connp);
18927 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, output_proc, connp,
18928 	    tcp_squeue_flag, SQTAG_TCP_WPUT_OTHER);
18929 }
18930 
18931 /*
18932  * Initial STREAMS write side put() procedure for sockets. It tries to
18933  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
18934  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
18935  * are handled by tcp_wput() as usual.
18936  *
18937  * All further messages will also be handled by tcp_wput() because we cannot
18938  * be sure that the above short cut is safe later.
18939  */
18940 static void
18941 tcp_wput_sock(queue_t *wq, mblk_t *mp)
18942 {
18943 	conn_t			*connp = Q_TO_CONN(wq);
18944 	tcp_t			*tcp = connp->conn_tcp;
18945 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
18946 
18947 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
18948 	wq->q_qinfo = &tcp_winit;
18949 
18950 	ASSERT(IPCL_IS_TCP(connp));
18951 	ASSERT(TCP_IS_SOCKET(tcp));
18952 
18953 	if (DB_TYPE(mp) == M_PCPROTO &&
18954 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
18955 	    car->PRIM_type == T_CAPABILITY_REQ) {
18956 		tcp_capability_req(tcp, mp);
18957 		return;
18958 	}
18959 
18960 	tcp_wput(wq, mp);
18961 }
18962 
18963 /* ARGSUSED */
18964 static void
18965 tcp_wput_fallback(queue_t *wq, mblk_t *mp)
18966 {
18967 #ifdef DEBUG
18968 	cmn_err(CE_CONT, "tcp_wput_fallback: Message during fallback \n");
18969 #endif
18970 	freemsg(mp);
18971 }
18972 
18973 static boolean_t
18974 tcp_zcopy_check(tcp_t *tcp)
18975 {
18976 	conn_t	*connp = tcp->tcp_connp;
18977 	ire_t	*ire;
18978 	boolean_t	zc_enabled = B_FALSE;
18979 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18980 
18981 	if (do_tcpzcopy == 2)
18982 		zc_enabled = B_TRUE;
18983 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
18984 	    IPCL_IS_CONNECTED(connp) &&
18985 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
18986 	    connp->conn_dontroute == 0 &&
18987 	    !connp->conn_nexthop_set &&
18988 	    connp->conn_outgoing_ill == NULL &&
18989 	    do_tcpzcopy == 1) {
18990 		/*
18991 		 * the checks above  closely resemble the fast path checks
18992 		 * in tcp_send_data().
18993 		 */
18994 		mutex_enter(&connp->conn_lock);
18995 		ire = connp->conn_ire_cache;
18996 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
18997 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
18998 			IRE_REFHOLD(ire);
18999 			if (ire->ire_stq != NULL) {
19000 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
19001 
19002 				zc_enabled = ill && (ill->ill_capabilities &
19003 				    ILL_CAPAB_ZEROCOPY) &&
19004 				    (ill->ill_zerocopy_capab->
19005 				    ill_zerocopy_flags != 0);
19006 			}
19007 			IRE_REFRELE(ire);
19008 		}
19009 		mutex_exit(&connp->conn_lock);
19010 	}
19011 	tcp->tcp_snd_zcopy_on = zc_enabled;
19012 	if (!TCP_IS_DETACHED(tcp)) {
19013 		if (zc_enabled) {
19014 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
19015 			    ZCVMSAFE);
19016 			TCP_STAT(tcps, tcp_zcopy_on);
19017 		} else {
19018 			(void) proto_set_tx_copyopt(tcp->tcp_rq, connp,
19019 			    ZCVMUNSAFE);
19020 			TCP_STAT(tcps, tcp_zcopy_off);
19021 		}
19022 	}
19023 	return (zc_enabled);
19024 }
19025 
19026 static mblk_t *
19027 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
19028 {
19029 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19030 
19031 	if (do_tcpzcopy == 2)
19032 		return (bp);
19033 	else if (tcp->tcp_snd_zcopy_on) {
19034 		tcp->tcp_snd_zcopy_on = B_FALSE;
19035 		if (!TCP_IS_DETACHED(tcp)) {
19036 			(void) proto_set_tx_copyopt(tcp->tcp_rq, tcp->tcp_connp,
19037 			    ZCVMUNSAFE);
19038 			TCP_STAT(tcps, tcp_zcopy_disable);
19039 		}
19040 	}
19041 	return (tcp_zcopy_backoff(tcp, bp, 0));
19042 }
19043 
19044 /*
19045  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
19046  * the original desballoca'ed segmapped mblk.
19047  */
19048 static mblk_t *
19049 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
19050 {
19051 	mblk_t *head, *tail, *nbp;
19052 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19053 
19054 	if (IS_VMLOANED_MBLK(bp)) {
19055 		TCP_STAT(tcps, tcp_zcopy_backoff);
19056 		if ((head = copyb(bp)) == NULL) {
19057 			/* fail to backoff; leave it for the next backoff */
19058 			tcp->tcp_xmit_zc_clean = B_FALSE;
19059 			return (bp);
19060 		}
19061 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19062 			if (fix_xmitlist)
19063 				tcp_zcopy_notify(tcp);
19064 			else
19065 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19066 		}
19067 		nbp = bp->b_cont;
19068 		if (fix_xmitlist) {
19069 			head->b_prev = bp->b_prev;
19070 			head->b_next = bp->b_next;
19071 			if (tcp->tcp_xmit_tail == bp)
19072 				tcp->tcp_xmit_tail = head;
19073 		}
19074 		bp->b_next = NULL;
19075 		bp->b_prev = NULL;
19076 		freeb(bp);
19077 	} else {
19078 		head = bp;
19079 		nbp = bp->b_cont;
19080 	}
19081 	tail = head;
19082 	while (nbp) {
19083 		if (IS_VMLOANED_MBLK(nbp)) {
19084 			TCP_STAT(tcps, tcp_zcopy_backoff);
19085 			if ((tail->b_cont = copyb(nbp)) == NULL) {
19086 				tcp->tcp_xmit_zc_clean = B_FALSE;
19087 				tail->b_cont = nbp;
19088 				return (head);
19089 			}
19090 			tail = tail->b_cont;
19091 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19092 				if (fix_xmitlist)
19093 					tcp_zcopy_notify(tcp);
19094 				else
19095 					tail->b_datap->db_struioflag |=
19096 					    STRUIO_ZCNOTIFY;
19097 			}
19098 			bp = nbp;
19099 			nbp = nbp->b_cont;
19100 			if (fix_xmitlist) {
19101 				tail->b_prev = bp->b_prev;
19102 				tail->b_next = bp->b_next;
19103 				if (tcp->tcp_xmit_tail == bp)
19104 					tcp->tcp_xmit_tail = tail;
19105 			}
19106 			bp->b_next = NULL;
19107 			bp->b_prev = NULL;
19108 			freeb(bp);
19109 		} else {
19110 			tail->b_cont = nbp;
19111 			tail = nbp;
19112 			nbp = nbp->b_cont;
19113 		}
19114 	}
19115 	if (fix_xmitlist) {
19116 		tcp->tcp_xmit_last = tail;
19117 		tcp->tcp_xmit_zc_clean = B_TRUE;
19118 	}
19119 	return (head);
19120 }
19121 
19122 static void
19123 tcp_zcopy_notify(tcp_t *tcp)
19124 {
19125 	struct stdata	*stp;
19126 	conn_t *connp;
19127 
19128 	if (tcp->tcp_detached)
19129 		return;
19130 	connp = tcp->tcp_connp;
19131 	if (IPCL_IS_NONSTR(connp)) {
19132 		(*connp->conn_upcalls->su_zcopy_notify)
19133 		    (connp->conn_upper_handle);
19134 		return;
19135 	}
19136 	stp = STREAM(tcp->tcp_rq);
19137 	mutex_enter(&stp->sd_lock);
19138 	stp->sd_flag |= STZCNOTIFY;
19139 	cv_broadcast(&stp->sd_zcopy_wait);
19140 	mutex_exit(&stp->sd_lock);
19141 }
19142 
19143 static boolean_t
19144 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19145 {
19146 	ire_t	*ire;
19147 	conn_t	*connp = tcp->tcp_connp;
19148 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19149 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19150 
19151 	mutex_enter(&connp->conn_lock);
19152 	ire = connp->conn_ire_cache;
19153 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19154 
19155 	if ((ire != NULL) &&
19156 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19157 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19158 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19159 		IRE_REFHOLD(ire);
19160 		mutex_exit(&connp->conn_lock);
19161 	} else {
19162 		boolean_t cached = B_FALSE;
19163 		ts_label_t *tsl;
19164 
19165 		/* force a recheck later on */
19166 		tcp->tcp_ire_ill_check_done = B_FALSE;
19167 
19168 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19169 		connp->conn_ire_cache = NULL;
19170 		mutex_exit(&connp->conn_lock);
19171 
19172 		if (ire != NULL)
19173 			IRE_REFRELE_NOTR(ire);
19174 
19175 		tsl = crgetlabel(CONN_CRED(connp));
19176 		ire = (dst ?
19177 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19178 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19179 		    connp->conn_zoneid, tsl, ipst));
19180 
19181 		if (ire == NULL) {
19182 			TCP_STAT(tcps, tcp_ire_null);
19183 			return (B_FALSE);
19184 		}
19185 
19186 		IRE_REFHOLD_NOTR(ire);
19187 
19188 		mutex_enter(&connp->conn_lock);
19189 		if (CONN_CACHE_IRE(connp)) {
19190 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19191 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19192 				TCP_CHECK_IREINFO(tcp, ire);
19193 				connp->conn_ire_cache = ire;
19194 				cached = B_TRUE;
19195 			}
19196 			rw_exit(&ire->ire_bucket->irb_lock);
19197 		}
19198 		mutex_exit(&connp->conn_lock);
19199 
19200 		/*
19201 		 * We can continue to use the ire but since it was
19202 		 * not cached, we should drop the extra reference.
19203 		 */
19204 		if (!cached)
19205 			IRE_REFRELE_NOTR(ire);
19206 
19207 		/*
19208 		 * Rampart note: no need to select a new label here, since
19209 		 * labels are not allowed to change during the life of a TCP
19210 		 * connection.
19211 		 */
19212 	}
19213 
19214 	*irep = ire;
19215 
19216 	return (B_TRUE);
19217 }
19218 
19219 /*
19220  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19221  *
19222  * 0 = success;
19223  * 1 = failed to find ire and ill.
19224  */
19225 static boolean_t
19226 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19227 {
19228 	ipha_t		*ipha;
19229 	ipaddr_t	dst;
19230 	ire_t		*ire;
19231 	ill_t		*ill;
19232 	mblk_t		*ire_fp_mp;
19233 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19234 
19235 	if (mp != NULL)
19236 		ipha = (ipha_t *)mp->b_rptr;
19237 	else
19238 		ipha = tcp->tcp_ipha;
19239 	dst = ipha->ipha_dst;
19240 
19241 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19242 		return (B_FALSE);
19243 
19244 	if ((ire->ire_flags & RTF_MULTIRT) ||
19245 	    (ire->ire_stq == NULL) ||
19246 	    (ire->ire_nce == NULL) ||
19247 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19248 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19249 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19250 		TCP_STAT(tcps, tcp_ip_ire_send);
19251 		IRE_REFRELE(ire);
19252 		return (B_FALSE);
19253 	}
19254 
19255 	ill = ire_to_ill(ire);
19256 	ASSERT(ill != NULL);
19257 
19258 	if (!tcp->tcp_ire_ill_check_done) {
19259 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19260 		tcp->tcp_ire_ill_check_done = B_TRUE;
19261 	}
19262 
19263 	*irep = ire;
19264 	*illp = ill;
19265 
19266 	return (B_TRUE);
19267 }
19268 
19269 static void
19270 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19271 {
19272 	ipha_t		*ipha;
19273 	ipaddr_t	src;
19274 	ipaddr_t	dst;
19275 	uint32_t	cksum;
19276 	ire_t		*ire;
19277 	uint16_t	*up;
19278 	ill_t		*ill;
19279 	conn_t		*connp = tcp->tcp_connp;
19280 	uint32_t	hcksum_txflags = 0;
19281 	mblk_t		*ire_fp_mp;
19282 	uint_t		ire_fp_mp_len;
19283 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19284 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19285 	cred_t		*cr;
19286 	pid_t		cpid;
19287 
19288 	ASSERT(DB_TYPE(mp) == M_DATA);
19289 
19290 	/*
19291 	 * Here we need to handle the overloading of the cred_t for
19292 	 * both getpeerucred and TX.
19293 	 * If this is a SYN then the caller already set db_credp so
19294 	 * that getpeerucred will work. But if TX is in use we might have
19295 	 * a conn_peercred which is different, and we need to use that cred
19296 	 * to make TX use the correct label and label dependent route.
19297 	 */
19298 	if (is_system_labeled()) {
19299 		cr = msg_getcred(mp, &cpid);
19300 		if (cr == NULL || connp->conn_peercred != NULL)
19301 			mblk_setcred(mp, CONN_CRED(connp), cpid);
19302 	}
19303 
19304 	ipha = (ipha_t *)mp->b_rptr;
19305 	src = ipha->ipha_src;
19306 	dst = ipha->ipha_dst;
19307 
19308 	ASSERT(q != NULL);
19309 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19310 
19311 	/*
19312 	 * Drop off fast path for IPv6 and also if options are present or
19313 	 * we need to resolve a TS label.
19314 	 */
19315 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19316 	    !IPCL_IS_CONNECTED(connp) ||
19317 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19318 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19319 	    !connp->conn_ulp_labeled ||
19320 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19321 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19322 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19323 		if (tcp->tcp_snd_zcopy_aware)
19324 			mp = tcp_zcopy_disable(tcp, mp);
19325 		TCP_STAT(tcps, tcp_ip_send);
19326 		CALL_IP_WPUT(connp, q, mp);
19327 		return;
19328 	}
19329 
19330 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19331 		if (tcp->tcp_snd_zcopy_aware)
19332 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19333 		CALL_IP_WPUT(connp, q, mp);
19334 		return;
19335 	}
19336 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19337 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19338 
19339 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19340 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19341 #ifndef _BIG_ENDIAN
19342 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19343 #endif
19344 
19345 	/*
19346 	 * Check to see if we need to re-enable LSO/MDT for this connection
19347 	 * because it was previously disabled due to changes in the ill;
19348 	 * note that by doing it here, this re-enabling only applies when
19349 	 * the packet is not dispatched through CALL_IP_WPUT().
19350 	 *
19351 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19352 	 * case, since that's how we ended up here.  For IPv6, we do the
19353 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19354 	 */
19355 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19356 		/*
19357 		 * Restore LSO for this connection, so that next time around
19358 		 * it is eligible to go through tcp_lsosend() path again.
19359 		 */
19360 		TCP_STAT(tcps, tcp_lso_enabled);
19361 		tcp->tcp_lso = B_TRUE;
19362 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19363 		    "interface %s\n", (void *)connp, ill->ill_name));
19364 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19365 		/*
19366 		 * Restore MDT for this connection, so that next time around
19367 		 * it is eligible to go through tcp_multisend() path again.
19368 		 */
19369 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19370 		tcp->tcp_mdt = B_TRUE;
19371 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19372 		    "interface %s\n", (void *)connp, ill->ill_name));
19373 	}
19374 
19375 	if (tcp->tcp_snd_zcopy_aware) {
19376 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19377 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19378 			mp = tcp_zcopy_disable(tcp, mp);
19379 		/*
19380 		 * we shouldn't need to reset ipha as the mp containing
19381 		 * ipha should never be a zero-copy mp.
19382 		 */
19383 	}
19384 
19385 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19386 		ASSERT(ill->ill_hcksum_capab != NULL);
19387 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19388 	}
19389 
19390 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19391 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19392 
19393 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19394 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19395 
19396 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19397 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19398 
19399 	/* Software checksum? */
19400 	if (DB_CKSUMFLAGS(mp) == 0) {
19401 		TCP_STAT(tcps, tcp_out_sw_cksum);
19402 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19403 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19404 	}
19405 
19406 	/* Calculate IP header checksum if hardware isn't capable */
19407 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19408 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19409 		    ((uint16_t *)ipha)[4]);
19410 	}
19411 
19412 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19413 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19414 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19415 
19416 	UPDATE_OB_PKT_COUNT(ire);
19417 	ire->ire_last_used_time = lbolt;
19418 
19419 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19420 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19421 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19422 	    ntohs(ipha->ipha_length));
19423 
19424 	DTRACE_PROBE4(ip4__physical__out__start,
19425 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
19426 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
19427 	    ipst->ips_ipv4firewall_physical_out,
19428 	    NULL, ill, ipha, mp, mp, 0, ipst);
19429 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19430 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
19431 
19432 	if (mp != NULL) {
19433 		if (ipst->ips_ipobs_enabled) {
19434 			zoneid_t szone;
19435 
19436 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
19437 			    ipst, ALL_ZONES);
19438 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
19439 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
19440 		}
19441 
19442 		ILL_SEND_TX(ill, ire, connp, mp, 0, NULL);
19443 	}
19444 
19445 	IRE_REFRELE(ire);
19446 }
19447 
19448 /*
19449  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19450  * if the receiver shrinks the window, i.e. moves the right window to the
19451  * left, the we should not send new data, but should retransmit normally the
19452  * old unacked data between suna and suna + swnd. We might has sent data
19453  * that is now outside the new window, pretend that we didn't send  it.
19454  */
19455 static void
19456 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19457 {
19458 	uint32_t	snxt = tcp->tcp_snxt;
19459 	mblk_t		*xmit_tail;
19460 	int32_t		offset;
19461 
19462 	ASSERT(shrunk_count > 0);
19463 
19464 	/* Pretend we didn't send the data outside the window */
19465 	snxt -= shrunk_count;
19466 
19467 	/* Get the mblk and the offset in it per the shrunk window */
19468 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19469 
19470 	ASSERT(xmit_tail != NULL);
19471 
19472 	/* Reset all the values per the now shrunk window */
19473 	tcp->tcp_snxt = snxt;
19474 	tcp->tcp_xmit_tail = xmit_tail;
19475 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19476 	    offset;
19477 	tcp->tcp_unsent += shrunk_count;
19478 
19479 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19480 		/*
19481 		 * Make sure the timer is running so that we will probe a zero
19482 		 * window.
19483 		 */
19484 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19485 }
19486 
19487 
19488 /*
19489  * The TCP normal data output path.
19490  * NOTE: the logic of the fast path is duplicated from this function.
19491  */
19492 static void
19493 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19494 {
19495 	int		len;
19496 	mblk_t		*local_time;
19497 	mblk_t		*mp1;
19498 	uint32_t	snxt;
19499 	int		tail_unsent;
19500 	int		tcpstate;
19501 	int		usable = 0;
19502 	mblk_t		*xmit_tail;
19503 	queue_t		*q = tcp->tcp_wq;
19504 	int32_t		mss;
19505 	int32_t		num_sack_blk = 0;
19506 	int32_t		tcp_hdr_len;
19507 	int32_t		tcp_tcp_hdr_len;
19508 	int		mdt_thres;
19509 	int		rc;
19510 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19511 	ip_stack_t	*ipst;
19512 
19513 	tcpstate = tcp->tcp_state;
19514 	if (mp == NULL) {
19515 		/*
19516 		 * tcp_wput_data() with NULL mp should only be called when
19517 		 * there is unsent data.
19518 		 */
19519 		ASSERT(tcp->tcp_unsent > 0);
19520 		/* Really tacky... but we need this for detached closes. */
19521 		len = tcp->tcp_unsent;
19522 		goto data_null;
19523 	}
19524 
19525 #if CCS_STATS
19526 	wrw_stats.tot.count++;
19527 	wrw_stats.tot.bytes += msgdsize(mp);
19528 #endif
19529 	ASSERT(mp->b_datap->db_type == M_DATA);
19530 	/*
19531 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19532 	 * or before a connection attempt has begun.
19533 	 */
19534 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19535 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19536 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19537 #ifdef DEBUG
19538 			cmn_err(CE_WARN,
19539 			    "tcp_wput_data: data after ordrel, %s",
19540 			    tcp_display(tcp, NULL,
19541 			    DISP_ADDR_AND_PORT));
19542 #else
19543 			if (tcp->tcp_debug) {
19544 				(void) strlog(TCP_MOD_ID, 0, 1,
19545 				    SL_TRACE|SL_ERROR,
19546 				    "tcp_wput_data: data after ordrel, %s\n",
19547 				    tcp_display(tcp, NULL,
19548 				    DISP_ADDR_AND_PORT));
19549 			}
19550 #endif /* DEBUG */
19551 		}
19552 		if (tcp->tcp_snd_zcopy_aware &&
19553 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19554 			tcp_zcopy_notify(tcp);
19555 		freemsg(mp);
19556 		mutex_enter(&tcp->tcp_non_sq_lock);
19557 		if (tcp->tcp_flow_stopped &&
19558 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19559 			tcp_clrqfull(tcp);
19560 		}
19561 		mutex_exit(&tcp->tcp_non_sq_lock);
19562 		return;
19563 	}
19564 
19565 	/* Strip empties */
19566 	for (;;) {
19567 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19568 		    (uintptr_t)INT_MAX);
19569 		len = (int)(mp->b_wptr - mp->b_rptr);
19570 		if (len > 0)
19571 			break;
19572 		mp1 = mp;
19573 		mp = mp->b_cont;
19574 		freeb(mp1);
19575 		if (!mp) {
19576 			return;
19577 		}
19578 	}
19579 
19580 	/* If we are the first on the list ... */
19581 	if (tcp->tcp_xmit_head == NULL) {
19582 		tcp->tcp_xmit_head = mp;
19583 		tcp->tcp_xmit_tail = mp;
19584 		tcp->tcp_xmit_tail_unsent = len;
19585 	} else {
19586 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19587 		struct datab *dp;
19588 
19589 		mp1 = tcp->tcp_xmit_last;
19590 		if (len < tcp_tx_pull_len &&
19591 		    (dp = mp1->b_datap)->db_ref == 1 &&
19592 		    dp->db_lim - mp1->b_wptr >= len) {
19593 			ASSERT(len > 0);
19594 			ASSERT(!mp1->b_cont);
19595 			if (len == 1) {
19596 				*mp1->b_wptr++ = *mp->b_rptr;
19597 			} else {
19598 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19599 				mp1->b_wptr += len;
19600 			}
19601 			if (mp1 == tcp->tcp_xmit_tail)
19602 				tcp->tcp_xmit_tail_unsent += len;
19603 			mp1->b_cont = mp->b_cont;
19604 			if (tcp->tcp_snd_zcopy_aware &&
19605 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19606 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19607 			freeb(mp);
19608 			mp = mp1;
19609 		} else {
19610 			tcp->tcp_xmit_last->b_cont = mp;
19611 		}
19612 		len += tcp->tcp_unsent;
19613 	}
19614 
19615 	/* Tack on however many more positive length mblks we have */
19616 	if ((mp1 = mp->b_cont) != NULL) {
19617 		do {
19618 			int tlen;
19619 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19620 			    (uintptr_t)INT_MAX);
19621 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19622 			if (tlen <= 0) {
19623 				mp->b_cont = mp1->b_cont;
19624 				freeb(mp1);
19625 			} else {
19626 				len += tlen;
19627 				mp = mp1;
19628 			}
19629 		} while ((mp1 = mp->b_cont) != NULL);
19630 	}
19631 	tcp->tcp_xmit_last = mp;
19632 	tcp->tcp_unsent = len;
19633 
19634 	if (urgent)
19635 		usable = 1;
19636 
19637 data_null:
19638 	snxt = tcp->tcp_snxt;
19639 	xmit_tail = tcp->tcp_xmit_tail;
19640 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19641 
19642 	/*
19643 	 * Note that tcp_mss has been adjusted to take into account the
19644 	 * timestamp option if applicable.  Because SACK options do not
19645 	 * appear in every TCP segments and they are of variable lengths,
19646 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19647 	 * the actual segment length when we need to send a segment which
19648 	 * includes SACK options.
19649 	 */
19650 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19651 		int32_t	opt_len;
19652 
19653 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19654 		    tcp->tcp_num_sack_blk);
19655 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19656 		    2 + TCPOPT_HEADER_LEN;
19657 		mss = tcp->tcp_mss - opt_len;
19658 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19659 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19660 	} else {
19661 		mss = tcp->tcp_mss;
19662 		tcp_hdr_len = tcp->tcp_hdr_len;
19663 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19664 	}
19665 
19666 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19667 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19668 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19669 	}
19670 	if (tcpstate == TCPS_SYN_RCVD) {
19671 		/*
19672 		 * The three-way connection establishment handshake is not
19673 		 * complete yet. We want to queue the data for transmission
19674 		 * after entering ESTABLISHED state (RFC793). A jump to
19675 		 * "done" label effectively leaves data on the queue.
19676 		 */
19677 		goto done;
19678 	} else {
19679 		int usable_r;
19680 
19681 		/*
19682 		 * In the special case when cwnd is zero, which can only
19683 		 * happen if the connection is ECN capable, return now.
19684 		 * New segments is sent using tcp_timer().  The timer
19685 		 * is set in tcp_rput_data().
19686 		 */
19687 		if (tcp->tcp_cwnd == 0) {
19688 			/*
19689 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19690 			 * finished.
19691 			 */
19692 			ASSERT(tcp->tcp_ecn_ok ||
19693 			    tcp->tcp_state < TCPS_ESTABLISHED);
19694 			return;
19695 		}
19696 
19697 		/* NOTE: trouble if xmitting while SYN not acked? */
19698 		usable_r = snxt - tcp->tcp_suna;
19699 		usable_r = tcp->tcp_swnd - usable_r;
19700 
19701 		/*
19702 		 * Check if the receiver has shrunk the window.  If
19703 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19704 		 * cannot be set as there is unsent data, so FIN cannot
19705 		 * be sent out.  Otherwise, we need to take into account
19706 		 * of FIN as it consumes an "invisible" sequence number.
19707 		 */
19708 		ASSERT(tcp->tcp_fin_sent == 0);
19709 		if (usable_r < 0) {
19710 			/*
19711 			 * The receiver has shrunk the window and we have sent
19712 			 * -usable_r date beyond the window, re-adjust.
19713 			 *
19714 			 * If TCP window scaling is enabled, there can be
19715 			 * round down error as the advertised receive window
19716 			 * is actually right shifted n bits.  This means that
19717 			 * the lower n bits info is wiped out.  It will look
19718 			 * like the window is shrunk.  Do a check here to
19719 			 * see if the shrunk amount is actually within the
19720 			 * error in window calculation.  If it is, just
19721 			 * return.  Note that this check is inside the
19722 			 * shrunk window check.  This makes sure that even
19723 			 * though tcp_process_shrunk_swnd() is not called,
19724 			 * we will stop further processing.
19725 			 */
19726 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19727 				tcp_process_shrunk_swnd(tcp, -usable_r);
19728 			}
19729 			return;
19730 		}
19731 
19732 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19733 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19734 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19735 
19736 		/* usable = MIN(usable, unsent) */
19737 		if (usable_r > len)
19738 			usable_r = len;
19739 
19740 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19741 		if (usable_r > 0) {
19742 			usable = usable_r;
19743 		} else {
19744 			/* Bypass all other unnecessary processing. */
19745 			goto done;
19746 		}
19747 	}
19748 
19749 	local_time = (mblk_t *)lbolt;
19750 
19751 	/*
19752 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19753 	 * BSD.  This is more in line with the true intent of Nagle.
19754 	 *
19755 	 * The conditions are:
19756 	 * 1. The amount of unsent data (or amount of data which can be
19757 	 *    sent, whichever is smaller) is less than Nagle limit.
19758 	 * 2. The last sent size is also less than Nagle limit.
19759 	 * 3. There is unack'ed data.
19760 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19761 	 *    Nagle algorithm.  This reduces the probability that urgent
19762 	 *    bytes get "merged" together.
19763 	 * 5. The app has not closed the connection.  This eliminates the
19764 	 *    wait time of the receiving side waiting for the last piece of
19765 	 *    (small) data.
19766 	 *
19767 	 * If all are satisified, exit without sending anything.  Note
19768 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19769 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19770 	 * 4095).
19771 	 */
19772 	if (usable < (int)tcp->tcp_naglim &&
19773 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19774 	    snxt != tcp->tcp_suna &&
19775 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19776 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19777 		goto done;
19778 	}
19779 
19780 	if (tcp->tcp_cork) {
19781 		/*
19782 		 * if the tcp->tcp_cork option is set, then we have to force
19783 		 * TCP not to send partial segment (smaller than MSS bytes).
19784 		 * We are calculating the usable now based on full mss and
19785 		 * will save the rest of remaining data for later.
19786 		 */
19787 		if (usable < mss)
19788 			goto done;
19789 		usable = (usable / mss) * mss;
19790 	}
19791 
19792 	/* Update the latest receive window size in TCP header. */
19793 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19794 	    tcp->tcp_tcph->th_win);
19795 
19796 	/*
19797 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19798 	 *
19799 	 * 1. Simple TCP/IP{v4,v6} (no options).
19800 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19801 	 * 3. If the TCP connection is in ESTABLISHED state.
19802 	 * 4. The TCP is not detached.
19803 	 *
19804 	 * If any of the above conditions have changed during the
19805 	 * connection, stop using LSO/MDT and restore the stream head
19806 	 * parameters accordingly.
19807 	 */
19808 	ipst = tcps->tcps_netstack->netstack_ip;
19809 
19810 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19811 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19812 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19813 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19814 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19815 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19816 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19817 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19818 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19819 		if (tcp->tcp_lso) {
19820 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19821 			tcp->tcp_lso = B_FALSE;
19822 		} else {
19823 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19824 			tcp->tcp_mdt = B_FALSE;
19825 		}
19826 
19827 		/* Anything other than detached is considered pathological */
19828 		if (!TCP_IS_DETACHED(tcp)) {
19829 			if (tcp->tcp_lso)
19830 				TCP_STAT(tcps, tcp_lso_disabled);
19831 			else
19832 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19833 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19834 		}
19835 	}
19836 
19837 	/* Use MDT if sendable amount is greater than the threshold */
19838 	if (tcp->tcp_mdt &&
19839 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19840 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19841 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19842 	    (tcp->tcp_valid_bits == 0 ||
19843 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19844 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19845 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19846 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19847 		    local_time, mdt_thres);
19848 	} else {
19849 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19850 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19851 		    local_time, INT_MAX);
19852 	}
19853 
19854 	/* Pretend that all we were trying to send really got sent */
19855 	if (rc < 0 && tail_unsent < 0) {
19856 		do {
19857 			xmit_tail = xmit_tail->b_cont;
19858 			xmit_tail->b_prev = local_time;
19859 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19860 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19861 			tail_unsent += (int)(xmit_tail->b_wptr -
19862 			    xmit_tail->b_rptr);
19863 		} while (tail_unsent < 0);
19864 	}
19865 done:;
19866 	tcp->tcp_xmit_tail = xmit_tail;
19867 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19868 	len = tcp->tcp_snxt - snxt;
19869 	if (len) {
19870 		/*
19871 		 * If new data was sent, need to update the notsack
19872 		 * list, which is, afterall, data blocks that have
19873 		 * not been sack'ed by the receiver.  New data is
19874 		 * not sack'ed.
19875 		 */
19876 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19877 			/* len is a negative value. */
19878 			tcp->tcp_pipe -= len;
19879 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19880 			    tcp->tcp_snxt, snxt,
19881 			    &(tcp->tcp_num_notsack_blk),
19882 			    &(tcp->tcp_cnt_notsack_list));
19883 		}
19884 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19885 		tcp->tcp_rack = tcp->tcp_rnxt;
19886 		tcp->tcp_rack_cnt = 0;
19887 		if ((snxt + len) == tcp->tcp_suna) {
19888 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19889 		}
19890 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19891 		/*
19892 		 * Didn't send anything. Make sure the timer is running
19893 		 * so that we will probe a zero window.
19894 		 */
19895 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19896 	}
19897 	/* Note that len is the amount we just sent but with a negative sign */
19898 	tcp->tcp_unsent += len;
19899 	mutex_enter(&tcp->tcp_non_sq_lock);
19900 	if (tcp->tcp_flow_stopped) {
19901 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19902 			tcp_clrqfull(tcp);
19903 		}
19904 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19905 		tcp_setqfull(tcp);
19906 	}
19907 	mutex_exit(&tcp->tcp_non_sq_lock);
19908 }
19909 
19910 /*
19911  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19912  * outgoing TCP header with the template header, as well as other
19913  * options such as time-stamp, ECN and/or SACK.
19914  */
19915 static void
19916 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19917 {
19918 	tcph_t *tcp_tmpl, *tcp_h;
19919 	uint32_t *dst, *src;
19920 	int hdrlen;
19921 
19922 	ASSERT(OK_32PTR(rptr));
19923 
19924 	/* Template header */
19925 	tcp_tmpl = tcp->tcp_tcph;
19926 
19927 	/* Header of outgoing packet */
19928 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
19929 
19930 	/* dst and src are opaque 32-bit fields, used for copying */
19931 	dst = (uint32_t *)rptr;
19932 	src = (uint32_t *)tcp->tcp_iphc;
19933 	hdrlen = tcp->tcp_hdr_len;
19934 
19935 	/* Fill time-stamp option if needed */
19936 	if (tcp->tcp_snd_ts_ok) {
19937 		U32_TO_BE32((uint32_t)now,
19938 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
19939 		U32_TO_BE32(tcp->tcp_ts_recent,
19940 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
19941 	} else {
19942 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
19943 	}
19944 
19945 	/*
19946 	 * Copy the template header; is this really more efficient than
19947 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
19948 	 * but perhaps not for other scenarios.
19949 	 */
19950 	dst[0] = src[0];
19951 	dst[1] = src[1];
19952 	dst[2] = src[2];
19953 	dst[3] = src[3];
19954 	dst[4] = src[4];
19955 	dst[5] = src[5];
19956 	dst[6] = src[6];
19957 	dst[7] = src[7];
19958 	dst[8] = src[8];
19959 	dst[9] = src[9];
19960 	if (hdrlen -= 40) {
19961 		hdrlen >>= 2;
19962 		dst += 10;
19963 		src += 10;
19964 		do {
19965 			*dst++ = *src++;
19966 		} while (--hdrlen);
19967 	}
19968 
19969 	/*
19970 	 * Set the ECN info in the TCP header if it is not a zero
19971 	 * window probe.  Zero window probe is only sent in
19972 	 * tcp_wput_data() and tcp_timer().
19973 	 */
19974 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
19975 		SET_ECT(tcp, rptr);
19976 
19977 		if (tcp->tcp_ecn_echo_on)
19978 			tcp_h->th_flags[0] |= TH_ECE;
19979 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
19980 			tcp_h->th_flags[0] |= TH_CWR;
19981 			tcp->tcp_ecn_cwr_sent = B_TRUE;
19982 		}
19983 	}
19984 
19985 	/* Fill in SACK options */
19986 	if (num_sack_blk > 0) {
19987 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
19988 		sack_blk_t *tmp;
19989 		int32_t	i;
19990 
19991 		wptr[0] = TCPOPT_NOP;
19992 		wptr[1] = TCPOPT_NOP;
19993 		wptr[2] = TCPOPT_SACK;
19994 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
19995 		    sizeof (sack_blk_t);
19996 		wptr += TCPOPT_REAL_SACK_LEN;
19997 
19998 		tmp = tcp->tcp_sack_list;
19999 		for (i = 0; i < num_sack_blk; i++) {
20000 			U32_TO_BE32(tmp[i].begin, wptr);
20001 			wptr += sizeof (tcp_seq);
20002 			U32_TO_BE32(tmp[i].end, wptr);
20003 			wptr += sizeof (tcp_seq);
20004 		}
20005 		tcp_h->th_offset_and_rsrvd[0] +=
20006 		    ((num_sack_blk * 2 + 1) << 4);
20007 	}
20008 }
20009 
20010 /*
20011  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
20012  * the destination address and SAP attribute, and if necessary, the
20013  * hardware checksum offload attribute to a Multidata message.
20014  */
20015 static int
20016 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
20017     const uint32_t start, const uint32_t stuff, const uint32_t end,
20018     const uint32_t flags, tcp_stack_t *tcps)
20019 {
20020 	/* Add global destination address & SAP attribute */
20021 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
20022 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
20023 		    "destination address+SAP\n"));
20024 
20025 		if (dlmp != NULL)
20026 			TCP_STAT(tcps, tcp_mdt_allocfail);
20027 		return (-1);
20028 	}
20029 
20030 	/* Add global hwcksum attribute */
20031 	if (hwcksum &&
20032 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
20033 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
20034 		    "checksum attribute\n"));
20035 
20036 		TCP_STAT(tcps, tcp_mdt_allocfail);
20037 		return (-1);
20038 	}
20039 
20040 	return (0);
20041 }
20042 
20043 /*
20044  * Smaller and private version of pdescinfo_t used specifically for TCP,
20045  * which allows for only two payload spans per packet.
20046  */
20047 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
20048 
20049 /*
20050  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
20051  * scheme, and returns one the following:
20052  *
20053  * -1 = failed allocation.
20054  *  0 = success; burst count reached, or usable send window is too small,
20055  *      and that we'd rather wait until later before sending again.
20056  */
20057 static int
20058 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20059     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20060     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20061     const int mdt_thres)
20062 {
20063 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
20064 	multidata_t	*mmd;
20065 	uint_t		obsegs, obbytes, hdr_frag_sz;
20066 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
20067 	int		num_burst_seg, max_pld;
20068 	pdesc_t		*pkt;
20069 	tcp_pdescinfo_t	tcp_pkt_info;
20070 	pdescinfo_t	*pkt_info;
20071 	int		pbuf_idx, pbuf_idx_nxt;
20072 	int		seg_len, len, spill, af;
20073 	boolean_t	add_buffer, zcopy, clusterwide;
20074 	boolean_t	rconfirm = B_FALSE;
20075 	boolean_t	done = B_FALSE;
20076 	uint32_t	cksum;
20077 	uint32_t	hwcksum_flags;
20078 	ire_t		*ire = NULL;
20079 	ill_t		*ill;
20080 	ipha_t		*ipha;
20081 	ip6_t		*ip6h;
20082 	ipaddr_t	src, dst;
20083 	ill_zerocopy_capab_t *zc_cap = NULL;
20084 	uint16_t	*up;
20085 	int		err;
20086 	conn_t		*connp;
20087 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20088 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
20089 	int		usable_mmd, tail_unsent_mmd;
20090 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
20091 	mblk_t		*xmit_tail_mmd;
20092 	netstackid_t	stack_id;
20093 
20094 #ifdef	_BIG_ENDIAN
20095 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20096 #else
20097 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20098 #endif
20099 
20100 #define	PREP_NEW_MULTIDATA() {			\
20101 	mmd = NULL;				\
20102 	md_mp = md_hbuf = NULL;			\
20103 	cur_hdr_off = 0;			\
20104 	max_pld = tcp->tcp_mdt_max_pld;		\
20105 	pbuf_idx = pbuf_idx_nxt = -1;		\
20106 	add_buffer = B_TRUE;			\
20107 	zcopy = B_FALSE;			\
20108 }
20109 
20110 #define	PREP_NEW_PBUF() {			\
20111 	md_pbuf = md_pbuf_nxt = NULL;		\
20112 	pbuf_idx = pbuf_idx_nxt = -1;		\
20113 	cur_pld_off = 0;			\
20114 	first_snxt = *snxt;			\
20115 	ASSERT(*tail_unsent > 0);		\
20116 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20117 }
20118 
20119 	ASSERT(mdt_thres >= mss);
20120 	ASSERT(*usable > 0 && *usable > mdt_thres);
20121 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20122 	ASSERT(!TCP_IS_DETACHED(tcp));
20123 	ASSERT(tcp->tcp_valid_bits == 0 ||
20124 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20125 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20126 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20127 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20128 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20129 
20130 	connp = tcp->tcp_connp;
20131 	ASSERT(connp != NULL);
20132 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20133 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20134 
20135 	stack_id = connp->conn_netstack->netstack_stackid;
20136 
20137 	usable_mmd = tail_unsent_mmd = 0;
20138 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20139 	xmit_tail_mmd = NULL;
20140 	/*
20141 	 * Note that tcp will only declare at most 2 payload spans per
20142 	 * packet, which is much lower than the maximum allowable number
20143 	 * of packet spans per Multidata.  For this reason, we use the
20144 	 * privately declared and smaller descriptor info structure, in
20145 	 * order to save some stack space.
20146 	 */
20147 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20148 
20149 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20150 	if (af == AF_INET) {
20151 		dst = tcp->tcp_ipha->ipha_dst;
20152 		src = tcp->tcp_ipha->ipha_src;
20153 		ASSERT(!CLASSD(dst));
20154 	}
20155 	ASSERT(af == AF_INET ||
20156 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20157 
20158 	obsegs = obbytes = 0;
20159 	num_burst_seg = tcp->tcp_snd_burst;
20160 	md_mp_head = NULL;
20161 	PREP_NEW_MULTIDATA();
20162 
20163 	/*
20164 	 * Before we go on further, make sure there is an IRE that we can
20165 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20166 	 * in proceeding any further, and we should just hand everything
20167 	 * off to the legacy path.
20168 	 */
20169 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20170 		goto legacy_send_no_md;
20171 
20172 	ASSERT(ire != NULL);
20173 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20174 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20175 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20176 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20177 	/*
20178 	 * If we do support loopback for MDT (which requires modifications
20179 	 * to the receiving paths), the following assertions should go away,
20180 	 * and we would be sending the Multidata to loopback conn later on.
20181 	 */
20182 	ASSERT(!IRE_IS_LOCAL(ire));
20183 	ASSERT(ire->ire_stq != NULL);
20184 
20185 	ill = ire_to_ill(ire);
20186 	ASSERT(ill != NULL);
20187 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20188 
20189 	if (!tcp->tcp_ire_ill_check_done) {
20190 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20191 		tcp->tcp_ire_ill_check_done = B_TRUE;
20192 	}
20193 
20194 	/*
20195 	 * If the underlying interface conditions have changed, or if the
20196 	 * new interface does not support MDT, go back to legacy path.
20197 	 */
20198 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20199 		/* don't go through this path anymore for this connection */
20200 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20201 		tcp->tcp_mdt = B_FALSE;
20202 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20203 		    "interface %s\n", (void *)connp, ill->ill_name));
20204 		/* IRE will be released prior to returning */
20205 		goto legacy_send_no_md;
20206 	}
20207 
20208 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20209 		zc_cap = ill->ill_zerocopy_capab;
20210 
20211 	/*
20212 	 * Check if we can take tcp fast-path. Note that "incomplete"
20213 	 * ire's (where the link-layer for next hop is not resolved
20214 	 * or where the fast-path header in nce_fp_mp is not available
20215 	 * yet) are sent down the legacy (slow) path.
20216 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20217 	 */
20218 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20219 		/* IRE will be released prior to returning */
20220 		goto legacy_send_no_md;
20221 	}
20222 
20223 	/* go to legacy path if interface doesn't support zerocopy */
20224 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20225 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20226 		/* IRE will be released prior to returning */
20227 		goto legacy_send_no_md;
20228 	}
20229 
20230 	/* does the interface support hardware checksum offload? */
20231 	hwcksum_flags = 0;
20232 	if (ILL_HCKSUM_CAPABLE(ill) &&
20233 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20234 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20235 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20236 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20237 		    HCKSUM_IPHDRCKSUM)
20238 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20239 
20240 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20241 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20242 			hwcksum_flags |= HCK_FULLCKSUM;
20243 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20244 		    HCKSUM_INET_PARTIAL)
20245 			hwcksum_flags |= HCK_PARTIALCKSUM;
20246 	}
20247 
20248 	/*
20249 	 * Each header fragment consists of the leading extra space,
20250 	 * followed by the TCP/IP header, and the trailing extra space.
20251 	 * We make sure that each header fragment begins on a 32-bit
20252 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20253 	 * aligned in tcp_mdt_update).
20254 	 */
20255 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20256 	    tcp->tcp_mdt_hdr_tail), 4);
20257 
20258 	/* are we starting from the beginning of data block? */
20259 	if (*tail_unsent == 0) {
20260 		*xmit_tail = (*xmit_tail)->b_cont;
20261 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20262 		*tail_unsent = (int)MBLKL(*xmit_tail);
20263 	}
20264 
20265 	/*
20266 	 * Here we create one or more Multidata messages, each made up of
20267 	 * one header buffer and up to N payload buffers.  This entire
20268 	 * operation is done within two loops:
20269 	 *
20270 	 * The outer loop mostly deals with creating the Multidata message,
20271 	 * as well as the header buffer that gets added to it.  It also
20272 	 * links the Multidata messages together such that all of them can
20273 	 * be sent down to the lower layer in a single putnext call; this
20274 	 * linking behavior depends on the tcp_mdt_chain tunable.
20275 	 *
20276 	 * The inner loop takes an existing Multidata message, and adds
20277 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20278 	 * packetizes those buffers by filling up the corresponding header
20279 	 * buffer fragments with the proper IP and TCP headers, and by
20280 	 * describing the layout of each packet in the packet descriptors
20281 	 * that get added to the Multidata.
20282 	 */
20283 	do {
20284 		/*
20285 		 * If usable send window is too small, or data blocks in
20286 		 * transmit list are smaller than our threshold (i.e. app
20287 		 * performs large writes followed by small ones), we hand
20288 		 * off the control over to the legacy path.  Note that we'll
20289 		 * get back the control once it encounters a large block.
20290 		 */
20291 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20292 		    (*xmit_tail)->b_cont != NULL &&
20293 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20294 			/* send down what we've got so far */
20295 			if (md_mp_head != NULL) {
20296 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20297 				    obsegs, obbytes, &rconfirm);
20298 			}
20299 			/*
20300 			 * Pass control over to tcp_send(), but tell it to
20301 			 * return to us once a large-size transmission is
20302 			 * possible.
20303 			 */
20304 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20305 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20306 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20307 			    tail_unsent, xmit_tail, local_time,
20308 			    mdt_thres)) <= 0) {
20309 				/* burst count reached, or alloc failed */
20310 				IRE_REFRELE(ire);
20311 				return (err);
20312 			}
20313 
20314 			/* tcp_send() may have sent everything, so check */
20315 			if (*usable <= 0) {
20316 				IRE_REFRELE(ire);
20317 				return (0);
20318 			}
20319 
20320 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20321 			/*
20322 			 * We may have delivered the Multidata, so make sure
20323 			 * to re-initialize before the next round.
20324 			 */
20325 			md_mp_head = NULL;
20326 			obsegs = obbytes = 0;
20327 			num_burst_seg = tcp->tcp_snd_burst;
20328 			PREP_NEW_MULTIDATA();
20329 
20330 			/* are we starting from the beginning of data block? */
20331 			if (*tail_unsent == 0) {
20332 				*xmit_tail = (*xmit_tail)->b_cont;
20333 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20334 				    (uintptr_t)INT_MAX);
20335 				*tail_unsent = (int)MBLKL(*xmit_tail);
20336 			}
20337 		}
20338 		/*
20339 		 * Record current values for parameters we may need to pass
20340 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20341 		 * each iteration of the outer loop (each multidata message
20342 		 * creation). If we have a failure in the inner loop, we send
20343 		 * any complete multidata messages we have before reverting
20344 		 * to using the traditional non-md path.
20345 		 */
20346 		snxt_mmd = *snxt;
20347 		usable_mmd = *usable;
20348 		xmit_tail_mmd = *xmit_tail;
20349 		tail_unsent_mmd = *tail_unsent;
20350 		obsegs_mmd = obsegs;
20351 		obbytes_mmd = obbytes;
20352 
20353 		/*
20354 		 * max_pld limits the number of mblks in tcp's transmit
20355 		 * queue that can be added to a Multidata message.  Once
20356 		 * this counter reaches zero, no more additional mblks
20357 		 * can be added to it.  What happens afterwards depends
20358 		 * on whether or not we are set to chain the Multidata
20359 		 * messages.  If we are to link them together, reset
20360 		 * max_pld to its original value (tcp_mdt_max_pld) and
20361 		 * prepare to create a new Multidata message which will
20362 		 * get linked to md_mp_head.  Else, leave it alone and
20363 		 * let the inner loop break on its own.
20364 		 */
20365 		if (tcp_mdt_chain && max_pld == 0)
20366 			PREP_NEW_MULTIDATA();
20367 
20368 		/* adding a payload buffer; re-initialize values */
20369 		if (add_buffer)
20370 			PREP_NEW_PBUF();
20371 
20372 		/*
20373 		 * If we don't have a Multidata, either because we just
20374 		 * (re)entered this outer loop, or after we branched off
20375 		 * to tcp_send above, setup the Multidata and header
20376 		 * buffer to be used.
20377 		 */
20378 		if (md_mp == NULL) {
20379 			int md_hbuflen;
20380 			uint32_t start, stuff;
20381 
20382 			/*
20383 			 * Calculate Multidata header buffer size large enough
20384 			 * to hold all of the headers that can possibly be
20385 			 * sent at this moment.  We'd rather over-estimate
20386 			 * the size than running out of space; this is okay
20387 			 * since this buffer is small anyway.
20388 			 */
20389 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20390 
20391 			/*
20392 			 * Start and stuff offset for partial hardware
20393 			 * checksum offload; these are currently for IPv4.
20394 			 * For full checksum offload, they are set to zero.
20395 			 */
20396 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20397 				if (af == AF_INET) {
20398 					start = IP_SIMPLE_HDR_LENGTH;
20399 					stuff = IP_SIMPLE_HDR_LENGTH +
20400 					    TCP_CHECKSUM_OFFSET;
20401 				} else {
20402 					start = IPV6_HDR_LEN;
20403 					stuff = IPV6_HDR_LEN +
20404 					    TCP_CHECKSUM_OFFSET;
20405 				}
20406 			} else {
20407 				start = stuff = 0;
20408 			}
20409 
20410 			/*
20411 			 * Create the header buffer, Multidata, as well as
20412 			 * any necessary attributes (destination address,
20413 			 * SAP and hardware checksum offload) that should
20414 			 * be associated with the Multidata message.
20415 			 */
20416 			ASSERT(cur_hdr_off == 0);
20417 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20418 			    ((md_hbuf->b_wptr += md_hbuflen),
20419 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20420 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20421 			    /* fastpath mblk */
20422 			    ire->ire_nce->nce_res_mp,
20423 			    /* hardware checksum enabled */
20424 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20425 			    /* hardware checksum offsets */
20426 			    start, stuff, 0,
20427 			    /* hardware checksum flag */
20428 			    hwcksum_flags, tcps) != 0)) {
20429 legacy_send:
20430 				/*
20431 				 * We arrive here from a failure within the
20432 				 * inner (packetizer) loop or we fail one of
20433 				 * the conditionals above. We restore the
20434 				 * previously checkpointed values for:
20435 				 *    xmit_tail
20436 				 *    usable
20437 				 *    tail_unsent
20438 				 *    snxt
20439 				 *    obbytes
20440 				 *    obsegs
20441 				 * We should then be able to dispatch any
20442 				 * complete multidata before reverting to the
20443 				 * traditional path with consistent parameters
20444 				 * (the inner loop updates these as it
20445 				 * iterates).
20446 				 */
20447 				*xmit_tail = xmit_tail_mmd;
20448 				*usable = usable_mmd;
20449 				*tail_unsent = tail_unsent_mmd;
20450 				*snxt = snxt_mmd;
20451 				obbytes = obbytes_mmd;
20452 				obsegs = obsegs_mmd;
20453 				if (md_mp != NULL) {
20454 					/* Unlink message from the chain */
20455 					if (md_mp_head != NULL) {
20456 						err = (intptr_t)rmvb(md_mp_head,
20457 						    md_mp);
20458 						/*
20459 						 * We can't assert that rmvb
20460 						 * did not return -1, since we
20461 						 * may get here before linkb
20462 						 * happens.  We do, however,
20463 						 * check if we just removed the
20464 						 * only element in the list.
20465 						 */
20466 						if (err == 0)
20467 							md_mp_head = NULL;
20468 					}
20469 					/* md_hbuf gets freed automatically */
20470 					TCP_STAT(tcps, tcp_mdt_discarded);
20471 					freeb(md_mp);
20472 				} else {
20473 					/* Either allocb or mmd_alloc failed */
20474 					TCP_STAT(tcps, tcp_mdt_allocfail);
20475 					if (md_hbuf != NULL)
20476 						freeb(md_hbuf);
20477 				}
20478 
20479 				/* send down what we've got so far */
20480 				if (md_mp_head != NULL) {
20481 					tcp_multisend_data(tcp, ire, ill,
20482 					    md_mp_head, obsegs, obbytes,
20483 					    &rconfirm);
20484 				}
20485 legacy_send_no_md:
20486 				if (ire != NULL)
20487 					IRE_REFRELE(ire);
20488 				/*
20489 				 * Too bad; let the legacy path handle this.
20490 				 * We specify INT_MAX for the threshold, since
20491 				 * we gave up with the Multidata processings
20492 				 * and let the old path have it all.
20493 				 */
20494 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20495 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20496 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20497 				    snxt, tail_unsent, xmit_tail, local_time,
20498 				    INT_MAX));
20499 			}
20500 
20501 			/* link to any existing ones, if applicable */
20502 			TCP_STAT(tcps, tcp_mdt_allocd);
20503 			if (md_mp_head == NULL) {
20504 				md_mp_head = md_mp;
20505 			} else if (tcp_mdt_chain) {
20506 				TCP_STAT(tcps, tcp_mdt_linked);
20507 				linkb(md_mp_head, md_mp);
20508 			}
20509 		}
20510 
20511 		ASSERT(md_mp_head != NULL);
20512 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20513 		ASSERT(md_mp != NULL && mmd != NULL);
20514 		ASSERT(md_hbuf != NULL);
20515 
20516 		/*
20517 		 * Packetize the transmittable portion of the data block;
20518 		 * each data block is essentially added to the Multidata
20519 		 * as a payload buffer.  We also deal with adding more
20520 		 * than one payload buffers, which happens when the remaining
20521 		 * packetized portion of the current payload buffer is less
20522 		 * than MSS, while the next data block in transmit queue
20523 		 * has enough data to make up for one.  This "spillover"
20524 		 * case essentially creates a split-packet, where portions
20525 		 * of the packet's payload fragments may span across two
20526 		 * virtually discontiguous address blocks.
20527 		 */
20528 		seg_len = mss;
20529 		do {
20530 			len = seg_len;
20531 
20532 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20533 			ipha = NULL;
20534 			ip6h = NULL;
20535 
20536 			ASSERT(len > 0);
20537 			ASSERT(max_pld >= 0);
20538 			ASSERT(!add_buffer || cur_pld_off == 0);
20539 
20540 			/*
20541 			 * First time around for this payload buffer; note
20542 			 * in the case of a spillover, the following has
20543 			 * been done prior to adding the split-packet
20544 			 * descriptor to Multidata, and we don't want to
20545 			 * repeat the process.
20546 			 */
20547 			if (add_buffer) {
20548 				ASSERT(mmd != NULL);
20549 				ASSERT(md_pbuf == NULL);
20550 				ASSERT(md_pbuf_nxt == NULL);
20551 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20552 
20553 				/*
20554 				 * Have we reached the limit?  We'd get to
20555 				 * this case when we're not chaining the
20556 				 * Multidata messages together, and since
20557 				 * we're done, terminate this loop.
20558 				 */
20559 				if (max_pld == 0)
20560 					break; /* done */
20561 
20562 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20563 					TCP_STAT(tcps, tcp_mdt_allocfail);
20564 					goto legacy_send; /* out_of_mem */
20565 				}
20566 
20567 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20568 				    zc_cap != NULL) {
20569 					if (!ip_md_zcopy_attr(mmd, NULL,
20570 					    zc_cap->ill_zerocopy_flags)) {
20571 						freeb(md_pbuf);
20572 						TCP_STAT(tcps,
20573 						    tcp_mdt_allocfail);
20574 						/* out_of_mem */
20575 						goto legacy_send;
20576 					}
20577 					zcopy = B_TRUE;
20578 				}
20579 
20580 				md_pbuf->b_rptr += base_pld_off;
20581 
20582 				/*
20583 				 * Add a payload buffer to the Multidata; this
20584 				 * operation must not fail, or otherwise our
20585 				 * logic in this routine is broken.  There
20586 				 * is no memory allocation done by the
20587 				 * routine, so any returned failure simply
20588 				 * tells us that we've done something wrong.
20589 				 *
20590 				 * A failure tells us that either we're adding
20591 				 * the same payload buffer more than once, or
20592 				 * we're trying to add more buffers than
20593 				 * allowed (max_pld calculation is wrong).
20594 				 * None of the above cases should happen, and
20595 				 * we panic because either there's horrible
20596 				 * heap corruption, and/or programming mistake.
20597 				 */
20598 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20599 				if (pbuf_idx < 0) {
20600 					cmn_err(CE_PANIC, "tcp_multisend: "
20601 					    "payload buffer logic error "
20602 					    "detected for tcp %p mmd %p "
20603 					    "pbuf %p (%d)\n",
20604 					    (void *)tcp, (void *)mmd,
20605 					    (void *)md_pbuf, pbuf_idx);
20606 				}
20607 
20608 				ASSERT(max_pld > 0);
20609 				--max_pld;
20610 				add_buffer = B_FALSE;
20611 			}
20612 
20613 			ASSERT(md_mp_head != NULL);
20614 			ASSERT(md_pbuf != NULL);
20615 			ASSERT(md_pbuf_nxt == NULL);
20616 			ASSERT(pbuf_idx != -1);
20617 			ASSERT(pbuf_idx_nxt == -1);
20618 			ASSERT(*usable > 0);
20619 
20620 			/*
20621 			 * We spillover to the next payload buffer only
20622 			 * if all of the following is true:
20623 			 *
20624 			 *   1. There is not enough data on the current
20625 			 *	payload buffer to make up `len',
20626 			 *   2. We are allowed to send `len',
20627 			 *   3. The next payload buffer length is large
20628 			 *	enough to accomodate `spill'.
20629 			 */
20630 			if ((spill = len - *tail_unsent) > 0 &&
20631 			    *usable >= len &&
20632 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20633 			    max_pld > 0) {
20634 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20635 				if (md_pbuf_nxt == NULL) {
20636 					TCP_STAT(tcps, tcp_mdt_allocfail);
20637 					goto legacy_send; /* out_of_mem */
20638 				}
20639 
20640 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20641 				    zc_cap != NULL) {
20642 					if (!ip_md_zcopy_attr(mmd, NULL,
20643 					    zc_cap->ill_zerocopy_flags)) {
20644 						freeb(md_pbuf_nxt);
20645 						TCP_STAT(tcps,
20646 						    tcp_mdt_allocfail);
20647 						/* out_of_mem */
20648 						goto legacy_send;
20649 					}
20650 					zcopy = B_TRUE;
20651 				}
20652 
20653 				/*
20654 				 * See comments above on the first call to
20655 				 * mmd_addpldbuf for explanation on the panic.
20656 				 */
20657 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20658 				if (pbuf_idx_nxt < 0) {
20659 					panic("tcp_multisend: "
20660 					    "next payload buffer logic error "
20661 					    "detected for tcp %p mmd %p "
20662 					    "pbuf %p (%d)\n",
20663 					    (void *)tcp, (void *)mmd,
20664 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20665 				}
20666 
20667 				ASSERT(max_pld > 0);
20668 				--max_pld;
20669 			} else if (spill > 0) {
20670 				/*
20671 				 * If there's a spillover, but the following
20672 				 * xmit_tail couldn't give us enough octets
20673 				 * to reach "len", then stop the current
20674 				 * Multidata creation and let the legacy
20675 				 * tcp_send() path take over.  We don't want
20676 				 * to send the tiny segment as part of this
20677 				 * Multidata for performance reasons; instead,
20678 				 * we let the legacy path deal with grouping
20679 				 * it with the subsequent small mblks.
20680 				 */
20681 				if (*usable >= len &&
20682 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20683 					max_pld = 0;
20684 					break;	/* done */
20685 				}
20686 
20687 				/*
20688 				 * We can't spillover, and we are near
20689 				 * the end of the current payload buffer,
20690 				 * so send what's left.
20691 				 */
20692 				ASSERT(*tail_unsent > 0);
20693 				len = *tail_unsent;
20694 			}
20695 
20696 			/* tail_unsent is negated if there is a spillover */
20697 			*tail_unsent -= len;
20698 			*usable -= len;
20699 			ASSERT(*usable >= 0);
20700 
20701 			if (*usable < mss)
20702 				seg_len = *usable;
20703 			/*
20704 			 * Sender SWS avoidance; see comments in tcp_send();
20705 			 * everything else is the same, except that we only
20706 			 * do this here if there is no more data to be sent
20707 			 * following the current xmit_tail.  We don't check
20708 			 * for 1-byte urgent data because we shouldn't get
20709 			 * here if TCP_URG_VALID is set.
20710 			 */
20711 			if (*usable > 0 && *usable < mss &&
20712 			    ((md_pbuf_nxt == NULL &&
20713 			    (*xmit_tail)->b_cont == NULL) ||
20714 			    (md_pbuf_nxt != NULL &&
20715 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20716 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20717 			    (tcp->tcp_unsent -
20718 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20719 			    !tcp->tcp_zero_win_probe) {
20720 				if ((*snxt + len) == tcp->tcp_snxt &&
20721 				    (*snxt + len) == tcp->tcp_suna) {
20722 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20723 				}
20724 				done = B_TRUE;
20725 			}
20726 
20727 			/*
20728 			 * Prime pump for IP's checksumming on our behalf;
20729 			 * include the adjustment for a source route if any.
20730 			 * Do this only for software/partial hardware checksum
20731 			 * offload, as this field gets zeroed out later for
20732 			 * the full hardware checksum offload case.
20733 			 */
20734 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20735 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20736 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20737 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20738 			}
20739 
20740 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20741 			*snxt += len;
20742 
20743 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20744 			/*
20745 			 * We set the PUSH bit only if TCP has no more buffered
20746 			 * data to be transmitted (or if sender SWS avoidance
20747 			 * takes place), as opposed to setting it for every
20748 			 * last packet in the burst.
20749 			 */
20750 			if (done ||
20751 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20752 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20753 
20754 			/*
20755 			 * Set FIN bit if this is our last segment; snxt
20756 			 * already includes its length, and it will not
20757 			 * be adjusted after this point.
20758 			 */
20759 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20760 			    *snxt == tcp->tcp_fss) {
20761 				if (!tcp->tcp_fin_acked) {
20762 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20763 					BUMP_MIB(&tcps->tcps_mib,
20764 					    tcpOutControl);
20765 				}
20766 				if (!tcp->tcp_fin_sent) {
20767 					tcp->tcp_fin_sent = B_TRUE;
20768 					/*
20769 					 * tcp state must be ESTABLISHED
20770 					 * in order for us to get here in
20771 					 * the first place.
20772 					 */
20773 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20774 
20775 					/*
20776 					 * Upon returning from this routine,
20777 					 * tcp_wput_data() will set tcp_snxt
20778 					 * to be equal to snxt + tcp_fin_sent.
20779 					 * This is essentially the same as
20780 					 * setting it to tcp_fss + 1.
20781 					 */
20782 				}
20783 			}
20784 
20785 			tcp->tcp_last_sent_len = (ushort_t)len;
20786 
20787 			len += tcp_hdr_len;
20788 			if (tcp->tcp_ipversion == IPV4_VERSION)
20789 				tcp->tcp_ipha->ipha_length = htons(len);
20790 			else
20791 				tcp->tcp_ip6h->ip6_plen = htons(len -
20792 				    ((char *)&tcp->tcp_ip6h[1] -
20793 				    tcp->tcp_iphc));
20794 
20795 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20796 
20797 			/* setup header fragment */
20798 			PDESC_HDR_ADD(pkt_info,
20799 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20800 			    tcp->tcp_mdt_hdr_head,		/* head room */
20801 			    tcp_hdr_len,			/* len */
20802 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20803 
20804 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20805 			    hdr_frag_sz);
20806 			ASSERT(MBLKIN(md_hbuf,
20807 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20808 			    PDESC_HDRSIZE(pkt_info)));
20809 
20810 			/* setup first payload fragment */
20811 			PDESC_PLD_INIT(pkt_info);
20812 			PDESC_PLD_SPAN_ADD(pkt_info,
20813 			    pbuf_idx,				/* index */
20814 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20815 			    tcp->tcp_last_sent_len);		/* len */
20816 
20817 			/* create a split-packet in case of a spillover */
20818 			if (md_pbuf_nxt != NULL) {
20819 				ASSERT(spill > 0);
20820 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20821 				ASSERT(!add_buffer);
20822 
20823 				md_pbuf = md_pbuf_nxt;
20824 				md_pbuf_nxt = NULL;
20825 				pbuf_idx = pbuf_idx_nxt;
20826 				pbuf_idx_nxt = -1;
20827 				cur_pld_off = spill;
20828 
20829 				/* trim out first payload fragment */
20830 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20831 
20832 				/* setup second payload fragment */
20833 				PDESC_PLD_SPAN_ADD(pkt_info,
20834 				    pbuf_idx,			/* index */
20835 				    md_pbuf->b_rptr,		/* start */
20836 				    spill);			/* len */
20837 
20838 				if ((*xmit_tail)->b_next == NULL) {
20839 					/*
20840 					 * Store the lbolt used for RTT
20841 					 * estimation. We can only record one
20842 					 * timestamp per mblk so we do it when
20843 					 * we reach the end of the payload
20844 					 * buffer.  Also we only take a new
20845 					 * timestamp sample when the previous
20846 					 * timed data from the same mblk has
20847 					 * been ack'ed.
20848 					 */
20849 					(*xmit_tail)->b_prev = local_time;
20850 					(*xmit_tail)->b_next =
20851 					    (mblk_t *)(uintptr_t)first_snxt;
20852 				}
20853 
20854 				first_snxt = *snxt - spill;
20855 
20856 				/*
20857 				 * Advance xmit_tail; usable could be 0 by
20858 				 * the time we got here, but we made sure
20859 				 * above that we would only spillover to
20860 				 * the next data block if usable includes
20861 				 * the spilled-over amount prior to the
20862 				 * subtraction.  Therefore, we are sure
20863 				 * that xmit_tail->b_cont can't be NULL.
20864 				 */
20865 				ASSERT((*xmit_tail)->b_cont != NULL);
20866 				*xmit_tail = (*xmit_tail)->b_cont;
20867 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20868 				    (uintptr_t)INT_MAX);
20869 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20870 			} else {
20871 				cur_pld_off += tcp->tcp_last_sent_len;
20872 			}
20873 
20874 			/*
20875 			 * Fill in the header using the template header, and
20876 			 * add options such as time-stamp, ECN and/or SACK,
20877 			 * as needed.
20878 			 */
20879 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20880 			    (clock_t)local_time, num_sack_blk);
20881 
20882 			/* take care of some IP header businesses */
20883 			if (af == AF_INET) {
20884 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20885 
20886 				ASSERT(OK_32PTR((uchar_t *)ipha));
20887 				ASSERT(PDESC_HDRL(pkt_info) >=
20888 				    IP_SIMPLE_HDR_LENGTH);
20889 				ASSERT(ipha->ipha_version_and_hdr_length ==
20890 				    IP_SIMPLE_HDR_VERSION);
20891 
20892 				/*
20893 				 * Assign ident value for current packet; see
20894 				 * related comments in ip_wput_ire() about the
20895 				 * contract private interface with clustering
20896 				 * group.
20897 				 */
20898 				clusterwide = B_FALSE;
20899 				if (cl_inet_ipident != NULL) {
20900 					ASSERT(cl_inet_isclusterwide != NULL);
20901 					if ((*cl_inet_isclusterwide)(stack_id,
20902 					    IPPROTO_IP, AF_INET,
20903 					    (uint8_t *)(uintptr_t)src, NULL)) {
20904 						ipha->ipha_ident =
20905 						    (*cl_inet_ipident)(stack_id,
20906 						    IPPROTO_IP, AF_INET,
20907 						    (uint8_t *)(uintptr_t)src,
20908 						    (uint8_t *)(uintptr_t)dst,
20909 						    NULL);
20910 						clusterwide = B_TRUE;
20911 					}
20912 				}
20913 
20914 				if (!clusterwide) {
20915 					ipha->ipha_ident = (uint16_t)
20916 					    atomic_add_32_nv(
20917 						&ire->ire_ident, 1);
20918 				}
20919 #ifndef _BIG_ENDIAN
20920 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20921 				    (ipha->ipha_ident >> 8);
20922 #endif
20923 			} else {
20924 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
20925 
20926 				ASSERT(OK_32PTR((uchar_t *)ip6h));
20927 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
20928 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
20929 				ASSERT(PDESC_HDRL(pkt_info) >=
20930 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
20931 				    TCP_CHECKSUM_SIZE));
20932 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
20933 
20934 				if (tcp->tcp_ip_forward_progress) {
20935 					rconfirm = B_TRUE;
20936 					tcp->tcp_ip_forward_progress = B_FALSE;
20937 				}
20938 			}
20939 
20940 			/* at least one payload span, and at most two */
20941 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
20942 
20943 			/* add the packet descriptor to Multidata */
20944 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
20945 			    KM_NOSLEEP)) == NULL) {
20946 				/*
20947 				 * Any failure other than ENOMEM indicates
20948 				 * that we have passed in invalid pkt_info
20949 				 * or parameters to mmd_addpdesc, which must
20950 				 * not happen.
20951 				 *
20952 				 * EINVAL is a result of failure on boundary
20953 				 * checks against the pkt_info contents.  It
20954 				 * should not happen, and we panic because
20955 				 * either there's horrible heap corruption,
20956 				 * and/or programming mistake.
20957 				 */
20958 				if (err != ENOMEM) {
20959 					cmn_err(CE_PANIC, "tcp_multisend: "
20960 					    "pdesc logic error detected for "
20961 					    "tcp %p mmd %p pinfo %p (%d)\n",
20962 					    (void *)tcp, (void *)mmd,
20963 					    (void *)pkt_info, err);
20964 				}
20965 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
20966 				goto legacy_send; /* out_of_mem */
20967 			}
20968 			ASSERT(pkt != NULL);
20969 
20970 			/* calculate IP header and TCP checksums */
20971 			if (af == AF_INET) {
20972 				/* calculate pseudo-header checksum */
20973 				cksum = (dst >> 16) + (dst & 0xFFFF) +
20974 				    (src >> 16) + (src & 0xFFFF);
20975 
20976 				/* offset for TCP header checksum */
20977 				up = IPH_TCPH_CHECKSUMP(ipha,
20978 				    IP_SIMPLE_HDR_LENGTH);
20979 			} else {
20980 				up = (uint16_t *)&ip6h->ip6_src;
20981 
20982 				/* calculate pseudo-header checksum */
20983 				cksum = up[0] + up[1] + up[2] + up[3] +
20984 				    up[4] + up[5] + up[6] + up[7] +
20985 				    up[8] + up[9] + up[10] + up[11] +
20986 				    up[12] + up[13] + up[14] + up[15];
20987 
20988 				/* Fold the initial sum */
20989 				cksum = (cksum & 0xffff) + (cksum >> 16);
20990 
20991 				up = (uint16_t *)(((uchar_t *)ip6h) +
20992 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
20993 			}
20994 
20995 			if (hwcksum_flags & HCK_FULLCKSUM) {
20996 				/* clear checksum field for hardware */
20997 				*up = 0;
20998 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
20999 				uint32_t sum;
21000 
21001 				/* pseudo-header checksumming */
21002 				sum = *up + cksum + IP_TCP_CSUM_COMP;
21003 				sum = (sum & 0xFFFF) + (sum >> 16);
21004 				*up = (sum & 0xFFFF) + (sum >> 16);
21005 			} else {
21006 				/* software checksumming */
21007 				TCP_STAT(tcps, tcp_out_sw_cksum);
21008 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
21009 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
21010 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
21011 				    cksum + IP_TCP_CSUM_COMP);
21012 				if (*up == 0)
21013 					*up = 0xFFFF;
21014 			}
21015 
21016 			/* IPv4 header checksum */
21017 			if (af == AF_INET) {
21018 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
21019 					ipha->ipha_hdr_checksum = 0;
21020 				} else {
21021 					IP_HDR_CKSUM(ipha, cksum,
21022 					    ((uint32_t *)ipha)[0],
21023 					    ((uint16_t *)ipha)[4]);
21024 				}
21025 			}
21026 
21027 			if (af == AF_INET &&
21028 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
21029 			    af == AF_INET6 &&
21030 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
21031 				mblk_t	*mp, *mp1;
21032 				uchar_t	*hdr_rptr, *hdr_wptr;
21033 				uchar_t	*pld_rptr, *pld_wptr;
21034 
21035 				/*
21036 				 * We reconstruct a pseudo packet for the hooks
21037 				 * framework using mmd_transform_link().
21038 				 * If it is a split packet we pullup the
21039 				 * payload. FW_HOOKS expects a pkt comprising
21040 				 * of two mblks: a header and the payload.
21041 				 */
21042 				if ((mp = mmd_transform_link(pkt)) == NULL) {
21043 					TCP_STAT(tcps, tcp_mdt_allocfail);
21044 					goto legacy_send;
21045 				}
21046 
21047 				if (pkt_info->pld_cnt > 1) {
21048 					/* split payload, more than one pld */
21049 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
21050 					    NULL) {
21051 						freemsg(mp);
21052 						TCP_STAT(tcps,
21053 						    tcp_mdt_allocfail);
21054 						goto legacy_send;
21055 					}
21056 					freemsg(mp->b_cont);
21057 					mp->b_cont = mp1;
21058 				} else {
21059 					mp1 = mp->b_cont;
21060 				}
21061 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
21062 
21063 				/*
21064 				 * Remember the message offsets. This is so we
21065 				 * can detect changes when we return from the
21066 				 * FW_HOOKS callbacks.
21067 				 */
21068 				hdr_rptr = mp->b_rptr;
21069 				hdr_wptr = mp->b_wptr;
21070 				pld_rptr = mp->b_cont->b_rptr;
21071 				pld_wptr = mp->b_cont->b_wptr;
21072 
21073 				if (af == AF_INET) {
21074 					DTRACE_PROBE4(
21075 					    ip4__physical__out__start,
21076 					    ill_t *, NULL,
21077 					    ill_t *, ill,
21078 					    ipha_t *, ipha,
21079 					    mblk_t *, mp);
21080 					FW_HOOKS(
21081 					    ipst->ips_ip4_physical_out_event,
21082 					    ipst->ips_ipv4firewall_physical_out,
21083 					    NULL, ill, ipha, mp, mp, 0, ipst);
21084 					DTRACE_PROBE1(
21085 					    ip4__physical__out__end,
21086 					    mblk_t *, mp);
21087 				} else {
21088 					DTRACE_PROBE4(
21089 					    ip6__physical__out_start,
21090 					    ill_t *, NULL,
21091 					    ill_t *, ill,
21092 					    ip6_t *, ip6h,
21093 					    mblk_t *, mp);
21094 					FW_HOOKS6(
21095 					    ipst->ips_ip6_physical_out_event,
21096 					    ipst->ips_ipv6firewall_physical_out,
21097 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21098 					DTRACE_PROBE1(
21099 					    ip6__physical__out__end,
21100 					    mblk_t *, mp);
21101 				}
21102 
21103 				if (mp == NULL ||
21104 				    (mp1 = mp->b_cont) == NULL ||
21105 				    mp->b_rptr != hdr_rptr ||
21106 				    mp->b_wptr != hdr_wptr ||
21107 				    mp1->b_rptr != pld_rptr ||
21108 				    mp1->b_wptr != pld_wptr ||
21109 				    mp1->b_cont != NULL) {
21110 					/*
21111 					 * We abandon multidata processing and
21112 					 * return to the normal path, either
21113 					 * when a packet is blocked, or when
21114 					 * the boundaries of header buffer or
21115 					 * payload buffer have been changed by
21116 					 * FW_HOOKS[6].
21117 					 */
21118 					if (mp != NULL)
21119 						freemsg(mp);
21120 					goto legacy_send;
21121 				}
21122 				/* Finished with the pseudo packet */
21123 				freemsg(mp);
21124 			}
21125 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21126 			    ill, ipha, ip6h);
21127 			/* advance header offset */
21128 			cur_hdr_off += hdr_frag_sz;
21129 
21130 			obbytes += tcp->tcp_last_sent_len;
21131 			++obsegs;
21132 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21133 		    *tail_unsent > 0);
21134 
21135 		if ((*xmit_tail)->b_next == NULL) {
21136 			/*
21137 			 * Store the lbolt used for RTT estimation. We can only
21138 			 * record one timestamp per mblk so we do it when we
21139 			 * reach the end of the payload buffer. Also we only
21140 			 * take a new timestamp sample when the previous timed
21141 			 * data from the same mblk has been ack'ed.
21142 			 */
21143 			(*xmit_tail)->b_prev = local_time;
21144 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21145 		}
21146 
21147 		ASSERT(*tail_unsent >= 0);
21148 		if (*tail_unsent > 0) {
21149 			/*
21150 			 * We got here because we broke out of the above
21151 			 * loop due to of one of the following cases:
21152 			 *
21153 			 *   1. len < adjusted MSS (i.e. small),
21154 			 *   2. Sender SWS avoidance,
21155 			 *   3. max_pld is zero.
21156 			 *
21157 			 * We are done for this Multidata, so trim our
21158 			 * last payload buffer (if any) accordingly.
21159 			 */
21160 			if (md_pbuf != NULL)
21161 				md_pbuf->b_wptr -= *tail_unsent;
21162 		} else if (*usable > 0) {
21163 			*xmit_tail = (*xmit_tail)->b_cont;
21164 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21165 			    (uintptr_t)INT_MAX);
21166 			*tail_unsent = (int)MBLKL(*xmit_tail);
21167 			add_buffer = B_TRUE;
21168 		}
21169 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21170 	    (tcp_mdt_chain || max_pld > 0));
21171 
21172 	if (md_mp_head != NULL) {
21173 		/* send everything down */
21174 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21175 		    &rconfirm);
21176 	}
21177 
21178 #undef PREP_NEW_MULTIDATA
21179 #undef PREP_NEW_PBUF
21180 #undef IPVER
21181 
21182 	IRE_REFRELE(ire);
21183 	return (0);
21184 }
21185 
21186 /*
21187  * A wrapper function for sending one or more Multidata messages down to
21188  * the module below ip; this routine does not release the reference of the
21189  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21190  */
21191 static void
21192 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21193     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21194 {
21195 	uint64_t delta;
21196 	nce_t *nce;
21197 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21198 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21199 
21200 	ASSERT(ire != NULL && ill != NULL);
21201 	ASSERT(ire->ire_stq != NULL);
21202 	ASSERT(md_mp_head != NULL);
21203 	ASSERT(rconfirm != NULL);
21204 
21205 	/* adjust MIBs and IRE timestamp */
21206 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21207 	tcp->tcp_obsegs += obsegs;
21208 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21209 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21210 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21211 
21212 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21213 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21214 	} else {
21215 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21216 	}
21217 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21218 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21219 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21220 
21221 	ire->ire_ob_pkt_count += obsegs;
21222 	if (ire->ire_ipif != NULL)
21223 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21224 	ire->ire_last_used_time = lbolt;
21225 
21226 	if (ipst->ips_ipobs_enabled) {
21227 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21228 		pdesc_t *dl_pkt;
21229 		pdescinfo_t pinfo;
21230 		mblk_t *nmp;
21231 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21232 
21233 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21234 		    (dl_pkt != NULL);
21235 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21236 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21237 				continue;
21238 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21239 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21240 			freemsg(nmp);
21241 		}
21242 	}
21243 
21244 	/* send it down */
21245 	putnext(ire->ire_stq, md_mp_head);
21246 
21247 	/* we're done for TCP/IPv4 */
21248 	if (tcp->tcp_ipversion == IPV4_VERSION)
21249 		return;
21250 
21251 	nce = ire->ire_nce;
21252 
21253 	ASSERT(nce != NULL);
21254 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21255 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21256 
21257 	/* reachability confirmation? */
21258 	if (*rconfirm) {
21259 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21260 		if (nce->nce_state != ND_REACHABLE) {
21261 			mutex_enter(&nce->nce_lock);
21262 			nce->nce_state = ND_REACHABLE;
21263 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21264 			mutex_exit(&nce->nce_lock);
21265 			(void) untimeout(nce->nce_timeout_id);
21266 			if (ip_debug > 2) {
21267 				/* ip1dbg */
21268 				pr_addr_dbg("tcp_multisend_data: state "
21269 				    "for %s changed to REACHABLE\n",
21270 				    AF_INET6, &ire->ire_addr_v6);
21271 			}
21272 		}
21273 		/* reset transport reachability confirmation */
21274 		*rconfirm = B_FALSE;
21275 	}
21276 
21277 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21278 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21279 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21280 
21281 	if (delta > (uint64_t)ill->ill_reachable_time) {
21282 		mutex_enter(&nce->nce_lock);
21283 		switch (nce->nce_state) {
21284 		case ND_REACHABLE:
21285 		case ND_STALE:
21286 			/*
21287 			 * ND_REACHABLE is identical to ND_STALE in this
21288 			 * specific case. If reachable time has expired for
21289 			 * this neighbor (delta is greater than reachable
21290 			 * time), conceptually, the neighbor cache is no
21291 			 * longer in REACHABLE state, but already in STALE
21292 			 * state.  So the correct transition here is to
21293 			 * ND_DELAY.
21294 			 */
21295 			nce->nce_state = ND_DELAY;
21296 			mutex_exit(&nce->nce_lock);
21297 			NDP_RESTART_TIMER(nce,
21298 			    ipst->ips_delay_first_probe_time);
21299 			if (ip_debug > 3) {
21300 				/* ip2dbg */
21301 				pr_addr_dbg("tcp_multisend_data: state "
21302 				    "for %s changed to DELAY\n",
21303 				    AF_INET6, &ire->ire_addr_v6);
21304 			}
21305 			break;
21306 		case ND_DELAY:
21307 		case ND_PROBE:
21308 			mutex_exit(&nce->nce_lock);
21309 			/* Timers have already started */
21310 			break;
21311 		case ND_UNREACHABLE:
21312 			/*
21313 			 * ndp timer has detected that this nce is
21314 			 * unreachable and initiated deleting this nce
21315 			 * and all its associated IREs. This is a race
21316 			 * where we found the ire before it was deleted
21317 			 * and have just sent out a packet using this
21318 			 * unreachable nce.
21319 			 */
21320 			mutex_exit(&nce->nce_lock);
21321 			break;
21322 		default:
21323 			ASSERT(0);
21324 		}
21325 	}
21326 }
21327 
21328 /*
21329  * Derived from tcp_send_data().
21330  */
21331 static void
21332 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21333     int num_lso_seg)
21334 {
21335 	ipha_t		*ipha;
21336 	mblk_t		*ire_fp_mp;
21337 	uint_t		ire_fp_mp_len;
21338 	uint32_t	hcksum_txflags = 0;
21339 	ipaddr_t	src;
21340 	ipaddr_t	dst;
21341 	uint32_t	cksum;
21342 	uint16_t	*up;
21343 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21344 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21345 
21346 	ASSERT(DB_TYPE(mp) == M_DATA);
21347 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21348 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21349 	ASSERT(tcp->tcp_connp != NULL);
21350 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21351 
21352 	ipha = (ipha_t *)mp->b_rptr;
21353 	src = ipha->ipha_src;
21354 	dst = ipha->ipha_dst;
21355 
21356 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21357 
21358 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21359 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21360 	    num_lso_seg);
21361 #ifndef _BIG_ENDIAN
21362 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21363 #endif
21364 	if (tcp->tcp_snd_zcopy_aware) {
21365 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21366 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21367 			mp = tcp_zcopy_disable(tcp, mp);
21368 	}
21369 
21370 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21371 		ASSERT(ill->ill_hcksum_capab != NULL);
21372 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21373 	}
21374 
21375 	/*
21376 	 * Since the TCP checksum should be recalculated by h/w, we can just
21377 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21378 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21379 	 * The partial pseudo-header excludes TCP length, that was calculated
21380 	 * in tcp_send(), so to zero *up before further processing.
21381 	 */
21382 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21383 
21384 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21385 	*up = 0;
21386 
21387 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21388 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21389 
21390 	/*
21391 	 * Append LSO flags and mss to the mp.
21392 	 */
21393 	lso_info_set(mp, mss, HW_LSO);
21394 
21395 	ipha->ipha_fragment_offset_and_flags |=
21396 	    (uint32_t)htons(ire->ire_frag_flag);
21397 
21398 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21399 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21400 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21401 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21402 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21403 
21404 	UPDATE_OB_PKT_COUNT(ire);
21405 	ire->ire_last_used_time = lbolt;
21406 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21407 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21408 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21409 	    ntohs(ipha->ipha_length));
21410 
21411 	DTRACE_PROBE4(ip4__physical__out__start,
21412 	    ill_t *, NULL, ill_t *, ill, ipha_t *, ipha, mblk_t *, mp);
21413 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
21414 	    ipst->ips_ipv4firewall_physical_out, NULL,
21415 	    ill, ipha, mp, mp, 0, ipst);
21416 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21417 	DTRACE_IP_FASTPATH(mp, ipha, ill, ipha, NULL);
21418 
21419 	if (mp != NULL) {
21420 		if (ipst->ips_ipobs_enabled) {
21421 			zoneid_t szone;
21422 
21423 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
21424 			    ipst, ALL_ZONES);
21425 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21426 			    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len, ipst);
21427 		}
21428 
21429 		ILL_SEND_TX(ill, ire, tcp->tcp_connp, mp, 0, NULL);
21430 	}
21431 }
21432 
21433 /*
21434  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21435  * scheme, and returns one of the following:
21436  *
21437  * -1 = failed allocation.
21438  *  0 = success; burst count reached, or usable send window is too small,
21439  *      and that we'd rather wait until later before sending again.
21440  *  1 = success; we are called from tcp_multisend(), and both usable send
21441  *      window and tail_unsent are greater than the MDT threshold, and thus
21442  *      Multidata Transmit should be used instead.
21443  */
21444 static int
21445 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21446     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21447     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21448     const int mdt_thres)
21449 {
21450 	int num_burst_seg = tcp->tcp_snd_burst;
21451 	ire_t		*ire = NULL;
21452 	ill_t		*ill = NULL;
21453 	mblk_t		*ire_fp_mp = NULL;
21454 	uint_t		ire_fp_mp_len = 0;
21455 	int		num_lso_seg = 1;
21456 	uint_t		lso_usable;
21457 	boolean_t	do_lso_send = B_FALSE;
21458 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21459 
21460 	/*
21461 	 * Check LSO capability before any further work. And the similar check
21462 	 * need to be done in for(;;) loop.
21463 	 * LSO will be deployed when therer is more than one mss of available
21464 	 * data and a burst transmission is allowed.
21465 	 */
21466 	if (tcp->tcp_lso &&
21467 	    (tcp->tcp_valid_bits == 0 ||
21468 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21469 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21470 		/*
21471 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21472 		 * Double check LSO usability before going further, since the
21473 		 * underlying interface could have been changed. In case of any
21474 		 * change of LSO capability, set tcp_ire_ill_check_done to
21475 		 * B_FALSE to force to check the ILL with the next send.
21476 		 */
21477 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill) &&
21478 		    tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
21479 			/*
21480 			 * Enable LSO with this transmission.
21481 			 * Since IRE has been hold in tcp_send_find_ire_ill(),
21482 			 * IRE_REFRELE(ire) should be called before return.
21483 			 */
21484 			do_lso_send = B_TRUE;
21485 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21486 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21487 			/* Round up to multiple of 4 */
21488 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21489 		} else {
21490 			tcp->tcp_lso = B_FALSE;
21491 			tcp->tcp_ire_ill_check_done = B_FALSE;
21492 			do_lso_send = B_FALSE;
21493 			ill = NULL;
21494 		}
21495 	}
21496 
21497 	for (;;) {
21498 		struct datab	*db;
21499 		tcph_t		*tcph;
21500 		uint32_t	sum;
21501 		mblk_t		*mp, *mp1;
21502 		uchar_t		*rptr;
21503 		int		len;
21504 
21505 		/*
21506 		 * If we're called by tcp_multisend(), and the amount of
21507 		 * sendable data as well as the size of current xmit_tail
21508 		 * is beyond the MDT threshold, return to the caller and
21509 		 * let the large data transmit be done using MDT.
21510 		 */
21511 		if (*usable > 0 && *usable > mdt_thres &&
21512 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21513 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21514 			ASSERT(tcp->tcp_mdt);
21515 			return (1);	/* success; do large send */
21516 		}
21517 
21518 		if (num_burst_seg == 0)
21519 			break;		/* success; burst count reached */
21520 
21521 		/*
21522 		 * Calculate the maximum payload length we can send in *one*
21523 		 * time.
21524 		 */
21525 		if (do_lso_send) {
21526 			/*
21527 			 * Check whether need to do LSO any more.
21528 			 */
21529 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21530 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21531 				lso_usable = MIN(lso_usable,
21532 				    num_burst_seg * mss);
21533 
21534 				num_lso_seg = lso_usable / mss;
21535 				if (lso_usable % mss) {
21536 					num_lso_seg++;
21537 					tcp->tcp_last_sent_len = (ushort_t)
21538 					    (lso_usable % mss);
21539 				} else {
21540 					tcp->tcp_last_sent_len = (ushort_t)mss;
21541 				}
21542 			} else {
21543 				do_lso_send = B_FALSE;
21544 				num_lso_seg = 1;
21545 				lso_usable = mss;
21546 			}
21547 		}
21548 
21549 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21550 
21551 		/*
21552 		 * Adjust num_burst_seg here.
21553 		 */
21554 		num_burst_seg -= num_lso_seg;
21555 
21556 		len = mss;
21557 		if (len > *usable) {
21558 			ASSERT(do_lso_send == B_FALSE);
21559 
21560 			len = *usable;
21561 			if (len <= 0) {
21562 				/* Terminate the loop */
21563 				break;	/* success; too small */
21564 			}
21565 			/*
21566 			 * Sender silly-window avoidance.
21567 			 * Ignore this if we are going to send a
21568 			 * zero window probe out.
21569 			 *
21570 			 * TODO: force data into microscopic window?
21571 			 *	==> (!pushed || (unsent > usable))
21572 			 */
21573 			if (len < (tcp->tcp_max_swnd >> 1) &&
21574 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21575 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21576 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21577 				/*
21578 				 * If the retransmit timer is not running
21579 				 * we start it so that we will retransmit
21580 				 * in the case when the the receiver has
21581 				 * decremented the window.
21582 				 */
21583 				if (*snxt == tcp->tcp_snxt &&
21584 				    *snxt == tcp->tcp_suna) {
21585 					/*
21586 					 * We are not supposed to send
21587 					 * anything.  So let's wait a little
21588 					 * bit longer before breaking SWS
21589 					 * avoidance.
21590 					 *
21591 					 * What should the value be?
21592 					 * Suggestion: MAX(init rexmit time,
21593 					 * tcp->tcp_rto)
21594 					 */
21595 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21596 				}
21597 				break;	/* success; too small */
21598 			}
21599 		}
21600 
21601 		tcph = tcp->tcp_tcph;
21602 
21603 		/*
21604 		 * The reason to adjust len here is that we need to set flags
21605 		 * and calculate checksum.
21606 		 */
21607 		if (do_lso_send)
21608 			len = lso_usable;
21609 
21610 		*usable -= len; /* Approximate - can be adjusted later */
21611 		if (*usable > 0)
21612 			tcph->th_flags[0] = TH_ACK;
21613 		else
21614 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21615 
21616 		/*
21617 		 * Prime pump for IP's checksumming on our behalf
21618 		 * Include the adjustment for a source route if any.
21619 		 */
21620 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21621 		sum = (sum >> 16) + (sum & 0xFFFF);
21622 		U16_TO_ABE16(sum, tcph->th_sum);
21623 
21624 		U32_TO_ABE32(*snxt, tcph->th_seq);
21625 
21626 		/*
21627 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21628 		 * set.  For the case when TCP_FSS_VALID is the only valid
21629 		 * bit (normal active close), branch off only when we think
21630 		 * that the FIN flag needs to be set.  Note for this case,
21631 		 * that (snxt + len) may not reflect the actual seg_len,
21632 		 * as len may be further reduced in tcp_xmit_mp().  If len
21633 		 * gets modified, we will end up here again.
21634 		 */
21635 		if (tcp->tcp_valid_bits != 0 &&
21636 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21637 		    ((*snxt + len) == tcp->tcp_fss))) {
21638 			uchar_t		*prev_rptr;
21639 			uint32_t	prev_snxt = tcp->tcp_snxt;
21640 
21641 			if (*tail_unsent == 0) {
21642 				ASSERT((*xmit_tail)->b_cont != NULL);
21643 				*xmit_tail = (*xmit_tail)->b_cont;
21644 				prev_rptr = (*xmit_tail)->b_rptr;
21645 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21646 				    (*xmit_tail)->b_rptr);
21647 			} else {
21648 				prev_rptr = (*xmit_tail)->b_rptr;
21649 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21650 				    *tail_unsent;
21651 			}
21652 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21653 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21654 			/* Restore tcp_snxt so we get amount sent right. */
21655 			tcp->tcp_snxt = prev_snxt;
21656 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21657 				/*
21658 				 * If the previous timestamp is still in use,
21659 				 * don't stomp on it.
21660 				 */
21661 				if ((*xmit_tail)->b_next == NULL) {
21662 					(*xmit_tail)->b_prev = local_time;
21663 					(*xmit_tail)->b_next =
21664 					    (mblk_t *)(uintptr_t)(*snxt);
21665 				}
21666 			} else
21667 				(*xmit_tail)->b_rptr = prev_rptr;
21668 
21669 			if (mp == NULL) {
21670 				if (ire != NULL)
21671 					IRE_REFRELE(ire);
21672 				return (-1);
21673 			}
21674 			mp1 = mp->b_cont;
21675 
21676 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21677 				tcp->tcp_last_sent_len = (ushort_t)len;
21678 			while (mp1->b_cont) {
21679 				*xmit_tail = (*xmit_tail)->b_cont;
21680 				(*xmit_tail)->b_prev = local_time;
21681 				(*xmit_tail)->b_next =
21682 				    (mblk_t *)(uintptr_t)(*snxt);
21683 				mp1 = mp1->b_cont;
21684 			}
21685 			*snxt += len;
21686 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21687 			BUMP_LOCAL(tcp->tcp_obsegs);
21688 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21689 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21690 			tcp_send_data(tcp, q, mp);
21691 			continue;
21692 		}
21693 
21694 		*snxt += len;	/* Adjust later if we don't send all of len */
21695 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21696 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21697 
21698 		if (*tail_unsent) {
21699 			/* Are the bytes above us in flight? */
21700 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21701 			if (rptr != (*xmit_tail)->b_rptr) {
21702 				*tail_unsent -= len;
21703 				if (len <= mss) /* LSO is unusable */
21704 					tcp->tcp_last_sent_len = (ushort_t)len;
21705 				len += tcp_hdr_len;
21706 				if (tcp->tcp_ipversion == IPV4_VERSION)
21707 					tcp->tcp_ipha->ipha_length = htons(len);
21708 				else
21709 					tcp->tcp_ip6h->ip6_plen =
21710 					    htons(len -
21711 					    ((char *)&tcp->tcp_ip6h[1] -
21712 					    tcp->tcp_iphc));
21713 				mp = dupb(*xmit_tail);
21714 				if (mp == NULL) {
21715 					if (ire != NULL)
21716 						IRE_REFRELE(ire);
21717 					return (-1);	/* out_of_mem */
21718 				}
21719 				mp->b_rptr = rptr;
21720 				/*
21721 				 * If the old timestamp is no longer in use,
21722 				 * sample a new timestamp now.
21723 				 */
21724 				if ((*xmit_tail)->b_next == NULL) {
21725 					(*xmit_tail)->b_prev = local_time;
21726 					(*xmit_tail)->b_next =
21727 					    (mblk_t *)(uintptr_t)(*snxt-len);
21728 				}
21729 				goto must_alloc;
21730 			}
21731 		} else {
21732 			*xmit_tail = (*xmit_tail)->b_cont;
21733 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21734 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21735 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21736 			    (*xmit_tail)->b_rptr);
21737 		}
21738 
21739 		(*xmit_tail)->b_prev = local_time;
21740 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21741 
21742 		*tail_unsent -= len;
21743 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21744 			tcp->tcp_last_sent_len = (ushort_t)len;
21745 
21746 		len += tcp_hdr_len;
21747 		if (tcp->tcp_ipversion == IPV4_VERSION)
21748 			tcp->tcp_ipha->ipha_length = htons(len);
21749 		else
21750 			tcp->tcp_ip6h->ip6_plen = htons(len -
21751 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21752 
21753 		mp = dupb(*xmit_tail);
21754 		if (mp == NULL) {
21755 			if (ire != NULL)
21756 				IRE_REFRELE(ire);
21757 			return (-1);	/* out_of_mem */
21758 		}
21759 
21760 		len = tcp_hdr_len;
21761 		/*
21762 		 * There are four reasons to allocate a new hdr mblk:
21763 		 *  1) The bytes above us are in use by another packet
21764 		 *  2) We don't have good alignment
21765 		 *  3) The mblk is being shared
21766 		 *  4) We don't have enough room for a header
21767 		 */
21768 		rptr = mp->b_rptr - len;
21769 		if (!OK_32PTR(rptr) ||
21770 		    ((db = mp->b_datap), db->db_ref != 2) ||
21771 		    rptr < db->db_base + ire_fp_mp_len) {
21772 			/* NOTE: we assume allocb returns an OK_32PTR */
21773 
21774 		must_alloc:;
21775 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21776 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21777 			if (mp1 == NULL) {
21778 				freemsg(mp);
21779 				if (ire != NULL)
21780 					IRE_REFRELE(ire);
21781 				return (-1);	/* out_of_mem */
21782 			}
21783 			mp1->b_cont = mp;
21784 			mp = mp1;
21785 			/* Leave room for Link Level header */
21786 			len = tcp_hdr_len;
21787 			rptr =
21788 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21789 			mp->b_wptr = &rptr[len];
21790 		}
21791 
21792 		/*
21793 		 * Fill in the header using the template header, and add
21794 		 * options such as time-stamp, ECN and/or SACK, as needed.
21795 		 */
21796 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21797 
21798 		mp->b_rptr = rptr;
21799 
21800 		if (*tail_unsent) {
21801 			int spill = *tail_unsent;
21802 
21803 			mp1 = mp->b_cont;
21804 			if (mp1 == NULL)
21805 				mp1 = mp;
21806 
21807 			/*
21808 			 * If we're a little short, tack on more mblks until
21809 			 * there is no more spillover.
21810 			 */
21811 			while (spill < 0) {
21812 				mblk_t *nmp;
21813 				int nmpsz;
21814 
21815 				nmp = (*xmit_tail)->b_cont;
21816 				nmpsz = MBLKL(nmp);
21817 
21818 				/*
21819 				 * Excess data in mblk; can we split it?
21820 				 * If MDT is enabled for the connection,
21821 				 * keep on splitting as this is a transient
21822 				 * send path.
21823 				 */
21824 				if (!do_lso_send && !tcp->tcp_mdt &&
21825 				    (spill + nmpsz > 0)) {
21826 					/*
21827 					 * Don't split if stream head was
21828 					 * told to break up larger writes
21829 					 * into smaller ones.
21830 					 */
21831 					if (tcp->tcp_maxpsz > 0)
21832 						break;
21833 
21834 					/*
21835 					 * Next mblk is less than SMSS/2
21836 					 * rounded up to nearest 64-byte;
21837 					 * let it get sent as part of the
21838 					 * next segment.
21839 					 */
21840 					if (tcp->tcp_localnet &&
21841 					    !tcp->tcp_cork &&
21842 					    (nmpsz < roundup((mss >> 1), 64)))
21843 						break;
21844 				}
21845 
21846 				*xmit_tail = nmp;
21847 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21848 				/* Stash for rtt use later */
21849 				(*xmit_tail)->b_prev = local_time;
21850 				(*xmit_tail)->b_next =
21851 				    (mblk_t *)(uintptr_t)(*snxt - len);
21852 				mp1->b_cont = dupb(*xmit_tail);
21853 				mp1 = mp1->b_cont;
21854 
21855 				spill += nmpsz;
21856 				if (mp1 == NULL) {
21857 					*tail_unsent = spill;
21858 					freemsg(mp);
21859 					if (ire != NULL)
21860 						IRE_REFRELE(ire);
21861 					return (-1);	/* out_of_mem */
21862 				}
21863 			}
21864 
21865 			/* Trim back any surplus on the last mblk */
21866 			if (spill >= 0) {
21867 				mp1->b_wptr -= spill;
21868 				*tail_unsent = spill;
21869 			} else {
21870 				/*
21871 				 * We did not send everything we could in
21872 				 * order to remain within the b_cont limit.
21873 				 */
21874 				*usable -= spill;
21875 				*snxt += spill;
21876 				tcp->tcp_last_sent_len += spill;
21877 				UPDATE_MIB(&tcps->tcps_mib,
21878 				    tcpOutDataBytes, spill);
21879 				/*
21880 				 * Adjust the checksum
21881 				 */
21882 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21883 				sum += spill;
21884 				sum = (sum >> 16) + (sum & 0xFFFF);
21885 				U16_TO_ABE16(sum, tcph->th_sum);
21886 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21887 					sum = ntohs(
21888 					    ((ipha_t *)rptr)->ipha_length) +
21889 					    spill;
21890 					((ipha_t *)rptr)->ipha_length =
21891 					    htons(sum);
21892 				} else {
21893 					sum = ntohs(
21894 					    ((ip6_t *)rptr)->ip6_plen) +
21895 					    spill;
21896 					((ip6_t *)rptr)->ip6_plen =
21897 					    htons(sum);
21898 				}
21899 				*tail_unsent = 0;
21900 			}
21901 		}
21902 		if (tcp->tcp_ip_forward_progress) {
21903 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21904 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21905 			tcp->tcp_ip_forward_progress = B_FALSE;
21906 		}
21907 
21908 		if (do_lso_send) {
21909 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21910 			    num_lso_seg);
21911 			tcp->tcp_obsegs += num_lso_seg;
21912 
21913 			TCP_STAT(tcps, tcp_lso_times);
21914 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21915 		} else {
21916 			tcp_send_data(tcp, q, mp);
21917 			BUMP_LOCAL(tcp->tcp_obsegs);
21918 		}
21919 	}
21920 
21921 	if (ire != NULL)
21922 		IRE_REFRELE(ire);
21923 	return (0);
21924 }
21925 
21926 /* Unlink and return any mblk that looks like it contains a MDT info */
21927 static mblk_t *
21928 tcp_mdt_info_mp(mblk_t *mp)
21929 {
21930 	mblk_t	*prev_mp;
21931 
21932 	for (;;) {
21933 		prev_mp = mp;
21934 		/* no more to process? */
21935 		if ((mp = mp->b_cont) == NULL)
21936 			break;
21937 
21938 		switch (DB_TYPE(mp)) {
21939 		case M_CTL:
21940 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
21941 				continue;
21942 			ASSERT(prev_mp != NULL);
21943 			prev_mp->b_cont = mp->b_cont;
21944 			mp->b_cont = NULL;
21945 			return (mp);
21946 		default:
21947 			break;
21948 		}
21949 	}
21950 	return (mp);
21951 }
21952 
21953 /* MDT info update routine, called when IP notifies us about MDT */
21954 static void
21955 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
21956 {
21957 	boolean_t prev_state;
21958 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21959 
21960 	/*
21961 	 * IP is telling us to abort MDT on this connection?  We know
21962 	 * this because the capability is only turned off when IP
21963 	 * encounters some pathological cases, e.g. link-layer change
21964 	 * where the new driver doesn't support MDT, or in situation
21965 	 * where MDT usage on the link-layer has been switched off.
21966 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
21967 	 * if the link-layer doesn't support MDT, and if it does, it
21968 	 * will indicate that the feature is to be turned on.
21969 	 */
21970 	prev_state = tcp->tcp_mdt;
21971 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
21972 	if (!tcp->tcp_mdt && !first) {
21973 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
21974 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
21975 		    (void *)tcp->tcp_connp));
21976 	}
21977 
21978 	/*
21979 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
21980 	 * so disable MDT otherwise.  The checks are done here
21981 	 * and in tcp_wput_data().
21982 	 */
21983 	if (tcp->tcp_mdt &&
21984 	    (tcp->tcp_ipversion == IPV4_VERSION &&
21985 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
21986 	    (tcp->tcp_ipversion == IPV6_VERSION &&
21987 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
21988 		tcp->tcp_mdt = B_FALSE;
21989 
21990 	if (tcp->tcp_mdt) {
21991 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
21992 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
21993 			    "version (%d), expected version is %d",
21994 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
21995 			tcp->tcp_mdt = B_FALSE;
21996 			return;
21997 		}
21998 
21999 		/*
22000 		 * We need the driver to be able to handle at least three
22001 		 * spans per packet in order for tcp MDT to be utilized.
22002 		 * The first is for the header portion, while the rest are
22003 		 * needed to handle a packet that straddles across two
22004 		 * virtually non-contiguous buffers; a typical tcp packet
22005 		 * therefore consists of only two spans.  Note that we take
22006 		 * a zero as "don't care".
22007 		 */
22008 		if (mdt_capab->ill_mdt_span_limit > 0 &&
22009 		    mdt_capab->ill_mdt_span_limit < 3) {
22010 			tcp->tcp_mdt = B_FALSE;
22011 			return;
22012 		}
22013 
22014 		/* a zero means driver wants default value */
22015 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
22016 		    tcps->tcps_mdt_max_pbufs);
22017 		if (tcp->tcp_mdt_max_pld == 0)
22018 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
22019 
22020 		/* ensure 32-bit alignment */
22021 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
22022 		    mdt_capab->ill_mdt_hdr_head), 4);
22023 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
22024 		    mdt_capab->ill_mdt_hdr_tail), 4);
22025 
22026 		if (!first && !prev_state) {
22027 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
22028 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
22029 			    (void *)tcp->tcp_connp));
22030 		}
22031 	}
22032 }
22033 
22034 /* Unlink and return any mblk that looks like it contains a LSO info */
22035 static mblk_t *
22036 tcp_lso_info_mp(mblk_t *mp)
22037 {
22038 	mblk_t	*prev_mp;
22039 
22040 	for (;;) {
22041 		prev_mp = mp;
22042 		/* no more to process? */
22043 		if ((mp = mp->b_cont) == NULL)
22044 			break;
22045 
22046 		switch (DB_TYPE(mp)) {
22047 		case M_CTL:
22048 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
22049 				continue;
22050 			ASSERT(prev_mp != NULL);
22051 			prev_mp->b_cont = mp->b_cont;
22052 			mp->b_cont = NULL;
22053 			return (mp);
22054 		default:
22055 			break;
22056 		}
22057 	}
22058 
22059 	return (mp);
22060 }
22061 
22062 /* LSO info update routine, called when IP notifies us about LSO */
22063 static void
22064 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
22065 {
22066 	tcp_stack_t *tcps = tcp->tcp_tcps;
22067 
22068 	/*
22069 	 * IP is telling us to abort LSO on this connection?  We know
22070 	 * this because the capability is only turned off when IP
22071 	 * encounters some pathological cases, e.g. link-layer change
22072 	 * where the new NIC/driver doesn't support LSO, or in situation
22073 	 * where LSO usage on the link-layer has been switched off.
22074 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
22075 	 * if the link-layer doesn't support LSO, and if it does, it
22076 	 * will indicate that the feature is to be turned on.
22077 	 */
22078 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
22079 	TCP_STAT(tcps, tcp_lso_enabled);
22080 
22081 	/*
22082 	 * We currently only support LSO on simple TCP/IPv4,
22083 	 * so disable LSO otherwise.  The checks are done here
22084 	 * and in tcp_wput_data().
22085 	 */
22086 	if (tcp->tcp_lso &&
22087 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22088 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22089 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
22090 		tcp->tcp_lso = B_FALSE;
22091 		TCP_STAT(tcps, tcp_lso_disabled);
22092 	} else {
22093 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
22094 		    lso_capab->ill_lso_max);
22095 	}
22096 }
22097 
22098 static void
22099 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22100 {
22101 	conn_t *connp = tcp->tcp_connp;
22102 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22103 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22104 
22105 	ASSERT(ire != NULL);
22106 
22107 	/*
22108 	 * We may be in the fastpath here, and although we essentially do
22109 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22110 	 * we try to keep things as brief as possible.  After all, these
22111 	 * are only best-effort checks, and we do more thorough ones prior
22112 	 * to calling tcp_send()/tcp_multisend().
22113 	 */
22114 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22115 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22116 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22117 	    !(ire->ire_flags & RTF_MULTIRT) &&
22118 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22119 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22120 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22121 			/* Cache the result */
22122 			connp->conn_lso_ok = B_TRUE;
22123 
22124 			ASSERT(ill->ill_lso_capab != NULL);
22125 			if (!ill->ill_lso_capab->ill_lso_on) {
22126 				ill->ill_lso_capab->ill_lso_on = 1;
22127 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22128 				    "LSO for interface %s\n", (void *)connp,
22129 				    ill->ill_name));
22130 			}
22131 			tcp_lso_update(tcp, ill->ill_lso_capab);
22132 		} else if (ipst->ips_ip_multidata_outbound &&
22133 		    ILL_MDT_CAPABLE(ill)) {
22134 			/* Cache the result */
22135 			connp->conn_mdt_ok = B_TRUE;
22136 
22137 			ASSERT(ill->ill_mdt_capab != NULL);
22138 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22139 				ill->ill_mdt_capab->ill_mdt_on = 1;
22140 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22141 				    "MDT for interface %s\n", (void *)connp,
22142 				    ill->ill_name));
22143 			}
22144 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22145 		}
22146 	}
22147 
22148 	/*
22149 	 * The goal is to reduce the number of generated tcp segments by
22150 	 * setting the maxpsz multiplier to 0; this will have an affect on
22151 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22152 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22153 	 * of outbound segments and incoming ACKs, thus allowing for better
22154 	 * network and system performance.  In contrast the legacy behavior
22155 	 * may result in sending less than SMSS size, because the last mblk
22156 	 * for some packets may have more data than needed to make up SMSS,
22157 	 * and the legacy code refused to "split" it.
22158 	 *
22159 	 * We apply the new behavior on following situations:
22160 	 *
22161 	 *   1) Loopback connections,
22162 	 *   2) Connections in which the remote peer is not on local subnet,
22163 	 *   3) Local subnet connections over the bge interface (see below).
22164 	 *
22165 	 * Ideally, we would like this behavior to apply for interfaces other
22166 	 * than bge.  However, doing so would negatively impact drivers which
22167 	 * perform dynamic mapping and unmapping of DMA resources, which are
22168 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22169 	 * packet will be generated by tcp).  The bge driver does not suffer
22170 	 * from this, as it copies the mblks into pre-mapped buffers, and
22171 	 * therefore does not require more I/O resources than before.
22172 	 *
22173 	 * Otherwise, this behavior is present on all network interfaces when
22174 	 * the destination endpoint is non-local, since reducing the number
22175 	 * of packets in general is good for the network.
22176 	 *
22177 	 * TODO We need to remove this hard-coded conditional for bge once
22178 	 *	a better "self-tuning" mechanism, or a way to comprehend
22179 	 *	the driver transmit strategy is devised.  Until the solution
22180 	 *	is found and well understood, we live with this hack.
22181 	 */
22182 	if (!tcp_static_maxpsz &&
22183 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22184 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22185 		/* override the default value */
22186 		tcp->tcp_maxpsz = 0;
22187 
22188 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22189 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22190 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22191 	}
22192 
22193 	/* set the stream head parameters accordingly */
22194 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22195 }
22196 
22197 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22198 static void
22199 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22200 {
22201 	uchar_t	fval = *mp->b_rptr;
22202 	mblk_t	*tail;
22203 	queue_t	*q = tcp->tcp_wq;
22204 
22205 	/* TODO: How should flush interact with urgent data? */
22206 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22207 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22208 		/*
22209 		 * Flush only data that has not yet been put on the wire.  If
22210 		 * we flush data that we have already transmitted, life, as we
22211 		 * know it, may come to an end.
22212 		 */
22213 		tail = tcp->tcp_xmit_tail;
22214 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22215 		tcp->tcp_xmit_tail_unsent = 0;
22216 		tcp->tcp_unsent = 0;
22217 		if (tail->b_wptr != tail->b_rptr)
22218 			tail = tail->b_cont;
22219 		if (tail) {
22220 			mblk_t **excess = &tcp->tcp_xmit_head;
22221 			for (;;) {
22222 				mblk_t *mp1 = *excess;
22223 				if (mp1 == tail)
22224 					break;
22225 				tcp->tcp_xmit_tail = mp1;
22226 				tcp->tcp_xmit_last = mp1;
22227 				excess = &mp1->b_cont;
22228 			}
22229 			*excess = NULL;
22230 			tcp_close_mpp(&tail);
22231 			if (tcp->tcp_snd_zcopy_aware)
22232 				tcp_zcopy_notify(tcp);
22233 		}
22234 		/*
22235 		 * We have no unsent data, so unsent must be less than
22236 		 * tcp_xmit_lowater, so re-enable flow.
22237 		 */
22238 		mutex_enter(&tcp->tcp_non_sq_lock);
22239 		if (tcp->tcp_flow_stopped) {
22240 			tcp_clrqfull(tcp);
22241 		}
22242 		mutex_exit(&tcp->tcp_non_sq_lock);
22243 	}
22244 	/*
22245 	 * TODO: you can't just flush these, you have to increase rwnd for one
22246 	 * thing.  For another, how should urgent data interact?
22247 	 */
22248 	if (fval & FLUSHR) {
22249 		*mp->b_rptr = fval & ~FLUSHW;
22250 		/* XXX */
22251 		qreply(q, mp);
22252 		return;
22253 	}
22254 	freemsg(mp);
22255 }
22256 
22257 /*
22258  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22259  * messages.
22260  */
22261 static void
22262 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22263 {
22264 	mblk_t	*mp1;
22265 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22266 	STRUCT_HANDLE(strbuf, sb);
22267 	queue_t *q = tcp->tcp_wq;
22268 	int	error;
22269 	uint_t	addrlen;
22270 
22271 	/* Make sure it is one of ours. */
22272 	switch (iocp->ioc_cmd) {
22273 	case TI_GETMYNAME:
22274 	case TI_GETPEERNAME:
22275 		break;
22276 	default:
22277 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22278 		return;
22279 	}
22280 	switch (mi_copy_state(q, mp, &mp1)) {
22281 	case -1:
22282 		return;
22283 	case MI_COPY_CASE(MI_COPY_IN, 1):
22284 		break;
22285 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22286 		/* Copy out the strbuf. */
22287 		mi_copyout(q, mp);
22288 		return;
22289 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22290 		/* All done. */
22291 		mi_copy_done(q, mp, 0);
22292 		return;
22293 	default:
22294 		mi_copy_done(q, mp, EPROTO);
22295 		return;
22296 	}
22297 	/* Check alignment of the strbuf */
22298 	if (!OK_32PTR(mp1->b_rptr)) {
22299 		mi_copy_done(q, mp, EINVAL);
22300 		return;
22301 	}
22302 
22303 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22304 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22305 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22306 		mi_copy_done(q, mp, EINVAL);
22307 		return;
22308 	}
22309 
22310 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22311 	if (mp1 == NULL)
22312 		return;
22313 
22314 	switch (iocp->ioc_cmd) {
22315 	case TI_GETMYNAME:
22316 		error = tcp_do_getsockname(tcp, (void *)mp1->b_rptr, &addrlen);
22317 		break;
22318 	case TI_GETPEERNAME:
22319 		error = tcp_do_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22320 		break;
22321 	}
22322 
22323 	if (error != 0) {
22324 		mi_copy_done(q, mp, error);
22325 	} else {
22326 		mp1->b_wptr += addrlen;
22327 		STRUCT_FSET(sb, len, addrlen);
22328 
22329 		/* Copy out the address */
22330 		mi_copyout(q, mp);
22331 	}
22332 }
22333 
22334 static void
22335 tcp_disable_direct_sockfs(tcp_t *tcp)
22336 {
22337 #ifdef	_ILP32
22338 	tcp->tcp_acceptor_id = (t_uscalar_t)tcp->tcp_rq;
22339 #else
22340 	tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22341 #endif
22342 	/*
22343 	 * Insert this socket into the acceptor hash.
22344 	 * We might need it for T_CONN_RES message
22345 	 */
22346 	tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22347 
22348 	if (tcp->tcp_fused) {
22349 		/*
22350 		 * This is a fused loopback tcp; disable
22351 		 * read-side synchronous streams interface
22352 		 * and drain any queued data.  It is okay
22353 		 * to do this for non-synchronous streams
22354 		 * fused tcp as well.
22355 		 */
22356 		tcp_fuse_disable_pair(tcp, B_FALSE);
22357 	}
22358 	tcp->tcp_issocket = B_FALSE;
22359 	tcp->tcp_sodirect = NULL;
22360 	TCP_STAT(tcp->tcp_tcps, tcp_sock_fallback);
22361 }
22362 
22363 /*
22364  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22365  * messages.
22366  */
22367 /* ARGSUSED */
22368 static void
22369 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22370 {
22371 	conn_t 	*connp = (conn_t *)arg;
22372 	tcp_t	*tcp = connp->conn_tcp;
22373 	queue_t	*q = tcp->tcp_wq;
22374 	struct iocblk	*iocp;
22375 
22376 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22377 	/*
22378 	 * Try and ASSERT the minimum possible references on the
22379 	 * conn early enough. Since we are executing on write side,
22380 	 * the connection is obviously not detached and that means
22381 	 * there is a ref each for TCP and IP. Since we are behind
22382 	 * the squeue, the minimum references needed are 3. If the
22383 	 * conn is in classifier hash list, there should be an
22384 	 * extra ref for that (we check both the possibilities).
22385 	 */
22386 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22387 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22388 
22389 	iocp = (struct iocblk *)mp->b_rptr;
22390 	switch (iocp->ioc_cmd) {
22391 	case TCP_IOC_DEFAULT_Q:
22392 		/* Wants to be the default wq. */
22393 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22394 			iocp->ioc_error = EPERM;
22395 			iocp->ioc_count = 0;
22396 			mp->b_datap->db_type = M_IOCACK;
22397 			qreply(q, mp);
22398 			return;
22399 		}
22400 		tcp_def_q_set(tcp, mp);
22401 		return;
22402 	case _SIOCSOCKFALLBACK:
22403 		/*
22404 		 * Either sockmod is about to be popped and the socket
22405 		 * would now be treated as a plain stream, or a module
22406 		 * is about to be pushed so we could no longer use read-
22407 		 * side synchronous streams for fused loopback tcp.
22408 		 * Drain any queued data and disable direct sockfs
22409 		 * interface from now on.
22410 		 */
22411 		if (!tcp->tcp_issocket) {
22412 			DB_TYPE(mp) = M_IOCNAK;
22413 			iocp->ioc_error = EINVAL;
22414 		} else {
22415 			tcp_disable_direct_sockfs(tcp);
22416 			DB_TYPE(mp) = M_IOCACK;
22417 			iocp->ioc_error = 0;
22418 		}
22419 		iocp->ioc_count = 0;
22420 		iocp->ioc_rval = 0;
22421 		qreply(q, mp);
22422 		return;
22423 	}
22424 	CALL_IP_WPUT(connp, q, mp);
22425 }
22426 
22427 /*
22428  * This routine is called by tcp_wput() to handle all TPI requests.
22429  */
22430 /* ARGSUSED */
22431 static void
22432 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22433 {
22434 	conn_t 	*connp = (conn_t *)arg;
22435 	tcp_t	*tcp = connp->conn_tcp;
22436 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22437 	uchar_t *rptr;
22438 	t_scalar_t type;
22439 	cred_t *cr;
22440 
22441 	/*
22442 	 * Try and ASSERT the minimum possible references on the
22443 	 * conn early enough. Since we are executing on write side,
22444 	 * the connection is obviously not detached and that means
22445 	 * there is a ref each for TCP and IP. Since we are behind
22446 	 * the squeue, the minimum references needed are 3. If the
22447 	 * conn is in classifier hash list, there should be an
22448 	 * extra ref for that (we check both the possibilities).
22449 	 */
22450 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22451 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22452 
22453 	rptr = mp->b_rptr;
22454 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22455 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22456 		type = ((union T_primitives *)rptr)->type;
22457 		if (type == T_EXDATA_REQ) {
22458 			tcp_output_urgent(connp, mp->b_cont, arg2);
22459 			freeb(mp);
22460 		} else if (type != T_DATA_REQ) {
22461 			goto non_urgent_data;
22462 		} else {
22463 			/* TODO: options, flags, ... from user */
22464 			/* Set length to zero for reclamation below */
22465 			tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22466 			freeb(mp);
22467 		}
22468 		return;
22469 	} else {
22470 		if (tcp->tcp_debug) {
22471 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22472 			    "tcp_wput_proto, dropping one...");
22473 		}
22474 		freemsg(mp);
22475 		return;
22476 	}
22477 
22478 non_urgent_data:
22479 
22480 	switch ((int)tprim->type) {
22481 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22482 		/*
22483 		 * save the kssl_ent_t from the next block, and convert this
22484 		 * back to a normal bind_req.
22485 		 */
22486 		if (mp->b_cont != NULL) {
22487 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22488 
22489 			if (tcp->tcp_kssl_ent != NULL) {
22490 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22491 				    KSSL_NO_PROXY);
22492 				tcp->tcp_kssl_ent = NULL;
22493 			}
22494 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22495 			    sizeof (kssl_ent_t));
22496 			kssl_hold_ent(tcp->tcp_kssl_ent);
22497 			freemsg(mp->b_cont);
22498 			mp->b_cont = NULL;
22499 		}
22500 		tprim->type = T_BIND_REQ;
22501 
22502 	/* FALLTHROUGH */
22503 	case O_T_BIND_REQ:	/* bind request */
22504 	case T_BIND_REQ:	/* new semantics bind request */
22505 		tcp_tpi_bind(tcp, mp);
22506 		break;
22507 	case T_UNBIND_REQ:	/* unbind request */
22508 		tcp_tpi_unbind(tcp, mp);
22509 		break;
22510 	case O_T_CONN_RES:	/* old connection response XXX */
22511 	case T_CONN_RES:	/* connection response */
22512 		tcp_tli_accept(tcp, mp);
22513 		break;
22514 	case T_CONN_REQ:	/* connection request */
22515 		tcp_tpi_connect(tcp, mp);
22516 		break;
22517 	case T_DISCON_REQ:	/* disconnect request */
22518 		tcp_disconnect(tcp, mp);
22519 		break;
22520 	case T_CAPABILITY_REQ:
22521 		tcp_capability_req(tcp, mp);	/* capability request */
22522 		break;
22523 	case T_INFO_REQ:	/* information request */
22524 		tcp_info_req(tcp, mp);
22525 		break;
22526 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22527 	case T_OPTMGMT_REQ:
22528 		/*
22529 		 * Note:  no support for snmpcom_req() through new
22530 		 * T_OPTMGMT_REQ. See comments in ip.c
22531 		 */
22532 
22533 		/*
22534 		 * All Solaris components should pass a db_credp
22535 		 * for this TPI message, hence we ASSERT.
22536 		 * But in case there is some other M_PROTO that looks
22537 		 * like a TPI message sent by some other kernel
22538 		 * component, we check and return an error.
22539 		 */
22540 		cr = msg_getcred(mp, NULL);
22541 		ASSERT(cr != NULL);
22542 		if (cr == NULL) {
22543 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
22544 			return;
22545 		}
22546 		/*
22547 		 * If EINPROGRESS is returned, the request has been queued
22548 		 * for subsequent processing by ip_restart_optmgmt(), which
22549 		 * will do the CONN_DEC_REF().
22550 		 */
22551 		CONN_INC_REF(connp);
22552 		if ((int)tprim->type == T_SVR4_OPTMGMT_REQ) {
22553 			if (svr4_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22554 			    B_TRUE) != EINPROGRESS) {
22555 				CONN_DEC_REF(connp);
22556 			}
22557 		} else {
22558 			if (tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22559 			    B_TRUE) != EINPROGRESS) {
22560 				CONN_DEC_REF(connp);
22561 			}
22562 		}
22563 		break;
22564 
22565 	case T_UNITDATA_REQ:	/* unitdata request */
22566 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22567 		break;
22568 	case T_ORDREL_REQ:	/* orderly release req */
22569 		freemsg(mp);
22570 
22571 		if (tcp->tcp_fused)
22572 			tcp_unfuse(tcp);
22573 
22574 		if (tcp_xmit_end(tcp) != 0) {
22575 			/*
22576 			 * We were crossing FINs and got a reset from
22577 			 * the other side. Just ignore it.
22578 			 */
22579 			if (tcp->tcp_debug) {
22580 				(void) strlog(TCP_MOD_ID, 0, 1,
22581 				    SL_ERROR|SL_TRACE,
22582 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22583 				    "state %s",
22584 				    tcp_display(tcp, NULL,
22585 				    DISP_ADDR_AND_PORT));
22586 			}
22587 		}
22588 		break;
22589 	case T_ADDR_REQ:
22590 		tcp_addr_req(tcp, mp);
22591 		break;
22592 	default:
22593 		if (tcp->tcp_debug) {
22594 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22595 			    "tcp_wput_proto, bogus TPI msg, type %d",
22596 			    tprim->type);
22597 		}
22598 		/*
22599 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22600 		 * to recover.
22601 		 */
22602 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22603 		break;
22604 	}
22605 }
22606 
22607 /*
22608  * The TCP write service routine should never be called...
22609  */
22610 /* ARGSUSED */
22611 static void
22612 tcp_wsrv(queue_t *q)
22613 {
22614 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22615 
22616 	TCP_STAT(tcps, tcp_wsrv_called);
22617 }
22618 
22619 /* Non overlapping byte exchanger */
22620 static void
22621 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22622 {
22623 	uchar_t	uch;
22624 
22625 	while (len-- > 0) {
22626 		uch = a[len];
22627 		a[len] = b[len];
22628 		b[len] = uch;
22629 	}
22630 }
22631 
22632 /*
22633  * Send out a control packet on the tcp connection specified.  This routine
22634  * is typically called where we need a simple ACK or RST generated.
22635  */
22636 static void
22637 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22638 {
22639 	uchar_t		*rptr;
22640 	tcph_t		*tcph;
22641 	ipha_t		*ipha = NULL;
22642 	ip6_t		*ip6h = NULL;
22643 	uint32_t	sum;
22644 	int		tcp_hdr_len;
22645 	int		tcp_ip_hdr_len;
22646 	mblk_t		*mp;
22647 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22648 
22649 	/*
22650 	 * Save sum for use in source route later.
22651 	 */
22652 	ASSERT(tcp != NULL);
22653 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22654 	tcp_hdr_len = tcp->tcp_hdr_len;
22655 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22656 
22657 	/* If a text string is passed in with the request, pass it to strlog. */
22658 	if (str != NULL && tcp->tcp_debug) {
22659 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22660 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22661 		    str, seq, ack, ctl);
22662 	}
22663 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22664 	    BPRI_MED);
22665 	if (mp == NULL) {
22666 		return;
22667 	}
22668 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22669 	mp->b_rptr = rptr;
22670 	mp->b_wptr = &rptr[tcp_hdr_len];
22671 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22672 
22673 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22674 		ipha = (ipha_t *)rptr;
22675 		ipha->ipha_length = htons(tcp_hdr_len);
22676 	} else {
22677 		ip6h = (ip6_t *)rptr;
22678 		ASSERT(tcp != NULL);
22679 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22680 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22681 	}
22682 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22683 	tcph->th_flags[0] = (uint8_t)ctl;
22684 	if (ctl & TH_RST) {
22685 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22686 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22687 		/*
22688 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22689 		 */
22690 		if (tcp->tcp_snd_ts_ok &&
22691 		    tcp->tcp_state > TCPS_SYN_SENT) {
22692 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22693 			*(mp->b_wptr) = TCPOPT_EOL;
22694 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22695 				ipha->ipha_length = htons(tcp_hdr_len -
22696 				    TCPOPT_REAL_TS_LEN);
22697 			} else {
22698 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22699 				    TCPOPT_REAL_TS_LEN);
22700 			}
22701 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22702 			sum -= TCPOPT_REAL_TS_LEN;
22703 		}
22704 	}
22705 	if (ctl & TH_ACK) {
22706 		if (tcp->tcp_snd_ts_ok) {
22707 			U32_TO_BE32(lbolt,
22708 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22709 			U32_TO_BE32(tcp->tcp_ts_recent,
22710 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22711 		}
22712 
22713 		/* Update the latest receive window size in TCP header. */
22714 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22715 		    tcph->th_win);
22716 		tcp->tcp_rack = ack;
22717 		tcp->tcp_rack_cnt = 0;
22718 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22719 	}
22720 	BUMP_LOCAL(tcp->tcp_obsegs);
22721 	U32_TO_BE32(seq, tcph->th_seq);
22722 	U32_TO_BE32(ack, tcph->th_ack);
22723 	/*
22724 	 * Include the adjustment for a source route if any.
22725 	 */
22726 	sum = (sum >> 16) + (sum & 0xFFFF);
22727 	U16_TO_BE16(sum, tcph->th_sum);
22728 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22729 }
22730 
22731 /*
22732  * If this routine returns B_TRUE, TCP can generate a RST in response
22733  * to a segment.  If it returns B_FALSE, TCP should not respond.
22734  */
22735 static boolean_t
22736 tcp_send_rst_chk(tcp_stack_t *tcps)
22737 {
22738 	clock_t	now;
22739 
22740 	/*
22741 	 * TCP needs to protect itself from generating too many RSTs.
22742 	 * This can be a DoS attack by sending us random segments
22743 	 * soliciting RSTs.
22744 	 *
22745 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22746 	 * in each 1 second interval.  In this way, TCP still generate
22747 	 * RSTs in normal cases but when under attack, the impact is
22748 	 * limited.
22749 	 */
22750 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22751 		now = lbolt;
22752 		/* lbolt can wrap around. */
22753 		if ((tcps->tcps_last_rst_intrvl > now) ||
22754 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22755 		    1*SECONDS)) {
22756 			tcps->tcps_last_rst_intrvl = now;
22757 			tcps->tcps_rst_cnt = 1;
22758 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22759 			return (B_FALSE);
22760 		}
22761 	}
22762 	return (B_TRUE);
22763 }
22764 
22765 /*
22766  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22767  */
22768 static void
22769 tcp_ip_ire_mark_advice(tcp_t *tcp)
22770 {
22771 	mblk_t *mp;
22772 	ipic_t *ipic;
22773 
22774 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22775 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22776 		    &ipic);
22777 	} else {
22778 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22779 		    &ipic);
22780 	}
22781 	if (mp == NULL)
22782 		return;
22783 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22784 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22785 }
22786 
22787 /*
22788  * Return an IP advice ioctl mblk and set ipic to be the pointer
22789  * to the advice structure.
22790  */
22791 static mblk_t *
22792 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22793 {
22794 	struct iocblk *ioc;
22795 	mblk_t *mp, *mp1;
22796 
22797 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22798 	if (mp == NULL)
22799 		return (NULL);
22800 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22801 	*ipic = (ipic_t *)mp->b_rptr;
22802 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22803 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22804 
22805 	bcopy(addr, *ipic + 1, addr_len);
22806 
22807 	(*ipic)->ipic_addr_length = addr_len;
22808 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22809 
22810 	mp1 = mkiocb(IP_IOCTL);
22811 	if (mp1 == NULL) {
22812 		freemsg(mp);
22813 		return (NULL);
22814 	}
22815 	mp1->b_cont = mp;
22816 	ioc = (struct iocblk *)mp1->b_rptr;
22817 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22818 
22819 	return (mp1);
22820 }
22821 
22822 /*
22823  * Generate a reset based on an inbound packet, connp is set by caller
22824  * when RST is in response to an unexpected inbound packet for which
22825  * there is active tcp state in the system.
22826  *
22827  * IPSEC NOTE : Try to send the reply with the same protection as it came
22828  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22829  * the packet will go out at the same level of protection as it came in by
22830  * converting the IPSEC_IN to IPSEC_OUT.
22831  */
22832 static void
22833 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22834     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22835     tcp_stack_t *tcps, conn_t *connp)
22836 {
22837 	ipha_t		*ipha = NULL;
22838 	ip6_t		*ip6h = NULL;
22839 	ushort_t	len;
22840 	tcph_t		*tcph;
22841 	int		i;
22842 	mblk_t		*ipsec_mp;
22843 	boolean_t	mctl_present;
22844 	ipic_t		*ipic;
22845 	ipaddr_t	v4addr;
22846 	in6_addr_t	v6addr;
22847 	int		addr_len;
22848 	void		*addr;
22849 	queue_t		*q = tcps->tcps_g_q;
22850 	tcp_t		*tcp;
22851 	cred_t		*cr;
22852 	mblk_t		*nmp;
22853 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22854 
22855 	if (tcps->tcps_g_q == NULL) {
22856 		/*
22857 		 * For non-zero stackids the default queue isn't created
22858 		 * until the first open, thus there can be a need to send
22859 		 * a reset before then. But we can't do that, hence we just
22860 		 * drop the packet. Later during boot, when the default queue
22861 		 * has been setup, a retransmitted packet from the peer
22862 		 * will result in a reset.
22863 		 */
22864 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22865 		    GLOBAL_NETSTACKID);
22866 		freemsg(mp);
22867 		return;
22868 	}
22869 
22870 	if (connp != NULL)
22871 		tcp = connp->conn_tcp;
22872 	else
22873 		tcp = Q_TO_TCP(q);
22874 
22875 	if (!tcp_send_rst_chk(tcps)) {
22876 		tcps->tcps_rst_unsent++;
22877 		freemsg(mp);
22878 		return;
22879 	}
22880 
22881 	if (mp->b_datap->db_type == M_CTL) {
22882 		ipsec_mp = mp;
22883 		mp = mp->b_cont;
22884 		mctl_present = B_TRUE;
22885 	} else {
22886 		ipsec_mp = mp;
22887 		mctl_present = B_FALSE;
22888 	}
22889 
22890 	if (str && q && tcps->tcps_dbg) {
22891 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22892 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22893 		    "flags 0x%x",
22894 		    str, seq, ack, ctl);
22895 	}
22896 	if (mp->b_datap->db_ref != 1) {
22897 		mblk_t *mp1 = copyb(mp);
22898 		freemsg(mp);
22899 		mp = mp1;
22900 		if (!mp) {
22901 			if (mctl_present)
22902 				freeb(ipsec_mp);
22903 			return;
22904 		} else {
22905 			if (mctl_present) {
22906 				ipsec_mp->b_cont = mp;
22907 			} else {
22908 				ipsec_mp = mp;
22909 			}
22910 		}
22911 	} else if (mp->b_cont) {
22912 		freemsg(mp->b_cont);
22913 		mp->b_cont = NULL;
22914 	}
22915 	/*
22916 	 * We skip reversing source route here.
22917 	 * (for now we replace all IP options with EOL)
22918 	 */
22919 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22920 		ipha = (ipha_t *)mp->b_rptr;
22921 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22922 			mp->b_rptr[i] = IPOPT_EOL;
22923 		/*
22924 		 * Make sure that src address isn't flagrantly invalid.
22925 		 * Not all broadcast address checking for the src address
22926 		 * is possible, since we don't know the netmask of the src
22927 		 * addr.  No check for destination address is done, since
22928 		 * IP will not pass up a packet with a broadcast dest
22929 		 * address to TCP.  Similar checks are done below for IPv6.
22930 		 */
22931 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
22932 		    CLASSD(ipha->ipha_src)) {
22933 			freemsg(ipsec_mp);
22934 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
22935 			return;
22936 		}
22937 	} else {
22938 		ip6h = (ip6_t *)mp->b_rptr;
22939 
22940 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
22941 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
22942 			freemsg(ipsec_mp);
22943 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
22944 			return;
22945 		}
22946 
22947 		/* Remove any extension headers assuming partial overlay */
22948 		if (ip_hdr_len > IPV6_HDR_LEN) {
22949 			uint8_t *to;
22950 
22951 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
22952 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
22953 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
22954 			ip_hdr_len = IPV6_HDR_LEN;
22955 			ip6h = (ip6_t *)mp->b_rptr;
22956 			ip6h->ip6_nxt = IPPROTO_TCP;
22957 		}
22958 	}
22959 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
22960 	if (tcph->th_flags[0] & TH_RST) {
22961 		freemsg(ipsec_mp);
22962 		return;
22963 	}
22964 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
22965 	len = ip_hdr_len + sizeof (tcph_t);
22966 	mp->b_wptr = &mp->b_rptr[len];
22967 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22968 		ipha->ipha_length = htons(len);
22969 		/* Swap addresses */
22970 		v4addr = ipha->ipha_src;
22971 		ipha->ipha_src = ipha->ipha_dst;
22972 		ipha->ipha_dst = v4addr;
22973 		ipha->ipha_ident = 0;
22974 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
22975 		addr_len = IP_ADDR_LEN;
22976 		addr = &v4addr;
22977 	} else {
22978 		/* No ip6i_t in this case */
22979 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
22980 		/* Swap addresses */
22981 		v6addr = ip6h->ip6_src;
22982 		ip6h->ip6_src = ip6h->ip6_dst;
22983 		ip6h->ip6_dst = v6addr;
22984 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
22985 		addr_len = IPV6_ADDR_LEN;
22986 		addr = &v6addr;
22987 	}
22988 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
22989 	U32_TO_BE32(ack, tcph->th_ack);
22990 	U32_TO_BE32(seq, tcph->th_seq);
22991 	U16_TO_BE16(0, tcph->th_win);
22992 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
22993 	tcph->th_flags[0] = (uint8_t)ctl;
22994 	if (ctl & TH_RST) {
22995 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22996 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22997 	}
22998 
22999 	/* IP trusts us to set up labels when required. */
23000 	if (is_system_labeled() && (cr = msg_getcred(mp, NULL)) != NULL &&
23001 	    crgetlabel(cr) != NULL) {
23002 		int err;
23003 
23004 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
23005 			err = tsol_check_label(cr, &mp,
23006 			    tcp->tcp_connp->conn_mac_exempt,
23007 			    tcps->tcps_netstack->netstack_ip);
23008 		else
23009 			err = tsol_check_label_v6(cr, &mp,
23010 			    tcp->tcp_connp->conn_mac_exempt,
23011 			    tcps->tcps_netstack->netstack_ip);
23012 		if (mctl_present)
23013 			ipsec_mp->b_cont = mp;
23014 		else
23015 			ipsec_mp = mp;
23016 		if (err != 0) {
23017 			freemsg(ipsec_mp);
23018 			return;
23019 		}
23020 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23021 			ipha = (ipha_t *)mp->b_rptr;
23022 		} else {
23023 			ip6h = (ip6_t *)mp->b_rptr;
23024 		}
23025 	}
23026 
23027 	if (mctl_present) {
23028 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23029 
23030 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23031 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
23032 			return;
23033 		}
23034 	}
23035 	if (zoneid == ALL_ZONES)
23036 		zoneid = GLOBAL_ZONEID;
23037 
23038 	/* Add the zoneid so ip_output routes it properly */
23039 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
23040 		freemsg(ipsec_mp);
23041 		return;
23042 	}
23043 	ipsec_mp = nmp;
23044 
23045 	/*
23046 	 * NOTE:  one might consider tracing a TCP packet here, but
23047 	 * this function has no active TCP state and no tcp structure
23048 	 * that has a trace buffer.  If we traced here, we would have
23049 	 * to keep a local trace buffer in tcp_record_trace().
23050 	 *
23051 	 * TSol note: The mblk that contains the incoming packet was
23052 	 * reused by tcp_xmit_listener_reset, so it already contains
23053 	 * the right credentials and we don't need to call mblk_setcred.
23054 	 * Also the conn's cred is not right since it is associated
23055 	 * with tcps_g_q.
23056 	 */
23057 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
23058 
23059 	/*
23060 	 * Tell IP to mark the IRE used for this destination temporary.
23061 	 * This way, we can limit our exposure to DoS attack because IP
23062 	 * creates an IRE for each destination.  If there are too many,
23063 	 * the time to do any routing lookup will be extremely long.  And
23064 	 * the lookup can be in interrupt context.
23065 	 *
23066 	 * Note that in normal circumstances, this marking should not
23067 	 * affect anything.  It would be nice if only 1 message is
23068 	 * needed to inform IP that the IRE created for this RST should
23069 	 * not be added to the cache table.  But there is currently
23070 	 * not such communication mechanism between TCP and IP.  So
23071 	 * the best we can do now is to send the advice ioctl to IP
23072 	 * to mark the IRE temporary.
23073 	 */
23074 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
23075 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
23076 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23077 	}
23078 }
23079 
23080 /*
23081  * Initiate closedown sequence on an active connection.  (May be called as
23082  * writer.)  Return value zero for OK return, non-zero for error return.
23083  */
23084 static int
23085 tcp_xmit_end(tcp_t *tcp)
23086 {
23087 	ipic_t	*ipic;
23088 	mblk_t	*mp;
23089 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23090 
23091 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
23092 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
23093 		/*
23094 		 * Invalid state, only states TCPS_SYN_RCVD,
23095 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
23096 		 */
23097 		return (-1);
23098 	}
23099 
23100 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
23101 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
23102 	/*
23103 	 * If there is nothing more unsent, send the FIN now.
23104 	 * Otherwise, it will go out with the last segment.
23105 	 */
23106 	if (tcp->tcp_unsent == 0) {
23107 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
23108 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
23109 
23110 		if (mp) {
23111 			tcp_send_data(tcp, tcp->tcp_wq, mp);
23112 		} else {
23113 			/*
23114 			 * Couldn't allocate msg.  Pretend we got it out.
23115 			 * Wait for rexmit timeout.
23116 			 */
23117 			tcp->tcp_snxt = tcp->tcp_fss + 1;
23118 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23119 		}
23120 
23121 		/*
23122 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23123 		 * changed.
23124 		 */
23125 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23126 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23127 		}
23128 	} else {
23129 		/*
23130 		 * If tcp->tcp_cork is set, then the data will not get sent,
23131 		 * so we have to check that and unset it first.
23132 		 */
23133 		if (tcp->tcp_cork)
23134 			tcp->tcp_cork = B_FALSE;
23135 		tcp_wput_data(tcp, NULL, B_FALSE);
23136 	}
23137 
23138 	/*
23139 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23140 	 * is 0, don't update the cache.
23141 	 */
23142 	if (tcps->tcps_rtt_updates == 0 ||
23143 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23144 		return (0);
23145 
23146 	/*
23147 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23148 	 * different from the destination.
23149 	 */
23150 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23151 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23152 			return (0);
23153 		}
23154 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23155 		    &ipic);
23156 	} else {
23157 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23158 		    &tcp->tcp_ip6h->ip6_dst))) {
23159 			return (0);
23160 		}
23161 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23162 		    &ipic);
23163 	}
23164 
23165 	/* Record route attributes in the IRE for use by future connections. */
23166 	if (mp == NULL)
23167 		return (0);
23168 
23169 	/*
23170 	 * We do not have a good algorithm to update ssthresh at this time.
23171 	 * So don't do any update.
23172 	 */
23173 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23174 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23175 
23176 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23177 
23178 	return (0);
23179 }
23180 
23181 /* ARGSUSED */
23182 void
23183 tcp_xmit_reset(void *arg, mblk_t *mp, void *arg2)
23184 {
23185 	conn_t *connp = (conn_t *)arg;
23186 	mblk_t *mp1;
23187 	tcp_t *tcp = connp->conn_tcp;
23188 	tcp_xmit_reset_event_t *eventp;
23189 
23190 	ASSERT(mp->b_datap->db_type == M_PROTO &&
23191 	    MBLKL(mp) == sizeof (tcp_xmit_reset_event_t));
23192 
23193 	if (tcp->tcp_state != TCPS_LISTEN) {
23194 		freemsg(mp);
23195 		return;
23196 	}
23197 
23198 	mp1 = mp->b_cont;
23199 	mp->b_cont = NULL;
23200 	eventp = (tcp_xmit_reset_event_t *)mp->b_rptr;
23201 	ASSERT(eventp->tcp_xre_tcps->tcps_netstack ==
23202 	    connp->conn_netstack);
23203 
23204 	tcp_xmit_listeners_reset(mp1, eventp->tcp_xre_iphdrlen,
23205 	    eventp->tcp_xre_zoneid, eventp->tcp_xre_tcps, connp);
23206 	freemsg(mp);
23207 }
23208 
23209 /*
23210  * Generate a "no listener here" RST in response to an "unknown" segment.
23211  * connp is set by caller when RST is in response to an unexpected
23212  * inbound packet for which there is active tcp state in the system.
23213  * Note that we are reusing the incoming mp to construct the outgoing RST.
23214  */
23215 void
23216 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23217     tcp_stack_t *tcps, conn_t *connp)
23218 {
23219 	uchar_t		*rptr;
23220 	uint32_t	seg_len;
23221 	tcph_t		*tcph;
23222 	uint32_t	seg_seq;
23223 	uint32_t	seg_ack;
23224 	uint_t		flags;
23225 	mblk_t		*ipsec_mp;
23226 	ipha_t 		*ipha;
23227 	ip6_t 		*ip6h;
23228 	boolean_t	mctl_present = B_FALSE;
23229 	boolean_t	check = B_TRUE;
23230 	boolean_t	policy_present;
23231 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23232 
23233 	TCP_STAT(tcps, tcp_no_listener);
23234 
23235 	ipsec_mp = mp;
23236 
23237 	if (mp->b_datap->db_type == M_CTL) {
23238 		ipsec_in_t *ii;
23239 
23240 		mctl_present = B_TRUE;
23241 		mp = mp->b_cont;
23242 
23243 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23244 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23245 		if (ii->ipsec_in_dont_check) {
23246 			check = B_FALSE;
23247 			if (!ii->ipsec_in_secure) {
23248 				freeb(ipsec_mp);
23249 				mctl_present = B_FALSE;
23250 				ipsec_mp = mp;
23251 			}
23252 		}
23253 	}
23254 
23255 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23256 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23257 		ipha = (ipha_t *)mp->b_rptr;
23258 		ip6h = NULL;
23259 	} else {
23260 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23261 		ipha = NULL;
23262 		ip6h = (ip6_t *)mp->b_rptr;
23263 	}
23264 
23265 	if (check && policy_present) {
23266 		/*
23267 		 * The conn_t parameter is NULL because we already know
23268 		 * nobody's home.
23269 		 */
23270 		ipsec_mp = ipsec_check_global_policy(
23271 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23272 		    tcps->tcps_netstack);
23273 		if (ipsec_mp == NULL)
23274 			return;
23275 	}
23276 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23277 		DTRACE_PROBE2(
23278 		    tx__ip__log__error__nolistener__tcp,
23279 		    char *, "Could not reply with RST to mp(1)",
23280 		    mblk_t *, mp);
23281 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23282 		freemsg(ipsec_mp);
23283 		return;
23284 	}
23285 
23286 	rptr = mp->b_rptr;
23287 
23288 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23289 	seg_seq = BE32_TO_U32(tcph->th_seq);
23290 	seg_ack = BE32_TO_U32(tcph->th_ack);
23291 	flags = tcph->th_flags[0];
23292 
23293 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23294 	if (flags & TH_RST) {
23295 		freemsg(ipsec_mp);
23296 	} else if (flags & TH_ACK) {
23297 		tcp_xmit_early_reset("no tcp, reset",
23298 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23299 		    connp);
23300 	} else {
23301 		if (flags & TH_SYN) {
23302 			seg_len++;
23303 		} else {
23304 			/*
23305 			 * Here we violate the RFC.  Note that a normal
23306 			 * TCP will never send a segment without the ACK
23307 			 * flag, except for RST or SYN segment.  This
23308 			 * segment is neither.  Just drop it on the
23309 			 * floor.
23310 			 */
23311 			freemsg(ipsec_mp);
23312 			tcps->tcps_rst_unsent++;
23313 			return;
23314 		}
23315 
23316 		tcp_xmit_early_reset("no tcp, reset/ack",
23317 		    ipsec_mp, 0, seg_seq + seg_len,
23318 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23319 	}
23320 }
23321 
23322 /*
23323  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23324  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23325  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23326  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23327  * otherwise it will dup partial mblks.)
23328  * Otherwise, an appropriate ACK packet will be generated.  This
23329  * routine is not usually called to send new data for the first time.  It
23330  * is mostly called out of the timer for retransmits, and to generate ACKs.
23331  *
23332  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23333  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23334  * of the original mblk chain will be returned in *offset and *end_mp.
23335  */
23336 mblk_t *
23337 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23338     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23339     boolean_t rexmit)
23340 {
23341 	int	data_length;
23342 	int32_t	off = 0;
23343 	uint_t	flags;
23344 	mblk_t	*mp1;
23345 	mblk_t	*mp2;
23346 	uchar_t	*rptr;
23347 	tcph_t	*tcph;
23348 	int32_t	num_sack_blk = 0;
23349 	int32_t	sack_opt_len = 0;
23350 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23351 
23352 	/* Allocate for our maximum TCP header + link-level */
23353 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23354 	    tcps->tcps_wroff_xtra, BPRI_MED);
23355 	if (!mp1)
23356 		return (NULL);
23357 	data_length = 0;
23358 
23359 	/*
23360 	 * Note that tcp_mss has been adjusted to take into account the
23361 	 * timestamp option if applicable.  Because SACK options do not
23362 	 * appear in every TCP segments and they are of variable lengths,
23363 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23364 	 * the actual segment length when we need to send a segment which
23365 	 * includes SACK options.
23366 	 */
23367 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23368 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23369 		    tcp->tcp_num_sack_blk);
23370 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23371 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23372 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23373 			max_to_send -= sack_opt_len;
23374 	}
23375 
23376 	if (offset != NULL) {
23377 		off = *offset;
23378 		/* We use offset as an indicator that end_mp is not NULL. */
23379 		*end_mp = NULL;
23380 	}
23381 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23382 		/* This could be faster with cooperation from downstream */
23383 		if (mp2 != mp1 && !sendall &&
23384 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23385 		    max_to_send)
23386 			/*
23387 			 * Don't send the next mblk since the whole mblk
23388 			 * does not fit.
23389 			 */
23390 			break;
23391 		mp2->b_cont = dupb(mp);
23392 		mp2 = mp2->b_cont;
23393 		if (!mp2) {
23394 			freemsg(mp1);
23395 			return (NULL);
23396 		}
23397 		mp2->b_rptr += off;
23398 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23399 		    (uintptr_t)INT_MAX);
23400 
23401 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23402 		if (data_length > max_to_send) {
23403 			mp2->b_wptr -= data_length - max_to_send;
23404 			data_length = max_to_send;
23405 			off = mp2->b_wptr - mp->b_rptr;
23406 			break;
23407 		} else {
23408 			off = 0;
23409 		}
23410 	}
23411 	if (offset != NULL) {
23412 		*offset = off;
23413 		*end_mp = mp;
23414 	}
23415 	if (seg_len != NULL) {
23416 		*seg_len = data_length;
23417 	}
23418 
23419 	/* Update the latest receive window size in TCP header. */
23420 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23421 	    tcp->tcp_tcph->th_win);
23422 
23423 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23424 	mp1->b_rptr = rptr;
23425 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23426 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23427 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23428 	U32_TO_ABE32(seq, tcph->th_seq);
23429 
23430 	/*
23431 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23432 	 * that this function was called from tcp_wput_data. Thus, when called
23433 	 * to retransmit data the setting of the PUSH bit may appear some
23434 	 * what random in that it might get set when it should not. This
23435 	 * should not pose any performance issues.
23436 	 */
23437 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23438 	    tcp->tcp_unsent == data_length)) {
23439 		flags = TH_ACK | TH_PUSH;
23440 	} else {
23441 		flags = TH_ACK;
23442 	}
23443 
23444 	if (tcp->tcp_ecn_ok) {
23445 		if (tcp->tcp_ecn_echo_on)
23446 			flags |= TH_ECE;
23447 
23448 		/*
23449 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23450 		 * There is no TCP flow control for non-data segments, and
23451 		 * only data segment is transmitted reliably.
23452 		 */
23453 		if (data_length > 0 && !rexmit) {
23454 			SET_ECT(tcp, rptr);
23455 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23456 				flags |= TH_CWR;
23457 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23458 			}
23459 		}
23460 	}
23461 
23462 	if (tcp->tcp_valid_bits) {
23463 		uint32_t u1;
23464 
23465 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23466 		    seq == tcp->tcp_iss) {
23467 			uchar_t	*wptr;
23468 
23469 			/*
23470 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23471 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23472 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23473 			 * our SYN is not ack'ed but the app closes this
23474 			 * TCP connection.
23475 			 */
23476 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23477 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23478 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23479 
23480 			/*
23481 			 * Tack on the MSS option.  It is always needed
23482 			 * for both active and passive open.
23483 			 *
23484 			 * MSS option value should be interface MTU - MIN
23485 			 * TCP/IP header according to RFC 793 as it means
23486 			 * the maximum segment size TCP can receive.  But
23487 			 * to get around some broken middle boxes/end hosts
23488 			 * out there, we allow the option value to be the
23489 			 * same as the MSS option size on the peer side.
23490 			 * In this way, the other side will not send
23491 			 * anything larger than they can receive.
23492 			 *
23493 			 * Note that for SYN_SENT state, the ndd param
23494 			 * tcp_use_smss_as_mss_opt has no effect as we
23495 			 * don't know the peer's MSS option value. So
23496 			 * the only case we need to take care of is in
23497 			 * SYN_RCVD state, which is done later.
23498 			 */
23499 			wptr = mp1->b_wptr;
23500 			wptr[0] = TCPOPT_MAXSEG;
23501 			wptr[1] = TCPOPT_MAXSEG_LEN;
23502 			wptr += 2;
23503 			u1 = tcp->tcp_if_mtu -
23504 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23505 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23506 			    TCP_MIN_HEADER_LENGTH;
23507 			U16_TO_BE16(u1, wptr);
23508 			mp1->b_wptr = wptr + 2;
23509 			/* Update the offset to cover the additional word */
23510 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23511 
23512 			/*
23513 			 * Note that the following way of filling in
23514 			 * TCP options are not optimal.  Some NOPs can
23515 			 * be saved.  But there is no need at this time
23516 			 * to optimize it.  When it is needed, we will
23517 			 * do it.
23518 			 */
23519 			switch (tcp->tcp_state) {
23520 			case TCPS_SYN_SENT:
23521 				flags = TH_SYN;
23522 
23523 				if (tcp->tcp_snd_ts_ok) {
23524 					uint32_t llbolt = (uint32_t)lbolt;
23525 
23526 					wptr = mp1->b_wptr;
23527 					wptr[0] = TCPOPT_NOP;
23528 					wptr[1] = TCPOPT_NOP;
23529 					wptr[2] = TCPOPT_TSTAMP;
23530 					wptr[3] = TCPOPT_TSTAMP_LEN;
23531 					wptr += 4;
23532 					U32_TO_BE32(llbolt, wptr);
23533 					wptr += 4;
23534 					ASSERT(tcp->tcp_ts_recent == 0);
23535 					U32_TO_BE32(0L, wptr);
23536 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23537 					tcph->th_offset_and_rsrvd[0] +=
23538 					    (3 << 4);
23539 				}
23540 
23541 				/*
23542 				 * Set up all the bits to tell other side
23543 				 * we are ECN capable.
23544 				 */
23545 				if (tcp->tcp_ecn_ok) {
23546 					flags |= (TH_ECE | TH_CWR);
23547 				}
23548 				break;
23549 			case TCPS_SYN_RCVD:
23550 				flags |= TH_SYN;
23551 
23552 				/*
23553 				 * Reset the MSS option value to be SMSS
23554 				 * We should probably add back the bytes
23555 				 * for timestamp option and IPsec.  We
23556 				 * don't do that as this is a workaround
23557 				 * for broken middle boxes/end hosts, it
23558 				 * is better for us to be more cautious.
23559 				 * They may not take these things into
23560 				 * account in their SMSS calculation.  Thus
23561 				 * the peer's calculated SMSS may be smaller
23562 				 * than what it can be.  This should be OK.
23563 				 */
23564 				if (tcps->tcps_use_smss_as_mss_opt) {
23565 					u1 = tcp->tcp_mss;
23566 					U16_TO_BE16(u1, wptr);
23567 				}
23568 
23569 				/*
23570 				 * If the other side is ECN capable, reply
23571 				 * that we are also ECN capable.
23572 				 */
23573 				if (tcp->tcp_ecn_ok)
23574 					flags |= TH_ECE;
23575 				break;
23576 			default:
23577 				/*
23578 				 * The above ASSERT() makes sure that this
23579 				 * must be FIN-WAIT-1 state.  Our SYN has
23580 				 * not been ack'ed so retransmit it.
23581 				 */
23582 				flags |= TH_SYN;
23583 				break;
23584 			}
23585 
23586 			if (tcp->tcp_snd_ws_ok) {
23587 				wptr = mp1->b_wptr;
23588 				wptr[0] =  TCPOPT_NOP;
23589 				wptr[1] =  TCPOPT_WSCALE;
23590 				wptr[2] =  TCPOPT_WS_LEN;
23591 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23592 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23593 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23594 			}
23595 
23596 			if (tcp->tcp_snd_sack_ok) {
23597 				wptr = mp1->b_wptr;
23598 				wptr[0] = TCPOPT_NOP;
23599 				wptr[1] = TCPOPT_NOP;
23600 				wptr[2] = TCPOPT_SACK_PERMITTED;
23601 				wptr[3] = TCPOPT_SACK_OK_LEN;
23602 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23603 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23604 			}
23605 
23606 			/* allocb() of adequate mblk assures space */
23607 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23608 			    (uintptr_t)INT_MAX);
23609 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23610 			/*
23611 			 * Get IP set to checksum on our behalf
23612 			 * Include the adjustment for a source route if any.
23613 			 */
23614 			u1 += tcp->tcp_sum;
23615 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23616 			U16_TO_BE16(u1, tcph->th_sum);
23617 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23618 		}
23619 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23620 		    (seq + data_length) == tcp->tcp_fss) {
23621 			if (!tcp->tcp_fin_acked) {
23622 				flags |= TH_FIN;
23623 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23624 			}
23625 			if (!tcp->tcp_fin_sent) {
23626 				tcp->tcp_fin_sent = B_TRUE;
23627 				switch (tcp->tcp_state) {
23628 				case TCPS_SYN_RCVD:
23629 				case TCPS_ESTABLISHED:
23630 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23631 					break;
23632 				case TCPS_CLOSE_WAIT:
23633 					tcp->tcp_state = TCPS_LAST_ACK;
23634 					break;
23635 				}
23636 				if (tcp->tcp_suna == tcp->tcp_snxt)
23637 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23638 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23639 			}
23640 		}
23641 		/*
23642 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23643 		 * is smaller than seq, u1 will become a very huge value.
23644 		 * So the comparison will fail.  Also note that tcp_urp
23645 		 * should be positive, see RFC 793 page 17.
23646 		 */
23647 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23648 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23649 		    u1 < (uint32_t)(64 * 1024)) {
23650 			flags |= TH_URG;
23651 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23652 			U32_TO_ABE16(u1, tcph->th_urp);
23653 		}
23654 	}
23655 	tcph->th_flags[0] = (uchar_t)flags;
23656 	tcp->tcp_rack = tcp->tcp_rnxt;
23657 	tcp->tcp_rack_cnt = 0;
23658 
23659 	if (tcp->tcp_snd_ts_ok) {
23660 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23661 			uint32_t llbolt = (uint32_t)lbolt;
23662 
23663 			U32_TO_BE32(llbolt,
23664 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23665 			U32_TO_BE32(tcp->tcp_ts_recent,
23666 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23667 		}
23668 	}
23669 
23670 	if (num_sack_blk > 0) {
23671 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23672 		sack_blk_t *tmp;
23673 		int32_t	i;
23674 
23675 		wptr[0] = TCPOPT_NOP;
23676 		wptr[1] = TCPOPT_NOP;
23677 		wptr[2] = TCPOPT_SACK;
23678 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23679 		    sizeof (sack_blk_t);
23680 		wptr += TCPOPT_REAL_SACK_LEN;
23681 
23682 		tmp = tcp->tcp_sack_list;
23683 		for (i = 0; i < num_sack_blk; i++) {
23684 			U32_TO_BE32(tmp[i].begin, wptr);
23685 			wptr += sizeof (tcp_seq);
23686 			U32_TO_BE32(tmp[i].end, wptr);
23687 			wptr += sizeof (tcp_seq);
23688 		}
23689 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23690 	}
23691 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23692 	data_length += (int)(mp1->b_wptr - rptr);
23693 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23694 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23695 	} else {
23696 		ip6_t *ip6 = (ip6_t *)(rptr +
23697 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23698 		    sizeof (ip6i_t) : 0));
23699 
23700 		ip6->ip6_plen = htons(data_length -
23701 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23702 	}
23703 
23704 	/*
23705 	 * Prime pump for IP
23706 	 * Include the adjustment for a source route if any.
23707 	 */
23708 	data_length -= tcp->tcp_ip_hdr_len;
23709 	data_length += tcp->tcp_sum;
23710 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23711 	U16_TO_ABE16(data_length, tcph->th_sum);
23712 	if (tcp->tcp_ip_forward_progress) {
23713 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23714 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23715 		tcp->tcp_ip_forward_progress = B_FALSE;
23716 	}
23717 	return (mp1);
23718 }
23719 
23720 /* This function handles the push timeout. */
23721 void
23722 tcp_push_timer(void *arg)
23723 {
23724 	conn_t	*connp = (conn_t *)arg;
23725 	tcp_t *tcp = connp->conn_tcp;
23726 	uint_t		flags;
23727 	sodirect_t	*sodp;
23728 
23729 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
23730 
23731 	ASSERT(tcp->tcp_listener == NULL);
23732 
23733 	ASSERT(!IPCL_IS_NONSTR(connp));
23734 
23735 	/*
23736 	 * We need to plug synchronous streams during our drain to prevent
23737 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23738 	 */
23739 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23740 	tcp->tcp_push_tid = 0;
23741 
23742 	SOD_PTR_ENTER(tcp, sodp);
23743 	if (sodp != NULL) {
23744 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23745 		/* sod_wakeup() does the mutex_exit() */
23746 	} else if (tcp->tcp_rcv_list != NULL) {
23747 		flags = tcp_rcv_drain(tcp);
23748 	}
23749 	if (flags == TH_ACK_NEEDED)
23750 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23751 
23752 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23753 }
23754 
23755 /*
23756  * This function handles delayed ACK timeout.
23757  */
23758 static void
23759 tcp_ack_timer(void *arg)
23760 {
23761 	conn_t	*connp = (conn_t *)arg;
23762 	tcp_t *tcp = connp->conn_tcp;
23763 	mblk_t *mp;
23764 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23765 
23766 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23767 
23768 	tcp->tcp_ack_tid = 0;
23769 
23770 	if (tcp->tcp_fused)
23771 		return;
23772 
23773 	/*
23774 	 * Do not send ACK if there is no outstanding unack'ed data.
23775 	 */
23776 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23777 		return;
23778 	}
23779 
23780 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23781 		/*
23782 		 * Make sure we don't allow deferred ACKs to result in
23783 		 * timer-based ACKing.  If we have held off an ACK
23784 		 * when there was more than an mss here, and the timer
23785 		 * goes off, we have to worry about the possibility
23786 		 * that the sender isn't doing slow-start, or is out
23787 		 * of step with us for some other reason.  We fall
23788 		 * permanently back in the direction of
23789 		 * ACK-every-other-packet as suggested in RFC 1122.
23790 		 */
23791 		if (tcp->tcp_rack_abs_max > 2)
23792 			tcp->tcp_rack_abs_max--;
23793 		tcp->tcp_rack_cur_max = 2;
23794 	}
23795 	mp = tcp_ack_mp(tcp);
23796 
23797 	if (mp != NULL) {
23798 		BUMP_LOCAL(tcp->tcp_obsegs);
23799 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23800 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23801 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23802 	}
23803 }
23804 
23805 
23806 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23807 static mblk_t *
23808 tcp_ack_mp(tcp_t *tcp)
23809 {
23810 	uint32_t	seq_no;
23811 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23812 
23813 	/*
23814 	 * There are a few cases to be considered while setting the sequence no.
23815 	 * Essentially, we can come here while processing an unacceptable pkt
23816 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23817 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23818 	 * If we are here for a zero window probe, stick with suna. In all
23819 	 * other cases, we check if suna + swnd encompasses snxt and set
23820 	 * the sequence number to snxt, if so. If snxt falls outside the
23821 	 * window (the receiver probably shrunk its window), we will go with
23822 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23823 	 * receiver.
23824 	 */
23825 	if (tcp->tcp_zero_win_probe) {
23826 		seq_no = tcp->tcp_suna;
23827 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23828 		ASSERT(tcp->tcp_swnd == 0);
23829 		seq_no = tcp->tcp_snxt;
23830 	} else {
23831 		seq_no = SEQ_GT(tcp->tcp_snxt,
23832 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23833 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23834 	}
23835 
23836 	if (tcp->tcp_valid_bits) {
23837 		/*
23838 		 * For the complex case where we have to send some
23839 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23840 		 */
23841 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23842 		    NULL, B_FALSE));
23843 	} else {
23844 		/* Generate a simple ACK */
23845 		int	data_length;
23846 		uchar_t	*rptr;
23847 		tcph_t	*tcph;
23848 		mblk_t	*mp1;
23849 		int32_t	tcp_hdr_len;
23850 		int32_t	tcp_tcp_hdr_len;
23851 		int32_t	num_sack_blk = 0;
23852 		int32_t sack_opt_len;
23853 
23854 		/*
23855 		 * Allocate space for TCP + IP headers
23856 		 * and link-level header
23857 		 */
23858 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23859 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23860 			    tcp->tcp_num_sack_blk);
23861 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23862 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23863 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23864 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23865 		} else {
23866 			tcp_hdr_len = tcp->tcp_hdr_len;
23867 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23868 		}
23869 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23870 		if (!mp1)
23871 			return (NULL);
23872 
23873 		/* Update the latest receive window size in TCP header. */
23874 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23875 		    tcp->tcp_tcph->th_win);
23876 		/* copy in prototype TCP + IP header */
23877 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23878 		mp1->b_rptr = rptr;
23879 		mp1->b_wptr = rptr + tcp_hdr_len;
23880 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23881 
23882 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23883 
23884 		/* Set the TCP sequence number. */
23885 		U32_TO_ABE32(seq_no, tcph->th_seq);
23886 
23887 		/* Set up the TCP flag field. */
23888 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23889 		if (tcp->tcp_ecn_echo_on)
23890 			tcph->th_flags[0] |= TH_ECE;
23891 
23892 		tcp->tcp_rack = tcp->tcp_rnxt;
23893 		tcp->tcp_rack_cnt = 0;
23894 
23895 		/* fill in timestamp option if in use */
23896 		if (tcp->tcp_snd_ts_ok) {
23897 			uint32_t llbolt = (uint32_t)lbolt;
23898 
23899 			U32_TO_BE32(llbolt,
23900 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23901 			U32_TO_BE32(tcp->tcp_ts_recent,
23902 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23903 		}
23904 
23905 		/* Fill in SACK options */
23906 		if (num_sack_blk > 0) {
23907 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23908 			sack_blk_t *tmp;
23909 			int32_t	i;
23910 
23911 			wptr[0] = TCPOPT_NOP;
23912 			wptr[1] = TCPOPT_NOP;
23913 			wptr[2] = TCPOPT_SACK;
23914 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23915 			    sizeof (sack_blk_t);
23916 			wptr += TCPOPT_REAL_SACK_LEN;
23917 
23918 			tmp = tcp->tcp_sack_list;
23919 			for (i = 0; i < num_sack_blk; i++) {
23920 				U32_TO_BE32(tmp[i].begin, wptr);
23921 				wptr += sizeof (tcp_seq);
23922 				U32_TO_BE32(tmp[i].end, wptr);
23923 				wptr += sizeof (tcp_seq);
23924 			}
23925 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23926 			    << 4);
23927 		}
23928 
23929 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23930 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23931 		} else {
23932 			/* Check for ip6i_t header in sticky hdrs */
23933 			ip6_t *ip6 = (ip6_t *)(rptr +
23934 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23935 			    sizeof (ip6i_t) : 0));
23936 
23937 			ip6->ip6_plen = htons(tcp_hdr_len -
23938 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23939 		}
23940 
23941 		/*
23942 		 * Prime pump for checksum calculation in IP.  Include the
23943 		 * adjustment for a source route if any.
23944 		 */
23945 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23946 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23947 		U16_TO_ABE16(data_length, tcph->th_sum);
23948 
23949 		if (tcp->tcp_ip_forward_progress) {
23950 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23951 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23952 			tcp->tcp_ip_forward_progress = B_FALSE;
23953 		}
23954 		return (mp1);
23955 	}
23956 }
23957 
23958 /*
23959  * Hash list insertion routine for tcp_t structures. Each hash bucket
23960  * contains a list of tcp_t entries, and each entry is bound to a unique
23961  * port. If there are multiple tcp_t's that are bound to the same port, then
23962  * one of them will be linked into the hash bucket list, and the rest will
23963  * hang off of that one entry. For each port, entries bound to a specific IP
23964  * address will be inserted before those those bound to INADDR_ANY.
23965  */
23966 static void
23967 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
23968 {
23969 	tcp_t	**tcpp;
23970 	tcp_t	*tcpnext;
23971 	tcp_t	*tcphash;
23972 
23973 	if (tcp->tcp_ptpbhn != NULL) {
23974 		ASSERT(!caller_holds_lock);
23975 		tcp_bind_hash_remove(tcp);
23976 	}
23977 	tcpp = &tbf->tf_tcp;
23978 	if (!caller_holds_lock) {
23979 		mutex_enter(&tbf->tf_lock);
23980 	} else {
23981 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
23982 	}
23983 	tcphash = tcpp[0];
23984 	tcpnext = NULL;
23985 	if (tcphash != NULL) {
23986 		/* Look for an entry using the same port */
23987 		while ((tcphash = tcpp[0]) != NULL &&
23988 		    tcp->tcp_lport != tcphash->tcp_lport)
23989 			tcpp = &(tcphash->tcp_bind_hash);
23990 
23991 		/* The port was not found, just add to the end */
23992 		if (tcphash == NULL)
23993 			goto insert;
23994 
23995 		/*
23996 		 * OK, there already exists an entry bound to the
23997 		 * same port.
23998 		 *
23999 		 * If the new tcp bound to the INADDR_ANY address
24000 		 * and the first one in the list is not bound to
24001 		 * INADDR_ANY we skip all entries until we find the
24002 		 * first one bound to INADDR_ANY.
24003 		 * This makes sure that applications binding to a
24004 		 * specific address get preference over those binding to
24005 		 * INADDR_ANY.
24006 		 */
24007 		tcpnext = tcphash;
24008 		tcphash = NULL;
24009 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
24010 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
24011 			while ((tcpnext = tcpp[0]) != NULL &&
24012 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
24013 				tcpp = &(tcpnext->tcp_bind_hash_port);
24014 
24015 			if (tcpnext) {
24016 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
24017 				tcphash = tcpnext->tcp_bind_hash;
24018 				if (tcphash != NULL) {
24019 					tcphash->tcp_ptpbhn =
24020 					    &(tcp->tcp_bind_hash);
24021 					tcpnext->tcp_bind_hash = NULL;
24022 				}
24023 			}
24024 		} else {
24025 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash_port;
24026 			tcphash = tcpnext->tcp_bind_hash;
24027 			if (tcphash != NULL) {
24028 				tcphash->tcp_ptpbhn =
24029 				    &(tcp->tcp_bind_hash);
24030 				tcpnext->tcp_bind_hash = NULL;
24031 			}
24032 		}
24033 	}
24034 insert:
24035 	tcp->tcp_bind_hash_port = tcpnext;
24036 	tcp->tcp_bind_hash = tcphash;
24037 	tcp->tcp_ptpbhn = tcpp;
24038 	tcpp[0] = tcp;
24039 	if (!caller_holds_lock)
24040 		mutex_exit(&tbf->tf_lock);
24041 }
24042 
24043 /*
24044  * Hash list removal routine for tcp_t structures.
24045  */
24046 static void
24047 tcp_bind_hash_remove(tcp_t *tcp)
24048 {
24049 	tcp_t	*tcpnext;
24050 	kmutex_t *lockp;
24051 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24052 
24053 	if (tcp->tcp_ptpbhn == NULL)
24054 		return;
24055 
24056 	/*
24057 	 * Extract the lock pointer in case there are concurrent
24058 	 * hash_remove's for this instance.
24059 	 */
24060 	ASSERT(tcp->tcp_lport != 0);
24061 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
24062 
24063 	ASSERT(lockp != NULL);
24064 	mutex_enter(lockp);
24065 	if (tcp->tcp_ptpbhn) {
24066 		tcpnext = tcp->tcp_bind_hash_port;
24067 		if (tcpnext != NULL) {
24068 			tcp->tcp_bind_hash_port = NULL;
24069 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24070 			tcpnext->tcp_bind_hash = tcp->tcp_bind_hash;
24071 			if (tcpnext->tcp_bind_hash != NULL) {
24072 				tcpnext->tcp_bind_hash->tcp_ptpbhn =
24073 				    &(tcpnext->tcp_bind_hash);
24074 				tcp->tcp_bind_hash = NULL;
24075 			}
24076 		} else if ((tcpnext = tcp->tcp_bind_hash) != NULL) {
24077 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24078 			tcp->tcp_bind_hash = NULL;
24079 		}
24080 		*tcp->tcp_ptpbhn = tcpnext;
24081 		tcp->tcp_ptpbhn = NULL;
24082 	}
24083 	mutex_exit(lockp);
24084 }
24085 
24086 
24087 /*
24088  * Hash list lookup routine for tcp_t structures.
24089  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24090  */
24091 static tcp_t *
24092 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24093 {
24094 	tf_t	*tf;
24095 	tcp_t	*tcp;
24096 
24097 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24098 	mutex_enter(&tf->tf_lock);
24099 	for (tcp = tf->tf_tcp; tcp != NULL;
24100 	    tcp = tcp->tcp_acceptor_hash) {
24101 		if (tcp->tcp_acceptor_id == id) {
24102 			CONN_INC_REF(tcp->tcp_connp);
24103 			mutex_exit(&tf->tf_lock);
24104 			return (tcp);
24105 		}
24106 	}
24107 	mutex_exit(&tf->tf_lock);
24108 	return (NULL);
24109 }
24110 
24111 
24112 /*
24113  * Hash list insertion routine for tcp_t structures.
24114  */
24115 void
24116 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24117 {
24118 	tf_t	*tf;
24119 	tcp_t	**tcpp;
24120 	tcp_t	*tcpnext;
24121 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24122 
24123 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24124 
24125 	if (tcp->tcp_ptpahn != NULL)
24126 		tcp_acceptor_hash_remove(tcp);
24127 	tcpp = &tf->tf_tcp;
24128 	mutex_enter(&tf->tf_lock);
24129 	tcpnext = tcpp[0];
24130 	if (tcpnext)
24131 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24132 	tcp->tcp_acceptor_hash = tcpnext;
24133 	tcp->tcp_ptpahn = tcpp;
24134 	tcpp[0] = tcp;
24135 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24136 	mutex_exit(&tf->tf_lock);
24137 }
24138 
24139 /*
24140  * Hash list removal routine for tcp_t structures.
24141  */
24142 static void
24143 tcp_acceptor_hash_remove(tcp_t *tcp)
24144 {
24145 	tcp_t	*tcpnext;
24146 	kmutex_t *lockp;
24147 
24148 	/*
24149 	 * Extract the lock pointer in case there are concurrent
24150 	 * hash_remove's for this instance.
24151 	 */
24152 	lockp = tcp->tcp_acceptor_lockp;
24153 
24154 	if (tcp->tcp_ptpahn == NULL)
24155 		return;
24156 
24157 	ASSERT(lockp != NULL);
24158 	mutex_enter(lockp);
24159 	if (tcp->tcp_ptpahn) {
24160 		tcpnext = tcp->tcp_acceptor_hash;
24161 		if (tcpnext) {
24162 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24163 			tcp->tcp_acceptor_hash = NULL;
24164 		}
24165 		*tcp->tcp_ptpahn = tcpnext;
24166 		tcp->tcp_ptpahn = NULL;
24167 	}
24168 	mutex_exit(lockp);
24169 	tcp->tcp_acceptor_lockp = NULL;
24170 }
24171 
24172 /* Data for fast netmask macro used by tcp_hsp_lookup */
24173 
24174 static ipaddr_t netmasks[] = {
24175 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24176 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24177 };
24178 
24179 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24180 
24181 /*
24182  * XXX This routine should go away and instead we should use the metrics
24183  * associated with the routes to determine the default sndspace and rcvspace.
24184  */
24185 static tcp_hsp_t *
24186 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24187 {
24188 	tcp_hsp_t *hsp = NULL;
24189 
24190 	/* Quick check without acquiring the lock. */
24191 	if (tcps->tcps_hsp_hash == NULL)
24192 		return (NULL);
24193 
24194 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24195 
24196 	/* This routine finds the best-matching HSP for address addr. */
24197 
24198 	if (tcps->tcps_hsp_hash) {
24199 		int i;
24200 		ipaddr_t srchaddr;
24201 		tcp_hsp_t *hsp_net;
24202 
24203 		/* We do three passes: host, network, and subnet. */
24204 
24205 		srchaddr = addr;
24206 
24207 		for (i = 1; i <= 3; i++) {
24208 			/* Look for exact match on srchaddr */
24209 
24210 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24211 			while (hsp) {
24212 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24213 				    hsp->tcp_hsp_addr == srchaddr)
24214 					break;
24215 				hsp = hsp->tcp_hsp_next;
24216 			}
24217 			ASSERT(hsp == NULL ||
24218 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24219 
24220 			/*
24221 			 * If this is the first pass:
24222 			 *   If we found a match, great, return it.
24223 			 *   If not, search for the network on the second pass.
24224 			 */
24225 
24226 			if (i == 1)
24227 				if (hsp)
24228 					break;
24229 				else
24230 				{
24231 					srchaddr = addr & netmask(addr);
24232 					continue;
24233 				}
24234 
24235 			/*
24236 			 * If this is the second pass:
24237 			 *   If we found a match, but there's a subnet mask,
24238 			 *    save the match but try again using the subnet
24239 			 *    mask on the third pass.
24240 			 *   Otherwise, return whatever we found.
24241 			 */
24242 
24243 			if (i == 2) {
24244 				if (hsp && hsp->tcp_hsp_subnet) {
24245 					hsp_net = hsp;
24246 					srchaddr = addr & hsp->tcp_hsp_subnet;
24247 					continue;
24248 				} else {
24249 					break;
24250 				}
24251 			}
24252 
24253 			/*
24254 			 * This must be the third pass.  If we didn't find
24255 			 * anything, return the saved network HSP instead.
24256 			 */
24257 
24258 			if (!hsp)
24259 				hsp = hsp_net;
24260 		}
24261 	}
24262 
24263 	rw_exit(&tcps->tcps_hsp_lock);
24264 	return (hsp);
24265 }
24266 
24267 /*
24268  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24269  * match lookup.
24270  */
24271 static tcp_hsp_t *
24272 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24273 {
24274 	tcp_hsp_t *hsp = NULL;
24275 
24276 	/* Quick check without acquiring the lock. */
24277 	if (tcps->tcps_hsp_hash == NULL)
24278 		return (NULL);
24279 
24280 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24281 
24282 	/* This routine finds the best-matching HSP for address addr. */
24283 
24284 	if (tcps->tcps_hsp_hash) {
24285 		int i;
24286 		in6_addr_t v6srchaddr;
24287 		tcp_hsp_t *hsp_net;
24288 
24289 		/* We do three passes: host, network, and subnet. */
24290 
24291 		v6srchaddr = *v6addr;
24292 
24293 		for (i = 1; i <= 3; i++) {
24294 			/* Look for exact match on srchaddr */
24295 
24296 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24297 			    V4_PART_OF_V6(v6srchaddr))];
24298 			while (hsp) {
24299 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24300 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24301 				    &v6srchaddr))
24302 					break;
24303 				hsp = hsp->tcp_hsp_next;
24304 			}
24305 
24306 			/*
24307 			 * If this is the first pass:
24308 			 *   If we found a match, great, return it.
24309 			 *   If not, search for the network on the second pass.
24310 			 */
24311 
24312 			if (i == 1)
24313 				if (hsp)
24314 					break;
24315 				else {
24316 					/* Assume a 64 bit mask */
24317 					v6srchaddr.s6_addr32[0] =
24318 					    v6addr->s6_addr32[0];
24319 					v6srchaddr.s6_addr32[1] =
24320 					    v6addr->s6_addr32[1];
24321 					v6srchaddr.s6_addr32[2] = 0;
24322 					v6srchaddr.s6_addr32[3] = 0;
24323 					continue;
24324 				}
24325 
24326 			/*
24327 			 * If this is the second pass:
24328 			 *   If we found a match, but there's a subnet mask,
24329 			 *    save the match but try again using the subnet
24330 			 *    mask on the third pass.
24331 			 *   Otherwise, return whatever we found.
24332 			 */
24333 
24334 			if (i == 2) {
24335 				ASSERT(hsp == NULL ||
24336 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24337 				if (hsp &&
24338 				    !IN6_IS_ADDR_UNSPECIFIED(
24339 				    &hsp->tcp_hsp_subnet_v6)) {
24340 					hsp_net = hsp;
24341 					V6_MASK_COPY(*v6addr,
24342 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24343 					continue;
24344 				} else {
24345 					break;
24346 				}
24347 			}
24348 
24349 			/*
24350 			 * This must be the third pass.  If we didn't find
24351 			 * anything, return the saved network HSP instead.
24352 			 */
24353 
24354 			if (!hsp)
24355 				hsp = hsp_net;
24356 		}
24357 	}
24358 
24359 	rw_exit(&tcps->tcps_hsp_lock);
24360 	return (hsp);
24361 }
24362 
24363 /*
24364  * Type three generator adapted from the random() function in 4.4 BSD:
24365  */
24366 
24367 /*
24368  * Copyright (c) 1983, 1993
24369  *	The Regents of the University of California.  All rights reserved.
24370  *
24371  * Redistribution and use in source and binary forms, with or without
24372  * modification, are permitted provided that the following conditions
24373  * are met:
24374  * 1. Redistributions of source code must retain the above copyright
24375  *    notice, this list of conditions and the following disclaimer.
24376  * 2. Redistributions in binary form must reproduce the above copyright
24377  *    notice, this list of conditions and the following disclaimer in the
24378  *    documentation and/or other materials provided with the distribution.
24379  * 3. All advertising materials mentioning features or use of this software
24380  *    must display the following acknowledgement:
24381  *	This product includes software developed by the University of
24382  *	California, Berkeley and its contributors.
24383  * 4. Neither the name of the University nor the names of its contributors
24384  *    may be used to endorse or promote products derived from this software
24385  *    without specific prior written permission.
24386  *
24387  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24388  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24389  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24390  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24391  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24392  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24393  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24394  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24395  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24396  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24397  * SUCH DAMAGE.
24398  */
24399 
24400 /* Type 3 -- x**31 + x**3 + 1 */
24401 #define	DEG_3		31
24402 #define	SEP_3		3
24403 
24404 
24405 /* Protected by tcp_random_lock */
24406 static int tcp_randtbl[DEG_3 + 1];
24407 
24408 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24409 static int *tcp_random_rptr = &tcp_randtbl[1];
24410 
24411 static int *tcp_random_state = &tcp_randtbl[1];
24412 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24413 
24414 kmutex_t tcp_random_lock;
24415 
24416 void
24417 tcp_random_init(void)
24418 {
24419 	int i;
24420 	hrtime_t hrt;
24421 	time_t wallclock;
24422 	uint64_t result;
24423 
24424 	/*
24425 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24426 	 * a longlong, which may contain resolution down to nanoseconds.
24427 	 * The current time will either be a 32-bit or a 64-bit quantity.
24428 	 * XOR the two together in a 64-bit result variable.
24429 	 * Convert the result to a 32-bit value by multiplying the high-order
24430 	 * 32-bits by the low-order 32-bits.
24431 	 */
24432 
24433 	hrt = gethrtime();
24434 	(void) drv_getparm(TIME, &wallclock);
24435 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24436 	mutex_enter(&tcp_random_lock);
24437 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24438 	    (result & 0xffffffff);
24439 
24440 	for (i = 1; i < DEG_3; i++)
24441 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24442 		    + 12345;
24443 	tcp_random_fptr = &tcp_random_state[SEP_3];
24444 	tcp_random_rptr = &tcp_random_state[0];
24445 	mutex_exit(&tcp_random_lock);
24446 	for (i = 0; i < 10 * DEG_3; i++)
24447 		(void) tcp_random();
24448 }
24449 
24450 /*
24451  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24452  * This range is selected to be approximately centered on TCP_ISS / 2,
24453  * and easy to compute. We get this value by generating a 32-bit random
24454  * number, selecting out the high-order 17 bits, and then adding one so
24455  * that we never return zero.
24456  */
24457 int
24458 tcp_random(void)
24459 {
24460 	int i;
24461 
24462 	mutex_enter(&tcp_random_lock);
24463 	*tcp_random_fptr += *tcp_random_rptr;
24464 
24465 	/*
24466 	 * The high-order bits are more random than the low-order bits,
24467 	 * so we select out the high-order 17 bits and add one so that
24468 	 * we never return zero.
24469 	 */
24470 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24471 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24472 		tcp_random_fptr = tcp_random_state;
24473 		++tcp_random_rptr;
24474 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24475 		tcp_random_rptr = tcp_random_state;
24476 
24477 	mutex_exit(&tcp_random_lock);
24478 	return (i);
24479 }
24480 
24481 static int
24482 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24483     int *t_errorp, int *sys_errorp)
24484 {
24485 	int error;
24486 	int is_absreq_failure;
24487 	t_scalar_t *opt_lenp;
24488 	t_scalar_t opt_offset;
24489 	int prim_type;
24490 	struct T_conn_req *tcreqp;
24491 	struct T_conn_res *tcresp;
24492 	cred_t *cr;
24493 
24494 	/*
24495 	 * All Solaris components should pass a db_credp
24496 	 * for this TPI message, hence we ASSERT.
24497 	 * But in case there is some other M_PROTO that looks
24498 	 * like a TPI message sent by some other kernel
24499 	 * component, we check and return an error.
24500 	 */
24501 	cr = msg_getcred(mp, NULL);
24502 	ASSERT(cr != NULL);
24503 	if (cr == NULL)
24504 		return (-1);
24505 
24506 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24507 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24508 	    prim_type == T_CONN_RES);
24509 
24510 	switch (prim_type) {
24511 	case T_CONN_REQ:
24512 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24513 		opt_offset = tcreqp->OPT_offset;
24514 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24515 		break;
24516 	case O_T_CONN_RES:
24517 	case T_CONN_RES:
24518 		tcresp = (struct T_conn_res *)mp->b_rptr;
24519 		opt_offset = tcresp->OPT_offset;
24520 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24521 		break;
24522 	}
24523 
24524 	*t_errorp = 0;
24525 	*sys_errorp = 0;
24526 	*do_disconnectp = 0;
24527 
24528 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24529 	    opt_offset, cr, &tcp_opt_obj,
24530 	    NULL, &is_absreq_failure);
24531 
24532 	switch (error) {
24533 	case  0:		/* no error */
24534 		ASSERT(is_absreq_failure == 0);
24535 		return (0);
24536 	case ENOPROTOOPT:
24537 		*t_errorp = TBADOPT;
24538 		break;
24539 	case EACCES:
24540 		*t_errorp = TACCES;
24541 		break;
24542 	default:
24543 		*t_errorp = TSYSERR; *sys_errorp = error;
24544 		break;
24545 	}
24546 	if (is_absreq_failure != 0) {
24547 		/*
24548 		 * The connection request should get the local ack
24549 		 * T_OK_ACK and then a T_DISCON_IND.
24550 		 */
24551 		*do_disconnectp = 1;
24552 	}
24553 	return (-1);
24554 }
24555 
24556 /*
24557  * Split this function out so that if the secret changes, I'm okay.
24558  *
24559  * Initialize the tcp_iss_cookie and tcp_iss_key.
24560  */
24561 
24562 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24563 
24564 static void
24565 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24566 {
24567 	struct {
24568 		int32_t current_time;
24569 		uint32_t randnum;
24570 		uint16_t pad;
24571 		uint8_t ether[6];
24572 		uint8_t passwd[PASSWD_SIZE];
24573 	} tcp_iss_cookie;
24574 	time_t t;
24575 
24576 	/*
24577 	 * Start with the current absolute time.
24578 	 */
24579 	(void) drv_getparm(TIME, &t);
24580 	tcp_iss_cookie.current_time = t;
24581 
24582 	/*
24583 	 * XXX - Need a more random number per RFC 1750, not this crap.
24584 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24585 	 */
24586 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24587 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24588 
24589 	/*
24590 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24591 	 * as a good template.
24592 	 */
24593 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24594 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24595 
24596 	/*
24597 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24598 	 */
24599 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24600 
24601 	/*
24602 	 * See 4010593 if this section becomes a problem again,
24603 	 * but the local ethernet address is useful here.
24604 	 */
24605 	(void) localetheraddr(NULL,
24606 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24607 
24608 	/*
24609 	 * Hash 'em all together.  The MD5Final is called per-connection.
24610 	 */
24611 	mutex_enter(&tcps->tcps_iss_key_lock);
24612 	MD5Init(&tcps->tcps_iss_key);
24613 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24614 	    sizeof (tcp_iss_cookie));
24615 	mutex_exit(&tcps->tcps_iss_key_lock);
24616 }
24617 
24618 /*
24619  * Set the RFC 1948 pass phrase
24620  */
24621 /* ARGSUSED */
24622 static int
24623 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24624     cred_t *cr)
24625 {
24626 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24627 
24628 	/*
24629 	 * Basically, value contains a new pass phrase.  Pass it along!
24630 	 */
24631 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24632 	return (0);
24633 }
24634 
24635 /* ARGSUSED */
24636 static int
24637 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24638 {
24639 	bzero(buf, sizeof (tcp_sack_info_t));
24640 	return (0);
24641 }
24642 
24643 /* ARGSUSED */
24644 static int
24645 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24646 {
24647 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24648 	return (0);
24649 }
24650 
24651 /*
24652  * Make sure we wait until the default queue is setup, yet allow
24653  * tcp_g_q_create() to open a TCP stream.
24654  * We need to allow tcp_g_q_create() do do an open
24655  * of tcp, hence we compare curhread.
24656  * All others have to wait until the tcps_g_q has been
24657  * setup.
24658  */
24659 void
24660 tcp_g_q_setup(tcp_stack_t *tcps)
24661 {
24662 	mutex_enter(&tcps->tcps_g_q_lock);
24663 	if (tcps->tcps_g_q != NULL) {
24664 		mutex_exit(&tcps->tcps_g_q_lock);
24665 		return;
24666 	}
24667 	if (tcps->tcps_g_q_creator == NULL) {
24668 		/* This thread will set it up */
24669 		tcps->tcps_g_q_creator = curthread;
24670 		mutex_exit(&tcps->tcps_g_q_lock);
24671 		tcp_g_q_create(tcps);
24672 		mutex_enter(&tcps->tcps_g_q_lock);
24673 		ASSERT(tcps->tcps_g_q_creator == curthread);
24674 		tcps->tcps_g_q_creator = NULL;
24675 		cv_signal(&tcps->tcps_g_q_cv);
24676 		ASSERT(tcps->tcps_g_q != NULL);
24677 		mutex_exit(&tcps->tcps_g_q_lock);
24678 		return;
24679 	}
24680 	/* Everybody but the creator has to wait */
24681 	if (tcps->tcps_g_q_creator != curthread) {
24682 		while (tcps->tcps_g_q == NULL)
24683 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24684 	}
24685 	mutex_exit(&tcps->tcps_g_q_lock);
24686 }
24687 
24688 #define	IP	"ip"
24689 
24690 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24691 
24692 /*
24693  * Create a default tcp queue here instead of in strplumb
24694  */
24695 void
24696 tcp_g_q_create(tcp_stack_t *tcps)
24697 {
24698 	int error;
24699 	ldi_handle_t	lh = NULL;
24700 	ldi_ident_t	li = NULL;
24701 	int		rval;
24702 	cred_t		*cr;
24703 	major_t IP_MAJ;
24704 
24705 #ifdef NS_DEBUG
24706 	(void) printf("tcp_g_q_create()\n");
24707 #endif
24708 
24709 	IP_MAJ = ddi_name_to_major(IP);
24710 
24711 	ASSERT(tcps->tcps_g_q_creator == curthread);
24712 
24713 	error = ldi_ident_from_major(IP_MAJ, &li);
24714 	if (error) {
24715 #ifdef DEBUG
24716 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24717 		    error);
24718 #endif
24719 		return;
24720 	}
24721 
24722 	cr = zone_get_kcred(netstackid_to_zoneid(
24723 	    tcps->tcps_netstack->netstack_stackid));
24724 	ASSERT(cr != NULL);
24725 	/*
24726 	 * We set the tcp default queue to IPv6 because IPv4 falls
24727 	 * back to IPv6 when it can't find a client, but
24728 	 * IPv6 does not fall back to IPv4.
24729 	 */
24730 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24731 	if (error) {
24732 #ifdef DEBUG
24733 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24734 		    error);
24735 #endif
24736 		goto out;
24737 	}
24738 
24739 	/*
24740 	 * This ioctl causes the tcp framework to cache a pointer to
24741 	 * this stream, so we don't want to close the stream after
24742 	 * this operation.
24743 	 * Use the kernel credentials that are for the zone we're in.
24744 	 */
24745 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24746 	    (intptr_t)0, FKIOCTL, cr, &rval);
24747 	if (error) {
24748 #ifdef DEBUG
24749 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24750 		    "error %d\n", error);
24751 #endif
24752 		goto out;
24753 	}
24754 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24755 	lh = NULL;
24756 out:
24757 	/* Close layered handles */
24758 	if (li)
24759 		ldi_ident_release(li);
24760 	/* Keep cred around until _inactive needs it */
24761 	tcps->tcps_g_q_cr = cr;
24762 }
24763 
24764 /*
24765  * We keep tcp_g_q set until all other tcp_t's in the zone
24766  * has gone away, and then when tcp_g_q_inactive() is called
24767  * we clear it.
24768  */
24769 void
24770 tcp_g_q_destroy(tcp_stack_t *tcps)
24771 {
24772 #ifdef NS_DEBUG
24773 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24774 	    tcps->tcps_netstack->netstack_stackid);
24775 #endif
24776 
24777 	if (tcps->tcps_g_q == NULL) {
24778 		return;	/* Nothing to cleanup */
24779 	}
24780 	/*
24781 	 * Drop reference corresponding to the default queue.
24782 	 * This reference was added from tcp_open when the default queue
24783 	 * was created, hence we compensate for this extra drop in
24784 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24785 	 * the default queue was the last one to be open, in which
24786 	 * case, then tcp_g_q_inactive will be
24787 	 * called as a result of the refrele.
24788 	 */
24789 	TCPS_REFRELE(tcps);
24790 }
24791 
24792 /*
24793  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24794  * Run by tcp_q_q_inactive using a taskq.
24795  */
24796 static void
24797 tcp_g_q_close(void *arg)
24798 {
24799 	tcp_stack_t *tcps = arg;
24800 	int error;
24801 	ldi_handle_t	lh = NULL;
24802 	ldi_ident_t	li = NULL;
24803 	cred_t		*cr;
24804 	major_t IP_MAJ;
24805 
24806 	IP_MAJ = ddi_name_to_major(IP);
24807 
24808 #ifdef NS_DEBUG
24809 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24810 	    tcps->tcps_netstack->netstack_stackid,
24811 	    tcps->tcps_netstack->netstack_refcnt);
24812 #endif
24813 	lh = tcps->tcps_g_q_lh;
24814 	if (lh == NULL)
24815 		return;	/* Nothing to cleanup */
24816 
24817 	ASSERT(tcps->tcps_refcnt == 1);
24818 	ASSERT(tcps->tcps_g_q != NULL);
24819 
24820 	error = ldi_ident_from_major(IP_MAJ, &li);
24821 	if (error) {
24822 #ifdef DEBUG
24823 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24824 		    error);
24825 #endif
24826 		return;
24827 	}
24828 
24829 	cr = tcps->tcps_g_q_cr;
24830 	tcps->tcps_g_q_cr = NULL;
24831 	ASSERT(cr != NULL);
24832 
24833 	/*
24834 	 * Make sure we can break the recursion when tcp_close decrements
24835 	 * the reference count causing g_q_inactive to be called again.
24836 	 */
24837 	tcps->tcps_g_q_lh = NULL;
24838 
24839 	/* close the default queue */
24840 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24841 	/*
24842 	 * At this point in time tcps and the rest of netstack_t might
24843 	 * have been deleted.
24844 	 */
24845 	tcps = NULL;
24846 
24847 	/* Close layered handles */
24848 	ldi_ident_release(li);
24849 	crfree(cr);
24850 }
24851 
24852 /*
24853  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24854  *
24855  * Have to ensure that the ldi routines are not used by an
24856  * interrupt thread by using a taskq.
24857  */
24858 void
24859 tcp_g_q_inactive(tcp_stack_t *tcps)
24860 {
24861 	if (tcps->tcps_g_q_lh == NULL)
24862 		return;	/* Nothing to cleanup */
24863 
24864 	ASSERT(tcps->tcps_refcnt == 0);
24865 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24866 
24867 	if (servicing_interrupt()) {
24868 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24869 		    (void *) tcps, TQ_SLEEP);
24870 	} else {
24871 		tcp_g_q_close(tcps);
24872 	}
24873 }
24874 
24875 /*
24876  * Called by IP when IP is loaded into the kernel
24877  */
24878 void
24879 tcp_ddi_g_init(void)
24880 {
24881 	tcp_timercache = kmem_cache_create("tcp_timercache",
24882 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24883 	    NULL, NULL, NULL, NULL, NULL, 0);
24884 
24885 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24886 	    sizeof (tcp_sack_info_t), 0,
24887 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24888 
24889 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24890 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24891 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24892 
24893 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24894 
24895 	/* Initialize the random number generator */
24896 	tcp_random_init();
24897 
24898 	/* A single callback independently of how many netstacks we have */
24899 	ip_squeue_init(tcp_squeue_add);
24900 
24901 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24902 
24903 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24904 	    TASKQ_PREPOPULATE);
24905 
24906 	tcp_squeue_flag = tcp_squeue_switch(tcp_squeue_wput);
24907 
24908 	/*
24909 	 * We want to be informed each time a stack is created or
24910 	 * destroyed in the kernel, so we can maintain the
24911 	 * set of tcp_stack_t's.
24912 	 */
24913 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24914 	    tcp_stack_fini);
24915 }
24916 
24917 
24918 #define	INET_NAME	"ip"
24919 
24920 /*
24921  * Initialize the TCP stack instance.
24922  */
24923 static void *
24924 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24925 {
24926 	tcp_stack_t	*tcps;
24927 	tcpparam_t	*pa;
24928 	int		i;
24929 	int		error = 0;
24930 	major_t		major;
24931 
24932 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24933 	tcps->tcps_netstack = ns;
24934 
24935 	/* Initialize locks */
24936 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24937 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24938 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24939 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24940 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24941 
24942 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24943 	tcps->tcps_g_epriv_ports[0] = 2049;
24944 	tcps->tcps_g_epriv_ports[1] = 4045;
24945 	tcps->tcps_min_anonpriv_port = 512;
24946 
24947 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24948 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24949 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24950 	    TCP_FANOUT_SIZE, KM_SLEEP);
24951 
24952 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24953 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24954 		    MUTEX_DEFAULT, NULL);
24955 	}
24956 
24957 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24958 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24959 		    MUTEX_DEFAULT, NULL);
24960 	}
24961 
24962 	/* TCP's IPsec code calls the packet dropper. */
24963 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24964 
24965 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24966 	tcps->tcps_params = pa;
24967 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24968 
24969 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24970 	    A_CNT(lcl_tcp_param_arr), tcps);
24971 
24972 	/*
24973 	 * Note: To really walk the device tree you need the devinfo
24974 	 * pointer to your device which is only available after probe/attach.
24975 	 * The following is safe only because it uses ddi_root_node()
24976 	 */
24977 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24978 	    tcp_opt_obj.odb_opt_arr_cnt);
24979 
24980 	/*
24981 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24982 	 * by the boot scripts.
24983 	 *
24984 	 * Use NULL name, as the name is caught by the new lockstats.
24985 	 *
24986 	 * Initialize with some random, non-guessable string, like the global
24987 	 * T_INFO_ACK.
24988 	 */
24989 
24990 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
24991 	    sizeof (tcp_g_t_info_ack), tcps);
24992 
24993 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
24994 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
24995 
24996 	major = mod_name_to_major(INET_NAME);
24997 	error = ldi_ident_from_major(major, &tcps->tcps_ldi_ident);
24998 	ASSERT(error == 0);
24999 	return (tcps);
25000 }
25001 
25002 /*
25003  * Called when the IP module is about to be unloaded.
25004  */
25005 void
25006 tcp_ddi_g_destroy(void)
25007 {
25008 	tcp_g_kstat_fini(tcp_g_kstat);
25009 	tcp_g_kstat = NULL;
25010 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25011 
25012 	mutex_destroy(&tcp_random_lock);
25013 
25014 	kmem_cache_destroy(tcp_timercache);
25015 	kmem_cache_destroy(tcp_sack_info_cache);
25016 	kmem_cache_destroy(tcp_iphc_cache);
25017 
25018 	netstack_unregister(NS_TCP);
25019 	taskq_destroy(tcp_taskq);
25020 }
25021 
25022 /*
25023  * Shut down the TCP stack instance.
25024  */
25025 /* ARGSUSED */
25026 static void
25027 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25028 {
25029 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25030 
25031 	tcp_g_q_destroy(tcps);
25032 }
25033 
25034 /*
25035  * Free the TCP stack instance.
25036  */
25037 static void
25038 tcp_stack_fini(netstackid_t stackid, void *arg)
25039 {
25040 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25041 	int i;
25042 
25043 	nd_free(&tcps->tcps_g_nd);
25044 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25045 	tcps->tcps_params = NULL;
25046 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25047 	tcps->tcps_wroff_xtra_param = NULL;
25048 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25049 	tcps->tcps_mdt_head_param = NULL;
25050 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25051 	tcps->tcps_mdt_tail_param = NULL;
25052 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25053 	tcps->tcps_mdt_max_pbufs_param = NULL;
25054 
25055 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25056 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25057 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25058 	}
25059 
25060 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25061 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25062 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25063 	}
25064 
25065 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25066 	tcps->tcps_bind_fanout = NULL;
25067 
25068 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25069 	tcps->tcps_acceptor_fanout = NULL;
25070 
25071 	mutex_destroy(&tcps->tcps_iss_key_lock);
25072 	rw_destroy(&tcps->tcps_hsp_lock);
25073 	mutex_destroy(&tcps->tcps_g_q_lock);
25074 	cv_destroy(&tcps->tcps_g_q_cv);
25075 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25076 
25077 	ip_drop_unregister(&tcps->tcps_dropper);
25078 
25079 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25080 	tcps->tcps_kstat = NULL;
25081 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25082 
25083 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25084 	tcps->tcps_mibkp = NULL;
25085 
25086 	ldi_ident_release(tcps->tcps_ldi_ident);
25087 	kmem_free(tcps, sizeof (*tcps));
25088 }
25089 
25090 /*
25091  * Generate ISS, taking into account NDD changes may happen halfway through.
25092  * (If the iss is not zero, set it.)
25093  */
25094 
25095 static void
25096 tcp_iss_init(tcp_t *tcp)
25097 {
25098 	MD5_CTX context;
25099 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25100 	uint32_t answer[4];
25101 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25102 
25103 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25104 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25105 	switch (tcps->tcps_strong_iss) {
25106 	case 2:
25107 		mutex_enter(&tcps->tcps_iss_key_lock);
25108 		context = tcps->tcps_iss_key;
25109 		mutex_exit(&tcps->tcps_iss_key_lock);
25110 		arg.ports = tcp->tcp_ports;
25111 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25112 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25113 			    &arg.src);
25114 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25115 			    &arg.dst);
25116 		} else {
25117 			arg.src = tcp->tcp_ip6h->ip6_src;
25118 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25119 		}
25120 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25121 		MD5Final((uchar_t *)answer, &context);
25122 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25123 		/*
25124 		 * Now that we've hashed into a unique per-connection sequence
25125 		 * space, add a random increment per strong_iss == 1.  So I
25126 		 * guess we'll have to...
25127 		 */
25128 		/* FALLTHRU */
25129 	case 1:
25130 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25131 		break;
25132 	default:
25133 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25134 		break;
25135 	}
25136 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25137 	tcp->tcp_fss = tcp->tcp_iss - 1;
25138 	tcp->tcp_suna = tcp->tcp_iss;
25139 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25140 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25141 	tcp->tcp_csuna = tcp->tcp_snxt;
25142 }
25143 
25144 /*
25145  * Exported routine for extracting active tcp connection status.
25146  *
25147  * This is used by the Solaris Cluster Networking software to
25148  * gather a list of connections that need to be forwarded to
25149  * specific nodes in the cluster when configuration changes occur.
25150  *
25151  * The callback is invoked for each tcp_t structure from all netstacks,
25152  * if 'stack_id' is less than 0. Otherwise, only for tcp_t structures
25153  * from the netstack with the specified stack_id. Returning
25154  * non-zero from the callback routine terminates the search.
25155  */
25156 int
25157 cl_tcp_walk_list(netstackid_t stack_id,
25158     int (*cl_callback)(cl_tcp_info_t *, void *), void *arg)
25159 {
25160 	netstack_handle_t nh;
25161 	netstack_t *ns;
25162 	int ret = 0;
25163 
25164 	if (stack_id >= 0) {
25165 		if ((ns = netstack_find_by_stackid(stack_id)) == NULL)
25166 			return (EINVAL);
25167 
25168 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25169 		    ns->netstack_tcp);
25170 		netstack_rele(ns);
25171 		return (ret);
25172 	}
25173 
25174 	netstack_next_init(&nh);
25175 	while ((ns = netstack_next(&nh)) != NULL) {
25176 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25177 		    ns->netstack_tcp);
25178 		netstack_rele(ns);
25179 	}
25180 	netstack_next_fini(&nh);
25181 	return (ret);
25182 }
25183 
25184 static int
25185 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25186     tcp_stack_t *tcps)
25187 {
25188 	tcp_t *tcp;
25189 	cl_tcp_info_t	cl_tcpi;
25190 	connf_t	*connfp;
25191 	conn_t	*connp;
25192 	int	i;
25193 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25194 
25195 	ASSERT(callback != NULL);
25196 
25197 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25198 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25199 		connp = NULL;
25200 
25201 		while ((connp =
25202 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25203 
25204 			tcp = connp->conn_tcp;
25205 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25206 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25207 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25208 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25209 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25210 			/*
25211 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25212 			 * addresses. They are copied implicitly below as
25213 			 * mapped addresses.
25214 			 */
25215 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25216 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25217 				cl_tcpi.cl_tcpi_faddr =
25218 				    tcp->tcp_ipha->ipha_dst;
25219 			} else {
25220 				cl_tcpi.cl_tcpi_faddr_v6 =
25221 				    tcp->tcp_ip6h->ip6_dst;
25222 			}
25223 
25224 			/*
25225 			 * If the callback returns non-zero
25226 			 * we terminate the traversal.
25227 			 */
25228 			if ((*callback)(&cl_tcpi, arg) != 0) {
25229 				CONN_DEC_REF(tcp->tcp_connp);
25230 				return (1);
25231 			}
25232 		}
25233 	}
25234 
25235 	return (0);
25236 }
25237 
25238 /*
25239  * Macros used for accessing the different types of sockaddr
25240  * structures inside a tcp_ioc_abort_conn_t.
25241  */
25242 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25243 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25244 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25245 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25246 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25247 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25248 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25249 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25250 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25251 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25252 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25253 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25254 
25255 /*
25256  * Return the correct error code to mimic the behavior
25257  * of a connection reset.
25258  */
25259 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25260 		switch ((state)) {		\
25261 		case TCPS_SYN_SENT:		\
25262 		case TCPS_SYN_RCVD:		\
25263 			(err) = ECONNREFUSED;	\
25264 			break;			\
25265 		case TCPS_ESTABLISHED:		\
25266 		case TCPS_FIN_WAIT_1:		\
25267 		case TCPS_FIN_WAIT_2:		\
25268 		case TCPS_CLOSE_WAIT:		\
25269 			(err) = ECONNRESET;	\
25270 			break;			\
25271 		case TCPS_CLOSING:		\
25272 		case TCPS_LAST_ACK:		\
25273 		case TCPS_TIME_WAIT:		\
25274 			(err) = 0;		\
25275 			break;			\
25276 		default:			\
25277 			(err) = ENXIO;		\
25278 		}				\
25279 	}
25280 
25281 /*
25282  * Check if a tcp structure matches the info in acp.
25283  */
25284 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25285 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25286 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25287 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25288 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25289 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25290 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25291 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25292 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25293 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25294 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25295 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25296 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25297 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25298 	&(tcp)->tcp_ip_src_v6)) &&				\
25299 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25300 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25301 	&(tcp)->tcp_remote_v6)) &&				\
25302 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25303 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25304 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25305 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25306 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25307 	(acp)->ac_end >= (tcp)->tcp_state))
25308 
25309 #define	TCP_AC_MATCH(acp, tcp)					\
25310 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25311 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25312 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25313 
25314 /*
25315  * Build a message containing a tcp_ioc_abort_conn_t structure
25316  * which is filled in with information from acp and tp.
25317  */
25318 static mblk_t *
25319 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25320 {
25321 	mblk_t *mp;
25322 	tcp_ioc_abort_conn_t *tacp;
25323 
25324 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25325 	if (mp == NULL)
25326 		return (NULL);
25327 
25328 	mp->b_datap->db_type = M_CTL;
25329 
25330 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25331 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25332 	    sizeof (uint32_t));
25333 
25334 	tacp->ac_start = acp->ac_start;
25335 	tacp->ac_end = acp->ac_end;
25336 	tacp->ac_zoneid = acp->ac_zoneid;
25337 
25338 	if (acp->ac_local.ss_family == AF_INET) {
25339 		tacp->ac_local.ss_family = AF_INET;
25340 		tacp->ac_remote.ss_family = AF_INET;
25341 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25342 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25343 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25344 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25345 	} else {
25346 		tacp->ac_local.ss_family = AF_INET6;
25347 		tacp->ac_remote.ss_family = AF_INET6;
25348 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25349 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25350 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25351 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25352 	}
25353 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25354 	return (mp);
25355 }
25356 
25357 /*
25358  * Print a tcp_ioc_abort_conn_t structure.
25359  */
25360 static void
25361 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25362 {
25363 	char lbuf[128];
25364 	char rbuf[128];
25365 	sa_family_t af;
25366 	in_port_t lport, rport;
25367 	ushort_t logflags;
25368 
25369 	af = acp->ac_local.ss_family;
25370 
25371 	if (af == AF_INET) {
25372 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25373 		    lbuf, 128);
25374 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25375 		    rbuf, 128);
25376 		lport = ntohs(TCP_AC_V4LPORT(acp));
25377 		rport = ntohs(TCP_AC_V4RPORT(acp));
25378 	} else {
25379 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25380 		    lbuf, 128);
25381 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25382 		    rbuf, 128);
25383 		lport = ntohs(TCP_AC_V6LPORT(acp));
25384 		rport = ntohs(TCP_AC_V6RPORT(acp));
25385 	}
25386 
25387 	logflags = SL_TRACE | SL_NOTE;
25388 	/*
25389 	 * Don't print this message to the console if the operation was done
25390 	 * to a non-global zone.
25391 	 */
25392 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25393 		logflags |= SL_CONSOLE;
25394 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25395 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25396 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25397 	    acp->ac_start, acp->ac_end);
25398 }
25399 
25400 /*
25401  * Called inside tcp_rput when a message built using
25402  * tcp_ioctl_abort_build_msg is put into a queue.
25403  * Note that when we get here there is no wildcard in acp any more.
25404  */
25405 static void
25406 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25407 {
25408 	tcp_ioc_abort_conn_t *acp;
25409 
25410 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25411 	if (tcp->tcp_state <= acp->ac_end) {
25412 		/*
25413 		 * If we get here, we are already on the correct
25414 		 * squeue. This ioctl follows the following path
25415 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25416 		 * ->tcp_ioctl_abort->squeue_enter (if on a
25417 		 * different squeue)
25418 		 */
25419 		int errcode;
25420 
25421 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25422 		(void) tcp_clean_death(tcp, errcode, 26);
25423 	}
25424 	freemsg(mp);
25425 }
25426 
25427 /*
25428  * Abort all matching connections on a hash chain.
25429  */
25430 static int
25431 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25432     boolean_t exact, tcp_stack_t *tcps)
25433 {
25434 	int nmatch, err = 0;
25435 	tcp_t *tcp;
25436 	MBLKP mp, last, listhead = NULL;
25437 	conn_t	*tconnp;
25438 	connf_t	*connfp;
25439 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25440 
25441 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25442 
25443 startover:
25444 	nmatch = 0;
25445 
25446 	mutex_enter(&connfp->connf_lock);
25447 	for (tconnp = connfp->connf_head; tconnp != NULL;
25448 	    tconnp = tconnp->conn_next) {
25449 		tcp = tconnp->conn_tcp;
25450 		if (TCP_AC_MATCH(acp, tcp)) {
25451 			CONN_INC_REF(tcp->tcp_connp);
25452 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25453 			if (mp == NULL) {
25454 				err = ENOMEM;
25455 				CONN_DEC_REF(tcp->tcp_connp);
25456 				break;
25457 			}
25458 			mp->b_prev = (mblk_t *)tcp;
25459 
25460 			if (listhead == NULL) {
25461 				listhead = mp;
25462 				last = mp;
25463 			} else {
25464 				last->b_next = mp;
25465 				last = mp;
25466 			}
25467 			nmatch++;
25468 			if (exact)
25469 				break;
25470 		}
25471 
25472 		/* Avoid holding lock for too long. */
25473 		if (nmatch >= 500)
25474 			break;
25475 	}
25476 	mutex_exit(&connfp->connf_lock);
25477 
25478 	/* Pass mp into the correct tcp */
25479 	while ((mp = listhead) != NULL) {
25480 		listhead = listhead->b_next;
25481 		tcp = (tcp_t *)mp->b_prev;
25482 		mp->b_next = mp->b_prev = NULL;
25483 		SQUEUE_ENTER_ONE(tcp->tcp_connp->conn_sqp, mp, tcp_input,
25484 		    tcp->tcp_connp, SQ_FILL, SQTAG_TCP_ABORT_BUCKET);
25485 	}
25486 
25487 	*count += nmatch;
25488 	if (nmatch >= 500 && err == 0)
25489 		goto startover;
25490 	return (err);
25491 }
25492 
25493 /*
25494  * Abort all connections that matches the attributes specified in acp.
25495  */
25496 static int
25497 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25498 {
25499 	sa_family_t af;
25500 	uint32_t  ports;
25501 	uint16_t *pports;
25502 	int err = 0, count = 0;
25503 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25504 	int index = -1;
25505 	ushort_t logflags;
25506 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25507 
25508 	af = acp->ac_local.ss_family;
25509 
25510 	if (af == AF_INET) {
25511 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25512 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25513 			pports = (uint16_t *)&ports;
25514 			pports[1] = TCP_AC_V4LPORT(acp);
25515 			pports[0] = TCP_AC_V4RPORT(acp);
25516 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25517 		}
25518 	} else {
25519 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25520 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25521 			pports = (uint16_t *)&ports;
25522 			pports[1] = TCP_AC_V6LPORT(acp);
25523 			pports[0] = TCP_AC_V6RPORT(acp);
25524 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25525 		}
25526 	}
25527 
25528 	/*
25529 	 * For cases where remote addr, local port, and remote port are non-
25530 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25531 	 */
25532 	if (index != -1) {
25533 		err = tcp_ioctl_abort_bucket(acp, index,
25534 		    &count, exact, tcps);
25535 	} else {
25536 		/*
25537 		 * loop through all entries for wildcard case
25538 		 */
25539 		for (index = 0;
25540 		    index < ipst->ips_ipcl_conn_fanout_size;
25541 		    index++) {
25542 			err = tcp_ioctl_abort_bucket(acp, index,
25543 			    &count, exact, tcps);
25544 			if (err != 0)
25545 				break;
25546 		}
25547 	}
25548 
25549 	logflags = SL_TRACE | SL_NOTE;
25550 	/*
25551 	 * Don't print this message to the console if the operation was done
25552 	 * to a non-global zone.
25553 	 */
25554 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25555 		logflags |= SL_CONSOLE;
25556 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25557 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25558 	if (err == 0 && count == 0)
25559 		err = ENOENT;
25560 	return (err);
25561 }
25562 
25563 /*
25564  * Process the TCP_IOC_ABORT_CONN ioctl request.
25565  */
25566 static void
25567 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25568 {
25569 	int	err;
25570 	IOCP    iocp;
25571 	MBLKP   mp1;
25572 	sa_family_t laf, raf;
25573 	tcp_ioc_abort_conn_t *acp;
25574 	zone_t		*zptr;
25575 	conn_t		*connp = Q_TO_CONN(q);
25576 	zoneid_t	zoneid = connp->conn_zoneid;
25577 	tcp_t		*tcp = connp->conn_tcp;
25578 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25579 
25580 	iocp = (IOCP)mp->b_rptr;
25581 
25582 	if ((mp1 = mp->b_cont) == NULL ||
25583 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25584 		err = EINVAL;
25585 		goto out;
25586 	}
25587 
25588 	/* check permissions */
25589 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25590 		err = EPERM;
25591 		goto out;
25592 	}
25593 
25594 	if (mp1->b_cont != NULL) {
25595 		freemsg(mp1->b_cont);
25596 		mp1->b_cont = NULL;
25597 	}
25598 
25599 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25600 	laf = acp->ac_local.ss_family;
25601 	raf = acp->ac_remote.ss_family;
25602 
25603 	/* check that a zone with the supplied zoneid exists */
25604 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25605 		zptr = zone_find_by_id(zoneid);
25606 		if (zptr != NULL) {
25607 			zone_rele(zptr);
25608 		} else {
25609 			err = EINVAL;
25610 			goto out;
25611 		}
25612 	}
25613 
25614 	/*
25615 	 * For exclusive stacks we set the zoneid to zero
25616 	 * to make TCP operate as if in the global zone.
25617 	 */
25618 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25619 		acp->ac_zoneid = GLOBAL_ZONEID;
25620 
25621 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25622 	    acp->ac_start > acp->ac_end || laf != raf ||
25623 	    (laf != AF_INET && laf != AF_INET6)) {
25624 		err = EINVAL;
25625 		goto out;
25626 	}
25627 
25628 	tcp_ioctl_abort_dump(acp);
25629 	err = tcp_ioctl_abort(acp, tcps);
25630 
25631 out:
25632 	if (mp1 != NULL) {
25633 		freemsg(mp1);
25634 		mp->b_cont = NULL;
25635 	}
25636 
25637 	if (err != 0)
25638 		miocnak(q, mp, 0, err);
25639 	else
25640 		miocack(q, mp, 0, 0);
25641 }
25642 
25643 /*
25644  * tcp_time_wait_processing() handles processing of incoming packets when
25645  * the tcp is in the TIME_WAIT state.
25646  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25647  * on the time wait list.
25648  */
25649 void
25650 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25651     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25652 {
25653 	int32_t		bytes_acked;
25654 	int32_t		gap;
25655 	int32_t		rgap;
25656 	tcp_opt_t	tcpopt;
25657 	uint_t		flags;
25658 	uint32_t	new_swnd = 0;
25659 	conn_t		*connp;
25660 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25661 
25662 	BUMP_LOCAL(tcp->tcp_ibsegs);
25663 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25664 
25665 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25666 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25667 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25668 	if (tcp->tcp_snd_ts_ok) {
25669 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25670 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25671 			    tcp->tcp_rnxt, TH_ACK);
25672 			goto done;
25673 		}
25674 	}
25675 	gap = seg_seq - tcp->tcp_rnxt;
25676 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25677 	if (gap < 0) {
25678 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25679 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25680 		    (seg_len > -gap ? -gap : seg_len));
25681 		seg_len += gap;
25682 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25683 			if (flags & TH_RST) {
25684 				goto done;
25685 			}
25686 			if ((flags & TH_FIN) && seg_len == -1) {
25687 				/*
25688 				 * When TCP receives a duplicate FIN in
25689 				 * TIME_WAIT state, restart the 2 MSL timer.
25690 				 * See page 73 in RFC 793. Make sure this TCP
25691 				 * is already on the TIME_WAIT list. If not,
25692 				 * just restart the timer.
25693 				 */
25694 				if (TCP_IS_DETACHED(tcp)) {
25695 					if (tcp_time_wait_remove(tcp, NULL) ==
25696 					    B_TRUE) {
25697 						tcp_time_wait_append(tcp);
25698 						TCP_DBGSTAT(tcps,
25699 						    tcp_rput_time_wait);
25700 					}
25701 				} else {
25702 					ASSERT(tcp != NULL);
25703 					TCP_TIMER_RESTART(tcp,
25704 					    tcps->tcps_time_wait_interval);
25705 				}
25706 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25707 				    tcp->tcp_rnxt, TH_ACK);
25708 				goto done;
25709 			}
25710 			flags |=  TH_ACK_NEEDED;
25711 			seg_len = 0;
25712 			goto process_ack;
25713 		}
25714 
25715 		/* Fix seg_seq, and chew the gap off the front. */
25716 		seg_seq = tcp->tcp_rnxt;
25717 	}
25718 
25719 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25720 		/*
25721 		 * Make sure that when we accept the connection, pick
25722 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25723 		 * old connection.
25724 		 *
25725 		 * The next ISS generated is equal to tcp_iss_incr_extra
25726 		 * + ISS_INCR/2 + other components depending on the
25727 		 * value of tcp_strong_iss.  We pre-calculate the new
25728 		 * ISS here and compare with tcp_snxt to determine if
25729 		 * we need to make adjustment to tcp_iss_incr_extra.
25730 		 *
25731 		 * The above calculation is ugly and is a
25732 		 * waste of CPU cycles...
25733 		 */
25734 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25735 		int32_t adj;
25736 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25737 
25738 		switch (tcps->tcps_strong_iss) {
25739 		case 2: {
25740 			/* Add time and MD5 components. */
25741 			uint32_t answer[4];
25742 			struct {
25743 				uint32_t ports;
25744 				in6_addr_t src;
25745 				in6_addr_t dst;
25746 			} arg;
25747 			MD5_CTX context;
25748 
25749 			mutex_enter(&tcps->tcps_iss_key_lock);
25750 			context = tcps->tcps_iss_key;
25751 			mutex_exit(&tcps->tcps_iss_key_lock);
25752 			arg.ports = tcp->tcp_ports;
25753 			/* We use MAPPED addresses in tcp_iss_init */
25754 			arg.src = tcp->tcp_ip_src_v6;
25755 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25756 				IN6_IPADDR_TO_V4MAPPED(
25757 				    tcp->tcp_ipha->ipha_dst,
25758 				    &arg.dst);
25759 			} else {
25760 				arg.dst =
25761 				    tcp->tcp_ip6h->ip6_dst;
25762 			}
25763 			MD5Update(&context, (uchar_t *)&arg,
25764 			    sizeof (arg));
25765 			MD5Final((uchar_t *)answer, &context);
25766 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25767 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25768 			break;
25769 		}
25770 		case 1:
25771 			/* Add time component and min random (i.e. 1). */
25772 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25773 			break;
25774 		default:
25775 			/* Add only time component. */
25776 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25777 			break;
25778 		}
25779 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25780 			/*
25781 			 * New ISS not guaranteed to be ISS_INCR/2
25782 			 * ahead of the current tcp_snxt, so add the
25783 			 * difference to tcp_iss_incr_extra.
25784 			 */
25785 			tcps->tcps_iss_incr_extra += adj;
25786 		}
25787 		/*
25788 		 * If tcp_clean_death() can not perform the task now,
25789 		 * drop the SYN packet and let the other side re-xmit.
25790 		 * Otherwise pass the SYN packet back in, since the
25791 		 * old tcp state has been cleaned up or freed.
25792 		 */
25793 		if (tcp_clean_death(tcp, 0, 27) == -1)
25794 			goto done;
25795 		/*
25796 		 * We will come back to tcp_rput_data
25797 		 * on the global queue. Packets destined
25798 		 * for the global queue will be checked
25799 		 * with global policy. But the policy for
25800 		 * this packet has already been checked as
25801 		 * this was destined for the detached
25802 		 * connection. We need to bypass policy
25803 		 * check this time by attaching a dummy
25804 		 * ipsec_in with ipsec_in_dont_check set.
25805 		 */
25806 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25807 		if (connp != NULL) {
25808 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25809 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25810 			return;
25811 		}
25812 		goto done;
25813 	}
25814 
25815 	/*
25816 	 * rgap is the amount of stuff received out of window.  A negative
25817 	 * value is the amount out of window.
25818 	 */
25819 	if (rgap < 0) {
25820 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25821 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25822 		/* Fix seg_len and make sure there is something left. */
25823 		seg_len += rgap;
25824 		if (seg_len <= 0) {
25825 			if (flags & TH_RST) {
25826 				goto done;
25827 			}
25828 			flags |=  TH_ACK_NEEDED;
25829 			seg_len = 0;
25830 			goto process_ack;
25831 		}
25832 	}
25833 	/*
25834 	 * Check whether we can update tcp_ts_recent.  This test is
25835 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25836 	 * Extensions for High Performance: An Update", Internet Draft.
25837 	 */
25838 	if (tcp->tcp_snd_ts_ok &&
25839 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25840 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25841 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25842 		tcp->tcp_last_rcv_lbolt = lbolt64;
25843 	}
25844 
25845 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25846 		/* Always ack out of order packets */
25847 		flags |= TH_ACK_NEEDED;
25848 		seg_len = 0;
25849 	} else if (seg_len > 0) {
25850 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25851 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25852 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25853 	}
25854 	if (flags & TH_RST) {
25855 		(void) tcp_clean_death(tcp, 0, 28);
25856 		goto done;
25857 	}
25858 	if (flags & TH_SYN) {
25859 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25860 		    TH_RST|TH_ACK);
25861 		/*
25862 		 * Do not delete the TCP structure if it is in
25863 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25864 		 */
25865 		goto done;
25866 	}
25867 process_ack:
25868 	if (flags & TH_ACK) {
25869 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25870 		if (bytes_acked <= 0) {
25871 			if (bytes_acked == 0 && seg_len == 0 &&
25872 			    new_swnd == tcp->tcp_swnd)
25873 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25874 		} else {
25875 			/* Acks something not sent */
25876 			flags |= TH_ACK_NEEDED;
25877 		}
25878 	}
25879 	if (flags & TH_ACK_NEEDED) {
25880 		/*
25881 		 * Time to send an ack for some reason.
25882 		 */
25883 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25884 		    tcp->tcp_rnxt, TH_ACK);
25885 	}
25886 done:
25887 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25888 		DB_CKSUMSTART(mp) = 0;
25889 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25890 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25891 	}
25892 	freemsg(mp);
25893 }
25894 
25895 /*
25896  * TCP Timers Implementation.
25897  */
25898 timeout_id_t
25899 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25900 {
25901 	mblk_t *mp;
25902 	tcp_timer_t *tcpt;
25903 	tcp_t *tcp = connp->conn_tcp;
25904 
25905 	ASSERT(connp->conn_sqp != NULL);
25906 
25907 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
25908 
25909 	if (tcp->tcp_timercache == NULL) {
25910 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25911 	} else {
25912 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
25913 		mp = tcp->tcp_timercache;
25914 		tcp->tcp_timercache = mp->b_next;
25915 		mp->b_next = NULL;
25916 		ASSERT(mp->b_wptr == NULL);
25917 	}
25918 
25919 	CONN_INC_REF(connp);
25920 	tcpt = (tcp_timer_t *)mp->b_rptr;
25921 	tcpt->connp = connp;
25922 	tcpt->tcpt_proc = f;
25923 	/*
25924 	 * TCP timers are normal timeouts. Plus, they do not require more than
25925 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25926 	 * rounding up the expiration to the next resolution boundary, we can
25927 	 * batch timers in the callout subsystem to make TCP timers more
25928 	 * efficient. The roundup also protects short timers from expiring too
25929 	 * early before they have a chance to be cancelled.
25930 	 */
25931 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25932 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25933 
25934 	return ((timeout_id_t)mp);
25935 }
25936 
25937 static void
25938 tcp_timer_callback(void *arg)
25939 {
25940 	mblk_t *mp = (mblk_t *)arg;
25941 	tcp_timer_t *tcpt;
25942 	conn_t	*connp;
25943 
25944 	tcpt = (tcp_timer_t *)mp->b_rptr;
25945 	connp = tcpt->connp;
25946 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
25947 	    SQ_FILL, SQTAG_TCP_TIMER);
25948 }
25949 
25950 static void
25951 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25952 {
25953 	tcp_timer_t *tcpt;
25954 	conn_t *connp = (conn_t *)arg;
25955 	tcp_t *tcp = connp->conn_tcp;
25956 
25957 	tcpt = (tcp_timer_t *)mp->b_rptr;
25958 	ASSERT(connp == tcpt->connp);
25959 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25960 
25961 	/*
25962 	 * If the TCP has reached the closed state, don't proceed any
25963 	 * further. This TCP logically does not exist on the system.
25964 	 * tcpt_proc could for example access queues, that have already
25965 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
25966 	 */
25967 	if (tcp->tcp_state != TCPS_CLOSED) {
25968 		(*tcpt->tcpt_proc)(connp);
25969 	} else {
25970 		tcp->tcp_timer_tid = 0;
25971 	}
25972 	tcp_timer_free(connp->conn_tcp, mp);
25973 }
25974 
25975 /*
25976  * There is potential race with untimeout and the handler firing at the same
25977  * time. The mblock may be freed by the handler while we are trying to use
25978  * it. But since both should execute on the same squeue, this race should not
25979  * occur.
25980  */
25981 clock_t
25982 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
25983 {
25984 	mblk_t	*mp = (mblk_t *)id;
25985 	tcp_timer_t *tcpt;
25986 	clock_t delta;
25987 
25988 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
25989 
25990 	if (mp == NULL)
25991 		return (-1);
25992 
25993 	tcpt = (tcp_timer_t *)mp->b_rptr;
25994 	ASSERT(tcpt->connp == connp);
25995 
25996 	delta = untimeout_default(tcpt->tcpt_tid, 0);
25997 
25998 	if (delta >= 0) {
25999 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
26000 		tcp_timer_free(connp->conn_tcp, mp);
26001 		CONN_DEC_REF(connp);
26002 	}
26003 
26004 	return (delta);
26005 }
26006 
26007 /*
26008  * Allocate space for the timer event. The allocation looks like mblk, but it is
26009  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26010  *
26011  * Dealing with failures: If we can't allocate from the timer cache we try
26012  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26013  * points to b_rptr.
26014  * If we can't allocate anything using allocb_tryhard(), we perform a last
26015  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26016  * save the actual allocation size in b_datap.
26017  */
26018 mblk_t *
26019 tcp_timermp_alloc(int kmflags)
26020 {
26021 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26022 	    kmflags & ~KM_PANIC);
26023 
26024 	if (mp != NULL) {
26025 		mp->b_next = mp->b_prev = NULL;
26026 		mp->b_rptr = (uchar_t *)(&mp[1]);
26027 		mp->b_wptr = NULL;
26028 		mp->b_datap = NULL;
26029 		mp->b_queue = NULL;
26030 		mp->b_cont = NULL;
26031 	} else if (kmflags & KM_PANIC) {
26032 		/*
26033 		 * Failed to allocate memory for the timer. Try allocating from
26034 		 * dblock caches.
26035 		 */
26036 		/* ipclassifier calls this from a constructor - hence no tcps */
26037 		TCP_G_STAT(tcp_timermp_allocfail);
26038 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26039 		if (mp == NULL) {
26040 			size_t size = 0;
26041 			/*
26042 			 * Memory is really low. Try tryhard allocation.
26043 			 *
26044 			 * ipclassifier calls this from a constructor -
26045 			 * hence no tcps
26046 			 */
26047 			TCP_G_STAT(tcp_timermp_allocdblfail);
26048 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26049 			    sizeof (tcp_timer_t), &size, kmflags);
26050 			mp->b_rptr = (uchar_t *)(&mp[1]);
26051 			mp->b_next = mp->b_prev = NULL;
26052 			mp->b_wptr = (uchar_t *)-1;
26053 			mp->b_datap = (dblk_t *)size;
26054 			mp->b_queue = NULL;
26055 			mp->b_cont = NULL;
26056 		}
26057 		ASSERT(mp->b_wptr != NULL);
26058 	}
26059 	/* ipclassifier calls this from a constructor - hence no tcps */
26060 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26061 
26062 	return (mp);
26063 }
26064 
26065 /*
26066  * Free per-tcp timer cache.
26067  * It can only contain entries from tcp_timercache.
26068  */
26069 void
26070 tcp_timermp_free(tcp_t *tcp)
26071 {
26072 	mblk_t *mp;
26073 
26074 	while ((mp = tcp->tcp_timercache) != NULL) {
26075 		ASSERT(mp->b_wptr == NULL);
26076 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26077 		kmem_cache_free(tcp_timercache, mp);
26078 	}
26079 }
26080 
26081 /*
26082  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26083  * events there already (currently at most two events are cached).
26084  * If the event is not allocated from the timer cache, free it right away.
26085  */
26086 static void
26087 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26088 {
26089 	mblk_t *mp1 = tcp->tcp_timercache;
26090 
26091 	if (mp->b_wptr != NULL) {
26092 		/*
26093 		 * This allocation is not from a timer cache, free it right
26094 		 * away.
26095 		 */
26096 		if (mp->b_wptr != (uchar_t *)-1)
26097 			freeb(mp);
26098 		else
26099 			kmem_free(mp, (size_t)mp->b_datap);
26100 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26101 		/* Cache this timer block for future allocations */
26102 		mp->b_rptr = (uchar_t *)(&mp[1]);
26103 		mp->b_next = mp1;
26104 		tcp->tcp_timercache = mp;
26105 	} else {
26106 		kmem_cache_free(tcp_timercache, mp);
26107 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
26108 	}
26109 }
26110 
26111 /*
26112  * End of TCP Timers implementation.
26113  */
26114 
26115 /*
26116  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26117  * on the specified backing STREAMS q. Note, the caller may make the
26118  * decision to call based on the tcp_t.tcp_flow_stopped value which
26119  * when check outside the q's lock is only an advisory check ...
26120  */
26121 void
26122 tcp_setqfull(tcp_t *tcp)
26123 {
26124 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26125 	conn_t	*connp = tcp->tcp_connp;
26126 
26127 	if (tcp->tcp_closed)
26128 		return;
26129 
26130 	if (IPCL_IS_NONSTR(connp)) {
26131 		(*connp->conn_upcalls->su_txq_full)
26132 		    (tcp->tcp_connp->conn_upper_handle, B_TRUE);
26133 		tcp->tcp_flow_stopped = B_TRUE;
26134 	} else {
26135 		queue_t *q = tcp->tcp_wq;
26136 
26137 		if (!(q->q_flag & QFULL)) {
26138 			mutex_enter(QLOCK(q));
26139 			if (!(q->q_flag & QFULL)) {
26140 				/* still need to set QFULL */
26141 				q->q_flag |= QFULL;
26142 				tcp->tcp_flow_stopped = B_TRUE;
26143 				mutex_exit(QLOCK(q));
26144 				TCP_STAT(tcps, tcp_flwctl_on);
26145 			} else {
26146 				mutex_exit(QLOCK(q));
26147 			}
26148 		}
26149 	}
26150 }
26151 
26152 void
26153 tcp_clrqfull(tcp_t *tcp)
26154 {
26155 	conn_t  *connp = tcp->tcp_connp;
26156 
26157 	if (tcp->tcp_closed)
26158 		return;
26159 
26160 	if (IPCL_IS_NONSTR(connp)) {
26161 		(*connp->conn_upcalls->su_txq_full)
26162 		    (tcp->tcp_connp->conn_upper_handle, B_FALSE);
26163 		tcp->tcp_flow_stopped = B_FALSE;
26164 	} else {
26165 		queue_t *q = tcp->tcp_wq;
26166 
26167 		if (q->q_flag & QFULL) {
26168 			mutex_enter(QLOCK(q));
26169 			if (q->q_flag & QFULL) {
26170 				q->q_flag &= ~QFULL;
26171 				tcp->tcp_flow_stopped = B_FALSE;
26172 				mutex_exit(QLOCK(q));
26173 				if (q->q_flag & QWANTW)
26174 					qbackenable(q, 0);
26175 			} else {
26176 				mutex_exit(QLOCK(q));
26177 			}
26178 		}
26179 	}
26180 }
26181 
26182 /*
26183  * kstats related to squeues i.e. not per IP instance
26184  */
26185 static void *
26186 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26187 {
26188 	kstat_t *ksp;
26189 
26190 	tcp_g_stat_t template = {
26191 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26192 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26193 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26194 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26195 	};
26196 
26197 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26198 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26199 	    KSTAT_FLAG_VIRTUAL);
26200 
26201 	if (ksp == NULL)
26202 		return (NULL);
26203 
26204 	bcopy(&template, tcp_g_statp, sizeof (template));
26205 	ksp->ks_data = (void *)tcp_g_statp;
26206 
26207 	kstat_install(ksp);
26208 	return (ksp);
26209 }
26210 
26211 static void
26212 tcp_g_kstat_fini(kstat_t *ksp)
26213 {
26214 	if (ksp != NULL) {
26215 		kstat_delete(ksp);
26216 	}
26217 }
26218 
26219 
26220 static void *
26221 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26222 {
26223 	kstat_t *ksp;
26224 
26225 	tcp_stat_t template = {
26226 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26227 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26228 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26229 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26230 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26231 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26232 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26233 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26234 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26235 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26236 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26237 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26238 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26239 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26240 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26241 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26242 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26243 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26244 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26245 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26246 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26247 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26248 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26249 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26250 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26251 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26252 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26253 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26254 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26255 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26256 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26257 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26258 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26259 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26260 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26261 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26262 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26263 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26264 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26265 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26266 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26267 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26268 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26269 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26270 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26271 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26272 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26273 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26274 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26275 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26276 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26277 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26278 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26279 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26280 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26281 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26282 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26283 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26284 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26285 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26286 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26287 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26288 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26289 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26290 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26291 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26292 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26293 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26294 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26295 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26296 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26297 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26298 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26299 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26300 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26301 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26302 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26303 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26304 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26305 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26306 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26307 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26308 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26309 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26310 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26311 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26312 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26313 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26314 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26315 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26316 	};
26317 
26318 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26319 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26320 	    KSTAT_FLAG_VIRTUAL, stackid);
26321 
26322 	if (ksp == NULL)
26323 		return (NULL);
26324 
26325 	bcopy(&template, tcps_statisticsp, sizeof (template));
26326 	ksp->ks_data = (void *)tcps_statisticsp;
26327 	ksp->ks_private = (void *)(uintptr_t)stackid;
26328 
26329 	kstat_install(ksp);
26330 	return (ksp);
26331 }
26332 
26333 static void
26334 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26335 {
26336 	if (ksp != NULL) {
26337 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26338 		kstat_delete_netstack(ksp, stackid);
26339 	}
26340 }
26341 
26342 /*
26343  * TCP Kstats implementation
26344  */
26345 static void *
26346 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26347 {
26348 	kstat_t	*ksp;
26349 
26350 	tcp_named_kstat_t template = {
26351 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26352 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26353 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26354 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26355 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26356 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26357 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26358 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26359 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26360 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26361 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26362 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26363 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26364 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26365 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26366 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26367 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26368 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26369 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26370 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26371 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26372 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26373 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26374 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26375 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26376 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26377 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26378 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26379 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26380 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26381 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26382 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26383 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26384 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26385 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26386 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26387 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26388 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26389 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26390 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26391 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26392 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26393 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26394 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26395 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26396 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26397 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26398 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26399 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26400 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26401 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26402 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26403 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26404 	};
26405 
26406 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26407 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26408 
26409 	if (ksp == NULL)
26410 		return (NULL);
26411 
26412 	template.rtoAlgorithm.value.ui32 = 4;
26413 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26414 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26415 	template.maxConn.value.i32 = -1;
26416 
26417 	bcopy(&template, ksp->ks_data, sizeof (template));
26418 	ksp->ks_update = tcp_kstat_update;
26419 	ksp->ks_private = (void *)(uintptr_t)stackid;
26420 
26421 	kstat_install(ksp);
26422 	return (ksp);
26423 }
26424 
26425 static void
26426 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26427 {
26428 	if (ksp != NULL) {
26429 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26430 		kstat_delete_netstack(ksp, stackid);
26431 	}
26432 }
26433 
26434 static int
26435 tcp_kstat_update(kstat_t *kp, int rw)
26436 {
26437 	tcp_named_kstat_t *tcpkp;
26438 	tcp_t		*tcp;
26439 	connf_t		*connfp;
26440 	conn_t		*connp;
26441 	int 		i;
26442 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26443 	netstack_t	*ns;
26444 	tcp_stack_t	*tcps;
26445 	ip_stack_t	*ipst;
26446 
26447 	if ((kp == NULL) || (kp->ks_data == NULL))
26448 		return (EIO);
26449 
26450 	if (rw == KSTAT_WRITE)
26451 		return (EACCES);
26452 
26453 	ns = netstack_find_by_stackid(stackid);
26454 	if (ns == NULL)
26455 		return (-1);
26456 	tcps = ns->netstack_tcp;
26457 	if (tcps == NULL) {
26458 		netstack_rele(ns);
26459 		return (-1);
26460 	}
26461 
26462 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26463 
26464 	tcpkp->currEstab.value.ui32 = 0;
26465 
26466 	ipst = ns->netstack_ip;
26467 
26468 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26469 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26470 		connp = NULL;
26471 		while ((connp =
26472 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26473 			tcp = connp->conn_tcp;
26474 			switch (tcp_snmp_state(tcp)) {
26475 			case MIB2_TCP_established:
26476 			case MIB2_TCP_closeWait:
26477 				tcpkp->currEstab.value.ui32++;
26478 				break;
26479 			}
26480 		}
26481 	}
26482 
26483 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26484 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26485 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26486 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26487 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26488 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26489 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26490 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26491 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26492 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26493 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26494 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26495 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26496 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26497 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26498 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26499 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26500 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26501 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26502 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26503 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26504 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26505 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26506 	tcpkp->inDataInorderSegs.value.ui32 =
26507 	    tcps->tcps_mib.tcpInDataInorderSegs;
26508 	tcpkp->inDataInorderBytes.value.ui32 =
26509 	    tcps->tcps_mib.tcpInDataInorderBytes;
26510 	tcpkp->inDataUnorderSegs.value.ui32 =
26511 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26512 	tcpkp->inDataUnorderBytes.value.ui32 =
26513 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26514 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26515 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26516 	tcpkp->inDataPartDupSegs.value.ui32 =
26517 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26518 	tcpkp->inDataPartDupBytes.value.ui32 =
26519 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26520 	tcpkp->inDataPastWinSegs.value.ui32 =
26521 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26522 	tcpkp->inDataPastWinBytes.value.ui32 =
26523 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26524 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26525 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26526 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26527 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26528 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26529 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26530 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26531 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26532 	tcpkp->timKeepaliveProbe.value.ui32 =
26533 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26534 	tcpkp->timKeepaliveDrop.value.ui32 =
26535 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26536 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26537 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26538 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26539 	tcpkp->outSackRetransSegs.value.ui32 =
26540 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26541 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26542 
26543 	netstack_rele(ns);
26544 	return (0);
26545 }
26546 
26547 void
26548 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26549 {
26550 	uint16_t	hdr_len;
26551 	ipha_t		*ipha;
26552 	uint8_t		*nexthdrp;
26553 	tcph_t		*tcph;
26554 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26555 
26556 	/* Already has an eager */
26557 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26558 		TCP_STAT(tcps, tcp_reinput_syn);
26559 		SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26560 		    SQ_PROCESS, SQTAG_TCP_REINPUT_EAGER);
26561 		return;
26562 	}
26563 
26564 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26565 	case IPV4_VERSION:
26566 		ipha = (ipha_t *)mp->b_rptr;
26567 		hdr_len = IPH_HDR_LENGTH(ipha);
26568 		break;
26569 	case IPV6_VERSION:
26570 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26571 		    &hdr_len, &nexthdrp)) {
26572 			CONN_DEC_REF(connp);
26573 			freemsg(mp);
26574 			return;
26575 		}
26576 		break;
26577 	}
26578 
26579 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26580 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26581 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26582 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26583 	}
26584 
26585 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, connp->conn_recv, connp,
26586 	    SQ_FILL, SQTAG_TCP_REINPUT);
26587 }
26588 
26589 static int
26590 tcp_squeue_switch(int val)
26591 {
26592 	int rval = SQ_FILL;
26593 
26594 	switch (val) {
26595 	case 1:
26596 		rval = SQ_NODRAIN;
26597 		break;
26598 	case 2:
26599 		rval = SQ_PROCESS;
26600 		break;
26601 	default:
26602 		break;
26603 	}
26604 	return (rval);
26605 }
26606 
26607 /*
26608  * This is called once for each squeue - globally for all stack
26609  * instances.
26610  */
26611 static void
26612 tcp_squeue_add(squeue_t *sqp)
26613 {
26614 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26615 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26616 
26617 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26618 	tcp_time_wait->tcp_time_wait_tid =
26619 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26620 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26621 	    CALLOUT_FLAG_ROUNDUP);
26622 	if (tcp_free_list_max_cnt == 0) {
26623 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26624 		    max_ncpus : boot_max_ncpus);
26625 
26626 		/*
26627 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26628 		 */
26629 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26630 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26631 	}
26632 	tcp_time_wait->tcp_free_list_cnt = 0;
26633 }
26634 
26635 static int
26636 tcp_post_ip_bind(tcp_t *tcp, mblk_t *mp, int error, cred_t *cr, pid_t pid)
26637 {
26638 	mblk_t	*ire_mp = NULL;
26639 	mblk_t	*syn_mp;
26640 	mblk_t	*mdti;
26641 	mblk_t	*lsoi;
26642 	int	retval;
26643 	tcph_t	*tcph;
26644 	uint32_t	mss;
26645 	queue_t	*q = tcp->tcp_rq;
26646 	conn_t	*connp = tcp->tcp_connp;
26647 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26648 
26649 	if (error == 0) {
26650 		/*
26651 		 * Adapt Multidata information, if any.  The
26652 		 * following tcp_mdt_update routine will free
26653 		 * the message.
26654 		 */
26655 		if (mp != NULL && ((mdti = tcp_mdt_info_mp(mp)) != NULL)) {
26656 			tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
26657 			    b_rptr)->mdt_capab, B_TRUE);
26658 			freemsg(mdti);
26659 		}
26660 
26661 		/*
26662 		 * Check to update LSO information with tcp, and
26663 		 * tcp_lso_update routine will free the message.
26664 		 */
26665 		if (mp != NULL && ((lsoi = tcp_lso_info_mp(mp)) != NULL)) {
26666 			tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
26667 			    b_rptr)->lso_capab);
26668 			freemsg(lsoi);
26669 		}
26670 
26671 		/* Get the IRE, if we had requested for it */
26672 		if (mp != NULL)
26673 			ire_mp = tcp_ire_mp(&mp);
26674 
26675 		if (tcp->tcp_hard_binding) {
26676 			tcp->tcp_hard_binding = B_FALSE;
26677 			tcp->tcp_hard_bound = B_TRUE;
26678 			CL_INET_CONNECT(tcp->tcp_connp, tcp, B_TRUE, retval);
26679 			if (retval != 0) {
26680 				error = EADDRINUSE;
26681 				goto bind_failed;
26682 			}
26683 		} else {
26684 			if (ire_mp != NULL)
26685 				freeb(ire_mp);
26686 			goto after_syn_sent;
26687 		}
26688 
26689 		retval = tcp_adapt_ire(tcp, ire_mp);
26690 		if (ire_mp != NULL)
26691 			freeb(ire_mp);
26692 		if (retval == 0) {
26693 			error = (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
26694 			    ENETUNREACH : EADDRNOTAVAIL);
26695 			goto ipcl_rm;
26696 		}
26697 		/*
26698 		 * Don't let an endpoint connect to itself.
26699 		 * Also checked in tcp_connect() but that
26700 		 * check can't handle the case when the
26701 		 * local IP address is INADDR_ANY.
26702 		 */
26703 		if (tcp->tcp_ipversion == IPV4_VERSION) {
26704 			if ((tcp->tcp_ipha->ipha_dst ==
26705 			    tcp->tcp_ipha->ipha_src) &&
26706 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26707 			    tcp->tcp_tcph->th_fport))) {
26708 				error = EADDRNOTAVAIL;
26709 				goto ipcl_rm;
26710 			}
26711 		} else {
26712 			if (IN6_ARE_ADDR_EQUAL(
26713 			    &tcp->tcp_ip6h->ip6_dst,
26714 			    &tcp->tcp_ip6h->ip6_src) &&
26715 			    (BE16_EQL(tcp->tcp_tcph->th_lport,
26716 			    tcp->tcp_tcph->th_fport))) {
26717 				error = EADDRNOTAVAIL;
26718 				goto ipcl_rm;
26719 			}
26720 		}
26721 		ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
26722 		/*
26723 		 * This should not be possible!  Just for
26724 		 * defensive coding...
26725 		 */
26726 		if (tcp->tcp_state != TCPS_SYN_SENT)
26727 			goto after_syn_sent;
26728 
26729 		if (is_system_labeled() &&
26730 		    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
26731 			error = EHOSTUNREACH;
26732 			goto ipcl_rm;
26733 		}
26734 
26735 		/*
26736 		 * tcp_adapt_ire() does not adjust
26737 		 * for TCP/IP header length.
26738 		 */
26739 		mss = tcp->tcp_mss - tcp->tcp_hdr_len;
26740 
26741 		/*
26742 		 * Just make sure our rwnd is at
26743 		 * least tcp_recv_hiwat_mss * MSS
26744 		 * large, and round up to the nearest
26745 		 * MSS.
26746 		 *
26747 		 * We do the round up here because
26748 		 * we need to get the interface
26749 		 * MTU first before we can do the
26750 		 * round up.
26751 		 */
26752 		tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
26753 		    tcps->tcps_recv_hiwat_minmss * mss);
26754 		if (!IPCL_IS_NONSTR(connp))
26755 			q->q_hiwat = tcp->tcp_rwnd;
26756 		tcp->tcp_recv_hiwater = tcp->tcp_rwnd;
26757 		tcp_set_ws_value(tcp);
26758 		U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
26759 		    tcp->tcp_tcph->th_win);
26760 		if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
26761 			tcp->tcp_snd_ws_ok = B_TRUE;
26762 
26763 		/*
26764 		 * Set tcp_snd_ts_ok to true
26765 		 * so that tcp_xmit_mp will
26766 		 * include the timestamp
26767 		 * option in the SYN segment.
26768 		 */
26769 		if (tcps->tcps_tstamp_always ||
26770 		    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
26771 			tcp->tcp_snd_ts_ok = B_TRUE;
26772 		}
26773 
26774 		/*
26775 		 * tcp_snd_sack_ok can be set in
26776 		 * tcp_adapt_ire() if the sack metric
26777 		 * is set.  So check it here also.
26778 		 */
26779 		if (tcps->tcps_sack_permitted == 2 ||
26780 		    tcp->tcp_snd_sack_ok) {
26781 			if (tcp->tcp_sack_info == NULL) {
26782 				tcp->tcp_sack_info =
26783 				    kmem_cache_alloc(tcp_sack_info_cache,
26784 				    KM_SLEEP);
26785 			}
26786 			tcp->tcp_snd_sack_ok = B_TRUE;
26787 		}
26788 
26789 		/*
26790 		 * Should we use ECN?  Note that the current
26791 		 * default value (SunOS 5.9) of tcp_ecn_permitted
26792 		 * is 1.  The reason for doing this is that there
26793 		 * are equipments out there that will drop ECN
26794 		 * enabled IP packets.  Setting it to 1 avoids
26795 		 * compatibility problems.
26796 		 */
26797 		if (tcps->tcps_ecn_permitted == 2)
26798 			tcp->tcp_ecn_ok = B_TRUE;
26799 
26800 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
26801 		syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
26802 		    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
26803 		if (syn_mp) {
26804 			if (cr == NULL) {
26805 				cr = tcp->tcp_cred;
26806 				pid = tcp->tcp_cpid;
26807 			}
26808 			mblk_setcred(syn_mp, cr, pid);
26809 			tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
26810 		}
26811 	after_syn_sent:
26812 		if (mp != NULL) {
26813 			ASSERT(mp->b_cont == NULL);
26814 			freeb(mp);
26815 		}
26816 		return (error);
26817 	} else {
26818 		/* error */
26819 		if (tcp->tcp_debug) {
26820 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
26821 			    "tcp_post_ip_bind: error == %d", error);
26822 		}
26823 		if (mp != NULL) {
26824 			freeb(mp);
26825 		}
26826 	}
26827 
26828 ipcl_rm:
26829 	/*
26830 	 * Need to unbind with classifier since we were just
26831 	 * told that our bind succeeded. a.k.a error == 0 at the entry.
26832 	 */
26833 	tcp->tcp_hard_bound = B_FALSE;
26834 	tcp->tcp_hard_binding = B_FALSE;
26835 
26836 	ipcl_hash_remove(connp);
26837 
26838 bind_failed:
26839 	tcp->tcp_state = TCPS_IDLE;
26840 	if (tcp->tcp_ipversion == IPV4_VERSION)
26841 		tcp->tcp_ipha->ipha_src = 0;
26842 	else
26843 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
26844 	/*
26845 	 * Copy of the src addr. in tcp_t is needed since
26846 	 * the lookup funcs. can only look at tcp_t
26847 	 */
26848 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
26849 
26850 	tcph = tcp->tcp_tcph;
26851 	tcph->th_lport[0] = 0;
26852 	tcph->th_lport[1] = 0;
26853 	tcp_bind_hash_remove(tcp);
26854 	bzero(&connp->u_port, sizeof (connp->u_port));
26855 	/* blow away saved option results if any */
26856 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
26857 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
26858 
26859 	conn_delete_ire(tcp->tcp_connp, NULL);
26860 
26861 	return (error);
26862 }
26863 
26864 static int
26865 tcp_bind_select_lport(tcp_t *tcp, in_port_t *requested_port_ptr,
26866     boolean_t bind_to_req_port_only, cred_t *cr)
26867 {
26868 	in_port_t	mlp_port;
26869 	mlp_type_t 	addrtype, mlptype;
26870 	boolean_t	user_specified;
26871 	in_port_t	allocated_port;
26872 	in_port_t	requested_port = *requested_port_ptr;
26873 	conn_t		*connp;
26874 	zone_t		*zone;
26875 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26876 	in6_addr_t	v6addr = tcp->tcp_ip_src_v6;
26877 
26878 	/*
26879 	 * XXX It's up to the caller to specify bind_to_req_port_only or not.
26880 	 */
26881 	if (cr == NULL)
26882 		cr = tcp->tcp_cred;
26883 	/*
26884 	 * Get a valid port (within the anonymous range and should not
26885 	 * be a privileged one) to use if the user has not given a port.
26886 	 * If multiple threads are here, they may all start with
26887 	 * with the same initial port. But, it should be fine as long as
26888 	 * tcp_bindi will ensure that no two threads will be assigned
26889 	 * the same port.
26890 	 *
26891 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
26892 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
26893 	 * unless TCP_ANONPRIVBIND option is set.
26894 	 */
26895 	mlptype = mlptSingle;
26896 	mlp_port = requested_port;
26897 	if (requested_port == 0) {
26898 		requested_port = tcp->tcp_anon_priv_bind ?
26899 		    tcp_get_next_priv_port(tcp) :
26900 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
26901 		    tcp, B_TRUE);
26902 		if (requested_port == 0) {
26903 			return (-TNOADDR);
26904 		}
26905 		user_specified = B_FALSE;
26906 
26907 		/*
26908 		 * If the user went through one of the RPC interfaces to create
26909 		 * this socket and RPC is MLP in this zone, then give him an
26910 		 * anonymous MLP.
26911 		 */
26912 		connp = tcp->tcp_connp;
26913 		if (connp->conn_anon_mlp && is_system_labeled()) {
26914 			zone = crgetzone(cr);
26915 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26916 			    IPV6_VERSION, &v6addr,
26917 			    tcps->tcps_netstack->netstack_ip);
26918 			if (addrtype == mlptSingle) {
26919 				return (-TNOADDR);
26920 			}
26921 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26922 			    PMAPPORT, addrtype);
26923 			mlp_port = PMAPPORT;
26924 		}
26925 	} else {
26926 		int i;
26927 		boolean_t priv = B_FALSE;
26928 
26929 		/*
26930 		 * If the requested_port is in the well-known privileged range,
26931 		 * verify that the stream was opened by a privileged user.
26932 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
26933 		 * but instead the code relies on:
26934 		 * - the fact that the address of the array and its size never
26935 		 *   changes
26936 		 * - the atomic assignment of the elements of the array
26937 		 */
26938 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
26939 			priv = B_TRUE;
26940 		} else {
26941 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
26942 				if (requested_port ==
26943 				    tcps->tcps_g_epriv_ports[i]) {
26944 					priv = B_TRUE;
26945 					break;
26946 				}
26947 			}
26948 		}
26949 		if (priv) {
26950 			if (secpolicy_net_privaddr(cr, requested_port,
26951 			    IPPROTO_TCP) != 0) {
26952 				if (tcp->tcp_debug) {
26953 					(void) strlog(TCP_MOD_ID, 0, 1,
26954 					    SL_ERROR|SL_TRACE,
26955 					    "tcp_bind: no priv for port %d",
26956 					    requested_port);
26957 				}
26958 				return (-TACCES);
26959 			}
26960 		}
26961 		user_specified = B_TRUE;
26962 
26963 		connp = tcp->tcp_connp;
26964 		if (is_system_labeled()) {
26965 			zone = crgetzone(cr);
26966 			addrtype = tsol_mlp_addr_type(zone->zone_id,
26967 			    IPV6_VERSION, &v6addr,
26968 			    tcps->tcps_netstack->netstack_ip);
26969 			if (addrtype == mlptSingle) {
26970 				return (-TNOADDR);
26971 			}
26972 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
26973 			    requested_port, addrtype);
26974 		}
26975 	}
26976 
26977 	if (mlptype != mlptSingle) {
26978 		if (secpolicy_net_bindmlp(cr) != 0) {
26979 			if (tcp->tcp_debug) {
26980 				(void) strlog(TCP_MOD_ID, 0, 1,
26981 				    SL_ERROR|SL_TRACE,
26982 				    "tcp_bind: no priv for multilevel port %d",
26983 				    requested_port);
26984 			}
26985 			return (-TACCES);
26986 		}
26987 
26988 		/*
26989 		 * If we're specifically binding a shared IP address and the
26990 		 * port is MLP on shared addresses, then check to see if this
26991 		 * zone actually owns the MLP.  Reject if not.
26992 		 */
26993 		if (mlptype == mlptShared && addrtype == mlptShared) {
26994 			/*
26995 			 * No need to handle exclusive-stack zones since
26996 			 * ALL_ZONES only applies to the shared stack.
26997 			 */
26998 			zoneid_t mlpzone;
26999 
27000 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
27001 			    htons(mlp_port));
27002 			if (connp->conn_zoneid != mlpzone) {
27003 				if (tcp->tcp_debug) {
27004 					(void) strlog(TCP_MOD_ID, 0, 1,
27005 					    SL_ERROR|SL_TRACE,
27006 					    "tcp_bind: attempt to bind port "
27007 					    "%d on shared addr in zone %d "
27008 					    "(should be %d)",
27009 					    mlp_port, connp->conn_zoneid,
27010 					    mlpzone);
27011 				}
27012 				return (-TACCES);
27013 			}
27014 		}
27015 
27016 		if (!user_specified) {
27017 			int err;
27018 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
27019 			    requested_port, B_TRUE);
27020 			if (err != 0) {
27021 				if (tcp->tcp_debug) {
27022 					(void) strlog(TCP_MOD_ID, 0, 1,
27023 					    SL_ERROR|SL_TRACE,
27024 					    "tcp_bind: cannot establish anon "
27025 					    "MLP for port %d",
27026 					    requested_port);
27027 				}
27028 				return (err);
27029 			}
27030 			connp->conn_anon_port = B_TRUE;
27031 		}
27032 		connp->conn_mlp_type = mlptype;
27033 	}
27034 
27035 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
27036 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
27037 
27038 	if (allocated_port == 0) {
27039 		connp->conn_mlp_type = mlptSingle;
27040 		if (connp->conn_anon_port) {
27041 			connp->conn_anon_port = B_FALSE;
27042 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
27043 			    requested_port, B_FALSE);
27044 		}
27045 		if (bind_to_req_port_only) {
27046 			if (tcp->tcp_debug) {
27047 				(void) strlog(TCP_MOD_ID, 0, 1,
27048 				    SL_ERROR|SL_TRACE,
27049 				    "tcp_bind: requested addr busy");
27050 			}
27051 			return (-TADDRBUSY);
27052 		} else {
27053 			/* If we are out of ports, fail the bind. */
27054 			if (tcp->tcp_debug) {
27055 				(void) strlog(TCP_MOD_ID, 0, 1,
27056 				    SL_ERROR|SL_TRACE,
27057 				    "tcp_bind: out of ports?");
27058 			}
27059 			return (-TNOADDR);
27060 		}
27061 	}
27062 
27063 	/* Pass the allocated port back */
27064 	*requested_port_ptr = allocated_port;
27065 	return (0);
27066 }
27067 
27068 static int
27069 tcp_bind_check(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27070     boolean_t bind_to_req_port_only)
27071 {
27072 	tcp_t	*tcp = connp->conn_tcp;
27073 	sin_t	*sin;
27074 	sin6_t  *sin6;
27075 	sin6_t	sin6addr;
27076 	in_port_t requested_port;
27077 	ipaddr_t	v4addr;
27078 	in6_addr_t	v6addr;
27079 	uint_t	origipversion;
27080 	int	error = 0;
27081 
27082 	ASSERT((uintptr_t)len <= (uintptr_t)INT_MAX);
27083 
27084 	if (tcp->tcp_state == TCPS_BOUND) {
27085 		return (0);
27086 	} else if (tcp->tcp_state > TCPS_BOUND) {
27087 		if (tcp->tcp_debug) {
27088 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27089 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27090 		}
27091 		return (-TOUTSTATE);
27092 	}
27093 	origipversion = tcp->tcp_ipversion;
27094 
27095 	if (sa != NULL && !OK_32PTR((char *)sa)) {
27096 		if (tcp->tcp_debug) {
27097 			(void) strlog(TCP_MOD_ID, 0, 1,
27098 			    SL_ERROR|SL_TRACE,
27099 			    "tcp_bind: bad address parameter, "
27100 			    "address %p, len %d",
27101 			    (void *)sa, len);
27102 		}
27103 		return (-TPROTO);
27104 	}
27105 
27106 	switch (len) {
27107 	case 0:		/* request for a generic port */
27108 		if (tcp->tcp_family == AF_INET) {
27109 			sin = (sin_t *)&sin6addr;
27110 			*sin = sin_null;
27111 			sin->sin_family = AF_INET;
27112 			tcp->tcp_ipversion = IPV4_VERSION;
27113 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
27114 		} else {
27115 			ASSERT(tcp->tcp_family == AF_INET6);
27116 			sin6 = (sin6_t *)&sin6addr;
27117 			*sin6 = sin6_null;
27118 			sin6->sin6_family = AF_INET6;
27119 			tcp->tcp_ipversion = IPV6_VERSION;
27120 			V6_SET_ZERO(v6addr);
27121 		}
27122 		requested_port = 0;
27123 		break;
27124 
27125 	case sizeof (sin_t):	/* Complete IPv4 address */
27126 		sin = (sin_t *)sa;
27127 		/*
27128 		 * With sockets sockfs will accept bogus sin_family in
27129 		 * bind() and replace it with the family used in the socket
27130 		 * call.
27131 		 */
27132 		if (sin->sin_family != AF_INET ||
27133 		    tcp->tcp_family != AF_INET) {
27134 			return (EAFNOSUPPORT);
27135 		}
27136 		requested_port = ntohs(sin->sin_port);
27137 		tcp->tcp_ipversion = IPV4_VERSION;
27138 		v4addr = sin->sin_addr.s_addr;
27139 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
27140 		break;
27141 
27142 	case sizeof (sin6_t): /* Complete IPv6 address */
27143 		sin6 = (sin6_t *)sa;
27144 		if (sin6->sin6_family != AF_INET6 ||
27145 		    tcp->tcp_family != AF_INET6) {
27146 			return (EAFNOSUPPORT);
27147 		}
27148 		requested_port = ntohs(sin6->sin6_port);
27149 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
27150 		    IPV4_VERSION : IPV6_VERSION;
27151 		v6addr = sin6->sin6_addr;
27152 		break;
27153 
27154 	default:
27155 		if (tcp->tcp_debug) {
27156 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27157 			    "tcp_bind: bad address length, %d", len);
27158 		}
27159 		return (EAFNOSUPPORT);
27160 		/* return (-TBADADDR); */
27161 	}
27162 
27163 	tcp->tcp_bound_source_v6 = v6addr;
27164 
27165 	/* Check for change in ipversion */
27166 	if (origipversion != tcp->tcp_ipversion) {
27167 		ASSERT(tcp->tcp_family == AF_INET6);
27168 		error = tcp->tcp_ipversion == IPV6_VERSION ?
27169 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
27170 		if (error) {
27171 			return (ENOMEM);
27172 		}
27173 	}
27174 
27175 	/*
27176 	 * Initialize family specific fields. Copy of the src addr.
27177 	 * in tcp_t is needed for the lookup funcs.
27178 	 */
27179 	if (tcp->tcp_ipversion == IPV6_VERSION) {
27180 		tcp->tcp_ip6h->ip6_src = v6addr;
27181 	} else {
27182 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
27183 	}
27184 	tcp->tcp_ip_src_v6 = v6addr;
27185 
27186 	bind_to_req_port_only = requested_port != 0 && bind_to_req_port_only;
27187 
27188 	error = tcp_bind_select_lport(tcp, &requested_port,
27189 	    bind_to_req_port_only, cr);
27190 
27191 	return (error);
27192 }
27193 
27194 /*
27195  * Return unix error is tli error is TSYSERR, otherwise return a negative
27196  * tli error.
27197  */
27198 int
27199 tcp_do_bind(conn_t *connp, struct sockaddr *sa, socklen_t len, cred_t *cr,
27200     boolean_t bind_to_req_port_only)
27201 {
27202 	int error;
27203 	tcp_t *tcp = connp->conn_tcp;
27204 
27205 	if (tcp->tcp_state >= TCPS_BOUND) {
27206 		if (tcp->tcp_debug) {
27207 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
27208 			    "tcp_bind: bad state, %d", tcp->tcp_state);
27209 		}
27210 		return (-TOUTSTATE);
27211 	}
27212 
27213 	error = tcp_bind_check(connp, sa, len, cr, bind_to_req_port_only);
27214 	if (error != 0)
27215 		return (error);
27216 
27217 	ASSERT(tcp->tcp_state == TCPS_BOUND);
27218 
27219 	tcp->tcp_conn_req_max = 0;
27220 
27221 	/*
27222 	 * We need to make sure that the conn_recv is set to a non-null
27223 	 * value before we insert the conn into the classifier table.
27224 	 * This is to avoid a race with an incoming packet which does an
27225 	 * ipcl_classify().
27226 	 */
27227 	connp->conn_recv = tcp_conn_request;
27228 
27229 	if (tcp->tcp_family == AF_INET6) {
27230 		ASSERT(tcp->tcp_connp->conn_af_isv6);
27231 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
27232 		    &tcp->tcp_bound_source_v6, 0, B_FALSE);
27233 	} else {
27234 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
27235 		error = ip_proto_bind_laddr_v4(connp, NULL, IPPROTO_TCP,
27236 		    tcp->tcp_ipha->ipha_src, 0, B_FALSE);
27237 	}
27238 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
27239 }
27240 
27241 int
27242 tcp_bind(sock_lower_handle_t proto_handle, struct sockaddr *sa,
27243     socklen_t len, cred_t *cr)
27244 {
27245 	int 		error;
27246 	conn_t		*connp = (conn_t *)proto_handle;
27247 	squeue_t	*sqp = connp->conn_sqp;
27248 
27249 	/* All Solaris components should pass a cred for this operation. */
27250 	ASSERT(cr != NULL);
27251 
27252 	ASSERT(sqp != NULL);
27253 	ASSERT(connp->conn_upper_handle != NULL);
27254 
27255 	error = squeue_synch_enter(sqp, connp, 0);
27256 	if (error != 0) {
27257 		/* failed to enter */
27258 		return (ENOSR);
27259 	}
27260 
27261 	/* binding to a NULL address really means unbind */
27262 	if (sa == NULL) {
27263 		if (connp->conn_tcp->tcp_state < TCPS_LISTEN)
27264 			error = tcp_do_unbind(connp);
27265 		else
27266 			error = EINVAL;
27267 	} else {
27268 		error = tcp_do_bind(connp, sa, len, cr, B_TRUE);
27269 	}
27270 
27271 	squeue_synch_exit(sqp, connp);
27272 
27273 	if (error < 0) {
27274 		if (error == -TOUTSTATE)
27275 			error = EINVAL;
27276 		else
27277 			error = proto_tlitosyserr(-error);
27278 	}
27279 
27280 	return (error);
27281 }
27282 
27283 /*
27284  * If the return value from this function is positive, it's a UNIX error.
27285  * Otherwise, if it's negative, then the absolute value is a TLI error.
27286  * the TPI routine tcp_tpi_connect() is a wrapper function for this.
27287  */
27288 int
27289 tcp_do_connect(conn_t *connp, const struct sockaddr *sa, socklen_t len,
27290     cred_t *cr, pid_t pid)
27291 {
27292 	tcp_t		*tcp = connp->conn_tcp;
27293 	sin_t		*sin = (sin_t *)sa;
27294 	sin6_t		*sin6 = (sin6_t *)sa;
27295 	ipaddr_t	*dstaddrp;
27296 	in_port_t	dstport;
27297 	uint_t		srcid;
27298 	int		error = 0;
27299 
27300 	switch (len) {
27301 	default:
27302 		/*
27303 		 * Should never happen
27304 		 */
27305 		return (EINVAL);
27306 
27307 	case sizeof (sin_t):
27308 		sin = (sin_t *)sa;
27309 		if (sin->sin_port == 0) {
27310 			return (-TBADADDR);
27311 		}
27312 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
27313 			return (EAFNOSUPPORT);
27314 		}
27315 		break;
27316 
27317 	case sizeof (sin6_t):
27318 		sin6 = (sin6_t *)sa;
27319 		if (sin6->sin6_port == 0) {
27320 			return (-TBADADDR);
27321 		}
27322 		break;
27323 	}
27324 	/*
27325 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
27326 	 * make sure that the template IP header in the tcp structure is an
27327 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
27328 	 * need to this before we call tcp_bindi() so that the port lookup
27329 	 * code will look for ports in the correct port space (IPv4 and
27330 	 * IPv6 have separate port spaces).
27331 	 */
27332 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
27333 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27334 		int err = 0;
27335 
27336 		err = tcp_header_init_ipv4(tcp);
27337 			if (err != 0) {
27338 				error = ENOMEM;
27339 				goto connect_failed;
27340 			}
27341 		if (tcp->tcp_lport != 0)
27342 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
27343 	}
27344 
27345 	switch (tcp->tcp_state) {
27346 	case TCPS_LISTEN:
27347 		/*
27348 		 * Listening sockets are not allowed to issue connect().
27349 		 */
27350 		if (IPCL_IS_NONSTR(connp))
27351 			return (EOPNOTSUPP);
27352 		/* FALLTHRU */
27353 	case TCPS_IDLE:
27354 		/*
27355 		 * We support quick connect, refer to comments in
27356 		 * tcp_connect_*()
27357 		 */
27358 		/* FALLTHRU */
27359 	case TCPS_BOUND:
27360 		/*
27361 		 * We must bump the generation before the operation start.
27362 		 * This is done to ensure that any upcall made later on sends
27363 		 * up the right generation to the socket.
27364 		 */
27365 		SOCK_CONNID_BUMP(tcp->tcp_connid);
27366 
27367 		if (tcp->tcp_family == AF_INET6) {
27368 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
27369 				return (tcp_connect_ipv6(tcp,
27370 				    &sin6->sin6_addr,
27371 				    sin6->sin6_port, sin6->sin6_flowinfo,
27372 				    sin6->__sin6_src_id, sin6->sin6_scope_id,
27373 				    cr, pid));
27374 			}
27375 			/*
27376 			 * Destination adress is mapped IPv6 address.
27377 			 * Source bound address should be unspecified or
27378 			 * IPv6 mapped address as well.
27379 			 */
27380 			if (!IN6_IS_ADDR_UNSPECIFIED(
27381 			    &tcp->tcp_bound_source_v6) &&
27382 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
27383 				return (EADDRNOTAVAIL);
27384 			}
27385 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
27386 			dstport = sin6->sin6_port;
27387 			srcid = sin6->__sin6_src_id;
27388 		} else {
27389 			dstaddrp = &sin->sin_addr.s_addr;
27390 			dstport = sin->sin_port;
27391 			srcid = 0;
27392 		}
27393 
27394 		error = tcp_connect_ipv4(tcp, dstaddrp, dstport, srcid, cr,
27395 		    pid);
27396 		break;
27397 	default:
27398 		return (-TOUTSTATE);
27399 	}
27400 	/*
27401 	 * Note: Code below is the "failure" case
27402 	 */
27403 connect_failed:
27404 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
27405 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
27406 	return (error);
27407 }
27408 
27409 int
27410 tcp_connect(sock_lower_handle_t proto_handle, const struct sockaddr *sa,
27411     socklen_t len, sock_connid_t *id, cred_t *cr)
27412 {
27413 	conn_t		*connp = (conn_t *)proto_handle;
27414 	tcp_t		*tcp = connp->conn_tcp;
27415 	squeue_t	*sqp = connp->conn_sqp;
27416 	int		error;
27417 
27418 	ASSERT(connp->conn_upper_handle != NULL);
27419 
27420 	/* All Solaris components should pass a cred for this operation. */
27421 	ASSERT(cr != NULL);
27422 
27423 	error = proto_verify_ip_addr(tcp->tcp_family, sa, len);
27424 	if (error != 0) {
27425 		return (error);
27426 	}
27427 
27428 	error = squeue_synch_enter(sqp, connp, 0);
27429 	if (error != 0) {
27430 		/* failed to enter */
27431 		return (ENOSR);
27432 	}
27433 
27434 	/*
27435 	 * TCP supports quick connect, so no need to do an implicit bind
27436 	 */
27437 	error = tcp_do_connect(connp, sa, len, cr, curproc->p_pid);
27438 	if (error == 0) {
27439 		*id = connp->conn_tcp->tcp_connid;
27440 	} else if (error < 0) {
27441 		if (error == -TOUTSTATE) {
27442 			switch (connp->conn_tcp->tcp_state) {
27443 			case TCPS_SYN_SENT:
27444 				error = EALREADY;
27445 				break;
27446 			case TCPS_ESTABLISHED:
27447 				error = EISCONN;
27448 				break;
27449 			case TCPS_LISTEN:
27450 				error = EOPNOTSUPP;
27451 				break;
27452 			default:
27453 				error = EINVAL;
27454 				break;
27455 			}
27456 		} else {
27457 			error = proto_tlitosyserr(-error);
27458 		}
27459 	}
27460 done:
27461 	squeue_synch_exit(sqp, connp);
27462 
27463 	return ((error == 0) ? EINPROGRESS : error);
27464 }
27465 
27466 /* ARGSUSED */
27467 sock_lower_handle_t
27468 tcp_create(int family, int type, int proto, sock_downcalls_t **sock_downcalls,
27469     uint_t *smodep, int *errorp, int flags, cred_t *credp)
27470 {
27471 	conn_t		*connp;
27472 	boolean_t	isv6 = family == AF_INET6;
27473 	if (type != SOCK_STREAM || (family != AF_INET && family != AF_INET6) ||
27474 	    (proto != 0 && proto != IPPROTO_TCP)) {
27475 		*errorp = EPROTONOSUPPORT;
27476 		return (NULL);
27477 	}
27478 
27479 	connp = tcp_create_common(NULL, credp, isv6, B_TRUE, errorp);
27480 	if (connp == NULL) {
27481 		return (NULL);
27482 	}
27483 
27484 	/*
27485 	 * Put the ref for TCP. Ref for IP was already put
27486 	 * by ipcl_conn_create. Also Make the conn_t globally
27487 	 * visible to walkers
27488 	 */
27489 	mutex_enter(&connp->conn_lock);
27490 	CONN_INC_REF_LOCKED(connp);
27491 	ASSERT(connp->conn_ref == 2);
27492 	connp->conn_state_flags &= ~CONN_INCIPIENT;
27493 
27494 	connp->conn_flags |= IPCL_NONSTR;
27495 	mutex_exit(&connp->conn_lock);
27496 
27497 	ASSERT(errorp != NULL);
27498 	*errorp = 0;
27499 	*sock_downcalls = &sock_tcp_downcalls;
27500 	*smodep = SM_CONNREQUIRED | SM_EXDATA | SM_ACCEPTSUPP |
27501 	    SM_SENDFILESUPP;
27502 
27503 	return ((sock_lower_handle_t)connp);
27504 }
27505 
27506 /* ARGSUSED */
27507 void
27508 tcp_activate(sock_lower_handle_t proto_handle, sock_upper_handle_t sock_handle,
27509     sock_upcalls_t *sock_upcalls, int flags, cred_t *cr)
27510 {
27511 	conn_t *connp = (conn_t *)proto_handle;
27512 	struct sock_proto_props sopp;
27513 
27514 	ASSERT(connp->conn_upper_handle == NULL);
27515 
27516 	/* All Solaris components should pass a cred for this operation. */
27517 	ASSERT(cr != NULL);
27518 
27519 	sopp.sopp_flags = SOCKOPT_RCVHIWAT | SOCKOPT_RCVLOWAT |
27520 	    SOCKOPT_MAXPSZ | SOCKOPT_MAXBLK | SOCKOPT_RCVTIMER |
27521 	    SOCKOPT_RCVTHRESH | SOCKOPT_MAXADDRLEN | SOCKOPT_MINPSZ;
27522 
27523 	sopp.sopp_rxhiwat = SOCKET_RECVHIWATER;
27524 	sopp.sopp_rxlowat = SOCKET_RECVLOWATER;
27525 	sopp.sopp_maxpsz = INFPSZ;
27526 	sopp.sopp_maxblk = INFPSZ;
27527 	sopp.sopp_rcvtimer = SOCKET_TIMER_INTERVAL;
27528 	sopp.sopp_rcvthresh = SOCKET_RECVHIWATER >> 3;
27529 	sopp.sopp_maxaddrlen = sizeof (sin6_t);
27530 	sopp.sopp_minpsz = (tcp_rinfo.mi_minpsz == 1) ? 0 :
27531 	    tcp_rinfo.mi_minpsz;
27532 
27533 	connp->conn_upcalls = sock_upcalls;
27534 	connp->conn_upper_handle = sock_handle;
27535 
27536 	(*sock_upcalls->su_set_proto_props)(sock_handle, &sopp);
27537 }
27538 
27539 /* ARGSUSED */
27540 int
27541 tcp_close(sock_lower_handle_t proto_handle, int flags, cred_t *cr)
27542 {
27543 	conn_t *connp = (conn_t *)proto_handle;
27544 
27545 	ASSERT(connp->conn_upper_handle != NULL);
27546 
27547 	/* All Solaris components should pass a cred for this operation. */
27548 	ASSERT(cr != NULL);
27549 
27550 	tcp_close_common(connp, flags);
27551 
27552 	ip_free_helper_stream(connp);
27553 
27554 	/*
27555 	 * Drop IP's reference on the conn. This is the last reference
27556 	 * on the connp if the state was less than established. If the
27557 	 * connection has gone into timewait state, then we will have
27558 	 * one ref for the TCP and one more ref (total of two) for the
27559 	 * classifier connected hash list (a timewait connections stays
27560 	 * in connected hash till closed).
27561 	 *
27562 	 * We can't assert the references because there might be other
27563 	 * transient reference places because of some walkers or queued
27564 	 * packets in squeue for the timewait state.
27565 	 */
27566 	CONN_DEC_REF(connp);
27567 	return (0);
27568 }
27569 
27570 /* ARGSUSED */
27571 int
27572 tcp_sendmsg(sock_lower_handle_t proto_handle, mblk_t *mp, struct nmsghdr *msg,
27573     cred_t *cr)
27574 {
27575 	tcp_t		*tcp;
27576 	uint32_t	msize;
27577 	conn_t *connp = (conn_t *)proto_handle;
27578 	int32_t		tcpstate;
27579 
27580 	/* All Solaris components should pass a cred for this operation. */
27581 	ASSERT(cr != NULL);
27582 
27583 	ASSERT(connp->conn_ref >= 2);
27584 	ASSERT(connp->conn_upper_handle != NULL);
27585 
27586 	if (msg->msg_controllen != 0) {
27587 		return (EOPNOTSUPP);
27588 
27589 	}
27590 	switch (DB_TYPE(mp)) {
27591 	case M_DATA:
27592 		tcp = connp->conn_tcp;
27593 		ASSERT(tcp != NULL);
27594 
27595 		tcpstate = tcp->tcp_state;
27596 		if (tcpstate < TCPS_ESTABLISHED) {
27597 			freemsg(mp);
27598 			return (ENOTCONN);
27599 		} else if (tcpstate > TCPS_CLOSE_WAIT) {
27600 			freemsg(mp);
27601 			return (EPIPE);
27602 		}
27603 
27604 		msize = msgdsize(mp);
27605 
27606 		mutex_enter(&tcp->tcp_non_sq_lock);
27607 		tcp->tcp_squeue_bytes += msize;
27608 		/*
27609 		 * Squeue Flow Control
27610 		 */
27611 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
27612 			tcp_setqfull(tcp);
27613 		}
27614 		mutex_exit(&tcp->tcp_non_sq_lock);
27615 
27616 		/*
27617 		 * The application may pass in an address in the msghdr, but
27618 		 * we ignore the address on connection-oriented sockets.
27619 		 * Just like BSD this code does not generate an error for
27620 		 * TCP (a CONNREQUIRED socket) when sending to an address
27621 		 * passed in with sendto/sendmsg. Instead the data is
27622 		 * delivered on the connection as if no address had been
27623 		 * supplied.
27624 		 */
27625 		CONN_INC_REF(connp);
27626 
27627 		if (msg != NULL && msg->msg_flags & MSG_OOB) {
27628 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
27629 			    tcp_output_urgent, connp, tcp_squeue_flag,
27630 			    SQTAG_TCP_OUTPUT);
27631 		} else {
27632 			SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_output,
27633 			    connp, tcp_squeue_flag, SQTAG_TCP_OUTPUT);
27634 		}
27635 
27636 		return (0);
27637 
27638 	default:
27639 		ASSERT(0);
27640 	}
27641 
27642 	freemsg(mp);
27643 	return (0);
27644 }
27645 
27646 /* ARGSUSED */
27647 void
27648 tcp_output_urgent(void *arg, mblk_t *mp, void *arg2)
27649 {
27650 	int len;
27651 	uint32_t msize;
27652 	conn_t *connp = (conn_t *)arg;
27653 	tcp_t *tcp = connp->conn_tcp;
27654 
27655 	msize = msgdsize(mp);
27656 
27657 	len = msize - 1;
27658 	if (len < 0) {
27659 		freemsg(mp);
27660 		return;
27661 	}
27662 
27663 	/*
27664 	 * Try to force urgent data out on the wire.
27665 	 * Even if we have unsent data this will
27666 	 * at least send the urgent flag.
27667 	 * XXX does not handle more flag correctly.
27668 	 */
27669 	len += tcp->tcp_unsent;
27670 	len += tcp->tcp_snxt;
27671 	tcp->tcp_urg = len;
27672 	tcp->tcp_valid_bits |= TCP_URG_VALID;
27673 
27674 	/* Bypass tcp protocol for fused tcp loopback */
27675 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
27676 		return;
27677 	tcp_wput_data(tcp, mp, B_TRUE);
27678 }
27679 
27680 /* ARGSUSED */
27681 int
27682 tcp_getpeername(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27683     socklen_t *addrlenp, cred_t *cr)
27684 {
27685 	conn_t	*connp = (conn_t *)proto_handle;
27686 	tcp_t	*tcp = connp->conn_tcp;
27687 
27688 	ASSERT(connp->conn_upper_handle != NULL);
27689 	/* All Solaris components should pass a cred for this operation. */
27690 	ASSERT(cr != NULL);
27691 
27692 	ASSERT(tcp != NULL);
27693 
27694 	return (tcp_do_getpeername(tcp, addr, addrlenp));
27695 }
27696 
27697 /* ARGSUSED */
27698 int
27699 tcp_getsockname(sock_lower_handle_t proto_handle, struct sockaddr *addr,
27700     socklen_t *addrlenp, cred_t *cr)
27701 {
27702 	conn_t	*connp = (conn_t *)proto_handle;
27703 	tcp_t	*tcp = connp->conn_tcp;
27704 
27705 	/* All Solaris components should pass a cred for this operation. */
27706 	ASSERT(cr != NULL);
27707 
27708 	ASSERT(connp->conn_upper_handle != NULL);
27709 
27710 	return (tcp_do_getsockname(tcp, addr, addrlenp));
27711 }
27712 
27713 /*
27714  * tcp_fallback
27715  *
27716  * A direct socket is falling back to using STREAMS. The queue
27717  * that is being passed down was created using tcp_open() with
27718  * the SO_FALLBACK flag set. As a result, the queue is not
27719  * associated with a conn, and the q_ptrs instead contain the
27720  * dev and minor area that should be used.
27721  *
27722  * The 'direct_sockfs' flag indicates whether the FireEngine
27723  * optimizations should be used. The common case would be that
27724  * optimizations are enabled, and they might be subsequently
27725  * disabled using the _SIOCSOCKFALLBACK ioctl.
27726  */
27727 
27728 /*
27729  * An active connection is falling back to TPI. Gather all the information
27730  * required by the STREAM head and TPI sonode and send it up.
27731  */
27732 void
27733 tcp_fallback_noneager(tcp_t *tcp, mblk_t *stropt_mp, queue_t *q,
27734     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27735 {
27736 	conn_t			*connp = tcp->tcp_connp;
27737 	struct stroptions	*stropt;
27738 	struct T_capability_ack tca;
27739 	struct sockaddr_in6	laddr, faddr;
27740 	socklen_t 		laddrlen, faddrlen;
27741 	short			opts;
27742 	int			error;
27743 	mblk_t			*mp;
27744 
27745 	/* Disable I/OAT during fallback */
27746 	tcp->tcp_sodirect = NULL;
27747 
27748 	connp->conn_dev = (dev_t)RD(q)->q_ptr;
27749 	connp->conn_minor_arena = WR(q)->q_ptr;
27750 
27751 	RD(q)->q_ptr = WR(q)->q_ptr = connp;
27752 
27753 	connp->conn_tcp->tcp_rq = connp->conn_rq = RD(q);
27754 	connp->conn_tcp->tcp_wq = connp->conn_wq = WR(q);
27755 
27756 	WR(q)->q_qinfo = &tcp_sock_winit;
27757 
27758 	if (!direct_sockfs)
27759 		tcp_disable_direct_sockfs(tcp);
27760 
27761 	/*
27762 	 * free the helper stream
27763 	 */
27764 	ip_free_helper_stream(connp);
27765 
27766 	/*
27767 	 * Notify the STREAM head about options
27768 	 */
27769 	DB_TYPE(stropt_mp) = M_SETOPTS;
27770 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27771 	stropt_mp->b_wptr += sizeof (struct stroptions);
27772 	stropt = (struct stroptions *)stropt_mp->b_rptr;
27773 	stropt->so_flags |= SO_HIWAT | SO_WROFF | SO_MAXBLK;
27774 
27775 	stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
27776 	    tcp->tcp_tcps->tcps_wroff_xtra);
27777 	if (tcp->tcp_snd_sack_ok)
27778 		stropt->so_wroff += TCPOPT_MAX_SACK_LEN;
27779 	stropt->so_hiwat = tcp->tcp_fused ?
27780 	    tcp_fuse_set_rcv_hiwat(tcp, tcp->tcp_recv_hiwater) :
27781 	    MAX(tcp->tcp_recv_hiwater, tcp->tcp_tcps->tcps_sth_rcv_hiwat);
27782 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
27783 
27784 	putnext(RD(q), stropt_mp);
27785 
27786 	/*
27787 	 * Collect the information needed to sync with the sonode
27788 	 */
27789 	tcp_do_capability_ack(tcp, &tca, TC1_INFO|TC1_ACCEPTOR_ID);
27790 
27791 	laddrlen = faddrlen = sizeof (sin6_t);
27792 	(void) tcp_do_getsockname(tcp, (struct sockaddr *)&laddr, &laddrlen);
27793 	error = tcp_do_getpeername(tcp, (struct sockaddr *)&faddr, &faddrlen);
27794 	if (error != 0)
27795 		faddrlen = 0;
27796 
27797 	opts = 0;
27798 	if (tcp->tcp_oobinline)
27799 		opts |= SO_OOBINLINE;
27800 	if (tcp->tcp_dontroute)
27801 		opts |= SO_DONTROUTE;
27802 
27803 	/*
27804 	 * Notify the socket that the protocol is now quiescent,
27805 	 * and it's therefore safe move data from the socket
27806 	 * to the stream head.
27807 	 */
27808 	(*quiesced_cb)(connp->conn_upper_handle, q, &tca,
27809 	    (struct sockaddr *)&laddr, laddrlen,
27810 	    (struct sockaddr *)&faddr, faddrlen, opts);
27811 
27812 	while ((mp = tcp->tcp_rcv_list) != NULL) {
27813 		tcp->tcp_rcv_list = mp->b_next;
27814 		mp->b_next = NULL;
27815 		putnext(q, mp);
27816 	}
27817 	tcp->tcp_rcv_last_head = NULL;
27818 	tcp->tcp_rcv_last_tail = NULL;
27819 	tcp->tcp_rcv_cnt = 0;
27820 }
27821 
27822 /*
27823  * An eager is falling back to TPI. All we have to do is send
27824  * up a T_CONN_IND.
27825  */
27826 void
27827 tcp_fallback_eager(tcp_t *eager, boolean_t direct_sockfs)
27828 {
27829 	tcp_t *listener = eager->tcp_listener;
27830 	mblk_t *mp = eager->tcp_conn.tcp_eager_conn_ind;
27831 
27832 	ASSERT(listener != NULL);
27833 	ASSERT(mp != NULL);
27834 
27835 	eager->tcp_conn.tcp_eager_conn_ind = NULL;
27836 
27837 	/*
27838 	 * TLI/XTI applications will get confused by
27839 	 * sending eager as an option since it violates
27840 	 * the option semantics. So remove the eager as
27841 	 * option since TLI/XTI app doesn't need it anyway.
27842 	 */
27843 	if (!direct_sockfs) {
27844 		struct T_conn_ind *conn_ind;
27845 
27846 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
27847 		conn_ind->OPT_length = 0;
27848 		conn_ind->OPT_offset = 0;
27849 	}
27850 
27851 	/*
27852 	 * Sockfs guarantees that the listener will not be closed
27853 	 * during fallback. So we can safely use the listener's queue.
27854 	 */
27855 	putnext(listener->tcp_rq, mp);
27856 }
27857 
27858 int
27859 tcp_fallback(sock_lower_handle_t proto_handle, queue_t *q,
27860     boolean_t direct_sockfs, so_proto_quiesced_cb_t quiesced_cb)
27861 {
27862 	tcp_t			*tcp;
27863 	conn_t 			*connp = (conn_t *)proto_handle;
27864 	int			error;
27865 	mblk_t			*stropt_mp;
27866 	mblk_t			*ordrel_mp;
27867 	mblk_t			*fused_sigurp_mp;
27868 
27869 	tcp = connp->conn_tcp;
27870 
27871 	stropt_mp = allocb_wait(sizeof (struct stroptions), BPRI_HI, STR_NOSIG,
27872 	    NULL);
27873 
27874 	/* Pre-allocate the T_ordrel_ind mblk. */
27875 	ASSERT(tcp->tcp_ordrel_mp == NULL);
27876 	ordrel_mp = allocb_wait(sizeof (struct T_ordrel_ind), BPRI_HI,
27877 	    STR_NOSIG, NULL);
27878 	ordrel_mp->b_datap->db_type = M_PROTO;
27879 	((struct T_ordrel_ind *)ordrel_mp->b_rptr)->PRIM_type = T_ORDREL_IND;
27880 	ordrel_mp->b_wptr += sizeof (struct T_ordrel_ind);
27881 
27882 	/* Pre-allocate the M_PCSIG used by fusion */
27883 	fused_sigurp_mp = allocb_wait(1, BPRI_HI, STR_NOSIG, NULL);
27884 
27885 	/*
27886 	 * Enter the squeue so that no new packets can come in
27887 	 */
27888 	error = squeue_synch_enter(connp->conn_sqp, connp, 0);
27889 	if (error != 0) {
27890 		/* failed to enter, free all the pre-allocated messages. */
27891 		freeb(stropt_mp);
27892 		freeb(ordrel_mp);
27893 		freeb(fused_sigurp_mp);
27894 		/*
27895 		 * We cannot process the eager, so at least send out a
27896 		 * RST so the peer can reconnect.
27897 		 */
27898 		if (tcp->tcp_listener != NULL) {
27899 			(void) tcp_eager_blowoff(tcp->tcp_listener,
27900 			    tcp->tcp_conn_req_seqnum);
27901 		}
27902 		return (ENOMEM);
27903 	}
27904 
27905 	/*
27906 	 * No longer a direct socket
27907 	 */
27908 	connp->conn_flags &= ~IPCL_NONSTR;
27909 
27910 	tcp->tcp_ordrel_mp = ordrel_mp;
27911 
27912 	if (tcp->tcp_fused) {
27913 		ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
27914 		tcp->tcp_fused_sigurg_mp = fused_sigurp_mp;
27915 	} else {
27916 		freeb(fused_sigurp_mp);
27917 	}
27918 
27919 	if (tcp->tcp_listener != NULL) {
27920 		/* The eager will deal with opts when accept() is called */
27921 		freeb(stropt_mp);
27922 		tcp_fallback_eager(tcp, direct_sockfs);
27923 	} else {
27924 		tcp_fallback_noneager(tcp, stropt_mp, q, direct_sockfs,
27925 		    quiesced_cb);
27926 	}
27927 
27928 	/*
27929 	 * There should be atleast two ref's (IP + TCP)
27930 	 */
27931 	ASSERT(connp->conn_ref >= 2);
27932 	squeue_synch_exit(connp->conn_sqp, connp);
27933 
27934 	return (0);
27935 }
27936 
27937 /* ARGSUSED */
27938 static void
27939 tcp_shutdown_output(void *arg, mblk_t *mp, void *arg2)
27940 {
27941 	conn_t 	*connp = (conn_t *)arg;
27942 	tcp_t	*tcp = connp->conn_tcp;
27943 
27944 	freemsg(mp);
27945 
27946 	if (tcp->tcp_fused)
27947 		tcp_unfuse(tcp);
27948 
27949 	if (tcp_xmit_end(tcp) != 0) {
27950 		/*
27951 		 * We were crossing FINs and got a reset from
27952 		 * the other side. Just ignore it.
27953 		 */
27954 		if (tcp->tcp_debug) {
27955 			(void) strlog(TCP_MOD_ID, 0, 1,
27956 			    SL_ERROR|SL_TRACE,
27957 			    "tcp_shutdown_output() out of state %s",
27958 			    tcp_display(tcp, NULL, DISP_ADDR_AND_PORT));
27959 		}
27960 	}
27961 }
27962 
27963 /* ARGSUSED */
27964 int
27965 tcp_shutdown(sock_lower_handle_t proto_handle, int how, cred_t *cr)
27966 {
27967 	conn_t  *connp = (conn_t *)proto_handle;
27968 	tcp_t   *tcp = connp->conn_tcp;
27969 
27970 	ASSERT(connp->conn_upper_handle != NULL);
27971 
27972 	/* All Solaris components should pass a cred for this operation. */
27973 	ASSERT(cr != NULL);
27974 
27975 	/*
27976 	 * X/Open requires that we check the connected state.
27977 	 */
27978 	if (tcp->tcp_state < TCPS_SYN_SENT)
27979 		return (ENOTCONN);
27980 
27981 	/* shutdown the send side */
27982 	if (how != SHUT_RD) {
27983 		mblk_t *bp;
27984 
27985 		bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
27986 		CONN_INC_REF(connp);
27987 		SQUEUE_ENTER_ONE(connp->conn_sqp, bp, tcp_shutdown_output,
27988 		    connp, SQ_NODRAIN, SQTAG_TCP_SHUTDOWN_OUTPUT);
27989 
27990 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27991 		    SOCK_OPCTL_SHUT_SEND, 0);
27992 	}
27993 
27994 	/* shutdown the recv side */
27995 	if (how != SHUT_WR)
27996 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
27997 		    SOCK_OPCTL_SHUT_RECV, 0);
27998 
27999 	return (0);
28000 }
28001 
28002 /*
28003  * SOP_LISTEN() calls into tcp_listen().
28004  */
28005 /* ARGSUSED */
28006 int
28007 tcp_listen(sock_lower_handle_t proto_handle, int backlog, cred_t *cr)
28008 {
28009 	conn_t	*connp = (conn_t *)proto_handle;
28010 	int 	error;
28011 	squeue_t *sqp = connp->conn_sqp;
28012 
28013 	ASSERT(connp->conn_upper_handle != NULL);
28014 
28015 	/* All Solaris components should pass a cred for this operation. */
28016 	ASSERT(cr != NULL);
28017 
28018 	error = squeue_synch_enter(sqp, connp, 0);
28019 	if (error != 0) {
28020 		/* failed to enter */
28021 		return (ENOBUFS);
28022 	}
28023 
28024 	error = tcp_do_listen(connp, backlog, cr);
28025 	if (error == 0) {
28026 		(*connp->conn_upcalls->su_opctl)(connp->conn_upper_handle,
28027 		    SOCK_OPCTL_ENAB_ACCEPT, (uintptr_t)backlog);
28028 	} else if (error < 0) {
28029 		if (error == -TOUTSTATE)
28030 			error = EINVAL;
28031 		else
28032 			error = proto_tlitosyserr(-error);
28033 	}
28034 	squeue_synch_exit(sqp, connp);
28035 	return (error);
28036 }
28037 
28038 static int
28039 tcp_do_listen(conn_t *connp, int backlog, cred_t *cr)
28040 {
28041 	tcp_t		*tcp = connp->conn_tcp;
28042 	sin_t		*sin;
28043 	sin6_t  	*sin6;
28044 	int		error = 0;
28045 	tcp_stack_t	*tcps = tcp->tcp_tcps;
28046 
28047 	/* All Solaris components should pass a cred for this operation. */
28048 	ASSERT(cr != NULL);
28049 
28050 	if (tcp->tcp_state >= TCPS_BOUND) {
28051 		if ((tcp->tcp_state == TCPS_BOUND ||
28052 		    tcp->tcp_state == TCPS_LISTEN) && backlog > 0) {
28053 			/*
28054 			 * Handle listen() increasing backlog.
28055 			 * This is more "liberal" then what the TPI spec
28056 			 * requires but is needed to avoid a t_unbind
28057 			 * when handling listen() since the port number
28058 			 * might be "stolen" between the unbind and bind.
28059 			 */
28060 			goto do_listen;
28061 		}
28062 		if (tcp->tcp_debug) {
28063 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
28064 			    "tcp_listen: bad state, %d", tcp->tcp_state);
28065 		}
28066 		return (-TOUTSTATE);
28067 	} else {
28068 		int32_t len;
28069 		sin6_t	addr;
28070 
28071 		/* Do an implicit bind: Request for a generic port. */
28072 		if (tcp->tcp_family == AF_INET) {
28073 			len = sizeof (sin_t);
28074 			sin = (sin_t *)&addr;
28075 			*sin = sin_null;
28076 			sin->sin_family = AF_INET;
28077 			tcp->tcp_ipversion = IPV4_VERSION;
28078 		} else {
28079 			ASSERT(tcp->tcp_family == AF_INET6);
28080 			len = sizeof (sin6_t);
28081 			sin6 = (sin6_t *)&addr;
28082 			*sin6 = sin6_null;
28083 			sin6->sin6_family = AF_INET6;
28084 			tcp->tcp_ipversion = IPV6_VERSION;
28085 		}
28086 
28087 		error = tcp_bind_check(connp, (struct sockaddr *)&addr, len,
28088 		    cr, B_FALSE);
28089 		if (error)
28090 			return (error);
28091 		/* Fall through and do the fanout insertion */
28092 	}
28093 
28094 do_listen:
28095 	ASSERT(tcp->tcp_state == TCPS_BOUND || tcp->tcp_state == TCPS_LISTEN);
28096 	tcp->tcp_conn_req_max = backlog;
28097 	if (tcp->tcp_conn_req_max) {
28098 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
28099 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
28100 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
28101 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
28102 		/*
28103 		 * If this is a listener, do not reset the eager list
28104 		 * and other stuffs.  Note that we don't check if the
28105 		 * existing eager list meets the new tcp_conn_req_max
28106 		 * requirement.
28107 		 */
28108 		if (tcp->tcp_state != TCPS_LISTEN) {
28109 			tcp->tcp_state = TCPS_LISTEN;
28110 			/* Initialize the chain. Don't need the eager_lock */
28111 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
28112 			tcp->tcp_eager_next_drop_q0 = tcp;
28113 			tcp->tcp_eager_prev_drop_q0 = tcp;
28114 			tcp->tcp_second_ctimer_threshold =
28115 			    tcps->tcps_ip_abort_linterval;
28116 		}
28117 	}
28118 
28119 	/*
28120 	 * We can call ip_bind directly, the processing continues
28121 	 * in tcp_post_ip_bind().
28122 	 *
28123 	 * We need to make sure that the conn_recv is set to a non-null
28124 	 * value before we insert the conn into the classifier table.
28125 	 * This is to avoid a race with an incoming packet which does an
28126 	 * ipcl_classify().
28127 	 */
28128 	connp->conn_recv = tcp_conn_request;
28129 	if (tcp->tcp_family == AF_INET) {
28130 		error = ip_proto_bind_laddr_v4(connp, NULL,
28131 		    IPPROTO_TCP, tcp->tcp_bound_source, tcp->tcp_lport, B_TRUE);
28132 	} else {
28133 		error = ip_proto_bind_laddr_v6(connp, NULL, IPPROTO_TCP,
28134 		    &tcp->tcp_bound_source_v6, tcp->tcp_lport, B_TRUE);
28135 	}
28136 	return (tcp_post_ip_bind(tcp, NULL, error, NULL, 0));
28137 }
28138 
28139 void
28140 tcp_clr_flowctrl(sock_lower_handle_t proto_handle)
28141 {
28142 	conn_t  *connp = (conn_t *)proto_handle;
28143 	tcp_t	*tcp = connp->conn_tcp;
28144 	tcp_stack_t	*tcps = tcp->tcp_tcps;
28145 	uint_t thwin;
28146 
28147 	ASSERT(connp->conn_upper_handle != NULL);
28148 
28149 	(void) squeue_synch_enter(connp->conn_sqp, connp, 0);
28150 
28151 	/* Flow control condition has been removed. */
28152 	tcp->tcp_rwnd = tcp->tcp_recv_hiwater;
28153 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
28154 	    << tcp->tcp_rcv_ws;
28155 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
28156 	/*
28157 	 * Send back a window update immediately if TCP is above
28158 	 * ESTABLISHED state and the increase of the rcv window
28159 	 * that the other side knows is at least 1 MSS after flow
28160 	 * control is lifted.
28161 	 */
28162 	if (tcp->tcp_state >= TCPS_ESTABLISHED &&
28163 	    (tcp->tcp_recv_hiwater - thwin >= tcp->tcp_mss)) {
28164 		tcp_xmit_ctl(NULL, tcp,
28165 		    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
28166 		    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
28167 		BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
28168 	}
28169 
28170 	squeue_synch_exit(connp->conn_sqp, connp);
28171 }
28172 
28173 /* ARGSUSED */
28174 int
28175 tcp_ioctl(sock_lower_handle_t proto_handle, int cmd, intptr_t arg,
28176     int mode, int32_t *rvalp, cred_t *cr)
28177 {
28178 	conn_t  	*connp = (conn_t *)proto_handle;
28179 	int		error;
28180 
28181 	ASSERT(connp->conn_upper_handle != NULL);
28182 
28183 	/* All Solaris components should pass a cred for this operation. */
28184 	ASSERT(cr != NULL);
28185 
28186 	switch (cmd) {
28187 		case ND_SET:
28188 		case ND_GET:
28189 		case TCP_IOC_DEFAULT_Q:
28190 		case _SIOCSOCKFALLBACK:
28191 		case TCP_IOC_ABORT_CONN:
28192 		case TI_GETPEERNAME:
28193 		case TI_GETMYNAME:
28194 			ip1dbg(("tcp_ioctl: cmd 0x%x on non sreams socket",
28195 			    cmd));
28196 			error = EINVAL;
28197 			break;
28198 		default:
28199 			/*
28200 			 * Pass on to IP using helper stream
28201 			 */
28202 			error = ldi_ioctl(connp->conn_helper_info->iphs_handle,
28203 			    cmd, arg, mode, cr, rvalp);
28204 			break;
28205 	}
28206 	return (error);
28207 }
28208 
28209 sock_downcalls_t sock_tcp_downcalls = {
28210 	tcp_activate,
28211 	tcp_accept,
28212 	tcp_bind,
28213 	tcp_listen,
28214 	tcp_connect,
28215 	tcp_getpeername,
28216 	tcp_getsockname,
28217 	tcp_getsockopt,
28218 	tcp_setsockopt,
28219 	tcp_sendmsg,
28220 	NULL,
28221 	NULL,
28222 	NULL,
28223 	tcp_shutdown,
28224 	tcp_clr_flowctrl,
28225 	tcp_ioctl,
28226 	tcp_close,
28227 };
28228