xref: /titanic_51/usr/src/uts/common/inet/tcp/tcp.c (revision c28a14f2d6c6363448d72fe487eecfe43b15ef86)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #include <sys/types.h>
29 #include <sys/stream.h>
30 #include <sys/strsun.h>
31 #include <sys/strsubr.h>
32 #include <sys/stropts.h>
33 #include <sys/strlog.h>
34 #include <sys/strsun.h>
35 #define	_SUN_TPI_VERSION 2
36 #include <sys/tihdr.h>
37 #include <sys/timod.h>
38 #include <sys/ddi.h>
39 #include <sys/sunddi.h>
40 #include <sys/suntpi.h>
41 #include <sys/xti_inet.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/sdt.h>
45 #include <sys/vtrace.h>
46 #include <sys/kmem.h>
47 #include <sys/ethernet.h>
48 #include <sys/cpuvar.h>
49 #include <sys/dlpi.h>
50 #include <sys/multidata.h>
51 #include <sys/multidata_impl.h>
52 #include <sys/pattr.h>
53 #include <sys/policy.h>
54 #include <sys/priv.h>
55 #include <sys/zone.h>
56 #include <sys/sunldi.h>
57 
58 #include <sys/errno.h>
59 #include <sys/signal.h>
60 #include <sys/socket.h>
61 #include <sys/sockio.h>
62 #include <sys/isa_defs.h>
63 #include <sys/md5.h>
64 #include <sys/random.h>
65 #include <sys/sodirect.h>
66 #include <sys/uio.h>
67 #include <sys/systm.h>
68 #include <netinet/in.h>
69 #include <netinet/tcp.h>
70 #include <netinet/ip6.h>
71 #include <netinet/icmp6.h>
72 #include <net/if.h>
73 #include <net/route.h>
74 #include <inet/ipsec_impl.h>
75 
76 #include <inet/common.h>
77 #include <inet/ip.h>
78 #include <inet/ip_impl.h>
79 #include <inet/ip6.h>
80 #include <inet/ip_ndp.h>
81 #include <inet/mi.h>
82 #include <inet/mib2.h>
83 #include <inet/nd.h>
84 #include <inet/optcom.h>
85 #include <inet/snmpcom.h>
86 #include <inet/kstatcom.h>
87 #include <inet/tcp.h>
88 #include <inet/tcp_impl.h>
89 #include <net/pfkeyv2.h>
90 #include <inet/ipsec_info.h>
91 #include <inet/ipdrop.h>
92 
93 #include <inet/ipclassifier.h>
94 #include <inet/ip_ire.h>
95 #include <inet/ip_ftable.h>
96 #include <inet/ip_if.h>
97 #include <inet/ipp_common.h>
98 #include <inet/ip_netinfo.h>
99 #include <sys/squeue.h>
100 #include <inet/kssl/ksslapi.h>
101 #include <sys/tsol/label.h>
102 #include <sys/tsol/tnet.h>
103 #include <rpc/pmap_prot.h>
104 #include <sys/callo.h>
105 
106 /*
107  * TCP Notes: aka FireEngine Phase I (PSARC 2002/433)
108  *
109  * (Read the detailed design doc in PSARC case directory)
110  *
111  * The entire tcp state is contained in tcp_t and conn_t structure
112  * which are allocated in tandem using ipcl_conn_create() and passing
113  * IPCL_CONNTCP as a flag. We use 'conn_ref' and 'conn_lock' to protect
114  * the references on the tcp_t. The tcp_t structure is never compressed
115  * and packets always land on the correct TCP perimeter from the time
116  * eager is created till the time tcp_t dies (as such the old mentat
117  * TCP global queue is not used for detached state and no IPSEC checking
118  * is required). The global queue is still allocated to send out resets
119  * for connection which have no listeners and IP directly calls
120  * tcp_xmit_listeners_reset() which does any policy check.
121  *
122  * Protection and Synchronisation mechanism:
123  *
124  * The tcp data structure does not use any kind of lock for protecting
125  * its state but instead uses 'squeues' for mutual exclusion from various
126  * read and write side threads. To access a tcp member, the thread should
127  * always be behind squeue (via squeue_enter, squeue_enter_nodrain, or
128  * squeue_fill). Since the squeues allow a direct function call, caller
129  * can pass any tcp function having prototype of edesc_t as argument
130  * (different from traditional STREAMs model where packets come in only
131  * designated entry points). The list of functions that can be directly
132  * called via squeue are listed before the usual function prototype.
133  *
134  * Referencing:
135  *
136  * TCP is MT-Hot and we use a reference based scheme to make sure that the
137  * tcp structure doesn't disappear when its needed. When the application
138  * creates an outgoing connection or accepts an incoming connection, we
139  * start out with 2 references on 'conn_ref'. One for TCP and one for IP.
140  * The IP reference is just a symbolic reference since ip_tcpclose()
141  * looks at tcp structure after tcp_close_output() returns which could
142  * have dropped the last TCP reference. So as long as the connection is
143  * in attached state i.e. !TCP_IS_DETACHED, we have 2 references on the
144  * conn_t. The classifier puts its own reference when the connection is
145  * inserted in listen or connected hash. Anytime a thread needs to enter
146  * the tcp connection perimeter, it retrieves the conn/tcp from q->ptr
147  * on write side or by doing a classify on read side and then puts a
148  * reference on the conn before doing squeue_enter/tryenter/fill. For
149  * read side, the classifier itself puts the reference under fanout lock
150  * to make sure that tcp can't disappear before it gets processed. The
151  * squeue will drop this reference automatically so the called function
152  * doesn't have to do a DEC_REF.
153  *
154  * Opening a new connection:
155  *
156  * The outgoing connection open is pretty simple. tcp_open() does the
157  * work in creating the conn/tcp structure and initializing it. The
158  * squeue assignment is done based on the CPU the application
159  * is running on. So for outbound connections, processing is always done
160  * on application CPU which might be different from the incoming CPU
161  * being interrupted by the NIC. An optimal way would be to figure out
162  * the NIC <-> CPU binding at listen time, and assign the outgoing
163  * connection to the squeue attached to the CPU that will be interrupted
164  * for incoming packets (we know the NIC based on the bind IP address).
165  * This might seem like a problem if more data is going out but the
166  * fact is that in most cases the transmit is ACK driven transmit where
167  * the outgoing data normally sits on TCP's xmit queue waiting to be
168  * transmitted.
169  *
170  * Accepting a connection:
171  *
172  * This is a more interesting case because of various races involved in
173  * establishing a eager in its own perimeter. Read the meta comment on
174  * top of tcp_conn_request(). But briefly, the squeue is picked by
175  * ip_tcp_input()/ip_fanout_tcp_v6() based on the interrupted CPU.
176  *
177  * Closing a connection:
178  *
179  * The close is fairly straight forward. tcp_close() calls tcp_close_output()
180  * via squeue to do the close and mark the tcp as detached if the connection
181  * was in state TCPS_ESTABLISHED or greater. In the later case, TCP keep its
182  * reference but tcp_close() drop IP's reference always. So if tcp was
183  * not killed, it is sitting in time_wait list with 2 reference - 1 for TCP
184  * and 1 because it is in classifier's connected hash. This is the condition
185  * we use to determine that its OK to clean up the tcp outside of squeue
186  * when time wait expires (check the ref under fanout and conn_lock and
187  * if it is 2, remove it from fanout hash and kill it).
188  *
189  * Although close just drops the necessary references and marks the
190  * tcp_detached state, tcp_close needs to know the tcp_detached has been
191  * set (under squeue) before letting the STREAM go away (because a
192  * inbound packet might attempt to go up the STREAM while the close
193  * has happened and tcp_detached is not set). So a special lock and
194  * flag is used along with a condition variable (tcp_closelock, tcp_closed,
195  * and tcp_closecv) to signal tcp_close that tcp_close_out() has marked
196  * tcp_detached.
197  *
198  * Special provisions and fast paths:
199  *
200  * We make special provision for (AF_INET, SOCK_STREAM) sockets which
201  * can't have 'ipv6_recvpktinfo' set and for these type of sockets, IP
202  * will never send a M_CTL to TCP. As such, ip_tcp_input() which handles
203  * all TCP packets from the wire makes a IPCL_IS_TCP4_CONNECTED_NO_POLICY
204  * check to send packets directly to tcp_rput_data via squeue. Everyone
205  * else comes through tcp_input() on the read side.
206  *
207  * We also make special provisions for sockfs by marking tcp_issocket
208  * whenever we have only sockfs on top of TCP. This allows us to skip
209  * putting the tcp in acceptor hash since a sockfs listener can never
210  * become acceptor and also avoid allocating a tcp_t for acceptor STREAM
211  * since eager has already been allocated and the accept now happens
212  * on acceptor STREAM. There is a big blob of comment on top of
213  * tcp_conn_request explaining the new accept. When socket is POP'd,
214  * sockfs sends us an ioctl to mark the fact and we go back to old
215  * behaviour. Once tcp_issocket is unset, its never set for the
216  * life of that connection.
217  *
218  * In support of on-board asynchronous DMA hardware (e.g. Intel I/OAT)
219  * two consoldiation private KAPIs are used to enqueue M_DATA mblk_t's
220  * directly to the socket (sodirect) and start an asynchronous copyout
221  * to a user-land receive-side buffer (uioa) when a blocking socket read
222  * (e.g. read, recv, ...) is pending.
223  *
224  * This is accomplished when tcp_issocket is set and tcp_sodirect is not
225  * NULL so points to an sodirect_t and if marked enabled then we enqueue
226  * all mblk_t's directly to the socket.
227  *
228  * Further, if the sodirect_t sod_uioa and if marked enabled (due to a
229  * blocking socket read, e.g. user-land read, recv, ...) then an asynchronous
230  * copyout will be started directly to the user-land uio buffer. Also, as we
231  * have a pending read, TCP's push logic can take into account the number of
232  * bytes to be received and only awake the blocked read()er when the uioa_t
233  * byte count has been satisfied.
234  *
235  * IPsec notes :
236  *
237  * Since a packet is always executed on the correct TCP perimeter
238  * all IPsec processing is defered to IP including checking new
239  * connections and setting IPSEC policies for new connection. The
240  * only exception is tcp_xmit_listeners_reset() which is called
241  * directly from IP and needs to policy check to see if TH_RST
242  * can be sent out.
243  *
244  * PFHooks notes :
245  *
246  * For mdt case, one meta buffer contains multiple packets. Mblks for every
247  * packet are assembled and passed to the hooks. When packets are blocked,
248  * or boundary of any packet is changed, the mdt processing is stopped, and
249  * packets of the meta buffer are send to the IP path one by one.
250  */
251 
252 /*
253  * Values for squeue switch:
254  * 1: squeue_enter_nodrain
255  * 2: squeue_enter
256  * 3: squeue_fill
257  */
258 int tcp_squeue_close = 2;	/* Setable in /etc/system */
259 int tcp_squeue_wput = 2;
260 
261 squeue_func_t tcp_squeue_close_proc;
262 squeue_func_t tcp_squeue_wput_proc;
263 
264 /*
265  * Macros for sodirect:
266  *
267  * SOD_PTR_ENTER(tcp, sodp) - for the tcp_t pointer "tcp" set the
268  * sodirect_t pointer "sodp" to the socket/tcp shared sodirect_t
269  * if it exists and is enabled, else to NULL. Note, in the current
270  * sodirect implementation the sod_lockp must not be held across any
271  * STREAMS call (e.g. putnext) else a "recursive mutex_enter" PANIC
272  * will result as sod_lockp is the streamhead stdata.sd_lock.
273  *
274  * SOD_NOT_ENABLED(tcp) - return true if not a sodirect tcp_t or the
275  * sodirect_t isn't enabled, usefull for ASSERT()ing that a recieve
276  * side tcp code path dealing with a tcp_rcv_list or putnext() isn't
277  * being used when sodirect code paths should be.
278  */
279 
280 #define	SOD_PTR_ENTER(tcp, sodp)					\
281 	(sodp) = (tcp)->tcp_sodirect;					\
282 									\
283 	if ((sodp) != NULL) {						\
284 		mutex_enter((sodp)->sod_lockp);				\
285 		if (!((sodp)->sod_state & SOD_ENABLED)) {		\
286 			mutex_exit((sodp)->sod_lockp);			\
287 			(sodp) = NULL;					\
288 		}							\
289 	}
290 
291 #define	SOD_NOT_ENABLED(tcp)						\
292 	((tcp)->tcp_sodirect == NULL ||					\
293 	    !((tcp)->tcp_sodirect->sod_state & SOD_ENABLED))
294 
295 /*
296  * This controls how tiny a write must be before we try to copy it
297  * into the the mblk on the tail of the transmit queue.  Not much
298  * speedup is observed for values larger than sixteen.  Zero will
299  * disable the optimisation.
300  */
301 int tcp_tx_pull_len = 16;
302 
303 /*
304  * TCP Statistics.
305  *
306  * How TCP statistics work.
307  *
308  * There are two types of statistics invoked by two macros.
309  *
310  * TCP_STAT(name) does non-atomic increment of a named stat counter. It is
311  * supposed to be used in non MT-hot paths of the code.
312  *
313  * TCP_DBGSTAT(name) does atomic increment of a named stat counter. It is
314  * supposed to be used for DEBUG purposes and may be used on a hot path.
315  *
316  * Both TCP_STAT and TCP_DBGSTAT counters are available using kstat
317  * (use "kstat tcp" to get them).
318  *
319  * There is also additional debugging facility that marks tcp_clean_death()
320  * instances and saves them in tcp_t structure. It is triggered by
321  * TCP_TAG_CLEAN_DEATH define. Also, there is a global array of counters for
322  * tcp_clean_death() calls that counts the number of times each tag was hit. It
323  * is triggered by TCP_CLD_COUNTERS define.
324  *
325  * How to add new counters.
326  *
327  * 1) Add a field in the tcp_stat structure describing your counter.
328  * 2) Add a line in the template in tcp_kstat2_init() with the name
329  *    of the counter.
330  *
331  *    IMPORTANT!! - make sure that both are in sync !!
332  * 3) Use either TCP_STAT or TCP_DBGSTAT with the name.
333  *
334  * Please avoid using private counters which are not kstat-exported.
335  *
336  * TCP_TAG_CLEAN_DEATH set to 1 enables tagging of tcp_clean_death() instances
337  * in tcp_t structure.
338  *
339  * TCP_MAX_CLEAN_DEATH_TAG is the maximum number of possible clean death tags.
340  */
341 
342 #ifndef TCP_DEBUG_COUNTER
343 #ifdef DEBUG
344 #define	TCP_DEBUG_COUNTER 1
345 #else
346 #define	TCP_DEBUG_COUNTER 0
347 #endif
348 #endif
349 
350 #define	TCP_CLD_COUNTERS 0
351 
352 #define	TCP_TAG_CLEAN_DEATH 1
353 #define	TCP_MAX_CLEAN_DEATH_TAG 32
354 
355 #ifdef lint
356 static int _lint_dummy_;
357 #endif
358 
359 #if TCP_CLD_COUNTERS
360 static uint_t tcp_clean_death_stat[TCP_MAX_CLEAN_DEATH_TAG];
361 #define	TCP_CLD_STAT(x) tcp_clean_death_stat[x]++
362 #elif defined(lint)
363 #define	TCP_CLD_STAT(x) ASSERT(_lint_dummy_ == 0);
364 #else
365 #define	TCP_CLD_STAT(x)
366 #endif
367 
368 #if TCP_DEBUG_COUNTER
369 #define	TCP_DBGSTAT(tcps, x)	\
370 	atomic_add_64(&((tcps)->tcps_statistics.x.value.ui64), 1)
371 #define	TCP_G_DBGSTAT(x)	\
372 	atomic_add_64(&(tcp_g_statistics.x.value.ui64), 1)
373 #elif defined(lint)
374 #define	TCP_DBGSTAT(tcps, x) ASSERT(_lint_dummy_ == 0);
375 #define	TCP_G_DBGSTAT(x) ASSERT(_lint_dummy_ == 0);
376 #else
377 #define	TCP_DBGSTAT(tcps, x)
378 #define	TCP_G_DBGSTAT(x)
379 #endif
380 
381 #define	TCP_G_STAT(x)	(tcp_g_statistics.x.value.ui64++)
382 
383 tcp_g_stat_t	tcp_g_statistics;
384 kstat_t		*tcp_g_kstat;
385 
386 /*
387  * Call either ip_output or ip_output_v6. This replaces putnext() calls on the
388  * tcp write side.
389  */
390 #define	CALL_IP_WPUT(connp, q, mp) {					\
391 	tcp_stack_t	*tcps;						\
392 									\
393 	tcps = connp->conn_netstack->netstack_tcp;			\
394 	ASSERT(((q)->q_flag & QREADR) == 0);				\
395 	TCP_DBGSTAT(tcps, tcp_ip_output);				\
396 	connp->conn_send(connp, (mp), (q), IP_WPUT);			\
397 }
398 
399 /* Macros for timestamp comparisons */
400 #define	TSTMP_GEQ(a, b)	((int32_t)((a)-(b)) >= 0)
401 #define	TSTMP_LT(a, b)	((int32_t)((a)-(b)) < 0)
402 
403 /*
404  * Parameters for TCP Initial Send Sequence number (ISS) generation.  When
405  * tcp_strong_iss is set to 1, which is the default, the ISS is calculated
406  * by adding three components: a time component which grows by 1 every 4096
407  * nanoseconds (versus every 4 microseconds suggested by RFC 793, page 27);
408  * a per-connection component which grows by 125000 for every new connection;
409  * and an "extra" component that grows by a random amount centered
410  * approximately on 64000.  This causes the the ISS generator to cycle every
411  * 4.89 hours if no TCP connections are made, and faster if connections are
412  * made.
413  *
414  * When tcp_strong_iss is set to 0, ISS is calculated by adding two
415  * components: a time component which grows by 250000 every second; and
416  * a per-connection component which grows by 125000 for every new connections.
417  *
418  * A third method, when tcp_strong_iss is set to 2, for generating ISS is
419  * prescribed by Steve Bellovin.  This involves adding time, the 125000 per
420  * connection, and a one-way hash (MD5) of the connection ID <sport, dport,
421  * src, dst>, a "truly" random (per RFC 1750) number, and a console-entered
422  * password.
423  */
424 #define	ISS_INCR	250000
425 #define	ISS_NSEC_SHT	12
426 
427 static sin_t	sin_null;	/* Zero address for quick clears */
428 static sin6_t	sin6_null;	/* Zero address for quick clears */
429 
430 /*
431  * This implementation follows the 4.3BSD interpretation of the urgent
432  * pointer and not RFC 1122. Switching to RFC 1122 behavior would cause
433  * incompatible changes in protocols like telnet and rlogin.
434  */
435 #define	TCP_OLD_URP_INTERPRETATION	1
436 
437 #define	TCP_IS_DETACHED_NONEAGER(tcp)	\
438 	(TCP_IS_DETACHED(tcp) && \
439 	    (!(tcp)->tcp_hard_binding))
440 
441 /*
442  * TCP reassembly macros.  We hide starting and ending sequence numbers in
443  * b_next and b_prev of messages on the reassembly queue.  The messages are
444  * chained using b_cont.  These macros are used in tcp_reass() so we don't
445  * have to see the ugly casts and assignments.
446  */
447 #define	TCP_REASS_SEQ(mp)		((uint32_t)(uintptr_t)((mp)->b_next))
448 #define	TCP_REASS_SET_SEQ(mp, u)	((mp)->b_next = \
449 					(mblk_t *)(uintptr_t)(u))
450 #define	TCP_REASS_END(mp)		((uint32_t)(uintptr_t)((mp)->b_prev))
451 #define	TCP_REASS_SET_END(mp, u)	((mp)->b_prev = \
452 					(mblk_t *)(uintptr_t)(u))
453 
454 /*
455  * Implementation of TCP Timers.
456  * =============================
457  *
458  * INTERFACE:
459  *
460  * There are two basic functions dealing with tcp timers:
461  *
462  *	timeout_id_t	tcp_timeout(connp, func, time)
463  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
464  *	TCP_TIMER_RESTART(tcp, intvl)
465  *
466  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
467  * after 'time' ticks passed. The function called by timeout() must adhere to
468  * the same restrictions as a driver soft interrupt handler - it must not sleep
469  * or call other functions that might sleep. The value returned is the opaque
470  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
471  * cancel the request. The call to tcp_timeout() may fail in which case it
472  * returns zero. This is different from the timeout(9F) function which never
473  * fails.
474  *
475  * The call-back function 'func' always receives 'connp' as its single
476  * argument. It is always executed in the squeue corresponding to the tcp
477  * structure. The tcp structure is guaranteed to be present at the time the
478  * call-back is called.
479  *
480  * NOTE: The call-back function 'func' is never called if tcp is in
481  * 	the TCPS_CLOSED state.
482  *
483  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
484  * request. locks acquired by the call-back routine should not be held across
485  * the call to tcp_timeout_cancel() or a deadlock may result.
486  *
487  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
488  * Otherwise, it returns an integer value greater than or equal to 0. In
489  * particular, if the call-back function is already placed on the squeue, it can
490  * not be canceled.
491  *
492  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
493  * 	within squeue context corresponding to the tcp instance. Since the
494  *	call-back is also called via the same squeue, there are no race
495  *	conditions described in untimeout(9F) manual page since all calls are
496  *	strictly serialized.
497  *
498  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
499  *	stored in tcp_timer_tid and starts a new one using
500  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
501  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
502  *	field.
503  *
504  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
505  *	call-back may still be called, so it is possible tcp_timer() will be
506  *	called several times. This should not be a problem since tcp_timer()
507  *	should always check the tcp instance state.
508  *
509  *
510  * IMPLEMENTATION:
511  *
512  * TCP timers are implemented using three-stage process. The call to
513  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
514  * when the timer expires. The tcp_timer_callback() arranges the call of the
515  * tcp_timer_handler() function via squeue corresponding to the tcp
516  * instance. The tcp_timer_handler() calls actual requested timeout call-back
517  * and passes tcp instance as an argument to it. Information is passed between
518  * stages using the tcp_timer_t structure which contains the connp pointer, the
519  * tcp call-back to call and the timeout id returned by the timeout(9F).
520  *
521  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
522  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
523  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
524  * returns the pointer to this mblk.
525  *
526  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
527  * looks like a normal mblk without actual dblk attached to it.
528  *
529  * To optimize performance each tcp instance holds a small cache of timer
530  * mblocks. In the current implementation it caches up to two timer mblocks per
531  * tcp instance. The cache is preserved over tcp frees and is only freed when
532  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
533  * timer processing happens on a corresponding squeue, the cache manipulation
534  * does not require any locks. Experiments show that majority of timer mblocks
535  * allocations are satisfied from the tcp cache and do not involve kmem calls.
536  *
537  * The tcp_timeout() places a refhold on the connp instance which guarantees
538  * that it will be present at the time the call-back function fires. The
539  * tcp_timer_handler() drops the reference after calling the call-back, so the
540  * call-back function does not need to manipulate the references explicitly.
541  */
542 
543 typedef struct tcp_timer_s {
544 	conn_t	*connp;
545 	void 	(*tcpt_proc)(void *);
546 	callout_id_t   tcpt_tid;
547 } tcp_timer_t;
548 
549 static kmem_cache_t *tcp_timercache;
550 kmem_cache_t	*tcp_sack_info_cache;
551 kmem_cache_t	*tcp_iphc_cache;
552 
553 /*
554  * For scalability, we must not run a timer for every TCP connection
555  * in TIME_WAIT state.  To see why, consider (for time wait interval of
556  * 4 minutes):
557  *	1000 connections/sec * 240 seconds/time wait = 240,000 active conn's
558  *
559  * This list is ordered by time, so you need only delete from the head
560  * until you get to entries which aren't old enough to delete yet.
561  * The list consists of only the detached TIME_WAIT connections.
562  *
563  * Note that the timer (tcp_time_wait_expire) is started when the tcp_t
564  * becomes detached TIME_WAIT (either by changing the state and already
565  * being detached or the other way around). This means that the TIME_WAIT
566  * state can be extended (up to doubled) if the connection doesn't become
567  * detached for a long time.
568  *
569  * The list manipulations (including tcp_time_wait_next/prev)
570  * are protected by the tcp_time_wait_lock. The content of the
571  * detached TIME_WAIT connections is protected by the normal perimeters.
572  *
573  * This list is per squeue and squeues are shared across the tcp_stack_t's.
574  * Things on tcp_time_wait_head remain associated with the tcp_stack_t
575  * and conn_netstack.
576  * The tcp_t's that are added to tcp_free_list are disassociated and
577  * have NULL tcp_tcps and conn_netstack pointers.
578  */
579 typedef struct tcp_squeue_priv_s {
580 	kmutex_t	tcp_time_wait_lock;
581 	callout_id_t	tcp_time_wait_tid;
582 	tcp_t		*tcp_time_wait_head;
583 	tcp_t		*tcp_time_wait_tail;
584 	tcp_t		*tcp_free_list;
585 	uint_t		tcp_free_list_cnt;
586 } tcp_squeue_priv_t;
587 
588 /*
589  * TCP_TIME_WAIT_DELAY governs how often the time_wait_collector runs.
590  * Running it every 5 seconds seems to give the best results.
591  */
592 #define	TCP_TIME_WAIT_DELAY drv_usectohz(5000000)
593 
594 /*
595  * To prevent memory hog, limit the number of entries in tcp_free_list
596  * to 1% of available memory / number of cpus
597  */
598 uint_t tcp_free_list_max_cnt = 0;
599 
600 #define	TCP_XMIT_LOWATER	4096
601 #define	TCP_XMIT_HIWATER	49152
602 #define	TCP_RECV_LOWATER	2048
603 #define	TCP_RECV_HIWATER	49152
604 
605 /*
606  *  PAWS needs a timer for 24 days.  This is the number of ticks in 24 days
607  */
608 #define	PAWS_TIMEOUT	((clock_t)(24*24*60*60*hz))
609 
610 #define	TIDUSZ	4096	/* transport interface data unit size */
611 
612 /*
613  * Bind hash list size and has function.  It has to be a power of 2 for
614  * hashing.
615  */
616 #define	TCP_BIND_FANOUT_SIZE	512
617 #define	TCP_BIND_HASH(lport) (ntohs(lport) & (TCP_BIND_FANOUT_SIZE - 1))
618 /*
619  * Size of listen and acceptor hash list.  It has to be a power of 2 for
620  * hashing.
621  */
622 #define	TCP_FANOUT_SIZE		256
623 
624 #ifdef	_ILP32
625 #define	TCP_ACCEPTOR_HASH(accid)					\
626 		(((uint_t)(accid) >> 8) & (TCP_FANOUT_SIZE - 1))
627 #else
628 #define	TCP_ACCEPTOR_HASH(accid)					\
629 		((uint_t)(accid) & (TCP_FANOUT_SIZE - 1))
630 #endif	/* _ILP32 */
631 
632 #define	IP_ADDR_CACHE_SIZE	2048
633 #define	IP_ADDR_CACHE_HASH(faddr)					\
634 	(ntohl(faddr) & (IP_ADDR_CACHE_SIZE -1))
635 
636 /* Hash for HSPs uses all 32 bits, since both networks and hosts are in table */
637 #define	TCP_HSP_HASH_SIZE 256
638 
639 #define	TCP_HSP_HASH(addr)					\
640 	(((addr>>24) ^ (addr >>16) ^			\
641 	    (addr>>8) ^ (addr)) % TCP_HSP_HASH_SIZE)
642 
643 /*
644  * TCP options struct returned from tcp_parse_options.
645  */
646 typedef struct tcp_opt_s {
647 	uint32_t	tcp_opt_mss;
648 	uint32_t	tcp_opt_wscale;
649 	uint32_t	tcp_opt_ts_val;
650 	uint32_t	tcp_opt_ts_ecr;
651 	tcp_t		*tcp;
652 } tcp_opt_t;
653 
654 /*
655  * RFC1323-recommended phrasing of TSTAMP option, for easier parsing
656  */
657 
658 #ifdef _BIG_ENDIAN
659 #define	TCPOPT_NOP_NOP_TSTAMP ((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | \
660 	(TCPOPT_TSTAMP << 8) | 10)
661 #else
662 #define	TCPOPT_NOP_NOP_TSTAMP ((10 << 24) | (TCPOPT_TSTAMP << 16) | \
663 	(TCPOPT_NOP << 8) | TCPOPT_NOP)
664 #endif
665 
666 /*
667  * Flags returned from tcp_parse_options.
668  */
669 #define	TCP_OPT_MSS_PRESENT	1
670 #define	TCP_OPT_WSCALE_PRESENT	2
671 #define	TCP_OPT_TSTAMP_PRESENT	4
672 #define	TCP_OPT_SACK_OK_PRESENT	8
673 #define	TCP_OPT_SACK_PRESENT	16
674 
675 /* TCP option length */
676 #define	TCPOPT_NOP_LEN		1
677 #define	TCPOPT_MAXSEG_LEN	4
678 #define	TCPOPT_WS_LEN		3
679 #define	TCPOPT_REAL_WS_LEN	(TCPOPT_WS_LEN+1)
680 #define	TCPOPT_TSTAMP_LEN	10
681 #define	TCPOPT_REAL_TS_LEN	(TCPOPT_TSTAMP_LEN+2)
682 #define	TCPOPT_SACK_OK_LEN	2
683 #define	TCPOPT_REAL_SACK_OK_LEN	(TCPOPT_SACK_OK_LEN+2)
684 #define	TCPOPT_REAL_SACK_LEN	4
685 #define	TCPOPT_MAX_SACK_LEN	36
686 #define	TCPOPT_HEADER_LEN	2
687 
688 /* TCP cwnd burst factor. */
689 #define	TCP_CWND_INFINITE	65535
690 #define	TCP_CWND_SS		3
691 #define	TCP_CWND_NORMAL		5
692 
693 /* Maximum TCP initial cwin (start/restart). */
694 #define	TCP_MAX_INIT_CWND	8
695 
696 /*
697  * Initialize cwnd according to RFC 3390.  def_max_init_cwnd is
698  * either tcp_slow_start_initial or tcp_slow_start_after idle
699  * depending on the caller.  If the upper layer has not used the
700  * TCP_INIT_CWND option to change the initial cwnd, tcp_init_cwnd
701  * should be 0 and we use the formula in RFC 3390 to set tcp_cwnd.
702  * If the upper layer has changed set the tcp_init_cwnd, just use
703  * it to calculate the tcp_cwnd.
704  */
705 #define	SET_TCP_INIT_CWND(tcp, mss, def_max_init_cwnd)			\
706 {									\
707 	if ((tcp)->tcp_init_cwnd == 0) {				\
708 		(tcp)->tcp_cwnd = MIN(def_max_init_cwnd * (mss),	\
709 		    MIN(4 * (mss), MAX(2 * (mss), 4380 / (mss) * (mss)))); \
710 	} else {							\
711 		(tcp)->tcp_cwnd = (tcp)->tcp_init_cwnd * (mss);		\
712 	}								\
713 	tcp->tcp_cwnd_cnt = 0;						\
714 }
715 
716 /* TCP Timer control structure */
717 typedef struct tcpt_s {
718 	pfv_t	tcpt_pfv;	/* The routine we are to call */
719 	tcp_t	*tcpt_tcp;	/* The parameter we are to pass in */
720 } tcpt_t;
721 
722 /* Host Specific Parameter structure */
723 typedef struct tcp_hsp {
724 	struct tcp_hsp	*tcp_hsp_next;
725 	in6_addr_t	tcp_hsp_addr_v6;
726 	in6_addr_t	tcp_hsp_subnet_v6;
727 	uint_t		tcp_hsp_vers;	/* IPV4_VERSION | IPV6_VERSION */
728 	int32_t		tcp_hsp_sendspace;
729 	int32_t		tcp_hsp_recvspace;
730 	int32_t		tcp_hsp_tstamp;
731 } tcp_hsp_t;
732 #define	tcp_hsp_addr	V4_PART_OF_V6(tcp_hsp_addr_v6)
733 #define	tcp_hsp_subnet	V4_PART_OF_V6(tcp_hsp_subnet_v6)
734 
735 /*
736  * Functions called directly via squeue having a prototype of edesc_t.
737  */
738 void		tcp_conn_request(void *arg, mblk_t *mp, void *arg2);
739 static void	tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2);
740 void		tcp_accept_finish(void *arg, mblk_t *mp, void *arg2);
741 static void	tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2);
742 static void	tcp_wput_proto(void *arg, mblk_t *mp, void *arg2);
743 void 		tcp_input(void *arg, mblk_t *mp, void *arg2);
744 void		tcp_rput_data(void *arg, mblk_t *mp, void *arg2);
745 static void	tcp_close_output(void *arg, mblk_t *mp, void *arg2);
746 void		tcp_output(void *arg, mblk_t *mp, void *arg2);
747 static void	tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2);
748 static void	tcp_timer_handler(void *arg, mblk_t *mp, void *arg2);
749 static void	tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2);
750 
751 
752 /* Prototype for TCP functions */
753 static void	tcp_random_init(void);
754 int		tcp_random(void);
755 static void	tcp_accept(tcp_t *tcp, mblk_t *mp);
756 static void	tcp_accept_swap(tcp_t *listener, tcp_t *acceptor,
757 		    tcp_t *eager);
758 static int	tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp);
759 static in_port_t tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
760     int reuseaddr, boolean_t quick_connect, boolean_t bind_to_req_port_only,
761     boolean_t user_specified);
762 static void	tcp_closei_local(tcp_t *tcp);
763 static void	tcp_close_detached(tcp_t *tcp);
764 static boolean_t tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph,
765 			mblk_t *idmp, mblk_t **defermp);
766 static void	tcp_connect(tcp_t *tcp, mblk_t *mp);
767 static void	tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp,
768 		    in_port_t dstport, uint_t srcid);
769 static void	tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
770 		    in_port_t dstport, uint32_t flowinfo, uint_t srcid,
771 		    uint32_t scope_id);
772 static int	tcp_clean_death(tcp_t *tcp, int err, uint8_t tag);
773 static void	tcp_def_q_set(tcp_t *tcp, mblk_t *mp);
774 static void	tcp_disconnect(tcp_t *tcp, mblk_t *mp);
775 static char	*tcp_display(tcp_t *tcp, char *, char);
776 static boolean_t tcp_eager_blowoff(tcp_t *listener, t_scalar_t seqnum);
777 static void	tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only);
778 static void	tcp_eager_unlink(tcp_t *tcp);
779 static void	tcp_err_ack(tcp_t *tcp, mblk_t *mp, int tlierr,
780 		    int unixerr);
781 static void	tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
782 		    int tlierr, int unixerr);
783 static int	tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp,
784 		    cred_t *cr);
785 static int	tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp,
786 		    char *value, caddr_t cp, cred_t *cr);
787 static int	tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp,
788 		    char *value, caddr_t cp, cred_t *cr);
789 static int	tcp_tpistate(tcp_t *tcp);
790 static void	tcp_bind_hash_insert(tf_t *tf, tcp_t *tcp,
791     int caller_holds_lock);
792 static void	tcp_bind_hash_remove(tcp_t *tcp);
793 static tcp_t	*tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *);
794 void		tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp);
795 static void	tcp_acceptor_hash_remove(tcp_t *tcp);
796 static void	tcp_capability_req(tcp_t *tcp, mblk_t *mp);
797 static void	tcp_info_req(tcp_t *tcp, mblk_t *mp);
798 static void	tcp_addr_req(tcp_t *tcp, mblk_t *mp);
799 static void	tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *mp);
800 void		tcp_g_q_setup(tcp_stack_t *);
801 void		tcp_g_q_create(tcp_stack_t *);
802 void		tcp_g_q_destroy(tcp_stack_t *);
803 static int	tcp_header_init_ipv4(tcp_t *tcp);
804 static int	tcp_header_init_ipv6(tcp_t *tcp);
805 int		tcp_init(tcp_t *tcp, queue_t *q);
806 static int	tcp_init_values(tcp_t *tcp);
807 static mblk_t	*tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic);
808 static mblk_t	*tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim,
809 		    t_scalar_t addr_length);
810 static void	tcp_ip_ire_mark_advice(tcp_t *tcp);
811 static void	tcp_ip_notify(tcp_t *tcp);
812 static mblk_t	*tcp_ire_mp(mblk_t *mp);
813 static void	tcp_iss_init(tcp_t *tcp);
814 static void	tcp_keepalive_killer(void *arg);
815 static int	tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt);
816 static void	tcp_mss_set(tcp_t *tcp, uint32_t size, boolean_t do_ss);
817 static int	tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp,
818 		    int *do_disconnectp, int *t_errorp, int *sys_errorp);
819 static boolean_t tcp_allow_connopt_set(int level, int name);
820 int		tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr);
821 int		tcp_opt_get(queue_t *q, int level, int name, uchar_t *ptr);
822 int		tcp_opt_set(queue_t *q, uint_t optset_context, int level,
823 		    int name, uint_t inlen, uchar_t *invalp, uint_t *outlenp,
824 		    uchar_t *outvalp, void *thisdg_attrs, cred_t *cr,
825 		    mblk_t *mblk);
826 static void	tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha);
827 static int	tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly,
828 		    uchar_t *ptr, uint_t len);
829 static int	tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr);
830 static boolean_t tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt,
831     tcp_stack_t *);
832 static int	tcp_param_set(queue_t *q, mblk_t *mp, char *value,
833 		    caddr_t cp, cred_t *cr);
834 static int	tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value,
835 		    caddr_t cp, cred_t *cr);
836 static void	tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *);
837 static int	tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value,
838 		    caddr_t cp, cred_t *cr);
839 static void	tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_cnt);
840 static mblk_t	*tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start);
841 static void	tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp);
842 static void	tcp_reinit(tcp_t *tcp);
843 static void	tcp_reinit_values(tcp_t *tcp);
844 static void	tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval,
845 		    tcp_t *thisstream, cred_t *cr);
846 
847 static uint_t	tcp_rcv_drain(queue_t *q, tcp_t *tcp);
848 static void	tcp_sack_rxmit(tcp_t *tcp, uint_t *flags);
849 static boolean_t tcp_send_rst_chk(tcp_stack_t *);
850 static void	tcp_ss_rexmit(tcp_t *tcp);
851 static mblk_t	*tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp);
852 static void	tcp_process_options(tcp_t *, tcph_t *);
853 static void	tcp_rput_common(tcp_t *tcp, mblk_t *mp);
854 static void	tcp_rsrv(queue_t *q);
855 static int	tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd);
856 static int	tcp_snmp_state(tcp_t *tcp);
857 static int	tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp,
858 		    cred_t *cr);
859 static int	tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
860 		    cred_t *cr);
861 static int	tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
862 		    cred_t *cr);
863 static int	tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
864 		    cred_t *cr);
865 static int	tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp,
866 		    cred_t *cr);
867 static void	tcp_timer(void *arg);
868 static void	tcp_timer_callback(void *);
869 static in_port_t tcp_update_next_port(in_port_t port, const tcp_t *tcp,
870     boolean_t random);
871 static in_port_t tcp_get_next_priv_port(const tcp_t *);
872 static void	tcp_wput_sock(queue_t *q, mblk_t *mp);
873 void		tcp_wput_accept(queue_t *q, mblk_t *mp);
874 static void	tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent);
875 static void	tcp_wput_flush(tcp_t *tcp, mblk_t *mp);
876 static void	tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp);
877 static int	tcp_send(queue_t *q, tcp_t *tcp, const int mss,
878 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
879 		    const int num_sack_blk, int *usable, uint_t *snxt,
880 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
881 		    const int mdt_thres);
882 static int	tcp_multisend(queue_t *q, tcp_t *tcp, const int mss,
883 		    const int tcp_hdr_len, const int tcp_tcp_hdr_len,
884 		    const int num_sack_blk, int *usable, uint_t *snxt,
885 		    int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
886 		    const int mdt_thres);
887 static void	tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now,
888 		    int num_sack_blk);
889 static void	tcp_wsrv(queue_t *q);
890 static int	tcp_xmit_end(tcp_t *tcp);
891 static void	tcp_ack_timer(void *arg);
892 static mblk_t	*tcp_ack_mp(tcp_t *tcp);
893 static void	tcp_xmit_early_reset(char *str, mblk_t *mp,
894 		    uint32_t seq, uint32_t ack, int ctl, uint_t ip_hdr_len,
895 		    zoneid_t zoneid, tcp_stack_t *, conn_t *connp);
896 static void	tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq,
897 		    uint32_t ack, int ctl);
898 static tcp_hsp_t *tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *);
899 static tcp_hsp_t *tcp_hsp_lookup_ipv6(in6_addr_t *addr, tcp_stack_t *);
900 static int	setmaxps(queue_t *q, int maxpsz);
901 static void	tcp_set_rto(tcp_t *, time_t);
902 static boolean_t tcp_check_policy(tcp_t *, mblk_t *, ipha_t *, ip6_t *,
903 		    boolean_t, boolean_t);
904 static void	tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp,
905 		    boolean_t ipsec_mctl);
906 static mblk_t	*tcp_setsockopt_mp(int level, int cmd,
907 		    char *opt, int optlen);
908 static int	tcp_build_hdrs(queue_t *, tcp_t *);
909 static void	tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp,
910 		    uint32_t seg_seq, uint32_t seg_ack, int seg_len,
911 		    tcph_t *tcph);
912 boolean_t	tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp);
913 static mblk_t	*tcp_mdt_info_mp(mblk_t *);
914 static void	tcp_mdt_update(tcp_t *, ill_mdt_capab_t *, boolean_t);
915 static int	tcp_mdt_add_attrs(multidata_t *, const mblk_t *,
916 		    const boolean_t, const uint32_t, const uint32_t,
917 		    const uint32_t, const uint32_t, tcp_stack_t *);
918 static void	tcp_multisend_data(tcp_t *, ire_t *, const ill_t *, mblk_t *,
919 		    const uint_t, const uint_t, boolean_t *);
920 static mblk_t	*tcp_lso_info_mp(mblk_t *);
921 static void	tcp_lso_update(tcp_t *, ill_lso_capab_t *);
922 static void	tcp_send_data(tcp_t *, queue_t *, mblk_t *);
923 extern mblk_t	*tcp_timermp_alloc(int);
924 extern void	tcp_timermp_free(tcp_t *);
925 static void	tcp_timer_free(tcp_t *tcp, mblk_t *mp);
926 static void	tcp_stop_lingering(tcp_t *tcp);
927 static void	tcp_close_linger_timeout(void *arg);
928 static void	*tcp_stack_init(netstackid_t stackid, netstack_t *ns);
929 static void	tcp_stack_shutdown(netstackid_t stackid, void *arg);
930 static void	tcp_stack_fini(netstackid_t stackid, void *arg);
931 static void	*tcp_g_kstat_init(tcp_g_stat_t *);
932 static void	tcp_g_kstat_fini(kstat_t *);
933 static void	*tcp_kstat_init(netstackid_t, tcp_stack_t *);
934 static void	tcp_kstat_fini(netstackid_t, kstat_t *);
935 static void	*tcp_kstat2_init(netstackid_t, tcp_stat_t *);
936 static void	tcp_kstat2_fini(netstackid_t, kstat_t *);
937 static int	tcp_kstat_update(kstat_t *kp, int rw);
938 void		tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp);
939 static int	tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
940 			tcph_t *tcph, uint_t ipvers, mblk_t *idmp);
941 static int	tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
942 			tcph_t *tcph, mblk_t *idmp);
943 static squeue_func_t tcp_squeue_switch(int);
944 
945 static int	tcp_open(queue_t *, dev_t *, int, int, cred_t *, boolean_t);
946 static int	tcp_openv4(queue_t *, dev_t *, int, int, cred_t *);
947 static int	tcp_openv6(queue_t *, dev_t *, int, int, cred_t *);
948 static int	tcp_close(queue_t *, int);
949 static int	tcpclose_accept(queue_t *);
950 
951 static void	tcp_squeue_add(squeue_t *);
952 static boolean_t tcp_zcopy_check(tcp_t *);
953 static void	tcp_zcopy_notify(tcp_t *);
954 static mblk_t	*tcp_zcopy_disable(tcp_t *, mblk_t *);
955 static mblk_t	*tcp_zcopy_backoff(tcp_t *, mblk_t *, int);
956 static void	tcp_ire_ill_check(tcp_t *, ire_t *, ill_t *, boolean_t);
957 
958 extern void	tcp_kssl_input(tcp_t *, mblk_t *);
959 
960 void tcp_eager_kill(void *arg, mblk_t *mp, void *arg2);
961 void tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2);
962 
963 /*
964  * Routines related to the TCP_IOC_ABORT_CONN ioctl command.
965  *
966  * TCP_IOC_ABORT_CONN is a non-transparent ioctl command used for aborting
967  * TCP connections. To invoke this ioctl, a tcp_ioc_abort_conn_t structure
968  * (defined in tcp.h) needs to be filled in and passed into the kernel
969  * via an I_STR ioctl command (see streamio(7I)). The tcp_ioc_abort_conn_t
970  * structure contains the four-tuple of a TCP connection and a range of TCP
971  * states (specified by ac_start and ac_end). The use of wildcard addresses
972  * and ports is allowed. Connections with a matching four tuple and a state
973  * within the specified range will be aborted. The valid states for the
974  * ac_start and ac_end fields are in the range TCPS_SYN_SENT to TCPS_TIME_WAIT,
975  * inclusive.
976  *
977  * An application which has its connection aborted by this ioctl will receive
978  * an error that is dependent on the connection state at the time of the abort.
979  * If the connection state is < TCPS_TIME_WAIT, an application should behave as
980  * though a RST packet has been received.  If the connection state is equal to
981  * TCPS_TIME_WAIT, the 2MSL timeout will immediately be canceled by the kernel
982  * and all resources associated with the connection will be freed.
983  */
984 static mblk_t	*tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *, tcp_t *);
985 static void	tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *);
986 static void	tcp_ioctl_abort_handler(tcp_t *, mblk_t *);
987 static int	tcp_ioctl_abort(tcp_ioc_abort_conn_t *, tcp_stack_t *tcps);
988 static void	tcp_ioctl_abort_conn(queue_t *, mblk_t *);
989 static int	tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *, int, int *,
990     boolean_t, tcp_stack_t *);
991 
992 static struct module_info tcp_rinfo =  {
993 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, TCP_RECV_HIWATER, TCP_RECV_LOWATER
994 };
995 
996 static struct module_info tcp_winfo =  {
997 	TCP_MOD_ID, TCP_MOD_NAME, 0, INFPSZ, 127, 16
998 };
999 
1000 /*
1001  * Entry points for TCP as a device. The normal case which supports
1002  * the TCP functionality.
1003  * We have separate open functions for the /dev/tcp and /dev/tcp6 devices.
1004  */
1005 struct qinit tcp_rinitv4 = {
1006 	NULL, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, NULL, &tcp_rinfo
1007 };
1008 
1009 struct qinit tcp_rinitv6 = {
1010 	NULL, (pfi_t)tcp_rsrv, tcp_openv6, tcp_close, NULL, &tcp_rinfo
1011 };
1012 
1013 struct qinit tcp_winit = {
1014 	(pfi_t)tcp_wput, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1015 };
1016 
1017 /* Initial entry point for TCP in socket mode. */
1018 struct qinit tcp_sock_winit = {
1019 	(pfi_t)tcp_wput_sock, (pfi_t)tcp_wsrv, NULL, NULL, NULL, &tcp_winfo
1020 };
1021 
1022 /*
1023  * Entry points for TCP as a acceptor STREAM opened by sockfs when doing
1024  * an accept. Avoid allocating data structures since eager has already
1025  * been created.
1026  */
1027 struct qinit tcp_acceptor_rinit = {
1028 	NULL, (pfi_t)tcp_rsrv, NULL, tcpclose_accept, NULL, &tcp_winfo
1029 };
1030 
1031 struct qinit tcp_acceptor_winit = {
1032 	(pfi_t)tcp_wput_accept, NULL, NULL, NULL, NULL, &tcp_winfo
1033 };
1034 
1035 /*
1036  * Entry points for TCP loopback (read side only)
1037  * The open routine is only used for reopens, thus no need to
1038  * have a separate one for tcp_openv6.
1039  */
1040 struct qinit tcp_loopback_rinit = {
1041 	(pfi_t)0, (pfi_t)tcp_rsrv, tcp_openv4, tcp_close, (pfi_t)0,
1042 	&tcp_rinfo, NULL, tcp_fuse_rrw, tcp_fuse_rinfop, STRUIOT_STANDARD
1043 };
1044 
1045 /* For AF_INET aka /dev/tcp */
1046 struct streamtab tcpinfov4 = {
1047 	&tcp_rinitv4, &tcp_winit
1048 };
1049 
1050 /* For AF_INET6 aka /dev/tcp6 */
1051 struct streamtab tcpinfov6 = {
1052 	&tcp_rinitv6, &tcp_winit
1053 };
1054 
1055 /*
1056  * Have to ensure that tcp_g_q_close is not done by an
1057  * interrupt thread.
1058  */
1059 static taskq_t *tcp_taskq;
1060 
1061 /* Setable only in /etc/system. Move to ndd? */
1062 boolean_t tcp_icmp_source_quench = B_FALSE;
1063 
1064 /*
1065  * Following assumes TPI alignment requirements stay along 32 bit
1066  * boundaries
1067  */
1068 #define	ROUNDUP32(x) \
1069 	(((x) + (sizeof (int32_t) - 1)) & ~(sizeof (int32_t) - 1))
1070 
1071 /* Template for response to info request. */
1072 static struct T_info_ack tcp_g_t_info_ack = {
1073 	T_INFO_ACK,		/* PRIM_type */
1074 	0,			/* TSDU_size */
1075 	T_INFINITE,		/* ETSDU_size */
1076 	T_INVALID,		/* CDATA_size */
1077 	T_INVALID,		/* DDATA_size */
1078 	sizeof (sin_t),		/* ADDR_size */
1079 	0,			/* OPT_size - not initialized here */
1080 	TIDUSZ,			/* TIDU_size */
1081 	T_COTS_ORD,		/* SERV_type */
1082 	TCPS_IDLE,		/* CURRENT_state */
1083 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1084 };
1085 
1086 static struct T_info_ack tcp_g_t_info_ack_v6 = {
1087 	T_INFO_ACK,		/* PRIM_type */
1088 	0,			/* TSDU_size */
1089 	T_INFINITE,		/* ETSDU_size */
1090 	T_INVALID,		/* CDATA_size */
1091 	T_INVALID,		/* DDATA_size */
1092 	sizeof (sin6_t),	/* ADDR_size */
1093 	0,			/* OPT_size - not initialized here */
1094 	TIDUSZ,		/* TIDU_size */
1095 	T_COTS_ORD,		/* SERV_type */
1096 	TCPS_IDLE,		/* CURRENT_state */
1097 	(XPG4_1|EXPINLINE)	/* PROVIDER_flag */
1098 };
1099 
1100 #define	MS	1L
1101 #define	SECONDS	(1000 * MS)
1102 #define	MINUTES	(60 * SECONDS)
1103 #define	HOURS	(60 * MINUTES)
1104 #define	DAYS	(24 * HOURS)
1105 
1106 #define	PARAM_MAX (~(uint32_t)0)
1107 
1108 /* Max size IP datagram is 64k - 1 */
1109 #define	TCP_MSS_MAX_IPV4 (IP_MAXPACKET - (sizeof (ipha_t) + sizeof (tcph_t)))
1110 #define	TCP_MSS_MAX_IPV6 (IP_MAXPACKET - (sizeof (ip6_t) + sizeof (tcph_t)))
1111 /* Max of the above */
1112 #define	TCP_MSS_MAX	TCP_MSS_MAX_IPV4
1113 
1114 /* Largest TCP port number */
1115 #define	TCP_MAX_PORT	(64 * 1024 - 1)
1116 
1117 /*
1118  * tcp_wroff_xtra is the extra space in front of TCP/IP header for link
1119  * layer header.  It has to be a multiple of 4.
1120  */
1121 static tcpparam_t lcl_tcp_wroff_xtra_param = { 0, 256, 32, "tcp_wroff_xtra" };
1122 #define	tcps_wroff_xtra	tcps_wroff_xtra_param->tcp_param_val
1123 
1124 /*
1125  * All of these are alterable, within the min/max values given, at run time.
1126  * Note that the default value of "tcp_time_wait_interval" is four minutes,
1127  * per the TCP spec.
1128  */
1129 /* BEGIN CSTYLED */
1130 static tcpparam_t	lcl_tcp_param_arr[] = {
1131  /*min		max		value		name */
1132  { 1*SECONDS,	10*MINUTES,	1*MINUTES,	"tcp_time_wait_interval"},
1133  { 1,		PARAM_MAX,	128,		"tcp_conn_req_max_q" },
1134  { 0,		PARAM_MAX,	1024,		"tcp_conn_req_max_q0" },
1135  { 1,		1024,		1,		"tcp_conn_req_min" },
1136  { 0*MS,	20*SECONDS,	0*MS,		"tcp_conn_grace_period" },
1137  { 128,		(1<<30),	1024*1024,	"tcp_cwnd_max" },
1138  { 0,		10,		0,		"tcp_debug" },
1139  { 1024,	(32*1024),	1024,		"tcp_smallest_nonpriv_port"},
1140  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_cinterval"},
1141  { 1*SECONDS,	PARAM_MAX,	3*MINUTES,	"tcp_ip_abort_linterval"},
1142  { 500*MS,	PARAM_MAX,	8*MINUTES,	"tcp_ip_abort_interval"},
1143  { 1*SECONDS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_cinterval"},
1144  { 500*MS,	PARAM_MAX,	10*SECONDS,	"tcp_ip_notify_interval"},
1145  { 1,		255,		64,		"tcp_ipv4_ttl"},
1146  { 10*SECONDS,	10*DAYS,	2*HOURS,	"tcp_keepalive_interval"},
1147  { 0,		100,		10,		"tcp_maxpsz_multiplier" },
1148  { 1,		TCP_MSS_MAX_IPV4, 536,		"tcp_mss_def_ipv4"},
1149  { 1,		TCP_MSS_MAX_IPV4, TCP_MSS_MAX_IPV4, "tcp_mss_max_ipv4"},
1150  { 1,		TCP_MSS_MAX,	108,		"tcp_mss_min"},
1151  { 1,		(64*1024)-1,	(4*1024)-1,	"tcp_naglim_def"},
1152  { 1*MS,	20*SECONDS,	3*SECONDS,	"tcp_rexmit_interval_initial"},
1153  { 1*MS,	2*HOURS,	60*SECONDS,	"tcp_rexmit_interval_max"},
1154  { 1*MS,	2*HOURS,	400*MS,		"tcp_rexmit_interval_min"},
1155  { 1*MS,	1*MINUTES,	100*MS,		"tcp_deferred_ack_interval" },
1156  { 0,		16,		0,		"tcp_snd_lowat_fraction" },
1157  { 0,		128000,		0,		"tcp_sth_rcv_hiwat" },
1158  { 0,		128000,		0,		"tcp_sth_rcv_lowat" },
1159  { 1,		10000,		3,		"tcp_dupack_fast_retransmit" },
1160  { 0,		1,		0,		"tcp_ignore_path_mtu" },
1161  { 1024,	TCP_MAX_PORT,	32*1024,	"tcp_smallest_anon_port"},
1162  { 1024,	TCP_MAX_PORT,	TCP_MAX_PORT,	"tcp_largest_anon_port"},
1163  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_HIWATER,"tcp_xmit_hiwat"},
1164  { TCP_XMIT_LOWATER, (1<<30), TCP_XMIT_LOWATER,"tcp_xmit_lowat"},
1165  { TCP_RECV_LOWATER, (1<<30), TCP_RECV_HIWATER,"tcp_recv_hiwat"},
1166  { 1,		65536,		4,		"tcp_recv_hiwat_minmss"},
1167  { 1*SECONDS,	PARAM_MAX,	675*SECONDS,	"tcp_fin_wait_2_flush_interval"},
1168  { 8192,	(1<<30),	1024*1024,	"tcp_max_buf"},
1169 /*
1170  * Question:  What default value should I set for tcp_strong_iss?
1171  */
1172  { 0,		2,		1,		"tcp_strong_iss"},
1173  { 0,		65536,		20,		"tcp_rtt_updates"},
1174  { 0,		1,		1,		"tcp_wscale_always"},
1175  { 0,		1,		0,		"tcp_tstamp_always"},
1176  { 0,		1,		1,		"tcp_tstamp_if_wscale"},
1177  { 0*MS,	2*HOURS,	0*MS,		"tcp_rexmit_interval_extra"},
1178  { 0,		16,		2,		"tcp_deferred_acks_max"},
1179  { 1,		16384,		4,		"tcp_slow_start_after_idle"},
1180  { 1,		4,		4,		"tcp_slow_start_initial"},
1181  { 0,		2,		2,		"tcp_sack_permitted"},
1182  { 0,		1,		1,		"tcp_compression_enabled"},
1183  { 0,		IPV6_MAX_HOPS,	IPV6_DEFAULT_HOPS,	"tcp_ipv6_hoplimit"},
1184  { 1,		TCP_MSS_MAX_IPV6, 1220,		"tcp_mss_def_ipv6"},
1185  { 1,		TCP_MSS_MAX_IPV6, TCP_MSS_MAX_IPV6, "tcp_mss_max_ipv6"},
1186  { 0,		1,		0,		"tcp_rev_src_routes"},
1187  { 10*MS,	500*MS,		50*MS,		"tcp_local_dack_interval"},
1188  { 100*MS,	60*SECONDS,	1*SECONDS,	"tcp_ndd_get_info_interval"},
1189  { 0,		16,		8,		"tcp_local_dacks_max"},
1190  { 0,		2,		1,		"tcp_ecn_permitted"},
1191  { 0,		1,		1,		"tcp_rst_sent_rate_enabled"},
1192  { 0,		PARAM_MAX,	40,		"tcp_rst_sent_rate"},
1193  { 0,		100*MS,		50*MS,		"tcp_push_timer_interval"},
1194  { 0,		1,		0,		"tcp_use_smss_as_mss_opt"},
1195  { 0,		PARAM_MAX,	8*MINUTES,	"tcp_keepalive_abort_interval"},
1196 };
1197 /* END CSTYLED */
1198 
1199 /*
1200  * tcp_mdt_hdr_{head,tail}_min are the leading and trailing spaces of
1201  * each header fragment in the header buffer.  Each parameter value has
1202  * to be a multiple of 4 (32-bit aligned).
1203  */
1204 static tcpparam_t lcl_tcp_mdt_head_param =
1205 	{ 32, 256, 32, "tcp_mdt_hdr_head_min" };
1206 static tcpparam_t lcl_tcp_mdt_tail_param =
1207 	{ 0,  256, 32, "tcp_mdt_hdr_tail_min" };
1208 #define	tcps_mdt_hdr_head_min	tcps_mdt_head_param->tcp_param_val
1209 #define	tcps_mdt_hdr_tail_min	tcps_mdt_tail_param->tcp_param_val
1210 
1211 /*
1212  * tcp_mdt_max_pbufs is the upper limit value that tcp uses to figure out
1213  * the maximum number of payload buffers associated per Multidata.
1214  */
1215 static tcpparam_t lcl_tcp_mdt_max_pbufs_param =
1216 	{ 1, MULTIDATA_MAX_PBUFS, MULTIDATA_MAX_PBUFS, "tcp_mdt_max_pbufs" };
1217 #define	tcps_mdt_max_pbufs	tcps_mdt_max_pbufs_param->tcp_param_val
1218 
1219 /* Round up the value to the nearest mss. */
1220 #define	MSS_ROUNDUP(value, mss)		((((value) - 1) / (mss) + 1) * (mss))
1221 
1222 /*
1223  * Set ECN capable transport (ECT) code point in IP header.
1224  *
1225  * Note that there are 2 ECT code points '01' and '10', which are called
1226  * ECT(1) and ECT(0) respectively.  Here we follow the original ECT code
1227  * point ECT(0) for TCP as described in RFC 2481.
1228  */
1229 #define	SET_ECT(tcp, iph) \
1230 	if ((tcp)->tcp_ipversion == IPV4_VERSION) { \
1231 		/* We need to clear the code point first. */ \
1232 		((ipha_t *)(iph))->ipha_type_of_service &= 0xFC; \
1233 		((ipha_t *)(iph))->ipha_type_of_service |= IPH_ECN_ECT0; \
1234 	} else { \
1235 		((ip6_t *)(iph))->ip6_vcf &= htonl(0xFFCFFFFF); \
1236 		((ip6_t *)(iph))->ip6_vcf |= htonl(IPH_ECN_ECT0 << 20); \
1237 	}
1238 
1239 /*
1240  * The format argument to pass to tcp_display().
1241  * DISP_PORT_ONLY means that the returned string has only port info.
1242  * DISP_ADDR_AND_PORT means that the returned string also contains the
1243  * remote and local IP address.
1244  */
1245 #define	DISP_PORT_ONLY		1
1246 #define	DISP_ADDR_AND_PORT	2
1247 
1248 #define	NDD_TOO_QUICK_MSG \
1249 	"ndd get info rate too high for non-privileged users, try again " \
1250 	"later.\n"
1251 #define	NDD_OUT_OF_BUF_MSG	"<< Out of buffer >>\n"
1252 
1253 #define	IS_VMLOANED_MBLK(mp) \
1254 	(((mp)->b_datap->db_struioflag & STRUIO_ZC) != 0)
1255 
1256 
1257 /* Enable or disable b_cont M_MULTIDATA chaining for MDT. */
1258 boolean_t tcp_mdt_chain = B_TRUE;
1259 
1260 /*
1261  * MDT threshold in the form of effective send MSS multiplier; we take
1262  * the MDT path if the amount of unsent data exceeds the threshold value
1263  * (default threshold is 1*SMSS).
1264  */
1265 uint_t tcp_mdt_smss_threshold = 1;
1266 
1267 uint32_t do_tcpzcopy = 1;		/* 0: disable, 1: enable, 2: force */
1268 
1269 /*
1270  * Forces all connections to obey the value of the tcps_maxpsz_multiplier
1271  * tunable settable via NDD.  Otherwise, the per-connection behavior is
1272  * determined dynamically during tcp_adapt_ire(), which is the default.
1273  */
1274 boolean_t tcp_static_maxpsz = B_FALSE;
1275 
1276 /* Setable in /etc/system */
1277 /* If set to 0, pick ephemeral port sequentially; otherwise randomly. */
1278 uint32_t tcp_random_anon_port = 1;
1279 
1280 /*
1281  * To reach to an eager in Q0 which can be dropped due to an incoming
1282  * new SYN request when Q0 is full, a new doubly linked list is
1283  * introduced. This list allows to select an eager from Q0 in O(1) time.
1284  * This is needed to avoid spending too much time walking through the
1285  * long list of eagers in Q0 when tcp_drop_q0() is called. Each member of
1286  * this new list has to be a member of Q0.
1287  * This list is headed by listener's tcp_t. When the list is empty,
1288  * both the pointers - tcp_eager_next_drop_q0 and tcp_eager_prev_drop_q0,
1289  * of listener's tcp_t point to listener's tcp_t itself.
1290  *
1291  * Given an eager in Q0 and a listener, MAKE_DROPPABLE() puts the eager
1292  * in the list. MAKE_UNDROPPABLE() takes the eager out of the list.
1293  * These macros do not affect the eager's membership to Q0.
1294  */
1295 
1296 
1297 #define	MAKE_DROPPABLE(listener, eager)					\
1298 	if ((eager)->tcp_eager_next_drop_q0 == NULL) {			\
1299 		(listener)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0\
1300 		    = (eager);						\
1301 		(eager)->tcp_eager_prev_drop_q0 = (listener);		\
1302 		(eager)->tcp_eager_next_drop_q0 =			\
1303 		    (listener)->tcp_eager_next_drop_q0;			\
1304 		(listener)->tcp_eager_next_drop_q0 = (eager);		\
1305 	}
1306 
1307 #define	MAKE_UNDROPPABLE(eager)						\
1308 	if ((eager)->tcp_eager_next_drop_q0 != NULL) {			\
1309 		(eager)->tcp_eager_next_drop_q0->tcp_eager_prev_drop_q0	\
1310 		    = (eager)->tcp_eager_prev_drop_q0;			\
1311 		(eager)->tcp_eager_prev_drop_q0->tcp_eager_next_drop_q0	\
1312 		    = (eager)->tcp_eager_next_drop_q0;			\
1313 		(eager)->tcp_eager_prev_drop_q0 = NULL;			\
1314 		(eager)->tcp_eager_next_drop_q0 = NULL;			\
1315 	}
1316 
1317 /*
1318  * If tcp_drop_ack_unsent_cnt is greater than 0, when TCP receives more
1319  * than tcp_drop_ack_unsent_cnt number of ACKs which acknowledge unsent
1320  * data, TCP will not respond with an ACK.  RFC 793 requires that
1321  * TCP responds with an ACK for such a bogus ACK.  By not following
1322  * the RFC, we prevent TCP from getting into an ACK storm if somehow
1323  * an attacker successfully spoofs an acceptable segment to our
1324  * peer; or when our peer is "confused."
1325  */
1326 uint32_t tcp_drop_ack_unsent_cnt = 10;
1327 
1328 /*
1329  * Hook functions to enable cluster networking
1330  * On non-clustered systems these vectors must always be NULL.
1331  */
1332 
1333 void (*cl_inet_listen)(uint8_t protocol, sa_family_t addr_family,
1334 			    uint8_t *laddrp, in_port_t lport) = NULL;
1335 void (*cl_inet_unlisten)(uint8_t protocol, sa_family_t addr_family,
1336 			    uint8_t *laddrp, in_port_t lport) = NULL;
1337 void (*cl_inet_connect)(uint8_t protocol, sa_family_t addr_family,
1338 			    uint8_t *laddrp, in_port_t lport,
1339 			    uint8_t *faddrp, in_port_t fport) = NULL;
1340 void (*cl_inet_disconnect)(uint8_t protocol, sa_family_t addr_family,
1341 			    uint8_t *laddrp, in_port_t lport,
1342 			    uint8_t *faddrp, in_port_t fport) = NULL;
1343 
1344 /*
1345  * The following are defined in ip.c
1346  */
1347 extern int (*cl_inet_isclusterwide)(uint8_t protocol, sa_family_t addr_family,
1348 				uint8_t *laddrp);
1349 extern uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
1350 				uint8_t *laddrp, uint8_t *faddrp);
1351 
1352 #define	CL_INET_CONNECT(tcp)		{			\
1353 	if (cl_inet_connect != NULL) {				\
1354 		/*						\
1355 		 * Running in cluster mode - register active connection	\
1356 		 * information						\
1357 		 */							\
1358 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1359 			if ((tcp)->tcp_ipha->ipha_src != 0) {		\
1360 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET,\
1361 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_src)),\
1362 				    (in_port_t)(tcp)->tcp_lport,	\
1363 				    (uint8_t *)(&((tcp)->tcp_ipha->ipha_dst)),\
1364 				    (in_port_t)(tcp)->tcp_fport);	\
1365 			}						\
1366 		} else {						\
1367 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1368 			    &(tcp)->tcp_ip6h->ip6_src)) {\
1369 				(*cl_inet_connect)(IPPROTO_TCP, AF_INET6,\
1370 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_src)),\
1371 				    (in_port_t)(tcp)->tcp_lport,	\
1372 				    (uint8_t *)(&((tcp)->tcp_ip6h->ip6_dst)),\
1373 				    (in_port_t)(tcp)->tcp_fport);	\
1374 			}						\
1375 		}							\
1376 	}								\
1377 }
1378 
1379 #define	CL_INET_DISCONNECT(tcp)	{				\
1380 	if (cl_inet_disconnect != NULL) {				\
1381 		/*							\
1382 		 * Running in cluster mode - deregister active		\
1383 		 * connection information				\
1384 		 */							\
1385 		if ((tcp)->tcp_ipversion == IPV4_VERSION) {		\
1386 			if ((tcp)->tcp_ip_src != 0) {			\
1387 				(*cl_inet_disconnect)(IPPROTO_TCP,	\
1388 				    AF_INET,				\
1389 				    (uint8_t *)(&((tcp)->tcp_ip_src)),\
1390 				    (in_port_t)(tcp)->tcp_lport,	\
1391 				    (uint8_t *)				\
1392 				    (&((tcp)->tcp_ipha->ipha_dst)),\
1393 				    (in_port_t)(tcp)->tcp_fport);	\
1394 			}						\
1395 		} else {						\
1396 			if (!IN6_IS_ADDR_UNSPECIFIED(			\
1397 			    &(tcp)->tcp_ip_src_v6)) {			\
1398 				(*cl_inet_disconnect)(IPPROTO_TCP, AF_INET6,\
1399 				    (uint8_t *)(&((tcp)->tcp_ip_src_v6)),\
1400 				    (in_port_t)(tcp)->tcp_lport,	\
1401 				    (uint8_t *)				\
1402 				    (&((tcp)->tcp_ip6h->ip6_dst)),\
1403 				    (in_port_t)(tcp)->tcp_fport);	\
1404 			}						\
1405 		}							\
1406 	}								\
1407 }
1408 
1409 /*
1410  * Cluster networking hook for traversing current connection list.
1411  * This routine is used to extract the current list of live connections
1412  * which must continue to to be dispatched to this node.
1413  */
1414 int cl_tcp_walk_list(int (*callback)(cl_tcp_info_t *, void *), void *arg);
1415 
1416 static int cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *),
1417     void *arg, tcp_stack_t *tcps);
1418 
1419 #define	DTRACE_IP_FASTPATH(mp, iph, ill, ipha, ip6h) 			\
1420 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,	\
1421 	    iph, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha,		\
1422 	    ip6_t *, ip6h, int, 0);
1423 
1424 /*
1425  * Figure out the value of window scale opton.  Note that the rwnd is
1426  * ASSUMED to be rounded up to the nearest MSS before the calculation.
1427  * We cannot find the scale value and then do a round up of tcp_rwnd
1428  * because the scale value may not be correct after that.
1429  *
1430  * Set the compiler flag to make this function inline.
1431  */
1432 static void
1433 tcp_set_ws_value(tcp_t *tcp)
1434 {
1435 	int i;
1436 	uint32_t rwnd = tcp->tcp_rwnd;
1437 
1438 	for (i = 0; rwnd > TCP_MAXWIN && i < TCP_MAX_WINSHIFT;
1439 	    i++, rwnd >>= 1)
1440 		;
1441 	tcp->tcp_rcv_ws = i;
1442 }
1443 
1444 /*
1445  * Remove a connection from the list of detached TIME_WAIT connections.
1446  * It returns B_FALSE if it can't remove the connection from the list
1447  * as the connection has already been removed from the list due to an
1448  * earlier call to tcp_time_wait_remove(); otherwise it returns B_TRUE.
1449  */
1450 static boolean_t
1451 tcp_time_wait_remove(tcp_t *tcp, tcp_squeue_priv_t *tcp_time_wait)
1452 {
1453 	boolean_t	locked = B_FALSE;
1454 
1455 	if (tcp_time_wait == NULL) {
1456 		tcp_time_wait = *((tcp_squeue_priv_t **)
1457 		    squeue_getprivate(tcp->tcp_connp->conn_sqp, SQPRIVATE_TCP));
1458 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1459 		locked = B_TRUE;
1460 	} else {
1461 		ASSERT(MUTEX_HELD(&tcp_time_wait->tcp_time_wait_lock));
1462 	}
1463 
1464 	if (tcp->tcp_time_wait_expire == 0) {
1465 		ASSERT(tcp->tcp_time_wait_next == NULL);
1466 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1467 		if (locked)
1468 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1469 		return (B_FALSE);
1470 	}
1471 	ASSERT(TCP_IS_DETACHED(tcp));
1472 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1473 
1474 	if (tcp == tcp_time_wait->tcp_time_wait_head) {
1475 		ASSERT(tcp->tcp_time_wait_prev == NULL);
1476 		tcp_time_wait->tcp_time_wait_head = tcp->tcp_time_wait_next;
1477 		if (tcp_time_wait->tcp_time_wait_head != NULL) {
1478 			tcp_time_wait->tcp_time_wait_head->tcp_time_wait_prev =
1479 			    NULL;
1480 		} else {
1481 			tcp_time_wait->tcp_time_wait_tail = NULL;
1482 		}
1483 	} else if (tcp == tcp_time_wait->tcp_time_wait_tail) {
1484 		ASSERT(tcp != tcp_time_wait->tcp_time_wait_head);
1485 		ASSERT(tcp->tcp_time_wait_next == NULL);
1486 		tcp_time_wait->tcp_time_wait_tail = tcp->tcp_time_wait_prev;
1487 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1488 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = NULL;
1489 	} else {
1490 		ASSERT(tcp->tcp_time_wait_prev->tcp_time_wait_next == tcp);
1491 		ASSERT(tcp->tcp_time_wait_next->tcp_time_wait_prev == tcp);
1492 		tcp->tcp_time_wait_prev->tcp_time_wait_next =
1493 		    tcp->tcp_time_wait_next;
1494 		tcp->tcp_time_wait_next->tcp_time_wait_prev =
1495 		    tcp->tcp_time_wait_prev;
1496 	}
1497 	tcp->tcp_time_wait_next = NULL;
1498 	tcp->tcp_time_wait_prev = NULL;
1499 	tcp->tcp_time_wait_expire = 0;
1500 
1501 	if (locked)
1502 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1503 	return (B_TRUE);
1504 }
1505 
1506 /*
1507  * Add a connection to the list of detached TIME_WAIT connections
1508  * and set its time to expire.
1509  */
1510 static void
1511 tcp_time_wait_append(tcp_t *tcp)
1512 {
1513 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1514 	tcp_squeue_priv_t *tcp_time_wait =
1515 	    *((tcp_squeue_priv_t **)squeue_getprivate(tcp->tcp_connp->conn_sqp,
1516 	    SQPRIVATE_TCP));
1517 
1518 	tcp_timers_stop(tcp);
1519 
1520 	/* Freed above */
1521 	ASSERT(tcp->tcp_timer_tid == 0);
1522 	ASSERT(tcp->tcp_ack_tid == 0);
1523 
1524 	/* must have happened at the time of detaching the tcp */
1525 	ASSERT(tcp->tcp_ptpahn == NULL);
1526 	ASSERT(tcp->tcp_flow_stopped == 0);
1527 	ASSERT(tcp->tcp_time_wait_next == NULL);
1528 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1529 	ASSERT(tcp->tcp_time_wait_expire == NULL);
1530 	ASSERT(tcp->tcp_listener == NULL);
1531 
1532 	tcp->tcp_time_wait_expire = ddi_get_lbolt();
1533 	/*
1534 	 * The value computed below in tcp->tcp_time_wait_expire may
1535 	 * appear negative or wrap around. That is ok since our
1536 	 * interest is only in the difference between the current lbolt
1537 	 * value and tcp->tcp_time_wait_expire. But the value should not
1538 	 * be zero, since it means the tcp is not in the TIME_WAIT list.
1539 	 * The corresponding comparison in tcp_time_wait_collector() uses
1540 	 * modular arithmetic.
1541 	 */
1542 	tcp->tcp_time_wait_expire +=
1543 	    drv_usectohz(tcps->tcps_time_wait_interval * 1000);
1544 	if (tcp->tcp_time_wait_expire == 0)
1545 		tcp->tcp_time_wait_expire = 1;
1546 
1547 	ASSERT(TCP_IS_DETACHED(tcp));
1548 	ASSERT(tcp->tcp_state == TCPS_TIME_WAIT);
1549 	ASSERT(tcp->tcp_time_wait_next == NULL);
1550 	ASSERT(tcp->tcp_time_wait_prev == NULL);
1551 	TCP_DBGSTAT(tcps, tcp_time_wait);
1552 
1553 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1554 	if (tcp_time_wait->tcp_time_wait_head == NULL) {
1555 		ASSERT(tcp_time_wait->tcp_time_wait_tail == NULL);
1556 		tcp_time_wait->tcp_time_wait_head = tcp;
1557 	} else {
1558 		ASSERT(tcp_time_wait->tcp_time_wait_tail != NULL);
1559 		ASSERT(tcp_time_wait->tcp_time_wait_tail->tcp_state ==
1560 		    TCPS_TIME_WAIT);
1561 		tcp_time_wait->tcp_time_wait_tail->tcp_time_wait_next = tcp;
1562 		tcp->tcp_time_wait_prev = tcp_time_wait->tcp_time_wait_tail;
1563 	}
1564 	tcp_time_wait->tcp_time_wait_tail = tcp;
1565 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1566 }
1567 
1568 /* ARGSUSED */
1569 void
1570 tcp_timewait_output(void *arg, mblk_t *mp, void *arg2)
1571 {
1572 	conn_t	*connp = (conn_t *)arg;
1573 	tcp_t	*tcp = connp->conn_tcp;
1574 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1575 
1576 	ASSERT(tcp != NULL);
1577 	if (tcp->tcp_state == TCPS_CLOSED) {
1578 		return;
1579 	}
1580 
1581 	ASSERT((tcp->tcp_family == AF_INET &&
1582 	    tcp->tcp_ipversion == IPV4_VERSION) ||
1583 	    (tcp->tcp_family == AF_INET6 &&
1584 	    (tcp->tcp_ipversion == IPV4_VERSION ||
1585 	    tcp->tcp_ipversion == IPV6_VERSION)));
1586 	ASSERT(!tcp->tcp_listener);
1587 
1588 	TCP_STAT(tcps, tcp_time_wait_reap);
1589 	ASSERT(TCP_IS_DETACHED(tcp));
1590 
1591 	/*
1592 	 * Because they have no upstream client to rebind or tcp_close()
1593 	 * them later, we axe the connection here and now.
1594 	 */
1595 	tcp_close_detached(tcp);
1596 }
1597 
1598 /*
1599  * Remove cached/latched IPsec references.
1600  */
1601 void
1602 tcp_ipsec_cleanup(tcp_t *tcp)
1603 {
1604 	conn_t		*connp = tcp->tcp_connp;
1605 
1606 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1607 
1608 	if (connp->conn_latch != NULL) {
1609 		IPLATCH_REFRELE(connp->conn_latch,
1610 		    connp->conn_netstack);
1611 		connp->conn_latch = NULL;
1612 	}
1613 	if (connp->conn_policy != NULL) {
1614 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
1615 		connp->conn_policy = NULL;
1616 	}
1617 }
1618 
1619 /*
1620  * Cleaup before placing on free list.
1621  * Disassociate from the netstack/tcp_stack_t since the freelist
1622  * is per squeue and not per netstack.
1623  */
1624 void
1625 tcp_cleanup(tcp_t *tcp)
1626 {
1627 	mblk_t		*mp;
1628 	char		*tcp_iphc;
1629 	int		tcp_iphc_len;
1630 	int		tcp_hdr_grown;
1631 	tcp_sack_info_t	*tcp_sack_info;
1632 	conn_t		*connp = tcp->tcp_connp;
1633 	tcp_stack_t	*tcps = tcp->tcp_tcps;
1634 	netstack_t	*ns = tcps->tcps_netstack;
1635 	mblk_t		*tcp_rsrv_mp;
1636 
1637 	tcp_bind_hash_remove(tcp);
1638 
1639 	/* Cleanup that which needs the netstack first */
1640 	tcp_ipsec_cleanup(tcp);
1641 
1642 	tcp_free(tcp);
1643 
1644 	/* Release any SSL context */
1645 	if (tcp->tcp_kssl_ent != NULL) {
1646 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
1647 		tcp->tcp_kssl_ent = NULL;
1648 	}
1649 
1650 	if (tcp->tcp_kssl_ctx != NULL) {
1651 		kssl_release_ctx(tcp->tcp_kssl_ctx);
1652 		tcp->tcp_kssl_ctx = NULL;
1653 	}
1654 	tcp->tcp_kssl_pending = B_FALSE;
1655 
1656 	conn_delete_ire(connp, NULL);
1657 
1658 	/*
1659 	 * Since we will bzero the entire structure, we need to
1660 	 * remove it and reinsert it in global hash list. We
1661 	 * know the walkers can't get to this conn because we
1662 	 * had set CONDEMNED flag earlier and checked reference
1663 	 * under conn_lock so walker won't pick it and when we
1664 	 * go the ipcl_globalhash_remove() below, no walker
1665 	 * can get to it.
1666 	 */
1667 	ipcl_globalhash_remove(connp);
1668 
1669 	/*
1670 	 * Now it is safe to decrement the reference counts.
1671 	 * This might be the last reference on the netstack and TCPS
1672 	 * in which case it will cause the tcp_g_q_close and
1673 	 * the freeing of the IP Instance.
1674 	 */
1675 	connp->conn_netstack = NULL;
1676 	netstack_rele(ns);
1677 	ASSERT(tcps != NULL);
1678 	tcp->tcp_tcps = NULL;
1679 	TCPS_REFRELE(tcps);
1680 
1681 	/* Save some state */
1682 	mp = tcp->tcp_timercache;
1683 
1684 	tcp_sack_info = tcp->tcp_sack_info;
1685 	tcp_iphc = tcp->tcp_iphc;
1686 	tcp_iphc_len = tcp->tcp_iphc_len;
1687 	tcp_hdr_grown = tcp->tcp_hdr_grown;
1688 	tcp_rsrv_mp = tcp->tcp_rsrv_mp;
1689 
1690 	if (connp->conn_cred != NULL) {
1691 		crfree(connp->conn_cred);
1692 		connp->conn_cred = NULL;
1693 	}
1694 	if (connp->conn_peercred != NULL) {
1695 		crfree(connp->conn_peercred);
1696 		connp->conn_peercred = NULL;
1697 	}
1698 	ipcl_conn_cleanup(connp);
1699 	connp->conn_flags = IPCL_TCPCONN;
1700 	bzero(tcp, sizeof (tcp_t));
1701 
1702 	/* restore the state */
1703 	tcp->tcp_timercache = mp;
1704 
1705 	tcp->tcp_sack_info = tcp_sack_info;
1706 	tcp->tcp_iphc = tcp_iphc;
1707 	tcp->tcp_iphc_len = tcp_iphc_len;
1708 	tcp->tcp_hdr_grown = tcp_hdr_grown;
1709 	tcp->tcp_rsrv_mp = tcp_rsrv_mp;
1710 
1711 	tcp->tcp_connp = connp;
1712 
1713 	ASSERT(connp->conn_tcp == tcp);
1714 	ASSERT(connp->conn_flags & IPCL_TCPCONN);
1715 	connp->conn_state_flags = CONN_INCIPIENT;
1716 	ASSERT(connp->conn_ulp == IPPROTO_TCP);
1717 	ASSERT(connp->conn_ref == 1);
1718 }
1719 
1720 /*
1721  * Blows away all tcps whose TIME_WAIT has expired. List traversal
1722  * is done forwards from the head.
1723  * This walks all stack instances since
1724  * tcp_time_wait remains global across all stacks.
1725  */
1726 /* ARGSUSED */
1727 void
1728 tcp_time_wait_collector(void *arg)
1729 {
1730 	tcp_t *tcp;
1731 	clock_t now;
1732 	mblk_t *mp;
1733 	conn_t *connp;
1734 	kmutex_t *lock;
1735 	boolean_t removed;
1736 
1737 	squeue_t *sqp = (squeue_t *)arg;
1738 	tcp_squeue_priv_t *tcp_time_wait =
1739 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
1740 
1741 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1742 	tcp_time_wait->tcp_time_wait_tid = 0;
1743 
1744 	if (tcp_time_wait->tcp_free_list != NULL &&
1745 	    tcp_time_wait->tcp_free_list->tcp_in_free_list == B_TRUE) {
1746 		TCP_G_STAT(tcp_freelist_cleanup);
1747 		while ((tcp = tcp_time_wait->tcp_free_list) != NULL) {
1748 			tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
1749 			tcp->tcp_time_wait_next = NULL;
1750 			tcp_time_wait->tcp_free_list_cnt--;
1751 			ASSERT(tcp->tcp_tcps == NULL);
1752 			CONN_DEC_REF(tcp->tcp_connp);
1753 		}
1754 		ASSERT(tcp_time_wait->tcp_free_list_cnt == 0);
1755 	}
1756 
1757 	/*
1758 	 * In order to reap time waits reliably, we should use a
1759 	 * source of time that is not adjustable by the user -- hence
1760 	 * the call to ddi_get_lbolt().
1761 	 */
1762 	now = ddi_get_lbolt();
1763 	while ((tcp = tcp_time_wait->tcp_time_wait_head) != NULL) {
1764 		/*
1765 		 * Compare times using modular arithmetic, since
1766 		 * lbolt can wrapover.
1767 		 */
1768 		if ((now - tcp->tcp_time_wait_expire) < 0) {
1769 			break;
1770 		}
1771 
1772 		removed = tcp_time_wait_remove(tcp, tcp_time_wait);
1773 		ASSERT(removed);
1774 
1775 		connp = tcp->tcp_connp;
1776 		ASSERT(connp->conn_fanout != NULL);
1777 		lock = &connp->conn_fanout->connf_lock;
1778 		/*
1779 		 * This is essentially a TW reclaim fast path optimization for
1780 		 * performance where the timewait collector checks under the
1781 		 * fanout lock (so that no one else can get access to the
1782 		 * conn_t) that the refcnt is 2 i.e. one for TCP and one for
1783 		 * the classifier hash list. If ref count is indeed 2, we can
1784 		 * just remove the conn under the fanout lock and avoid
1785 		 * cleaning up the conn under the squeue, provided that
1786 		 * clustering callbacks are not enabled. If clustering is
1787 		 * enabled, we need to make the clustering callback before
1788 		 * setting the CONDEMNED flag and after dropping all locks and
1789 		 * so we forego this optimization and fall back to the slow
1790 		 * path. Also please see the comments in tcp_closei_local
1791 		 * regarding the refcnt logic.
1792 		 *
1793 		 * Since we are holding the tcp_time_wait_lock, its better
1794 		 * not to block on the fanout_lock because other connections
1795 		 * can't add themselves to time_wait list. So we do a
1796 		 * tryenter instead of mutex_enter.
1797 		 */
1798 		if (mutex_tryenter(lock)) {
1799 			mutex_enter(&connp->conn_lock);
1800 			if ((connp->conn_ref == 2) &&
1801 			    (cl_inet_disconnect == NULL)) {
1802 				ipcl_hash_remove_locked(connp,
1803 				    connp->conn_fanout);
1804 				/*
1805 				 * Set the CONDEMNED flag now itself so that
1806 				 * the refcnt cannot increase due to any
1807 				 * walker. But we have still not cleaned up
1808 				 * conn_ire_cache. This is still ok since
1809 				 * we are going to clean it up in tcp_cleanup
1810 				 * immediately and any interface unplumb
1811 				 * thread will wait till the ire is blown away
1812 				 */
1813 				connp->conn_state_flags |= CONN_CONDEMNED;
1814 				mutex_exit(lock);
1815 				mutex_exit(&connp->conn_lock);
1816 				if (tcp_time_wait->tcp_free_list_cnt <
1817 				    tcp_free_list_max_cnt) {
1818 					/* Add to head of tcp_free_list */
1819 					mutex_exit(
1820 					    &tcp_time_wait->tcp_time_wait_lock);
1821 					tcp_cleanup(tcp);
1822 					ASSERT(connp->conn_latch == NULL);
1823 					ASSERT(connp->conn_policy == NULL);
1824 					ASSERT(tcp->tcp_tcps == NULL);
1825 					ASSERT(connp->conn_netstack == NULL);
1826 
1827 					mutex_enter(
1828 					    &tcp_time_wait->tcp_time_wait_lock);
1829 					tcp->tcp_time_wait_next =
1830 					    tcp_time_wait->tcp_free_list;
1831 					tcp_time_wait->tcp_free_list = tcp;
1832 					tcp_time_wait->tcp_free_list_cnt++;
1833 					continue;
1834 				} else {
1835 					/* Do not add to tcp_free_list */
1836 					mutex_exit(
1837 					    &tcp_time_wait->tcp_time_wait_lock);
1838 					tcp_bind_hash_remove(tcp);
1839 					conn_delete_ire(tcp->tcp_connp, NULL);
1840 					tcp_ipsec_cleanup(tcp);
1841 					CONN_DEC_REF(tcp->tcp_connp);
1842 				}
1843 			} else {
1844 				CONN_INC_REF_LOCKED(connp);
1845 				mutex_exit(lock);
1846 				mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1847 				mutex_exit(&connp->conn_lock);
1848 				/*
1849 				 * We can reuse the closemp here since conn has
1850 				 * detached (otherwise we wouldn't even be in
1851 				 * time_wait list). tcp_closemp_used can safely
1852 				 * be changed without taking a lock as no other
1853 				 * thread can concurrently access it at this
1854 				 * point in the connection lifecycle.
1855 				 */
1856 
1857 				if (tcp->tcp_closemp.b_prev == NULL)
1858 					tcp->tcp_closemp_used = B_TRUE;
1859 				else
1860 					cmn_err(CE_PANIC,
1861 					    "tcp_timewait_collector: "
1862 					    "concurrent use of tcp_closemp: "
1863 					    "connp %p tcp %p\n", (void *)connp,
1864 					    (void *)tcp);
1865 
1866 				TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1867 				mp = &tcp->tcp_closemp;
1868 				squeue_fill(connp->conn_sqp, mp,
1869 				    tcp_timewait_output, connp,
1870 				    SQTAG_TCP_TIMEWAIT);
1871 			}
1872 		} else {
1873 			mutex_enter(&connp->conn_lock);
1874 			CONN_INC_REF_LOCKED(connp);
1875 			mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1876 			mutex_exit(&connp->conn_lock);
1877 			/*
1878 			 * We can reuse the closemp here since conn has
1879 			 * detached (otherwise we wouldn't even be in
1880 			 * time_wait list). tcp_closemp_used can safely
1881 			 * be changed without taking a lock as no other
1882 			 * thread can concurrently access it at this
1883 			 * point in the connection lifecycle.
1884 			 */
1885 
1886 			if (tcp->tcp_closemp.b_prev == NULL)
1887 				tcp->tcp_closemp_used = B_TRUE;
1888 			else
1889 				cmn_err(CE_PANIC, "tcp_timewait_collector: "
1890 				    "concurrent use of tcp_closemp: "
1891 				    "connp %p tcp %p\n", (void *)connp,
1892 				    (void *)tcp);
1893 
1894 			TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
1895 			mp = &tcp->tcp_closemp;
1896 			squeue_fill(connp->conn_sqp, mp,
1897 			    tcp_timewait_output, connp, 0);
1898 		}
1899 		mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
1900 	}
1901 
1902 	if (tcp_time_wait->tcp_free_list != NULL)
1903 		tcp_time_wait->tcp_free_list->tcp_in_free_list = B_TRUE;
1904 
1905 	tcp_time_wait->tcp_time_wait_tid =
1906 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
1907 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
1908 	    CALLOUT_FLAG_ROUNDUP);
1909 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
1910 }
1911 /*
1912  * Reply to a clients T_CONN_RES TPI message. This function
1913  * is used only for TLI/XTI listener. Sockfs sends T_CONN_RES
1914  * on the acceptor STREAM and processed in tcp_wput_accept().
1915  * Read the block comment on top of tcp_conn_request().
1916  */
1917 static void
1918 tcp_accept(tcp_t *listener, mblk_t *mp)
1919 {
1920 	tcp_t	*acceptor;
1921 	tcp_t	*eager;
1922 	tcp_t   *tcp;
1923 	struct T_conn_res	*tcr;
1924 	t_uscalar_t	acceptor_id;
1925 	t_scalar_t	seqnum;
1926 	mblk_t	*opt_mp = NULL;	/* T_OPTMGMT_REQ messages */
1927 	mblk_t	*ok_mp;
1928 	mblk_t	*mp1;
1929 	tcp_stack_t	*tcps = listener->tcp_tcps;
1930 
1931 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
1932 		tcp_err_ack(listener, mp, TPROTO, 0);
1933 		return;
1934 	}
1935 	tcr = (struct T_conn_res *)mp->b_rptr;
1936 
1937 	/*
1938 	 * Under ILP32 the stream head points tcr->ACCEPTOR_id at the
1939 	 * read side queue of the streams device underneath us i.e. the
1940 	 * read side queue of 'ip'. Since we can't deference QUEUE_ptr we
1941 	 * look it up in the queue_hash.  Under LP64 it sends down the
1942 	 * minor_t of the accepting endpoint.
1943 	 *
1944 	 * Once the acceptor/eager are modified (in tcp_accept_swap) the
1945 	 * fanout hash lock is held.
1946 	 * This prevents any thread from entering the acceptor queue from
1947 	 * below (since it has not been hard bound yet i.e. any inbound
1948 	 * packets will arrive on the listener or default tcp queue and
1949 	 * go through tcp_lookup).
1950 	 * The CONN_INC_REF will prevent the acceptor from closing.
1951 	 *
1952 	 * XXX It is still possible for a tli application to send down data
1953 	 * on the accepting stream while another thread calls t_accept.
1954 	 * This should not be a problem for well-behaved applications since
1955 	 * the T_OK_ACK is sent after the queue swapping is completed.
1956 	 *
1957 	 * If the accepting fd is the same as the listening fd, avoid
1958 	 * queue hash lookup since that will return an eager listener in a
1959 	 * already established state.
1960 	 */
1961 	acceptor_id = tcr->ACCEPTOR_id;
1962 	mutex_enter(&listener->tcp_eager_lock);
1963 	if (listener->tcp_acceptor_id == acceptor_id) {
1964 		eager = listener->tcp_eager_next_q;
1965 		/* only count how many T_CONN_INDs so don't count q0 */
1966 		if ((listener->tcp_conn_req_cnt_q != 1) ||
1967 		    (eager->tcp_conn_req_seqnum != tcr->SEQ_number)) {
1968 			mutex_exit(&listener->tcp_eager_lock);
1969 			tcp_err_ack(listener, mp, TBADF, 0);
1970 			return;
1971 		}
1972 		if (listener->tcp_conn_req_cnt_q0 != 0) {
1973 			/* Throw away all the eagers on q0. */
1974 			tcp_eager_cleanup(listener, 1);
1975 		}
1976 		if (listener->tcp_syn_defense) {
1977 			listener->tcp_syn_defense = B_FALSE;
1978 			if (listener->tcp_ip_addr_cache != NULL) {
1979 				kmem_free(listener->tcp_ip_addr_cache,
1980 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
1981 				listener->tcp_ip_addr_cache = NULL;
1982 			}
1983 		}
1984 		/*
1985 		 * Transfer tcp_conn_req_max to the eager so that when
1986 		 * a disconnect occurs we can revert the endpoint to the
1987 		 * listen state.
1988 		 */
1989 		eager->tcp_conn_req_max = listener->tcp_conn_req_max;
1990 		ASSERT(listener->tcp_conn_req_cnt_q0 == 0);
1991 		/*
1992 		 * Get a reference on the acceptor just like the
1993 		 * tcp_acceptor_hash_lookup below.
1994 		 */
1995 		acceptor = listener;
1996 		CONN_INC_REF(acceptor->tcp_connp);
1997 	} else {
1998 		acceptor = tcp_acceptor_hash_lookup(acceptor_id, tcps);
1999 		if (acceptor == NULL) {
2000 			if (listener->tcp_debug) {
2001 				(void) strlog(TCP_MOD_ID, 0, 1,
2002 				    SL_ERROR|SL_TRACE,
2003 				    "tcp_accept: did not find acceptor 0x%x\n",
2004 				    acceptor_id);
2005 			}
2006 			mutex_exit(&listener->tcp_eager_lock);
2007 			tcp_err_ack(listener, mp, TPROVMISMATCH, 0);
2008 			return;
2009 		}
2010 		/*
2011 		 * Verify acceptor state. The acceptable states for an acceptor
2012 		 * include TCPS_IDLE and TCPS_BOUND.
2013 		 */
2014 		switch (acceptor->tcp_state) {
2015 		case TCPS_IDLE:
2016 			/* FALLTHRU */
2017 		case TCPS_BOUND:
2018 			break;
2019 		default:
2020 			CONN_DEC_REF(acceptor->tcp_connp);
2021 			mutex_exit(&listener->tcp_eager_lock);
2022 			tcp_err_ack(listener, mp, TOUTSTATE, 0);
2023 			return;
2024 		}
2025 	}
2026 
2027 	/* The listener must be in TCPS_LISTEN */
2028 	if (listener->tcp_state != TCPS_LISTEN) {
2029 		CONN_DEC_REF(acceptor->tcp_connp);
2030 		mutex_exit(&listener->tcp_eager_lock);
2031 		tcp_err_ack(listener, mp, TOUTSTATE, 0);
2032 		return;
2033 	}
2034 
2035 	/*
2036 	 * Rendezvous with an eager connection request packet hanging off
2037 	 * 'tcp' that has the 'seqnum' tag.  We tagged the detached open
2038 	 * tcp structure when the connection packet arrived in
2039 	 * tcp_conn_request().
2040 	 */
2041 	seqnum = tcr->SEQ_number;
2042 	eager = listener;
2043 	do {
2044 		eager = eager->tcp_eager_next_q;
2045 		if (eager == NULL) {
2046 			CONN_DEC_REF(acceptor->tcp_connp);
2047 			mutex_exit(&listener->tcp_eager_lock);
2048 			tcp_err_ack(listener, mp, TBADSEQ, 0);
2049 			return;
2050 		}
2051 	} while (eager->tcp_conn_req_seqnum != seqnum);
2052 	mutex_exit(&listener->tcp_eager_lock);
2053 
2054 	/*
2055 	 * At this point, both acceptor and listener have 2 ref
2056 	 * that they begin with. Acceptor has one additional ref
2057 	 * we placed in lookup while listener has 3 additional
2058 	 * ref for being behind the squeue (tcp_accept() is
2059 	 * done on listener's squeue); being in classifier hash;
2060 	 * and eager's ref on listener.
2061 	 */
2062 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2063 	ASSERT(acceptor->tcp_connp->conn_ref >= 3);
2064 
2065 	/*
2066 	 * The eager at this point is set in its own squeue and
2067 	 * could easily have been killed (tcp_accept_finish will
2068 	 * deal with that) because of a TH_RST so we can only
2069 	 * ASSERT for a single ref.
2070 	 */
2071 	ASSERT(eager->tcp_connp->conn_ref >= 1);
2072 
2073 	/* Pre allocate the stroptions mblk also */
2074 	opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
2075 	if (opt_mp == NULL) {
2076 		CONN_DEC_REF(acceptor->tcp_connp);
2077 		CONN_DEC_REF(eager->tcp_connp);
2078 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2079 		return;
2080 	}
2081 	DB_TYPE(opt_mp) = M_SETOPTS;
2082 	opt_mp->b_wptr += sizeof (struct stroptions);
2083 
2084 	/*
2085 	 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
2086 	 * from listener to acceptor. The message is chained on opt_mp
2087 	 * which will be sent onto eager's squeue.
2088 	 */
2089 	if (listener->tcp_bound_if != 0) {
2090 		/* allocate optmgmt req */
2091 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2092 		    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
2093 		    sizeof (int));
2094 		if (mp1 != NULL)
2095 			linkb(opt_mp, mp1);
2096 	}
2097 	if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
2098 		uint_t on = 1;
2099 
2100 		/* allocate optmgmt req */
2101 		mp1 = tcp_setsockopt_mp(IPPROTO_IPV6,
2102 		    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
2103 		if (mp1 != NULL)
2104 			linkb(opt_mp, mp1);
2105 	}
2106 
2107 	/* Re-use mp1 to hold a copy of mp, in case reallocb fails */
2108 	if ((mp1 = copymsg(mp)) == NULL) {
2109 		CONN_DEC_REF(acceptor->tcp_connp);
2110 		CONN_DEC_REF(eager->tcp_connp);
2111 		freemsg(opt_mp);
2112 		tcp_err_ack(listener, mp, TSYSERR, ENOMEM);
2113 		return;
2114 	}
2115 
2116 	tcr = (struct T_conn_res *)mp1->b_rptr;
2117 
2118 	/*
2119 	 * This is an expanded version of mi_tpi_ok_ack_alloc()
2120 	 * which allocates a larger mblk and appends the new
2121 	 * local address to the ok_ack.  The address is copied by
2122 	 * soaccept() for getsockname().
2123 	 */
2124 	{
2125 		int extra;
2126 
2127 		extra = (eager->tcp_family == AF_INET) ?
2128 		    sizeof (sin_t) : sizeof (sin6_t);
2129 
2130 		/*
2131 		 * Try to re-use mp, if possible.  Otherwise, allocate
2132 		 * an mblk and return it as ok_mp.  In any case, mp
2133 		 * is no longer usable upon return.
2134 		 */
2135 		if ((ok_mp = mi_tpi_ok_ack_alloc_extra(mp, extra)) == NULL) {
2136 			CONN_DEC_REF(acceptor->tcp_connp);
2137 			CONN_DEC_REF(eager->tcp_connp);
2138 			freemsg(opt_mp);
2139 			/* Original mp has been freed by now, so use mp1 */
2140 			tcp_err_ack(listener, mp1, TSYSERR, ENOMEM);
2141 			return;
2142 		}
2143 
2144 		mp = NULL;	/* We should never use mp after this point */
2145 
2146 		switch (extra) {
2147 		case sizeof (sin_t): {
2148 				sin_t *sin = (sin_t *)ok_mp->b_wptr;
2149 
2150 				ok_mp->b_wptr += extra;
2151 				sin->sin_family = AF_INET;
2152 				sin->sin_port = eager->tcp_lport;
2153 				sin->sin_addr.s_addr =
2154 				    eager->tcp_ipha->ipha_src;
2155 				break;
2156 			}
2157 		case sizeof (sin6_t): {
2158 				sin6_t *sin6 = (sin6_t *)ok_mp->b_wptr;
2159 
2160 				ok_mp->b_wptr += extra;
2161 				sin6->sin6_family = AF_INET6;
2162 				sin6->sin6_port = eager->tcp_lport;
2163 				if (eager->tcp_ipversion == IPV4_VERSION) {
2164 					sin6->sin6_flowinfo = 0;
2165 					IN6_IPADDR_TO_V4MAPPED(
2166 					    eager->tcp_ipha->ipha_src,
2167 					    &sin6->sin6_addr);
2168 				} else {
2169 					ASSERT(eager->tcp_ip6h != NULL);
2170 					sin6->sin6_flowinfo =
2171 					    eager->tcp_ip6h->ip6_vcf &
2172 					    ~IPV6_VERS_AND_FLOW_MASK;
2173 					sin6->sin6_addr =
2174 					    eager->tcp_ip6h->ip6_src;
2175 				}
2176 				sin6->sin6_scope_id = 0;
2177 				sin6->__sin6_src_id = 0;
2178 				break;
2179 			}
2180 		default:
2181 			break;
2182 		}
2183 		ASSERT(ok_mp->b_wptr <= ok_mp->b_datap->db_lim);
2184 	}
2185 
2186 	/*
2187 	 * If there are no options we know that the T_CONN_RES will
2188 	 * succeed. However, we can't send the T_OK_ACK upstream until
2189 	 * the tcp_accept_swap is done since it would be dangerous to
2190 	 * let the application start using the new fd prior to the swap.
2191 	 */
2192 	tcp_accept_swap(listener, acceptor, eager);
2193 
2194 	/*
2195 	 * tcp_accept_swap unlinks eager from listener but does not drop
2196 	 * the eager's reference on the listener.
2197 	 */
2198 	ASSERT(eager->tcp_listener == NULL);
2199 	ASSERT(listener->tcp_connp->conn_ref >= 5);
2200 
2201 	/*
2202 	 * The eager is now associated with its own queue. Insert in
2203 	 * the hash so that the connection can be reused for a future
2204 	 * T_CONN_RES.
2205 	 */
2206 	tcp_acceptor_hash_insert(acceptor_id, eager);
2207 
2208 	/*
2209 	 * We now do the processing of options with T_CONN_RES.
2210 	 * We delay till now since we wanted to have queue to pass to
2211 	 * option processing routines that points back to the right
2212 	 * instance structure which does not happen until after
2213 	 * tcp_accept_swap().
2214 	 *
2215 	 * Note:
2216 	 * The sanity of the logic here assumes that whatever options
2217 	 * are appropriate to inherit from listner=>eager are done
2218 	 * before this point, and whatever were to be overridden (or not)
2219 	 * in transfer logic from eager=>acceptor in tcp_accept_swap().
2220 	 * [ Warning: acceptor endpoint can have T_OPTMGMT_REQ done to it
2221 	 *   before its ACCEPTOR_id comes down in T_CONN_RES ]
2222 	 * This may not be true at this point in time but can be fixed
2223 	 * independently. This option processing code starts with
2224 	 * the instantiated acceptor instance and the final queue at
2225 	 * this point.
2226 	 */
2227 
2228 	if (tcr->OPT_length != 0) {
2229 		/* Options to process */
2230 		int t_error = 0;
2231 		int sys_error = 0;
2232 		int do_disconnect = 0;
2233 
2234 		if (tcp_conprim_opt_process(eager, mp1,
2235 		    &do_disconnect, &t_error, &sys_error) < 0) {
2236 			eager->tcp_accept_error = 1;
2237 			if (do_disconnect) {
2238 				/*
2239 				 * An option failed which does not allow
2240 				 * connection to be accepted.
2241 				 *
2242 				 * We allow T_CONN_RES to succeed and
2243 				 * put a T_DISCON_IND on the eager queue.
2244 				 */
2245 				ASSERT(t_error == 0 && sys_error == 0);
2246 				eager->tcp_send_discon_ind = 1;
2247 			} else {
2248 				ASSERT(t_error != 0);
2249 				freemsg(ok_mp);
2250 				/*
2251 				 * Original mp was either freed or set
2252 				 * to ok_mp above, so use mp1 instead.
2253 				 */
2254 				tcp_err_ack(listener, mp1, t_error, sys_error);
2255 				goto finish;
2256 			}
2257 		}
2258 		/*
2259 		 * Most likely success in setting options (except if
2260 		 * eager->tcp_send_discon_ind set).
2261 		 * mp1 option buffer represented by OPT_length/offset
2262 		 * potentially modified and contains results of setting
2263 		 * options at this point
2264 		 */
2265 	}
2266 
2267 	/* We no longer need mp1, since all options processing has passed */
2268 	freemsg(mp1);
2269 
2270 	putnext(listener->tcp_rq, ok_mp);
2271 
2272 	mutex_enter(&listener->tcp_eager_lock);
2273 	if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
2274 		tcp_t	*tail;
2275 		mblk_t	*conn_ind;
2276 
2277 		/*
2278 		 * This path should not be executed if listener and
2279 		 * acceptor streams are the same.
2280 		 */
2281 		ASSERT(listener != acceptor);
2282 
2283 		tcp = listener->tcp_eager_prev_q0;
2284 		/*
2285 		 * listener->tcp_eager_prev_q0 points to the TAIL of the
2286 		 * deferred T_conn_ind queue. We need to get to the head of
2287 		 * the queue in order to send up T_conn_ind the same order as
2288 		 * how the 3WHS is completed.
2289 		 */
2290 		while (tcp != listener) {
2291 			if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0)
2292 				break;
2293 			else
2294 				tcp = tcp->tcp_eager_prev_q0;
2295 		}
2296 		ASSERT(tcp != listener);
2297 		conn_ind = tcp->tcp_conn.tcp_eager_conn_ind;
2298 		ASSERT(conn_ind != NULL);
2299 		tcp->tcp_conn.tcp_eager_conn_ind = NULL;
2300 
2301 		/* Move from q0 to q */
2302 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
2303 		listener->tcp_conn_req_cnt_q0--;
2304 		listener->tcp_conn_req_cnt_q++;
2305 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
2306 		    tcp->tcp_eager_prev_q0;
2307 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
2308 		    tcp->tcp_eager_next_q0;
2309 		tcp->tcp_eager_prev_q0 = NULL;
2310 		tcp->tcp_eager_next_q0 = NULL;
2311 		tcp->tcp_conn_def_q0 = B_FALSE;
2312 
2313 		/* Make sure the tcp isn't in the list of droppables */
2314 		ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
2315 		    tcp->tcp_eager_prev_drop_q0 == NULL);
2316 
2317 		/*
2318 		 * Insert at end of the queue because sockfs sends
2319 		 * down T_CONN_RES in chronological order. Leaving
2320 		 * the older conn indications at front of the queue
2321 		 * helps reducing search time.
2322 		 */
2323 		tail = listener->tcp_eager_last_q;
2324 		if (tail != NULL)
2325 			tail->tcp_eager_next_q = tcp;
2326 		else
2327 			listener->tcp_eager_next_q = tcp;
2328 		listener->tcp_eager_last_q = tcp;
2329 		tcp->tcp_eager_next_q = NULL;
2330 		mutex_exit(&listener->tcp_eager_lock);
2331 		putnext(tcp->tcp_rq, conn_ind);
2332 	} else {
2333 		mutex_exit(&listener->tcp_eager_lock);
2334 	}
2335 
2336 	/*
2337 	 * Done with the acceptor - free it
2338 	 *
2339 	 * Note: from this point on, no access to listener should be made
2340 	 * as listener can be equal to acceptor.
2341 	 */
2342 finish:
2343 	ASSERT(acceptor->tcp_detached);
2344 	ASSERT(tcps->tcps_g_q != NULL);
2345 	acceptor->tcp_rq = tcps->tcps_g_q;
2346 	acceptor->tcp_wq = WR(tcps->tcps_g_q);
2347 	(void) tcp_clean_death(acceptor, 0, 2);
2348 	CONN_DEC_REF(acceptor->tcp_connp);
2349 
2350 	/*
2351 	 * In case we already received a FIN we have to make tcp_rput send
2352 	 * the ordrel_ind. This will also send up a window update if the window
2353 	 * has opened up.
2354 	 *
2355 	 * In the normal case of a successful connection acceptance
2356 	 * we give the O_T_BIND_REQ to the read side put procedure as an
2357 	 * indication that this was just accepted. This tells tcp_rput to
2358 	 * pass up any data queued in tcp_rcv_list.
2359 	 *
2360 	 * In the fringe case where options sent with T_CONN_RES failed and
2361 	 * we required, we would be indicating a T_DISCON_IND to blow
2362 	 * away this connection.
2363 	 */
2364 
2365 	/*
2366 	 * XXX: we currently have a problem if XTI application closes the
2367 	 * acceptor stream in between. This problem exists in on10-gate also
2368 	 * and is well know but nothing can be done short of major rewrite
2369 	 * to fix it. Now it is possible to take care of it by assigning TLI/XTI
2370 	 * eager same squeue as listener (we can distinguish non socket
2371 	 * listeners at the time of handling a SYN in tcp_conn_request)
2372 	 * and do most of the work that tcp_accept_finish does here itself
2373 	 * and then get behind the acceptor squeue to access the acceptor
2374 	 * queue.
2375 	 */
2376 	/*
2377 	 * We already have a ref on tcp so no need to do one before squeue_fill
2378 	 */
2379 	squeue_fill(eager->tcp_connp->conn_sqp, opt_mp,
2380 	    tcp_accept_finish, eager->tcp_connp, SQTAG_TCP_ACCEPT_FINISH);
2381 }
2382 
2383 /*
2384  * Swap information between the eager and acceptor for a TLI/XTI client.
2385  * The sockfs accept is done on the acceptor stream and control goes
2386  * through tcp_wput_accept() and tcp_accept()/tcp_accept_swap() is not
2387  * called. In either case, both the eager and listener are in their own
2388  * perimeter (squeue) and the code has to deal with potential race.
2389  *
2390  * See the block comment on top of tcp_accept() and tcp_wput_accept().
2391  */
2392 static void
2393 tcp_accept_swap(tcp_t *listener, tcp_t *acceptor, tcp_t *eager)
2394 {
2395 	conn_t	*econnp, *aconnp;
2396 
2397 	ASSERT(eager->tcp_rq == listener->tcp_rq);
2398 	ASSERT(eager->tcp_detached && !acceptor->tcp_detached);
2399 	ASSERT(!eager->tcp_hard_bound);
2400 	ASSERT(!TCP_IS_SOCKET(acceptor));
2401 	ASSERT(!TCP_IS_SOCKET(eager));
2402 	ASSERT(!TCP_IS_SOCKET(listener));
2403 
2404 	acceptor->tcp_detached = B_TRUE;
2405 	/*
2406 	 * To permit stream re-use by TLI/XTI, the eager needs a copy of
2407 	 * the acceptor id.
2408 	 */
2409 	eager->tcp_acceptor_id = acceptor->tcp_acceptor_id;
2410 
2411 	/* remove eager from listen list... */
2412 	mutex_enter(&listener->tcp_eager_lock);
2413 	tcp_eager_unlink(eager);
2414 	ASSERT(eager->tcp_eager_next_q == NULL &&
2415 	    eager->tcp_eager_last_q == NULL);
2416 	ASSERT(eager->tcp_eager_next_q0 == NULL &&
2417 	    eager->tcp_eager_prev_q0 == NULL);
2418 	mutex_exit(&listener->tcp_eager_lock);
2419 	eager->tcp_rq = acceptor->tcp_rq;
2420 	eager->tcp_wq = acceptor->tcp_wq;
2421 
2422 	econnp = eager->tcp_connp;
2423 	aconnp = acceptor->tcp_connp;
2424 
2425 	eager->tcp_rq->q_ptr = econnp;
2426 	eager->tcp_wq->q_ptr = econnp;
2427 
2428 	/*
2429 	 * In the TLI/XTI loopback case, we are inside the listener's squeue,
2430 	 * which might be a different squeue from our peer TCP instance.
2431 	 * For TCP Fusion, the peer expects that whenever tcp_detached is
2432 	 * clear, our TCP queues point to the acceptor's queues.  Thus, use
2433 	 * membar_producer() to ensure that the assignments of tcp_rq/tcp_wq
2434 	 * above reach global visibility prior to the clearing of tcp_detached.
2435 	 */
2436 	membar_producer();
2437 	eager->tcp_detached = B_FALSE;
2438 
2439 	ASSERT(eager->tcp_ack_tid == 0);
2440 
2441 	econnp->conn_dev = aconnp->conn_dev;
2442 	econnp->conn_minor_arena = aconnp->conn_minor_arena;
2443 	ASSERT(econnp->conn_minor_arena != NULL);
2444 	if (eager->tcp_cred != NULL)
2445 		crfree(eager->tcp_cred);
2446 	eager->tcp_cred = econnp->conn_cred = aconnp->conn_cred;
2447 	ASSERT(econnp->conn_netstack == aconnp->conn_netstack);
2448 	ASSERT(eager->tcp_tcps == acceptor->tcp_tcps);
2449 
2450 	aconnp->conn_cred = NULL;
2451 
2452 	econnp->conn_zoneid = aconnp->conn_zoneid;
2453 	econnp->conn_allzones = aconnp->conn_allzones;
2454 
2455 	econnp->conn_mac_exempt = aconnp->conn_mac_exempt;
2456 	aconnp->conn_mac_exempt = B_FALSE;
2457 
2458 	ASSERT(aconnp->conn_peercred == NULL);
2459 
2460 	/* Do the IPC initialization */
2461 	CONN_INC_REF(econnp);
2462 
2463 	econnp->conn_multicast_loop = aconnp->conn_multicast_loop;
2464 	econnp->conn_af_isv6 = aconnp->conn_af_isv6;
2465 	econnp->conn_pkt_isv6 = aconnp->conn_pkt_isv6;
2466 
2467 	/* Done with old IPC. Drop its ref on its connp */
2468 	CONN_DEC_REF(aconnp);
2469 }
2470 
2471 
2472 /*
2473  * Adapt to the information, such as rtt and rtt_sd, provided from the
2474  * ire cached in conn_cache_ire. If no ire cached, do a ire lookup.
2475  *
2476  * Checks for multicast and broadcast destination address.
2477  * Returns zero on failure; non-zero if ok.
2478  *
2479  * Note that the MSS calculation here is based on the info given in
2480  * the IRE.  We do not do any calculation based on TCP options.  They
2481  * will be handled in tcp_rput_other() and tcp_rput_data() when TCP
2482  * knows which options to use.
2483  *
2484  * Note on how TCP gets its parameters for a connection.
2485  *
2486  * When a tcp_t structure is allocated, it gets all the default parameters.
2487  * In tcp_adapt_ire(), it gets those metric parameters, like rtt, rtt_sd,
2488  * spipe, rpipe, ... from the route metrics.  Route metric overrides the
2489  * default.
2490  *
2491  * An incoming SYN with a multicast or broadcast destination address, is dropped
2492  * in 1 of 2 places.
2493  *
2494  * 1. If the packet was received over the wire it is dropped in
2495  * ip_rput_process_broadcast()
2496  *
2497  * 2. If the packet was received through internal IP loopback, i.e. the packet
2498  * was generated and received on the same machine, it is dropped in
2499  * ip_wput_local()
2500  *
2501  * An incoming SYN with a multicast or broadcast source address is always
2502  * dropped in tcp_adapt_ire. The same logic in tcp_adapt_ire also serves to
2503  * reject an attempt to connect to a broadcast or multicast (destination)
2504  * address.
2505  */
2506 static int
2507 tcp_adapt_ire(tcp_t *tcp, mblk_t *ire_mp)
2508 {
2509 	tcp_hsp_t	*hsp;
2510 	ire_t		*ire;
2511 	ire_t		*sire = NULL;
2512 	iulp_t		*ire_uinfo = NULL;
2513 	uint32_t	mss_max;
2514 	uint32_t	mss;
2515 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
2516 	conn_t		*connp = tcp->tcp_connp;
2517 	boolean_t	ire_cacheable = B_FALSE;
2518 	zoneid_t	zoneid = connp->conn_zoneid;
2519 	int		match_flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
2520 	    MATCH_IRE_SECATTR;
2521 	ts_label_t	*tsl = crgetlabel(CONN_CRED(connp));
2522 	ill_t		*ill = NULL;
2523 	boolean_t	incoming = (ire_mp == NULL);
2524 	tcp_stack_t	*tcps = tcp->tcp_tcps;
2525 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
2526 
2527 	ASSERT(connp->conn_ire_cache == NULL);
2528 
2529 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2530 
2531 		if (CLASSD(tcp->tcp_connp->conn_rem)) {
2532 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
2533 			return (0);
2534 		}
2535 		/*
2536 		 * If IP_NEXTHOP is set, then look for an IRE_CACHE
2537 		 * for the destination with the nexthop as gateway.
2538 		 * ire_ctable_lookup() is used because this particular
2539 		 * ire, if it exists, will be marked private.
2540 		 * If that is not available, use the interface ire
2541 		 * for the nexthop.
2542 		 *
2543 		 * TSol: tcp_update_label will detect label mismatches based
2544 		 * only on the destination's label, but that would not
2545 		 * detect label mismatches based on the security attributes
2546 		 * of routes or next hop gateway. Hence we need to pass the
2547 		 * label to ire_ftable_lookup below in order to locate the
2548 		 * right prefix (and/or) ire cache. Similarly we also need
2549 		 * pass the label to the ire_cache_lookup below to locate
2550 		 * the right ire that also matches on the label.
2551 		 */
2552 		if (tcp->tcp_connp->conn_nexthop_set) {
2553 			ire = ire_ctable_lookup(tcp->tcp_connp->conn_rem,
2554 			    tcp->tcp_connp->conn_nexthop_v4, 0, NULL, zoneid,
2555 			    tsl, MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW,
2556 			    ipst);
2557 			if (ire == NULL) {
2558 				ire = ire_ftable_lookup(
2559 				    tcp->tcp_connp->conn_nexthop_v4,
2560 				    0, 0, IRE_INTERFACE, NULL, NULL, zoneid, 0,
2561 				    tsl, match_flags, ipst);
2562 				if (ire == NULL)
2563 					return (0);
2564 			} else {
2565 				ire_uinfo = &ire->ire_uinfo;
2566 			}
2567 		} else {
2568 			ire = ire_cache_lookup(tcp->tcp_connp->conn_rem,
2569 			    zoneid, tsl, ipst);
2570 			if (ire != NULL) {
2571 				ire_cacheable = B_TRUE;
2572 				ire_uinfo = (ire_mp != NULL) ?
2573 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2574 				    &ire->ire_uinfo;
2575 
2576 			} else {
2577 				if (ire_mp == NULL) {
2578 					ire = ire_ftable_lookup(
2579 					    tcp->tcp_connp->conn_rem,
2580 					    0, 0, 0, NULL, &sire, zoneid, 0,
2581 					    tsl, (MATCH_IRE_RECURSIVE |
2582 					    MATCH_IRE_DEFAULT), ipst);
2583 					if (ire == NULL)
2584 						return (0);
2585 					ire_uinfo = (sire != NULL) ?
2586 					    &sire->ire_uinfo :
2587 					    &ire->ire_uinfo;
2588 				} else {
2589 					ire = (ire_t *)ire_mp->b_rptr;
2590 					ire_uinfo =
2591 					    &((ire_t *)
2592 					    ire_mp->b_rptr)->ire_uinfo;
2593 				}
2594 			}
2595 		}
2596 		ASSERT(ire != NULL);
2597 
2598 		if ((ire->ire_src_addr == INADDR_ANY) ||
2599 		    (ire->ire_type & IRE_BROADCAST)) {
2600 			/*
2601 			 * ire->ire_mp is non null when ire_mp passed in is used
2602 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2603 			 */
2604 			if (ire->ire_mp == NULL)
2605 				ire_refrele(ire);
2606 			if (sire != NULL)
2607 				ire_refrele(sire);
2608 			return (0);
2609 		}
2610 
2611 		if (tcp->tcp_ipha->ipha_src == INADDR_ANY) {
2612 			ipaddr_t src_addr;
2613 
2614 			/*
2615 			 * ip_bind_connected() has stored the correct source
2616 			 * address in conn_src.
2617 			 */
2618 			src_addr = tcp->tcp_connp->conn_src;
2619 			tcp->tcp_ipha->ipha_src = src_addr;
2620 			/*
2621 			 * Copy of the src addr. in tcp_t is needed
2622 			 * for the lookup funcs.
2623 			 */
2624 			IN6_IPADDR_TO_V4MAPPED(src_addr, &tcp->tcp_ip_src_v6);
2625 		}
2626 		/*
2627 		 * Set the fragment bit so that IP will tell us if the MTU
2628 		 * should change. IP tells us the latest setting of
2629 		 * ip_path_mtu_discovery through ire_frag_flag.
2630 		 */
2631 		if (ipst->ips_ip_path_mtu_discovery) {
2632 			tcp->tcp_ipha->ipha_fragment_offset_and_flags =
2633 			    htons(IPH_DF);
2634 		}
2635 		/*
2636 		 * If ire_uinfo is NULL, this is the IRE_INTERFACE case
2637 		 * for IP_NEXTHOP. No cache ire has been found for the
2638 		 * destination and we are working with the nexthop's
2639 		 * interface ire. Since we need to forward all packets
2640 		 * to the nexthop first, we "blindly" set tcp_localnet
2641 		 * to false, eventhough the destination may also be
2642 		 * onlink.
2643 		 */
2644 		if (ire_uinfo == NULL)
2645 			tcp->tcp_localnet = 0;
2646 		else
2647 			tcp->tcp_localnet = (ire->ire_gateway_addr == 0);
2648 	} else {
2649 		/*
2650 		 * For incoming connection ire_mp = NULL
2651 		 * For outgoing connection ire_mp != NULL
2652 		 * Technically we should check conn_incoming_ill
2653 		 * when ire_mp is NULL and conn_outgoing_ill when
2654 		 * ire_mp is non-NULL. But this is performance
2655 		 * critical path and for IPV*_BOUND_IF, outgoing
2656 		 * and incoming ill are always set to the same value.
2657 		 */
2658 		ill_t	*dst_ill = NULL;
2659 		ipif_t  *dst_ipif = NULL;
2660 
2661 		ASSERT(connp->conn_outgoing_ill == connp->conn_incoming_ill);
2662 
2663 		if (connp->conn_outgoing_ill != NULL) {
2664 			/* Outgoing or incoming path */
2665 			int   err;
2666 
2667 			dst_ill = conn_get_held_ill(connp,
2668 			    &connp->conn_outgoing_ill, &err);
2669 			if (err == ILL_LOOKUP_FAILED || dst_ill == NULL) {
2670 				ip1dbg(("tcp_adapt_ire: ill_lookup failed\n"));
2671 				return (0);
2672 			}
2673 			match_flags |= MATCH_IRE_ILL;
2674 			dst_ipif = dst_ill->ill_ipif;
2675 		}
2676 		ire = ire_ctable_lookup_v6(&tcp->tcp_connp->conn_remv6,
2677 		    0, 0, dst_ipif, zoneid, tsl, match_flags, ipst);
2678 
2679 		if (ire != NULL) {
2680 			ire_cacheable = B_TRUE;
2681 			ire_uinfo = (ire_mp != NULL) ?
2682 			    &((ire_t *)ire_mp->b_rptr)->ire_uinfo:
2683 			    &ire->ire_uinfo;
2684 		} else {
2685 			if (ire_mp == NULL) {
2686 				ire = ire_ftable_lookup_v6(
2687 				    &tcp->tcp_connp->conn_remv6,
2688 				    0, 0, 0, dst_ipif, &sire, zoneid,
2689 				    0, tsl, match_flags, ipst);
2690 				if (ire == NULL) {
2691 					if (dst_ill != NULL)
2692 						ill_refrele(dst_ill);
2693 					return (0);
2694 				}
2695 				ire_uinfo = (sire != NULL) ? &sire->ire_uinfo :
2696 				    &ire->ire_uinfo;
2697 			} else {
2698 				ire = (ire_t *)ire_mp->b_rptr;
2699 				ire_uinfo =
2700 				    &((ire_t *)ire_mp->b_rptr)->ire_uinfo;
2701 			}
2702 		}
2703 		if (dst_ill != NULL)
2704 			ill_refrele(dst_ill);
2705 
2706 		ASSERT(ire != NULL);
2707 		ASSERT(ire_uinfo != NULL);
2708 
2709 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) ||
2710 		    IN6_IS_ADDR_MULTICAST(&ire->ire_addr_v6)) {
2711 			/*
2712 			 * ire->ire_mp is non null when ire_mp passed in is used
2713 			 * ire->ire_mp is set in ip_bind_insert_ire[_v6]().
2714 			 */
2715 			if (ire->ire_mp == NULL)
2716 				ire_refrele(ire);
2717 			if (sire != NULL)
2718 				ire_refrele(sire);
2719 			return (0);
2720 		}
2721 
2722 		if (IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
2723 			in6_addr_t	src_addr;
2724 
2725 			/*
2726 			 * ip_bind_connected_v6() has stored the correct source
2727 			 * address per IPv6 addr. selection policy in
2728 			 * conn_src_v6.
2729 			 */
2730 			src_addr = tcp->tcp_connp->conn_srcv6;
2731 
2732 			tcp->tcp_ip6h->ip6_src = src_addr;
2733 			/*
2734 			 * Copy of the src addr. in tcp_t is needed
2735 			 * for the lookup funcs.
2736 			 */
2737 			tcp->tcp_ip_src_v6 = src_addr;
2738 			ASSERT(IN6_ARE_ADDR_EQUAL(&tcp->tcp_ip6h->ip6_src,
2739 			    &connp->conn_srcv6));
2740 		}
2741 		tcp->tcp_localnet =
2742 		    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6);
2743 	}
2744 
2745 	/*
2746 	 * This allows applications to fail quickly when connections are made
2747 	 * to dead hosts. Hosts can be labeled dead by adding a reject route
2748 	 * with both the RTF_REJECT and RTF_PRIVATE flags set.
2749 	 */
2750 	if ((ire->ire_flags & RTF_REJECT) &&
2751 	    (ire->ire_flags & RTF_PRIVATE))
2752 		goto error;
2753 
2754 	/*
2755 	 * Make use of the cached rtt and rtt_sd values to calculate the
2756 	 * initial RTO.  Note that they are already initialized in
2757 	 * tcp_init_values().
2758 	 * If ire_uinfo is NULL, i.e., we do not have a cache ire for
2759 	 * IP_NEXTHOP, but instead are using the interface ire for the
2760 	 * nexthop, then we do not use the ire_uinfo from that ire to
2761 	 * do any initializations.
2762 	 */
2763 	if (ire_uinfo != NULL) {
2764 		if (ire_uinfo->iulp_rtt != 0) {
2765 			clock_t	rto;
2766 
2767 			tcp->tcp_rtt_sa = ire_uinfo->iulp_rtt;
2768 			tcp->tcp_rtt_sd = ire_uinfo->iulp_rtt_sd;
2769 			rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
2770 			    tcps->tcps_rexmit_interval_extra +
2771 			    (tcp->tcp_rtt_sa >> 5);
2772 
2773 			if (rto > tcps->tcps_rexmit_interval_max) {
2774 				tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
2775 			} else if (rto < tcps->tcps_rexmit_interval_min) {
2776 				tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
2777 			} else {
2778 				tcp->tcp_rto = rto;
2779 			}
2780 		}
2781 		if (ire_uinfo->iulp_ssthresh != 0)
2782 			tcp->tcp_cwnd_ssthresh = ire_uinfo->iulp_ssthresh;
2783 		else
2784 			tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
2785 		if (ire_uinfo->iulp_spipe > 0) {
2786 			tcp->tcp_xmit_hiwater = MIN(ire_uinfo->iulp_spipe,
2787 			    tcps->tcps_max_buf);
2788 			if (tcps->tcps_snd_lowat_fraction != 0)
2789 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2790 				    tcps->tcps_snd_lowat_fraction;
2791 			(void) tcp_maxpsz_set(tcp, B_TRUE);
2792 		}
2793 		/*
2794 		 * Note that up till now, acceptor always inherits receive
2795 		 * window from the listener.  But if there is a metrics
2796 		 * associated with a host, we should use that instead of
2797 		 * inheriting it from listener. Thus we need to pass this
2798 		 * info back to the caller.
2799 		 */
2800 		if (ire_uinfo->iulp_rpipe > 0) {
2801 			tcp->tcp_rwnd = MIN(ire_uinfo->iulp_rpipe,
2802 			    tcps->tcps_max_buf);
2803 		}
2804 
2805 		if (ire_uinfo->iulp_rtomax > 0) {
2806 			tcp->tcp_second_timer_threshold =
2807 			    ire_uinfo->iulp_rtomax;
2808 		}
2809 
2810 		/*
2811 		 * Use the metric option settings, iulp_tstamp_ok and
2812 		 * iulp_wscale_ok, only for active open. What this means
2813 		 * is that if the other side uses timestamp or window
2814 		 * scale option, TCP will also use those options. That
2815 		 * is for passive open.  If the application sets a
2816 		 * large window, window scale is enabled regardless of
2817 		 * the value in iulp_wscale_ok.  This is the behavior
2818 		 * since 2.6.  So we keep it.
2819 		 * The only case left in passive open processing is the
2820 		 * check for SACK.
2821 		 * For ECN, it should probably be like SACK.  But the
2822 		 * current value is binary, so we treat it like the other
2823 		 * cases.  The metric only controls active open.For passive
2824 		 * open, the ndd param, tcp_ecn_permitted, controls the
2825 		 * behavior.
2826 		 */
2827 		if (!tcp_detached) {
2828 			/*
2829 			 * The if check means that the following can only
2830 			 * be turned on by the metrics only IRE, but not off.
2831 			 */
2832 			if (ire_uinfo->iulp_tstamp_ok)
2833 				tcp->tcp_snd_ts_ok = B_TRUE;
2834 			if (ire_uinfo->iulp_wscale_ok)
2835 				tcp->tcp_snd_ws_ok = B_TRUE;
2836 			if (ire_uinfo->iulp_sack == 2)
2837 				tcp->tcp_snd_sack_ok = B_TRUE;
2838 			if (ire_uinfo->iulp_ecn_ok)
2839 				tcp->tcp_ecn_ok = B_TRUE;
2840 		} else {
2841 			/*
2842 			 * Passive open.
2843 			 *
2844 			 * As above, the if check means that SACK can only be
2845 			 * turned on by the metric only IRE.
2846 			 */
2847 			if (ire_uinfo->iulp_sack > 0) {
2848 				tcp->tcp_snd_sack_ok = B_TRUE;
2849 			}
2850 		}
2851 	}
2852 
2853 
2854 	/*
2855 	 * XXX: Note that currently, ire_max_frag can be as small as 68
2856 	 * because of PMTUd.  So tcp_mss may go to negative if combined
2857 	 * length of all those options exceeds 28 bytes.  But because
2858 	 * of the tcp_mss_min check below, we may not have a problem if
2859 	 * tcp_mss_min is of a reasonable value.  The default is 1 so
2860 	 * the negative problem still exists.  And the check defeats PMTUd.
2861 	 * In fact, if PMTUd finds that the MSS should be smaller than
2862 	 * tcp_mss_min, TCP should turn off PMUTd and use the tcp_mss_min
2863 	 * value.
2864 	 *
2865 	 * We do not deal with that now.  All those problems related to
2866 	 * PMTUd will be fixed later.
2867 	 */
2868 	ASSERT(ire->ire_max_frag != 0);
2869 	mss = tcp->tcp_if_mtu = ire->ire_max_frag;
2870 	if (tcp->tcp_ipp_fields & IPPF_USE_MIN_MTU) {
2871 		if (tcp->tcp_ipp_use_min_mtu == IPV6_USE_MIN_MTU_NEVER) {
2872 			mss = MIN(mss, IPV6_MIN_MTU);
2873 		}
2874 	}
2875 
2876 	/* Sanity check for MSS value. */
2877 	if (tcp->tcp_ipversion == IPV4_VERSION)
2878 		mss_max = tcps->tcps_mss_max_ipv4;
2879 	else
2880 		mss_max = tcps->tcps_mss_max_ipv6;
2881 
2882 	if (tcp->tcp_ipversion == IPV6_VERSION &&
2883 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
2884 		/*
2885 		 * After receiving an ICMPv6 "packet too big" message with a
2886 		 * MTU < 1280, and for multirouted IPv6 packets, the IP layer
2887 		 * will insert a 8-byte fragment header in every packet; we
2888 		 * reduce the MSS by that amount here.
2889 		 */
2890 		mss -= sizeof (ip6_frag_t);
2891 	}
2892 
2893 	if (tcp->tcp_ipsec_overhead == 0)
2894 		tcp->tcp_ipsec_overhead = conn_ipsec_length(connp);
2895 
2896 	mss -= tcp->tcp_ipsec_overhead;
2897 
2898 	if (mss < tcps->tcps_mss_min)
2899 		mss = tcps->tcps_mss_min;
2900 	if (mss > mss_max)
2901 		mss = mss_max;
2902 
2903 	/* Note that this is the maximum MSS, excluding all options. */
2904 	tcp->tcp_mss = mss;
2905 
2906 	/*
2907 	 * Initialize the ISS here now that we have the full connection ID.
2908 	 * The RFC 1948 method of initial sequence number generation requires
2909 	 * knowledge of the full connection ID before setting the ISS.
2910 	 */
2911 
2912 	tcp_iss_init(tcp);
2913 
2914 	if (ire->ire_type & (IRE_LOOPBACK | IRE_LOCAL))
2915 		tcp->tcp_loopback = B_TRUE;
2916 
2917 	if (tcp->tcp_ipversion == IPV4_VERSION) {
2918 		hsp = tcp_hsp_lookup(tcp->tcp_remote, tcps);
2919 	} else {
2920 		hsp = tcp_hsp_lookup_ipv6(&tcp->tcp_remote_v6, tcps);
2921 	}
2922 
2923 	if (hsp != NULL) {
2924 		/* Only modify if we're going to make them bigger */
2925 		if (hsp->tcp_hsp_sendspace > tcp->tcp_xmit_hiwater) {
2926 			tcp->tcp_xmit_hiwater = hsp->tcp_hsp_sendspace;
2927 			if (tcps->tcps_snd_lowat_fraction != 0)
2928 				tcp->tcp_xmit_lowater = tcp->tcp_xmit_hiwater /
2929 				    tcps->tcps_snd_lowat_fraction;
2930 		}
2931 
2932 		if (hsp->tcp_hsp_recvspace > tcp->tcp_rwnd) {
2933 			tcp->tcp_rwnd = hsp->tcp_hsp_recvspace;
2934 		}
2935 
2936 		/* Copy timestamp flag only for active open */
2937 		if (!tcp_detached)
2938 			tcp->tcp_snd_ts_ok = hsp->tcp_hsp_tstamp;
2939 	}
2940 
2941 	if (sire != NULL)
2942 		IRE_REFRELE(sire);
2943 
2944 	/*
2945 	 * If we got an IRE_CACHE and an ILL, go through their properties;
2946 	 * otherwise, this is deferred until later when we have an IRE_CACHE.
2947 	 */
2948 	if (tcp->tcp_loopback ||
2949 	    (ire_cacheable && (ill = ire_to_ill(ire)) != NULL)) {
2950 		/*
2951 		 * For incoming, see if this tcp may be MDT-capable.  For
2952 		 * outgoing, this process has been taken care of through
2953 		 * tcp_rput_other.
2954 		 */
2955 		tcp_ire_ill_check(tcp, ire, ill, incoming);
2956 		tcp->tcp_ire_ill_check_done = B_TRUE;
2957 	}
2958 
2959 	mutex_enter(&connp->conn_lock);
2960 	/*
2961 	 * Make sure that conn is not marked incipient
2962 	 * for incoming connections. A blind
2963 	 * removal of incipient flag is cheaper than
2964 	 * check and removal.
2965 	 */
2966 	connp->conn_state_flags &= ~CONN_INCIPIENT;
2967 
2968 	/*
2969 	 * Must not cache forwarding table routes
2970 	 * or recache an IRE after the conn_t has
2971 	 * had conn_ire_cache cleared and is flagged
2972 	 * unusable, (see the CONN_CACHE_IRE() macro).
2973 	 */
2974 	if (ire_cacheable && CONN_CACHE_IRE(connp)) {
2975 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2976 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
2977 			connp->conn_ire_cache = ire;
2978 			IRE_UNTRACE_REF(ire);
2979 			rw_exit(&ire->ire_bucket->irb_lock);
2980 			mutex_exit(&connp->conn_lock);
2981 			return (1);
2982 		}
2983 		rw_exit(&ire->ire_bucket->irb_lock);
2984 	}
2985 	mutex_exit(&connp->conn_lock);
2986 
2987 	if (ire->ire_mp == NULL)
2988 		ire_refrele(ire);
2989 	return (1);
2990 
2991 error:
2992 	if (ire->ire_mp == NULL)
2993 		ire_refrele(ire);
2994 	if (sire != NULL)
2995 		ire_refrele(sire);
2996 	return (0);
2997 }
2998 
2999 /*
3000  * tcp_bind is called (holding the writer lock) by tcp_wput_proto to process a
3001  * O_T_BIND_REQ/T_BIND_REQ message.
3002  */
3003 static void
3004 tcp_bind(tcp_t *tcp, mblk_t *mp)
3005 {
3006 	sin_t	*sin;
3007 	sin6_t	*sin6;
3008 	mblk_t	*mp1;
3009 	in_port_t requested_port;
3010 	in_port_t allocated_port;
3011 	struct T_bind_req *tbr;
3012 	boolean_t	bind_to_req_port_only;
3013 	boolean_t	backlog_update = B_FALSE;
3014 	boolean_t	user_specified;
3015 	in6_addr_t	v6addr;
3016 	ipaddr_t	v4addr;
3017 	uint_t	origipversion;
3018 	int	err;
3019 	queue_t *q = tcp->tcp_wq;
3020 	conn_t	*connp = tcp->tcp_connp;
3021 	mlp_type_t addrtype, mlptype;
3022 	zone_t	*zone;
3023 	cred_t	*cr;
3024 	in_port_t mlp_port;
3025 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3026 
3027 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
3028 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tbr)) {
3029 		if (tcp->tcp_debug) {
3030 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3031 			    "tcp_bind: bad req, len %u",
3032 			    (uint_t)(mp->b_wptr - mp->b_rptr));
3033 		}
3034 		tcp_err_ack(tcp, mp, TPROTO, 0);
3035 		return;
3036 	}
3037 	/* Make sure the largest address fits */
3038 	mp1 = reallocb(mp, sizeof (struct T_bind_ack) + sizeof (sin6_t) + 1, 1);
3039 	if (mp1 == NULL) {
3040 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3041 		return;
3042 	}
3043 	mp = mp1;
3044 	tbr = (struct T_bind_req *)mp->b_rptr;
3045 	if (tcp->tcp_state >= TCPS_BOUND) {
3046 		if ((tcp->tcp_state == TCPS_BOUND ||
3047 		    tcp->tcp_state == TCPS_LISTEN) &&
3048 		    tcp->tcp_conn_req_max != tbr->CONIND_number &&
3049 		    tbr->CONIND_number > 0) {
3050 			/*
3051 			 * Handle listen() increasing CONIND_number.
3052 			 * This is more "liberal" then what the TPI spec
3053 			 * requires but is needed to avoid a t_unbind
3054 			 * when handling listen() since the port number
3055 			 * might be "stolen" between the unbind and bind.
3056 			 */
3057 			backlog_update = B_TRUE;
3058 			goto do_bind;
3059 		}
3060 		if (tcp->tcp_debug) {
3061 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3062 			    "tcp_bind: bad state, %d", tcp->tcp_state);
3063 		}
3064 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
3065 		return;
3066 	}
3067 	origipversion = tcp->tcp_ipversion;
3068 
3069 	switch (tbr->ADDR_length) {
3070 	case 0:			/* request for a generic port */
3071 		tbr->ADDR_offset = sizeof (struct T_bind_req);
3072 		if (tcp->tcp_family == AF_INET) {
3073 			tbr->ADDR_length = sizeof (sin_t);
3074 			sin = (sin_t *)&tbr[1];
3075 			*sin = sin_null;
3076 			sin->sin_family = AF_INET;
3077 			mp->b_wptr = (uchar_t *)&sin[1];
3078 			tcp->tcp_ipversion = IPV4_VERSION;
3079 			IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &v6addr);
3080 		} else {
3081 			ASSERT(tcp->tcp_family == AF_INET6);
3082 			tbr->ADDR_length = sizeof (sin6_t);
3083 			sin6 = (sin6_t *)&tbr[1];
3084 			*sin6 = sin6_null;
3085 			sin6->sin6_family = AF_INET6;
3086 			mp->b_wptr = (uchar_t *)&sin6[1];
3087 			tcp->tcp_ipversion = IPV6_VERSION;
3088 			V6_SET_ZERO(v6addr);
3089 		}
3090 		requested_port = 0;
3091 		break;
3092 
3093 	case sizeof (sin_t):	/* Complete IPv4 address */
3094 		sin = (sin_t *)mi_offset_param(mp, tbr->ADDR_offset,
3095 		    sizeof (sin_t));
3096 		if (sin == NULL || !OK_32PTR((char *)sin)) {
3097 			if (tcp->tcp_debug) {
3098 				(void) strlog(TCP_MOD_ID, 0, 1,
3099 				    SL_ERROR|SL_TRACE,
3100 				    "tcp_bind: bad address parameter, "
3101 				    "offset %d, len %d",
3102 				    tbr->ADDR_offset, tbr->ADDR_length);
3103 			}
3104 			tcp_err_ack(tcp, mp, TPROTO, 0);
3105 			return;
3106 		}
3107 		/*
3108 		 * With sockets sockfs will accept bogus sin_family in
3109 		 * bind() and replace it with the family used in the socket
3110 		 * call.
3111 		 */
3112 		if (sin->sin_family != AF_INET ||
3113 		    tcp->tcp_family != AF_INET) {
3114 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3115 			return;
3116 		}
3117 		requested_port = ntohs(sin->sin_port);
3118 		tcp->tcp_ipversion = IPV4_VERSION;
3119 		v4addr = sin->sin_addr.s_addr;
3120 		IN6_IPADDR_TO_V4MAPPED(v4addr, &v6addr);
3121 		break;
3122 
3123 	case sizeof (sin6_t): /* Complete IPv6 address */
3124 		sin6 = (sin6_t *)mi_offset_param(mp,
3125 		    tbr->ADDR_offset, sizeof (sin6_t));
3126 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
3127 			if (tcp->tcp_debug) {
3128 				(void) strlog(TCP_MOD_ID, 0, 1,
3129 				    SL_ERROR|SL_TRACE,
3130 				    "tcp_bind: bad IPv6 address parameter, "
3131 				    "offset %d, len %d", tbr->ADDR_offset,
3132 				    tbr->ADDR_length);
3133 			}
3134 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
3135 			return;
3136 		}
3137 		if (sin6->sin6_family != AF_INET6 ||
3138 		    tcp->tcp_family != AF_INET6) {
3139 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
3140 			return;
3141 		}
3142 		requested_port = ntohs(sin6->sin6_port);
3143 		tcp->tcp_ipversion = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr) ?
3144 		    IPV4_VERSION : IPV6_VERSION;
3145 		v6addr = sin6->sin6_addr;
3146 		break;
3147 
3148 	default:
3149 		if (tcp->tcp_debug) {
3150 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
3151 			    "tcp_bind: bad address length, %d",
3152 			    tbr->ADDR_length);
3153 		}
3154 		tcp_err_ack(tcp, mp, TBADADDR, 0);
3155 		return;
3156 	}
3157 	tcp->tcp_bound_source_v6 = v6addr;
3158 
3159 	/* Check for change in ipversion */
3160 	if (origipversion != tcp->tcp_ipversion) {
3161 		ASSERT(tcp->tcp_family == AF_INET6);
3162 		err = tcp->tcp_ipversion == IPV6_VERSION ?
3163 		    tcp_header_init_ipv6(tcp) : tcp_header_init_ipv4(tcp);
3164 		if (err) {
3165 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3166 			return;
3167 		}
3168 	}
3169 
3170 	/*
3171 	 * Initialize family specific fields. Copy of the src addr.
3172 	 * in tcp_t is needed for the lookup funcs.
3173 	 */
3174 	if (tcp->tcp_ipversion == IPV6_VERSION) {
3175 		tcp->tcp_ip6h->ip6_src = v6addr;
3176 	} else {
3177 		IN6_V4MAPPED_TO_IPADDR(&v6addr, tcp->tcp_ipha->ipha_src);
3178 	}
3179 	tcp->tcp_ip_src_v6 = v6addr;
3180 
3181 	/*
3182 	 * For O_T_BIND_REQ:
3183 	 * Verify that the target port/addr is available, or choose
3184 	 * another.
3185 	 * For  T_BIND_REQ:
3186 	 * Verify that the target port/addr is available or fail.
3187 	 * In both cases when it succeeds the tcp is inserted in the
3188 	 * bind hash table. This ensures that the operation is atomic
3189 	 * under the lock on the hash bucket.
3190 	 */
3191 	bind_to_req_port_only = requested_port != 0 &&
3192 	    tbr->PRIM_type != O_T_BIND_REQ;
3193 	/*
3194 	 * Get a valid port (within the anonymous range and should not
3195 	 * be a privileged one) to use if the user has not given a port.
3196 	 * If multiple threads are here, they may all start with
3197 	 * with the same initial port. But, it should be fine as long as
3198 	 * tcp_bindi will ensure that no two threads will be assigned
3199 	 * the same port.
3200 	 *
3201 	 * NOTE: XXX If a privileged process asks for an anonymous port, we
3202 	 * still check for ports only in the range > tcp_smallest_non_priv_port,
3203 	 * unless TCP_ANONPRIVBIND option is set.
3204 	 */
3205 	mlptype = mlptSingle;
3206 	mlp_port = requested_port;
3207 	if (requested_port == 0) {
3208 		requested_port = tcp->tcp_anon_priv_bind ?
3209 		    tcp_get_next_priv_port(tcp) :
3210 		    tcp_update_next_port(tcps->tcps_next_port_to_try,
3211 		    tcp, B_TRUE);
3212 		if (requested_port == 0) {
3213 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3214 			return;
3215 		}
3216 		user_specified = B_FALSE;
3217 
3218 		/*
3219 		 * If the user went through one of the RPC interfaces to create
3220 		 * this socket and RPC is MLP in this zone, then give him an
3221 		 * anonymous MLP.
3222 		 */
3223 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3224 		if (connp->conn_anon_mlp && is_system_labeled()) {
3225 			zone = crgetzone(cr);
3226 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3227 			    IPV6_VERSION, &v6addr,
3228 			    tcps->tcps_netstack->netstack_ip);
3229 			if (addrtype == mlptSingle) {
3230 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3231 				return;
3232 			}
3233 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3234 			    PMAPPORT, addrtype);
3235 			mlp_port = PMAPPORT;
3236 		}
3237 	} else {
3238 		int i;
3239 		boolean_t priv = B_FALSE;
3240 
3241 		/*
3242 		 * If the requested_port is in the well-known privileged range,
3243 		 * verify that the stream was opened by a privileged user.
3244 		 * Note: No locks are held when inspecting tcp_g_*epriv_ports
3245 		 * but instead the code relies on:
3246 		 * - the fact that the address of the array and its size never
3247 		 *   changes
3248 		 * - the atomic assignment of the elements of the array
3249 		 */
3250 		cr = DB_CREDDEF(mp, tcp->tcp_cred);
3251 		if (requested_port < tcps->tcps_smallest_nonpriv_port) {
3252 			priv = B_TRUE;
3253 		} else {
3254 			for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
3255 				if (requested_port ==
3256 				    tcps->tcps_g_epriv_ports[i]) {
3257 					priv = B_TRUE;
3258 					break;
3259 				}
3260 			}
3261 		}
3262 		if (priv) {
3263 			if (secpolicy_net_privaddr(cr, requested_port,
3264 			    IPPROTO_TCP) != 0) {
3265 				if (tcp->tcp_debug) {
3266 					(void) strlog(TCP_MOD_ID, 0, 1,
3267 					    SL_ERROR|SL_TRACE,
3268 					    "tcp_bind: no priv for port %d",
3269 					    requested_port);
3270 				}
3271 				tcp_err_ack(tcp, mp, TACCES, 0);
3272 				return;
3273 			}
3274 		}
3275 		user_specified = B_TRUE;
3276 
3277 		if (is_system_labeled()) {
3278 			zone = crgetzone(cr);
3279 			addrtype = tsol_mlp_addr_type(zone->zone_id,
3280 			    IPV6_VERSION, &v6addr,
3281 			    tcps->tcps_netstack->netstack_ip);
3282 			if (addrtype == mlptSingle) {
3283 				tcp_err_ack(tcp, mp, TNOADDR, 0);
3284 				return;
3285 			}
3286 			mlptype = tsol_mlp_port_type(zone, IPPROTO_TCP,
3287 			    requested_port, addrtype);
3288 		}
3289 	}
3290 
3291 	if (mlptype != mlptSingle) {
3292 		if (secpolicy_net_bindmlp(cr) != 0) {
3293 			if (tcp->tcp_debug) {
3294 				(void) strlog(TCP_MOD_ID, 0, 1,
3295 				    SL_ERROR|SL_TRACE,
3296 				    "tcp_bind: no priv for multilevel port %d",
3297 				    requested_port);
3298 			}
3299 			tcp_err_ack(tcp, mp, TACCES, 0);
3300 			return;
3301 		}
3302 
3303 		/*
3304 		 * If we're specifically binding a shared IP address and the
3305 		 * port is MLP on shared addresses, then check to see if this
3306 		 * zone actually owns the MLP.  Reject if not.
3307 		 */
3308 		if (mlptype == mlptShared && addrtype == mlptShared) {
3309 			/*
3310 			 * No need to handle exclusive-stack zones since
3311 			 * ALL_ZONES only applies to the shared stack.
3312 			 */
3313 			zoneid_t mlpzone;
3314 
3315 			mlpzone = tsol_mlp_findzone(IPPROTO_TCP,
3316 			    htons(mlp_port));
3317 			if (connp->conn_zoneid != mlpzone) {
3318 				if (tcp->tcp_debug) {
3319 					(void) strlog(TCP_MOD_ID, 0, 1,
3320 					    SL_ERROR|SL_TRACE,
3321 					    "tcp_bind: attempt to bind port "
3322 					    "%d on shared addr in zone %d "
3323 					    "(should be %d)",
3324 					    mlp_port, connp->conn_zoneid,
3325 					    mlpzone);
3326 				}
3327 				tcp_err_ack(tcp, mp, TACCES, 0);
3328 				return;
3329 			}
3330 		}
3331 
3332 		if (!user_specified) {
3333 			err = tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3334 			    requested_port, B_TRUE);
3335 			if (err != 0) {
3336 				if (tcp->tcp_debug) {
3337 					(void) strlog(TCP_MOD_ID, 0, 1,
3338 					    SL_ERROR|SL_TRACE,
3339 					    "tcp_bind: cannot establish anon "
3340 					    "MLP for port %d",
3341 					    requested_port);
3342 				}
3343 				tcp_err_ack(tcp, mp, TSYSERR, err);
3344 				return;
3345 			}
3346 			connp->conn_anon_port = B_TRUE;
3347 		}
3348 		connp->conn_mlp_type = mlptype;
3349 	}
3350 
3351 	allocated_port = tcp_bindi(tcp, requested_port, &v6addr,
3352 	    tcp->tcp_reuseaddr, B_FALSE, bind_to_req_port_only, user_specified);
3353 
3354 	if (allocated_port == 0) {
3355 		connp->conn_mlp_type = mlptSingle;
3356 		if (connp->conn_anon_port) {
3357 			connp->conn_anon_port = B_FALSE;
3358 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3359 			    requested_port, B_FALSE);
3360 		}
3361 		if (bind_to_req_port_only) {
3362 			if (tcp->tcp_debug) {
3363 				(void) strlog(TCP_MOD_ID, 0, 1,
3364 				    SL_ERROR|SL_TRACE,
3365 				    "tcp_bind: requested addr busy");
3366 			}
3367 			tcp_err_ack(tcp, mp, TADDRBUSY, 0);
3368 		} else {
3369 			/* If we are out of ports, fail the bind. */
3370 			if (tcp->tcp_debug) {
3371 				(void) strlog(TCP_MOD_ID, 0, 1,
3372 				    SL_ERROR|SL_TRACE,
3373 				    "tcp_bind: out of ports?");
3374 			}
3375 			tcp_err_ack(tcp, mp, TNOADDR, 0);
3376 		}
3377 		return;
3378 	}
3379 	ASSERT(tcp->tcp_state == TCPS_BOUND);
3380 do_bind:
3381 	if (!backlog_update) {
3382 		if (tcp->tcp_family == AF_INET)
3383 			sin->sin_port = htons(allocated_port);
3384 		else
3385 			sin6->sin6_port = htons(allocated_port);
3386 	}
3387 	if (tcp->tcp_family == AF_INET) {
3388 		if (tbr->CONIND_number != 0) {
3389 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3390 			    sizeof (sin_t));
3391 		} else {
3392 			/* Just verify the local IP address */
3393 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type, IP_ADDR_LEN);
3394 		}
3395 	} else {
3396 		if (tbr->CONIND_number != 0) {
3397 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3398 			    sizeof (sin6_t));
3399 		} else {
3400 			/* Just verify the local IP address */
3401 			mp1 = tcp_ip_bind_mp(tcp, tbr->PRIM_type,
3402 			    IPV6_ADDR_LEN);
3403 		}
3404 	}
3405 	if (mp1 == NULL) {
3406 		if (connp->conn_anon_port) {
3407 			connp->conn_anon_port = B_FALSE;
3408 			(void) tsol_mlp_anon(zone, mlptype, connp->conn_ulp,
3409 			    requested_port, B_FALSE);
3410 		}
3411 		connp->conn_mlp_type = mlptSingle;
3412 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
3413 		return;
3414 	}
3415 
3416 	tbr->PRIM_type = T_BIND_ACK;
3417 	mp->b_datap->db_type = M_PCPROTO;
3418 
3419 	/* Chain in the reply mp for tcp_rput() */
3420 	mp1->b_cont = mp;
3421 	mp = mp1;
3422 
3423 	tcp->tcp_conn_req_max = tbr->CONIND_number;
3424 	if (tcp->tcp_conn_req_max) {
3425 		if (tcp->tcp_conn_req_max < tcps->tcps_conn_req_min)
3426 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_min;
3427 		if (tcp->tcp_conn_req_max > tcps->tcps_conn_req_max_q)
3428 			tcp->tcp_conn_req_max = tcps->tcps_conn_req_max_q;
3429 		/*
3430 		 * If this is a listener, do not reset the eager list
3431 		 * and other stuffs.  Note that we don't check if the
3432 		 * existing eager list meets the new tcp_conn_req_max
3433 		 * requirement.
3434 		 */
3435 		if (tcp->tcp_state != TCPS_LISTEN) {
3436 			tcp->tcp_state = TCPS_LISTEN;
3437 			/* Initialize the chain. Don't need the eager_lock */
3438 			tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
3439 			tcp->tcp_eager_next_drop_q0 = tcp;
3440 			tcp->tcp_eager_prev_drop_q0 = tcp;
3441 			tcp->tcp_second_ctimer_threshold =
3442 			    tcps->tcps_ip_abort_linterval;
3443 		}
3444 	}
3445 
3446 	/*
3447 	 * We can call ip_bind directly which returns a T_BIND_ACK mp. The
3448 	 * processing continues in tcp_rput_other().
3449 	 *
3450 	 * We need to make sure that the conn_recv is set to a non-null
3451 	 * value before we insert the conn into the classifier table.
3452 	 * This is to avoid a race with an incoming packet which does an
3453 	 * ipcl_classify().
3454 	 */
3455 	connp->conn_recv = tcp_conn_request;
3456 	if (tcp->tcp_family == AF_INET6) {
3457 		ASSERT(tcp->tcp_connp->conn_af_isv6);
3458 		mp = ip_bind_v6(q, mp, tcp->tcp_connp, &tcp->tcp_sticky_ipp);
3459 	} else {
3460 		ASSERT(!tcp->tcp_connp->conn_af_isv6);
3461 		mp = ip_bind_v4(q, mp, tcp->tcp_connp);
3462 	}
3463 	/*
3464 	 * If the bind cannot complete immediately
3465 	 * IP will arrange to call tcp_rput_other
3466 	 * when the bind completes.
3467 	 */
3468 	if (mp != NULL) {
3469 		tcp_rput_other(tcp, mp);
3470 	} else {
3471 		/*
3472 		 * Bind will be resumed later. Need to ensure
3473 		 * that conn doesn't disappear when that happens.
3474 		 * This will be decremented in ip_resume_tcp_bind().
3475 		 */
3476 		CONN_INC_REF(tcp->tcp_connp);
3477 	}
3478 }
3479 
3480 
3481 /*
3482  * If the "bind_to_req_port_only" parameter is set, if the requested port
3483  * number is available, return it, If not return 0
3484  *
3485  * If "bind_to_req_port_only" parameter is not set and
3486  * If the requested port number is available, return it.  If not, return
3487  * the first anonymous port we happen across.  If no anonymous ports are
3488  * available, return 0. addr is the requested local address, if any.
3489  *
3490  * In either case, when succeeding update the tcp_t to record the port number
3491  * and insert it in the bind hash table.
3492  *
3493  * Note that TCP over IPv4 and IPv6 sockets can use the same port number
3494  * without setting SO_REUSEADDR. This is needed so that they
3495  * can be viewed as two independent transport protocols.
3496  */
3497 static in_port_t
3498 tcp_bindi(tcp_t *tcp, in_port_t port, const in6_addr_t *laddr,
3499     int reuseaddr, boolean_t quick_connect,
3500     boolean_t bind_to_req_port_only, boolean_t user_specified)
3501 {
3502 	/* number of times we have run around the loop */
3503 	int count = 0;
3504 	/* maximum number of times to run around the loop */
3505 	int loopmax;
3506 	conn_t *connp = tcp->tcp_connp;
3507 	zoneid_t zoneid = connp->conn_zoneid;
3508 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3509 
3510 	/*
3511 	 * Lookup for free addresses is done in a loop and "loopmax"
3512 	 * influences how long we spin in the loop
3513 	 */
3514 	if (bind_to_req_port_only) {
3515 		/*
3516 		 * If the requested port is busy, don't bother to look
3517 		 * for a new one. Setting loop maximum count to 1 has
3518 		 * that effect.
3519 		 */
3520 		loopmax = 1;
3521 	} else {
3522 		/*
3523 		 * If the requested port is busy, look for a free one
3524 		 * in the anonymous port range.
3525 		 * Set loopmax appropriately so that one does not look
3526 		 * forever in the case all of the anonymous ports are in use.
3527 		 */
3528 		if (tcp->tcp_anon_priv_bind) {
3529 			/*
3530 			 * loopmax =
3531 			 * 	(IPPORT_RESERVED-1) - tcp_min_anonpriv_port + 1
3532 			 */
3533 			loopmax = IPPORT_RESERVED -
3534 			    tcps->tcps_min_anonpriv_port;
3535 		} else {
3536 			loopmax = (tcps->tcps_largest_anon_port -
3537 			    tcps->tcps_smallest_anon_port + 1);
3538 		}
3539 	}
3540 	do {
3541 		uint16_t	lport;
3542 		tf_t		*tbf;
3543 		tcp_t		*ltcp;
3544 		conn_t		*lconnp;
3545 
3546 		lport = htons(port);
3547 
3548 		/*
3549 		 * Ensure that the tcp_t is not currently in the bind hash.
3550 		 * Hold the lock on the hash bucket to ensure that
3551 		 * the duplicate check plus the insertion is an atomic
3552 		 * operation.
3553 		 *
3554 		 * This function does an inline lookup on the bind hash list
3555 		 * Make sure that we access only members of tcp_t
3556 		 * and that we don't look at tcp_tcp, since we are not
3557 		 * doing a CONN_INC_REF.
3558 		 */
3559 		tcp_bind_hash_remove(tcp);
3560 		tbf = &tcps->tcps_bind_fanout[TCP_BIND_HASH(lport)];
3561 		mutex_enter(&tbf->tf_lock);
3562 		for (ltcp = tbf->tf_tcp; ltcp != NULL;
3563 		    ltcp = ltcp->tcp_bind_hash) {
3564 			boolean_t not_socket;
3565 			boolean_t exclbind;
3566 
3567 			if (lport != ltcp->tcp_lport)
3568 				continue;
3569 
3570 			lconnp = ltcp->tcp_connp;
3571 
3572 			/*
3573 			 * On a labeled system, we must treat bindings to ports
3574 			 * on shared IP addresses by sockets with MAC exemption
3575 			 * privilege as being in all zones, as there's
3576 			 * otherwise no way to identify the right receiver.
3577 			 */
3578 			if (!(IPCL_ZONE_MATCH(ltcp->tcp_connp, zoneid) ||
3579 			    IPCL_ZONE_MATCH(connp,
3580 			    ltcp->tcp_connp->conn_zoneid)) &&
3581 			    !lconnp->conn_mac_exempt &&
3582 			    !connp->conn_mac_exempt)
3583 				continue;
3584 
3585 			/*
3586 			 * If TCP_EXCLBIND is set for either the bound or
3587 			 * binding endpoint, the semantics of bind
3588 			 * is changed according to the following.
3589 			 *
3590 			 * spec = specified address (v4 or v6)
3591 			 * unspec = unspecified address (v4 or v6)
3592 			 * A = specified addresses are different for endpoints
3593 			 *
3594 			 * bound	bind to		allowed
3595 			 * -------------------------------------
3596 			 * unspec	unspec		no
3597 			 * unspec	spec		no
3598 			 * spec		unspec		no
3599 			 * spec		spec		yes if A
3600 			 *
3601 			 * For labeled systems, SO_MAC_EXEMPT behaves the same
3602 			 * as TCP_EXCLBIND, except that zoneid is ignored.
3603 			 *
3604 			 * Note:
3605 			 *
3606 			 * 1. Because of TLI semantics, an endpoint can go
3607 			 * back from, say TCP_ESTABLISHED to TCPS_LISTEN or
3608 			 * TCPS_BOUND, depending on whether it is originally
3609 			 * a listener or not.  That is why we need to check
3610 			 * for states greater than or equal to TCPS_BOUND
3611 			 * here.
3612 			 *
3613 			 * 2. Ideally, we should only check for state equals
3614 			 * to TCPS_LISTEN. And the following check should be
3615 			 * added.
3616 			 *
3617 			 * if (ltcp->tcp_state == TCPS_LISTEN ||
3618 			 *	!reuseaddr || !ltcp->tcp_reuseaddr) {
3619 			 *		...
3620 			 * }
3621 			 *
3622 			 * The semantics will be changed to this.  If the
3623 			 * endpoint on the list is in state not equal to
3624 			 * TCPS_LISTEN and both endpoints have SO_REUSEADDR
3625 			 * set, let the bind succeed.
3626 			 *
3627 			 * Because of (1), we cannot do that for TLI
3628 			 * endpoints.  But we can do that for socket endpoints.
3629 			 * If in future, we can change this going back
3630 			 * semantics, we can use the above check for TLI also.
3631 			 */
3632 			not_socket = !(TCP_IS_SOCKET(ltcp) &&
3633 			    TCP_IS_SOCKET(tcp));
3634 			exclbind = ltcp->tcp_exclbind || tcp->tcp_exclbind;
3635 
3636 			if (lconnp->conn_mac_exempt || connp->conn_mac_exempt ||
3637 			    (exclbind && (not_socket ||
3638 			    ltcp->tcp_state <= TCPS_ESTABLISHED))) {
3639 				if (V6_OR_V4_INADDR_ANY(
3640 				    ltcp->tcp_bound_source_v6) ||
3641 				    V6_OR_V4_INADDR_ANY(*laddr) ||
3642 				    IN6_ARE_ADDR_EQUAL(laddr,
3643 				    &ltcp->tcp_bound_source_v6)) {
3644 					break;
3645 				}
3646 				continue;
3647 			}
3648 
3649 			/*
3650 			 * Check ipversion to allow IPv4 and IPv6 sockets to
3651 			 * have disjoint port number spaces, if *_EXCLBIND
3652 			 * is not set and only if the application binds to a
3653 			 * specific port. We use the same autoassigned port
3654 			 * number space for IPv4 and IPv6 sockets.
3655 			 */
3656 			if (tcp->tcp_ipversion != ltcp->tcp_ipversion &&
3657 			    bind_to_req_port_only)
3658 				continue;
3659 
3660 			/*
3661 			 * Ideally, we should make sure that the source
3662 			 * address, remote address, and remote port in the
3663 			 * four tuple for this tcp-connection is unique.
3664 			 * However, trying to find out the local source
3665 			 * address would require too much code duplication
3666 			 * with IP, since IP needs needs to have that code
3667 			 * to support userland TCP implementations.
3668 			 */
3669 			if (quick_connect &&
3670 			    (ltcp->tcp_state > TCPS_LISTEN) &&
3671 			    ((tcp->tcp_fport != ltcp->tcp_fport) ||
3672 			    !IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
3673 			    &ltcp->tcp_remote_v6)))
3674 				continue;
3675 
3676 			if (!reuseaddr) {
3677 				/*
3678 				 * No socket option SO_REUSEADDR.
3679 				 * If existing port is bound to
3680 				 * a non-wildcard IP address
3681 				 * and the requesting stream is
3682 				 * bound to a distinct
3683 				 * different IP addresses
3684 				 * (non-wildcard, also), keep
3685 				 * going.
3686 				 */
3687 				if (!V6_OR_V4_INADDR_ANY(*laddr) &&
3688 				    !V6_OR_V4_INADDR_ANY(
3689 				    ltcp->tcp_bound_source_v6) &&
3690 				    !IN6_ARE_ADDR_EQUAL(laddr,
3691 				    &ltcp->tcp_bound_source_v6))
3692 					continue;
3693 				if (ltcp->tcp_state >= TCPS_BOUND) {
3694 					/*
3695 					 * This port is being used and
3696 					 * its state is >= TCPS_BOUND,
3697 					 * so we can't bind to it.
3698 					 */
3699 					break;
3700 				}
3701 			} else {
3702 				/*
3703 				 * socket option SO_REUSEADDR is set on the
3704 				 * binding tcp_t.
3705 				 *
3706 				 * If two streams are bound to
3707 				 * same IP address or both addr
3708 				 * and bound source are wildcards
3709 				 * (INADDR_ANY), we want to stop
3710 				 * searching.
3711 				 * We have found a match of IP source
3712 				 * address and source port, which is
3713 				 * refused regardless of the
3714 				 * SO_REUSEADDR setting, so we break.
3715 				 */
3716 				if (IN6_ARE_ADDR_EQUAL(laddr,
3717 				    &ltcp->tcp_bound_source_v6) &&
3718 				    (ltcp->tcp_state == TCPS_LISTEN ||
3719 				    ltcp->tcp_state == TCPS_BOUND))
3720 					break;
3721 			}
3722 		}
3723 		if (ltcp != NULL) {
3724 			/* The port number is busy */
3725 			mutex_exit(&tbf->tf_lock);
3726 		} else {
3727 			/*
3728 			 * This port is ours. Insert in fanout and mark as
3729 			 * bound to prevent others from getting the port
3730 			 * number.
3731 			 */
3732 			tcp->tcp_state = TCPS_BOUND;
3733 			tcp->tcp_lport = htons(port);
3734 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
3735 
3736 			ASSERT(&tcps->tcps_bind_fanout[TCP_BIND_HASH(
3737 			    tcp->tcp_lport)] == tbf);
3738 			tcp_bind_hash_insert(tbf, tcp, 1);
3739 
3740 			mutex_exit(&tbf->tf_lock);
3741 
3742 			/*
3743 			 * We don't want tcp_next_port_to_try to "inherit"
3744 			 * a port number supplied by the user in a bind.
3745 			 */
3746 			if (user_specified)
3747 				return (port);
3748 
3749 			/*
3750 			 * This is the only place where tcp_next_port_to_try
3751 			 * is updated. After the update, it may or may not
3752 			 * be in the valid range.
3753 			 */
3754 			if (!tcp->tcp_anon_priv_bind)
3755 				tcps->tcps_next_port_to_try = port + 1;
3756 			return (port);
3757 		}
3758 
3759 		if (tcp->tcp_anon_priv_bind) {
3760 			port = tcp_get_next_priv_port(tcp);
3761 		} else {
3762 			if (count == 0 && user_specified) {
3763 				/*
3764 				 * We may have to return an anonymous port. So
3765 				 * get one to start with.
3766 				 */
3767 				port =
3768 				    tcp_update_next_port(
3769 				    tcps->tcps_next_port_to_try,
3770 				    tcp, B_TRUE);
3771 				user_specified = B_FALSE;
3772 			} else {
3773 				port = tcp_update_next_port(port + 1, tcp,
3774 				    B_FALSE);
3775 			}
3776 		}
3777 		if (port == 0)
3778 			break;
3779 
3780 		/*
3781 		 * Don't let this loop run forever in the case where
3782 		 * all of the anonymous ports are in use.
3783 		 */
3784 	} while (++count < loopmax);
3785 	return (0);
3786 }
3787 
3788 /*
3789  * tcp_clean_death / tcp_close_detached must not be called more than once
3790  * on a tcp. Thus every function that potentially calls tcp_clean_death
3791  * must check for the tcp state before calling tcp_clean_death.
3792  * Eg. tcp_input, tcp_rput_data, tcp_eager_kill, tcp_clean_death_wrapper,
3793  * tcp_timer_handler, all check for the tcp state.
3794  */
3795 /* ARGSUSED */
3796 void
3797 tcp_clean_death_wrapper(void *arg, mblk_t *mp, void *arg2)
3798 {
3799 	tcp_t	*tcp = ((conn_t *)arg)->conn_tcp;
3800 
3801 	freemsg(mp);
3802 	if (tcp->tcp_state > TCPS_BOUND)
3803 		(void) tcp_clean_death(((conn_t *)arg)->conn_tcp,
3804 		    ETIMEDOUT, 5);
3805 }
3806 
3807 /*
3808  * We are dying for some reason.  Try to do it gracefully.  (May be called
3809  * as writer.)
3810  *
3811  * Return -1 if the structure was not cleaned up (if the cleanup had to be
3812  * done by a service procedure).
3813  * TBD - Should the return value distinguish between the tcp_t being
3814  * freed and it being reinitialized?
3815  */
3816 static int
3817 tcp_clean_death(tcp_t *tcp, int err, uint8_t tag)
3818 {
3819 	mblk_t	*mp;
3820 	queue_t	*q;
3821 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3822 	sodirect_t	*sodp;
3823 
3824 	TCP_CLD_STAT(tag);
3825 
3826 #if TCP_TAG_CLEAN_DEATH
3827 	tcp->tcp_cleandeathtag = tag;
3828 #endif
3829 
3830 	if (tcp->tcp_fused)
3831 		tcp_unfuse(tcp);
3832 
3833 	if (tcp->tcp_linger_tid != 0 &&
3834 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
3835 		tcp_stop_lingering(tcp);
3836 	}
3837 
3838 	ASSERT(tcp != NULL);
3839 	ASSERT((tcp->tcp_family == AF_INET &&
3840 	    tcp->tcp_ipversion == IPV4_VERSION) ||
3841 	    (tcp->tcp_family == AF_INET6 &&
3842 	    (tcp->tcp_ipversion == IPV4_VERSION ||
3843 	    tcp->tcp_ipversion == IPV6_VERSION)));
3844 
3845 	if (TCP_IS_DETACHED(tcp)) {
3846 		if (tcp->tcp_hard_binding) {
3847 			/*
3848 			 * Its an eager that we are dealing with. We close the
3849 			 * eager but in case a conn_ind has already gone to the
3850 			 * listener, let tcp_accept_finish() send a discon_ind
3851 			 * to the listener and drop the last reference. If the
3852 			 * listener doesn't even know about the eager i.e. the
3853 			 * conn_ind hasn't gone up, blow away the eager and drop
3854 			 * the last reference as well. If the conn_ind has gone
3855 			 * up, state should be BOUND. tcp_accept_finish
3856 			 * will figure out that the connection has received a
3857 			 * RST and will send a DISCON_IND to the application.
3858 			 */
3859 			tcp_closei_local(tcp);
3860 			if (!tcp->tcp_tconnind_started) {
3861 				CONN_DEC_REF(tcp->tcp_connp);
3862 			} else {
3863 				tcp->tcp_state = TCPS_BOUND;
3864 			}
3865 		} else {
3866 			tcp_close_detached(tcp);
3867 		}
3868 		return (0);
3869 	}
3870 
3871 	TCP_STAT(tcps, tcp_clean_death_nondetached);
3872 
3873 	/* If sodirect, not anymore */
3874 	SOD_PTR_ENTER(tcp, sodp);
3875 	if (sodp != NULL) {
3876 		tcp->tcp_sodirect = NULL;
3877 		mutex_exit(sodp->sod_lockp);
3878 	}
3879 
3880 	q = tcp->tcp_rq;
3881 
3882 	/* Trash all inbound data */
3883 	flushq(q, FLUSHALL);
3884 
3885 	/*
3886 	 * If we are at least part way open and there is error
3887 	 * (err==0 implies no error)
3888 	 * notify our client by a T_DISCON_IND.
3889 	 */
3890 	if ((tcp->tcp_state >= TCPS_SYN_SENT) && err) {
3891 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
3892 		    !TCP_IS_SOCKET(tcp)) {
3893 			/*
3894 			 * Send M_FLUSH according to TPI. Because sockets will
3895 			 * (and must) ignore FLUSHR we do that only for TPI
3896 			 * endpoints and sockets in STREAMS mode.
3897 			 */
3898 			(void) putnextctl1(q, M_FLUSH, FLUSHR);
3899 		}
3900 		if (tcp->tcp_debug) {
3901 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
3902 			    "tcp_clean_death: discon err %d", err);
3903 		}
3904 		mp = mi_tpi_discon_ind(NULL, err, 0);
3905 		if (mp != NULL) {
3906 			putnext(q, mp);
3907 		} else {
3908 			if (tcp->tcp_debug) {
3909 				(void) strlog(TCP_MOD_ID, 0, 1,
3910 				    SL_ERROR|SL_TRACE,
3911 				    "tcp_clean_death, sending M_ERROR");
3912 			}
3913 			(void) putnextctl1(q, M_ERROR, EPROTO);
3914 		}
3915 		if (tcp->tcp_state <= TCPS_SYN_RCVD) {
3916 			/* SYN_SENT or SYN_RCVD */
3917 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
3918 		} else if (tcp->tcp_state <= TCPS_CLOSE_WAIT) {
3919 			/* ESTABLISHED or CLOSE_WAIT */
3920 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
3921 		}
3922 	}
3923 
3924 	tcp_reinit(tcp);
3925 	return (-1);
3926 }
3927 
3928 /*
3929  * In case tcp is in the "lingering state" and waits for the SO_LINGER timeout
3930  * to expire, stop the wait and finish the close.
3931  */
3932 static void
3933 tcp_stop_lingering(tcp_t *tcp)
3934 {
3935 	clock_t	delta = 0;
3936 	tcp_stack_t	*tcps = tcp->tcp_tcps;
3937 
3938 	tcp->tcp_linger_tid = 0;
3939 	if (tcp->tcp_state > TCPS_LISTEN) {
3940 		tcp_acceptor_hash_remove(tcp);
3941 		mutex_enter(&tcp->tcp_non_sq_lock);
3942 		if (tcp->tcp_flow_stopped) {
3943 			tcp_clrqfull(tcp);
3944 		}
3945 		mutex_exit(&tcp->tcp_non_sq_lock);
3946 
3947 		if (tcp->tcp_timer_tid != 0) {
3948 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
3949 			tcp->tcp_timer_tid = 0;
3950 		}
3951 		/*
3952 		 * Need to cancel those timers which will not be used when
3953 		 * TCP is detached.  This has to be done before the tcp_wq
3954 		 * is set to the global queue.
3955 		 */
3956 		tcp_timers_stop(tcp);
3957 
3958 
3959 		tcp->tcp_detached = B_TRUE;
3960 		ASSERT(tcps->tcps_g_q != NULL);
3961 		tcp->tcp_rq = tcps->tcps_g_q;
3962 		tcp->tcp_wq = WR(tcps->tcps_g_q);
3963 
3964 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
3965 			tcp_time_wait_append(tcp);
3966 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
3967 			goto finish;
3968 		}
3969 
3970 		/*
3971 		 * If delta is zero the timer event wasn't executed and was
3972 		 * successfully canceled. In this case we need to restart it
3973 		 * with the minimal delta possible.
3974 		 */
3975 		if (delta >= 0) {
3976 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
3977 			    delta ? delta : 1);
3978 		}
3979 	} else {
3980 		tcp_closei_local(tcp);
3981 		CONN_DEC_REF(tcp->tcp_connp);
3982 	}
3983 finish:
3984 	/* Signal closing thread that it can complete close */
3985 	mutex_enter(&tcp->tcp_closelock);
3986 	tcp->tcp_detached = B_TRUE;
3987 	ASSERT(tcps->tcps_g_q != NULL);
3988 	tcp->tcp_rq = tcps->tcps_g_q;
3989 	tcp->tcp_wq = WR(tcps->tcps_g_q);
3990 	tcp->tcp_closed = 1;
3991 	cv_signal(&tcp->tcp_closecv);
3992 	mutex_exit(&tcp->tcp_closelock);
3993 }
3994 
3995 /*
3996  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
3997  * expires.
3998  */
3999 static void
4000 tcp_close_linger_timeout(void *arg)
4001 {
4002 	conn_t	*connp = (conn_t *)arg;
4003 	tcp_t 	*tcp = connp->conn_tcp;
4004 
4005 	tcp->tcp_client_errno = ETIMEDOUT;
4006 	tcp_stop_lingering(tcp);
4007 }
4008 
4009 static int
4010 tcp_close(queue_t *q, int flags)
4011 {
4012 	conn_t		*connp = Q_TO_CONN(q);
4013 	tcp_t		*tcp = connp->conn_tcp;
4014 	mblk_t 		*mp = &tcp->tcp_closemp;
4015 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
4016 	mblk_t		*bp;
4017 
4018 	ASSERT(WR(q)->q_next == NULL);
4019 	ASSERT(connp->conn_ref >= 2);
4020 
4021 	/*
4022 	 * We are being closed as /dev/tcp or /dev/tcp6.
4023 	 *
4024 	 * Mark the conn as closing. ill_pending_mp_add will not
4025 	 * add any mp to the pending mp list, after this conn has
4026 	 * started closing. Same for sq_pending_mp_add
4027 	 */
4028 	mutex_enter(&connp->conn_lock);
4029 	connp->conn_state_flags |= CONN_CLOSING;
4030 	if (connp->conn_oper_pending_ill != NULL)
4031 		conn_ioctl_cleanup_reqd = B_TRUE;
4032 	CONN_INC_REF_LOCKED(connp);
4033 	mutex_exit(&connp->conn_lock);
4034 	tcp->tcp_closeflags = (uint8_t)flags;
4035 	ASSERT(connp->conn_ref >= 3);
4036 
4037 	/*
4038 	 * tcp_closemp_used is used below without any protection of a lock
4039 	 * as we don't expect any one else to use it concurrently at this
4040 	 * point otherwise it would be a major defect.
4041 	 */
4042 
4043 	if (mp->b_prev == NULL)
4044 		tcp->tcp_closemp_used = B_TRUE;
4045 	else
4046 		cmn_err(CE_PANIC, "tcp_close: concurrent use of tcp_closemp: "
4047 		    "connp %p tcp %p\n", (void *)connp, (void *)tcp);
4048 
4049 	TCP_DEBUG_GETPCSTACK(tcp->tcmp_stk, 15);
4050 
4051 	(*tcp_squeue_close_proc)(connp->conn_sqp, mp,
4052 	    tcp_close_output, connp, SQTAG_IP_TCP_CLOSE);
4053 
4054 	mutex_enter(&tcp->tcp_closelock);
4055 	while (!tcp->tcp_closed) {
4056 		if (!cv_wait_sig(&tcp->tcp_closecv, &tcp->tcp_closelock)) {
4057 			/*
4058 			 * The cv_wait_sig() was interrupted. We now do the
4059 			 * following:
4060 			 *
4061 			 * 1) If the endpoint was lingering, we allow this
4062 			 * to be interrupted by cancelling the linger timeout
4063 			 * and closing normally.
4064 			 *
4065 			 * 2) Revert to calling cv_wait()
4066 			 *
4067 			 * We revert to using cv_wait() to avoid an
4068 			 * infinite loop which can occur if the calling
4069 			 * thread is higher priority than the squeue worker
4070 			 * thread and is bound to the same cpu.
4071 			 */
4072 			if (tcp->tcp_linger && tcp->tcp_lingertime > 0) {
4073 				mutex_exit(&tcp->tcp_closelock);
4074 				/* Entering squeue, bump ref count. */
4075 				CONN_INC_REF(connp);
4076 				bp = allocb_wait(0, BPRI_HI, STR_NOSIG, NULL);
4077 				squeue_enter(connp->conn_sqp, bp,
4078 				    tcp_linger_interrupted, connp,
4079 				    SQTAG_IP_TCP_CLOSE);
4080 				mutex_enter(&tcp->tcp_closelock);
4081 			}
4082 			break;
4083 		}
4084 	}
4085 	while (!tcp->tcp_closed)
4086 		cv_wait(&tcp->tcp_closecv, &tcp->tcp_closelock);
4087 	mutex_exit(&tcp->tcp_closelock);
4088 
4089 	/*
4090 	 * In the case of listener streams that have eagers in the q or q0
4091 	 * we wait for the eagers to drop their reference to us. tcp_rq and
4092 	 * tcp_wq of the eagers point to our queues. By waiting for the
4093 	 * refcnt to drop to 1, we are sure that the eagers have cleaned
4094 	 * up their queue pointers and also dropped their references to us.
4095 	 */
4096 	if (tcp->tcp_wait_for_eagers) {
4097 		mutex_enter(&connp->conn_lock);
4098 		while (connp->conn_ref != 1) {
4099 			cv_wait(&connp->conn_cv, &connp->conn_lock);
4100 		}
4101 		mutex_exit(&connp->conn_lock);
4102 	}
4103 	/*
4104 	 * ioctl cleanup. The mp is queued in the
4105 	 * ill_pending_mp or in the sq_pending_mp.
4106 	 */
4107 	if (conn_ioctl_cleanup_reqd)
4108 		conn_ioctl_cleanup(connp);
4109 
4110 	qprocsoff(q);
4111 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
4112 
4113 	tcp->tcp_cpid = -1;
4114 
4115 	/*
4116 	 * Drop IP's reference on the conn. This is the last reference
4117 	 * on the connp if the state was less than established. If the
4118 	 * connection has gone into timewait state, then we will have
4119 	 * one ref for the TCP and one more ref (total of two) for the
4120 	 * classifier connected hash list (a timewait connections stays
4121 	 * in connected hash till closed).
4122 	 *
4123 	 * We can't assert the references because there might be other
4124 	 * transient reference places because of some walkers or queued
4125 	 * packets in squeue for the timewait state.
4126 	 */
4127 	CONN_DEC_REF(connp);
4128 	q->q_ptr = WR(q)->q_ptr = NULL;
4129 	return (0);
4130 }
4131 
4132 static int
4133 tcpclose_accept(queue_t *q)
4134 {
4135 	vmem_t	*minor_arena;
4136 	dev_t	conn_dev;
4137 
4138 	ASSERT(WR(q)->q_qinfo == &tcp_acceptor_winit);
4139 
4140 	/*
4141 	 * We had opened an acceptor STREAM for sockfs which is
4142 	 * now being closed due to some error.
4143 	 */
4144 	qprocsoff(q);
4145 
4146 	minor_arena = (vmem_t *)WR(q)->q_ptr;
4147 	conn_dev = (dev_t)RD(q)->q_ptr;
4148 	ASSERT(minor_arena != NULL);
4149 	ASSERT(conn_dev != 0);
4150 	inet_minor_free(minor_arena, conn_dev);
4151 	q->q_ptr = WR(q)->q_ptr = NULL;
4152 	return (0);
4153 }
4154 
4155 /*
4156  * Called by tcp_close() routine via squeue when lingering is
4157  * interrupted by a signal.
4158  */
4159 
4160 /* ARGSUSED */
4161 static void
4162 tcp_linger_interrupted(void *arg, mblk_t *mp, void *arg2)
4163 {
4164 	conn_t	*connp = (conn_t *)arg;
4165 	tcp_t	*tcp = connp->conn_tcp;
4166 
4167 	freeb(mp);
4168 	if (tcp->tcp_linger_tid != 0 &&
4169 	    TCP_TIMER_CANCEL(tcp, tcp->tcp_linger_tid) >= 0) {
4170 		tcp_stop_lingering(tcp);
4171 		tcp->tcp_client_errno = EINTR;
4172 	}
4173 }
4174 
4175 /*
4176  * Called by streams close routine via squeues when our client blows off her
4177  * descriptor, we take this to mean: "close the stream state NOW, close the tcp
4178  * connection politely" When SO_LINGER is set (with a non-zero linger time and
4179  * it is not a nonblocking socket) then this routine sleeps until the FIN is
4180  * acked.
4181  *
4182  * NOTE: tcp_close potentially returns error when lingering.
4183  * However, the stream head currently does not pass these errors
4184  * to the application. 4.4BSD only returns EINTR and EWOULDBLOCK
4185  * errors to the application (from tsleep()) and not errors
4186  * like ECONNRESET caused by receiving a reset packet.
4187  */
4188 
4189 /* ARGSUSED */
4190 static void
4191 tcp_close_output(void *arg, mblk_t *mp, void *arg2)
4192 {
4193 	char	*msg;
4194 	conn_t	*connp = (conn_t *)arg;
4195 	tcp_t	*tcp = connp->conn_tcp;
4196 	clock_t	delta = 0;
4197 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4198 
4199 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
4200 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
4201 
4202 	mutex_enter(&tcp->tcp_eager_lock);
4203 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
4204 		/* Cleanup for listener */
4205 		tcp_eager_cleanup(tcp, 0);
4206 		tcp->tcp_wait_for_eagers = 1;
4207 	}
4208 	mutex_exit(&tcp->tcp_eager_lock);
4209 
4210 	connp->conn_mdt_ok = B_FALSE;
4211 	tcp->tcp_mdt = B_FALSE;
4212 
4213 	connp->conn_lso_ok = B_FALSE;
4214 	tcp->tcp_lso = B_FALSE;
4215 
4216 	msg = NULL;
4217 	switch (tcp->tcp_state) {
4218 	case TCPS_CLOSED:
4219 	case TCPS_IDLE:
4220 	case TCPS_BOUND:
4221 	case TCPS_LISTEN:
4222 		break;
4223 	case TCPS_SYN_SENT:
4224 		msg = "tcp_close, during connect";
4225 		break;
4226 	case TCPS_SYN_RCVD:
4227 		/*
4228 		 * Close during the connect 3-way handshake
4229 		 * but here there may or may not be pending data
4230 		 * already on queue. Process almost same as in
4231 		 * the ESTABLISHED state.
4232 		 */
4233 		/* FALLTHRU */
4234 	default:
4235 		if (tcp->tcp_sodirect != NULL) {
4236 			/* Ok, no more sodirect */
4237 			tcp->tcp_sodirect = NULL;
4238 		}
4239 
4240 		if (tcp->tcp_fused)
4241 			tcp_unfuse(tcp);
4242 
4243 		/*
4244 		 * If SO_LINGER has set a zero linger time, abort the
4245 		 * connection with a reset.
4246 		 */
4247 		if (tcp->tcp_linger && tcp->tcp_lingertime == 0) {
4248 			msg = "tcp_close, zero lingertime";
4249 			break;
4250 		}
4251 
4252 		ASSERT(tcp->tcp_hard_bound || tcp->tcp_hard_binding);
4253 		/*
4254 		 * Abort connection if there is unread data queued.
4255 		 */
4256 		if (tcp->tcp_rcv_list || tcp->tcp_reass_head) {
4257 			msg = "tcp_close, unread data";
4258 			break;
4259 		}
4260 		/*
4261 		 * tcp_hard_bound is now cleared thus all packets go through
4262 		 * tcp_lookup. This fact is used by tcp_detach below.
4263 		 *
4264 		 * We have done a qwait() above which could have possibly
4265 		 * drained more messages in turn causing transition to a
4266 		 * different state. Check whether we have to do the rest
4267 		 * of the processing or not.
4268 		 */
4269 		if (tcp->tcp_state <= TCPS_LISTEN)
4270 			break;
4271 
4272 		/*
4273 		 * Transmit the FIN before detaching the tcp_t.
4274 		 * After tcp_detach returns this queue/perimeter
4275 		 * no longer owns the tcp_t thus others can modify it.
4276 		 */
4277 		(void) tcp_xmit_end(tcp);
4278 
4279 		/*
4280 		 * If lingering on close then wait until the fin is acked,
4281 		 * the SO_LINGER time passes, or a reset is sent/received.
4282 		 */
4283 		if (tcp->tcp_linger && tcp->tcp_lingertime > 0 &&
4284 		    !(tcp->tcp_fin_acked) &&
4285 		    tcp->tcp_state >= TCPS_ESTABLISHED) {
4286 			if (tcp->tcp_closeflags & (FNDELAY|FNONBLOCK)) {
4287 				tcp->tcp_client_errno = EWOULDBLOCK;
4288 			} else if (tcp->tcp_client_errno == 0) {
4289 
4290 				ASSERT(tcp->tcp_linger_tid == 0);
4291 
4292 				tcp->tcp_linger_tid = TCP_TIMER(tcp,
4293 				    tcp_close_linger_timeout,
4294 				    tcp->tcp_lingertime * hz);
4295 
4296 				/* tcp_close_linger_timeout will finish close */
4297 				if (tcp->tcp_linger_tid == 0)
4298 					tcp->tcp_client_errno = ENOSR;
4299 				else
4300 					return;
4301 			}
4302 
4303 			/*
4304 			 * Check if we need to detach or just close
4305 			 * the instance.
4306 			 */
4307 			if (tcp->tcp_state <= TCPS_LISTEN)
4308 				break;
4309 		}
4310 
4311 		/*
4312 		 * Make sure that no other thread will access the tcp_rq of
4313 		 * this instance (through lookups etc.) as tcp_rq will go
4314 		 * away shortly.
4315 		 */
4316 		tcp_acceptor_hash_remove(tcp);
4317 
4318 		mutex_enter(&tcp->tcp_non_sq_lock);
4319 		if (tcp->tcp_flow_stopped) {
4320 			tcp_clrqfull(tcp);
4321 		}
4322 		mutex_exit(&tcp->tcp_non_sq_lock);
4323 
4324 		if (tcp->tcp_timer_tid != 0) {
4325 			delta = TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4326 			tcp->tcp_timer_tid = 0;
4327 		}
4328 		/*
4329 		 * Need to cancel those timers which will not be used when
4330 		 * TCP is detached.  This has to be done before the tcp_wq
4331 		 * is set to the global queue.
4332 		 */
4333 		tcp_timers_stop(tcp);
4334 
4335 		tcp->tcp_detached = B_TRUE;
4336 		if (tcp->tcp_state == TCPS_TIME_WAIT) {
4337 			tcp_time_wait_append(tcp);
4338 			TCP_DBGSTAT(tcps, tcp_detach_time_wait);
4339 			ASSERT(connp->conn_ref >= 3);
4340 			goto finish;
4341 		}
4342 
4343 		/*
4344 		 * If delta is zero the timer event wasn't executed and was
4345 		 * successfully canceled. In this case we need to restart it
4346 		 * with the minimal delta possible.
4347 		 */
4348 		if (delta >= 0)
4349 			tcp->tcp_timer_tid = TCP_TIMER(tcp, tcp_timer,
4350 			    delta ? delta : 1);
4351 
4352 		ASSERT(connp->conn_ref >= 3);
4353 		goto finish;
4354 	}
4355 
4356 	/* Detach did not complete. Still need to remove q from stream. */
4357 	if (msg) {
4358 		if (tcp->tcp_state == TCPS_ESTABLISHED ||
4359 		    tcp->tcp_state == TCPS_CLOSE_WAIT)
4360 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
4361 		if (tcp->tcp_state == TCPS_SYN_SENT ||
4362 		    tcp->tcp_state == TCPS_SYN_RCVD)
4363 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
4364 		tcp_xmit_ctl(msg, tcp,  tcp->tcp_snxt, 0, TH_RST);
4365 	}
4366 
4367 	tcp_closei_local(tcp);
4368 	CONN_DEC_REF(connp);
4369 	ASSERT(connp->conn_ref >= 2);
4370 
4371 finish:
4372 	/*
4373 	 * Although packets are always processed on the correct
4374 	 * tcp's perimeter and access is serialized via squeue's,
4375 	 * IP still needs a queue when sending packets in time_wait
4376 	 * state so use WR(tcps_g_q) till ip_output() can be
4377 	 * changed to deal with just connp. For read side, we
4378 	 * could have set tcp_rq to NULL but there are some cases
4379 	 * in tcp_rput_data() from early days of this code which
4380 	 * do a putnext without checking if tcp is closed. Those
4381 	 * need to be identified before both tcp_rq and tcp_wq
4382 	 * can be set to NULL and tcps_g_q can disappear forever.
4383 	 */
4384 	mutex_enter(&tcp->tcp_closelock);
4385 	/*
4386 	 * Don't change the queues in the case of a listener that has
4387 	 * eagers in its q or q0. It could surprise the eagers.
4388 	 * Instead wait for the eagers outside the squeue.
4389 	 */
4390 	if (!tcp->tcp_wait_for_eagers) {
4391 		tcp->tcp_detached = B_TRUE;
4392 		/*
4393 		 * When default queue is closing we set tcps_g_q to NULL
4394 		 * after the close is done.
4395 		 */
4396 		ASSERT(tcps->tcps_g_q != NULL);
4397 		tcp->tcp_rq = tcps->tcps_g_q;
4398 		tcp->tcp_wq = WR(tcps->tcps_g_q);
4399 	}
4400 
4401 	/* Signal tcp_close() to finish closing. */
4402 	tcp->tcp_closed = 1;
4403 	cv_signal(&tcp->tcp_closecv);
4404 	mutex_exit(&tcp->tcp_closelock);
4405 }
4406 
4407 
4408 /*
4409  * Clean up the b_next and b_prev fields of every mblk pointed at by *mpp.
4410  * Some stream heads get upset if they see these later on as anything but NULL.
4411  */
4412 static void
4413 tcp_close_mpp(mblk_t **mpp)
4414 {
4415 	mblk_t	*mp;
4416 
4417 	if ((mp = *mpp) != NULL) {
4418 		do {
4419 			mp->b_next = NULL;
4420 			mp->b_prev = NULL;
4421 		} while ((mp = mp->b_cont) != NULL);
4422 
4423 		mp = *mpp;
4424 		*mpp = NULL;
4425 		freemsg(mp);
4426 	}
4427 }
4428 
4429 /* Do detached close. */
4430 static void
4431 tcp_close_detached(tcp_t *tcp)
4432 {
4433 	if (tcp->tcp_fused)
4434 		tcp_unfuse(tcp);
4435 
4436 	/*
4437 	 * Clustering code serializes TCP disconnect callbacks and
4438 	 * cluster tcp list walks by blocking a TCP disconnect callback
4439 	 * if a cluster tcp list walk is in progress. This ensures
4440 	 * accurate accounting of TCPs in the cluster code even though
4441 	 * the TCP list walk itself is not atomic.
4442 	 */
4443 	tcp_closei_local(tcp);
4444 	CONN_DEC_REF(tcp->tcp_connp);
4445 }
4446 
4447 /*
4448  * Stop all TCP timers, and free the timer mblks if requested.
4449  */
4450 void
4451 tcp_timers_stop(tcp_t *tcp)
4452 {
4453 	if (tcp->tcp_timer_tid != 0) {
4454 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
4455 		tcp->tcp_timer_tid = 0;
4456 	}
4457 	if (tcp->tcp_ka_tid != 0) {
4458 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
4459 		tcp->tcp_ka_tid = 0;
4460 	}
4461 	if (tcp->tcp_ack_tid != 0) {
4462 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
4463 		tcp->tcp_ack_tid = 0;
4464 	}
4465 	if (tcp->tcp_push_tid != 0) {
4466 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
4467 		tcp->tcp_push_tid = 0;
4468 	}
4469 }
4470 
4471 /*
4472  * The tcp_t is going away. Remove it from all lists and set it
4473  * to TCPS_CLOSED. The freeing up of memory is deferred until
4474  * tcp_inactive. This is needed since a thread in tcp_rput might have
4475  * done a CONN_INC_REF on this structure before it was removed from the
4476  * hashes.
4477  */
4478 static void
4479 tcp_closei_local(tcp_t *tcp)
4480 {
4481 	ire_t 	*ire;
4482 	conn_t	*connp = tcp->tcp_connp;
4483 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4484 
4485 	if (!TCP_IS_SOCKET(tcp))
4486 		tcp_acceptor_hash_remove(tcp);
4487 
4488 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
4489 	tcp->tcp_ibsegs = 0;
4490 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
4491 	tcp->tcp_obsegs = 0;
4492 
4493 	/*
4494 	 * If we are an eager connection hanging off a listener that
4495 	 * hasn't formally accepted the connection yet, get off his
4496 	 * list and blow off any data that we have accumulated.
4497 	 */
4498 	if (tcp->tcp_listener != NULL) {
4499 		tcp_t	*listener = tcp->tcp_listener;
4500 		mutex_enter(&listener->tcp_eager_lock);
4501 		/*
4502 		 * tcp_tconnind_started == B_TRUE means that the
4503 		 * conn_ind has already gone to listener. At
4504 		 * this point, eager will be closed but we
4505 		 * leave it in listeners eager list so that
4506 		 * if listener decides to close without doing
4507 		 * accept, we can clean this up. In tcp_wput_accept
4508 		 * we take care of the case of accept on closed
4509 		 * eager.
4510 		 */
4511 		if (!tcp->tcp_tconnind_started) {
4512 			tcp_eager_unlink(tcp);
4513 			mutex_exit(&listener->tcp_eager_lock);
4514 			/*
4515 			 * We don't want to have any pointers to the
4516 			 * listener queue, after we have released our
4517 			 * reference on the listener
4518 			 */
4519 			ASSERT(tcps->tcps_g_q != NULL);
4520 			tcp->tcp_rq = tcps->tcps_g_q;
4521 			tcp->tcp_wq = WR(tcps->tcps_g_q);
4522 			CONN_DEC_REF(listener->tcp_connp);
4523 		} else {
4524 			mutex_exit(&listener->tcp_eager_lock);
4525 		}
4526 	}
4527 
4528 	/* Stop all the timers */
4529 	tcp_timers_stop(tcp);
4530 
4531 	if (tcp->tcp_state == TCPS_LISTEN) {
4532 		if (tcp->tcp_ip_addr_cache) {
4533 			kmem_free((void *)tcp->tcp_ip_addr_cache,
4534 			    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
4535 			tcp->tcp_ip_addr_cache = NULL;
4536 		}
4537 	}
4538 	mutex_enter(&tcp->tcp_non_sq_lock);
4539 	if (tcp->tcp_flow_stopped)
4540 		tcp_clrqfull(tcp);
4541 	mutex_exit(&tcp->tcp_non_sq_lock);
4542 
4543 	tcp_bind_hash_remove(tcp);
4544 	/*
4545 	 * If the tcp_time_wait_collector (which runs outside the squeue)
4546 	 * is trying to remove this tcp from the time wait list, we will
4547 	 * block in tcp_time_wait_remove while trying to acquire the
4548 	 * tcp_time_wait_lock. The logic in tcp_time_wait_collector also
4549 	 * requires the ipcl_hash_remove to be ordered after the
4550 	 * tcp_time_wait_remove for the refcnt checks to work correctly.
4551 	 */
4552 	if (tcp->tcp_state == TCPS_TIME_WAIT)
4553 		(void) tcp_time_wait_remove(tcp, NULL);
4554 	CL_INET_DISCONNECT(tcp);
4555 	ipcl_hash_remove(connp);
4556 
4557 	/*
4558 	 * Delete the cached ire in conn_ire_cache and also mark
4559 	 * the conn as CONDEMNED
4560 	 */
4561 	mutex_enter(&connp->conn_lock);
4562 	connp->conn_state_flags |= CONN_CONDEMNED;
4563 	ire = connp->conn_ire_cache;
4564 	connp->conn_ire_cache = NULL;
4565 	mutex_exit(&connp->conn_lock);
4566 	if (ire != NULL)
4567 		IRE_REFRELE_NOTR(ire);
4568 
4569 	/* Need to cleanup any pending ioctls */
4570 	ASSERT(tcp->tcp_time_wait_next == NULL);
4571 	ASSERT(tcp->tcp_time_wait_prev == NULL);
4572 	ASSERT(tcp->tcp_time_wait_expire == 0);
4573 	tcp->tcp_state = TCPS_CLOSED;
4574 
4575 	/* Release any SSL context */
4576 	if (tcp->tcp_kssl_ent != NULL) {
4577 		kssl_release_ent(tcp->tcp_kssl_ent, NULL, KSSL_NO_PROXY);
4578 		tcp->tcp_kssl_ent = NULL;
4579 	}
4580 	if (tcp->tcp_kssl_ctx != NULL) {
4581 		kssl_release_ctx(tcp->tcp_kssl_ctx);
4582 		tcp->tcp_kssl_ctx = NULL;
4583 	}
4584 	tcp->tcp_kssl_pending = B_FALSE;
4585 
4586 	tcp_ipsec_cleanup(tcp);
4587 }
4588 
4589 /*
4590  * tcp is dying (called from ipcl_conn_destroy and error cases).
4591  * Free the tcp_t in either case.
4592  */
4593 void
4594 tcp_free(tcp_t *tcp)
4595 {
4596 	mblk_t	*mp;
4597 	ip6_pkt_t	*ipp;
4598 
4599 	ASSERT(tcp != NULL);
4600 	ASSERT(tcp->tcp_ptpahn == NULL && tcp->tcp_acceptor_hash == NULL);
4601 
4602 	tcp->tcp_rq = NULL;
4603 	tcp->tcp_wq = NULL;
4604 
4605 	tcp_close_mpp(&tcp->tcp_xmit_head);
4606 	tcp_close_mpp(&tcp->tcp_reass_head);
4607 	if (tcp->tcp_rcv_list != NULL) {
4608 		/* Free b_next chain */
4609 		tcp_close_mpp(&tcp->tcp_rcv_list);
4610 	}
4611 	if ((mp = tcp->tcp_urp_mp) != NULL) {
4612 		freemsg(mp);
4613 	}
4614 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
4615 		freemsg(mp);
4616 	}
4617 
4618 	if (tcp->tcp_fused_sigurg_mp != NULL) {
4619 		freeb(tcp->tcp_fused_sigurg_mp);
4620 		tcp->tcp_fused_sigurg_mp = NULL;
4621 	}
4622 
4623 	if (tcp->tcp_sack_info != NULL) {
4624 		if (tcp->tcp_notsack_list != NULL) {
4625 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
4626 		}
4627 		bzero(tcp->tcp_sack_info, sizeof (tcp_sack_info_t));
4628 	}
4629 
4630 	if (tcp->tcp_hopopts != NULL) {
4631 		mi_free(tcp->tcp_hopopts);
4632 		tcp->tcp_hopopts = NULL;
4633 		tcp->tcp_hopoptslen = 0;
4634 	}
4635 	ASSERT(tcp->tcp_hopoptslen == 0);
4636 	if (tcp->tcp_dstopts != NULL) {
4637 		mi_free(tcp->tcp_dstopts);
4638 		tcp->tcp_dstopts = NULL;
4639 		tcp->tcp_dstoptslen = 0;
4640 	}
4641 	ASSERT(tcp->tcp_dstoptslen == 0);
4642 	if (tcp->tcp_rtdstopts != NULL) {
4643 		mi_free(tcp->tcp_rtdstopts);
4644 		tcp->tcp_rtdstopts = NULL;
4645 		tcp->tcp_rtdstoptslen = 0;
4646 	}
4647 	ASSERT(tcp->tcp_rtdstoptslen == 0);
4648 	if (tcp->tcp_rthdr != NULL) {
4649 		mi_free(tcp->tcp_rthdr);
4650 		tcp->tcp_rthdr = NULL;
4651 		tcp->tcp_rthdrlen = 0;
4652 	}
4653 	ASSERT(tcp->tcp_rthdrlen == 0);
4654 
4655 	ipp = &tcp->tcp_sticky_ipp;
4656 	if (ipp->ipp_fields & (IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
4657 	    IPPF_RTHDR))
4658 		ip6_pkt_free(ipp);
4659 
4660 	/*
4661 	 * Free memory associated with the tcp/ip header template.
4662 	 */
4663 
4664 	if (tcp->tcp_iphc != NULL)
4665 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4666 
4667 	/*
4668 	 * Following is really a blowing away a union.
4669 	 * It happens to have exactly two members of identical size
4670 	 * the following code is enough.
4671 	 */
4672 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
4673 }
4674 
4675 
4676 /*
4677  * Put a connection confirmation message upstream built from the
4678  * address information within 'iph' and 'tcph'.  Report our success or failure.
4679  */
4680 static boolean_t
4681 tcp_conn_con(tcp_t *tcp, uchar_t *iphdr, tcph_t *tcph, mblk_t *idmp,
4682     mblk_t **defermp)
4683 {
4684 	sin_t	sin;
4685 	sin6_t	sin6;
4686 	mblk_t	*mp;
4687 	char	*optp = NULL;
4688 	int	optlen = 0;
4689 	cred_t	*cr;
4690 
4691 	if (defermp != NULL)
4692 		*defermp = NULL;
4693 
4694 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL) {
4695 		/*
4696 		 * Return in T_CONN_CON results of option negotiation through
4697 		 * the T_CONN_REQ. Note: If there is an real end-to-end option
4698 		 * negotiation, then what is received from remote end needs
4699 		 * to be taken into account but there is no such thing (yet?)
4700 		 * in our TCP/IP.
4701 		 * Note: We do not use mi_offset_param() here as
4702 		 * tcp_opts_conn_req contents do not directly come from
4703 		 * an application and are either generated in kernel or
4704 		 * from user input that was already verified.
4705 		 */
4706 		mp = tcp->tcp_conn.tcp_opts_conn_req;
4707 		optp = (char *)(mp->b_rptr +
4708 		    ((struct T_conn_req *)mp->b_rptr)->OPT_offset);
4709 		optlen = (int)
4710 		    ((struct T_conn_req *)mp->b_rptr)->OPT_length;
4711 	}
4712 
4713 	if (IPH_HDR_VERSION(iphdr) == IPV4_VERSION) {
4714 		ipha_t *ipha = (ipha_t *)iphdr;
4715 
4716 		/* packet is IPv4 */
4717 		if (tcp->tcp_family == AF_INET) {
4718 			sin = sin_null;
4719 			sin.sin_addr.s_addr = ipha->ipha_src;
4720 			sin.sin_port = *(uint16_t *)tcph->th_lport;
4721 			sin.sin_family = AF_INET;
4722 			mp = mi_tpi_conn_con(NULL, (char *)&sin,
4723 			    (int)sizeof (sin_t), optp, optlen);
4724 		} else {
4725 			sin6 = sin6_null;
4726 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4727 			sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4728 			sin6.sin6_family = AF_INET6;
4729 			mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4730 			    (int)sizeof (sin6_t), optp, optlen);
4731 
4732 		}
4733 	} else {
4734 		ip6_t	*ip6h = (ip6_t *)iphdr;
4735 
4736 		ASSERT(IPH_HDR_VERSION(iphdr) == IPV6_VERSION);
4737 		ASSERT(tcp->tcp_family == AF_INET6);
4738 		sin6 = sin6_null;
4739 		sin6.sin6_addr = ip6h->ip6_src;
4740 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4741 		sin6.sin6_family = AF_INET6;
4742 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4743 		mp = mi_tpi_conn_con(NULL, (char *)&sin6,
4744 		    (int)sizeof (sin6_t), optp, optlen);
4745 	}
4746 
4747 	if (!mp)
4748 		return (B_FALSE);
4749 
4750 	if ((cr = DB_CRED(idmp)) != NULL) {
4751 		mblk_setcred(mp, cr);
4752 		DB_CPID(mp) = DB_CPID(idmp);
4753 	}
4754 
4755 	if (defermp == NULL)
4756 		putnext(tcp->tcp_rq, mp);
4757 	else
4758 		*defermp = mp;
4759 
4760 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
4761 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
4762 	return (B_TRUE);
4763 }
4764 
4765 /*
4766  * Defense for the SYN attack -
4767  * 1. When q0 is full, drop from the tail (tcp_eager_prev_drop_q0) the oldest
4768  *    one from the list of droppable eagers. This list is a subset of q0.
4769  *    see comments before the definition of MAKE_DROPPABLE().
4770  * 2. Don't drop a SYN request before its first timeout. This gives every
4771  *    request at least til the first timeout to complete its 3-way handshake.
4772  * 3. Maintain tcp_syn_rcvd_timeout as an accurate count of how many
4773  *    requests currently on the queue that has timed out. This will be used
4774  *    as an indicator of whether an attack is under way, so that appropriate
4775  *    actions can be taken. (It's incremented in tcp_timer() and decremented
4776  *    either when eager goes into ESTABLISHED, or gets freed up.)
4777  * 4. The current threshold is - # of timeout > q0len/4 => SYN alert on
4778  *    # of timeout drops back to <= q0len/32 => SYN alert off
4779  */
4780 static boolean_t
4781 tcp_drop_q0(tcp_t *tcp)
4782 {
4783 	tcp_t	*eager;
4784 	mblk_t	*mp;
4785 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4786 
4787 	ASSERT(MUTEX_HELD(&tcp->tcp_eager_lock));
4788 	ASSERT(tcp->tcp_eager_next_q0 != tcp->tcp_eager_prev_q0);
4789 
4790 	/* Pick oldest eager from the list of droppable eagers */
4791 	eager = tcp->tcp_eager_prev_drop_q0;
4792 
4793 	/* If list is empty. return B_FALSE */
4794 	if (eager == tcp) {
4795 		return (B_FALSE);
4796 	}
4797 
4798 	/* If allocated, the mp will be freed in tcp_clean_death_wrapper() */
4799 	if ((mp = allocb(0, BPRI_HI)) == NULL)
4800 		return (B_FALSE);
4801 
4802 	/*
4803 	 * Take this eager out from the list of droppable eagers since we are
4804 	 * going to drop it.
4805 	 */
4806 	MAKE_UNDROPPABLE(eager);
4807 
4808 	if (tcp->tcp_debug) {
4809 		(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
4810 		    "tcp_drop_q0: listen half-open queue (max=%d) overflow"
4811 		    " (%d pending) on %s, drop one", tcps->tcps_conn_req_max_q0,
4812 		    tcp->tcp_conn_req_cnt_q0,
4813 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
4814 	}
4815 
4816 	BUMP_MIB(&tcps->tcps_mib, tcpHalfOpenDrop);
4817 
4818 	/* Put a reference on the conn as we are enqueueing it in the sqeue */
4819 	CONN_INC_REF(eager->tcp_connp);
4820 
4821 	/* Mark the IRE created for this SYN request temporary */
4822 	tcp_ip_ire_mark_advice(eager);
4823 	squeue_fill(eager->tcp_connp->conn_sqp, mp,
4824 	    tcp_clean_death_wrapper, eager->tcp_connp, SQTAG_TCP_DROP_Q0);
4825 
4826 	return (B_TRUE);
4827 }
4828 
4829 int
4830 tcp_conn_create_v6(conn_t *lconnp, conn_t *connp, mblk_t *mp,
4831     tcph_t *tcph, uint_t ipvers, mblk_t *idmp)
4832 {
4833 	tcp_t 		*ltcp = lconnp->conn_tcp;
4834 	tcp_t		*tcp = connp->conn_tcp;
4835 	mblk_t		*tpi_mp;
4836 	ipha_t		*ipha;
4837 	ip6_t		*ip6h;
4838 	sin6_t 		sin6;
4839 	in6_addr_t 	v6dst;
4840 	int		err;
4841 	int		ifindex = 0;
4842 	cred_t		*cr;
4843 	tcp_stack_t	*tcps = tcp->tcp_tcps;
4844 
4845 	if (ipvers == IPV4_VERSION) {
4846 		ipha = (ipha_t *)mp->b_rptr;
4847 
4848 		connp->conn_send = ip_output;
4849 		connp->conn_recv = tcp_input;
4850 
4851 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
4852 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
4853 
4854 		sin6 = sin6_null;
4855 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &sin6.sin6_addr);
4856 		IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &v6dst);
4857 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4858 		sin6.sin6_family = AF_INET6;
4859 		sin6.__sin6_src_id = ip_srcid_find_addr(&v6dst,
4860 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4861 		if (tcp->tcp_recvdstaddr) {
4862 			sin6_t	sin6d;
4863 
4864 			sin6d = sin6_null;
4865 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst,
4866 			    &sin6d.sin6_addr);
4867 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4868 			sin6d.sin6_family = AF_INET;
4869 			tpi_mp = mi_tpi_extconn_ind(NULL,
4870 			    (char *)&sin6d, sizeof (sin6_t),
4871 			    (char *)&tcp,
4872 			    (t_scalar_t)sizeof (intptr_t),
4873 			    (char *)&sin6d, sizeof (sin6_t),
4874 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4875 		} else {
4876 			tpi_mp = mi_tpi_conn_ind(NULL,
4877 			    (char *)&sin6, sizeof (sin6_t),
4878 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4879 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4880 		}
4881 	} else {
4882 		ip6h = (ip6_t *)mp->b_rptr;
4883 
4884 		connp->conn_send = ip_output_v6;
4885 		connp->conn_recv = tcp_input;
4886 
4887 		connp->conn_srcv6 = ip6h->ip6_dst;
4888 		connp->conn_remv6 = ip6h->ip6_src;
4889 
4890 		/* db_cksumstuff is set at ip_fanout_tcp_v6 */
4891 		ifindex = (int)DB_CKSUMSTUFF(mp);
4892 		DB_CKSUMSTUFF(mp) = 0;
4893 
4894 		sin6 = sin6_null;
4895 		sin6.sin6_addr = ip6h->ip6_src;
4896 		sin6.sin6_port = *(uint16_t *)tcph->th_lport;
4897 		sin6.sin6_family = AF_INET6;
4898 		sin6.sin6_flowinfo = ip6h->ip6_vcf & ~IPV6_VERS_AND_FLOW_MASK;
4899 		sin6.__sin6_src_id = ip_srcid_find_addr(&ip6h->ip6_dst,
4900 		    lconnp->conn_zoneid, tcps->tcps_netstack);
4901 
4902 		if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4903 			/* Pass up the scope_id of remote addr */
4904 			sin6.sin6_scope_id = ifindex;
4905 		} else {
4906 			sin6.sin6_scope_id = 0;
4907 		}
4908 		if (tcp->tcp_recvdstaddr) {
4909 			sin6_t	sin6d;
4910 
4911 			sin6d = sin6_null;
4912 			sin6.sin6_addr = ip6h->ip6_dst;
4913 			sin6d.sin6_port = *(uint16_t *)tcph->th_fport;
4914 			sin6d.sin6_family = AF_INET;
4915 			tpi_mp = mi_tpi_extconn_ind(NULL,
4916 			    (char *)&sin6d, sizeof (sin6_t),
4917 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4918 			    (char *)&sin6d, sizeof (sin6_t),
4919 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4920 		} else {
4921 			tpi_mp = mi_tpi_conn_ind(NULL,
4922 			    (char *)&sin6, sizeof (sin6_t),
4923 			    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
4924 			    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
4925 		}
4926 	}
4927 
4928 	if (tpi_mp == NULL)
4929 		return (ENOMEM);
4930 
4931 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
4932 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
4933 	connp->conn_flags |= (IPCL_TCP6|IPCL_EAGER);
4934 	connp->conn_fully_bound = B_FALSE;
4935 
4936 	/* Inherit information from the "parent" */
4937 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
4938 	tcp->tcp_family = ltcp->tcp_family;
4939 	tcp->tcp_wq = ltcp->tcp_wq;
4940 	tcp->tcp_rq = ltcp->tcp_rq;
4941 	tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
4942 	tcp->tcp_detached = B_TRUE;
4943 	if ((err = tcp_init_values(tcp)) != 0) {
4944 		freemsg(tpi_mp);
4945 		return (err);
4946 	}
4947 
4948 	if (ipvers == IPV4_VERSION) {
4949 		if ((err = tcp_header_init_ipv4(tcp)) != 0) {
4950 			freemsg(tpi_mp);
4951 			return (err);
4952 		}
4953 		ASSERT(tcp->tcp_ipha != NULL);
4954 	} else {
4955 		/* ifindex must be already set */
4956 		ASSERT(ifindex != 0);
4957 
4958 		if (ltcp->tcp_bound_if != 0) {
4959 			/*
4960 			 * Set newtcp's bound_if equal to
4961 			 * listener's value. If ifindex is
4962 			 * not the same as ltcp->tcp_bound_if,
4963 			 * it must be a packet for the ipmp group
4964 			 * of interfaces
4965 			 */
4966 			tcp->tcp_bound_if = ltcp->tcp_bound_if;
4967 		} else if (IN6_IS_ADDR_LINKSCOPE(&ip6h->ip6_src)) {
4968 			tcp->tcp_bound_if = ifindex;
4969 		}
4970 
4971 		tcp->tcp_ipv6_recvancillary = ltcp->tcp_ipv6_recvancillary;
4972 		tcp->tcp_recvifindex = 0;
4973 		tcp->tcp_recvhops = 0xffffffffU;
4974 		ASSERT(tcp->tcp_ip6h != NULL);
4975 	}
4976 
4977 	tcp->tcp_lport = ltcp->tcp_lport;
4978 
4979 	if (ltcp->tcp_ipversion == tcp->tcp_ipversion) {
4980 		if (tcp->tcp_iphc_len != ltcp->tcp_iphc_len) {
4981 			/*
4982 			 * Listener had options of some sort; eager inherits.
4983 			 * Free up the eager template and allocate one
4984 			 * of the right size.
4985 			 */
4986 			if (tcp->tcp_hdr_grown) {
4987 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
4988 			} else {
4989 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
4990 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
4991 			}
4992 			tcp->tcp_iphc = kmem_zalloc(ltcp->tcp_iphc_len,
4993 			    KM_NOSLEEP);
4994 			if (tcp->tcp_iphc == NULL) {
4995 				tcp->tcp_iphc_len = 0;
4996 				freemsg(tpi_mp);
4997 				return (ENOMEM);
4998 			}
4999 			tcp->tcp_iphc_len = ltcp->tcp_iphc_len;
5000 			tcp->tcp_hdr_grown = B_TRUE;
5001 		}
5002 		tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5003 		tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5004 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5005 		tcp->tcp_ip6_hops = ltcp->tcp_ip6_hops;
5006 		tcp->tcp_ip6_vcf = ltcp->tcp_ip6_vcf;
5007 
5008 		/*
5009 		 * Copy the IP+TCP header template from listener to eager
5010 		 */
5011 		bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5012 		if (tcp->tcp_ipversion == IPV6_VERSION) {
5013 			if (((ip6i_t *)(tcp->tcp_iphc))->ip6i_nxt ==
5014 			    IPPROTO_RAW) {
5015 				tcp->tcp_ip6h =
5016 				    (ip6_t *)(tcp->tcp_iphc +
5017 				    sizeof (ip6i_t));
5018 			} else {
5019 				tcp->tcp_ip6h =
5020 				    (ip6_t *)(tcp->tcp_iphc);
5021 			}
5022 			tcp->tcp_ipha = NULL;
5023 		} else {
5024 			tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5025 			tcp->tcp_ip6h = NULL;
5026 		}
5027 		tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5028 		    tcp->tcp_ip_hdr_len);
5029 	} else {
5030 		/*
5031 		 * only valid case when ipversion of listener and
5032 		 * eager differ is when listener is IPv6 and
5033 		 * eager is IPv4.
5034 		 * Eager header template has been initialized to the
5035 		 * maximum v4 header sizes, which includes space for
5036 		 * TCP and IP options.
5037 		 */
5038 		ASSERT((ltcp->tcp_ipversion == IPV6_VERSION) &&
5039 		    (tcp->tcp_ipversion == IPV4_VERSION));
5040 		ASSERT(tcp->tcp_iphc_len >=
5041 		    TCP_MAX_COMBINED_HEADER_LENGTH);
5042 		tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5043 		/* copy IP header fields individually */
5044 		tcp->tcp_ipha->ipha_ttl =
5045 		    ltcp->tcp_ip6h->ip6_hops;
5046 		bcopy(ltcp->tcp_tcph->th_lport,
5047 		    tcp->tcp_tcph->th_lport, sizeof (ushort_t));
5048 	}
5049 
5050 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5051 	bcopy(tcp->tcp_tcph->th_fport, &tcp->tcp_fport,
5052 	    sizeof (in_port_t));
5053 
5054 	if (ltcp->tcp_lport == 0) {
5055 		tcp->tcp_lport = *(in_port_t *)tcph->th_fport;
5056 		bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport,
5057 		    sizeof (in_port_t));
5058 	}
5059 
5060 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5061 		ASSERT(ipha != NULL);
5062 		tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5063 		tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5064 
5065 		/* Source routing option copyover (reverse it) */
5066 		if (tcps->tcps_rev_src_routes)
5067 			tcp_opt_reverse(tcp, ipha);
5068 	} else {
5069 		ASSERT(ip6h != NULL);
5070 		tcp->tcp_ip6h->ip6_dst = ip6h->ip6_src;
5071 		tcp->tcp_ip6h->ip6_src = ip6h->ip6_dst;
5072 	}
5073 
5074 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5075 	ASSERT(!tcp->tcp_tconnind_started);
5076 	/*
5077 	 * If the SYN contains a credential, it's a loopback packet; attach
5078 	 * the credential to the TPI message.
5079 	 */
5080 	if ((cr = DB_CRED(idmp)) != NULL) {
5081 		mblk_setcred(tpi_mp, cr);
5082 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5083 	}
5084 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5085 
5086 	/* Inherit the listener's SSL protection state */
5087 
5088 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5089 		kssl_hold_ent(tcp->tcp_kssl_ent);
5090 		tcp->tcp_kssl_pending = B_TRUE;
5091 	}
5092 
5093 	return (0);
5094 }
5095 
5096 
5097 int
5098 tcp_conn_create_v4(conn_t *lconnp, conn_t *connp, ipha_t *ipha,
5099     tcph_t *tcph, mblk_t *idmp)
5100 {
5101 	tcp_t 		*ltcp = lconnp->conn_tcp;
5102 	tcp_t		*tcp = connp->conn_tcp;
5103 	sin_t		sin;
5104 	mblk_t		*tpi_mp = NULL;
5105 	int		err;
5106 	cred_t		*cr;
5107 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5108 
5109 	sin = sin_null;
5110 	sin.sin_addr.s_addr = ipha->ipha_src;
5111 	sin.sin_port = *(uint16_t *)tcph->th_lport;
5112 	sin.sin_family = AF_INET;
5113 	if (ltcp->tcp_recvdstaddr) {
5114 		sin_t	sind;
5115 
5116 		sind = sin_null;
5117 		sind.sin_addr.s_addr = ipha->ipha_dst;
5118 		sind.sin_port = *(uint16_t *)tcph->th_fport;
5119 		sind.sin_family = AF_INET;
5120 		tpi_mp = mi_tpi_extconn_ind(NULL,
5121 		    (char *)&sind, sizeof (sin_t), (char *)&tcp,
5122 		    (t_scalar_t)sizeof (intptr_t), (char *)&sind,
5123 		    sizeof (sin_t), (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5124 	} else {
5125 		tpi_mp = mi_tpi_conn_ind(NULL,
5126 		    (char *)&sin, sizeof (sin_t),
5127 		    (char *)&tcp, (t_scalar_t)sizeof (intptr_t),
5128 		    (t_scalar_t)ltcp->tcp_conn_req_seqnum);
5129 	}
5130 
5131 	if (tpi_mp == NULL) {
5132 		return (ENOMEM);
5133 	}
5134 
5135 	connp->conn_flags |= (IPCL_TCP4|IPCL_EAGER);
5136 	connp->conn_send = ip_output;
5137 	connp->conn_recv = tcp_input;
5138 	connp->conn_fully_bound = B_FALSE;
5139 
5140 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &connp->conn_srcv6);
5141 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &connp->conn_remv6);
5142 	connp->conn_fport = *(uint16_t *)tcph->th_lport;
5143 	connp->conn_lport = *(uint16_t *)tcph->th_fport;
5144 
5145 	/* Inherit information from the "parent" */
5146 	tcp->tcp_ipversion = ltcp->tcp_ipversion;
5147 	tcp->tcp_family = ltcp->tcp_family;
5148 	tcp->tcp_wq = ltcp->tcp_wq;
5149 	tcp->tcp_rq = ltcp->tcp_rq;
5150 	tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
5151 	tcp->tcp_detached = B_TRUE;
5152 	if ((err = tcp_init_values(tcp)) != 0) {
5153 		freemsg(tpi_mp);
5154 		return (err);
5155 	}
5156 
5157 	/*
5158 	 * Let's make sure that eager tcp template has enough space to
5159 	 * copy IPv4 listener's tcp template. Since the conn_t structure is
5160 	 * preserved and tcp_iphc_len is also preserved, an eager conn_t may
5161 	 * have a tcp_template of total len TCP_MAX_COMBINED_HEADER_LENGTH or
5162 	 * more (in case of re-allocation of conn_t with tcp-IPv6 template with
5163 	 * extension headers or with ip6i_t struct). Note that bcopy() below
5164 	 * copies listener tcp's hdr_len which cannot be greater than TCP_MAX_
5165 	 * COMBINED_HEADER_LENGTH as this listener must be a IPv4 listener.
5166 	 */
5167 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
5168 	ASSERT(ltcp->tcp_hdr_len <= TCP_MAX_COMBINED_HEADER_LENGTH);
5169 
5170 	tcp->tcp_hdr_len = ltcp->tcp_hdr_len;
5171 	tcp->tcp_ip_hdr_len = ltcp->tcp_ip_hdr_len;
5172 	tcp->tcp_tcp_hdr_len = ltcp->tcp_tcp_hdr_len;
5173 	tcp->tcp_ttl = ltcp->tcp_ttl;
5174 	tcp->tcp_tos = ltcp->tcp_tos;
5175 
5176 	/* Copy the IP+TCP header template from listener to eager */
5177 	bcopy(ltcp->tcp_iphc, tcp->tcp_iphc, ltcp->tcp_hdr_len);
5178 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
5179 	tcp->tcp_ip6h = NULL;
5180 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc +
5181 	    tcp->tcp_ip_hdr_len);
5182 
5183 	/* Initialize the IP addresses and Ports */
5184 	tcp->tcp_ipha->ipha_dst = ipha->ipha_src;
5185 	tcp->tcp_ipha->ipha_src = ipha->ipha_dst;
5186 	bcopy(tcph->th_lport, tcp->tcp_tcph->th_fport, sizeof (in_port_t));
5187 	bcopy(tcph->th_fport, tcp->tcp_tcph->th_lport, sizeof (in_port_t));
5188 
5189 	/* Source routing option copyover (reverse it) */
5190 	if (tcps->tcps_rev_src_routes)
5191 		tcp_opt_reverse(tcp, ipha);
5192 
5193 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
5194 	ASSERT(!tcp->tcp_tconnind_started);
5195 
5196 	/*
5197 	 * If the SYN contains a credential, it's a loopback packet; attach
5198 	 * the credential to the TPI message.
5199 	 */
5200 	if ((cr = DB_CRED(idmp)) != NULL) {
5201 		mblk_setcred(tpi_mp, cr);
5202 		DB_CPID(tpi_mp) = DB_CPID(idmp);
5203 	}
5204 	tcp->tcp_conn.tcp_eager_conn_ind = tpi_mp;
5205 
5206 	/* Inherit the listener's SSL protection state */
5207 	if ((tcp->tcp_kssl_ent = ltcp->tcp_kssl_ent) != NULL) {
5208 		kssl_hold_ent(tcp->tcp_kssl_ent);
5209 		tcp->tcp_kssl_pending = B_TRUE;
5210 	}
5211 
5212 	return (0);
5213 }
5214 
5215 /*
5216  * sets up conn for ipsec.
5217  * if the first mblk is M_CTL it is consumed and mpp is updated.
5218  * in case of error mpp is freed.
5219  */
5220 conn_t *
5221 tcp_get_ipsec_conn(tcp_t *tcp, squeue_t *sqp, mblk_t **mpp)
5222 {
5223 	conn_t 		*connp = tcp->tcp_connp;
5224 	conn_t 		*econnp;
5225 	squeue_t 	*new_sqp;
5226 	mblk_t 		*first_mp = *mpp;
5227 	mblk_t		*mp = *mpp;
5228 	boolean_t	mctl_present = B_FALSE;
5229 	uint_t		ipvers;
5230 
5231 	econnp = tcp_get_conn(sqp, tcp->tcp_tcps);
5232 	if (econnp == NULL) {
5233 		freemsg(first_mp);
5234 		return (NULL);
5235 	}
5236 	if (DB_TYPE(mp) == M_CTL) {
5237 		if (mp->b_cont == NULL ||
5238 		    mp->b_cont->b_datap->db_type != M_DATA) {
5239 			freemsg(first_mp);
5240 			return (NULL);
5241 		}
5242 		mp = mp->b_cont;
5243 		if ((mp->b_datap->db_struioflag & STRUIO_EAGER) == 0) {
5244 			freemsg(first_mp);
5245 			return (NULL);
5246 		}
5247 
5248 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5249 		first_mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5250 		mctl_present = B_TRUE;
5251 	} else {
5252 		ASSERT(mp->b_datap->db_struioflag & STRUIO_POLICY);
5253 		mp->b_datap->db_struioflag &= ~STRUIO_POLICY;
5254 	}
5255 
5256 	new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5257 	DB_CKSUMSTART(mp) = 0;
5258 
5259 	ASSERT(OK_32PTR(mp->b_rptr));
5260 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5261 	if (ipvers == IPV4_VERSION) {
5262 		uint16_t  	*up;
5263 		uint32_t	ports;
5264 		ipha_t		*ipha;
5265 
5266 		ipha = (ipha_t *)mp->b_rptr;
5267 		up = (uint16_t *)((uchar_t *)ipha +
5268 		    IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET);
5269 		ports = *(uint32_t *)up;
5270 		IPCL_TCP_EAGER_INIT(econnp, IPPROTO_TCP,
5271 		    ipha->ipha_dst, ipha->ipha_src, ports);
5272 	} else {
5273 		uint16_t  	*up;
5274 		uint32_t	ports;
5275 		uint16_t	ip_hdr_len;
5276 		uint8_t		*nexthdrp;
5277 		ip6_t 		*ip6h;
5278 		tcph_t		*tcph;
5279 
5280 		ip6h = (ip6_t *)mp->b_rptr;
5281 		if (ip6h->ip6_nxt == IPPROTO_TCP) {
5282 			ip_hdr_len = IPV6_HDR_LEN;
5283 		} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ip_hdr_len,
5284 		    &nexthdrp) || *nexthdrp != IPPROTO_TCP) {
5285 			CONN_DEC_REF(econnp);
5286 			freemsg(first_mp);
5287 			return (NULL);
5288 		}
5289 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5290 		up = (uint16_t *)tcph->th_lport;
5291 		ports = *(uint32_t *)up;
5292 		IPCL_TCP_EAGER_INIT_V6(econnp, IPPROTO_TCP,
5293 		    ip6h->ip6_dst, ip6h->ip6_src, ports);
5294 	}
5295 
5296 	/*
5297 	 * The caller already ensured that there is a sqp present.
5298 	 */
5299 	econnp->conn_sqp = new_sqp;
5300 
5301 	if (connp->conn_policy != NULL) {
5302 		ipsec_in_t *ii;
5303 		ii = (ipsec_in_t *)(first_mp->b_rptr);
5304 		ASSERT(ii->ipsec_in_policy == NULL);
5305 		IPPH_REFHOLD(connp->conn_policy);
5306 		ii->ipsec_in_policy = connp->conn_policy;
5307 
5308 		first_mp->b_datap->db_type = IPSEC_POLICY_SET;
5309 		if (!ip_bind_ipsec_policy_set(econnp, first_mp)) {
5310 			CONN_DEC_REF(econnp);
5311 			freemsg(first_mp);
5312 			return (NULL);
5313 		}
5314 	}
5315 
5316 	if (ipsec_conn_cache_policy(econnp, ipvers == IPV4_VERSION) != 0) {
5317 		CONN_DEC_REF(econnp);
5318 		freemsg(first_mp);
5319 		return (NULL);
5320 	}
5321 
5322 	/*
5323 	 * If we know we have some policy, pass the "IPSEC"
5324 	 * options size TCP uses this adjust the MSS.
5325 	 */
5326 	econnp->conn_tcp->tcp_ipsec_overhead = conn_ipsec_length(econnp);
5327 	if (mctl_present) {
5328 		freeb(first_mp);
5329 		*mpp = mp;
5330 	}
5331 
5332 	return (econnp);
5333 }
5334 
5335 /*
5336  * tcp_get_conn/tcp_free_conn
5337  *
5338  * tcp_get_conn is used to get a clean tcp connection structure.
5339  * It tries to reuse the connections put on the freelist by the
5340  * time_wait_collector failing which it goes to kmem_cache. This
5341  * way has two benefits compared to just allocating from and
5342  * freeing to kmem_cache.
5343  * 1) The time_wait_collector can free (which includes the cleanup)
5344  * outside the squeue. So when the interrupt comes, we have a clean
5345  * connection sitting in the freelist. Obviously, this buys us
5346  * performance.
5347  *
5348  * 2) Defence against DOS attack. Allocating a tcp/conn in tcp_conn_request
5349  * has multiple disadvantages - tying up the squeue during alloc, and the
5350  * fact that IPSec policy initialization has to happen here which
5351  * requires us sending a M_CTL and checking for it i.e. real ugliness.
5352  * But allocating the conn/tcp in IP land is also not the best since
5353  * we can't check the 'q' and 'q0' which are protected by squeue and
5354  * blindly allocate memory which might have to be freed here if we are
5355  * not allowed to accept the connection. By using the freelist and
5356  * putting the conn/tcp back in freelist, we don't pay a penalty for
5357  * allocating memory without checking 'q/q0' and freeing it if we can't
5358  * accept the connection.
5359  *
5360  * Care should be taken to put the conn back in the same squeue's freelist
5361  * from which it was allocated. Best results are obtained if conn is
5362  * allocated from listener's squeue and freed to the same. Time wait
5363  * collector will free up the freelist is the connection ends up sitting
5364  * there for too long.
5365  */
5366 void *
5367 tcp_get_conn(void *arg, tcp_stack_t *tcps)
5368 {
5369 	tcp_t			*tcp = NULL;
5370 	conn_t			*connp = NULL;
5371 	squeue_t		*sqp = (squeue_t *)arg;
5372 	tcp_squeue_priv_t 	*tcp_time_wait;
5373 	netstack_t		*ns;
5374 
5375 	tcp_time_wait =
5376 	    *((tcp_squeue_priv_t **)squeue_getprivate(sqp, SQPRIVATE_TCP));
5377 
5378 	mutex_enter(&tcp_time_wait->tcp_time_wait_lock);
5379 	tcp = tcp_time_wait->tcp_free_list;
5380 	ASSERT((tcp != NULL) ^ (tcp_time_wait->tcp_free_list_cnt == 0));
5381 	if (tcp != NULL) {
5382 		tcp_time_wait->tcp_free_list = tcp->tcp_time_wait_next;
5383 		tcp_time_wait->tcp_free_list_cnt--;
5384 		mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5385 		tcp->tcp_time_wait_next = NULL;
5386 		connp = tcp->tcp_connp;
5387 		connp->conn_flags |= IPCL_REUSED;
5388 
5389 		ASSERT(tcp->tcp_tcps == NULL);
5390 		ASSERT(connp->conn_netstack == NULL);
5391 		ASSERT(tcp->tcp_rsrv_mp != NULL);
5392 		ns = tcps->tcps_netstack;
5393 		netstack_hold(ns);
5394 		connp->conn_netstack = ns;
5395 		tcp->tcp_tcps = tcps;
5396 		TCPS_REFHOLD(tcps);
5397 		ipcl_globalhash_insert(connp);
5398 		return ((void *)connp);
5399 	}
5400 	mutex_exit(&tcp_time_wait->tcp_time_wait_lock);
5401 	if ((connp = ipcl_conn_create(IPCL_TCPCONN, KM_NOSLEEP,
5402 	    tcps->tcps_netstack)) == NULL)
5403 		return (NULL);
5404 	tcp = connp->conn_tcp;
5405 	/*
5406 	 * Pre-allocate the tcp_rsrv_mp.  This mblk will not be freed
5407 	 * until this conn_t/tcp_t is freed at ipcl_conn_destroy().
5408 	 */
5409 	if ((tcp->tcp_rsrv_mp = allocb(0, BPRI_HI)) == NULL) {
5410 		ipcl_conn_destroy(connp);
5411 		return (NULL);
5412 	}
5413 	mutex_init(&tcp->tcp_rsrv_mp_lock, NULL, MUTEX_DEFAULT, NULL);
5414 	tcp->tcp_tcps = tcps;
5415 	TCPS_REFHOLD(tcps);
5416 
5417 	return ((void *)connp);
5418 }
5419 
5420 /*
5421  * Update the cached label for the given tcp_t.  This should be called once per
5422  * connection, and before any packets are sent or tcp_process_options is
5423  * invoked.  Returns B_FALSE if the correct label could not be constructed.
5424  */
5425 static boolean_t
5426 tcp_update_label(tcp_t *tcp, const cred_t *cr)
5427 {
5428 	conn_t *connp = tcp->tcp_connp;
5429 
5430 	if (tcp->tcp_ipversion == IPV4_VERSION) {
5431 		uchar_t optbuf[IP_MAX_OPT_LENGTH];
5432 		int added;
5433 
5434 		if (tsol_compute_label(cr, tcp->tcp_remote, optbuf,
5435 		    connp->conn_mac_exempt,
5436 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5437 			return (B_FALSE);
5438 
5439 		added = tsol_remove_secopt(tcp->tcp_ipha, tcp->tcp_hdr_len);
5440 		if (added == -1)
5441 			return (B_FALSE);
5442 		tcp->tcp_hdr_len += added;
5443 		tcp->tcp_tcph = (tcph_t *)((uchar_t *)tcp->tcp_tcph + added);
5444 		tcp->tcp_ip_hdr_len += added;
5445 		if ((tcp->tcp_label_len = optbuf[IPOPT_OLEN]) != 0) {
5446 			tcp->tcp_label_len = (tcp->tcp_label_len + 3) & ~3;
5447 			added = tsol_prepend_option(optbuf, tcp->tcp_ipha,
5448 			    tcp->tcp_hdr_len);
5449 			if (added == -1)
5450 				return (B_FALSE);
5451 			tcp->tcp_hdr_len += added;
5452 			tcp->tcp_tcph = (tcph_t *)
5453 			    ((uchar_t *)tcp->tcp_tcph + added);
5454 			tcp->tcp_ip_hdr_len += added;
5455 		}
5456 	} else {
5457 		uchar_t optbuf[TSOL_MAX_IPV6_OPTION];
5458 
5459 		if (tsol_compute_label_v6(cr, &tcp->tcp_remote_v6, optbuf,
5460 		    connp->conn_mac_exempt,
5461 		    tcp->tcp_tcps->tcps_netstack->netstack_ip) != 0)
5462 			return (B_FALSE);
5463 		if (tsol_update_sticky(&tcp->tcp_sticky_ipp,
5464 		    &tcp->tcp_label_len, optbuf) != 0)
5465 			return (B_FALSE);
5466 		if (tcp_build_hdrs(tcp->tcp_rq, tcp) != 0)
5467 			return (B_FALSE);
5468 	}
5469 
5470 	connp->conn_ulp_labeled = 1;
5471 
5472 	return (B_TRUE);
5473 }
5474 
5475 /* BEGIN CSTYLED */
5476 /*
5477  *
5478  * The sockfs ACCEPT path:
5479  * =======================
5480  *
5481  * The eager is now established in its own perimeter as soon as SYN is
5482  * received in tcp_conn_request(). When sockfs receives conn_ind, it
5483  * completes the accept processing on the acceptor STREAM. The sending
5484  * of conn_ind part is common for both sockfs listener and a TLI/XTI
5485  * listener but a TLI/XTI listener completes the accept processing
5486  * on the listener perimeter.
5487  *
5488  * Common control flow for 3 way handshake:
5489  * ----------------------------------------
5490  *
5491  * incoming SYN (listener perimeter) 	-> tcp_rput_data()
5492  *					-> tcp_conn_request()
5493  *
5494  * incoming SYN-ACK-ACK (eager perim) 	-> tcp_rput_data()
5495  * send T_CONN_IND (listener perim)	-> tcp_send_conn_ind()
5496  *
5497  * Sockfs ACCEPT Path:
5498  * -------------------
5499  *
5500  * open acceptor stream (tcp_open allocates tcp_wput_accept()
5501  * as STREAM entry point)
5502  *
5503  * soaccept() sends T_CONN_RES on the acceptor STREAM to tcp_wput_accept()
5504  *
5505  * tcp_wput_accept() extracts the eager and makes the q->q_ptr <-> eager
5506  * association (we are not behind eager's squeue but sockfs is protecting us
5507  * and no one knows about this stream yet. The STREAMS entry point q->q_info
5508  * is changed to point at tcp_wput().
5509  *
5510  * tcp_wput_accept() sends any deferred eagers via tcp_send_pending() to
5511  * listener (done on listener's perimeter).
5512  *
5513  * tcp_wput_accept() calls tcp_accept_finish() on eagers perimeter to finish
5514  * accept.
5515  *
5516  * TLI/XTI client ACCEPT path:
5517  * ---------------------------
5518  *
5519  * soaccept() sends T_CONN_RES on the listener STREAM.
5520  *
5521  * tcp_accept() -> tcp_accept_swap() complete the processing and send
5522  * the bind_mp to eager perimeter to finish accept (tcp_rput_other()).
5523  *
5524  * Locks:
5525  * ======
5526  *
5527  * listener->tcp_eager_lock protects the listeners->tcp_eager_next_q0 and
5528  * and listeners->tcp_eager_next_q.
5529  *
5530  * Referencing:
5531  * ============
5532  *
5533  * 1) We start out in tcp_conn_request by eager placing a ref on
5534  * listener and listener adding eager to listeners->tcp_eager_next_q0.
5535  *
5536  * 2) When a SYN-ACK-ACK arrives, we send the conn_ind to listener. Before
5537  * doing so we place a ref on the eager. This ref is finally dropped at the
5538  * end of tcp_accept_finish() while unwinding from the squeue, i.e. the
5539  * reference is dropped by the squeue framework.
5540  *
5541  * 3) The ref on listener placed in 1 above is dropped in tcp_accept_finish
5542  *
5543  * The reference must be released by the same entity that added the reference
5544  * In the above scheme, the eager is the entity that adds and releases the
5545  * references. Note that tcp_accept_finish executes in the squeue of the eager
5546  * (albeit after it is attached to the acceptor stream). Though 1. executes
5547  * in the listener's squeue, the eager is nascent at this point and the
5548  * reference can be considered to have been added on behalf of the eager.
5549  *
5550  * Eager getting a Reset or listener closing:
5551  * ==========================================
5552  *
5553  * Once the listener and eager are linked, the listener never does the unlink.
5554  * If the listener needs to close, tcp_eager_cleanup() is called which queues
5555  * a message on all eager perimeter. The eager then does the unlink, clears
5556  * any pointers to the listener's queue and drops the reference to the
5557  * listener. The listener waits in tcp_close outside the squeue until its
5558  * refcount has dropped to 1. This ensures that the listener has waited for
5559  * all eagers to clear their association with the listener.
5560  *
5561  * Similarly, if eager decides to go away, it can unlink itself and close.
5562  * When the T_CONN_RES comes down, we check if eager has closed. Note that
5563  * the reference to eager is still valid because of the extra ref we put
5564  * in tcp_send_conn_ind.
5565  *
5566  * Listener can always locate the eager under the protection
5567  * of the listener->tcp_eager_lock, and then do a refhold
5568  * on the eager during the accept processing.
5569  *
5570  * The acceptor stream accesses the eager in the accept processing
5571  * based on the ref placed on eager before sending T_conn_ind.
5572  * The only entity that can negate this refhold is a listener close
5573  * which is mutually exclusive with an active acceptor stream.
5574  *
5575  * Eager's reference on the listener
5576  * ===================================
5577  *
5578  * If the accept happens (even on a closed eager) the eager drops its
5579  * reference on the listener at the start of tcp_accept_finish. If the
5580  * eager is killed due to an incoming RST before the T_conn_ind is sent up,
5581  * the reference is dropped in tcp_closei_local. If the listener closes,
5582  * the reference is dropped in tcp_eager_kill. In all cases the reference
5583  * is dropped while executing in the eager's context (squeue).
5584  */
5585 /* END CSTYLED */
5586 
5587 /* Process the SYN packet, mp, directed at the listener 'tcp' */
5588 
5589 /*
5590  * THIS FUNCTION IS DIRECTLY CALLED BY IP VIA SQUEUE FOR SYN.
5591  * tcp_rput_data will not see any SYN packets.
5592  */
5593 /* ARGSUSED */
5594 void
5595 tcp_conn_request(void *arg, mblk_t *mp, void *arg2)
5596 {
5597 	tcph_t		*tcph;
5598 	uint32_t	seg_seq;
5599 	tcp_t		*eager;
5600 	uint_t		ipvers;
5601 	ipha_t		*ipha;
5602 	ip6_t		*ip6h;
5603 	int		err;
5604 	conn_t		*econnp = NULL;
5605 	squeue_t	*new_sqp;
5606 	mblk_t		*mp1;
5607 	uint_t 		ip_hdr_len;
5608 	conn_t		*connp = (conn_t *)arg;
5609 	tcp_t		*tcp = connp->conn_tcp;
5610 	cred_t		*credp;
5611 	tcp_stack_t	*tcps = tcp->tcp_tcps;
5612 	ip_stack_t	*ipst;
5613 
5614 	if (tcp->tcp_state != TCPS_LISTEN)
5615 		goto error2;
5616 
5617 	ASSERT((tcp->tcp_connp->conn_flags & IPCL_BOUND) != 0);
5618 
5619 	mutex_enter(&tcp->tcp_eager_lock);
5620 	if (tcp->tcp_conn_req_cnt_q >= tcp->tcp_conn_req_max) {
5621 		mutex_exit(&tcp->tcp_eager_lock);
5622 		TCP_STAT(tcps, tcp_listendrop);
5623 		BUMP_MIB(&tcps->tcps_mib, tcpListenDrop);
5624 		if (tcp->tcp_debug) {
5625 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
5626 			    "tcp_conn_request: listen backlog (max=%d) "
5627 			    "overflow (%d pending) on %s",
5628 			    tcp->tcp_conn_req_max, tcp->tcp_conn_req_cnt_q,
5629 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
5630 		}
5631 		goto error2;
5632 	}
5633 
5634 	if (tcp->tcp_conn_req_cnt_q0 >=
5635 	    tcp->tcp_conn_req_max + tcps->tcps_conn_req_max_q0) {
5636 		/*
5637 		 * Q0 is full. Drop a pending half-open req from the queue
5638 		 * to make room for the new SYN req. Also mark the time we
5639 		 * drop a SYN.
5640 		 *
5641 		 * A more aggressive defense against SYN attack will
5642 		 * be to set the "tcp_syn_defense" flag now.
5643 		 */
5644 		TCP_STAT(tcps, tcp_listendropq0);
5645 		tcp->tcp_last_rcv_lbolt = lbolt64;
5646 		if (!tcp_drop_q0(tcp)) {
5647 			mutex_exit(&tcp->tcp_eager_lock);
5648 			BUMP_MIB(&tcps->tcps_mib, tcpListenDropQ0);
5649 			if (tcp->tcp_debug) {
5650 				(void) strlog(TCP_MOD_ID, 0, 3, SL_TRACE,
5651 				    "tcp_conn_request: listen half-open queue "
5652 				    "(max=%d) full (%d pending) on %s",
5653 				    tcps->tcps_conn_req_max_q0,
5654 				    tcp->tcp_conn_req_cnt_q0,
5655 				    tcp_display(tcp, NULL,
5656 				    DISP_PORT_ONLY));
5657 			}
5658 			goto error2;
5659 		}
5660 	}
5661 	mutex_exit(&tcp->tcp_eager_lock);
5662 
5663 	/*
5664 	 * IP adds STRUIO_EAGER and ensures that the received packet is
5665 	 * M_DATA even if conn_ipv6_recvpktinfo is enabled or for ip6
5666 	 * link local address.  If IPSec is enabled, db_struioflag has
5667 	 * STRUIO_POLICY set (mutually exclusive from STRUIO_EAGER);
5668 	 * otherwise an error case if neither of them is set.
5669 	 */
5670 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
5671 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
5672 		DB_CKSUMSTART(mp) = 0;
5673 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
5674 		econnp = (conn_t *)tcp_get_conn(arg2, tcps);
5675 		if (econnp == NULL)
5676 			goto error2;
5677 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5678 		econnp->conn_sqp = new_sqp;
5679 	} else if ((mp->b_datap->db_struioflag & STRUIO_POLICY) != 0) {
5680 		/*
5681 		 * mp is updated in tcp_get_ipsec_conn().
5682 		 */
5683 		econnp = tcp_get_ipsec_conn(tcp, arg2, &mp);
5684 		if (econnp == NULL) {
5685 			/*
5686 			 * mp freed by tcp_get_ipsec_conn.
5687 			 */
5688 			return;
5689 		}
5690 		ASSERT(econnp->conn_netstack == connp->conn_netstack);
5691 	} else {
5692 		goto error2;
5693 	}
5694 
5695 	ASSERT(DB_TYPE(mp) == M_DATA);
5696 
5697 	ipvers = IPH_HDR_VERSION(mp->b_rptr);
5698 	ASSERT(ipvers == IPV6_VERSION || ipvers == IPV4_VERSION);
5699 	ASSERT(OK_32PTR(mp->b_rptr));
5700 	if (ipvers == IPV4_VERSION) {
5701 		ipha = (ipha_t *)mp->b_rptr;
5702 		ip_hdr_len = IPH_HDR_LENGTH(ipha);
5703 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5704 	} else {
5705 		ip6h = (ip6_t *)mp->b_rptr;
5706 		ip_hdr_len = ip_hdr_length_v6(mp, ip6h);
5707 		tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
5708 	}
5709 
5710 	if (tcp->tcp_family == AF_INET) {
5711 		ASSERT(ipvers == IPV4_VERSION);
5712 		err = tcp_conn_create_v4(connp, econnp, ipha, tcph, mp);
5713 	} else {
5714 		err = tcp_conn_create_v6(connp, econnp, mp, tcph, ipvers, mp);
5715 	}
5716 
5717 	if (err)
5718 		goto error3;
5719 
5720 	eager = econnp->conn_tcp;
5721 
5722 	/*
5723 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
5724 	 * will always have that to send up.  Otherwise, we need to do
5725 	 * special handling in case the allocation fails at that time.
5726 	 */
5727 	ASSERT(eager->tcp_ordrel_mp == NULL);
5728 	if ((eager->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL)
5729 		goto error3;
5730 
5731 	/* Inherit various TCP parameters from the listener */
5732 	eager->tcp_naglim = tcp->tcp_naglim;
5733 	eager->tcp_first_timer_threshold =
5734 	    tcp->tcp_first_timer_threshold;
5735 	eager->tcp_second_timer_threshold =
5736 	    tcp->tcp_second_timer_threshold;
5737 
5738 	eager->tcp_first_ctimer_threshold =
5739 	    tcp->tcp_first_ctimer_threshold;
5740 	eager->tcp_second_ctimer_threshold =
5741 	    tcp->tcp_second_ctimer_threshold;
5742 
5743 	/*
5744 	 * tcp_adapt_ire() may change tcp_rwnd according to the ire metrics.
5745 	 * If it does not, the eager's receive window will be set to the
5746 	 * listener's receive window later in this function.
5747 	 */
5748 	eager->tcp_rwnd = 0;
5749 
5750 	/*
5751 	 * Inherit listener's tcp_init_cwnd.  Need to do this before
5752 	 * calling tcp_process_options() where tcp_mss_set() is called
5753 	 * to set the initial cwnd.
5754 	 */
5755 	eager->tcp_init_cwnd = tcp->tcp_init_cwnd;
5756 
5757 	/*
5758 	 * Zones: tcp_adapt_ire() and tcp_send_data() both need the
5759 	 * zone id before the accept is completed in tcp_wput_accept().
5760 	 */
5761 	econnp->conn_zoneid = connp->conn_zoneid;
5762 	econnp->conn_allzones = connp->conn_allzones;
5763 
5764 	/* Copy nexthop information from listener to eager */
5765 	if (connp->conn_nexthop_set) {
5766 		econnp->conn_nexthop_set = connp->conn_nexthop_set;
5767 		econnp->conn_nexthop_v4 = connp->conn_nexthop_v4;
5768 	}
5769 
5770 	/*
5771 	 * TSOL: tsol_input_proc() needs the eager's cred before the
5772 	 * eager is accepted
5773 	 */
5774 	econnp->conn_cred = eager->tcp_cred = credp = connp->conn_cred;
5775 	crhold(credp);
5776 
5777 	/*
5778 	 * If the caller has the process-wide flag set, then default to MAC
5779 	 * exempt mode.  This allows read-down to unlabeled hosts.
5780 	 */
5781 	if (getpflags(NET_MAC_AWARE, credp) != 0)
5782 		econnp->conn_mac_exempt = B_TRUE;
5783 
5784 	if (is_system_labeled()) {
5785 		cred_t *cr;
5786 
5787 		if (connp->conn_mlp_type != mlptSingle) {
5788 			cr = econnp->conn_peercred = DB_CRED(mp);
5789 			if (cr != NULL)
5790 				crhold(cr);
5791 			else
5792 				cr = econnp->conn_cred;
5793 			DTRACE_PROBE2(mlp_syn_accept, conn_t *,
5794 			    econnp, cred_t *, cr)
5795 		} else {
5796 			cr = econnp->conn_cred;
5797 			DTRACE_PROBE2(syn_accept, conn_t *,
5798 			    econnp, cred_t *, cr)
5799 		}
5800 
5801 		if (!tcp_update_label(eager, cr)) {
5802 			DTRACE_PROBE3(
5803 			    tx__ip__log__error__connrequest__tcp,
5804 			    char *, "eager connp(1) label on SYN mp(2) failed",
5805 			    conn_t *, econnp, mblk_t *, mp);
5806 			goto error3;
5807 		}
5808 	}
5809 
5810 	eager->tcp_hard_binding = B_TRUE;
5811 
5812 	tcp_bind_hash_insert(&tcps->tcps_bind_fanout[
5813 	    TCP_BIND_HASH(eager->tcp_lport)], eager, 0);
5814 
5815 	CL_INET_CONNECT(eager);
5816 
5817 	/*
5818 	 * No need to check for multicast destination since ip will only pass
5819 	 * up multicasts to those that have expressed interest
5820 	 * TODO: what about rejecting broadcasts?
5821 	 * Also check that source is not a multicast or broadcast address.
5822 	 */
5823 	eager->tcp_state = TCPS_SYN_RCVD;
5824 
5825 
5826 	/*
5827 	 * There should be no ire in the mp as we are being called after
5828 	 * receiving the SYN.
5829 	 */
5830 	ASSERT(tcp_ire_mp(mp) == NULL);
5831 
5832 	/*
5833 	 * Adapt our mss, ttl, ... according to information provided in IRE.
5834 	 */
5835 
5836 	if (tcp_adapt_ire(eager, NULL) == 0) {
5837 		/* Undo the bind_hash_insert */
5838 		tcp_bind_hash_remove(eager);
5839 		goto error3;
5840 	}
5841 
5842 	/* Process all TCP options. */
5843 	tcp_process_options(eager, tcph);
5844 
5845 	/* Is the other end ECN capable? */
5846 	if (tcps->tcps_ecn_permitted >= 1 &&
5847 	    (tcph->th_flags[0] & (TH_ECE|TH_CWR)) == (TH_ECE|TH_CWR)) {
5848 		eager->tcp_ecn_ok = B_TRUE;
5849 	}
5850 
5851 	/*
5852 	 * listener->tcp_rq->q_hiwat should be the default window size or a
5853 	 * window size changed via SO_RCVBUF option.  First round up the
5854 	 * eager's tcp_rwnd to the nearest MSS.  Then find out the window
5855 	 * scale option value if needed.  Call tcp_rwnd_set() to finish the
5856 	 * setting.
5857 	 *
5858 	 * Note if there is a rpipe metric associated with the remote host,
5859 	 * we should not inherit receive window size from listener.
5860 	 */
5861 	eager->tcp_rwnd = MSS_ROUNDUP(
5862 	    (eager->tcp_rwnd == 0 ? tcp->tcp_rq->q_hiwat :
5863 	    eager->tcp_rwnd), eager->tcp_mss);
5864 	if (eager->tcp_snd_ws_ok)
5865 		tcp_set_ws_value(eager);
5866 	/*
5867 	 * Note that this is the only place tcp_rwnd_set() is called for
5868 	 * accepting a connection.  We need to call it here instead of
5869 	 * after the 3-way handshake because we need to tell the other
5870 	 * side our rwnd in the SYN-ACK segment.
5871 	 */
5872 	(void) tcp_rwnd_set(eager, eager->tcp_rwnd);
5873 
5874 	/*
5875 	 * We eliminate the need for sockfs to send down a T_SVR4_OPTMGMT_REQ
5876 	 * via soaccept()->soinheritoptions() which essentially applies
5877 	 * all the listener options to the new STREAM. The options that we
5878 	 * need to take care of are:
5879 	 * SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
5880 	 * SO_USELOOPBACK, SO_OOBINLINE, SO_DGRAM_ERRIND, SO_LINGER,
5881 	 * SO_SNDBUF, SO_RCVBUF.
5882 	 *
5883 	 * SO_RCVBUF:	tcp_rwnd_set() above takes care of it.
5884 	 * SO_SNDBUF:	Set the tcp_xmit_hiwater for the eager. When
5885 	 *		tcp_maxpsz_set() gets called later from
5886 	 *		tcp_accept_finish(), the option takes effect.
5887 	 *
5888 	 */
5889 	/* Set the TCP options */
5890 	eager->tcp_xmit_hiwater = tcp->tcp_xmit_hiwater;
5891 	eager->tcp_dgram_errind = tcp->tcp_dgram_errind;
5892 	eager->tcp_oobinline = tcp->tcp_oobinline;
5893 	eager->tcp_reuseaddr = tcp->tcp_reuseaddr;
5894 	eager->tcp_broadcast = tcp->tcp_broadcast;
5895 	eager->tcp_useloopback = tcp->tcp_useloopback;
5896 	eager->tcp_dontroute = tcp->tcp_dontroute;
5897 	eager->tcp_linger = tcp->tcp_linger;
5898 	eager->tcp_lingertime = tcp->tcp_lingertime;
5899 	if (tcp->tcp_ka_enabled)
5900 		eager->tcp_ka_enabled = 1;
5901 
5902 	/* Set the IP options */
5903 	econnp->conn_broadcast = connp->conn_broadcast;
5904 	econnp->conn_loopback = connp->conn_loopback;
5905 	econnp->conn_dontroute = connp->conn_dontroute;
5906 	econnp->conn_reuseaddr = connp->conn_reuseaddr;
5907 
5908 	/* Put a ref on the listener for the eager. */
5909 	CONN_INC_REF(connp);
5910 	mutex_enter(&tcp->tcp_eager_lock);
5911 	tcp->tcp_eager_next_q0->tcp_eager_prev_q0 = eager;
5912 	eager->tcp_eager_next_q0 = tcp->tcp_eager_next_q0;
5913 	tcp->tcp_eager_next_q0 = eager;
5914 	eager->tcp_eager_prev_q0 = tcp;
5915 
5916 	/* Set tcp_listener before adding it to tcp_conn_fanout */
5917 	eager->tcp_listener = tcp;
5918 	eager->tcp_saved_listener = tcp;
5919 
5920 	/*
5921 	 * Tag this detached tcp vector for later retrieval
5922 	 * by our listener client in tcp_accept().
5923 	 */
5924 	eager->tcp_conn_req_seqnum = tcp->tcp_conn_req_seqnum;
5925 	tcp->tcp_conn_req_cnt_q0++;
5926 	if (++tcp->tcp_conn_req_seqnum == -1) {
5927 		/*
5928 		 * -1 is "special" and defined in TPI as something
5929 		 * that should never be used in T_CONN_IND
5930 		 */
5931 		++tcp->tcp_conn_req_seqnum;
5932 	}
5933 	mutex_exit(&tcp->tcp_eager_lock);
5934 
5935 	if (tcp->tcp_syn_defense) {
5936 		/* Don't drop the SYN that comes from a good IP source */
5937 		ipaddr_t *addr_cache = (ipaddr_t *)(tcp->tcp_ip_addr_cache);
5938 		if (addr_cache != NULL && eager->tcp_remote ==
5939 		    addr_cache[IP_ADDR_CACHE_HASH(eager->tcp_remote)]) {
5940 			eager->tcp_dontdrop = B_TRUE;
5941 		}
5942 	}
5943 
5944 	/*
5945 	 * We need to insert the eager in its own perimeter but as soon
5946 	 * as we do that, we expose the eager to the classifier and
5947 	 * should not touch any field outside the eager's perimeter.
5948 	 * So do all the work necessary before inserting the eager
5949 	 * in its own perimeter. Be optimistic that ipcl_conn_insert()
5950 	 * will succeed but undo everything if it fails.
5951 	 */
5952 	seg_seq = ABE32_TO_U32(tcph->th_seq);
5953 	eager->tcp_irs = seg_seq;
5954 	eager->tcp_rack = seg_seq;
5955 	eager->tcp_rnxt = seg_seq + 1;
5956 	U32_TO_ABE32(eager->tcp_rnxt, eager->tcp_tcph->th_ack);
5957 	BUMP_MIB(&tcps->tcps_mib, tcpPassiveOpens);
5958 	eager->tcp_state = TCPS_SYN_RCVD;
5959 	mp1 = tcp_xmit_mp(eager, eager->tcp_xmit_head, eager->tcp_mss,
5960 	    NULL, NULL, eager->tcp_iss, B_FALSE, NULL, B_FALSE);
5961 	if (mp1 == NULL) {
5962 		/*
5963 		 * Increment the ref count as we are going to
5964 		 * enqueueing an mp in squeue
5965 		 */
5966 		CONN_INC_REF(econnp);
5967 		goto error;
5968 	}
5969 	DB_CPID(mp1) = tcp->tcp_cpid;
5970 	eager->tcp_cpid = tcp->tcp_cpid;
5971 	eager->tcp_open_time = lbolt64;
5972 
5973 	/*
5974 	 * We need to start the rto timer. In normal case, we start
5975 	 * the timer after sending the packet on the wire (or at
5976 	 * least believing that packet was sent by waiting for
5977 	 * CALL_IP_WPUT() to return). Since this is the first packet
5978 	 * being sent on the wire for the eager, our initial tcp_rto
5979 	 * is at least tcp_rexmit_interval_min which is a fairly
5980 	 * large value to allow the algorithm to adjust slowly to large
5981 	 * fluctuations of RTT during first few transmissions.
5982 	 *
5983 	 * Starting the timer first and then sending the packet in this
5984 	 * case shouldn't make much difference since tcp_rexmit_interval_min
5985 	 * is of the order of several 100ms and starting the timer
5986 	 * first and then sending the packet will result in difference
5987 	 * of few micro seconds.
5988 	 *
5989 	 * Without this optimization, we are forced to hold the fanout
5990 	 * lock across the ipcl_bind_insert() and sending the packet
5991 	 * so that we don't race against an incoming packet (maybe RST)
5992 	 * for this eager.
5993 	 *
5994 	 * It is necessary to acquire an extra reference on the eager
5995 	 * at this point and hold it until after tcp_send_data() to
5996 	 * ensure against an eager close race.
5997 	 */
5998 
5999 	CONN_INC_REF(eager->tcp_connp);
6000 
6001 	TCP_TIMER_RESTART(eager, eager->tcp_rto);
6002 
6003 	/*
6004 	 * Insert the eager in its own perimeter now. We are ready to deal
6005 	 * with any packets on eager.
6006 	 */
6007 	if (eager->tcp_ipversion == IPV4_VERSION) {
6008 		if (ipcl_conn_insert(econnp, IPPROTO_TCP, 0, 0, 0) != 0) {
6009 			goto error;
6010 		}
6011 	} else {
6012 		if (ipcl_conn_insert_v6(econnp, IPPROTO_TCP, 0, 0, 0, 0) != 0) {
6013 			goto error;
6014 		}
6015 	}
6016 
6017 	/* mark conn as fully-bound */
6018 	econnp->conn_fully_bound = B_TRUE;
6019 
6020 	/* Send the SYN-ACK */
6021 	tcp_send_data(eager, eager->tcp_wq, mp1);
6022 	CONN_DEC_REF(eager->tcp_connp);
6023 	freemsg(mp);
6024 
6025 	return;
6026 error:
6027 	freemsg(mp1);
6028 	eager->tcp_closemp_used = B_TRUE;
6029 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
6030 	squeue_fill(econnp->conn_sqp, &eager->tcp_closemp, tcp_eager_kill,
6031 	    econnp, SQTAG_TCP_CONN_REQ_2);
6032 
6033 	/*
6034 	 * If a connection already exists, send the mp to that connections so
6035 	 * that it can be appropriately dealt with.
6036 	 */
6037 	ipst = tcps->tcps_netstack->netstack_ip;
6038 
6039 	if ((econnp = ipcl_classify(mp, connp->conn_zoneid, ipst)) != NULL) {
6040 		if (!IPCL_IS_CONNECTED(econnp)) {
6041 			/*
6042 			 * Something bad happened. ipcl_conn_insert()
6043 			 * failed because a connection already existed
6044 			 * in connected hash but we can't find it
6045 			 * anymore (someone blew it away). Just
6046 			 * free this message and hopefully remote
6047 			 * will retransmit at which time the SYN can be
6048 			 * treated as a new connection or dealth with
6049 			 * a TH_RST if a connection already exists.
6050 			 */
6051 			CONN_DEC_REF(econnp);
6052 			freemsg(mp);
6053 		} else {
6054 			squeue_fill(econnp->conn_sqp, mp, tcp_input,
6055 			    econnp, SQTAG_TCP_CONN_REQ_1);
6056 		}
6057 	} else {
6058 		/* Nobody wants this packet */
6059 		freemsg(mp);
6060 	}
6061 	return;
6062 error3:
6063 	CONN_DEC_REF(econnp);
6064 error2:
6065 	freemsg(mp);
6066 }
6067 
6068 /*
6069  * In an ideal case of vertical partition in NUMA architecture, its
6070  * beneficial to have the listener and all the incoming connections
6071  * tied to the same squeue. The other constraint is that incoming
6072  * connections should be tied to the squeue attached to interrupted
6073  * CPU for obvious locality reason so this leaves the listener to
6074  * be tied to the same squeue. Our only problem is that when listener
6075  * is binding, the CPU that will get interrupted by the NIC whose
6076  * IP address the listener is binding to is not even known. So
6077  * the code below allows us to change that binding at the time the
6078  * CPU is interrupted by virtue of incoming connection's squeue.
6079  *
6080  * This is usefull only in case of a listener bound to a specific IP
6081  * address. For other kind of listeners, they get bound the
6082  * very first time and there is no attempt to rebind them.
6083  */
6084 void
6085 tcp_conn_request_unbound(void *arg, mblk_t *mp, void *arg2)
6086 {
6087 	conn_t		*connp = (conn_t *)arg;
6088 	squeue_t	*sqp = (squeue_t *)arg2;
6089 	squeue_t	*new_sqp;
6090 	uint32_t	conn_flags;
6091 
6092 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
6093 		new_sqp = (squeue_t *)DB_CKSUMSTART(mp);
6094 	} else {
6095 		goto done;
6096 	}
6097 
6098 	if (connp->conn_fanout == NULL)
6099 		goto done;
6100 
6101 	if (!(connp->conn_flags & IPCL_FULLY_BOUND)) {
6102 		mutex_enter(&connp->conn_fanout->connf_lock);
6103 		mutex_enter(&connp->conn_lock);
6104 		/*
6105 		 * No one from read or write side can access us now
6106 		 * except for already queued packets on this squeue.
6107 		 * But since we haven't changed the squeue yet, they
6108 		 * can't execute. If they are processed after we have
6109 		 * changed the squeue, they are sent back to the
6110 		 * correct squeue down below.
6111 		 * But a listner close can race with processing of
6112 		 * incoming SYN. If incoming SYN processing changes
6113 		 * the squeue then the listener close which is waiting
6114 		 * to enter the squeue would operate on the wrong
6115 		 * squeue. Hence we don't change the squeue here unless
6116 		 * the refcount is exactly the minimum refcount. The
6117 		 * minimum refcount of 4 is counted as - 1 each for
6118 		 * TCP and IP, 1 for being in the classifier hash, and
6119 		 * 1 for the mblk being processed.
6120 		 */
6121 
6122 		if (connp->conn_ref != 4 ||
6123 		    connp->conn_tcp->tcp_state != TCPS_LISTEN) {
6124 			mutex_exit(&connp->conn_lock);
6125 			mutex_exit(&connp->conn_fanout->connf_lock);
6126 			goto done;
6127 		}
6128 		if (connp->conn_sqp != new_sqp) {
6129 			while (connp->conn_sqp != new_sqp)
6130 				(void) casptr(&connp->conn_sqp, sqp, new_sqp);
6131 		}
6132 
6133 		do {
6134 			conn_flags = connp->conn_flags;
6135 			conn_flags |= IPCL_FULLY_BOUND;
6136 			(void) cas32(&connp->conn_flags, connp->conn_flags,
6137 			    conn_flags);
6138 		} while (!(connp->conn_flags & IPCL_FULLY_BOUND));
6139 
6140 		mutex_exit(&connp->conn_fanout->connf_lock);
6141 		mutex_exit(&connp->conn_lock);
6142 	}
6143 
6144 done:
6145 	if (connp->conn_sqp != sqp) {
6146 		CONN_INC_REF(connp);
6147 		squeue_fill(connp->conn_sqp, mp,
6148 		    connp->conn_recv, connp, SQTAG_TCP_CONN_REQ_UNBOUND);
6149 	} else {
6150 		tcp_conn_request(connp, mp, sqp);
6151 	}
6152 }
6153 
6154 /*
6155  * Successful connect request processing begins when our client passes
6156  * a T_CONN_REQ message into tcp_wput() and ends when tcp_rput() passes
6157  * our T_OK_ACK reply message upstream.  The control flow looks like this:
6158  *   upstream -> tcp_wput() -> tcp_wput_proto() -> tcp_connect() -> IP
6159  *   upstream <- tcp_rput()                <- IP
6160  * After various error checks are completed, tcp_connect() lays
6161  * the target address and port into the composite header template,
6162  * preallocates the T_OK_ACK reply message, construct a full 12 byte bind
6163  * request followed by an IRE request, and passes the three mblk message
6164  * down to IP looking like this:
6165  *   O_T_BIND_REQ for IP  --> IRE req --> T_OK_ACK for our client
6166  * Processing continues in tcp_rput() when we receive the following message:
6167  *   T_BIND_ACK from IP --> IRE ack --> T_OK_ACK for our client
6168  * After consuming the first two mblks, tcp_rput() calls tcp_timer(),
6169  * to fire off the connection request, and then passes the T_OK_ACK mblk
6170  * upstream that we filled in below.  There are, of course, numerous
6171  * error conditions along the way which truncate the processing described
6172  * above.
6173  */
6174 static void
6175 tcp_connect(tcp_t *tcp, mblk_t *mp)
6176 {
6177 	sin_t		*sin;
6178 	sin6_t		*sin6;
6179 	queue_t		*q = tcp->tcp_wq;
6180 	struct T_conn_req	*tcr;
6181 	ipaddr_t	*dstaddrp;
6182 	in_port_t	dstport;
6183 	uint_t		srcid;
6184 
6185 	tcr = (struct T_conn_req *)mp->b_rptr;
6186 
6187 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6188 	if ((mp->b_wptr - mp->b_rptr) < sizeof (*tcr)) {
6189 		tcp_err_ack(tcp, mp, TPROTO, 0);
6190 		return;
6191 	}
6192 
6193 	/*
6194 	 * Pre-allocate the T_ordrel_ind mblk so that at close time, we
6195 	 * will always have that to send up.  Otherwise, we need to do
6196 	 * special handling in case the allocation fails at that time.
6197 	 */
6198 	ASSERT(tcp->tcp_ordrel_mp == NULL);
6199 	if ((tcp->tcp_ordrel_mp = mi_tpi_ordrel_ind()) == NULL) {
6200 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6201 		return;
6202 	}
6203 
6204 	/*
6205 	 * Determine packet type based on type of address passed in
6206 	 * the request should contain an IPv4 or IPv6 address.
6207 	 * Make sure that address family matches the type of
6208 	 * family of the the address passed down
6209 	 */
6210 	switch (tcr->DEST_length) {
6211 	default:
6212 		tcp_err_ack(tcp, mp, TBADADDR, 0);
6213 		return;
6214 
6215 	case (sizeof (sin_t) - sizeof (sin->sin_zero)): {
6216 		/*
6217 		 * XXX: The check for valid DEST_length was not there
6218 		 * in earlier releases and some buggy
6219 		 * TLI apps (e.g Sybase) got away with not feeding
6220 		 * in sin_zero part of address.
6221 		 * We allow that bug to keep those buggy apps humming.
6222 		 * Test suites require the check on DEST_length.
6223 		 * We construct a new mblk with valid DEST_length
6224 		 * free the original so the rest of the code does
6225 		 * not have to keep track of this special shorter
6226 		 * length address case.
6227 		 */
6228 		mblk_t *nmp;
6229 		struct T_conn_req *ntcr;
6230 		sin_t *nsin;
6231 
6232 		nmp = allocb(sizeof (struct T_conn_req) + sizeof (sin_t) +
6233 		    tcr->OPT_length, BPRI_HI);
6234 		if (nmp == NULL) {
6235 			tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
6236 			return;
6237 		}
6238 		ntcr = (struct T_conn_req *)nmp->b_rptr;
6239 		bzero(ntcr, sizeof (struct T_conn_req)); /* zero fill */
6240 		ntcr->PRIM_type = T_CONN_REQ;
6241 		ntcr->DEST_length = sizeof (sin_t);
6242 		ntcr->DEST_offset = sizeof (struct T_conn_req);
6243 
6244 		nsin = (sin_t *)((uchar_t *)ntcr + ntcr->DEST_offset);
6245 		*nsin = sin_null;
6246 		/* Get pointer to shorter address to copy from original mp */
6247 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6248 		    tcr->DEST_length); /* extract DEST_length worth of sin_t */
6249 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6250 			freemsg(nmp);
6251 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6252 			return;
6253 		}
6254 		nsin->sin_family = sin->sin_family;
6255 		nsin->sin_port = sin->sin_port;
6256 		nsin->sin_addr = sin->sin_addr;
6257 		/* Note:nsin->sin_zero zero-fill with sin_null assign above */
6258 		nmp->b_wptr = (uchar_t *)&nsin[1];
6259 		if (tcr->OPT_length != 0) {
6260 			ntcr->OPT_length = tcr->OPT_length;
6261 			ntcr->OPT_offset = nmp->b_wptr - nmp->b_rptr;
6262 			bcopy((uchar_t *)tcr + tcr->OPT_offset,
6263 			    (uchar_t *)ntcr + ntcr->OPT_offset,
6264 			    tcr->OPT_length);
6265 			nmp->b_wptr += tcr->OPT_length;
6266 		}
6267 		freemsg(mp);	/* original mp freed */
6268 		mp = nmp;	/* re-initialize original variables */
6269 		tcr = ntcr;
6270 	}
6271 	/* FALLTHRU */
6272 
6273 	case sizeof (sin_t):
6274 		sin = (sin_t *)mi_offset_param(mp, tcr->DEST_offset,
6275 		    sizeof (sin_t));
6276 		if (sin == NULL || !OK_32PTR((char *)sin)) {
6277 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6278 			return;
6279 		}
6280 		if (tcp->tcp_family != AF_INET ||
6281 		    sin->sin_family != AF_INET) {
6282 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6283 			return;
6284 		}
6285 		if (sin->sin_port == 0) {
6286 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6287 			return;
6288 		}
6289 		if (tcp->tcp_connp && tcp->tcp_connp->conn_ipv6_v6only) {
6290 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6291 			return;
6292 		}
6293 
6294 		break;
6295 
6296 	case sizeof (sin6_t):
6297 		sin6 = (sin6_t *)mi_offset_param(mp, tcr->DEST_offset,
6298 		    sizeof (sin6_t));
6299 		if (sin6 == NULL || !OK_32PTR((char *)sin6)) {
6300 			tcp_err_ack(tcp, mp, TSYSERR, EINVAL);
6301 			return;
6302 		}
6303 		if (tcp->tcp_family != AF_INET6 ||
6304 		    sin6->sin6_family != AF_INET6) {
6305 			tcp_err_ack(tcp, mp, TSYSERR, EAFNOSUPPORT);
6306 			return;
6307 		}
6308 		if (sin6->sin6_port == 0) {
6309 			tcp_err_ack(tcp, mp, TBADADDR, 0);
6310 			return;
6311 		}
6312 		break;
6313 	}
6314 	/*
6315 	 * TODO: If someone in TCPS_TIME_WAIT has this dst/port we
6316 	 * should key on their sequence number and cut them loose.
6317 	 */
6318 
6319 	/*
6320 	 * If options passed in, feed it for verification and handling
6321 	 */
6322 	if (tcr->OPT_length != 0) {
6323 		mblk_t	*ok_mp;
6324 		mblk_t	*discon_mp;
6325 		mblk_t  *conn_opts_mp;
6326 		int t_error, sys_error, do_disconnect;
6327 
6328 		conn_opts_mp = NULL;
6329 
6330 		if (tcp_conprim_opt_process(tcp, mp,
6331 		    &do_disconnect, &t_error, &sys_error) < 0) {
6332 			if (do_disconnect) {
6333 				ASSERT(t_error == 0 && sys_error == 0);
6334 				discon_mp = mi_tpi_discon_ind(NULL,
6335 				    ECONNREFUSED, 0);
6336 				if (!discon_mp) {
6337 					tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6338 					    TSYSERR, ENOMEM);
6339 					return;
6340 				}
6341 				ok_mp = mi_tpi_ok_ack_alloc(mp);
6342 				if (!ok_mp) {
6343 					tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6344 					    TSYSERR, ENOMEM);
6345 					return;
6346 				}
6347 				qreply(q, ok_mp);
6348 				qreply(q, discon_mp); /* no flush! */
6349 			} else {
6350 				ASSERT(t_error != 0);
6351 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ, t_error,
6352 				    sys_error);
6353 			}
6354 			return;
6355 		}
6356 		/*
6357 		 * Success in setting options, the mp option buffer represented
6358 		 * by OPT_length/offset has been potentially modified and
6359 		 * contains results of option processing. We copy it in
6360 		 * another mp to save it for potentially influencing returning
6361 		 * it in T_CONN_CONN.
6362 		 */
6363 		if (tcr->OPT_length != 0) { /* there are resulting options */
6364 			conn_opts_mp = copyb(mp);
6365 			if (!conn_opts_mp) {
6366 				tcp_err_ack_prim(tcp, mp, T_CONN_REQ,
6367 				    TSYSERR, ENOMEM);
6368 				return;
6369 			}
6370 			ASSERT(tcp->tcp_conn.tcp_opts_conn_req == NULL);
6371 			tcp->tcp_conn.tcp_opts_conn_req = conn_opts_mp;
6372 			/*
6373 			 * Note:
6374 			 * These resulting option negotiation can include any
6375 			 * end-to-end negotiation options but there no such
6376 			 * thing (yet?) in our TCP/IP.
6377 			 */
6378 		}
6379 	}
6380 
6381 	/*
6382 	 * If we're connecting to an IPv4-mapped IPv6 address, we need to
6383 	 * make sure that the template IP header in the tcp structure is an
6384 	 * IPv4 header, and that the tcp_ipversion is IPV4_VERSION.  We
6385 	 * need to this before we call tcp_bindi() so that the port lookup
6386 	 * code will look for ports in the correct port space (IPv4 and
6387 	 * IPv6 have separate port spaces).
6388 	 */
6389 	if (tcp->tcp_family == AF_INET6 && tcp->tcp_ipversion == IPV6_VERSION &&
6390 	    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6391 		int err = 0;
6392 
6393 		err = tcp_header_init_ipv4(tcp);
6394 		if (err != 0) {
6395 			mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6396 			goto connect_failed;
6397 		}
6398 		if (tcp->tcp_lport != 0)
6399 			*(uint16_t *)tcp->tcp_tcph->th_lport = tcp->tcp_lport;
6400 	}
6401 
6402 	if (tcp->tcp_issocket) {
6403 		/*
6404 		 * TCP is _D_SODIRECT and sockfs is directly above so save
6405 		 * the shared sonode sodirect_t pointer (if any) to enable
6406 		 * TCP sodirect.
6407 		 */
6408 		tcp->tcp_sodirect = SOD_QTOSODP(tcp->tcp_rq);
6409 	}
6410 
6411 	switch (tcp->tcp_state) {
6412 	case TCPS_IDLE:
6413 		/*
6414 		 * We support quick connect, refer to comments in
6415 		 * tcp_connect_*()
6416 		 */
6417 		/* FALLTHRU */
6418 	case TCPS_BOUND:
6419 	case TCPS_LISTEN:
6420 		if (tcp->tcp_family == AF_INET6) {
6421 			if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
6422 				tcp_connect_ipv6(tcp, mp,
6423 				    &sin6->sin6_addr,
6424 				    sin6->sin6_port, sin6->sin6_flowinfo,
6425 				    sin6->__sin6_src_id, sin6->sin6_scope_id);
6426 				return;
6427 			}
6428 			/*
6429 			 * Destination adress is mapped IPv6 address.
6430 			 * Source bound address should be unspecified or
6431 			 * IPv6 mapped address as well.
6432 			 */
6433 			if (!IN6_IS_ADDR_UNSPECIFIED(
6434 			    &tcp->tcp_bound_source_v6) &&
6435 			    !IN6_IS_ADDR_V4MAPPED(&tcp->tcp_bound_source_v6)) {
6436 				mp = mi_tpi_err_ack_alloc(mp, TSYSERR,
6437 				    EADDRNOTAVAIL);
6438 				break;
6439 			}
6440 			dstaddrp = &V4_PART_OF_V6((sin6->sin6_addr));
6441 			dstport = sin6->sin6_port;
6442 			srcid = sin6->__sin6_src_id;
6443 		} else {
6444 			dstaddrp = &sin->sin_addr.s_addr;
6445 			dstport = sin->sin_port;
6446 			srcid = 0;
6447 		}
6448 
6449 		tcp_connect_ipv4(tcp, mp, dstaddrp, dstport, srcid);
6450 		return;
6451 	default:
6452 		mp = mi_tpi_err_ack_alloc(mp, TOUTSTATE, 0);
6453 		break;
6454 	}
6455 	/*
6456 	 * Note: Code below is the "failure" case
6457 	 */
6458 	/* return error ack and blow away saved option results if any */
6459 connect_failed:
6460 	if (mp != NULL)
6461 		putnext(tcp->tcp_rq, mp);
6462 	else {
6463 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6464 		    TSYSERR, ENOMEM);
6465 	}
6466 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6467 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6468 }
6469 
6470 /*
6471  * Handle connect to IPv4 destinations, including connections for AF_INET6
6472  * sockets connecting to IPv4 mapped IPv6 destinations.
6473  */
6474 static void
6475 tcp_connect_ipv4(tcp_t *tcp, mblk_t *mp, ipaddr_t *dstaddrp, in_port_t dstport,
6476     uint_t srcid)
6477 {
6478 	tcph_t	*tcph;
6479 	mblk_t	*mp1;
6480 	ipaddr_t dstaddr = *dstaddrp;
6481 	int32_t	oldstate;
6482 	uint16_t lport;
6483 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6484 
6485 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
6486 
6487 	/* Check for attempt to connect to INADDR_ANY */
6488 	if (dstaddr == INADDR_ANY)  {
6489 		/*
6490 		 * SunOS 4.x and 4.3 BSD allow an application
6491 		 * to connect a TCP socket to INADDR_ANY.
6492 		 * When they do this, the kernel picks the
6493 		 * address of one interface and uses it
6494 		 * instead.  The kernel usually ends up
6495 		 * picking the address of the loopback
6496 		 * interface.  This is an undocumented feature.
6497 		 * However, we provide the same thing here
6498 		 * in order to have source and binary
6499 		 * compatibility with SunOS 4.x.
6500 		 * Update the T_CONN_REQ (sin/sin6) since it is used to
6501 		 * generate the T_CONN_CON.
6502 		 */
6503 		dstaddr = htonl(INADDR_LOOPBACK);
6504 		*dstaddrp = dstaddr;
6505 	}
6506 
6507 	/* Handle __sin6_src_id if socket not bound to an IP address */
6508 	if (srcid != 0 && tcp->tcp_ipha->ipha_src == INADDR_ANY) {
6509 		ip_srcid_find_id(srcid, &tcp->tcp_ip_src_v6,
6510 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6511 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_ip_src_v6,
6512 		    tcp->tcp_ipha->ipha_src);
6513 	}
6514 
6515 	/*
6516 	 * Don't let an endpoint connect to itself.  Note that
6517 	 * the test here does not catch the case where the
6518 	 * source IP addr was left unspecified by the user. In
6519 	 * this case, the source addr is set in tcp_adapt_ire()
6520 	 * using the reply to the T_BIND message that we send
6521 	 * down to IP here and the check is repeated in tcp_rput_other.
6522 	 */
6523 	if (dstaddr == tcp->tcp_ipha->ipha_src &&
6524 	    dstport == tcp->tcp_lport) {
6525 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6526 		goto failed;
6527 	}
6528 
6529 	tcp->tcp_ipha->ipha_dst = dstaddr;
6530 	IN6_IPADDR_TO_V4MAPPED(dstaddr, &tcp->tcp_remote_v6);
6531 
6532 	/*
6533 	 * Massage a source route if any putting the first hop
6534 	 * in iph_dst. Compute a starting value for the checksum which
6535 	 * takes into account that the original iph_dst should be
6536 	 * included in the checksum but that ip will include the
6537 	 * first hop in the source route in the tcp checksum.
6538 	 */
6539 	tcp->tcp_sum = ip_massage_options(tcp->tcp_ipha, tcps->tcps_netstack);
6540 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6541 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
6542 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
6543 	if ((int)tcp->tcp_sum < 0)
6544 		tcp->tcp_sum--;
6545 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
6546 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6547 	    (tcp->tcp_sum >> 16));
6548 	tcph = tcp->tcp_tcph;
6549 	*(uint16_t *)tcph->th_fport = dstport;
6550 	tcp->tcp_fport = dstport;
6551 
6552 	oldstate = tcp->tcp_state;
6553 	/*
6554 	 * At this point the remote destination address and remote port fields
6555 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6556 	 * have to see which state tcp was in so we can take apropriate action.
6557 	 */
6558 	if (oldstate == TCPS_IDLE) {
6559 		/*
6560 		 * We support a quick connect capability here, allowing
6561 		 * clients to transition directly from IDLE to SYN_SENT
6562 		 * tcp_bindi will pick an unused port, insert the connection
6563 		 * in the bind hash and transition to BOUND state.
6564 		 */
6565 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6566 		    tcp, B_TRUE);
6567 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6568 		    B_FALSE, B_FALSE);
6569 		if (lport == 0) {
6570 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6571 			goto failed;
6572 		}
6573 	}
6574 	tcp->tcp_state = TCPS_SYN_SENT;
6575 
6576 	/*
6577 	 * TODO: allow data with connect requests
6578 	 * by unlinking M_DATA trailers here and
6579 	 * linking them in behind the T_OK_ACK mblk.
6580 	 * The tcp_rput() bind ack handler would then
6581 	 * feed them to tcp_wput_data() rather than call
6582 	 * tcp_timer().
6583 	 */
6584 	mp = mi_tpi_ok_ack_alloc(mp);
6585 	if (!mp) {
6586 		tcp->tcp_state = oldstate;
6587 		goto failed;
6588 	}
6589 	if (tcp->tcp_family == AF_INET) {
6590 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6591 		    sizeof (ipa_conn_t));
6592 	} else {
6593 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ,
6594 		    sizeof (ipa6_conn_t));
6595 	}
6596 	if (mp1) {
6597 		/*
6598 		 * We need to make sure that the conn_recv is set to a non-null
6599 		 * value before we insert the conn_t into the classifier table.
6600 		 * This is to avoid a race with an incoming packet which does
6601 		 * an ipcl_classify().
6602 		 */
6603 		tcp->tcp_connp->conn_recv = tcp_input;
6604 
6605 		/* Hang onto the T_OK_ACK for later. */
6606 		linkb(mp1, mp);
6607 		mblk_setcred(mp1, tcp->tcp_cred);
6608 		if (tcp->tcp_family == AF_INET)
6609 			mp1 = ip_bind_v4(tcp->tcp_wq, mp1, tcp->tcp_connp);
6610 		else {
6611 			mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6612 			    &tcp->tcp_sticky_ipp);
6613 		}
6614 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6615 		tcp->tcp_active_open = 1;
6616 		/*
6617 		 * If the bind cannot complete immediately
6618 		 * IP will arrange to call tcp_rput_other
6619 		 * when the bind completes.
6620 		 */
6621 		if (mp1 != NULL)
6622 			tcp_rput_other(tcp, mp1);
6623 		return;
6624 	}
6625 	/* Error case */
6626 	tcp->tcp_state = oldstate;
6627 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6628 
6629 failed:
6630 	/* return error ack and blow away saved option results if any */
6631 	if (mp != NULL)
6632 		putnext(tcp->tcp_rq, mp);
6633 	else {
6634 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6635 		    TSYSERR, ENOMEM);
6636 	}
6637 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6638 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6639 
6640 }
6641 
6642 /*
6643  * Handle connect to IPv6 destinations.
6644  */
6645 static void
6646 tcp_connect_ipv6(tcp_t *tcp, mblk_t *mp, in6_addr_t *dstaddrp,
6647     in_port_t dstport, uint32_t flowinfo, uint_t srcid, uint32_t scope_id)
6648 {
6649 	tcph_t	*tcph;
6650 	mblk_t	*mp1;
6651 	ip6_rthdr_t *rth;
6652 	int32_t  oldstate;
6653 	uint16_t lport;
6654 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6655 
6656 	ASSERT(tcp->tcp_family == AF_INET6);
6657 
6658 	/*
6659 	 * If we're here, it means that the destination address is a native
6660 	 * IPv6 address.  Return an error if tcp_ipversion is not IPv6.  A
6661 	 * reason why it might not be IPv6 is if the socket was bound to an
6662 	 * IPv4-mapped IPv6 address.
6663 	 */
6664 	if (tcp->tcp_ipversion != IPV6_VERSION) {
6665 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6666 		goto failed;
6667 	}
6668 
6669 	/*
6670 	 * Interpret a zero destination to mean loopback.
6671 	 * Update the T_CONN_REQ (sin/sin6) since it is used to
6672 	 * generate the T_CONN_CON.
6673 	 */
6674 	if (IN6_IS_ADDR_UNSPECIFIED(dstaddrp)) {
6675 		*dstaddrp = ipv6_loopback;
6676 	}
6677 
6678 	/* Handle __sin6_src_id if socket not bound to an IP address */
6679 	if (srcid != 0 && IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip6h->ip6_src)) {
6680 		ip_srcid_find_id(srcid, &tcp->tcp_ip6h->ip6_src,
6681 		    tcp->tcp_connp->conn_zoneid, tcps->tcps_netstack);
6682 		tcp->tcp_ip_src_v6 = tcp->tcp_ip6h->ip6_src;
6683 	}
6684 
6685 	/*
6686 	 * Take care of the scope_id now and add ip6i_t
6687 	 * if ip6i_t is not already allocated through TCP
6688 	 * sticky options. At this point tcp_ip6h does not
6689 	 * have dst info, thus use dstaddrp.
6690 	 */
6691 	if (scope_id != 0 &&
6692 	    IN6_IS_ADDR_LINKSCOPE(dstaddrp)) {
6693 		ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
6694 		ip6i_t  *ip6i;
6695 
6696 		ipp->ipp_ifindex = scope_id;
6697 		ip6i = (ip6i_t *)tcp->tcp_iphc;
6698 
6699 		if ((ipp->ipp_fields & IPPF_HAS_IP6I) &&
6700 		    ip6i != NULL && (ip6i->ip6i_nxt == IPPROTO_RAW)) {
6701 			/* Already allocated */
6702 			ip6i->ip6i_flags |= IP6I_IFINDEX;
6703 			ip6i->ip6i_ifindex = ipp->ipp_ifindex;
6704 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6705 		} else {
6706 			int reterr;
6707 
6708 			ipp->ipp_fields |= IPPF_SCOPE_ID;
6709 			if (ipp->ipp_fields & IPPF_HAS_IP6I)
6710 				ip2dbg(("tcp_connect_v6: SCOPE_ID set\n"));
6711 			reterr = tcp_build_hdrs(tcp->tcp_rq, tcp);
6712 			if (reterr != 0)
6713 				goto failed;
6714 			ip1dbg(("tcp_connect_ipv6: tcp_bld_hdrs returned\n"));
6715 		}
6716 	}
6717 
6718 	/*
6719 	 * Don't let an endpoint connect to itself.  Note that
6720 	 * the test here does not catch the case where the
6721 	 * source IP addr was left unspecified by the user. In
6722 	 * this case, the source addr is set in tcp_adapt_ire()
6723 	 * using the reply to the T_BIND message that we send
6724 	 * down to IP here and the check is repeated in tcp_rput_other.
6725 	 */
6726 	if (IN6_ARE_ADDR_EQUAL(dstaddrp, &tcp->tcp_ip6h->ip6_src) &&
6727 	    (dstport == tcp->tcp_lport)) {
6728 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
6729 		goto failed;
6730 	}
6731 
6732 	tcp->tcp_ip6h->ip6_dst = *dstaddrp;
6733 	tcp->tcp_remote_v6 = *dstaddrp;
6734 	tcp->tcp_ip6h->ip6_vcf =
6735 	    (IPV6_DEFAULT_VERS_AND_FLOW & IPV6_VERS_AND_FLOW_MASK) |
6736 	    (flowinfo & ~IPV6_VERS_AND_FLOW_MASK);
6737 
6738 
6739 	/*
6740 	 * Massage a routing header (if present) putting the first hop
6741 	 * in ip6_dst. Compute a starting value for the checksum which
6742 	 * takes into account that the original ip6_dst should be
6743 	 * included in the checksum but that ip will include the
6744 	 * first hop in the source route in the tcp checksum.
6745 	 */
6746 	rth = ip_find_rthdr_v6(tcp->tcp_ip6h, (uint8_t *)tcp->tcp_tcph);
6747 	if (rth != NULL) {
6748 		tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h, rth,
6749 		    tcps->tcps_netstack);
6750 		tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
6751 		    (tcp->tcp_sum >> 16));
6752 	} else {
6753 		tcp->tcp_sum = 0;
6754 	}
6755 
6756 	tcph = tcp->tcp_tcph;
6757 	*(uint16_t *)tcph->th_fport = dstport;
6758 	tcp->tcp_fport = dstport;
6759 
6760 	oldstate = tcp->tcp_state;
6761 	/*
6762 	 * At this point the remote destination address and remote port fields
6763 	 * in the tcp-four-tuple have been filled in the tcp structure. Now we
6764 	 * have to see which state tcp was in so we can take apropriate action.
6765 	 */
6766 	if (oldstate == TCPS_IDLE) {
6767 		/*
6768 		 * We support a quick connect capability here, allowing
6769 		 * clients to transition directly from IDLE to SYN_SENT
6770 		 * tcp_bindi will pick an unused port, insert the connection
6771 		 * in the bind hash and transition to BOUND state.
6772 		 */
6773 		lport = tcp_update_next_port(tcps->tcps_next_port_to_try,
6774 		    tcp, B_TRUE);
6775 		lport = tcp_bindi(tcp, lport, &tcp->tcp_ip_src_v6, 0, B_TRUE,
6776 		    B_FALSE, B_FALSE);
6777 		if (lport == 0) {
6778 			mp = mi_tpi_err_ack_alloc(mp, TNOADDR, 0);
6779 			goto failed;
6780 		}
6781 	}
6782 	tcp->tcp_state = TCPS_SYN_SENT;
6783 	/*
6784 	 * TODO: allow data with connect requests
6785 	 * by unlinking M_DATA trailers here and
6786 	 * linking them in behind the T_OK_ACK mblk.
6787 	 * The tcp_rput() bind ack handler would then
6788 	 * feed them to tcp_wput_data() rather than call
6789 	 * tcp_timer().
6790 	 */
6791 	mp = mi_tpi_ok_ack_alloc(mp);
6792 	if (!mp) {
6793 		tcp->tcp_state = oldstate;
6794 		goto failed;
6795 	}
6796 	mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, sizeof (ipa6_conn_t));
6797 	if (mp1) {
6798 		/*
6799 		 * We need to make sure that the conn_recv is set to a non-null
6800 		 * value before we insert the conn_t into the classifier table.
6801 		 * This is to avoid a race with an incoming packet which does
6802 		 * an ipcl_classify().
6803 		 */
6804 		tcp->tcp_connp->conn_recv = tcp_input;
6805 
6806 		/* Hang onto the T_OK_ACK for later. */
6807 		linkb(mp1, mp);
6808 		mblk_setcred(mp1, tcp->tcp_cred);
6809 		mp1 = ip_bind_v6(tcp->tcp_wq, mp1, tcp->tcp_connp,
6810 		    &tcp->tcp_sticky_ipp);
6811 		BUMP_MIB(&tcps->tcps_mib, tcpActiveOpens);
6812 		tcp->tcp_active_open = 1;
6813 		/* ip_bind_v6() may return ACK or ERROR */
6814 		if (mp1 != NULL)
6815 			tcp_rput_other(tcp, mp1);
6816 		return;
6817 	}
6818 	/* Error case */
6819 	tcp->tcp_state = oldstate;
6820 	mp = mi_tpi_err_ack_alloc(mp, TSYSERR, ENOMEM);
6821 
6822 failed:
6823 	/* return error ack and blow away saved option results if any */
6824 	if (mp != NULL)
6825 		putnext(tcp->tcp_rq, mp);
6826 	else {
6827 		tcp_err_ack_prim(tcp, NULL, T_CONN_REQ,
6828 		    TSYSERR, ENOMEM);
6829 	}
6830 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
6831 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
6832 }
6833 
6834 /*
6835  * We need a stream q for detached closing tcp connections
6836  * to use.  Our client hereby indicates that this q is the
6837  * one to use.
6838  */
6839 static void
6840 tcp_def_q_set(tcp_t *tcp, mblk_t *mp)
6841 {
6842 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
6843 	queue_t	*q = tcp->tcp_wq;
6844 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6845 
6846 #ifdef NS_DEBUG
6847 	(void) printf("TCP_IOC_DEFAULT_Q for stack %d\n",
6848 	    tcps->tcps_netstack->netstack_stackid);
6849 #endif
6850 	mp->b_datap->db_type = M_IOCACK;
6851 	iocp->ioc_count = 0;
6852 	mutex_enter(&tcps->tcps_g_q_lock);
6853 	if (tcps->tcps_g_q != NULL) {
6854 		mutex_exit(&tcps->tcps_g_q_lock);
6855 		iocp->ioc_error = EALREADY;
6856 	} else {
6857 		mblk_t *mp1;
6858 
6859 		mp1 = tcp_ip_bind_mp(tcp, O_T_BIND_REQ, 0);
6860 		if (mp1 == NULL) {
6861 			mutex_exit(&tcps->tcps_g_q_lock);
6862 			iocp->ioc_error = ENOMEM;
6863 		} else {
6864 			tcps->tcps_g_q = tcp->tcp_rq;
6865 			mutex_exit(&tcps->tcps_g_q_lock);
6866 			iocp->ioc_error = 0;
6867 			iocp->ioc_rval = 0;
6868 			/*
6869 			 * We are passing tcp_sticky_ipp as NULL
6870 			 * as it is not useful for tcp_default queue
6871 			 *
6872 			 * Set conn_recv just in case.
6873 			 */
6874 			tcp->tcp_connp->conn_recv = tcp_conn_request;
6875 
6876 			mp1 = ip_bind_v6(q, mp1, tcp->tcp_connp, NULL);
6877 			if (mp1 != NULL)
6878 				tcp_rput_other(tcp, mp1);
6879 		}
6880 	}
6881 	qreply(q, mp);
6882 }
6883 
6884 /*
6885  * Our client hereby directs us to reject the connection request
6886  * that tcp_conn_request() marked with 'seqnum'.  Rejection consists
6887  * of sending the appropriate RST, not an ICMP error.
6888  */
6889 static void
6890 tcp_disconnect(tcp_t *tcp, mblk_t *mp)
6891 {
6892 	tcp_t	*ltcp = NULL;
6893 	t_scalar_t seqnum;
6894 	conn_t	*connp;
6895 	tcp_stack_t	*tcps = tcp->tcp_tcps;
6896 
6897 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
6898 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_discon_req)) {
6899 		tcp_err_ack(tcp, mp, TPROTO, 0);
6900 		return;
6901 	}
6902 
6903 	/*
6904 	 * Right now, upper modules pass down a T_DISCON_REQ to TCP,
6905 	 * when the stream is in BOUND state. Do not send a reset,
6906 	 * since the destination IP address is not valid, and it can
6907 	 * be the initialized value of all zeros (broadcast address).
6908 	 *
6909 	 * If TCP has sent down a bind request to IP and has not
6910 	 * received the reply, reject the request.  Otherwise, TCP
6911 	 * will be confused.
6912 	 */
6913 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_hard_binding) {
6914 		if (tcp->tcp_debug) {
6915 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
6916 			    "tcp_disconnect: bad state, %d", tcp->tcp_state);
6917 		}
6918 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
6919 		return;
6920 	}
6921 
6922 	seqnum = ((struct T_discon_req *)mp->b_rptr)->SEQ_number;
6923 
6924 	if (seqnum == -1 || tcp->tcp_conn_req_max == 0) {
6925 
6926 		/*
6927 		 * According to TPI, for non-listeners, ignore seqnum
6928 		 * and disconnect.
6929 		 * Following interpretation of -1 seqnum is historical
6930 		 * and implied TPI ? (TPI only states that for T_CONN_IND,
6931 		 * a valid seqnum should not be -1).
6932 		 *
6933 		 *	-1 means disconnect everything
6934 		 *	regardless even on a listener.
6935 		 */
6936 
6937 		int old_state = tcp->tcp_state;
6938 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
6939 
6940 		/*
6941 		 * The connection can't be on the tcp_time_wait_head list
6942 		 * since it is not detached.
6943 		 */
6944 		ASSERT(tcp->tcp_time_wait_next == NULL);
6945 		ASSERT(tcp->tcp_time_wait_prev == NULL);
6946 		ASSERT(tcp->tcp_time_wait_expire == 0);
6947 		ltcp = NULL;
6948 		/*
6949 		 * If it used to be a listener, check to make sure no one else
6950 		 * has taken the port before switching back to LISTEN state.
6951 		 */
6952 		if (tcp->tcp_ipversion == IPV4_VERSION) {
6953 			connp = ipcl_lookup_listener_v4(tcp->tcp_lport,
6954 			    tcp->tcp_ipha->ipha_src,
6955 			    tcp->tcp_connp->conn_zoneid, ipst);
6956 			if (connp != NULL)
6957 				ltcp = connp->conn_tcp;
6958 		} else {
6959 			/* Allow tcp_bound_if listeners? */
6960 			connp = ipcl_lookup_listener_v6(tcp->tcp_lport,
6961 			    &tcp->tcp_ip6h->ip6_src, 0,
6962 			    tcp->tcp_connp->conn_zoneid, ipst);
6963 			if (connp != NULL)
6964 				ltcp = connp->conn_tcp;
6965 		}
6966 		if (tcp->tcp_conn_req_max && ltcp == NULL) {
6967 			tcp->tcp_state = TCPS_LISTEN;
6968 		} else if (old_state > TCPS_BOUND) {
6969 			tcp->tcp_conn_req_max = 0;
6970 			tcp->tcp_state = TCPS_BOUND;
6971 		}
6972 		if (ltcp != NULL)
6973 			CONN_DEC_REF(ltcp->tcp_connp);
6974 		if (old_state == TCPS_SYN_SENT || old_state == TCPS_SYN_RCVD) {
6975 			BUMP_MIB(&tcps->tcps_mib, tcpAttemptFails);
6976 		} else if (old_state == TCPS_ESTABLISHED ||
6977 		    old_state == TCPS_CLOSE_WAIT) {
6978 			BUMP_MIB(&tcps->tcps_mib, tcpEstabResets);
6979 		}
6980 
6981 		if (tcp->tcp_fused)
6982 			tcp_unfuse(tcp);
6983 
6984 		mutex_enter(&tcp->tcp_eager_lock);
6985 		if ((tcp->tcp_conn_req_cnt_q0 != 0) ||
6986 		    (tcp->tcp_conn_req_cnt_q != 0)) {
6987 			tcp_eager_cleanup(tcp, 0);
6988 		}
6989 		mutex_exit(&tcp->tcp_eager_lock);
6990 
6991 		tcp_xmit_ctl("tcp_disconnect", tcp, tcp->tcp_snxt,
6992 		    tcp->tcp_rnxt, TH_RST | TH_ACK);
6993 
6994 		tcp_reinit(tcp);
6995 
6996 		if (old_state >= TCPS_ESTABLISHED) {
6997 			/* Send M_FLUSH according to TPI */
6998 			(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
6999 		}
7000 		mp = mi_tpi_ok_ack_alloc(mp);
7001 		if (mp)
7002 			putnext(tcp->tcp_rq, mp);
7003 		return;
7004 	} else if (!tcp_eager_blowoff(tcp, seqnum)) {
7005 		tcp_err_ack(tcp, mp, TBADSEQ, 0);
7006 		return;
7007 	}
7008 	if (tcp->tcp_state >= TCPS_ESTABLISHED) {
7009 		/* Send M_FLUSH according to TPI */
7010 		(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
7011 	}
7012 	mp = mi_tpi_ok_ack_alloc(mp);
7013 	if (mp)
7014 		putnext(tcp->tcp_rq, mp);
7015 }
7016 
7017 /*
7018  * Diagnostic routine used to return a string associated with the tcp state.
7019  * Note that if the caller does not supply a buffer, it will use an internal
7020  * static string.  This means that if multiple threads call this function at
7021  * the same time, output can be corrupted...  Note also that this function
7022  * does not check the size of the supplied buffer.  The caller has to make
7023  * sure that it is big enough.
7024  */
7025 static char *
7026 tcp_display(tcp_t *tcp, char *sup_buf, char format)
7027 {
7028 	char		buf1[30];
7029 	static char	priv_buf[INET6_ADDRSTRLEN * 2 + 80];
7030 	char		*buf;
7031 	char		*cp;
7032 	in6_addr_t	local, remote;
7033 	char		local_addrbuf[INET6_ADDRSTRLEN];
7034 	char		remote_addrbuf[INET6_ADDRSTRLEN];
7035 
7036 	if (sup_buf != NULL)
7037 		buf = sup_buf;
7038 	else
7039 		buf = priv_buf;
7040 
7041 	if (tcp == NULL)
7042 		return ("NULL_TCP");
7043 	switch (tcp->tcp_state) {
7044 	case TCPS_CLOSED:
7045 		cp = "TCP_CLOSED";
7046 		break;
7047 	case TCPS_IDLE:
7048 		cp = "TCP_IDLE";
7049 		break;
7050 	case TCPS_BOUND:
7051 		cp = "TCP_BOUND";
7052 		break;
7053 	case TCPS_LISTEN:
7054 		cp = "TCP_LISTEN";
7055 		break;
7056 	case TCPS_SYN_SENT:
7057 		cp = "TCP_SYN_SENT";
7058 		break;
7059 	case TCPS_SYN_RCVD:
7060 		cp = "TCP_SYN_RCVD";
7061 		break;
7062 	case TCPS_ESTABLISHED:
7063 		cp = "TCP_ESTABLISHED";
7064 		break;
7065 	case TCPS_CLOSE_WAIT:
7066 		cp = "TCP_CLOSE_WAIT";
7067 		break;
7068 	case TCPS_FIN_WAIT_1:
7069 		cp = "TCP_FIN_WAIT_1";
7070 		break;
7071 	case TCPS_CLOSING:
7072 		cp = "TCP_CLOSING";
7073 		break;
7074 	case TCPS_LAST_ACK:
7075 		cp = "TCP_LAST_ACK";
7076 		break;
7077 	case TCPS_FIN_WAIT_2:
7078 		cp = "TCP_FIN_WAIT_2";
7079 		break;
7080 	case TCPS_TIME_WAIT:
7081 		cp = "TCP_TIME_WAIT";
7082 		break;
7083 	default:
7084 		(void) mi_sprintf(buf1, "TCPUnkState(%d)", tcp->tcp_state);
7085 		cp = buf1;
7086 		break;
7087 	}
7088 	switch (format) {
7089 	case DISP_ADDR_AND_PORT:
7090 		if (tcp->tcp_ipversion == IPV4_VERSION) {
7091 			/*
7092 			 * Note that we use the remote address in the tcp_b
7093 			 * structure.  This means that it will print out
7094 			 * the real destination address, not the next hop's
7095 			 * address if source routing is used.
7096 			 */
7097 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ip_src, &local);
7098 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &remote);
7099 
7100 		} else {
7101 			local = tcp->tcp_ip_src_v6;
7102 			remote = tcp->tcp_remote_v6;
7103 		}
7104 		(void) inet_ntop(AF_INET6, &local, local_addrbuf,
7105 		    sizeof (local_addrbuf));
7106 		(void) inet_ntop(AF_INET6, &remote, remote_addrbuf,
7107 		    sizeof (remote_addrbuf));
7108 		(void) mi_sprintf(buf, "[%s.%u, %s.%u] %s",
7109 		    local_addrbuf, ntohs(tcp->tcp_lport), remote_addrbuf,
7110 		    ntohs(tcp->tcp_fport), cp);
7111 		break;
7112 	case DISP_PORT_ONLY:
7113 	default:
7114 		(void) mi_sprintf(buf, "[%u, %u] %s",
7115 		    ntohs(tcp->tcp_lport), ntohs(tcp->tcp_fport), cp);
7116 		break;
7117 	}
7118 
7119 	return (buf);
7120 }
7121 
7122 /*
7123  * Called via squeue to get on to eager's perimeter. It sends a
7124  * TH_RST if eager is in the fanout table. The listener wants the
7125  * eager to disappear either by means of tcp_eager_blowoff() or
7126  * tcp_eager_cleanup() being called. tcp_eager_kill() can also be
7127  * called (via squeue) if the eager cannot be inserted in the
7128  * fanout table in tcp_conn_request().
7129  */
7130 /* ARGSUSED */
7131 void
7132 tcp_eager_kill(void *arg, mblk_t *mp, void *arg2)
7133 {
7134 	conn_t	*econnp = (conn_t *)arg;
7135 	tcp_t	*eager = econnp->conn_tcp;
7136 	tcp_t	*listener = eager->tcp_listener;
7137 	tcp_stack_t	*tcps = eager->tcp_tcps;
7138 
7139 	/*
7140 	 * We could be called because listener is closing. Since
7141 	 * the eager is using listener's queue's, its not safe.
7142 	 * Better use the default queue just to send the TH_RST
7143 	 * out.
7144 	 */
7145 	ASSERT(tcps->tcps_g_q != NULL);
7146 	eager->tcp_rq = tcps->tcps_g_q;
7147 	eager->tcp_wq = WR(tcps->tcps_g_q);
7148 
7149 	/*
7150 	 * An eager's conn_fanout will be NULL if it's a duplicate
7151 	 * for an existing 4-tuples in the conn fanout table.
7152 	 * We don't want to send an RST out in such case.
7153 	 */
7154 	if (econnp->conn_fanout != NULL && eager->tcp_state > TCPS_LISTEN) {
7155 		tcp_xmit_ctl("tcp_eager_kill, can't wait",
7156 		    eager, eager->tcp_snxt, 0, TH_RST);
7157 	}
7158 
7159 	/* We are here because listener wants this eager gone */
7160 	if (listener != NULL) {
7161 		mutex_enter(&listener->tcp_eager_lock);
7162 		tcp_eager_unlink(eager);
7163 		if (eager->tcp_tconnind_started) {
7164 			/*
7165 			 * The eager has sent a conn_ind up to the
7166 			 * listener but listener decides to close
7167 			 * instead. We need to drop the extra ref
7168 			 * placed on eager in tcp_rput_data() before
7169 			 * sending the conn_ind to listener.
7170 			 */
7171 			CONN_DEC_REF(econnp);
7172 		}
7173 		mutex_exit(&listener->tcp_eager_lock);
7174 		CONN_DEC_REF(listener->tcp_connp);
7175 	}
7176 
7177 	if (eager->tcp_state > TCPS_BOUND)
7178 		tcp_close_detached(eager);
7179 }
7180 
7181 /*
7182  * Reset any eager connection hanging off this listener marked
7183  * with 'seqnum' and then reclaim it's resources.
7184  */
7185 static boolean_t
7186 tcp_eager_blowoff(tcp_t	*listener, t_scalar_t seqnum)
7187 {
7188 	tcp_t	*eager;
7189 	mblk_t 	*mp;
7190 	tcp_stack_t	*tcps = listener->tcp_tcps;
7191 
7192 	TCP_STAT(tcps, tcp_eager_blowoff_calls);
7193 	eager = listener;
7194 	mutex_enter(&listener->tcp_eager_lock);
7195 	do {
7196 		eager = eager->tcp_eager_next_q;
7197 		if (eager == NULL) {
7198 			mutex_exit(&listener->tcp_eager_lock);
7199 			return (B_FALSE);
7200 		}
7201 	} while (eager->tcp_conn_req_seqnum != seqnum);
7202 
7203 	if (eager->tcp_closemp_used) {
7204 		mutex_exit(&listener->tcp_eager_lock);
7205 		return (B_TRUE);
7206 	}
7207 	eager->tcp_closemp_used = B_TRUE;
7208 	TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7209 	CONN_INC_REF(eager->tcp_connp);
7210 	mutex_exit(&listener->tcp_eager_lock);
7211 	mp = &eager->tcp_closemp;
7212 	squeue_fill(eager->tcp_connp->conn_sqp, mp, tcp_eager_kill,
7213 	    eager->tcp_connp, SQTAG_TCP_EAGER_BLOWOFF);
7214 	return (B_TRUE);
7215 }
7216 
7217 /*
7218  * Reset any eager connection hanging off this listener
7219  * and then reclaim it's resources.
7220  */
7221 static void
7222 tcp_eager_cleanup(tcp_t *listener, boolean_t q0_only)
7223 {
7224 	tcp_t	*eager;
7225 	mblk_t	*mp;
7226 	tcp_stack_t	*tcps = listener->tcp_tcps;
7227 
7228 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7229 
7230 	if (!q0_only) {
7231 		/* First cleanup q */
7232 		TCP_STAT(tcps, tcp_eager_blowoff_q);
7233 		eager = listener->tcp_eager_next_q;
7234 		while (eager != NULL) {
7235 			if (!eager->tcp_closemp_used) {
7236 				eager->tcp_closemp_used = B_TRUE;
7237 				TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7238 				CONN_INC_REF(eager->tcp_connp);
7239 				mp = &eager->tcp_closemp;
7240 				squeue_fill(eager->tcp_connp->conn_sqp, mp,
7241 				    tcp_eager_kill, eager->tcp_connp,
7242 				    SQTAG_TCP_EAGER_CLEANUP);
7243 			}
7244 			eager = eager->tcp_eager_next_q;
7245 		}
7246 	}
7247 	/* Then cleanup q0 */
7248 	TCP_STAT(tcps, tcp_eager_blowoff_q0);
7249 	eager = listener->tcp_eager_next_q0;
7250 	while (eager != listener) {
7251 		if (!eager->tcp_closemp_used) {
7252 			eager->tcp_closemp_used = B_TRUE;
7253 			TCP_DEBUG_GETPCSTACK(eager->tcmp_stk, 15);
7254 			CONN_INC_REF(eager->tcp_connp);
7255 			mp = &eager->tcp_closemp;
7256 			squeue_fill(eager->tcp_connp->conn_sqp, mp,
7257 			    tcp_eager_kill, eager->tcp_connp,
7258 			    SQTAG_TCP_EAGER_CLEANUP_Q0);
7259 		}
7260 		eager = eager->tcp_eager_next_q0;
7261 	}
7262 }
7263 
7264 /*
7265  * If we are an eager connection hanging off a listener that hasn't
7266  * formally accepted the connection yet, get off his list and blow off
7267  * any data that we have accumulated.
7268  */
7269 static void
7270 tcp_eager_unlink(tcp_t *tcp)
7271 {
7272 	tcp_t	*listener = tcp->tcp_listener;
7273 
7274 	ASSERT(MUTEX_HELD(&listener->tcp_eager_lock));
7275 	ASSERT(listener != NULL);
7276 	if (tcp->tcp_eager_next_q0 != NULL) {
7277 		ASSERT(tcp->tcp_eager_prev_q0 != NULL);
7278 
7279 		/* Remove the eager tcp from q0 */
7280 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
7281 		    tcp->tcp_eager_prev_q0;
7282 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
7283 		    tcp->tcp_eager_next_q0;
7284 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
7285 		listener->tcp_conn_req_cnt_q0--;
7286 
7287 		tcp->tcp_eager_next_q0 = NULL;
7288 		tcp->tcp_eager_prev_q0 = NULL;
7289 
7290 		/*
7291 		 * Take the eager out, if it is in the list of droppable
7292 		 * eagers.
7293 		 */
7294 		MAKE_UNDROPPABLE(tcp);
7295 
7296 		if (tcp->tcp_syn_rcvd_timeout != 0) {
7297 			/* we have timed out before */
7298 			ASSERT(listener->tcp_syn_rcvd_timeout > 0);
7299 			listener->tcp_syn_rcvd_timeout--;
7300 		}
7301 	} else {
7302 		tcp_t   **tcpp = &listener->tcp_eager_next_q;
7303 		tcp_t	*prev = NULL;
7304 
7305 		for (; tcpp[0]; tcpp = &tcpp[0]->tcp_eager_next_q) {
7306 			if (tcpp[0] == tcp) {
7307 				if (listener->tcp_eager_last_q == tcp) {
7308 					/*
7309 					 * If we are unlinking the last
7310 					 * element on the list, adjust
7311 					 * tail pointer. Set tail pointer
7312 					 * to nil when list is empty.
7313 					 */
7314 					ASSERT(tcp->tcp_eager_next_q == NULL);
7315 					if (listener->tcp_eager_last_q ==
7316 					    listener->tcp_eager_next_q) {
7317 						listener->tcp_eager_last_q =
7318 						    NULL;
7319 					} else {
7320 						/*
7321 						 * We won't get here if there
7322 						 * is only one eager in the
7323 						 * list.
7324 						 */
7325 						ASSERT(prev != NULL);
7326 						listener->tcp_eager_last_q =
7327 						    prev;
7328 					}
7329 				}
7330 				tcpp[0] = tcp->tcp_eager_next_q;
7331 				tcp->tcp_eager_next_q = NULL;
7332 				tcp->tcp_eager_last_q = NULL;
7333 				ASSERT(listener->tcp_conn_req_cnt_q > 0);
7334 				listener->tcp_conn_req_cnt_q--;
7335 				break;
7336 			}
7337 			prev = tcpp[0];
7338 		}
7339 	}
7340 	tcp->tcp_listener = NULL;
7341 }
7342 
7343 /* Shorthand to generate and send TPI error acks to our client */
7344 static void
7345 tcp_err_ack(tcp_t *tcp, mblk_t *mp, int t_error, int sys_error)
7346 {
7347 	if ((mp = mi_tpi_err_ack_alloc(mp, t_error, sys_error)) != NULL)
7348 		putnext(tcp->tcp_rq, mp);
7349 }
7350 
7351 /* Shorthand to generate and send TPI error acks to our client */
7352 static void
7353 tcp_err_ack_prim(tcp_t *tcp, mblk_t *mp, int primitive,
7354     int t_error, int sys_error)
7355 {
7356 	struct T_error_ack	*teackp;
7357 
7358 	if ((mp = tpi_ack_alloc(mp, sizeof (struct T_error_ack),
7359 	    M_PCPROTO, T_ERROR_ACK)) != NULL) {
7360 		teackp = (struct T_error_ack *)mp->b_rptr;
7361 		teackp->ERROR_prim = primitive;
7362 		teackp->TLI_error = t_error;
7363 		teackp->UNIX_error = sys_error;
7364 		putnext(tcp->tcp_rq, mp);
7365 	}
7366 }
7367 
7368 /*
7369  * Note: No locks are held when inspecting tcp_g_*epriv_ports
7370  * but instead the code relies on:
7371  * - the fact that the address of the array and its size never changes
7372  * - the atomic assignment of the elements of the array
7373  */
7374 /* ARGSUSED */
7375 static int
7376 tcp_extra_priv_ports_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
7377 {
7378 	int i;
7379 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7380 
7381 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7382 		if (tcps->tcps_g_epriv_ports[i] != 0)
7383 			(void) mi_mpprintf(mp, "%d ",
7384 			    tcps->tcps_g_epriv_ports[i]);
7385 	}
7386 	return (0);
7387 }
7388 
7389 /*
7390  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7391  * threads from changing it at the same time.
7392  */
7393 /* ARGSUSED */
7394 static int
7395 tcp_extra_priv_ports_add(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7396     cred_t *cr)
7397 {
7398 	long	new_value;
7399 	int	i;
7400 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7401 
7402 	/*
7403 	 * Fail the request if the new value does not lie within the
7404 	 * port number limits.
7405 	 */
7406 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
7407 	    new_value <= 0 || new_value >= 65536) {
7408 		return (EINVAL);
7409 	}
7410 
7411 	mutex_enter(&tcps->tcps_epriv_port_lock);
7412 	/* Check if the value is already in the list */
7413 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7414 		if (new_value == tcps->tcps_g_epriv_ports[i]) {
7415 			mutex_exit(&tcps->tcps_epriv_port_lock);
7416 			return (EEXIST);
7417 		}
7418 	}
7419 	/* Find an empty slot */
7420 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7421 		if (tcps->tcps_g_epriv_ports[i] == 0)
7422 			break;
7423 	}
7424 	if (i == tcps->tcps_g_num_epriv_ports) {
7425 		mutex_exit(&tcps->tcps_epriv_port_lock);
7426 		return (EOVERFLOW);
7427 	}
7428 	/* Set the new value */
7429 	tcps->tcps_g_epriv_ports[i] = (uint16_t)new_value;
7430 	mutex_exit(&tcps->tcps_epriv_port_lock);
7431 	return (0);
7432 }
7433 
7434 /*
7435  * Hold a lock while changing tcp_g_epriv_ports to prevent multiple
7436  * threads from changing it at the same time.
7437  */
7438 /* ARGSUSED */
7439 static int
7440 tcp_extra_priv_ports_del(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
7441     cred_t *cr)
7442 {
7443 	long	new_value;
7444 	int	i;
7445 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
7446 
7447 	/*
7448 	 * Fail the request if the new value does not lie within the
7449 	 * port number limits.
7450 	 */
7451 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 || new_value <= 0 ||
7452 	    new_value >= 65536) {
7453 		return (EINVAL);
7454 	}
7455 
7456 	mutex_enter(&tcps->tcps_epriv_port_lock);
7457 	/* Check that the value is already in the list */
7458 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
7459 		if (tcps->tcps_g_epriv_ports[i] == new_value)
7460 			break;
7461 	}
7462 	if (i == tcps->tcps_g_num_epriv_ports) {
7463 		mutex_exit(&tcps->tcps_epriv_port_lock);
7464 		return (ESRCH);
7465 	}
7466 	/* Clear the value */
7467 	tcps->tcps_g_epriv_ports[i] = 0;
7468 	mutex_exit(&tcps->tcps_epriv_port_lock);
7469 	return (0);
7470 }
7471 
7472 /* Return the TPI/TLI equivalent of our current tcp_state */
7473 static int
7474 tcp_tpistate(tcp_t *tcp)
7475 {
7476 	switch (tcp->tcp_state) {
7477 	case TCPS_IDLE:
7478 		return (TS_UNBND);
7479 	case TCPS_LISTEN:
7480 		/*
7481 		 * Return whether there are outstanding T_CONN_IND waiting
7482 		 * for the matching T_CONN_RES. Therefore don't count q0.
7483 		 */
7484 		if (tcp->tcp_conn_req_cnt_q > 0)
7485 			return (TS_WRES_CIND);
7486 		else
7487 			return (TS_IDLE);
7488 	case TCPS_BOUND:
7489 		return (TS_IDLE);
7490 	case TCPS_SYN_SENT:
7491 		return (TS_WCON_CREQ);
7492 	case TCPS_SYN_RCVD:
7493 		/*
7494 		 * Note: assumption: this has to the active open SYN_RCVD.
7495 		 * The passive instance is detached in SYN_RCVD stage of
7496 		 * incoming connection processing so we cannot get request
7497 		 * for T_info_ack on it.
7498 		 */
7499 		return (TS_WACK_CRES);
7500 	case TCPS_ESTABLISHED:
7501 		return (TS_DATA_XFER);
7502 	case TCPS_CLOSE_WAIT:
7503 		return (TS_WREQ_ORDREL);
7504 	case TCPS_FIN_WAIT_1:
7505 		return (TS_WIND_ORDREL);
7506 	case TCPS_FIN_WAIT_2:
7507 		return (TS_WIND_ORDREL);
7508 
7509 	case TCPS_CLOSING:
7510 	case TCPS_LAST_ACK:
7511 	case TCPS_TIME_WAIT:
7512 	case TCPS_CLOSED:
7513 		/*
7514 		 * Following TS_WACK_DREQ7 is a rendition of "not
7515 		 * yet TS_IDLE" TPI state. There is no best match to any
7516 		 * TPI state for TCPS_{CLOSING, LAST_ACK, TIME_WAIT} but we
7517 		 * choose a value chosen that will map to TLI/XTI level
7518 		 * state of TSTATECHNG (state is process of changing) which
7519 		 * captures what this dummy state represents.
7520 		 */
7521 		return (TS_WACK_DREQ7);
7522 	default:
7523 		cmn_err(CE_WARN, "tcp_tpistate: strange state (%d) %s",
7524 		    tcp->tcp_state, tcp_display(tcp, NULL,
7525 		    DISP_PORT_ONLY));
7526 		return (TS_UNBND);
7527 	}
7528 }
7529 
7530 static void
7531 tcp_copy_info(struct T_info_ack *tia, tcp_t *tcp)
7532 {
7533 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7534 
7535 	if (tcp->tcp_family == AF_INET6)
7536 		*tia = tcp_g_t_info_ack_v6;
7537 	else
7538 		*tia = tcp_g_t_info_ack;
7539 	tia->CURRENT_state = tcp_tpistate(tcp);
7540 	tia->OPT_size = tcp_max_optsize;
7541 	if (tcp->tcp_mss == 0) {
7542 		/* Not yet set - tcp_open does not set mss */
7543 		if (tcp->tcp_ipversion == IPV4_VERSION)
7544 			tia->TIDU_size = tcps->tcps_mss_def_ipv4;
7545 		else
7546 			tia->TIDU_size = tcps->tcps_mss_def_ipv6;
7547 	} else {
7548 		tia->TIDU_size = tcp->tcp_mss;
7549 	}
7550 	/* TODO: Default ETSDU is 1.  Is that correct for tcp? */
7551 }
7552 
7553 /*
7554  * This routine responds to T_CAPABILITY_REQ messages.  It is called by
7555  * tcp_wput.  Much of the T_CAPABILITY_ACK information is copied from
7556  * tcp_g_t_info_ack.  The current state of the stream is copied from
7557  * tcp_state.
7558  */
7559 static void
7560 tcp_capability_req(tcp_t *tcp, mblk_t *mp)
7561 {
7562 	t_uscalar_t		cap_bits1;
7563 	struct T_capability_ack	*tcap;
7564 
7565 	if (MBLKL(mp) < sizeof (struct T_capability_req)) {
7566 		freemsg(mp);
7567 		return;
7568 	}
7569 
7570 	cap_bits1 = ((struct T_capability_req *)mp->b_rptr)->CAP_bits1;
7571 
7572 	mp = tpi_ack_alloc(mp, sizeof (struct T_capability_ack),
7573 	    mp->b_datap->db_type, T_CAPABILITY_ACK);
7574 	if (mp == NULL)
7575 		return;
7576 
7577 	tcap = (struct T_capability_ack *)mp->b_rptr;
7578 	tcap->CAP_bits1 = 0;
7579 
7580 	if (cap_bits1 & TC1_INFO) {
7581 		tcp_copy_info(&tcap->INFO_ack, tcp);
7582 		tcap->CAP_bits1 |= TC1_INFO;
7583 	}
7584 
7585 	if (cap_bits1 & TC1_ACCEPTOR_ID) {
7586 		tcap->ACCEPTOR_id = tcp->tcp_acceptor_id;
7587 		tcap->CAP_bits1 |= TC1_ACCEPTOR_ID;
7588 	}
7589 
7590 	putnext(tcp->tcp_rq, mp);
7591 }
7592 
7593 /*
7594  * This routine responds to T_INFO_REQ messages.  It is called by tcp_wput.
7595  * Most of the T_INFO_ACK information is copied from tcp_g_t_info_ack.
7596  * The current state of the stream is copied from tcp_state.
7597  */
7598 static void
7599 tcp_info_req(tcp_t *tcp, mblk_t *mp)
7600 {
7601 	mp = tpi_ack_alloc(mp, sizeof (struct T_info_ack), M_PCPROTO,
7602 	    T_INFO_ACK);
7603 	if (!mp) {
7604 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7605 		return;
7606 	}
7607 	tcp_copy_info((struct T_info_ack *)mp->b_rptr, tcp);
7608 	putnext(tcp->tcp_rq, mp);
7609 }
7610 
7611 /* Respond to the TPI addr request */
7612 static void
7613 tcp_addr_req(tcp_t *tcp, mblk_t *mp)
7614 {
7615 	sin_t	*sin;
7616 	mblk_t	*ackmp;
7617 	struct T_addr_ack *taa;
7618 
7619 	/* Make it large enough for worst case */
7620 	ackmp = reallocb(mp, sizeof (struct T_addr_ack) +
7621 	    2 * sizeof (sin6_t), 1);
7622 	if (ackmp == NULL) {
7623 		tcp_err_ack(tcp, mp, TSYSERR, ENOMEM);
7624 		return;
7625 	}
7626 
7627 	if (tcp->tcp_ipversion == IPV6_VERSION) {
7628 		tcp_addr_req_ipv6(tcp, ackmp);
7629 		return;
7630 	}
7631 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7632 
7633 	bzero(taa, sizeof (struct T_addr_ack));
7634 	ackmp->b_wptr = (uchar_t *)&taa[1];
7635 
7636 	taa->PRIM_type = T_ADDR_ACK;
7637 	ackmp->b_datap->db_type = M_PCPROTO;
7638 
7639 	/*
7640 	 * Note: Following code assumes 32 bit alignment of basic
7641 	 * data structures like sin_t and struct T_addr_ack.
7642 	 */
7643 	if (tcp->tcp_state >= TCPS_BOUND) {
7644 		/*
7645 		 * Fill in local address
7646 		 */
7647 		taa->LOCADDR_length = sizeof (sin_t);
7648 		taa->LOCADDR_offset = sizeof (*taa);
7649 
7650 		sin = (sin_t *)&taa[1];
7651 
7652 		/* Fill zeroes and then intialize non-zero fields */
7653 		*sin = sin_null;
7654 
7655 		sin->sin_family = AF_INET;
7656 
7657 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
7658 		sin->sin_port = *(uint16_t *)tcp->tcp_tcph->th_lport;
7659 
7660 		ackmp->b_wptr = (uchar_t *)&sin[1];
7661 
7662 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7663 			/*
7664 			 * Fill in Remote address
7665 			 */
7666 			taa->REMADDR_length = sizeof (sin_t);
7667 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7668 			    taa->LOCADDR_length);
7669 
7670 			sin = (sin_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7671 			*sin = sin_null;
7672 			sin->sin_family = AF_INET;
7673 			sin->sin_addr.s_addr = tcp->tcp_remote;
7674 			sin->sin_port = tcp->tcp_fport;
7675 
7676 			ackmp->b_wptr = (uchar_t *)&sin[1];
7677 		}
7678 	}
7679 	putnext(tcp->tcp_rq, ackmp);
7680 }
7681 
7682 /* Assumes that tcp_addr_req gets enough space and alignment */
7683 static void
7684 tcp_addr_req_ipv6(tcp_t *tcp, mblk_t *ackmp)
7685 {
7686 	sin6_t	*sin6;
7687 	struct T_addr_ack *taa;
7688 
7689 	ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
7690 	ASSERT(OK_32PTR(ackmp->b_rptr));
7691 	ASSERT(ackmp->b_wptr - ackmp->b_rptr >= sizeof (struct T_addr_ack) +
7692 	    2 * sizeof (sin6_t));
7693 
7694 	taa = (struct T_addr_ack *)ackmp->b_rptr;
7695 
7696 	bzero(taa, sizeof (struct T_addr_ack));
7697 	ackmp->b_wptr = (uchar_t *)&taa[1];
7698 
7699 	taa->PRIM_type = T_ADDR_ACK;
7700 	ackmp->b_datap->db_type = M_PCPROTO;
7701 
7702 	/*
7703 	 * Note: Following code assumes 32 bit alignment of basic
7704 	 * data structures like sin6_t and struct T_addr_ack.
7705 	 */
7706 	if (tcp->tcp_state >= TCPS_BOUND) {
7707 		/*
7708 		 * Fill in local address
7709 		 */
7710 		taa->LOCADDR_length = sizeof (sin6_t);
7711 		taa->LOCADDR_offset = sizeof (*taa);
7712 
7713 		sin6 = (sin6_t *)&taa[1];
7714 		*sin6 = sin6_null;
7715 
7716 		sin6->sin6_family = AF_INET6;
7717 		sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
7718 		sin6->sin6_port = tcp->tcp_lport;
7719 
7720 		ackmp->b_wptr = (uchar_t *)&sin6[1];
7721 
7722 		if (tcp->tcp_state >= TCPS_SYN_RCVD) {
7723 			/*
7724 			 * Fill in Remote address
7725 			 */
7726 			taa->REMADDR_length = sizeof (sin6_t);
7727 			taa->REMADDR_offset = ROUNDUP32(taa->LOCADDR_offset +
7728 			    taa->LOCADDR_length);
7729 
7730 			sin6 = (sin6_t *)(ackmp->b_rptr + taa->REMADDR_offset);
7731 			*sin6 = sin6_null;
7732 			sin6->sin6_family = AF_INET6;
7733 			sin6->sin6_flowinfo =
7734 			    tcp->tcp_ip6h->ip6_vcf &
7735 			    ~IPV6_VERS_AND_FLOW_MASK;
7736 			sin6->sin6_addr = tcp->tcp_remote_v6;
7737 			sin6->sin6_port = tcp->tcp_fport;
7738 
7739 			ackmp->b_wptr = (uchar_t *)&sin6[1];
7740 		}
7741 	}
7742 	putnext(tcp->tcp_rq, ackmp);
7743 }
7744 
7745 /*
7746  * Handle reinitialization of a tcp structure.
7747  * Maintain "binding state" resetting the state to BOUND, LISTEN, or IDLE.
7748  */
7749 static void
7750 tcp_reinit(tcp_t *tcp)
7751 {
7752 	mblk_t	*mp;
7753 	int 	err;
7754 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7755 
7756 	TCP_STAT(tcps, tcp_reinit_calls);
7757 
7758 	/* tcp_reinit should never be called for detached tcp_t's */
7759 	ASSERT(tcp->tcp_listener == NULL);
7760 	ASSERT((tcp->tcp_family == AF_INET &&
7761 	    tcp->tcp_ipversion == IPV4_VERSION) ||
7762 	    (tcp->tcp_family == AF_INET6 &&
7763 	    (tcp->tcp_ipversion == IPV4_VERSION ||
7764 	    tcp->tcp_ipversion == IPV6_VERSION)));
7765 
7766 	/* Cancel outstanding timers */
7767 	tcp_timers_stop(tcp);
7768 
7769 	/*
7770 	 * Reset everything in the state vector, after updating global
7771 	 * MIB data from instance counters.
7772 	 */
7773 	UPDATE_MIB(&tcps->tcps_mib, tcpHCInSegs, tcp->tcp_ibsegs);
7774 	tcp->tcp_ibsegs = 0;
7775 	UPDATE_MIB(&tcps->tcps_mib, tcpHCOutSegs, tcp->tcp_obsegs);
7776 	tcp->tcp_obsegs = 0;
7777 
7778 	tcp_close_mpp(&tcp->tcp_xmit_head);
7779 	if (tcp->tcp_snd_zcopy_aware)
7780 		tcp_zcopy_notify(tcp);
7781 	tcp->tcp_xmit_last = tcp->tcp_xmit_tail = NULL;
7782 	tcp->tcp_unsent = tcp->tcp_xmit_tail_unsent = 0;
7783 	mutex_enter(&tcp->tcp_non_sq_lock);
7784 	if (tcp->tcp_flow_stopped &&
7785 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
7786 		tcp_clrqfull(tcp);
7787 	}
7788 	mutex_exit(&tcp->tcp_non_sq_lock);
7789 	tcp_close_mpp(&tcp->tcp_reass_head);
7790 	tcp->tcp_reass_tail = NULL;
7791 	if (tcp->tcp_rcv_list != NULL) {
7792 		/* Free b_next chain */
7793 		tcp_close_mpp(&tcp->tcp_rcv_list);
7794 		tcp->tcp_rcv_last_head = NULL;
7795 		tcp->tcp_rcv_last_tail = NULL;
7796 		tcp->tcp_rcv_cnt = 0;
7797 	}
7798 	tcp->tcp_rcv_last_tail = NULL;
7799 
7800 	if ((mp = tcp->tcp_urp_mp) != NULL) {
7801 		freemsg(mp);
7802 		tcp->tcp_urp_mp = NULL;
7803 	}
7804 	if ((mp = tcp->tcp_urp_mark_mp) != NULL) {
7805 		freemsg(mp);
7806 		tcp->tcp_urp_mark_mp = NULL;
7807 	}
7808 	if (tcp->tcp_fused_sigurg_mp != NULL) {
7809 		freeb(tcp->tcp_fused_sigurg_mp);
7810 		tcp->tcp_fused_sigurg_mp = NULL;
7811 	}
7812 	if (tcp->tcp_ordrel_mp != NULL) {
7813 		freeb(tcp->tcp_ordrel_mp);
7814 		tcp->tcp_ordrel_mp = NULL;
7815 	}
7816 
7817 	/*
7818 	 * Following is a union with two members which are
7819 	 * identical types and size so the following cleanup
7820 	 * is enough.
7821 	 */
7822 	tcp_close_mpp(&tcp->tcp_conn.tcp_eager_conn_ind);
7823 
7824 	CL_INET_DISCONNECT(tcp);
7825 
7826 	/*
7827 	 * The connection can't be on the tcp_time_wait_head list
7828 	 * since it is not detached.
7829 	 */
7830 	ASSERT(tcp->tcp_time_wait_next == NULL);
7831 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7832 	ASSERT(tcp->tcp_time_wait_expire == 0);
7833 
7834 	if (tcp->tcp_kssl_pending) {
7835 		tcp->tcp_kssl_pending = B_FALSE;
7836 
7837 		/* Don't reset if the initialized by bind. */
7838 		if (tcp->tcp_kssl_ent != NULL) {
7839 			kssl_release_ent(tcp->tcp_kssl_ent, NULL,
7840 			    KSSL_NO_PROXY);
7841 		}
7842 	}
7843 	if (tcp->tcp_kssl_ctx != NULL) {
7844 		kssl_release_ctx(tcp->tcp_kssl_ctx);
7845 		tcp->tcp_kssl_ctx = NULL;
7846 	}
7847 
7848 	/*
7849 	 * Reset/preserve other values
7850 	 */
7851 	tcp_reinit_values(tcp);
7852 	ipcl_hash_remove(tcp->tcp_connp);
7853 	conn_delete_ire(tcp->tcp_connp, NULL);
7854 	tcp_ipsec_cleanup(tcp);
7855 
7856 	if (tcp->tcp_conn_req_max != 0) {
7857 		/*
7858 		 * This is the case when a TLI program uses the same
7859 		 * transport end point to accept a connection.  This
7860 		 * makes the TCP both a listener and acceptor.  When
7861 		 * this connection is closed, we need to set the state
7862 		 * back to TCPS_LISTEN.  Make sure that the eager list
7863 		 * is reinitialized.
7864 		 *
7865 		 * Note that this stream is still bound to the four
7866 		 * tuples of the previous connection in IP.  If a new
7867 		 * SYN with different foreign address comes in, IP will
7868 		 * not find it and will send it to the global queue.  In
7869 		 * the global queue, TCP will do a tcp_lookup_listener()
7870 		 * to find this stream.  This works because this stream
7871 		 * is only removed from connected hash.
7872 		 *
7873 		 */
7874 		tcp->tcp_state = TCPS_LISTEN;
7875 		tcp->tcp_eager_next_q0 = tcp->tcp_eager_prev_q0 = tcp;
7876 		tcp->tcp_eager_next_drop_q0 = tcp;
7877 		tcp->tcp_eager_prev_drop_q0 = tcp;
7878 		tcp->tcp_connp->conn_recv = tcp_conn_request;
7879 		if (tcp->tcp_family == AF_INET6) {
7880 			ASSERT(tcp->tcp_connp->conn_af_isv6);
7881 			(void) ipcl_bind_insert_v6(tcp->tcp_connp, IPPROTO_TCP,
7882 			    &tcp->tcp_ip6h->ip6_src, tcp->tcp_lport);
7883 		} else {
7884 			ASSERT(!tcp->tcp_connp->conn_af_isv6);
7885 			(void) ipcl_bind_insert(tcp->tcp_connp, IPPROTO_TCP,
7886 			    tcp->tcp_ipha->ipha_src, tcp->tcp_lport);
7887 		}
7888 	} else {
7889 		tcp->tcp_state = TCPS_BOUND;
7890 	}
7891 
7892 	/*
7893 	 * Initialize to default values
7894 	 * Can't fail since enough header template space already allocated
7895 	 * at open().
7896 	 */
7897 	err = tcp_init_values(tcp);
7898 	ASSERT(err == 0);
7899 	/* Restore state in tcp_tcph */
7900 	bcopy(&tcp->tcp_lport, tcp->tcp_tcph->th_lport, TCP_PORT_LEN);
7901 	if (tcp->tcp_ipversion == IPV4_VERSION)
7902 		tcp->tcp_ipha->ipha_src = tcp->tcp_bound_source;
7903 	else
7904 		tcp->tcp_ip6h->ip6_src = tcp->tcp_bound_source_v6;
7905 	/*
7906 	 * Copy of the src addr. in tcp_t is needed in tcp_t
7907 	 * since the lookup funcs can only lookup on tcp_t
7908 	 */
7909 	tcp->tcp_ip_src_v6 = tcp->tcp_bound_source_v6;
7910 
7911 	ASSERT(tcp->tcp_ptpbhn != NULL);
7912 	tcp->tcp_rq->q_hiwat = tcps->tcps_recv_hiwat;
7913 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
7914 	tcp->tcp_mss = tcp->tcp_ipversion != IPV4_VERSION ?
7915 	    tcps->tcps_mss_def_ipv6 : tcps->tcps_mss_def_ipv4;
7916 }
7917 
7918 /*
7919  * Force values to zero that need be zero.
7920  * Do not touch values asociated with the BOUND or LISTEN state
7921  * since the connection will end up in that state after the reinit.
7922  * NOTE: tcp_reinit_values MUST have a line for each field in the tcp_t
7923  * structure!
7924  */
7925 static void
7926 tcp_reinit_values(tcp)
7927 	tcp_t *tcp;
7928 {
7929 	tcp_stack_t	*tcps = tcp->tcp_tcps;
7930 
7931 #ifndef	lint
7932 #define	DONTCARE(x)
7933 #define	PRESERVE(x)
7934 #else
7935 #define	DONTCARE(x)	((x) = (x))
7936 #define	PRESERVE(x)	((x) = (x))
7937 #endif	/* lint */
7938 
7939 	PRESERVE(tcp->tcp_bind_hash);
7940 	PRESERVE(tcp->tcp_ptpbhn);
7941 	PRESERVE(tcp->tcp_acceptor_hash);
7942 	PRESERVE(tcp->tcp_ptpahn);
7943 
7944 	/* Should be ASSERT NULL on these with new code! */
7945 	ASSERT(tcp->tcp_time_wait_next == NULL);
7946 	ASSERT(tcp->tcp_time_wait_prev == NULL);
7947 	ASSERT(tcp->tcp_time_wait_expire == 0);
7948 	PRESERVE(tcp->tcp_state);
7949 	PRESERVE(tcp->tcp_rq);
7950 	PRESERVE(tcp->tcp_wq);
7951 
7952 	ASSERT(tcp->tcp_xmit_head == NULL);
7953 	ASSERT(tcp->tcp_xmit_last == NULL);
7954 	ASSERT(tcp->tcp_unsent == 0);
7955 	ASSERT(tcp->tcp_xmit_tail == NULL);
7956 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
7957 
7958 	tcp->tcp_snxt = 0;			/* Displayed in mib */
7959 	tcp->tcp_suna = 0;			/* Displayed in mib */
7960 	tcp->tcp_swnd = 0;
7961 	DONTCARE(tcp->tcp_cwnd);		/* Init in tcp_mss_set */
7962 
7963 	ASSERT(tcp->tcp_ibsegs == 0);
7964 	ASSERT(tcp->tcp_obsegs == 0);
7965 
7966 	if (tcp->tcp_iphc != NULL) {
7967 		ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
7968 		bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
7969 	}
7970 
7971 	DONTCARE(tcp->tcp_naglim);		/* Init in tcp_init_values */
7972 	DONTCARE(tcp->tcp_hdr_len);		/* Init in tcp_init_values */
7973 	DONTCARE(tcp->tcp_ipha);
7974 	DONTCARE(tcp->tcp_ip6h);
7975 	DONTCARE(tcp->tcp_ip_hdr_len);
7976 	DONTCARE(tcp->tcp_tcph);
7977 	DONTCARE(tcp->tcp_tcp_hdr_len);		/* Init in tcp_init_values */
7978 	tcp->tcp_valid_bits = 0;
7979 
7980 	DONTCARE(tcp->tcp_xmit_hiwater);	/* Init in tcp_init_values */
7981 	DONTCARE(tcp->tcp_timer_backoff);	/* Init in tcp_init_values */
7982 	DONTCARE(tcp->tcp_last_recv_time);	/* Init in tcp_init_values */
7983 	tcp->tcp_last_rcv_lbolt = 0;
7984 
7985 	tcp->tcp_init_cwnd = 0;
7986 
7987 	tcp->tcp_urp_last_valid = 0;
7988 	tcp->tcp_hard_binding = 0;
7989 	tcp->tcp_hard_bound = 0;
7990 	PRESERVE(tcp->tcp_cred);
7991 	PRESERVE(tcp->tcp_cpid);
7992 	PRESERVE(tcp->tcp_open_time);
7993 	PRESERVE(tcp->tcp_exclbind);
7994 
7995 	tcp->tcp_fin_acked = 0;
7996 	tcp->tcp_fin_rcvd = 0;
7997 	tcp->tcp_fin_sent = 0;
7998 	tcp->tcp_ordrel_done = 0;
7999 
8000 	tcp->tcp_debug = 0;
8001 	tcp->tcp_dontroute = 0;
8002 	tcp->tcp_broadcast = 0;
8003 
8004 	tcp->tcp_useloopback = 0;
8005 	tcp->tcp_reuseaddr = 0;
8006 	tcp->tcp_oobinline = 0;
8007 	tcp->tcp_dgram_errind = 0;
8008 
8009 	tcp->tcp_detached = 0;
8010 	tcp->tcp_bind_pending = 0;
8011 	tcp->tcp_unbind_pending = 0;
8012 
8013 	tcp->tcp_snd_ws_ok = B_FALSE;
8014 	tcp->tcp_snd_ts_ok = B_FALSE;
8015 	tcp->tcp_linger = 0;
8016 	tcp->tcp_ka_enabled = 0;
8017 	tcp->tcp_zero_win_probe = 0;
8018 
8019 	tcp->tcp_loopback = 0;
8020 	tcp->tcp_refuse = 0;
8021 	tcp->tcp_localnet = 0;
8022 	tcp->tcp_syn_defense = 0;
8023 	tcp->tcp_set_timer = 0;
8024 
8025 	tcp->tcp_active_open = 0;
8026 	tcp->tcp_rexmit = B_FALSE;
8027 	tcp->tcp_xmit_zc_clean = B_FALSE;
8028 
8029 	tcp->tcp_snd_sack_ok = B_FALSE;
8030 	PRESERVE(tcp->tcp_recvdstaddr);
8031 	tcp->tcp_hwcksum = B_FALSE;
8032 
8033 	tcp->tcp_ire_ill_check_done = B_FALSE;
8034 	DONTCARE(tcp->tcp_maxpsz);		/* Init in tcp_init_values */
8035 
8036 	tcp->tcp_mdt = B_FALSE;
8037 	tcp->tcp_mdt_hdr_head = 0;
8038 	tcp->tcp_mdt_hdr_tail = 0;
8039 
8040 	tcp->tcp_conn_def_q0 = 0;
8041 	tcp->tcp_ip_forward_progress = B_FALSE;
8042 	tcp->tcp_anon_priv_bind = 0;
8043 	tcp->tcp_ecn_ok = B_FALSE;
8044 
8045 	tcp->tcp_cwr = B_FALSE;
8046 	tcp->tcp_ecn_echo_on = B_FALSE;
8047 
8048 	if (tcp->tcp_sack_info != NULL) {
8049 		if (tcp->tcp_notsack_list != NULL) {
8050 			TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
8051 		}
8052 		kmem_cache_free(tcp_sack_info_cache, tcp->tcp_sack_info);
8053 		tcp->tcp_sack_info = NULL;
8054 	}
8055 
8056 	tcp->tcp_rcv_ws = 0;
8057 	tcp->tcp_snd_ws = 0;
8058 	tcp->tcp_ts_recent = 0;
8059 	tcp->tcp_rnxt = 0;			/* Displayed in mib */
8060 	DONTCARE(tcp->tcp_rwnd);		/* Set in tcp_reinit() */
8061 	tcp->tcp_if_mtu = 0;
8062 
8063 	ASSERT(tcp->tcp_reass_head == NULL);
8064 	ASSERT(tcp->tcp_reass_tail == NULL);
8065 
8066 	tcp->tcp_cwnd_cnt = 0;
8067 
8068 	ASSERT(tcp->tcp_rcv_list == NULL);
8069 	ASSERT(tcp->tcp_rcv_last_head == NULL);
8070 	ASSERT(tcp->tcp_rcv_last_tail == NULL);
8071 	ASSERT(tcp->tcp_rcv_cnt == 0);
8072 
8073 	DONTCARE(tcp->tcp_cwnd_ssthresh);	/* Init in tcp_adapt_ire */
8074 	DONTCARE(tcp->tcp_cwnd_max);		/* Init in tcp_init_values */
8075 	tcp->tcp_csuna = 0;
8076 
8077 	tcp->tcp_rto = 0;			/* Displayed in MIB */
8078 	DONTCARE(tcp->tcp_rtt_sa);		/* Init in tcp_init_values */
8079 	DONTCARE(tcp->tcp_rtt_sd);		/* Init in tcp_init_values */
8080 	tcp->tcp_rtt_update = 0;
8081 
8082 	DONTCARE(tcp->tcp_swl1); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8083 	DONTCARE(tcp->tcp_swl2); /* Init in case TCPS_LISTEN/TCPS_SYN_SENT */
8084 
8085 	tcp->tcp_rack = 0;			/* Displayed in mib */
8086 	tcp->tcp_rack_cnt = 0;
8087 	tcp->tcp_rack_cur_max = 0;
8088 	tcp->tcp_rack_abs_max = 0;
8089 
8090 	tcp->tcp_max_swnd = 0;
8091 
8092 	ASSERT(tcp->tcp_listener == NULL);
8093 
8094 	DONTCARE(tcp->tcp_xmit_lowater);	/* Init in tcp_init_values */
8095 
8096 	DONTCARE(tcp->tcp_irs);			/* tcp_valid_bits cleared */
8097 	DONTCARE(tcp->tcp_iss);			/* tcp_valid_bits cleared */
8098 	DONTCARE(tcp->tcp_fss);			/* tcp_valid_bits cleared */
8099 	DONTCARE(tcp->tcp_urg);			/* tcp_valid_bits cleared */
8100 
8101 	ASSERT(tcp->tcp_conn_req_cnt_q == 0);
8102 	ASSERT(tcp->tcp_conn_req_cnt_q0 == 0);
8103 	PRESERVE(tcp->tcp_conn_req_max);
8104 	PRESERVE(tcp->tcp_conn_req_seqnum);
8105 
8106 	DONTCARE(tcp->tcp_ip_hdr_len);		/* Init in tcp_init_values */
8107 	DONTCARE(tcp->tcp_first_timer_threshold); /* Init in tcp_init_values */
8108 	DONTCARE(tcp->tcp_second_timer_threshold); /* Init in tcp_init_values */
8109 	DONTCARE(tcp->tcp_first_ctimer_threshold); /* Init in tcp_init_values */
8110 	DONTCARE(tcp->tcp_second_ctimer_threshold); /* in tcp_init_values */
8111 
8112 	tcp->tcp_lingertime = 0;
8113 
8114 	DONTCARE(tcp->tcp_urp_last);	/* tcp_urp_last_valid is cleared */
8115 	ASSERT(tcp->tcp_urp_mp == NULL);
8116 	ASSERT(tcp->tcp_urp_mark_mp == NULL);
8117 	ASSERT(tcp->tcp_fused_sigurg_mp == NULL);
8118 
8119 	ASSERT(tcp->tcp_eager_next_q == NULL);
8120 	ASSERT(tcp->tcp_eager_last_q == NULL);
8121 	ASSERT((tcp->tcp_eager_next_q0 == NULL &&
8122 	    tcp->tcp_eager_prev_q0 == NULL) ||
8123 	    tcp->tcp_eager_next_q0 == tcp->tcp_eager_prev_q0);
8124 	ASSERT(tcp->tcp_conn.tcp_eager_conn_ind == NULL);
8125 
8126 	ASSERT((tcp->tcp_eager_next_drop_q0 == NULL &&
8127 	    tcp->tcp_eager_prev_drop_q0 == NULL) ||
8128 	    tcp->tcp_eager_next_drop_q0 == tcp->tcp_eager_prev_drop_q0);
8129 
8130 	tcp->tcp_client_errno = 0;
8131 
8132 	DONTCARE(tcp->tcp_sum);			/* Init in tcp_init_values */
8133 
8134 	tcp->tcp_remote_v6 = ipv6_all_zeros;	/* Displayed in MIB */
8135 
8136 	PRESERVE(tcp->tcp_bound_source_v6);
8137 	tcp->tcp_last_sent_len = 0;
8138 	tcp->tcp_dupack_cnt = 0;
8139 
8140 	tcp->tcp_fport = 0;			/* Displayed in MIB */
8141 	PRESERVE(tcp->tcp_lport);
8142 
8143 	PRESERVE(tcp->tcp_acceptor_lockp);
8144 
8145 	ASSERT(tcp->tcp_ordrel_mp == NULL);
8146 	PRESERVE(tcp->tcp_acceptor_id);
8147 	DONTCARE(tcp->tcp_ipsec_overhead);
8148 
8149 	PRESERVE(tcp->tcp_family);
8150 	if (tcp->tcp_family == AF_INET6) {
8151 		tcp->tcp_ipversion = IPV6_VERSION;
8152 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
8153 	} else {
8154 		tcp->tcp_ipversion = IPV4_VERSION;
8155 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
8156 	}
8157 
8158 	tcp->tcp_bound_if = 0;
8159 	tcp->tcp_ipv6_recvancillary = 0;
8160 	tcp->tcp_recvifindex = 0;
8161 	tcp->tcp_recvhops = 0;
8162 	tcp->tcp_closed = 0;
8163 	tcp->tcp_cleandeathtag = 0;
8164 	if (tcp->tcp_hopopts != NULL) {
8165 		mi_free(tcp->tcp_hopopts);
8166 		tcp->tcp_hopopts = NULL;
8167 		tcp->tcp_hopoptslen = 0;
8168 	}
8169 	ASSERT(tcp->tcp_hopoptslen == 0);
8170 	if (tcp->tcp_dstopts != NULL) {
8171 		mi_free(tcp->tcp_dstopts);
8172 		tcp->tcp_dstopts = NULL;
8173 		tcp->tcp_dstoptslen = 0;
8174 	}
8175 	ASSERT(tcp->tcp_dstoptslen == 0);
8176 	if (tcp->tcp_rtdstopts != NULL) {
8177 		mi_free(tcp->tcp_rtdstopts);
8178 		tcp->tcp_rtdstopts = NULL;
8179 		tcp->tcp_rtdstoptslen = 0;
8180 	}
8181 	ASSERT(tcp->tcp_rtdstoptslen == 0);
8182 	if (tcp->tcp_rthdr != NULL) {
8183 		mi_free(tcp->tcp_rthdr);
8184 		tcp->tcp_rthdr = NULL;
8185 		tcp->tcp_rthdrlen = 0;
8186 	}
8187 	ASSERT(tcp->tcp_rthdrlen == 0);
8188 	PRESERVE(tcp->tcp_drop_opt_ack_cnt);
8189 
8190 	/* Reset fusion-related fields */
8191 	tcp->tcp_fused = B_FALSE;
8192 	tcp->tcp_unfusable = B_FALSE;
8193 	tcp->tcp_fused_sigurg = B_FALSE;
8194 	tcp->tcp_direct_sockfs = B_FALSE;
8195 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8196 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8197 	tcp->tcp_loopback_peer = NULL;
8198 	tcp->tcp_fuse_rcv_hiwater = 0;
8199 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8200 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8201 
8202 	tcp->tcp_lso = B_FALSE;
8203 
8204 	tcp->tcp_in_ack_unsent = 0;
8205 	tcp->tcp_cork = B_FALSE;
8206 	tcp->tcp_tconnind_started = B_FALSE;
8207 
8208 	PRESERVE(tcp->tcp_squeue_bytes);
8209 
8210 	ASSERT(tcp->tcp_kssl_ctx == NULL);
8211 	ASSERT(!tcp->tcp_kssl_pending);
8212 	PRESERVE(tcp->tcp_kssl_ent);
8213 
8214 	/* Sodirect */
8215 	tcp->tcp_sodirect = NULL;
8216 
8217 	tcp->tcp_closemp_used = B_FALSE;
8218 
8219 	PRESERVE(tcp->tcp_rsrv_mp);
8220 	PRESERVE(tcp->tcp_rsrv_mp_lock);
8221 
8222 #ifdef DEBUG
8223 	DONTCARE(tcp->tcmp_stk[0]);
8224 #endif
8225 
8226 
8227 #undef	DONTCARE
8228 #undef	PRESERVE
8229 }
8230 
8231 /*
8232  * Allocate necessary resources and initialize state vector.
8233  * Guaranteed not to fail so that when an error is returned,
8234  * the caller doesn't need to do any additional cleanup.
8235  */
8236 int
8237 tcp_init(tcp_t *tcp, queue_t *q)
8238 {
8239 	int	err;
8240 
8241 	tcp->tcp_rq = q;
8242 	tcp->tcp_wq = WR(q);
8243 	tcp->tcp_state = TCPS_IDLE;
8244 	if ((err = tcp_init_values(tcp)) != 0)
8245 		tcp_timers_stop(tcp);
8246 	return (err);
8247 }
8248 
8249 static int
8250 tcp_init_values(tcp_t *tcp)
8251 {
8252 	int	err;
8253 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8254 
8255 	ASSERT((tcp->tcp_family == AF_INET &&
8256 	    tcp->tcp_ipversion == IPV4_VERSION) ||
8257 	    (tcp->tcp_family == AF_INET6 &&
8258 	    (tcp->tcp_ipversion == IPV4_VERSION ||
8259 	    tcp->tcp_ipversion == IPV6_VERSION)));
8260 
8261 	/*
8262 	 * Initialize tcp_rtt_sa and tcp_rtt_sd so that the calculated RTO
8263 	 * will be close to tcp_rexmit_interval_initial.  By doing this, we
8264 	 * allow the algorithm to adjust slowly to large fluctuations of RTT
8265 	 * during first few transmissions of a connection as seen in slow
8266 	 * links.
8267 	 */
8268 	tcp->tcp_rtt_sa = tcps->tcps_rexmit_interval_initial << 2;
8269 	tcp->tcp_rtt_sd = tcps->tcps_rexmit_interval_initial >> 1;
8270 	tcp->tcp_rto = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
8271 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5) +
8272 	    tcps->tcps_conn_grace_period;
8273 	if (tcp->tcp_rto < tcps->tcps_rexmit_interval_min)
8274 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
8275 	tcp->tcp_timer_backoff = 0;
8276 	tcp->tcp_ms_we_have_waited = 0;
8277 	tcp->tcp_last_recv_time = lbolt;
8278 	tcp->tcp_cwnd_max = tcps->tcps_cwnd_max_;
8279 	tcp->tcp_cwnd_ssthresh = TCP_MAX_LARGEWIN;
8280 	tcp->tcp_snd_burst = TCP_CWND_INFINITE;
8281 
8282 	tcp->tcp_maxpsz = tcps->tcps_maxpsz_multiplier;
8283 
8284 	tcp->tcp_first_timer_threshold = tcps->tcps_ip_notify_interval;
8285 	tcp->tcp_first_ctimer_threshold = tcps->tcps_ip_notify_cinterval;
8286 	tcp->tcp_second_timer_threshold = tcps->tcps_ip_abort_interval;
8287 	/*
8288 	 * Fix it to tcp_ip_abort_linterval later if it turns out to be a
8289 	 * passive open.
8290 	 */
8291 	tcp->tcp_second_ctimer_threshold = tcps->tcps_ip_abort_cinterval;
8292 
8293 	tcp->tcp_naglim = tcps->tcps_naglim_def;
8294 
8295 	/* NOTE:  ISS is now set in tcp_adapt_ire(). */
8296 
8297 	tcp->tcp_mdt_hdr_head = 0;
8298 	tcp->tcp_mdt_hdr_tail = 0;
8299 
8300 	/* Reset fusion-related fields */
8301 	tcp->tcp_fused = B_FALSE;
8302 	tcp->tcp_unfusable = B_FALSE;
8303 	tcp->tcp_fused_sigurg = B_FALSE;
8304 	tcp->tcp_direct_sockfs = B_FALSE;
8305 	tcp->tcp_fuse_syncstr_stopped = B_FALSE;
8306 	tcp->tcp_fuse_syncstr_plugged = B_FALSE;
8307 	tcp->tcp_loopback_peer = NULL;
8308 	tcp->tcp_fuse_rcv_hiwater = 0;
8309 	tcp->tcp_fuse_rcv_unread_hiwater = 0;
8310 	tcp->tcp_fuse_rcv_unread_cnt = 0;
8311 
8312 	/* Sodirect */
8313 	tcp->tcp_sodirect = NULL;
8314 
8315 	/* Initialize the header template */
8316 	if (tcp->tcp_ipversion == IPV4_VERSION) {
8317 		err = tcp_header_init_ipv4(tcp);
8318 	} else {
8319 		err = tcp_header_init_ipv6(tcp);
8320 	}
8321 	if (err)
8322 		return (err);
8323 
8324 	/*
8325 	 * Init the window scale to the max so tcp_rwnd_set() won't pare
8326 	 * down tcp_rwnd. tcp_adapt_ire() will set the right value later.
8327 	 */
8328 	tcp->tcp_rcv_ws = TCP_MAX_WINSHIFT;
8329 	tcp->tcp_xmit_lowater = tcps->tcps_xmit_lowat;
8330 	tcp->tcp_xmit_hiwater = tcps->tcps_xmit_hiwat;
8331 
8332 	tcp->tcp_cork = B_FALSE;
8333 	/*
8334 	 * Init the tcp_debug option.  This value determines whether TCP
8335 	 * calls strlog() to print out debug messages.  Doing this
8336 	 * initialization here means that this value is not inherited thru
8337 	 * tcp_reinit().
8338 	 */
8339 	tcp->tcp_debug = tcps->tcps_dbg;
8340 
8341 	tcp->tcp_ka_interval = tcps->tcps_keepalive_interval;
8342 	tcp->tcp_ka_abort_thres = tcps->tcps_keepalive_abort_interval;
8343 
8344 	return (0);
8345 }
8346 
8347 /*
8348  * Initialize the IPv4 header. Loses any record of any IP options.
8349  */
8350 static int
8351 tcp_header_init_ipv4(tcp_t *tcp)
8352 {
8353 	tcph_t		*tcph;
8354 	uint32_t	sum;
8355 	conn_t		*connp;
8356 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8357 
8358 	/*
8359 	 * This is a simple initialization. If there's
8360 	 * already a template, it should never be too small,
8361 	 * so reuse it.  Otherwise, allocate space for the new one.
8362 	 */
8363 	if (tcp->tcp_iphc == NULL) {
8364 		ASSERT(tcp->tcp_iphc_len == 0);
8365 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8366 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8367 		if (tcp->tcp_iphc == NULL) {
8368 			tcp->tcp_iphc_len = 0;
8369 			return (ENOMEM);
8370 		}
8371 	}
8372 
8373 	/* options are gone; may need a new label */
8374 	connp = tcp->tcp_connp;
8375 	connp->conn_mlp_type = mlptSingle;
8376 	connp->conn_ulp_labeled = !is_system_labeled();
8377 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8378 	tcp->tcp_ipha = (ipha_t *)tcp->tcp_iphc;
8379 	tcp->tcp_ip6h = NULL;
8380 	tcp->tcp_ipversion = IPV4_VERSION;
8381 	tcp->tcp_hdr_len = sizeof (ipha_t) + sizeof (tcph_t);
8382 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8383 	tcp->tcp_ip_hdr_len = sizeof (ipha_t);
8384 	tcp->tcp_ipha->ipha_length = htons(sizeof (ipha_t) + sizeof (tcph_t));
8385 	tcp->tcp_ipha->ipha_version_and_hdr_length
8386 	    = (IP_VERSION << 4) | IP_SIMPLE_HDR_LENGTH_IN_WORDS;
8387 	tcp->tcp_ipha->ipha_ident = 0;
8388 
8389 	tcp->tcp_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8390 	tcp->tcp_tos = 0;
8391 	tcp->tcp_ipha->ipha_fragment_offset_and_flags = 0;
8392 	tcp->tcp_ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
8393 	tcp->tcp_ipha->ipha_protocol = IPPROTO_TCP;
8394 
8395 	tcph = (tcph_t *)(tcp->tcp_iphc + sizeof (ipha_t));
8396 	tcp->tcp_tcph = tcph;
8397 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8398 	/*
8399 	 * IP wants our header length in the checksum field to
8400 	 * allow it to perform a single pseudo-header+checksum
8401 	 * calculation on behalf of TCP.
8402 	 * Include the adjustment for a source route once IP_OPTIONS is set.
8403 	 */
8404 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8405 	sum = (sum >> 16) + (sum & 0xFFFF);
8406 	U16_TO_ABE16(sum, tcph->th_sum);
8407 	return (0);
8408 }
8409 
8410 /*
8411  * Initialize the IPv6 header. Loses any record of any IPv6 extension headers.
8412  */
8413 static int
8414 tcp_header_init_ipv6(tcp_t *tcp)
8415 {
8416 	tcph_t	*tcph;
8417 	uint32_t	sum;
8418 	conn_t	*connp;
8419 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8420 
8421 	/*
8422 	 * This is a simple initialization. If there's
8423 	 * already a template, it should never be too small,
8424 	 * so reuse it. Otherwise, allocate space for the new one.
8425 	 * Ensure that there is enough space to "downgrade" the tcp_t
8426 	 * to an IPv4 tcp_t. This requires having space for a full load
8427 	 * of IPv4 options, as well as a full load of TCP options
8428 	 * (TCP_MAX_COMBINED_HEADER_LENGTH, 120 bytes); this is more space
8429 	 * than a v6 header and a TCP header with a full load of TCP options
8430 	 * (IPV6_HDR_LEN is 40 bytes; TCP_MAX_HDR_LENGTH is 60 bytes).
8431 	 * We want to avoid reallocation in the "downgraded" case when
8432 	 * processing outbound IPv4 options.
8433 	 */
8434 	if (tcp->tcp_iphc == NULL) {
8435 		ASSERT(tcp->tcp_iphc_len == 0);
8436 		tcp->tcp_iphc_len = TCP_MAX_COMBINED_HEADER_LENGTH;
8437 		tcp->tcp_iphc = kmem_cache_alloc(tcp_iphc_cache, KM_NOSLEEP);
8438 		if (tcp->tcp_iphc == NULL) {
8439 			tcp->tcp_iphc_len = 0;
8440 			return (ENOMEM);
8441 		}
8442 	}
8443 
8444 	/* options are gone; may need a new label */
8445 	connp = tcp->tcp_connp;
8446 	connp->conn_mlp_type = mlptSingle;
8447 	connp->conn_ulp_labeled = !is_system_labeled();
8448 
8449 	ASSERT(tcp->tcp_iphc_len >= TCP_MAX_COMBINED_HEADER_LENGTH);
8450 	tcp->tcp_ipversion = IPV6_VERSION;
8451 	tcp->tcp_hdr_len = IPV6_HDR_LEN + sizeof (tcph_t);
8452 	tcp->tcp_tcp_hdr_len = sizeof (tcph_t);
8453 	tcp->tcp_ip_hdr_len = IPV6_HDR_LEN;
8454 	tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
8455 	tcp->tcp_ipha = NULL;
8456 
8457 	/* Initialize the header template */
8458 
8459 	tcp->tcp_ip6h->ip6_vcf = IPV6_DEFAULT_VERS_AND_FLOW;
8460 	tcp->tcp_ip6h->ip6_plen = ntohs(sizeof (tcph_t));
8461 	tcp->tcp_ip6h->ip6_nxt = IPPROTO_TCP;
8462 	tcp->tcp_ip6h->ip6_hops = (uint8_t)tcps->tcps_ipv6_hoplimit;
8463 
8464 	tcph = (tcph_t *)(tcp->tcp_iphc + IPV6_HDR_LEN);
8465 	tcp->tcp_tcph = tcph;
8466 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
8467 	/*
8468 	 * IP wants our header length in the checksum field to
8469 	 * allow it to perform a single psuedo-header+checksum
8470 	 * calculation on behalf of TCP.
8471 	 * Include the adjustment for a source route when IPV6_RTHDR is set.
8472 	 */
8473 	sum = sizeof (tcph_t) + tcp->tcp_sum;
8474 	sum = (sum >> 16) + (sum & 0xFFFF);
8475 	U16_TO_ABE16(sum, tcph->th_sum);
8476 	return (0);
8477 }
8478 
8479 /* At minimum we need 8 bytes in the TCP header for the lookup */
8480 #define	ICMP_MIN_TCP_HDR	8
8481 
8482 /*
8483  * tcp_icmp_error is called by tcp_rput_other to process ICMP error messages
8484  * passed up by IP. The message is always received on the correct tcp_t.
8485  * Assumes that IP has pulled up everything up to and including the ICMP header.
8486  */
8487 void
8488 tcp_icmp_error(tcp_t *tcp, mblk_t *mp)
8489 {
8490 	icmph_t *icmph;
8491 	ipha_t	*ipha;
8492 	int	iph_hdr_length;
8493 	tcph_t	*tcph;
8494 	boolean_t ipsec_mctl = B_FALSE;
8495 	boolean_t secure;
8496 	mblk_t *first_mp = mp;
8497 	int32_t new_mss;
8498 	uint32_t ratio;
8499 	size_t mp_size = MBLKL(mp);
8500 	uint32_t seg_seq;
8501 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8502 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
8503 
8504 	/* Assume IP provides aligned packets - otherwise toss */
8505 	if (!OK_32PTR(mp->b_rptr)) {
8506 		freemsg(mp);
8507 		return;
8508 	}
8509 
8510 	/*
8511 	 * Since ICMP errors are normal data marked with M_CTL when sent
8512 	 * to TCP or UDP, we have to look for a IPSEC_IN value to identify
8513 	 * packets starting with an ipsec_info_t, see ipsec_info.h.
8514 	 */
8515 	if ((mp_size == sizeof (ipsec_info_t)) &&
8516 	    (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type == IPSEC_IN)) {
8517 		ASSERT(mp->b_cont != NULL);
8518 		mp = mp->b_cont;
8519 		/* IP should have done this */
8520 		ASSERT(OK_32PTR(mp->b_rptr));
8521 		mp_size = MBLKL(mp);
8522 		ipsec_mctl = B_TRUE;
8523 	}
8524 
8525 	/*
8526 	 * Verify that we have a complete outer IP header. If not, drop it.
8527 	 */
8528 	if (mp_size < sizeof (ipha_t)) {
8529 noticmpv4:
8530 		freemsg(first_mp);
8531 		return;
8532 	}
8533 
8534 	ipha = (ipha_t *)mp->b_rptr;
8535 	/*
8536 	 * Verify IP version. Anything other than IPv4 or IPv6 packet is sent
8537 	 * upstream. ICMPv6 is handled in tcp_icmp_error_ipv6.
8538 	 */
8539 	switch (IPH_HDR_VERSION(ipha)) {
8540 	case IPV6_VERSION:
8541 		tcp_icmp_error_ipv6(tcp, first_mp, ipsec_mctl);
8542 		return;
8543 	case IPV4_VERSION:
8544 		break;
8545 	default:
8546 		goto noticmpv4;
8547 	}
8548 
8549 	/* Skip past the outer IP and ICMP headers */
8550 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8551 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
8552 	/*
8553 	 * If we don't have the correct outer IP header length or if the ULP
8554 	 * is not IPPROTO_ICMP or if we don't have a complete inner IP header
8555 	 * send it upstream.
8556 	 */
8557 	if (iph_hdr_length < sizeof (ipha_t) ||
8558 	    ipha->ipha_protocol != IPPROTO_ICMP ||
8559 	    (ipha_t *)&icmph[1] + 1 > (ipha_t *)mp->b_wptr) {
8560 		goto noticmpv4;
8561 	}
8562 	ipha = (ipha_t *)&icmph[1];
8563 
8564 	/* Skip past the inner IP and find the ULP header */
8565 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
8566 	tcph = (tcph_t *)((char *)ipha + iph_hdr_length);
8567 	/*
8568 	 * If we don't have the correct inner IP header length or if the ULP
8569 	 * is not IPPROTO_TCP or if we don't have at least ICMP_MIN_TCP_HDR
8570 	 * bytes of TCP header, drop it.
8571 	 */
8572 	if (iph_hdr_length < sizeof (ipha_t) ||
8573 	    ipha->ipha_protocol != IPPROTO_TCP ||
8574 	    (uchar_t *)tcph + ICMP_MIN_TCP_HDR > mp->b_wptr) {
8575 		goto noticmpv4;
8576 	}
8577 
8578 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
8579 		if (ipsec_mctl) {
8580 			secure = ipsec_in_is_secure(first_mp);
8581 		} else {
8582 			secure = B_FALSE;
8583 		}
8584 		if (secure) {
8585 			/*
8586 			 * If we are willing to accept this in clear
8587 			 * we don't have to verify policy.
8588 			 */
8589 			if (!ipsec_inbound_accept_clear(mp, ipha, NULL)) {
8590 				if (!tcp_check_policy(tcp, first_mp,
8591 				    ipha, NULL, secure, ipsec_mctl)) {
8592 					/*
8593 					 * tcp_check_policy called
8594 					 * ip_drop_packet() on failure.
8595 					 */
8596 					return;
8597 				}
8598 			}
8599 		}
8600 	} else if (ipsec_mctl) {
8601 		/*
8602 		 * This is a hard_bound connection. IP has already
8603 		 * verified policy. We don't have to do it again.
8604 		 */
8605 		freeb(first_mp);
8606 		first_mp = mp;
8607 		ipsec_mctl = B_FALSE;
8608 	}
8609 
8610 	seg_seq = ABE32_TO_U32(tcph->th_seq);
8611 	/*
8612 	 * TCP SHOULD check that the TCP sequence number contained in
8613 	 * payload of the ICMP error message is within the range
8614 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8615 	 */
8616 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8617 		/*
8618 		 * The ICMP message is bogus, just drop it.  But if this is
8619 		 * an ICMP too big message, IP has already changed
8620 		 * the ire_max_frag to the bogus value.  We need to change
8621 		 * it back.
8622 		 */
8623 		if (icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
8624 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
8625 			conn_t *connp = tcp->tcp_connp;
8626 			ire_t *ire;
8627 			int flag;
8628 
8629 			if (tcp->tcp_ipversion == IPV4_VERSION) {
8630 				flag = tcp->tcp_ipha->
8631 				    ipha_fragment_offset_and_flags;
8632 			} else {
8633 				flag = 0;
8634 			}
8635 			mutex_enter(&connp->conn_lock);
8636 			if ((ire = connp->conn_ire_cache) != NULL) {
8637 				mutex_enter(&ire->ire_lock);
8638 				mutex_exit(&connp->conn_lock);
8639 				ire->ire_max_frag = tcp->tcp_if_mtu;
8640 				ire->ire_frag_flag |= flag;
8641 				mutex_exit(&ire->ire_lock);
8642 			} else {
8643 				mutex_exit(&connp->conn_lock);
8644 			}
8645 		}
8646 		goto noticmpv4;
8647 	}
8648 
8649 	switch (icmph->icmph_type) {
8650 	case ICMP_DEST_UNREACHABLE:
8651 		switch (icmph->icmph_code) {
8652 		case ICMP_FRAGMENTATION_NEEDED:
8653 			/*
8654 			 * Reduce the MSS based on the new MTU.  This will
8655 			 * eliminate any fragmentation locally.
8656 			 * N.B.  There may well be some funny side-effects on
8657 			 * the local send policy and the remote receive policy.
8658 			 * Pending further research, we provide
8659 			 * tcp_ignore_path_mtu just in case this proves
8660 			 * disastrous somewhere.
8661 			 *
8662 			 * After updating the MSS, retransmit part of the
8663 			 * dropped segment using the new mss by calling
8664 			 * tcp_wput_data().  Need to adjust all those
8665 			 * params to make sure tcp_wput_data() work properly.
8666 			 */
8667 			if (tcps->tcps_ignore_path_mtu ||
8668 			    tcp->tcp_ipha->ipha_fragment_offset_and_flags == 0)
8669 				break;
8670 
8671 			/*
8672 			 * Decrease the MSS by time stamp options
8673 			 * IP options and IPSEC options. tcp_hdr_len
8674 			 * includes time stamp option and IP option
8675 			 * length.  Note that new_mss may be negative
8676 			 * if tcp_ipsec_overhead is large and the
8677 			 * icmph_du_mtu is the minimum value, which is 68.
8678 			 */
8679 			new_mss = ntohs(icmph->icmph_du_mtu) -
8680 			    tcp->tcp_hdr_len - tcp->tcp_ipsec_overhead;
8681 
8682 			DTRACE_PROBE2(tcp__pmtu__change, tcp_t *, tcp, int,
8683 			    new_mss);
8684 
8685 			/*
8686 			 * Only update the MSS if the new one is
8687 			 * smaller than the previous one.  This is
8688 			 * to avoid problems when getting multiple
8689 			 * ICMP errors for the same MTU.
8690 			 */
8691 			if (new_mss >= tcp->tcp_mss)
8692 				break;
8693 
8694 			/*
8695 			 * Note that we are using the template header's DF
8696 			 * bit in the fast path sending.  So we need to compare
8697 			 * the new mss with both tcps_mss_min and ip_pmtu_min.
8698 			 * And stop doing IPv4 PMTUd if new_mss is less than
8699 			 * MAX(tcps_mss_min, ip_pmtu_min).
8700 			 */
8701 			if (new_mss < tcps->tcps_mss_min ||
8702 			    new_mss < ipst->ips_ip_pmtu_min) {
8703 				tcp->tcp_ipha->ipha_fragment_offset_and_flags =
8704 				    0;
8705 			}
8706 
8707 			ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8708 			ASSERT(ratio >= 1);
8709 			tcp_mss_set(tcp, new_mss, B_TRUE);
8710 
8711 			/*
8712 			 * Make sure we have something to
8713 			 * send.
8714 			 */
8715 			if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8716 			    (tcp->tcp_xmit_head != NULL)) {
8717 				/*
8718 				 * Shrink tcp_cwnd in
8719 				 * proportion to the old MSS/new MSS.
8720 				 */
8721 				tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8722 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8723 				    (tcp->tcp_unsent == 0)) {
8724 					tcp->tcp_rexmit_max = tcp->tcp_fss;
8725 				} else {
8726 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
8727 				}
8728 				tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8729 				tcp->tcp_rexmit = B_TRUE;
8730 				tcp->tcp_dupack_cnt = 0;
8731 				tcp->tcp_snd_burst = TCP_CWND_SS;
8732 				tcp_ss_rexmit(tcp);
8733 			}
8734 			break;
8735 		case ICMP_PORT_UNREACHABLE:
8736 		case ICMP_PROTOCOL_UNREACHABLE:
8737 			switch (tcp->tcp_state) {
8738 			case TCPS_SYN_SENT:
8739 			case TCPS_SYN_RCVD:
8740 				/*
8741 				 * ICMP can snipe away incipient
8742 				 * TCP connections as long as
8743 				 * seq number is same as initial
8744 				 * send seq number.
8745 				 */
8746 				if (seg_seq == tcp->tcp_iss) {
8747 					(void) tcp_clean_death(tcp,
8748 					    ECONNREFUSED, 6);
8749 				}
8750 				break;
8751 			}
8752 			break;
8753 		case ICMP_HOST_UNREACHABLE:
8754 		case ICMP_NET_UNREACHABLE:
8755 			/* Record the error in case we finally time out. */
8756 			if (icmph->icmph_code == ICMP_HOST_UNREACHABLE)
8757 				tcp->tcp_client_errno = EHOSTUNREACH;
8758 			else
8759 				tcp->tcp_client_errno = ENETUNREACH;
8760 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
8761 				if (tcp->tcp_listener != NULL &&
8762 				    tcp->tcp_listener->tcp_syn_defense) {
8763 					/*
8764 					 * Ditch the half-open connection if we
8765 					 * suspect a SYN attack is under way.
8766 					 */
8767 					tcp_ip_ire_mark_advice(tcp);
8768 					(void) tcp_clean_death(tcp,
8769 					    tcp->tcp_client_errno, 7);
8770 				}
8771 			}
8772 			break;
8773 		default:
8774 			break;
8775 		}
8776 		break;
8777 	case ICMP_SOURCE_QUENCH: {
8778 		/*
8779 		 * use a global boolean to control
8780 		 * whether TCP should respond to ICMP_SOURCE_QUENCH.
8781 		 * The default is false.
8782 		 */
8783 		if (tcp_icmp_source_quench) {
8784 			/*
8785 			 * Reduce the sending rate as if we got a
8786 			 * retransmit timeout
8787 			 */
8788 			uint32_t npkt;
8789 
8790 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) /
8791 			    tcp->tcp_mss;
8792 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * tcp->tcp_mss;
8793 			tcp->tcp_cwnd = tcp->tcp_mss;
8794 			tcp->tcp_cwnd_cnt = 0;
8795 		}
8796 		break;
8797 	}
8798 	}
8799 	freemsg(first_mp);
8800 }
8801 
8802 /*
8803  * tcp_icmp_error_ipv6 is called by tcp_rput_other to process ICMPv6
8804  * error messages passed up by IP.
8805  * Assumes that IP has pulled up all the extension headers as well
8806  * as the ICMPv6 header.
8807  */
8808 static void
8809 tcp_icmp_error_ipv6(tcp_t *tcp, mblk_t *mp, boolean_t ipsec_mctl)
8810 {
8811 	icmp6_t *icmp6;
8812 	ip6_t	*ip6h;
8813 	uint16_t	iph_hdr_length;
8814 	tcpha_t	*tcpha;
8815 	uint8_t	*nexthdrp;
8816 	uint32_t new_mss;
8817 	uint32_t ratio;
8818 	boolean_t secure;
8819 	mblk_t *first_mp = mp;
8820 	size_t mp_size;
8821 	uint32_t seg_seq;
8822 	tcp_stack_t	*tcps = tcp->tcp_tcps;
8823 
8824 	/*
8825 	 * The caller has determined if this is an IPSEC_IN packet and
8826 	 * set ipsec_mctl appropriately (see tcp_icmp_error).
8827 	 */
8828 	if (ipsec_mctl)
8829 		mp = mp->b_cont;
8830 
8831 	mp_size = MBLKL(mp);
8832 
8833 	/*
8834 	 * Verify that we have a complete IP header. If not, send it upstream.
8835 	 */
8836 	if (mp_size < sizeof (ip6_t)) {
8837 noticmpv6:
8838 		freemsg(first_mp);
8839 		return;
8840 	}
8841 
8842 	/*
8843 	 * Verify this is an ICMPV6 packet, else send it upstream.
8844 	 */
8845 	ip6h = (ip6_t *)mp->b_rptr;
8846 	if (ip6h->ip6_nxt == IPPROTO_ICMPV6) {
8847 		iph_hdr_length = IPV6_HDR_LEN;
8848 	} else if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length,
8849 	    &nexthdrp) ||
8850 	    *nexthdrp != IPPROTO_ICMPV6) {
8851 		goto noticmpv6;
8852 	}
8853 	icmp6 = (icmp6_t *)&mp->b_rptr[iph_hdr_length];
8854 	ip6h = (ip6_t *)&icmp6[1];
8855 	/*
8856 	 * Verify if we have a complete ICMP and inner IP header.
8857 	 */
8858 	if ((uchar_t *)&ip6h[1] > mp->b_wptr)
8859 		goto noticmpv6;
8860 
8861 	if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &iph_hdr_length, &nexthdrp))
8862 		goto noticmpv6;
8863 	tcpha = (tcpha_t *)((char *)ip6h + iph_hdr_length);
8864 	/*
8865 	 * Validate inner header. If the ULP is not IPPROTO_TCP or if we don't
8866 	 * have at least ICMP_MIN_TCP_HDR bytes of  TCP header drop the
8867 	 * packet.
8868 	 */
8869 	if ((*nexthdrp != IPPROTO_TCP) ||
8870 	    ((uchar_t *)tcpha + ICMP_MIN_TCP_HDR) > mp->b_wptr) {
8871 		goto noticmpv6;
8872 	}
8873 
8874 	/*
8875 	 * ICMP errors come on the right queue or come on
8876 	 * listener/global queue for detached connections and
8877 	 * get switched to the right queue. If it comes on the
8878 	 * right queue, policy check has already been done by IP
8879 	 * and thus free the first_mp without verifying the policy.
8880 	 * If it has come for a non-hard bound connection, we need
8881 	 * to verify policy as IP may not have done it.
8882 	 */
8883 	if (!tcp->tcp_hard_bound) {
8884 		if (ipsec_mctl) {
8885 			secure = ipsec_in_is_secure(first_mp);
8886 		} else {
8887 			secure = B_FALSE;
8888 		}
8889 		if (secure) {
8890 			/*
8891 			 * If we are willing to accept this in clear
8892 			 * we don't have to verify policy.
8893 			 */
8894 			if (!ipsec_inbound_accept_clear(mp, NULL, ip6h)) {
8895 				if (!tcp_check_policy(tcp, first_mp,
8896 				    NULL, ip6h, secure, ipsec_mctl)) {
8897 					/*
8898 					 * tcp_check_policy called
8899 					 * ip_drop_packet() on failure.
8900 					 */
8901 					return;
8902 				}
8903 			}
8904 		}
8905 	} else if (ipsec_mctl) {
8906 		/*
8907 		 * This is a hard_bound connection. IP has already
8908 		 * verified policy. We don't have to do it again.
8909 		 */
8910 		freeb(first_mp);
8911 		first_mp = mp;
8912 		ipsec_mctl = B_FALSE;
8913 	}
8914 
8915 	seg_seq = ntohl(tcpha->tha_seq);
8916 	/*
8917 	 * TCP SHOULD check that the TCP sequence number contained in
8918 	 * payload of the ICMP error message is within the range
8919 	 * SND.UNA <= SEG.SEQ < SND.NXT.
8920 	 */
8921 	if (SEQ_LT(seg_seq, tcp->tcp_suna) || SEQ_GEQ(seg_seq, tcp->tcp_snxt)) {
8922 		/*
8923 		 * If the ICMP message is bogus, should we kill the
8924 		 * connection, or should we just drop the bogus ICMP
8925 		 * message? It would probably make more sense to just
8926 		 * drop the message so that if this one managed to get
8927 		 * in, the real connection should not suffer.
8928 		 */
8929 		goto noticmpv6;
8930 	}
8931 
8932 	switch (icmp6->icmp6_type) {
8933 	case ICMP6_PACKET_TOO_BIG:
8934 		/*
8935 		 * Reduce the MSS based on the new MTU.  This will
8936 		 * eliminate any fragmentation locally.
8937 		 * N.B.  There may well be some funny side-effects on
8938 		 * the local send policy and the remote receive policy.
8939 		 * Pending further research, we provide
8940 		 * tcp_ignore_path_mtu just in case this proves
8941 		 * disastrous somewhere.
8942 		 *
8943 		 * After updating the MSS, retransmit part of the
8944 		 * dropped segment using the new mss by calling
8945 		 * tcp_wput_data().  Need to adjust all those
8946 		 * params to make sure tcp_wput_data() work properly.
8947 		 */
8948 		if (tcps->tcps_ignore_path_mtu)
8949 			break;
8950 
8951 		/*
8952 		 * Decrease the MSS by time stamp options
8953 		 * IP options and IPSEC options. tcp_hdr_len
8954 		 * includes time stamp option and IP option
8955 		 * length.
8956 		 */
8957 		new_mss = ntohs(icmp6->icmp6_mtu) - tcp->tcp_hdr_len -
8958 		    tcp->tcp_ipsec_overhead;
8959 
8960 		/*
8961 		 * Only update the MSS if the new one is
8962 		 * smaller than the previous one.  This is
8963 		 * to avoid problems when getting multiple
8964 		 * ICMP errors for the same MTU.
8965 		 */
8966 		if (new_mss >= tcp->tcp_mss)
8967 			break;
8968 
8969 		ratio = tcp->tcp_cwnd / tcp->tcp_mss;
8970 		ASSERT(ratio >= 1);
8971 		tcp_mss_set(tcp, new_mss, B_TRUE);
8972 
8973 		/*
8974 		 * Make sure we have something to
8975 		 * send.
8976 		 */
8977 		if (SEQ_LT(tcp->tcp_suna, tcp->tcp_snxt) &&
8978 		    (tcp->tcp_xmit_head != NULL)) {
8979 			/*
8980 			 * Shrink tcp_cwnd in
8981 			 * proportion to the old MSS/new MSS.
8982 			 */
8983 			tcp->tcp_cwnd = ratio * tcp->tcp_mss;
8984 			if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
8985 			    (tcp->tcp_unsent == 0)) {
8986 				tcp->tcp_rexmit_max = tcp->tcp_fss;
8987 			} else {
8988 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
8989 			}
8990 			tcp->tcp_rexmit_nxt = tcp->tcp_suna;
8991 			tcp->tcp_rexmit = B_TRUE;
8992 			tcp->tcp_dupack_cnt = 0;
8993 			tcp->tcp_snd_burst = TCP_CWND_SS;
8994 			tcp_ss_rexmit(tcp);
8995 		}
8996 		break;
8997 
8998 	case ICMP6_DST_UNREACH:
8999 		switch (icmp6->icmp6_code) {
9000 		case ICMP6_DST_UNREACH_NOPORT:
9001 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9002 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9003 			    (seg_seq == tcp->tcp_iss)) {
9004 				(void) tcp_clean_death(tcp,
9005 				    ECONNREFUSED, 8);
9006 			}
9007 			break;
9008 
9009 		case ICMP6_DST_UNREACH_ADMIN:
9010 		case ICMP6_DST_UNREACH_NOROUTE:
9011 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
9012 		case ICMP6_DST_UNREACH_ADDR:
9013 			/* Record the error in case we finally time out. */
9014 			tcp->tcp_client_errno = EHOSTUNREACH;
9015 			if (((tcp->tcp_state == TCPS_SYN_SENT) ||
9016 			    (tcp->tcp_state == TCPS_SYN_RCVD)) &&
9017 			    (seg_seq == tcp->tcp_iss)) {
9018 				if (tcp->tcp_listener != NULL &&
9019 				    tcp->tcp_listener->tcp_syn_defense) {
9020 					/*
9021 					 * Ditch the half-open connection if we
9022 					 * suspect a SYN attack is under way.
9023 					 */
9024 					tcp_ip_ire_mark_advice(tcp);
9025 					(void) tcp_clean_death(tcp,
9026 					    tcp->tcp_client_errno, 9);
9027 				}
9028 			}
9029 
9030 
9031 			break;
9032 		default:
9033 			break;
9034 		}
9035 		break;
9036 
9037 	case ICMP6_PARAM_PROB:
9038 		/* If this corresponds to an ICMP_PROTOCOL_UNREACHABLE */
9039 		if (icmp6->icmp6_code == ICMP6_PARAMPROB_NEXTHEADER &&
9040 		    (uchar_t *)ip6h + icmp6->icmp6_pptr ==
9041 		    (uchar_t *)nexthdrp) {
9042 			if (tcp->tcp_state == TCPS_SYN_SENT ||
9043 			    tcp->tcp_state == TCPS_SYN_RCVD) {
9044 				(void) tcp_clean_death(tcp,
9045 				    ECONNREFUSED, 10);
9046 			}
9047 			break;
9048 		}
9049 		break;
9050 
9051 	case ICMP6_TIME_EXCEEDED:
9052 	default:
9053 		break;
9054 	}
9055 	freemsg(first_mp);
9056 }
9057 
9058 /*
9059  * IP recognizes seven kinds of bind requests:
9060  *
9061  * - A zero-length address binds only to the protocol number.
9062  *
9063  * - A 4-byte address is treated as a request to
9064  * validate that the address is a valid local IPv4
9065  * address, appropriate for an application to bind to.
9066  * IP does the verification, but does not make any note
9067  * of the address at this time.
9068  *
9069  * - A 16-byte address contains is treated as a request
9070  * to validate a local IPv6 address, as the 4-byte
9071  * address case above.
9072  *
9073  * - A 16-byte sockaddr_in to validate the local IPv4 address and also
9074  * use it for the inbound fanout of packets.
9075  *
9076  * - A 24-byte sockaddr_in6 to validate the local IPv6 address and also
9077  * use it for the inbound fanout of packets.
9078  *
9079  * - A 12-byte address (ipa_conn_t) containing complete IPv4 fanout
9080  * information consisting of local and remote addresses
9081  * and ports.  In this case, the addresses are both
9082  * validated as appropriate for this operation, and, if
9083  * so, the information is retained for use in the
9084  * inbound fanout.
9085  *
9086  * - A 36-byte address address (ipa6_conn_t) containing complete IPv6
9087  * fanout information, like the 12-byte case above.
9088  *
9089  * IP will also fill in the IRE request mblk with information
9090  * regarding our peer.  In all cases, we notify IP of our protocol
9091  * type by appending a single protocol byte to the bind request.
9092  */
9093 static mblk_t *
9094 tcp_ip_bind_mp(tcp_t *tcp, t_scalar_t bind_prim, t_scalar_t addr_length)
9095 {
9096 	char	*cp;
9097 	mblk_t	*mp;
9098 	struct T_bind_req *tbr;
9099 	ipa_conn_t	*ac;
9100 	ipa6_conn_t	*ac6;
9101 	sin_t		*sin;
9102 	sin6_t		*sin6;
9103 
9104 	ASSERT(bind_prim == O_T_BIND_REQ || bind_prim == T_BIND_REQ);
9105 	ASSERT((tcp->tcp_family == AF_INET &&
9106 	    tcp->tcp_ipversion == IPV4_VERSION) ||
9107 	    (tcp->tcp_family == AF_INET6 &&
9108 	    (tcp->tcp_ipversion == IPV4_VERSION ||
9109 	    tcp->tcp_ipversion == IPV6_VERSION)));
9110 
9111 	mp = allocb(sizeof (*tbr) + addr_length + 1, BPRI_HI);
9112 	if (!mp)
9113 		return (mp);
9114 	mp->b_datap->db_type = M_PROTO;
9115 	tbr = (struct T_bind_req *)mp->b_rptr;
9116 	tbr->PRIM_type = bind_prim;
9117 	tbr->ADDR_offset = sizeof (*tbr);
9118 	tbr->CONIND_number = 0;
9119 	tbr->ADDR_length = addr_length;
9120 	cp = (char *)&tbr[1];
9121 	switch (addr_length) {
9122 	case sizeof (ipa_conn_t):
9123 		ASSERT(tcp->tcp_family == AF_INET);
9124 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9125 
9126 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9127 		if (mp->b_cont == NULL) {
9128 			freemsg(mp);
9129 			return (NULL);
9130 		}
9131 		mp->b_cont->b_wptr += sizeof (ire_t);
9132 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9133 
9134 		/* cp known to be 32 bit aligned */
9135 		ac = (ipa_conn_t *)cp;
9136 		ac->ac_laddr = tcp->tcp_ipha->ipha_src;
9137 		ac->ac_faddr = tcp->tcp_remote;
9138 		ac->ac_fport = tcp->tcp_fport;
9139 		ac->ac_lport = tcp->tcp_lport;
9140 		tcp->tcp_hard_binding = 1;
9141 		break;
9142 
9143 	case sizeof (ipa6_conn_t):
9144 		ASSERT(tcp->tcp_family == AF_INET6);
9145 
9146 		mp->b_cont = allocb(sizeof (ire_t), BPRI_HI);
9147 		if (mp->b_cont == NULL) {
9148 			freemsg(mp);
9149 			return (NULL);
9150 		}
9151 		mp->b_cont->b_wptr += sizeof (ire_t);
9152 		mp->b_cont->b_datap->db_type = IRE_DB_REQ_TYPE;
9153 
9154 		/* cp known to be 32 bit aligned */
9155 		ac6 = (ipa6_conn_t *)cp;
9156 		if (tcp->tcp_ipversion == IPV4_VERSION) {
9157 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
9158 			    &ac6->ac6_laddr);
9159 		} else {
9160 			ac6->ac6_laddr = tcp->tcp_ip6h->ip6_src;
9161 		}
9162 		ac6->ac6_faddr = tcp->tcp_remote_v6;
9163 		ac6->ac6_fport = tcp->tcp_fport;
9164 		ac6->ac6_lport = tcp->tcp_lport;
9165 		tcp->tcp_hard_binding = 1;
9166 		break;
9167 
9168 	case sizeof (sin_t):
9169 		/*
9170 		 * NOTE: IPV6_ADDR_LEN also has same size.
9171 		 * Use family to discriminate.
9172 		 */
9173 		if (tcp->tcp_family == AF_INET) {
9174 			sin = (sin_t *)cp;
9175 
9176 			*sin = sin_null;
9177 			sin->sin_family = AF_INET;
9178 			sin->sin_addr.s_addr = tcp->tcp_bound_source;
9179 			sin->sin_port = tcp->tcp_lport;
9180 			break;
9181 		} else {
9182 			*(in6_addr_t *)cp = tcp->tcp_bound_source_v6;
9183 		}
9184 		break;
9185 
9186 	case sizeof (sin6_t):
9187 		ASSERT(tcp->tcp_family == AF_INET6);
9188 		sin6 = (sin6_t *)cp;
9189 
9190 		*sin6 = sin6_null;
9191 		sin6->sin6_family = AF_INET6;
9192 		sin6->sin6_addr = tcp->tcp_bound_source_v6;
9193 		sin6->sin6_port = tcp->tcp_lport;
9194 		break;
9195 
9196 	case IP_ADDR_LEN:
9197 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
9198 		*(uint32_t *)cp = tcp->tcp_ipha->ipha_src;
9199 		break;
9200 
9201 	}
9202 	/* Add protocol number to end */
9203 	cp[addr_length] = (char)IPPROTO_TCP;
9204 	mp->b_wptr = (uchar_t *)&cp[addr_length + 1];
9205 	return (mp);
9206 }
9207 
9208 /*
9209  * Notify IP that we are having trouble with this connection.  IP should
9210  * blow the IRE away and start over.
9211  */
9212 static void
9213 tcp_ip_notify(tcp_t *tcp)
9214 {
9215 	struct iocblk	*iocp;
9216 	ipid_t	*ipid;
9217 	mblk_t	*mp;
9218 
9219 	/* IPv6 has NUD thus notification to delete the IRE is not needed */
9220 	if (tcp->tcp_ipversion == IPV6_VERSION)
9221 		return;
9222 
9223 	mp = mkiocb(IP_IOCTL);
9224 	if (mp == NULL)
9225 		return;
9226 
9227 	iocp = (struct iocblk *)mp->b_rptr;
9228 	iocp->ioc_count = sizeof (ipid_t) + sizeof (tcp->tcp_ipha->ipha_dst);
9229 
9230 	mp->b_cont = allocb(iocp->ioc_count, BPRI_HI);
9231 	if (!mp->b_cont) {
9232 		freeb(mp);
9233 		return;
9234 	}
9235 
9236 	ipid = (ipid_t *)mp->b_cont->b_rptr;
9237 	mp->b_cont->b_wptr += iocp->ioc_count;
9238 	bzero(ipid, sizeof (*ipid));
9239 	ipid->ipid_cmd = IP_IOC_IRE_DELETE_NO_REPLY;
9240 	ipid->ipid_ire_type = IRE_CACHE;
9241 	ipid->ipid_addr_offset = sizeof (ipid_t);
9242 	ipid->ipid_addr_length = sizeof (tcp->tcp_ipha->ipha_dst);
9243 	/*
9244 	 * Note: in the case of source routing we want to blow away the
9245 	 * route to the first source route hop.
9246 	 */
9247 	bcopy(&tcp->tcp_ipha->ipha_dst, &ipid[1],
9248 	    sizeof (tcp->tcp_ipha->ipha_dst));
9249 
9250 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
9251 }
9252 
9253 /* Unlink and return any mblk that looks like it contains an ire */
9254 static mblk_t *
9255 tcp_ire_mp(mblk_t *mp)
9256 {
9257 	mblk_t	*prev_mp;
9258 
9259 	for (;;) {
9260 		prev_mp = mp;
9261 		mp = mp->b_cont;
9262 		if (mp == NULL)
9263 			break;
9264 		switch (DB_TYPE(mp)) {
9265 		case IRE_DB_TYPE:
9266 		case IRE_DB_REQ_TYPE:
9267 			if (prev_mp != NULL)
9268 				prev_mp->b_cont = mp->b_cont;
9269 			mp->b_cont = NULL;
9270 			return (mp);
9271 		default:
9272 			break;
9273 		}
9274 	}
9275 	return (mp);
9276 }
9277 
9278 /*
9279  * Timer callback routine for keepalive probe.  We do a fake resend of
9280  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
9281  * check to see if we have heard anything from the other end for the last
9282  * RTO period.  If we have, set the timer to expire for another
9283  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
9284  * RTO << 1 and check again when it expires.  Keep exponentially increasing
9285  * the timeout if we have not heard from the other side.  If for more than
9286  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
9287  * kill the connection unless the keepalive abort threshold is 0.  In
9288  * that case, we will probe "forever."
9289  */
9290 static void
9291 tcp_keepalive_killer(void *arg)
9292 {
9293 	mblk_t	*mp;
9294 	conn_t	*connp = (conn_t *)arg;
9295 	tcp_t  	*tcp = connp->conn_tcp;
9296 	int32_t	firetime;
9297 	int32_t	idletime;
9298 	int32_t	ka_intrvl;
9299 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9300 
9301 	tcp->tcp_ka_tid = 0;
9302 
9303 	if (tcp->tcp_fused)
9304 		return;
9305 
9306 	BUMP_MIB(&tcps->tcps_mib, tcpTimKeepalive);
9307 	ka_intrvl = tcp->tcp_ka_interval;
9308 
9309 	/*
9310 	 * Keepalive probe should only be sent if the application has not
9311 	 * done a close on the connection.
9312 	 */
9313 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
9314 		return;
9315 	}
9316 	/* Timer fired too early, restart it. */
9317 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
9318 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9319 		    MSEC_TO_TICK(ka_intrvl));
9320 		return;
9321 	}
9322 
9323 	idletime = TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time);
9324 	/*
9325 	 * If we have not heard from the other side for a long
9326 	 * time, kill the connection unless the keepalive abort
9327 	 * threshold is 0.  In that case, we will probe "forever."
9328 	 */
9329 	if (tcp->tcp_ka_abort_thres != 0 &&
9330 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
9331 		BUMP_MIB(&tcps->tcps_mib, tcpTimKeepaliveDrop);
9332 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
9333 		    tcp->tcp_client_errno : ETIMEDOUT, 11);
9334 		return;
9335 	}
9336 
9337 	if (tcp->tcp_snxt == tcp->tcp_suna &&
9338 	    idletime >= ka_intrvl) {
9339 		/* Fake resend of last ACKed byte. */
9340 		mblk_t	*mp1 = allocb(1, BPRI_LO);
9341 
9342 		if (mp1 != NULL) {
9343 			*mp1->b_wptr++ = '\0';
9344 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
9345 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
9346 			freeb(mp1);
9347 			/*
9348 			 * if allocation failed, fall through to start the
9349 			 * timer back.
9350 			 */
9351 			if (mp != NULL) {
9352 				tcp_send_data(tcp, tcp->tcp_wq, mp);
9353 				BUMP_MIB(&tcps->tcps_mib,
9354 				    tcpTimKeepaliveProbe);
9355 				if (tcp->tcp_ka_last_intrvl != 0) {
9356 					int max;
9357 					/*
9358 					 * We should probe again at least
9359 					 * in ka_intrvl, but not more than
9360 					 * tcp_rexmit_interval_max.
9361 					 */
9362 					max = tcps->tcps_rexmit_interval_max;
9363 					firetime = MIN(ka_intrvl - 1,
9364 					    tcp->tcp_ka_last_intrvl << 1);
9365 					if (firetime > max)
9366 						firetime = max;
9367 				} else {
9368 					firetime = tcp->tcp_rto;
9369 				}
9370 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
9371 				    tcp_keepalive_killer,
9372 				    MSEC_TO_TICK(firetime));
9373 				tcp->tcp_ka_last_intrvl = firetime;
9374 				return;
9375 			}
9376 		}
9377 	} else {
9378 		tcp->tcp_ka_last_intrvl = 0;
9379 	}
9380 
9381 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
9382 	if ((firetime = ka_intrvl - idletime) < 0) {
9383 		firetime = ka_intrvl;
9384 	}
9385 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
9386 	    MSEC_TO_TICK(firetime));
9387 }
9388 
9389 int
9390 tcp_maxpsz_set(tcp_t *tcp, boolean_t set_maxblk)
9391 {
9392 	queue_t	*q = tcp->tcp_rq;
9393 	int32_t	mss = tcp->tcp_mss;
9394 	int	maxpsz;
9395 
9396 	if (TCP_IS_DETACHED(tcp))
9397 		return (mss);
9398 
9399 	if (tcp->tcp_fused) {
9400 		maxpsz = tcp_fuse_maxpsz_set(tcp);
9401 		mss = INFPSZ;
9402 	} else if (tcp->tcp_mdt || tcp->tcp_lso || tcp->tcp_maxpsz == 0) {
9403 		/*
9404 		 * Set the sd_qn_maxpsz according to the socket send buffer
9405 		 * size, and sd_maxblk to INFPSZ (-1).  This will essentially
9406 		 * instruct the stream head to copyin user data into contiguous
9407 		 * kernel-allocated buffers without breaking it up into smaller
9408 		 * chunks.  We round up the buffer size to the nearest SMSS.
9409 		 */
9410 		maxpsz = MSS_ROUNDUP(tcp->tcp_xmit_hiwater, mss);
9411 		if (tcp->tcp_kssl_ctx == NULL)
9412 			mss = INFPSZ;
9413 		else
9414 			mss = SSL3_MAX_RECORD_LEN;
9415 	} else {
9416 		/*
9417 		 * Set sd_qn_maxpsz to approx half the (receivers) buffer
9418 		 * (and a multiple of the mss).  This instructs the stream
9419 		 * head to break down larger than SMSS writes into SMSS-
9420 		 * size mblks, up to tcp_maxpsz_multiplier mblks at a time.
9421 		 */
9422 		maxpsz = tcp->tcp_maxpsz * mss;
9423 		if (maxpsz > tcp->tcp_xmit_hiwater/2) {
9424 			maxpsz = tcp->tcp_xmit_hiwater/2;
9425 			/* Round up to nearest mss */
9426 			maxpsz = MSS_ROUNDUP(maxpsz, mss);
9427 		}
9428 	}
9429 	(void) setmaxps(q, maxpsz);
9430 	tcp->tcp_wq->q_maxpsz = maxpsz;
9431 
9432 	if (set_maxblk)
9433 		(void) mi_set_sth_maxblk(q, mss);
9434 
9435 	return (mss);
9436 }
9437 
9438 /*
9439  * Extract option values from a tcp header.  We put any found values into the
9440  * tcpopt struct and return a bitmask saying which options were found.
9441  */
9442 static int
9443 tcp_parse_options(tcph_t *tcph, tcp_opt_t *tcpopt)
9444 {
9445 	uchar_t		*endp;
9446 	int		len;
9447 	uint32_t	mss;
9448 	uchar_t		*up = (uchar_t *)tcph;
9449 	int		found = 0;
9450 	int32_t		sack_len;
9451 	tcp_seq		sack_begin, sack_end;
9452 	tcp_t		*tcp;
9453 
9454 	endp = up + TCP_HDR_LENGTH(tcph);
9455 	up += TCP_MIN_HEADER_LENGTH;
9456 	while (up < endp) {
9457 		len = endp - up;
9458 		switch (*up) {
9459 		case TCPOPT_EOL:
9460 			break;
9461 
9462 		case TCPOPT_NOP:
9463 			up++;
9464 			continue;
9465 
9466 		case TCPOPT_MAXSEG:
9467 			if (len < TCPOPT_MAXSEG_LEN ||
9468 			    up[1] != TCPOPT_MAXSEG_LEN)
9469 				break;
9470 
9471 			mss = BE16_TO_U16(up+2);
9472 			/* Caller must handle tcp_mss_min and tcp_mss_max_* */
9473 			tcpopt->tcp_opt_mss = mss;
9474 			found |= TCP_OPT_MSS_PRESENT;
9475 
9476 			up += TCPOPT_MAXSEG_LEN;
9477 			continue;
9478 
9479 		case TCPOPT_WSCALE:
9480 			if (len < TCPOPT_WS_LEN || up[1] != TCPOPT_WS_LEN)
9481 				break;
9482 
9483 			if (up[2] > TCP_MAX_WINSHIFT)
9484 				tcpopt->tcp_opt_wscale = TCP_MAX_WINSHIFT;
9485 			else
9486 				tcpopt->tcp_opt_wscale = up[2];
9487 			found |= TCP_OPT_WSCALE_PRESENT;
9488 
9489 			up += TCPOPT_WS_LEN;
9490 			continue;
9491 
9492 		case TCPOPT_SACK_PERMITTED:
9493 			if (len < TCPOPT_SACK_OK_LEN ||
9494 			    up[1] != TCPOPT_SACK_OK_LEN)
9495 				break;
9496 			found |= TCP_OPT_SACK_OK_PRESENT;
9497 			up += TCPOPT_SACK_OK_LEN;
9498 			continue;
9499 
9500 		case TCPOPT_SACK:
9501 			if (len <= 2 || up[1] <= 2 || len < up[1])
9502 				break;
9503 
9504 			/* If TCP is not interested in SACK blks... */
9505 			if ((tcp = tcpopt->tcp) == NULL) {
9506 				up += up[1];
9507 				continue;
9508 			}
9509 			sack_len = up[1] - TCPOPT_HEADER_LEN;
9510 			up += TCPOPT_HEADER_LEN;
9511 
9512 			/*
9513 			 * If the list is empty, allocate one and assume
9514 			 * nothing is sack'ed.
9515 			 */
9516 			ASSERT(tcp->tcp_sack_info != NULL);
9517 			if (tcp->tcp_notsack_list == NULL) {
9518 				tcp_notsack_update(&(tcp->tcp_notsack_list),
9519 				    tcp->tcp_suna, tcp->tcp_snxt,
9520 				    &(tcp->tcp_num_notsack_blk),
9521 				    &(tcp->tcp_cnt_notsack_list));
9522 
9523 				/*
9524 				 * Make sure tcp_notsack_list is not NULL.
9525 				 * This happens when kmem_alloc(KM_NOSLEEP)
9526 				 * returns NULL.
9527 				 */
9528 				if (tcp->tcp_notsack_list == NULL) {
9529 					up += sack_len;
9530 					continue;
9531 				}
9532 				tcp->tcp_fack = tcp->tcp_suna;
9533 			}
9534 
9535 			while (sack_len > 0) {
9536 				if (up + 8 > endp) {
9537 					up = endp;
9538 					break;
9539 				}
9540 				sack_begin = BE32_TO_U32(up);
9541 				up += 4;
9542 				sack_end = BE32_TO_U32(up);
9543 				up += 4;
9544 				sack_len -= 8;
9545 				/*
9546 				 * Bounds checking.  Make sure the SACK
9547 				 * info is within tcp_suna and tcp_snxt.
9548 				 * If this SACK blk is out of bound, ignore
9549 				 * it but continue to parse the following
9550 				 * blks.
9551 				 */
9552 				if (SEQ_LEQ(sack_end, sack_begin) ||
9553 				    SEQ_LT(sack_begin, tcp->tcp_suna) ||
9554 				    SEQ_GT(sack_end, tcp->tcp_snxt)) {
9555 					continue;
9556 				}
9557 				tcp_notsack_insert(&(tcp->tcp_notsack_list),
9558 				    sack_begin, sack_end,
9559 				    &(tcp->tcp_num_notsack_blk),
9560 				    &(tcp->tcp_cnt_notsack_list));
9561 				if (SEQ_GT(sack_end, tcp->tcp_fack)) {
9562 					tcp->tcp_fack = sack_end;
9563 				}
9564 			}
9565 			found |= TCP_OPT_SACK_PRESENT;
9566 			continue;
9567 
9568 		case TCPOPT_TSTAMP:
9569 			if (len < TCPOPT_TSTAMP_LEN ||
9570 			    up[1] != TCPOPT_TSTAMP_LEN)
9571 				break;
9572 
9573 			tcpopt->tcp_opt_ts_val = BE32_TO_U32(up+2);
9574 			tcpopt->tcp_opt_ts_ecr = BE32_TO_U32(up+6);
9575 
9576 			found |= TCP_OPT_TSTAMP_PRESENT;
9577 
9578 			up += TCPOPT_TSTAMP_LEN;
9579 			continue;
9580 
9581 		default:
9582 			if (len <= 1 || len < (int)up[1] || up[1] == 0)
9583 				break;
9584 			up += up[1];
9585 			continue;
9586 		}
9587 		break;
9588 	}
9589 	return (found);
9590 }
9591 
9592 /*
9593  * Set the mss associated with a particular tcp based on its current value,
9594  * and a new one passed in. Observe minimums and maximums, and reset
9595  * other state variables that we want to view as multiples of mss.
9596  *
9597  * This function is called mainly because values like tcp_mss, tcp_cwnd,
9598  * highwater marks etc. need to be initialized or adjusted.
9599  * 1) From tcp_process_options() when the other side's SYN/SYN-ACK
9600  *    packet arrives.
9601  * 2) We need to set a new MSS when ICMP_FRAGMENTATION_NEEDED or
9602  *    ICMP6_PACKET_TOO_BIG arrives.
9603  * 3) From tcp_paws_check() if the other side stops sending the timestamp,
9604  *    to increase the MSS to use the extra bytes available.
9605  *
9606  * Callers except tcp_paws_check() ensure that they only reduce mss.
9607  */
9608 static void
9609 tcp_mss_set(tcp_t *tcp, uint32_t mss, boolean_t do_ss)
9610 {
9611 	uint32_t	mss_max;
9612 	tcp_stack_t	*tcps = tcp->tcp_tcps;
9613 
9614 	if (tcp->tcp_ipversion == IPV4_VERSION)
9615 		mss_max = tcps->tcps_mss_max_ipv4;
9616 	else
9617 		mss_max = tcps->tcps_mss_max_ipv6;
9618 
9619 	if (mss < tcps->tcps_mss_min)
9620 		mss = tcps->tcps_mss_min;
9621 	if (mss > mss_max)
9622 		mss = mss_max;
9623 	/*
9624 	 * Unless naglim has been set by our client to
9625 	 * a non-mss value, force naglim to track mss.
9626 	 * This can help to aggregate small writes.
9627 	 */
9628 	if (mss < tcp->tcp_naglim || tcp->tcp_mss == tcp->tcp_naglim)
9629 		tcp->tcp_naglim = mss;
9630 	/*
9631 	 * TCP should be able to buffer at least 4 MSS data for obvious
9632 	 * performance reason.
9633 	 */
9634 	if ((mss << 2) > tcp->tcp_xmit_hiwater)
9635 		tcp->tcp_xmit_hiwater = mss << 2;
9636 
9637 	if (do_ss) {
9638 		/*
9639 		 * Either the tcp_cwnd is as yet uninitialized, or mss is
9640 		 * changing due to a reduction in MTU, presumably as a
9641 		 * result of a new path component, reset cwnd to its
9642 		 * "initial" value, as a multiple of the new mss.
9643 		 */
9644 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_initial);
9645 	} else {
9646 		/*
9647 		 * Called by tcp_paws_check(), the mss increased
9648 		 * marginally to allow use of space previously taken
9649 		 * by the timestamp option. It would be inappropriate
9650 		 * to apply slow start or tcp_init_cwnd values to
9651 		 * tcp_cwnd, simply adjust to a multiple of the new mss.
9652 		 */
9653 		tcp->tcp_cwnd = (tcp->tcp_cwnd / tcp->tcp_mss) * mss;
9654 		tcp->tcp_cwnd_cnt = 0;
9655 	}
9656 	tcp->tcp_mss = mss;
9657 	(void) tcp_maxpsz_set(tcp, B_TRUE);
9658 }
9659 
9660 /* For /dev/tcp aka AF_INET open */
9661 static int
9662 tcp_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9663 {
9664 	return (tcp_open(q, devp, flag, sflag, credp, B_FALSE));
9665 }
9666 
9667 /* For /dev/tcp6 aka AF_INET6 open */
9668 static int
9669 tcp_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9670 {
9671 	return (tcp_open(q, devp, flag, sflag, credp, B_TRUE));
9672 }
9673 
9674 static int
9675 tcp_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9676     boolean_t isv6)
9677 {
9678 	tcp_t		*tcp = NULL;
9679 	conn_t		*connp;
9680 	int		err;
9681 	vmem_t		*minor_arena = NULL;
9682 	dev_t		conn_dev;
9683 	zoneid_t	zoneid;
9684 	tcp_stack_t	*tcps = NULL;
9685 
9686 	if (q->q_ptr != NULL)
9687 		return (0);
9688 
9689 	if (sflag == MODOPEN)
9690 		return (EINVAL);
9691 
9692 	if (!(flag & SO_ACCEPTOR)) {
9693 		/*
9694 		 * Special case for install: miniroot needs to be able to
9695 		 * access files via NFS as though it were always in the
9696 		 * global zone.
9697 		 */
9698 		if (credp == kcred && nfs_global_client_only != 0) {
9699 			zoneid = GLOBAL_ZONEID;
9700 			tcps = netstack_find_by_stackid(GLOBAL_NETSTACKID)->
9701 			    netstack_tcp;
9702 			ASSERT(tcps != NULL);
9703 		} else {
9704 			netstack_t *ns;
9705 
9706 			ns = netstack_find_by_cred(credp);
9707 			ASSERT(ns != NULL);
9708 			tcps = ns->netstack_tcp;
9709 			ASSERT(tcps != NULL);
9710 
9711 			/*
9712 			 * For exclusive stacks we set the zoneid to zero
9713 			 * to make TCP operate as if in the global zone.
9714 			 */
9715 			if (tcps->tcps_netstack->netstack_stackid !=
9716 			    GLOBAL_NETSTACKID)
9717 				zoneid = GLOBAL_ZONEID;
9718 			else
9719 				zoneid = crgetzoneid(credp);
9720 		}
9721 		/*
9722 		 * For stackid zero this is done from strplumb.c, but
9723 		 * non-zero stackids are handled here.
9724 		 */
9725 		if (tcps->tcps_g_q == NULL &&
9726 		    tcps->tcps_netstack->netstack_stackid !=
9727 		    GLOBAL_NETSTACKID) {
9728 			tcp_g_q_setup(tcps);
9729 		}
9730 	}
9731 
9732 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9733 	    ((conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9734 		minor_arena = ip_minor_arena_la;
9735 	} else {
9736 		/*
9737 		 * Either minor numbers in the large arena were exhausted
9738 		 * or a non socket application is doing the open.
9739 		 * Try to allocate from the small arena.
9740 		 */
9741 		if ((conn_dev = inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9742 			if (tcps != NULL)
9743 				netstack_rele(tcps->tcps_netstack);
9744 			return (EBUSY);
9745 		}
9746 		minor_arena = ip_minor_arena_sa;
9747 	}
9748 	ASSERT(minor_arena != NULL);
9749 
9750 	*devp = makedevice(getemajor(*devp), (minor_t)conn_dev);
9751 
9752 	if (flag & SO_ACCEPTOR) {
9753 		/* No netstack_find_by_cred, hence no netstack_rele needed */
9754 		ASSERT(tcps == NULL);
9755 		q->q_qinfo = &tcp_acceptor_rinit;
9756 		/*
9757 		 * the conn_dev and minor_arena will be subsequently used by
9758 		 * tcp_wput_accept() and tcpclose_accept() to figure out the
9759 		 * minor device number for this connection from the q_ptr.
9760 		 */
9761 		RD(q)->q_ptr = (void *)conn_dev;
9762 		WR(q)->q_qinfo = &tcp_acceptor_winit;
9763 		WR(q)->q_ptr = (void *)minor_arena;
9764 		qprocson(q);
9765 		return (0);
9766 	}
9767 
9768 	connp = (conn_t *)tcp_get_conn(IP_SQUEUE_GET(lbolt), tcps);
9769 	/*
9770 	 * Both tcp_get_conn and netstack_find_by_cred incremented refcnt,
9771 	 * so we drop it by one.
9772 	 */
9773 	netstack_rele(tcps->tcps_netstack);
9774 	if (connp == NULL) {
9775 		inet_minor_free(minor_arena, conn_dev);
9776 		q->q_ptr = NULL;
9777 		return (ENOSR);
9778 	}
9779 	connp->conn_sqp = IP_SQUEUE_GET(lbolt);
9780 	tcp = connp->conn_tcp;
9781 
9782 	q->q_ptr = WR(q)->q_ptr = connp;
9783 	if (isv6) {
9784 		connp->conn_flags |= (IPCL_TCP6|IPCL_ISV6);
9785 		connp->conn_send = ip_output_v6;
9786 		connp->conn_af_isv6 = B_TRUE;
9787 		connp->conn_pkt_isv6 = B_TRUE;
9788 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9789 		tcp->tcp_ipversion = IPV6_VERSION;
9790 		tcp->tcp_family = AF_INET6;
9791 		tcp->tcp_mss = tcps->tcps_mss_def_ipv6;
9792 	} else {
9793 		connp->conn_flags |= IPCL_TCP4;
9794 		connp->conn_send = ip_output;
9795 		connp->conn_af_isv6 = B_FALSE;
9796 		connp->conn_pkt_isv6 = B_FALSE;
9797 		tcp->tcp_ipversion = IPV4_VERSION;
9798 		tcp->tcp_family = AF_INET;
9799 		tcp->tcp_mss = tcps->tcps_mss_def_ipv4;
9800 	}
9801 
9802 	/*
9803 	 * TCP keeps a copy of cred for cache locality reasons but
9804 	 * we put a reference only once. If connp->conn_cred
9805 	 * becomes invalid, tcp_cred should also be set to NULL.
9806 	 */
9807 	tcp->tcp_cred = connp->conn_cred = credp;
9808 	crhold(connp->conn_cred);
9809 	tcp->tcp_cpid = curproc->p_pid;
9810 	tcp->tcp_open_time = lbolt64;
9811 	connp->conn_zoneid = zoneid;
9812 	connp->conn_mlp_type = mlptSingle;
9813 	connp->conn_ulp_labeled = !is_system_labeled();
9814 	ASSERT(connp->conn_netstack == tcps->tcps_netstack);
9815 	ASSERT(tcp->tcp_tcps == tcps);
9816 
9817 	/*
9818 	 * If the caller has the process-wide flag set, then default to MAC
9819 	 * exempt mode.  This allows read-down to unlabeled hosts.
9820 	 */
9821 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9822 		connp->conn_mac_exempt = B_TRUE;
9823 
9824 	connp->conn_dev = conn_dev;
9825 	connp->conn_minor_arena = minor_arena;
9826 
9827 	ASSERT(q->q_qinfo == &tcp_rinitv4 || q->q_qinfo == &tcp_rinitv6);
9828 	ASSERT(WR(q)->q_qinfo == &tcp_winit);
9829 
9830 	if (flag & SO_SOCKSTR) {
9831 		/*
9832 		 * No need to insert a socket in tcp acceptor hash.
9833 		 * If it was a socket acceptor stream, we dealt with
9834 		 * it above. A socket listener can never accept a
9835 		 * connection and doesn't need acceptor_id.
9836 		 */
9837 		connp->conn_flags |= IPCL_SOCKET;
9838 		tcp->tcp_issocket = 1;
9839 		WR(q)->q_qinfo = &tcp_sock_winit;
9840 	} else {
9841 #ifdef	_ILP32
9842 		tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
9843 #else
9844 		tcp->tcp_acceptor_id = conn_dev;
9845 #endif	/* _ILP32 */
9846 		tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
9847 	}
9848 
9849 	err = tcp_init(tcp, q);
9850 	if (err != 0) {
9851 		inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
9852 		tcp_acceptor_hash_remove(tcp);
9853 		CONN_DEC_REF(connp);
9854 		q->q_ptr = WR(q)->q_ptr = NULL;
9855 		return (err);
9856 	}
9857 
9858 	RD(q)->q_hiwat = tcps->tcps_recv_hiwat;
9859 	tcp->tcp_rwnd = tcps->tcps_recv_hiwat;
9860 
9861 	/* Non-zero default values */
9862 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9863 	/*
9864 	 * Put the ref for TCP. Ref for IP was already put
9865 	 * by ipcl_conn_create. Also Make the conn_t globally
9866 	 * visible to walkers
9867 	 */
9868 	mutex_enter(&connp->conn_lock);
9869 	CONN_INC_REF_LOCKED(connp);
9870 	ASSERT(connp->conn_ref == 2);
9871 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9872 	mutex_exit(&connp->conn_lock);
9873 
9874 	qprocson(q);
9875 	return (0);
9876 }
9877 
9878 /*
9879  * Some TCP options can be "set" by requesting them in the option
9880  * buffer. This is needed for XTI feature test though we do not
9881  * allow it in general. We interpret that this mechanism is more
9882  * applicable to OSI protocols and need not be allowed in general.
9883  * This routine filters out options for which it is not allowed (most)
9884  * and lets through those (few) for which it is. [ The XTI interface
9885  * test suite specifics will imply that any XTI_GENERIC level XTI_* if
9886  * ever implemented will have to be allowed here ].
9887  */
9888 static boolean_t
9889 tcp_allow_connopt_set(int level, int name)
9890 {
9891 
9892 	switch (level) {
9893 	case IPPROTO_TCP:
9894 		switch (name) {
9895 		case TCP_NODELAY:
9896 			return (B_TRUE);
9897 		default:
9898 			return (B_FALSE);
9899 		}
9900 		/*NOTREACHED*/
9901 	default:
9902 		return (B_FALSE);
9903 	}
9904 	/*NOTREACHED*/
9905 }
9906 
9907 /*
9908  * This routine gets default values of certain options whose default
9909  * values are maintained by protocol specific code
9910  */
9911 /* ARGSUSED */
9912 int
9913 tcp_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
9914 {
9915 	int32_t	*i1 = (int32_t *)ptr;
9916 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
9917 
9918 	switch (level) {
9919 	case IPPROTO_TCP:
9920 		switch (name) {
9921 		case TCP_NOTIFY_THRESHOLD:
9922 			*i1 = tcps->tcps_ip_notify_interval;
9923 			break;
9924 		case TCP_ABORT_THRESHOLD:
9925 			*i1 = tcps->tcps_ip_abort_interval;
9926 			break;
9927 		case TCP_CONN_NOTIFY_THRESHOLD:
9928 			*i1 = tcps->tcps_ip_notify_cinterval;
9929 			break;
9930 		case TCP_CONN_ABORT_THRESHOLD:
9931 			*i1 = tcps->tcps_ip_abort_cinterval;
9932 			break;
9933 		default:
9934 			return (-1);
9935 		}
9936 		break;
9937 	case IPPROTO_IP:
9938 		switch (name) {
9939 		case IP_TTL:
9940 			*i1 = tcps->tcps_ipv4_ttl;
9941 			break;
9942 		default:
9943 			return (-1);
9944 		}
9945 		break;
9946 	case IPPROTO_IPV6:
9947 		switch (name) {
9948 		case IPV6_UNICAST_HOPS:
9949 			*i1 = tcps->tcps_ipv6_hoplimit;
9950 			break;
9951 		default:
9952 			return (-1);
9953 		}
9954 		break;
9955 	default:
9956 		return (-1);
9957 	}
9958 	return (sizeof (int));
9959 }
9960 
9961 
9962 /*
9963  * TCP routine to get the values of options.
9964  */
9965 int
9966 tcp_opt_get(queue_t *q, int level, int	name, uchar_t *ptr)
9967 {
9968 	int		*i1 = (int *)ptr;
9969 	conn_t		*connp = Q_TO_CONN(q);
9970 	tcp_t		*tcp = connp->conn_tcp;
9971 	ip6_pkt_t	*ipp = &tcp->tcp_sticky_ipp;
9972 
9973 	switch (level) {
9974 	case SOL_SOCKET:
9975 		switch (name) {
9976 		case SO_LINGER:	{
9977 			struct linger *lgr = (struct linger *)ptr;
9978 
9979 			lgr->l_onoff = tcp->tcp_linger ? SO_LINGER : 0;
9980 			lgr->l_linger = tcp->tcp_lingertime;
9981 			}
9982 			return (sizeof (struct linger));
9983 		case SO_DEBUG:
9984 			*i1 = tcp->tcp_debug ? SO_DEBUG : 0;
9985 			break;
9986 		case SO_KEEPALIVE:
9987 			*i1 = tcp->tcp_ka_enabled ? SO_KEEPALIVE : 0;
9988 			break;
9989 		case SO_DONTROUTE:
9990 			*i1 = tcp->tcp_dontroute ? SO_DONTROUTE : 0;
9991 			break;
9992 		case SO_USELOOPBACK:
9993 			*i1 = tcp->tcp_useloopback ? SO_USELOOPBACK : 0;
9994 			break;
9995 		case SO_BROADCAST:
9996 			*i1 = tcp->tcp_broadcast ? SO_BROADCAST : 0;
9997 			break;
9998 		case SO_REUSEADDR:
9999 			*i1 = tcp->tcp_reuseaddr ? SO_REUSEADDR : 0;
10000 			break;
10001 		case SO_OOBINLINE:
10002 			*i1 = tcp->tcp_oobinline ? SO_OOBINLINE : 0;
10003 			break;
10004 		case SO_DGRAM_ERRIND:
10005 			*i1 = tcp->tcp_dgram_errind ? SO_DGRAM_ERRIND : 0;
10006 			break;
10007 		case SO_TYPE:
10008 			*i1 = SOCK_STREAM;
10009 			break;
10010 		case SO_SNDBUF:
10011 			*i1 = tcp->tcp_xmit_hiwater;
10012 			break;
10013 		case SO_RCVBUF:
10014 			*i1 = RD(q)->q_hiwat;
10015 			break;
10016 		case SO_SND_COPYAVOID:
10017 			*i1 = tcp->tcp_snd_zcopy_on ?
10018 			    SO_SND_COPYAVOID : 0;
10019 			break;
10020 		case SO_ALLZONES:
10021 			*i1 = connp->conn_allzones ? 1 : 0;
10022 			break;
10023 		case SO_ANON_MLP:
10024 			*i1 = connp->conn_anon_mlp;
10025 			break;
10026 		case SO_MAC_EXEMPT:
10027 			*i1 = connp->conn_mac_exempt;
10028 			break;
10029 		case SO_EXCLBIND:
10030 			*i1 = tcp->tcp_exclbind ? SO_EXCLBIND : 0;
10031 			break;
10032 		case SO_PROTOTYPE:
10033 			*i1 = IPPROTO_TCP;
10034 			break;
10035 		case SO_DOMAIN:
10036 			*i1 = tcp->tcp_family;
10037 			break;
10038 		default:
10039 			return (-1);
10040 		}
10041 		break;
10042 	case IPPROTO_TCP:
10043 		switch (name) {
10044 		case TCP_NODELAY:
10045 			*i1 = (tcp->tcp_naglim == 1) ? TCP_NODELAY : 0;
10046 			break;
10047 		case TCP_MAXSEG:
10048 			*i1 = tcp->tcp_mss;
10049 			break;
10050 		case TCP_NOTIFY_THRESHOLD:
10051 			*i1 = (int)tcp->tcp_first_timer_threshold;
10052 			break;
10053 		case TCP_ABORT_THRESHOLD:
10054 			*i1 = tcp->tcp_second_timer_threshold;
10055 			break;
10056 		case TCP_CONN_NOTIFY_THRESHOLD:
10057 			*i1 = tcp->tcp_first_ctimer_threshold;
10058 			break;
10059 		case TCP_CONN_ABORT_THRESHOLD:
10060 			*i1 = tcp->tcp_second_ctimer_threshold;
10061 			break;
10062 		case TCP_RECVDSTADDR:
10063 			*i1 = tcp->tcp_recvdstaddr;
10064 			break;
10065 		case TCP_ANONPRIVBIND:
10066 			*i1 = tcp->tcp_anon_priv_bind;
10067 			break;
10068 		case TCP_EXCLBIND:
10069 			*i1 = tcp->tcp_exclbind ? TCP_EXCLBIND : 0;
10070 			break;
10071 		case TCP_INIT_CWND:
10072 			*i1 = tcp->tcp_init_cwnd;
10073 			break;
10074 		case TCP_KEEPALIVE_THRESHOLD:
10075 			*i1 = tcp->tcp_ka_interval;
10076 			break;
10077 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10078 			*i1 = tcp->tcp_ka_abort_thres;
10079 			break;
10080 		case TCP_CORK:
10081 			*i1 = tcp->tcp_cork;
10082 			break;
10083 		default:
10084 			return (-1);
10085 		}
10086 		break;
10087 	case IPPROTO_IP:
10088 		if (tcp->tcp_family != AF_INET)
10089 			return (-1);
10090 		switch (name) {
10091 		case IP_OPTIONS:
10092 		case T_IP_OPTIONS: {
10093 			/*
10094 			 * This is compatible with BSD in that in only return
10095 			 * the reverse source route with the final destination
10096 			 * as the last entry. The first 4 bytes of the option
10097 			 * will contain the final destination.
10098 			 */
10099 			int	opt_len;
10100 
10101 			opt_len = (char *)tcp->tcp_tcph - (char *)tcp->tcp_ipha;
10102 			opt_len -= tcp->tcp_label_len + IP_SIMPLE_HDR_LENGTH;
10103 			ASSERT(opt_len >= 0);
10104 			/* Caller ensures enough space */
10105 			if (opt_len > 0) {
10106 				/*
10107 				 * TODO: Do we have to handle getsockopt on an
10108 				 * initiator as well?
10109 				 */
10110 				return (ip_opt_get_user(tcp->tcp_ipha, ptr));
10111 			}
10112 			return (0);
10113 			}
10114 		case IP_TOS:
10115 		case T_IP_TOS:
10116 			*i1 = (int)tcp->tcp_ipha->ipha_type_of_service;
10117 			break;
10118 		case IP_TTL:
10119 			*i1 = (int)tcp->tcp_ipha->ipha_ttl;
10120 			break;
10121 		case IP_NEXTHOP:
10122 			/* Handled at IP level */
10123 			return (-EINVAL);
10124 		default:
10125 			return (-1);
10126 		}
10127 		break;
10128 	case IPPROTO_IPV6:
10129 		/*
10130 		 * IPPROTO_IPV6 options are only supported for sockets
10131 		 * that are using IPv6 on the wire.
10132 		 */
10133 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10134 			return (-1);
10135 		}
10136 		switch (name) {
10137 		case IPV6_UNICAST_HOPS:
10138 			*i1 = (unsigned int) tcp->tcp_ip6h->ip6_hops;
10139 			break;	/* goto sizeof (int) option return */
10140 		case IPV6_BOUND_IF:
10141 			/* Zero if not set */
10142 			*i1 = tcp->tcp_bound_if;
10143 			break;	/* goto sizeof (int) option return */
10144 		case IPV6_RECVPKTINFO:
10145 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)
10146 				*i1 = 1;
10147 			else
10148 				*i1 = 0;
10149 			break;	/* goto sizeof (int) option return */
10150 		case IPV6_RECVTCLASS:
10151 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)
10152 				*i1 = 1;
10153 			else
10154 				*i1 = 0;
10155 			break;	/* goto sizeof (int) option return */
10156 		case IPV6_RECVHOPLIMIT:
10157 			if (tcp->tcp_ipv6_recvancillary &
10158 			    TCP_IPV6_RECVHOPLIMIT)
10159 				*i1 = 1;
10160 			else
10161 				*i1 = 0;
10162 			break;	/* goto sizeof (int) option return */
10163 		case IPV6_RECVHOPOPTS:
10164 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS)
10165 				*i1 = 1;
10166 			else
10167 				*i1 = 0;
10168 			break;	/* goto sizeof (int) option return */
10169 		case IPV6_RECVDSTOPTS:
10170 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVDSTOPTS)
10171 				*i1 = 1;
10172 			else
10173 				*i1 = 0;
10174 			break;	/* goto sizeof (int) option return */
10175 		case _OLD_IPV6_RECVDSTOPTS:
10176 			if (tcp->tcp_ipv6_recvancillary &
10177 			    TCP_OLD_IPV6_RECVDSTOPTS)
10178 				*i1 = 1;
10179 			else
10180 				*i1 = 0;
10181 			break;	/* goto sizeof (int) option return */
10182 		case IPV6_RECVRTHDR:
10183 			if (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR)
10184 				*i1 = 1;
10185 			else
10186 				*i1 = 0;
10187 			break;	/* goto sizeof (int) option return */
10188 		case IPV6_RECVRTHDRDSTOPTS:
10189 			if (tcp->tcp_ipv6_recvancillary &
10190 			    TCP_IPV6_RECVRTDSTOPTS)
10191 				*i1 = 1;
10192 			else
10193 				*i1 = 0;
10194 			break;	/* goto sizeof (int) option return */
10195 		case IPV6_PKTINFO: {
10196 			/* XXX assumes that caller has room for max size! */
10197 			struct in6_pktinfo *pkti;
10198 
10199 			pkti = (struct in6_pktinfo *)ptr;
10200 			if (ipp->ipp_fields & IPPF_IFINDEX)
10201 				pkti->ipi6_ifindex = ipp->ipp_ifindex;
10202 			else
10203 				pkti->ipi6_ifindex = 0;
10204 			if (ipp->ipp_fields & IPPF_ADDR)
10205 				pkti->ipi6_addr = ipp->ipp_addr;
10206 			else
10207 				pkti->ipi6_addr = ipv6_all_zeros;
10208 			return (sizeof (struct in6_pktinfo));
10209 		}
10210 		case IPV6_TCLASS:
10211 			if (ipp->ipp_fields & IPPF_TCLASS)
10212 				*i1 = ipp->ipp_tclass;
10213 			else
10214 				*i1 = IPV6_FLOW_TCLASS(
10215 				    IPV6_DEFAULT_VERS_AND_FLOW);
10216 			break;	/* goto sizeof (int) option return */
10217 		case IPV6_NEXTHOP: {
10218 			sin6_t *sin6 = (sin6_t *)ptr;
10219 
10220 			if (!(ipp->ipp_fields & IPPF_NEXTHOP))
10221 				return (0);
10222 			*sin6 = sin6_null;
10223 			sin6->sin6_family = AF_INET6;
10224 			sin6->sin6_addr = ipp->ipp_nexthop;
10225 			return (sizeof (sin6_t));
10226 		}
10227 		case IPV6_HOPOPTS:
10228 			if (!(ipp->ipp_fields & IPPF_HOPOPTS))
10229 				return (0);
10230 			if (ipp->ipp_hopoptslen <= tcp->tcp_label_len)
10231 				return (0);
10232 			bcopy((char *)ipp->ipp_hopopts + tcp->tcp_label_len,
10233 			    ptr, ipp->ipp_hopoptslen - tcp->tcp_label_len);
10234 			if (tcp->tcp_label_len > 0) {
10235 				ptr[0] = ((char *)ipp->ipp_hopopts)[0];
10236 				ptr[1] = (ipp->ipp_hopoptslen -
10237 				    tcp->tcp_label_len + 7) / 8 - 1;
10238 			}
10239 			return (ipp->ipp_hopoptslen - tcp->tcp_label_len);
10240 		case IPV6_RTHDRDSTOPTS:
10241 			if (!(ipp->ipp_fields & IPPF_RTDSTOPTS))
10242 				return (0);
10243 			bcopy(ipp->ipp_rtdstopts, ptr, ipp->ipp_rtdstoptslen);
10244 			return (ipp->ipp_rtdstoptslen);
10245 		case IPV6_RTHDR:
10246 			if (!(ipp->ipp_fields & IPPF_RTHDR))
10247 				return (0);
10248 			bcopy(ipp->ipp_rthdr, ptr, ipp->ipp_rthdrlen);
10249 			return (ipp->ipp_rthdrlen);
10250 		case IPV6_DSTOPTS:
10251 			if (!(ipp->ipp_fields & IPPF_DSTOPTS))
10252 				return (0);
10253 			bcopy(ipp->ipp_dstopts, ptr, ipp->ipp_dstoptslen);
10254 			return (ipp->ipp_dstoptslen);
10255 		case IPV6_SRC_PREFERENCES:
10256 			return (ip6_get_src_preferences(connp,
10257 			    (uint32_t *)ptr));
10258 		case IPV6_PATHMTU: {
10259 			struct ip6_mtuinfo *mtuinfo = (struct ip6_mtuinfo *)ptr;
10260 
10261 			if (tcp->tcp_state < TCPS_ESTABLISHED)
10262 				return (-1);
10263 
10264 			return (ip_fill_mtuinfo(&connp->conn_remv6,
10265 			    connp->conn_fport, mtuinfo,
10266 			    connp->conn_netstack));
10267 		}
10268 		default:
10269 			return (-1);
10270 		}
10271 		break;
10272 	default:
10273 		return (-1);
10274 	}
10275 	return (sizeof (int));
10276 }
10277 
10278 /*
10279  * We declare as 'int' rather than 'void' to satisfy pfi_t arg requirements.
10280  * Parameters are assumed to be verified by the caller.
10281  */
10282 /* ARGSUSED */
10283 int
10284 tcp_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10285     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10286     void *thisdg_attrs, cred_t *cr, mblk_t *mblk)
10287 {
10288 	conn_t	*connp = Q_TO_CONN(q);
10289 	tcp_t	*tcp = connp->conn_tcp;
10290 	int	*i1 = (int *)invalp;
10291 	boolean_t onoff = (*i1 == 0) ? 0 : 1;
10292 	boolean_t checkonly;
10293 	int	reterr;
10294 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
10295 
10296 	switch (optset_context) {
10297 	case SETFN_OPTCOM_CHECKONLY:
10298 		checkonly = B_TRUE;
10299 		/*
10300 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10301 		 * inlen != 0 implies value supplied and
10302 		 * 	we have to "pretend" to set it.
10303 		 * inlen == 0 implies that there is no
10304 		 * 	value part in T_CHECK request and just validation
10305 		 * done elsewhere should be enough, we just return here.
10306 		 */
10307 		if (inlen == 0) {
10308 			*outlenp = 0;
10309 			return (0);
10310 		}
10311 		break;
10312 	case SETFN_OPTCOM_NEGOTIATE:
10313 		checkonly = B_FALSE;
10314 		break;
10315 	case SETFN_UD_NEGOTIATE: /* error on conn-oriented transports ? */
10316 	case SETFN_CONN_NEGOTIATE:
10317 		checkonly = B_FALSE;
10318 		/*
10319 		 * Negotiating local and "association-related" options
10320 		 * from other (T_CONN_REQ, T_CONN_RES,T_UNITDATA_REQ)
10321 		 * primitives is allowed by XTI, but we choose
10322 		 * to not implement this style negotiation for Internet
10323 		 * protocols (We interpret it is a must for OSI world but
10324 		 * optional for Internet protocols) for all options.
10325 		 * [ Will do only for the few options that enable test
10326 		 * suites that our XTI implementation of this feature
10327 		 * works for transports that do allow it ]
10328 		 */
10329 		if (!tcp_allow_connopt_set(level, name)) {
10330 			*outlenp = 0;
10331 			return (EINVAL);
10332 		}
10333 		break;
10334 	default:
10335 		/*
10336 		 * We should never get here
10337 		 */
10338 		*outlenp = 0;
10339 		return (EINVAL);
10340 	}
10341 
10342 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10343 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10344 
10345 	/*
10346 	 * For TCP, we should have no ancillary data sent down
10347 	 * (sendmsg isn't supported for SOCK_STREAM), so thisdg_attrs
10348 	 * has to be zero.
10349 	 */
10350 	ASSERT(thisdg_attrs == NULL);
10351 
10352 	/*
10353 	 * For fixed length options, no sanity check
10354 	 * of passed in length is done. It is assumed *_optcom_req()
10355 	 * routines do the right thing.
10356 	 */
10357 
10358 	switch (level) {
10359 	case SOL_SOCKET:
10360 		switch (name) {
10361 		case SO_LINGER: {
10362 			struct linger *lgr = (struct linger *)invalp;
10363 
10364 			if (!checkonly) {
10365 				if (lgr->l_onoff) {
10366 					tcp->tcp_linger = 1;
10367 					tcp->tcp_lingertime = lgr->l_linger;
10368 				} else {
10369 					tcp->tcp_linger = 0;
10370 					tcp->tcp_lingertime = 0;
10371 				}
10372 				/* struct copy */
10373 				*(struct linger *)outvalp = *lgr;
10374 			} else {
10375 				if (!lgr->l_onoff) {
10376 					((struct linger *)
10377 					    outvalp)->l_onoff = 0;
10378 					((struct linger *)
10379 					    outvalp)->l_linger = 0;
10380 				} else {
10381 					/* struct copy */
10382 					*(struct linger *)outvalp = *lgr;
10383 				}
10384 			}
10385 			*outlenp = sizeof (struct linger);
10386 			return (0);
10387 		}
10388 		case SO_DEBUG:
10389 			if (!checkonly)
10390 				tcp->tcp_debug = onoff;
10391 			break;
10392 		case SO_KEEPALIVE:
10393 			if (checkonly) {
10394 				/* T_CHECK case */
10395 				break;
10396 			}
10397 
10398 			if (!onoff) {
10399 				if (tcp->tcp_ka_enabled) {
10400 					if (tcp->tcp_ka_tid != 0) {
10401 						(void) TCP_TIMER_CANCEL(tcp,
10402 						    tcp->tcp_ka_tid);
10403 						tcp->tcp_ka_tid = 0;
10404 					}
10405 					tcp->tcp_ka_enabled = 0;
10406 				}
10407 				break;
10408 			}
10409 			if (!tcp->tcp_ka_enabled) {
10410 				/* Crank up the keepalive timer */
10411 				tcp->tcp_ka_last_intrvl = 0;
10412 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
10413 				    tcp_keepalive_killer,
10414 				    MSEC_TO_TICK(tcp->tcp_ka_interval));
10415 				tcp->tcp_ka_enabled = 1;
10416 			}
10417 			break;
10418 		case SO_DONTROUTE:
10419 			/*
10420 			 * SO_DONTROUTE, SO_USELOOPBACK, and SO_BROADCAST are
10421 			 * only of interest to IP.  We track them here only so
10422 			 * that we can report their current value.
10423 			 */
10424 			if (!checkonly) {
10425 				tcp->tcp_dontroute = onoff;
10426 				tcp->tcp_connp->conn_dontroute = onoff;
10427 			}
10428 			break;
10429 		case SO_USELOOPBACK:
10430 			if (!checkonly) {
10431 				tcp->tcp_useloopback = onoff;
10432 				tcp->tcp_connp->conn_loopback = onoff;
10433 			}
10434 			break;
10435 		case SO_BROADCAST:
10436 			if (!checkonly) {
10437 				tcp->tcp_broadcast = onoff;
10438 				tcp->tcp_connp->conn_broadcast = onoff;
10439 			}
10440 			break;
10441 		case SO_REUSEADDR:
10442 			if (!checkonly) {
10443 				tcp->tcp_reuseaddr = onoff;
10444 				tcp->tcp_connp->conn_reuseaddr = onoff;
10445 			}
10446 			break;
10447 		case SO_OOBINLINE:
10448 			if (!checkonly)
10449 				tcp->tcp_oobinline = onoff;
10450 			break;
10451 		case SO_DGRAM_ERRIND:
10452 			if (!checkonly)
10453 				tcp->tcp_dgram_errind = onoff;
10454 			break;
10455 		case SO_SNDBUF: {
10456 			if (*i1 > tcps->tcps_max_buf) {
10457 				*outlenp = 0;
10458 				return (ENOBUFS);
10459 			}
10460 			if (checkonly)
10461 				break;
10462 
10463 			tcp->tcp_xmit_hiwater = *i1;
10464 			if (tcps->tcps_snd_lowat_fraction != 0)
10465 				tcp->tcp_xmit_lowater =
10466 				    tcp->tcp_xmit_hiwater /
10467 				    tcps->tcps_snd_lowat_fraction;
10468 			(void) tcp_maxpsz_set(tcp, B_TRUE);
10469 			/*
10470 			 * If we are flow-controlled, recheck the condition.
10471 			 * There are apps that increase SO_SNDBUF size when
10472 			 * flow-controlled (EWOULDBLOCK), and expect the flow
10473 			 * control condition to be lifted right away.
10474 			 */
10475 			mutex_enter(&tcp->tcp_non_sq_lock);
10476 			if (tcp->tcp_flow_stopped &&
10477 			    TCP_UNSENT_BYTES(tcp) < tcp->tcp_xmit_hiwater) {
10478 				tcp_clrqfull(tcp);
10479 			}
10480 			mutex_exit(&tcp->tcp_non_sq_lock);
10481 			break;
10482 		}
10483 		case SO_RCVBUF:
10484 			if (*i1 > tcps->tcps_max_buf) {
10485 				*outlenp = 0;
10486 				return (ENOBUFS);
10487 			}
10488 			/* Silently ignore zero */
10489 			if (!checkonly && *i1 != 0) {
10490 				*i1 = MSS_ROUNDUP(*i1, tcp->tcp_mss);
10491 				(void) tcp_rwnd_set(tcp, *i1);
10492 			}
10493 			/*
10494 			 * XXX should we return the rwnd here
10495 			 * and tcp_opt_get ?
10496 			 */
10497 			break;
10498 		case SO_SND_COPYAVOID:
10499 			if (!checkonly) {
10500 				/* we only allow enable at most once for now */
10501 				if (tcp->tcp_loopback ||
10502 				    (tcp->tcp_kssl_ctx != NULL) ||
10503 				    (!tcp->tcp_snd_zcopy_aware &&
10504 				    (onoff != 1 || !tcp_zcopy_check(tcp)))) {
10505 					*outlenp = 0;
10506 					return (EOPNOTSUPP);
10507 				}
10508 				tcp->tcp_snd_zcopy_aware = 1;
10509 			}
10510 			break;
10511 		case SO_ALLZONES:
10512 			/* Pass option along to IP level for handling */
10513 			return (-EINVAL);
10514 		case SO_ANON_MLP:
10515 			/* Pass option along to IP level for handling */
10516 			return (-EINVAL);
10517 		case SO_MAC_EXEMPT:
10518 			/* Pass option along to IP level for handling */
10519 			return (-EINVAL);
10520 		case SO_EXCLBIND:
10521 			if (!checkonly)
10522 				tcp->tcp_exclbind = onoff;
10523 			break;
10524 		default:
10525 			*outlenp = 0;
10526 			return (EINVAL);
10527 		}
10528 		break;
10529 	case IPPROTO_TCP:
10530 		switch (name) {
10531 		case TCP_NODELAY:
10532 			if (!checkonly)
10533 				tcp->tcp_naglim = *i1 ? 1 : tcp->tcp_mss;
10534 			break;
10535 		case TCP_NOTIFY_THRESHOLD:
10536 			if (!checkonly)
10537 				tcp->tcp_first_timer_threshold = *i1;
10538 			break;
10539 		case TCP_ABORT_THRESHOLD:
10540 			if (!checkonly)
10541 				tcp->tcp_second_timer_threshold = *i1;
10542 			break;
10543 		case TCP_CONN_NOTIFY_THRESHOLD:
10544 			if (!checkonly)
10545 				tcp->tcp_first_ctimer_threshold = *i1;
10546 			break;
10547 		case TCP_CONN_ABORT_THRESHOLD:
10548 			if (!checkonly)
10549 				tcp->tcp_second_ctimer_threshold = *i1;
10550 			break;
10551 		case TCP_RECVDSTADDR:
10552 			if (tcp->tcp_state > TCPS_LISTEN)
10553 				return (EOPNOTSUPP);
10554 			if (!checkonly)
10555 				tcp->tcp_recvdstaddr = onoff;
10556 			break;
10557 		case TCP_ANONPRIVBIND:
10558 			if ((reterr = secpolicy_net_privaddr(cr, 0,
10559 			    IPPROTO_TCP)) != 0) {
10560 				*outlenp = 0;
10561 				return (reterr);
10562 			}
10563 			if (!checkonly) {
10564 				tcp->tcp_anon_priv_bind = onoff;
10565 			}
10566 			break;
10567 		case TCP_EXCLBIND:
10568 			if (!checkonly)
10569 				tcp->tcp_exclbind = onoff;
10570 			break;	/* goto sizeof (int) option return */
10571 		case TCP_INIT_CWND: {
10572 			uint32_t init_cwnd = *((uint32_t *)invalp);
10573 
10574 			if (checkonly)
10575 				break;
10576 
10577 			/*
10578 			 * Only allow socket with network configuration
10579 			 * privilege to set the initial cwnd to be larger
10580 			 * than allowed by RFC 3390.
10581 			 */
10582 			if (init_cwnd <= MIN(4, MAX(2, 4380 / tcp->tcp_mss))) {
10583 				tcp->tcp_init_cwnd = init_cwnd;
10584 				break;
10585 			}
10586 			if ((reterr = secpolicy_ip_config(cr, B_TRUE)) != 0) {
10587 				*outlenp = 0;
10588 				return (reterr);
10589 			}
10590 			if (init_cwnd > TCP_MAX_INIT_CWND) {
10591 				*outlenp = 0;
10592 				return (EINVAL);
10593 			}
10594 			tcp->tcp_init_cwnd = init_cwnd;
10595 			break;
10596 		}
10597 		case TCP_KEEPALIVE_THRESHOLD:
10598 			if (checkonly)
10599 				break;
10600 
10601 			if (*i1 < tcps->tcps_keepalive_interval_low ||
10602 			    *i1 > tcps->tcps_keepalive_interval_high) {
10603 				*outlenp = 0;
10604 				return (EINVAL);
10605 			}
10606 			if (*i1 != tcp->tcp_ka_interval) {
10607 				tcp->tcp_ka_interval = *i1;
10608 				/*
10609 				 * Check if we need to restart the
10610 				 * keepalive timer.
10611 				 */
10612 				if (tcp->tcp_ka_tid != 0) {
10613 					ASSERT(tcp->tcp_ka_enabled);
10614 					(void) TCP_TIMER_CANCEL(tcp,
10615 					    tcp->tcp_ka_tid);
10616 					tcp->tcp_ka_last_intrvl = 0;
10617 					tcp->tcp_ka_tid = TCP_TIMER(tcp,
10618 					    tcp_keepalive_killer,
10619 					    MSEC_TO_TICK(tcp->tcp_ka_interval));
10620 				}
10621 			}
10622 			break;
10623 		case TCP_KEEPALIVE_ABORT_THRESHOLD:
10624 			if (!checkonly) {
10625 				if (*i1 <
10626 				    tcps->tcps_keepalive_abort_interval_low ||
10627 				    *i1 >
10628 				    tcps->tcps_keepalive_abort_interval_high) {
10629 					*outlenp = 0;
10630 					return (EINVAL);
10631 				}
10632 				tcp->tcp_ka_abort_thres = *i1;
10633 			}
10634 			break;
10635 		case TCP_CORK:
10636 			if (!checkonly) {
10637 				/*
10638 				 * if tcp->tcp_cork was set and is now
10639 				 * being unset, we have to make sure that
10640 				 * the remaining data gets sent out. Also
10641 				 * unset tcp->tcp_cork so that tcp_wput_data()
10642 				 * can send data even if it is less than mss
10643 				 */
10644 				if (tcp->tcp_cork && onoff == 0 &&
10645 				    tcp->tcp_unsent > 0) {
10646 					tcp->tcp_cork = B_FALSE;
10647 					tcp_wput_data(tcp, NULL, B_FALSE);
10648 				}
10649 				tcp->tcp_cork = onoff;
10650 			}
10651 			break;
10652 		default:
10653 			*outlenp = 0;
10654 			return (EINVAL);
10655 		}
10656 		break;
10657 	case IPPROTO_IP:
10658 		if (tcp->tcp_family != AF_INET) {
10659 			*outlenp = 0;
10660 			return (ENOPROTOOPT);
10661 		}
10662 		switch (name) {
10663 		case IP_OPTIONS:
10664 		case T_IP_OPTIONS:
10665 			reterr = tcp_opt_set_header(tcp, checkonly,
10666 			    invalp, inlen);
10667 			if (reterr) {
10668 				*outlenp = 0;
10669 				return (reterr);
10670 			}
10671 			/* OK return - copy input buffer into output buffer */
10672 			if (invalp != outvalp) {
10673 				/* don't trust bcopy for identical src/dst */
10674 				bcopy(invalp, outvalp, inlen);
10675 			}
10676 			*outlenp = inlen;
10677 			return (0);
10678 		case IP_TOS:
10679 		case T_IP_TOS:
10680 			if (!checkonly) {
10681 				tcp->tcp_ipha->ipha_type_of_service =
10682 				    (uchar_t)*i1;
10683 				tcp->tcp_tos = (uchar_t)*i1;
10684 			}
10685 			break;
10686 		case IP_TTL:
10687 			if (!checkonly) {
10688 				tcp->tcp_ipha->ipha_ttl = (uchar_t)*i1;
10689 				tcp->tcp_ttl = (uchar_t)*i1;
10690 			}
10691 			break;
10692 		case IP_BOUND_IF:
10693 		case IP_NEXTHOP:
10694 			/* Handled at the IP level */
10695 			return (-EINVAL);
10696 		case IP_SEC_OPT:
10697 			/*
10698 			 * We should not allow policy setting after
10699 			 * we start listening for connections.
10700 			 */
10701 			if (tcp->tcp_state == TCPS_LISTEN) {
10702 				return (EINVAL);
10703 			} else {
10704 				/* Handled at the IP level */
10705 				return (-EINVAL);
10706 			}
10707 		default:
10708 			*outlenp = 0;
10709 			return (EINVAL);
10710 		}
10711 		break;
10712 	case IPPROTO_IPV6: {
10713 		ip6_pkt_t		*ipp;
10714 
10715 		/*
10716 		 * IPPROTO_IPV6 options are only supported for sockets
10717 		 * that are using IPv6 on the wire.
10718 		 */
10719 		if (tcp->tcp_ipversion != IPV6_VERSION) {
10720 			*outlenp = 0;
10721 			return (ENOPROTOOPT);
10722 		}
10723 		/*
10724 		 * Only sticky options; no ancillary data
10725 		 */
10726 		ASSERT(thisdg_attrs == NULL);
10727 		ipp = &tcp->tcp_sticky_ipp;
10728 
10729 		switch (name) {
10730 		case IPV6_UNICAST_HOPS:
10731 			/* -1 means use default */
10732 			if (*i1 < -1 || *i1 > IPV6_MAX_HOPS) {
10733 				*outlenp = 0;
10734 				return (EINVAL);
10735 			}
10736 			if (!checkonly) {
10737 				if (*i1 == -1) {
10738 					tcp->tcp_ip6h->ip6_hops =
10739 					    ipp->ipp_unicast_hops =
10740 					    (uint8_t)tcps->tcps_ipv6_hoplimit;
10741 					ipp->ipp_fields &= ~IPPF_UNICAST_HOPS;
10742 					/* Pass modified value to IP. */
10743 					*i1 = tcp->tcp_ip6h->ip6_hops;
10744 				} else {
10745 					tcp->tcp_ip6h->ip6_hops =
10746 					    ipp->ipp_unicast_hops =
10747 					    (uint8_t)*i1;
10748 					ipp->ipp_fields |= IPPF_UNICAST_HOPS;
10749 				}
10750 				reterr = tcp_build_hdrs(q, tcp);
10751 				if (reterr != 0)
10752 					return (reterr);
10753 			}
10754 			break;
10755 		case IPV6_BOUND_IF:
10756 			if (!checkonly) {
10757 				int error = 0;
10758 
10759 				tcp->tcp_bound_if = *i1;
10760 				error = ip_opt_set_ill(tcp->tcp_connp, *i1,
10761 				    B_TRUE, checkonly, level, name, mblk);
10762 				if (error != 0) {
10763 					*outlenp = 0;
10764 					return (error);
10765 				}
10766 			}
10767 			break;
10768 		/*
10769 		 * Set boolean switches for ancillary data delivery
10770 		 */
10771 		case IPV6_RECVPKTINFO:
10772 			if (!checkonly) {
10773 				if (onoff)
10774 					tcp->tcp_ipv6_recvancillary |=
10775 					    TCP_IPV6_RECVPKTINFO;
10776 				else
10777 					tcp->tcp_ipv6_recvancillary &=
10778 					    ~TCP_IPV6_RECVPKTINFO;
10779 				/* Force it to be sent up with the next msg */
10780 				tcp->tcp_recvifindex = 0;
10781 			}
10782 			break;
10783 		case IPV6_RECVTCLASS:
10784 			if (!checkonly) {
10785 				if (onoff)
10786 					tcp->tcp_ipv6_recvancillary |=
10787 					    TCP_IPV6_RECVTCLASS;
10788 				else
10789 					tcp->tcp_ipv6_recvancillary &=
10790 					    ~TCP_IPV6_RECVTCLASS;
10791 			}
10792 			break;
10793 		case IPV6_RECVHOPLIMIT:
10794 			if (!checkonly) {
10795 				if (onoff)
10796 					tcp->tcp_ipv6_recvancillary |=
10797 					    TCP_IPV6_RECVHOPLIMIT;
10798 				else
10799 					tcp->tcp_ipv6_recvancillary &=
10800 					    ~TCP_IPV6_RECVHOPLIMIT;
10801 				/* Force it to be sent up with the next msg */
10802 				tcp->tcp_recvhops = 0xffffffffU;
10803 			}
10804 			break;
10805 		case IPV6_RECVHOPOPTS:
10806 			if (!checkonly) {
10807 				if (onoff)
10808 					tcp->tcp_ipv6_recvancillary |=
10809 					    TCP_IPV6_RECVHOPOPTS;
10810 				else
10811 					tcp->tcp_ipv6_recvancillary &=
10812 					    ~TCP_IPV6_RECVHOPOPTS;
10813 			}
10814 			break;
10815 		case IPV6_RECVDSTOPTS:
10816 			if (!checkonly) {
10817 				if (onoff)
10818 					tcp->tcp_ipv6_recvancillary |=
10819 					    TCP_IPV6_RECVDSTOPTS;
10820 				else
10821 					tcp->tcp_ipv6_recvancillary &=
10822 					    ~TCP_IPV6_RECVDSTOPTS;
10823 			}
10824 			break;
10825 		case _OLD_IPV6_RECVDSTOPTS:
10826 			if (!checkonly) {
10827 				if (onoff)
10828 					tcp->tcp_ipv6_recvancillary |=
10829 					    TCP_OLD_IPV6_RECVDSTOPTS;
10830 				else
10831 					tcp->tcp_ipv6_recvancillary &=
10832 					    ~TCP_OLD_IPV6_RECVDSTOPTS;
10833 			}
10834 			break;
10835 		case IPV6_RECVRTHDR:
10836 			if (!checkonly) {
10837 				if (onoff)
10838 					tcp->tcp_ipv6_recvancillary |=
10839 					    TCP_IPV6_RECVRTHDR;
10840 				else
10841 					tcp->tcp_ipv6_recvancillary &=
10842 					    ~TCP_IPV6_RECVRTHDR;
10843 			}
10844 			break;
10845 		case IPV6_RECVRTHDRDSTOPTS:
10846 			if (!checkonly) {
10847 				if (onoff)
10848 					tcp->tcp_ipv6_recvancillary |=
10849 					    TCP_IPV6_RECVRTDSTOPTS;
10850 				else
10851 					tcp->tcp_ipv6_recvancillary &=
10852 					    ~TCP_IPV6_RECVRTDSTOPTS;
10853 			}
10854 			break;
10855 		case IPV6_PKTINFO:
10856 			if (inlen != 0 && inlen != sizeof (struct in6_pktinfo))
10857 				return (EINVAL);
10858 			if (checkonly)
10859 				break;
10860 
10861 			if (inlen == 0) {
10862 				ipp->ipp_fields &= ~(IPPF_IFINDEX|IPPF_ADDR);
10863 			} else {
10864 				struct in6_pktinfo *pkti;
10865 
10866 				pkti = (struct in6_pktinfo *)invalp;
10867 				/*
10868 				 * RFC 3542 states that ipi6_addr must be
10869 				 * the unspecified address when setting the
10870 				 * IPV6_PKTINFO sticky socket option on a
10871 				 * TCP socket.
10872 				 */
10873 				if (!IN6_IS_ADDR_UNSPECIFIED(&pkti->ipi6_addr))
10874 					return (EINVAL);
10875 				/*
10876 				 * ip6_set_pktinfo() validates the source
10877 				 * address and interface index.
10878 				 */
10879 				reterr = ip6_set_pktinfo(cr, tcp->tcp_connp,
10880 				    pkti, mblk);
10881 				if (reterr != 0)
10882 					return (reterr);
10883 				ipp->ipp_ifindex = pkti->ipi6_ifindex;
10884 				ipp->ipp_addr = pkti->ipi6_addr;
10885 				if (ipp->ipp_ifindex != 0)
10886 					ipp->ipp_fields |= IPPF_IFINDEX;
10887 				else
10888 					ipp->ipp_fields &= ~IPPF_IFINDEX;
10889 				if (!IN6_IS_ADDR_UNSPECIFIED(&ipp->ipp_addr))
10890 					ipp->ipp_fields |= IPPF_ADDR;
10891 				else
10892 					ipp->ipp_fields &= ~IPPF_ADDR;
10893 			}
10894 			reterr = tcp_build_hdrs(q, tcp);
10895 			if (reterr != 0)
10896 				return (reterr);
10897 			break;
10898 		case IPV6_TCLASS:
10899 			if (inlen != 0 && inlen != sizeof (int))
10900 				return (EINVAL);
10901 			if (checkonly)
10902 				break;
10903 
10904 			if (inlen == 0) {
10905 				ipp->ipp_fields &= ~IPPF_TCLASS;
10906 			} else {
10907 				if (*i1 > 255 || *i1 < -1)
10908 					return (EINVAL);
10909 				if (*i1 == -1) {
10910 					ipp->ipp_tclass = 0;
10911 					*i1 = 0;
10912 				} else {
10913 					ipp->ipp_tclass = *i1;
10914 				}
10915 				ipp->ipp_fields |= IPPF_TCLASS;
10916 			}
10917 			reterr = tcp_build_hdrs(q, tcp);
10918 			if (reterr != 0)
10919 				return (reterr);
10920 			break;
10921 		case IPV6_NEXTHOP:
10922 			/*
10923 			 * IP will verify that the nexthop is reachable
10924 			 * and fail for sticky options.
10925 			 */
10926 			if (inlen != 0 && inlen != sizeof (sin6_t))
10927 				return (EINVAL);
10928 			if (checkonly)
10929 				break;
10930 
10931 			if (inlen == 0) {
10932 				ipp->ipp_fields &= ~IPPF_NEXTHOP;
10933 			} else {
10934 				sin6_t *sin6 = (sin6_t *)invalp;
10935 
10936 				if (sin6->sin6_family != AF_INET6)
10937 					return (EAFNOSUPPORT);
10938 				if (IN6_IS_ADDR_V4MAPPED(
10939 				    &sin6->sin6_addr))
10940 					return (EADDRNOTAVAIL);
10941 				ipp->ipp_nexthop = sin6->sin6_addr;
10942 				if (!IN6_IS_ADDR_UNSPECIFIED(
10943 				    &ipp->ipp_nexthop))
10944 					ipp->ipp_fields |= IPPF_NEXTHOP;
10945 				else
10946 					ipp->ipp_fields &= ~IPPF_NEXTHOP;
10947 			}
10948 			reterr = tcp_build_hdrs(q, tcp);
10949 			if (reterr != 0)
10950 				return (reterr);
10951 			break;
10952 		case IPV6_HOPOPTS: {
10953 			ip6_hbh_t *hopts = (ip6_hbh_t *)invalp;
10954 
10955 			/*
10956 			 * Sanity checks - minimum size, size a multiple of
10957 			 * eight bytes, and matching size passed in.
10958 			 */
10959 			if (inlen != 0 &&
10960 			    inlen != (8 * (hopts->ip6h_len + 1)))
10961 				return (EINVAL);
10962 
10963 			if (checkonly)
10964 				break;
10965 
10966 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10967 			    (uchar_t **)&ipp->ipp_hopopts,
10968 			    &ipp->ipp_hopoptslen, tcp->tcp_label_len);
10969 			if (reterr != 0)
10970 				return (reterr);
10971 			if (ipp->ipp_hopoptslen == 0)
10972 				ipp->ipp_fields &= ~IPPF_HOPOPTS;
10973 			else
10974 				ipp->ipp_fields |= IPPF_HOPOPTS;
10975 			reterr = tcp_build_hdrs(q, tcp);
10976 			if (reterr != 0)
10977 				return (reterr);
10978 			break;
10979 		}
10980 		case IPV6_RTHDRDSTOPTS: {
10981 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
10982 
10983 			/*
10984 			 * Sanity checks - minimum size, size a multiple of
10985 			 * eight bytes, and matching size passed in.
10986 			 */
10987 			if (inlen != 0 &&
10988 			    inlen != (8 * (dopts->ip6d_len + 1)))
10989 				return (EINVAL);
10990 
10991 			if (checkonly)
10992 				break;
10993 
10994 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
10995 			    (uchar_t **)&ipp->ipp_rtdstopts,
10996 			    &ipp->ipp_rtdstoptslen, 0);
10997 			if (reterr != 0)
10998 				return (reterr);
10999 			if (ipp->ipp_rtdstoptslen == 0)
11000 				ipp->ipp_fields &= ~IPPF_RTDSTOPTS;
11001 			else
11002 				ipp->ipp_fields |= IPPF_RTDSTOPTS;
11003 			reterr = tcp_build_hdrs(q, tcp);
11004 			if (reterr != 0)
11005 				return (reterr);
11006 			break;
11007 		}
11008 		case IPV6_DSTOPTS: {
11009 			ip6_dest_t *dopts = (ip6_dest_t *)invalp;
11010 
11011 			/*
11012 			 * Sanity checks - minimum size, size a multiple of
11013 			 * eight bytes, and matching size passed in.
11014 			 */
11015 			if (inlen != 0 &&
11016 			    inlen != (8 * (dopts->ip6d_len + 1)))
11017 				return (EINVAL);
11018 
11019 			if (checkonly)
11020 				break;
11021 
11022 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
11023 			    (uchar_t **)&ipp->ipp_dstopts,
11024 			    &ipp->ipp_dstoptslen, 0);
11025 			if (reterr != 0)
11026 				return (reterr);
11027 			if (ipp->ipp_dstoptslen == 0)
11028 				ipp->ipp_fields &= ~IPPF_DSTOPTS;
11029 			else
11030 				ipp->ipp_fields |= IPPF_DSTOPTS;
11031 			reterr = tcp_build_hdrs(q, tcp);
11032 			if (reterr != 0)
11033 				return (reterr);
11034 			break;
11035 		}
11036 		case IPV6_RTHDR: {
11037 			ip6_rthdr_t *rt = (ip6_rthdr_t *)invalp;
11038 
11039 			/*
11040 			 * Sanity checks - minimum size, size a multiple of
11041 			 * eight bytes, and matching size passed in.
11042 			 */
11043 			if (inlen != 0 &&
11044 			    inlen != (8 * (rt->ip6r_len + 1)))
11045 				return (EINVAL);
11046 
11047 			if (checkonly)
11048 				break;
11049 
11050 			reterr = optcom_pkt_set(invalp, inlen, B_TRUE,
11051 			    (uchar_t **)&ipp->ipp_rthdr,
11052 			    &ipp->ipp_rthdrlen, 0);
11053 			if (reterr != 0)
11054 				return (reterr);
11055 			if (ipp->ipp_rthdrlen == 0)
11056 				ipp->ipp_fields &= ~IPPF_RTHDR;
11057 			else
11058 				ipp->ipp_fields |= IPPF_RTHDR;
11059 			reterr = tcp_build_hdrs(q, tcp);
11060 			if (reterr != 0)
11061 				return (reterr);
11062 			break;
11063 		}
11064 		case IPV6_V6ONLY:
11065 			if (!checkonly)
11066 				tcp->tcp_connp->conn_ipv6_v6only = onoff;
11067 			break;
11068 		case IPV6_USE_MIN_MTU:
11069 			if (inlen != sizeof (int))
11070 				return (EINVAL);
11071 
11072 			if (*i1 < -1 || *i1 > 1)
11073 				return (EINVAL);
11074 
11075 			if (checkonly)
11076 				break;
11077 
11078 			ipp->ipp_fields |= IPPF_USE_MIN_MTU;
11079 			ipp->ipp_use_min_mtu = *i1;
11080 			break;
11081 		case IPV6_BOUND_PIF:
11082 			/* Handled at the IP level */
11083 			return (-EINVAL);
11084 		case IPV6_SEC_OPT:
11085 			/*
11086 			 * We should not allow policy setting after
11087 			 * we start listening for connections.
11088 			 */
11089 			if (tcp->tcp_state == TCPS_LISTEN) {
11090 				return (EINVAL);
11091 			} else {
11092 				/* Handled at the IP level */
11093 				return (-EINVAL);
11094 			}
11095 		case IPV6_SRC_PREFERENCES:
11096 			if (inlen != sizeof (uint32_t))
11097 				return (EINVAL);
11098 			reterr = ip6_set_src_preferences(tcp->tcp_connp,
11099 			    *(uint32_t *)invalp);
11100 			if (reterr != 0) {
11101 				*outlenp = 0;
11102 				return (reterr);
11103 			}
11104 			break;
11105 		default:
11106 			*outlenp = 0;
11107 			return (EINVAL);
11108 		}
11109 		break;
11110 	}		/* end IPPROTO_IPV6 */
11111 	default:
11112 		*outlenp = 0;
11113 		return (EINVAL);
11114 	}
11115 	/*
11116 	 * Common case of OK return with outval same as inval
11117 	 */
11118 	if (invalp != outvalp) {
11119 		/* don't trust bcopy for identical src/dst */
11120 		(void) bcopy(invalp, outvalp, inlen);
11121 	}
11122 	*outlenp = inlen;
11123 	return (0);
11124 }
11125 
11126 /*
11127  * Update tcp_sticky_hdrs based on tcp_sticky_ipp.
11128  * The headers include ip6i_t (if needed), ip6_t, any sticky extension
11129  * headers, and the maximum size tcp header (to avoid reallocation
11130  * on the fly for additional tcp options).
11131  * Returns failure if can't allocate memory.
11132  */
11133 static int
11134 tcp_build_hdrs(queue_t *q, tcp_t *tcp)
11135 {
11136 	char	*hdrs;
11137 	uint_t	hdrs_len;
11138 	ip6i_t	*ip6i;
11139 	char	buf[TCP_MAX_HDR_LENGTH];
11140 	ip6_pkt_t *ipp = &tcp->tcp_sticky_ipp;
11141 	in6_addr_t src, dst;
11142 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11143 
11144 	/*
11145 	 * save the existing tcp header and source/dest IP addresses
11146 	 */
11147 	bcopy(tcp->tcp_tcph, buf, tcp->tcp_tcp_hdr_len);
11148 	src = tcp->tcp_ip6h->ip6_src;
11149 	dst = tcp->tcp_ip6h->ip6_dst;
11150 	hdrs_len = ip_total_hdrs_len_v6(ipp) + TCP_MAX_HDR_LENGTH;
11151 	ASSERT(hdrs_len != 0);
11152 	if (hdrs_len > tcp->tcp_iphc_len) {
11153 		/* Need to reallocate */
11154 		hdrs = kmem_zalloc(hdrs_len, KM_NOSLEEP);
11155 		if (hdrs == NULL)
11156 			return (ENOMEM);
11157 		if (tcp->tcp_iphc != NULL) {
11158 			if (tcp->tcp_hdr_grown) {
11159 				kmem_free(tcp->tcp_iphc, tcp->tcp_iphc_len);
11160 			} else {
11161 				bzero(tcp->tcp_iphc, tcp->tcp_iphc_len);
11162 				kmem_cache_free(tcp_iphc_cache, tcp->tcp_iphc);
11163 			}
11164 			tcp->tcp_iphc_len = 0;
11165 		}
11166 		ASSERT(tcp->tcp_iphc_len == 0);
11167 		tcp->tcp_iphc = hdrs;
11168 		tcp->tcp_iphc_len = hdrs_len;
11169 		tcp->tcp_hdr_grown = B_TRUE;
11170 	}
11171 	ip_build_hdrs_v6((uchar_t *)tcp->tcp_iphc,
11172 	    hdrs_len - TCP_MAX_HDR_LENGTH, ipp, IPPROTO_TCP);
11173 
11174 	/* Set header fields not in ipp */
11175 	if (ipp->ipp_fields & IPPF_HAS_IP6I) {
11176 		ip6i = (ip6i_t *)tcp->tcp_iphc;
11177 		tcp->tcp_ip6h = (ip6_t *)&ip6i[1];
11178 	} else {
11179 		tcp->tcp_ip6h = (ip6_t *)tcp->tcp_iphc;
11180 	}
11181 	/*
11182 	 * tcp->tcp_ip_hdr_len will include ip6i_t if there is one.
11183 	 *
11184 	 * tcp->tcp_tcp_hdr_len doesn't change here.
11185 	 */
11186 	tcp->tcp_ip_hdr_len = hdrs_len - TCP_MAX_HDR_LENGTH;
11187 	tcp->tcp_tcph = (tcph_t *)(tcp->tcp_iphc + tcp->tcp_ip_hdr_len);
11188 	tcp->tcp_hdr_len = tcp->tcp_ip_hdr_len + tcp->tcp_tcp_hdr_len;
11189 
11190 	bcopy(buf, tcp->tcp_tcph, tcp->tcp_tcp_hdr_len);
11191 
11192 	tcp->tcp_ip6h->ip6_src = src;
11193 	tcp->tcp_ip6h->ip6_dst = dst;
11194 
11195 	/*
11196 	 * If the hop limit was not set by ip_build_hdrs_v6(), set it to
11197 	 * the default value for TCP.
11198 	 */
11199 	if (!(ipp->ipp_fields & IPPF_UNICAST_HOPS))
11200 		tcp->tcp_ip6h->ip6_hops = tcps->tcps_ipv6_hoplimit;
11201 
11202 	/*
11203 	 * If we're setting extension headers after a connection
11204 	 * has been established, and if we have a routing header
11205 	 * among the extension headers, call ip_massage_options_v6 to
11206 	 * manipulate the routing header/ip6_dst set the checksum
11207 	 * difference in the tcp header template.
11208 	 * (This happens in tcp_connect_ipv6 if the routing header
11209 	 * is set prior to the connect.)
11210 	 * Set the tcp_sum to zero first in case we've cleared a
11211 	 * routing header or don't have one at all.
11212 	 */
11213 	tcp->tcp_sum = 0;
11214 	if ((tcp->tcp_state >= TCPS_SYN_SENT) &&
11215 	    (tcp->tcp_ipp_fields & IPPF_RTHDR)) {
11216 		ip6_rthdr_t *rth = ip_find_rthdr_v6(tcp->tcp_ip6h,
11217 		    (uint8_t *)tcp->tcp_tcph);
11218 		if (rth != NULL) {
11219 			tcp->tcp_sum = ip_massage_options_v6(tcp->tcp_ip6h,
11220 			    rth, tcps->tcps_netstack);
11221 			tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) +
11222 			    (tcp->tcp_sum >> 16));
11223 		}
11224 	}
11225 
11226 	/* Try to get everything in a single mblk */
11227 	(void) mi_set_sth_wroff(RD(q), hdrs_len + tcps->tcps_wroff_xtra);
11228 	return (0);
11229 }
11230 
11231 /*
11232  * Transfer any source route option from ipha to buf/dst in reversed form.
11233  */
11234 static int
11235 tcp_opt_rev_src_route(ipha_t *ipha, char *buf, uchar_t *dst)
11236 {
11237 	ipoptp_t	opts;
11238 	uchar_t		*opt;
11239 	uint8_t		optval;
11240 	uint8_t		optlen;
11241 	uint32_t	len = 0;
11242 
11243 	for (optval = ipoptp_first(&opts, ipha);
11244 	    optval != IPOPT_EOL;
11245 	    optval = ipoptp_next(&opts)) {
11246 		opt = opts.ipoptp_cur;
11247 		optlen = opts.ipoptp_len;
11248 		switch (optval) {
11249 			int	off1, off2;
11250 		case IPOPT_SSRR:
11251 		case IPOPT_LSRR:
11252 
11253 			/* Reverse source route */
11254 			/*
11255 			 * First entry should be the next to last one in the
11256 			 * current source route (the last entry is our
11257 			 * address.)
11258 			 * The last entry should be the final destination.
11259 			 */
11260 			buf[IPOPT_OPTVAL] = (uint8_t)optval;
11261 			buf[IPOPT_OLEN] = (uint8_t)optlen;
11262 			off1 = IPOPT_MINOFF_SR - 1;
11263 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
11264 			if (off2 < 0) {
11265 				/* No entries in source route */
11266 				break;
11267 			}
11268 			bcopy(opt + off2, dst, IP_ADDR_LEN);
11269 			/*
11270 			 * Note: use src since ipha has not had its src
11271 			 * and dst reversed (it is in the state it was
11272 			 * received.
11273 			 */
11274 			bcopy(&ipha->ipha_src, buf + off2,
11275 			    IP_ADDR_LEN);
11276 			off2 -= IP_ADDR_LEN;
11277 
11278 			while (off2 > 0) {
11279 				bcopy(opt + off2, buf + off1,
11280 				    IP_ADDR_LEN);
11281 				off1 += IP_ADDR_LEN;
11282 				off2 -= IP_ADDR_LEN;
11283 			}
11284 			buf[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
11285 			buf += optlen;
11286 			len += optlen;
11287 			break;
11288 		}
11289 	}
11290 done:
11291 	/* Pad the resulting options */
11292 	while (len & 0x3) {
11293 		*buf++ = IPOPT_EOL;
11294 		len++;
11295 	}
11296 	return (len);
11297 }
11298 
11299 
11300 /*
11301  * Extract and revert a source route from ipha (if any)
11302  * and then update the relevant fields in both tcp_t and the standard header.
11303  */
11304 static void
11305 tcp_opt_reverse(tcp_t *tcp, ipha_t *ipha)
11306 {
11307 	char	buf[TCP_MAX_HDR_LENGTH];
11308 	uint_t	tcph_len;
11309 	int	len;
11310 
11311 	ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
11312 	len = IPH_HDR_LENGTH(ipha);
11313 	if (len == IP_SIMPLE_HDR_LENGTH)
11314 		/* Nothing to do */
11315 		return;
11316 	if (len > IP_SIMPLE_HDR_LENGTH + TCP_MAX_IP_OPTIONS_LENGTH ||
11317 	    (len & 0x3))
11318 		return;
11319 
11320 	tcph_len = tcp->tcp_tcp_hdr_len;
11321 	bcopy(tcp->tcp_tcph, buf, tcph_len);
11322 	tcp->tcp_sum = (tcp->tcp_ipha->ipha_dst >> 16) +
11323 	    (tcp->tcp_ipha->ipha_dst & 0xffff);
11324 	len = tcp_opt_rev_src_route(ipha, (char *)tcp->tcp_ipha +
11325 	    IP_SIMPLE_HDR_LENGTH, (uchar_t *)&tcp->tcp_ipha->ipha_dst);
11326 	len += IP_SIMPLE_HDR_LENGTH;
11327 	tcp->tcp_sum -= ((tcp->tcp_ipha->ipha_dst >> 16) +
11328 	    (tcp->tcp_ipha->ipha_dst & 0xffff));
11329 	if ((int)tcp->tcp_sum < 0)
11330 		tcp->tcp_sum--;
11331 	tcp->tcp_sum = (tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16);
11332 	tcp->tcp_sum = ntohs((tcp->tcp_sum & 0xFFFF) + (tcp->tcp_sum >> 16));
11333 	tcp->tcp_tcph = (tcph_t *)((char *)tcp->tcp_ipha + len);
11334 	bcopy(buf, tcp->tcp_tcph, tcph_len);
11335 	tcp->tcp_ip_hdr_len = len;
11336 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11337 	    (IP_VERSION << 4) | (len >> 2);
11338 	len += tcph_len;
11339 	tcp->tcp_hdr_len = len;
11340 }
11341 
11342 /*
11343  * Copy the standard header into its new location,
11344  * lay in the new options and then update the relevant
11345  * fields in both tcp_t and the standard header.
11346  */
11347 static int
11348 tcp_opt_set_header(tcp_t *tcp, boolean_t checkonly, uchar_t *ptr, uint_t len)
11349 {
11350 	uint_t	tcph_len;
11351 	uint8_t	*ip_optp;
11352 	tcph_t	*new_tcph;
11353 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11354 
11355 	if ((len > TCP_MAX_IP_OPTIONS_LENGTH) || (len & 0x3))
11356 		return (EINVAL);
11357 
11358 	if (len > IP_MAX_OPT_LENGTH - tcp->tcp_label_len)
11359 		return (EINVAL);
11360 
11361 	if (checkonly) {
11362 		/*
11363 		 * do not really set, just pretend to - T_CHECK
11364 		 */
11365 		return (0);
11366 	}
11367 
11368 	ip_optp = (uint8_t *)tcp->tcp_ipha + IP_SIMPLE_HDR_LENGTH;
11369 	if (tcp->tcp_label_len > 0) {
11370 		int padlen;
11371 		uint8_t opt;
11372 
11373 		/* convert list termination to no-ops */
11374 		padlen = tcp->tcp_label_len - ip_optp[IPOPT_OLEN];
11375 		ip_optp += ip_optp[IPOPT_OLEN];
11376 		opt = len > 0 ? IPOPT_NOP : IPOPT_EOL;
11377 		while (--padlen >= 0)
11378 			*ip_optp++ = opt;
11379 	}
11380 	tcph_len = tcp->tcp_tcp_hdr_len;
11381 	new_tcph = (tcph_t *)(ip_optp + len);
11382 	ovbcopy(tcp->tcp_tcph, new_tcph, tcph_len);
11383 	tcp->tcp_tcph = new_tcph;
11384 	bcopy(ptr, ip_optp, len);
11385 
11386 	len += IP_SIMPLE_HDR_LENGTH + tcp->tcp_label_len;
11387 
11388 	tcp->tcp_ip_hdr_len = len;
11389 	tcp->tcp_ipha->ipha_version_and_hdr_length =
11390 	    (IP_VERSION << 4) | (len >> 2);
11391 	tcp->tcp_hdr_len = len + tcph_len;
11392 	if (!TCP_IS_DETACHED(tcp)) {
11393 		/* Always allocate room for all options. */
11394 		(void) mi_set_sth_wroff(tcp->tcp_rq,
11395 		    TCP_MAX_COMBINED_HEADER_LENGTH + tcps->tcps_wroff_xtra);
11396 	}
11397 	return (0);
11398 }
11399 
11400 /* Get callback routine passed to nd_load by tcp_param_register */
11401 /* ARGSUSED */
11402 static int
11403 tcp_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
11404 {
11405 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11406 
11407 	(void) mi_mpprintf(mp, "%u", tcppa->tcp_param_val);
11408 	return (0);
11409 }
11410 
11411 /*
11412  * Walk through the param array specified registering each element with the
11413  * named dispatch handler.
11414  */
11415 static boolean_t
11416 tcp_param_register(IDP *ndp, tcpparam_t *tcppa, int cnt, tcp_stack_t *tcps)
11417 {
11418 	for (; cnt-- > 0; tcppa++) {
11419 		if (tcppa->tcp_param_name && tcppa->tcp_param_name[0]) {
11420 			if (!nd_load(ndp, tcppa->tcp_param_name,
11421 			    tcp_param_get, tcp_param_set,
11422 			    (caddr_t)tcppa)) {
11423 				nd_free(ndp);
11424 				return (B_FALSE);
11425 			}
11426 		}
11427 	}
11428 	tcps->tcps_wroff_xtra_param = kmem_zalloc(sizeof (tcpparam_t),
11429 	    KM_SLEEP);
11430 	bcopy(&lcl_tcp_wroff_xtra_param, tcps->tcps_wroff_xtra_param,
11431 	    sizeof (tcpparam_t));
11432 	if (!nd_load(ndp, tcps->tcps_wroff_xtra_param->tcp_param_name,
11433 	    tcp_param_get, tcp_param_set_aligned,
11434 	    (caddr_t)tcps->tcps_wroff_xtra_param)) {
11435 		nd_free(ndp);
11436 		return (B_FALSE);
11437 	}
11438 	tcps->tcps_mdt_head_param = kmem_zalloc(sizeof (tcpparam_t),
11439 	    KM_SLEEP);
11440 	bcopy(&lcl_tcp_mdt_head_param, tcps->tcps_mdt_head_param,
11441 	    sizeof (tcpparam_t));
11442 	if (!nd_load(ndp, tcps->tcps_mdt_head_param->tcp_param_name,
11443 	    tcp_param_get, tcp_param_set_aligned,
11444 	    (caddr_t)tcps->tcps_mdt_head_param)) {
11445 		nd_free(ndp);
11446 		return (B_FALSE);
11447 	}
11448 	tcps->tcps_mdt_tail_param = kmem_zalloc(sizeof (tcpparam_t),
11449 	    KM_SLEEP);
11450 	bcopy(&lcl_tcp_mdt_tail_param, tcps->tcps_mdt_tail_param,
11451 	    sizeof (tcpparam_t));
11452 	if (!nd_load(ndp, tcps->tcps_mdt_tail_param->tcp_param_name,
11453 	    tcp_param_get, tcp_param_set_aligned,
11454 	    (caddr_t)tcps->tcps_mdt_tail_param)) {
11455 		nd_free(ndp);
11456 		return (B_FALSE);
11457 	}
11458 	tcps->tcps_mdt_max_pbufs_param = kmem_zalloc(sizeof (tcpparam_t),
11459 	    KM_SLEEP);
11460 	bcopy(&lcl_tcp_mdt_max_pbufs_param, tcps->tcps_mdt_max_pbufs_param,
11461 	    sizeof (tcpparam_t));
11462 	if (!nd_load(ndp, tcps->tcps_mdt_max_pbufs_param->tcp_param_name,
11463 	    tcp_param_get, tcp_param_set_aligned,
11464 	    (caddr_t)tcps->tcps_mdt_max_pbufs_param)) {
11465 		nd_free(ndp);
11466 		return (B_FALSE);
11467 	}
11468 	if (!nd_load(ndp, "tcp_extra_priv_ports",
11469 	    tcp_extra_priv_ports_get, NULL, NULL)) {
11470 		nd_free(ndp);
11471 		return (B_FALSE);
11472 	}
11473 	if (!nd_load(ndp, "tcp_extra_priv_ports_add",
11474 	    NULL, tcp_extra_priv_ports_add, NULL)) {
11475 		nd_free(ndp);
11476 		return (B_FALSE);
11477 	}
11478 	if (!nd_load(ndp, "tcp_extra_priv_ports_del",
11479 	    NULL, tcp_extra_priv_ports_del, NULL)) {
11480 		nd_free(ndp);
11481 		return (B_FALSE);
11482 	}
11483 	if (!nd_load(ndp, "tcp_status", tcp_status_report, NULL,
11484 	    NULL)) {
11485 		nd_free(ndp);
11486 		return (B_FALSE);
11487 	}
11488 	if (!nd_load(ndp, "tcp_bind_hash", tcp_bind_hash_report,
11489 	    NULL, NULL)) {
11490 		nd_free(ndp);
11491 		return (B_FALSE);
11492 	}
11493 	if (!nd_load(ndp, "tcp_listen_hash",
11494 	    tcp_listen_hash_report, NULL, NULL)) {
11495 		nd_free(ndp);
11496 		return (B_FALSE);
11497 	}
11498 	if (!nd_load(ndp, "tcp_conn_hash", tcp_conn_hash_report,
11499 	    NULL, NULL)) {
11500 		nd_free(ndp);
11501 		return (B_FALSE);
11502 	}
11503 	if (!nd_load(ndp, "tcp_acceptor_hash",
11504 	    tcp_acceptor_hash_report, NULL, NULL)) {
11505 		nd_free(ndp);
11506 		return (B_FALSE);
11507 	}
11508 	if (!nd_load(ndp, "tcp_1948_phrase", NULL,
11509 	    tcp_1948_phrase_set, NULL)) {
11510 		nd_free(ndp);
11511 		return (B_FALSE);
11512 	}
11513 	/*
11514 	 * Dummy ndd variables - only to convey obsolescence information
11515 	 * through printing of their name (no get or set routines)
11516 	 * XXX Remove in future releases ?
11517 	 */
11518 	if (!nd_load(ndp,
11519 	    "tcp_close_wait_interval(obsoleted - "
11520 	    "use tcp_time_wait_interval)", NULL, NULL, NULL)) {
11521 		nd_free(ndp);
11522 		return (B_FALSE);
11523 	}
11524 	return (B_TRUE);
11525 }
11526 
11527 /* ndd set routine for tcp_wroff_xtra, tcp_mdt_hdr_{head,tail}_min. */
11528 /* ARGSUSED */
11529 static int
11530 tcp_param_set_aligned(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
11531     cred_t *cr)
11532 {
11533 	long new_value;
11534 	tcpparam_t *tcppa = (tcpparam_t *)cp;
11535 
11536 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11537 	    new_value < tcppa->tcp_param_min ||
11538 	    new_value > tcppa->tcp_param_max) {
11539 		return (EINVAL);
11540 	}
11541 	/*
11542 	 * Need to make sure new_value is a multiple of 4.  If it is not,
11543 	 * round it up.  For future 64 bit requirement, we actually make it
11544 	 * a multiple of 8.
11545 	 */
11546 	if (new_value & 0x7) {
11547 		new_value = (new_value & ~0x7) + 0x8;
11548 	}
11549 	tcppa->tcp_param_val = new_value;
11550 	return (0);
11551 }
11552 
11553 /* Set callback routine passed to nd_load by tcp_param_register */
11554 /* ARGSUSED */
11555 static int
11556 tcp_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *cr)
11557 {
11558 	long	new_value;
11559 	tcpparam_t	*tcppa = (tcpparam_t *)cp;
11560 
11561 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11562 	    new_value < tcppa->tcp_param_min ||
11563 	    new_value > tcppa->tcp_param_max) {
11564 		return (EINVAL);
11565 	}
11566 	tcppa->tcp_param_val = new_value;
11567 	return (0);
11568 }
11569 
11570 /*
11571  * Add a new piece to the tcp reassembly queue.  If the gap at the beginning
11572  * is filled, return as much as we can.  The message passed in may be
11573  * multi-part, chained using b_cont.  "start" is the starting sequence
11574  * number for this piece.
11575  */
11576 static mblk_t *
11577 tcp_reass(tcp_t *tcp, mblk_t *mp, uint32_t start)
11578 {
11579 	uint32_t	end;
11580 	mblk_t		*mp1;
11581 	mblk_t		*mp2;
11582 	mblk_t		*next_mp;
11583 	uint32_t	u1;
11584 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11585 
11586 	/* Walk through all the new pieces. */
11587 	do {
11588 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
11589 		    (uintptr_t)INT_MAX);
11590 		end = start + (int)(mp->b_wptr - mp->b_rptr);
11591 		next_mp = mp->b_cont;
11592 		if (start == end) {
11593 			/* Empty.  Blast it. */
11594 			freeb(mp);
11595 			continue;
11596 		}
11597 		mp->b_cont = NULL;
11598 		TCP_REASS_SET_SEQ(mp, start);
11599 		TCP_REASS_SET_END(mp, end);
11600 		mp1 = tcp->tcp_reass_tail;
11601 		if (!mp1) {
11602 			tcp->tcp_reass_tail = mp;
11603 			tcp->tcp_reass_head = mp;
11604 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11605 			UPDATE_MIB(&tcps->tcps_mib,
11606 			    tcpInDataUnorderBytes, end - start);
11607 			continue;
11608 		}
11609 		/* New stuff completely beyond tail? */
11610 		if (SEQ_GEQ(start, TCP_REASS_END(mp1))) {
11611 			/* Link it on end. */
11612 			mp1->b_cont = mp;
11613 			tcp->tcp_reass_tail = mp;
11614 			BUMP_MIB(&tcps->tcps_mib, tcpInDataUnorderSegs);
11615 			UPDATE_MIB(&tcps->tcps_mib,
11616 			    tcpInDataUnorderBytes, end - start);
11617 			continue;
11618 		}
11619 		mp1 = tcp->tcp_reass_head;
11620 		u1 = TCP_REASS_SEQ(mp1);
11621 		/* New stuff at the front? */
11622 		if (SEQ_LT(start, u1)) {
11623 			/* Yes... Check for overlap. */
11624 			mp->b_cont = mp1;
11625 			tcp->tcp_reass_head = mp;
11626 			tcp_reass_elim_overlap(tcp, mp);
11627 			continue;
11628 		}
11629 		/*
11630 		 * The new piece fits somewhere between the head and tail.
11631 		 * We find our slot, where mp1 precedes us and mp2 trails.
11632 		 */
11633 		for (; (mp2 = mp1->b_cont) != NULL; mp1 = mp2) {
11634 			u1 = TCP_REASS_SEQ(mp2);
11635 			if (SEQ_LEQ(start, u1))
11636 				break;
11637 		}
11638 		/* Link ourselves in */
11639 		mp->b_cont = mp2;
11640 		mp1->b_cont = mp;
11641 
11642 		/* Trim overlap with following mblk(s) first */
11643 		tcp_reass_elim_overlap(tcp, mp);
11644 
11645 		/* Trim overlap with preceding mblk */
11646 		tcp_reass_elim_overlap(tcp, mp1);
11647 
11648 	} while (start = end, mp = next_mp);
11649 	mp1 = tcp->tcp_reass_head;
11650 	/* Anything ready to go? */
11651 	if (TCP_REASS_SEQ(mp1) != tcp->tcp_rnxt)
11652 		return (NULL);
11653 	/* Eat what we can off the queue */
11654 	for (;;) {
11655 		mp = mp1->b_cont;
11656 		end = TCP_REASS_END(mp1);
11657 		TCP_REASS_SET_SEQ(mp1, 0);
11658 		TCP_REASS_SET_END(mp1, 0);
11659 		if (!mp) {
11660 			tcp->tcp_reass_tail = NULL;
11661 			break;
11662 		}
11663 		if (end != TCP_REASS_SEQ(mp)) {
11664 			mp1->b_cont = NULL;
11665 			break;
11666 		}
11667 		mp1 = mp;
11668 	}
11669 	mp1 = tcp->tcp_reass_head;
11670 	tcp->tcp_reass_head = mp;
11671 	return (mp1);
11672 }
11673 
11674 /* Eliminate any overlap that mp may have over later mblks */
11675 static void
11676 tcp_reass_elim_overlap(tcp_t *tcp, mblk_t *mp)
11677 {
11678 	uint32_t	end;
11679 	mblk_t		*mp1;
11680 	uint32_t	u1;
11681 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11682 
11683 	end = TCP_REASS_END(mp);
11684 	while ((mp1 = mp->b_cont) != NULL) {
11685 		u1 = TCP_REASS_SEQ(mp1);
11686 		if (!SEQ_GT(end, u1))
11687 			break;
11688 		if (!SEQ_GEQ(end, TCP_REASS_END(mp1))) {
11689 			mp->b_wptr -= end - u1;
11690 			TCP_REASS_SET_END(mp, u1);
11691 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPartDupSegs);
11692 			UPDATE_MIB(&tcps->tcps_mib,
11693 			    tcpInDataPartDupBytes, end - u1);
11694 			break;
11695 		}
11696 		mp->b_cont = mp1->b_cont;
11697 		TCP_REASS_SET_SEQ(mp1, 0);
11698 		TCP_REASS_SET_END(mp1, 0);
11699 		freeb(mp1);
11700 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
11701 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes, end - u1);
11702 	}
11703 	if (!mp1)
11704 		tcp->tcp_reass_tail = mp;
11705 }
11706 
11707 /*
11708  * Send up all messages queued on tcp_rcv_list.
11709  */
11710 static uint_t
11711 tcp_rcv_drain(queue_t *q, tcp_t *tcp)
11712 {
11713 	mblk_t *mp;
11714 	uint_t ret = 0;
11715 	uint_t thwin;
11716 #ifdef DEBUG
11717 	uint_t cnt = 0;
11718 #endif
11719 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11720 
11721 	/* Can't drain on an eager connection */
11722 	if (tcp->tcp_listener != NULL)
11723 		return (ret);
11724 
11725 	/* Can't be sodirect enabled */
11726 	ASSERT(SOD_NOT_ENABLED(tcp));
11727 
11728 	/* No need for the push timer now. */
11729 	if (tcp->tcp_push_tid != 0) {
11730 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11731 		tcp->tcp_push_tid = 0;
11732 	}
11733 
11734 	/*
11735 	 * Handle two cases here: we are currently fused or we were
11736 	 * previously fused and have some urgent data to be delivered
11737 	 * upstream.  The latter happens because we either ran out of
11738 	 * memory or were detached and therefore sending the SIGURG was
11739 	 * deferred until this point.  In either case we pass control
11740 	 * over to tcp_fuse_rcv_drain() since it may need to complete
11741 	 * some work.
11742 	 */
11743 	if ((tcp->tcp_fused || tcp->tcp_fused_sigurg)) {
11744 		ASSERT(tcp->tcp_fused_sigurg_mp != NULL);
11745 		if (tcp_fuse_rcv_drain(q, tcp, tcp->tcp_fused ? NULL :
11746 		    &tcp->tcp_fused_sigurg_mp))
11747 			return (ret);
11748 	}
11749 
11750 	while ((mp = tcp->tcp_rcv_list) != NULL) {
11751 		tcp->tcp_rcv_list = mp->b_next;
11752 		mp->b_next = NULL;
11753 #ifdef DEBUG
11754 		cnt += msgdsize(mp);
11755 #endif
11756 		/* Does this need SSL processing first? */
11757 		if ((tcp->tcp_kssl_ctx != NULL) && (DB_TYPE(mp) == M_DATA)) {
11758 			DTRACE_PROBE1(kssl_mblk__ksslinput_rcvdrain,
11759 			    mblk_t *, mp);
11760 			tcp_kssl_input(tcp, mp);
11761 			continue;
11762 		}
11763 		putnext(q, mp);
11764 	}
11765 	ASSERT(cnt == tcp->tcp_rcv_cnt);
11766 	tcp->tcp_rcv_last_head = NULL;
11767 	tcp->tcp_rcv_last_tail = NULL;
11768 	tcp->tcp_rcv_cnt = 0;
11769 
11770 	/* Learn the latest rwnd information that we sent to the other side. */
11771 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11772 	    << tcp->tcp_rcv_ws;
11773 	/* This is peer's calculated send window (our receive window). */
11774 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11775 	/*
11776 	 * Increase the receive window to max.  But we need to do receiver
11777 	 * SWS avoidance.  This means that we need to check the increase of
11778 	 * of receive window is at least 1 MSS.
11779 	 */
11780 	if (canputnext(q) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11781 		/*
11782 		 * If the window that the other side knows is less than max
11783 		 * deferred acks segments, send an update immediately.
11784 		 */
11785 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11786 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11787 			ret = TH_ACK_NEEDED;
11788 		}
11789 		tcp->tcp_rwnd = q->q_hiwat;
11790 	}
11791 	return (ret);
11792 }
11793 
11794 /*
11795  * Queue data on tcp_rcv_list which is a b_next chain.
11796  * tcp_rcv_last_head/tail is the last element of this chain.
11797  * Each element of the chain is a b_cont chain.
11798  *
11799  * M_DATA messages are added to the current element.
11800  * Other messages are added as new (b_next) elements.
11801  */
11802 void
11803 tcp_rcv_enqueue(tcp_t *tcp, mblk_t *mp, uint_t seg_len)
11804 {
11805 	ASSERT(seg_len == msgdsize(mp));
11806 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_rcv_last_head != NULL);
11807 
11808 	if (tcp->tcp_rcv_list == NULL) {
11809 		ASSERT(tcp->tcp_rcv_last_head == NULL);
11810 		tcp->tcp_rcv_list = mp;
11811 		tcp->tcp_rcv_last_head = mp;
11812 	} else if (DB_TYPE(mp) == DB_TYPE(tcp->tcp_rcv_last_head)) {
11813 		tcp->tcp_rcv_last_tail->b_cont = mp;
11814 	} else {
11815 		tcp->tcp_rcv_last_head->b_next = mp;
11816 		tcp->tcp_rcv_last_head = mp;
11817 	}
11818 
11819 	while (mp->b_cont)
11820 		mp = mp->b_cont;
11821 
11822 	tcp->tcp_rcv_last_tail = mp;
11823 	tcp->tcp_rcv_cnt += seg_len;
11824 	tcp->tcp_rwnd -= seg_len;
11825 }
11826 
11827 /*
11828  * The tcp_rcv_sod_XXX() functions enqueue data directly to the socket
11829  * above, in addition when uioa is enabled schedule an asynchronous uio
11830  * prior to enqueuing. They implement the combinhed semantics of the
11831  * tcp_rcv_XXX() functions, tcp_rcv_list push logic, and STREAMS putnext()
11832  * canputnext(), i.e. flow-control with backenable.
11833  *
11834  * tcp_sod_wakeup() is called where tcp_rcv_drain() would be called in the
11835  * non sodirect connection but as there are no tcp_tcv_list mblk_t's we deal
11836  * with the rcv_wnd and push timer and call the sodirect wakeup function.
11837  *
11838  * Must be called with sodp->sod_lockp held and will return with the lock
11839  * released.
11840  */
11841 static uint_t
11842 tcp_rcv_sod_wakeup(tcp_t *tcp, sodirect_t *sodp)
11843 {
11844 	queue_t		*q = tcp->tcp_rq;
11845 	uint_t		thwin;
11846 	tcp_stack_t	*tcps = tcp->tcp_tcps;
11847 	uint_t		ret = 0;
11848 
11849 	/* Can't be an eager connection */
11850 	ASSERT(tcp->tcp_listener == NULL);
11851 
11852 	/* Caller must have lock held */
11853 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11854 
11855 	/* Sodirect mode so must not be a tcp_rcv_list */
11856 	ASSERT(tcp->tcp_rcv_list == NULL);
11857 
11858 	if (SOD_QFULL(sodp)) {
11859 		/* Q is full, mark Q for need backenable */
11860 		SOD_QSETBE(sodp);
11861 	}
11862 	/* Last advertised rwnd, i.e. rwnd last sent in a packet */
11863 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
11864 	    << tcp->tcp_rcv_ws;
11865 	/* This is peer's calculated send window (our available rwnd). */
11866 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
11867 	/*
11868 	 * Increase the receive window to max.  But we need to do receiver
11869 	 * SWS avoidance.  This means that we need to check the increase of
11870 	 * of receive window is at least 1 MSS.
11871 	 */
11872 	if (!SOD_QFULL(sodp) && (q->q_hiwat - thwin >= tcp->tcp_mss)) {
11873 		/*
11874 		 * If the window that the other side knows is less than max
11875 		 * deferred acks segments, send an update immediately.
11876 		 */
11877 		if (thwin < tcp->tcp_rack_cur_max * tcp->tcp_mss) {
11878 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
11879 			ret = TH_ACK_NEEDED;
11880 		}
11881 		tcp->tcp_rwnd = q->q_hiwat;
11882 	}
11883 
11884 	if (!SOD_QEMPTY(sodp)) {
11885 		/* Wakeup to socket */
11886 		sodp->sod_state &= SOD_WAKE_CLR;
11887 		sodp->sod_state |= SOD_WAKE_DONE;
11888 		(sodp->sod_wakeup)(sodp);
11889 		/* wakeup() does the mutex_ext() */
11890 	} else {
11891 		/* Q is empty, no need to wake */
11892 		sodp->sod_state &= SOD_WAKE_CLR;
11893 		sodp->sod_state |= SOD_WAKE_NOT;
11894 		mutex_exit(sodp->sod_lockp);
11895 	}
11896 
11897 	/* No need for the push timer now. */
11898 	if (tcp->tcp_push_tid != 0) {
11899 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
11900 		tcp->tcp_push_tid = 0;
11901 	}
11902 
11903 	return (ret);
11904 }
11905 
11906 /*
11907  * Called where tcp_rcv_enqueue()/putnext(RD(q)) would be. For M_DATA
11908  * mblk_t's if uioa enabled then start a uioa asynchronous copy directly
11909  * to the user-land buffer and flag the mblk_t as such.
11910  *
11911  * Also, handle tcp_rwnd.
11912  */
11913 uint_t
11914 tcp_rcv_sod_enqueue(tcp_t *tcp, sodirect_t *sodp, mblk_t *mp, uint_t seg_len)
11915 {
11916 	uioa_t		*uioap = &sodp->sod_uioa;
11917 	boolean_t	qfull;
11918 	uint_t		thwin;
11919 
11920 	/* Can't be an eager connection */
11921 	ASSERT(tcp->tcp_listener == NULL);
11922 
11923 	/* Caller must have lock held */
11924 	ASSERT(MUTEX_HELD(sodp->sod_lockp));
11925 
11926 	/* Sodirect mode so must not be a tcp_rcv_list */
11927 	ASSERT(tcp->tcp_rcv_list == NULL);
11928 
11929 	/* Passed in segment length must be equal to mblk_t chain data size */
11930 	ASSERT(seg_len == msgdsize(mp));
11931 
11932 	if (DB_TYPE(mp) != M_DATA) {
11933 		/* Only process M_DATA mblk_t's */
11934 		goto enq;
11935 	}
11936 	if (uioap->uioa_state & UIOA_ENABLED) {
11937 		/* Uioa is enabled */
11938 		mblk_t		*mp1 = mp;
11939 		mblk_t		*lmp = NULL;
11940 
11941 		if (seg_len > uioap->uio_resid) {
11942 			/*
11943 			 * There isn't enough uio space for the mblk_t chain
11944 			 * so disable uioa such that this and any additional
11945 			 * mblk_t data is handled by the socket and schedule
11946 			 * the socket for wakeup to finish this uioa.
11947 			 */
11948 			uioap->uioa_state &= UIOA_CLR;
11949 			uioap->uioa_state |= UIOA_FINI;
11950 			if (sodp->sod_state & SOD_WAKE_NOT) {
11951 				sodp->sod_state &= SOD_WAKE_CLR;
11952 				sodp->sod_state |= SOD_WAKE_NEED;
11953 			}
11954 			goto enq;
11955 		}
11956 		do {
11957 			uint32_t	len = MBLKL(mp1);
11958 
11959 			if (!uioamove(mp1->b_rptr, len, UIO_READ, uioap)) {
11960 				/* Scheduled, mark dblk_t as such */
11961 				DB_FLAGS(mp1) |= DBLK_UIOA;
11962 			} else {
11963 				/* Error, turn off async processing */
11964 				uioap->uioa_state &= UIOA_CLR;
11965 				uioap->uioa_state |= UIOA_FINI;
11966 				break;
11967 			}
11968 			lmp = mp1;
11969 		} while ((mp1 = mp1->b_cont) != NULL);
11970 
11971 		if (mp1 != NULL || uioap->uio_resid == 0) {
11972 			/*
11973 			 * Not all mblk_t(s) uioamoved (error) or all uio
11974 			 * space has been consumed so schedule the socket
11975 			 * for wakeup to finish this uio.
11976 			 */
11977 			sodp->sod_state &= SOD_WAKE_CLR;
11978 			sodp->sod_state |= SOD_WAKE_NEED;
11979 
11980 			/* Break the mblk chain if neccessary. */
11981 			if (mp1 != NULL && lmp != NULL) {
11982 				mp->b_next = mp1;
11983 				lmp->b_cont = NULL;
11984 			}
11985 		}
11986 	} else if (uioap->uioa_state & UIOA_FINI) {
11987 		/*
11988 		 * Post UIO_ENABLED waiting for socket to finish processing
11989 		 * so just enqueue and update tcp_rwnd.
11990 		 */
11991 		if (SOD_QFULL(sodp))
11992 			tcp->tcp_rwnd -= seg_len;
11993 	} else if (sodp->sod_want > 0) {
11994 		/*
11995 		 * Uioa isn't enabled but sodirect has a pending read().
11996 		 */
11997 		if (SOD_QCNT(sodp) + seg_len >= sodp->sod_want) {
11998 			if (sodp->sod_state & SOD_WAKE_NOT) {
11999 				/* Schedule socket for wakeup */
12000 				sodp->sod_state &= SOD_WAKE_CLR;
12001 				sodp->sod_state |= SOD_WAKE_NEED;
12002 			}
12003 			tcp->tcp_rwnd -= seg_len;
12004 		}
12005 	} else if (SOD_QCNT(sodp) + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
12006 		/*
12007 		 * No pending sodirect read() so used the default
12008 		 * TCP push logic to guess that a push is needed.
12009 		 */
12010 		if (sodp->sod_state & SOD_WAKE_NOT) {
12011 			/* Schedule socket for wakeup */
12012 			sodp->sod_state &= SOD_WAKE_CLR;
12013 			sodp->sod_state |= SOD_WAKE_NEED;
12014 		}
12015 		tcp->tcp_rwnd -= seg_len;
12016 	} else {
12017 		/* Just update tcp_rwnd */
12018 		tcp->tcp_rwnd -= seg_len;
12019 	}
12020 enq:
12021 	qfull = SOD_QFULL(sodp);
12022 
12023 	(sodp->sod_enqueue)(sodp, mp);
12024 
12025 	if (! qfull && SOD_QFULL(sodp)) {
12026 		/* Wasn't QFULL, now QFULL, need back-enable */
12027 		SOD_QSETBE(sodp);
12028 	}
12029 
12030 	/*
12031 	 * Check to see if remote avail swnd < mss due to delayed ACK,
12032 	 * first get advertised rwnd.
12033 	 */
12034 	thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win));
12035 	/* Minus delayed ACK count */
12036 	thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
12037 	if (thwin < tcp->tcp_mss) {
12038 		/* Remote avail swnd < mss, need ACK now */
12039 		return (TH_ACK_NEEDED);
12040 	}
12041 
12042 	return (0);
12043 }
12044 
12045 /*
12046  * DEFAULT TCP ENTRY POINT via squeue on READ side.
12047  *
12048  * This is the default entry function into TCP on the read side. TCP is
12049  * always entered via squeue i.e. using squeue's for mutual exclusion.
12050  * When classifier does a lookup to find the tcp, it also puts a reference
12051  * on the conn structure associated so the tcp is guaranteed to exist
12052  * when we come here. We still need to check the state because it might
12053  * as well has been closed. The squeue processing function i.e. squeue_enter,
12054  * squeue_enter_nodrain, or squeue_drain is responsible for doing the
12055  * CONN_DEC_REF.
12056  *
12057  * Apart from the default entry point, IP also sends packets directly to
12058  * tcp_rput_data for AF_INET fast path and tcp_conn_request for incoming
12059  * connections.
12060  */
12061 void
12062 tcp_input(void *arg, mblk_t *mp, void *arg2)
12063 {
12064 	conn_t	*connp = (conn_t *)arg;
12065 	tcp_t	*tcp = (tcp_t *)connp->conn_tcp;
12066 
12067 	/* arg2 is the sqp */
12068 	ASSERT(arg2 != NULL);
12069 	ASSERT(mp != NULL);
12070 
12071 	/*
12072 	 * Don't accept any input on a closed tcp as this TCP logically does
12073 	 * not exist on the system. Don't proceed further with this TCP.
12074 	 * For eg. this packet could trigger another close of this tcp
12075 	 * which would be disastrous for tcp_refcnt. tcp_close_detached /
12076 	 * tcp_clean_death / tcp_closei_local must be called at most once
12077 	 * on a TCP. In this case we need to refeed the packet into the
12078 	 * classifier and figure out where the packet should go. Need to
12079 	 * preserve the recv_ill somehow. Until we figure that out, for
12080 	 * now just drop the packet if we can't classify the packet.
12081 	 */
12082 	if (tcp->tcp_state == TCPS_CLOSED ||
12083 	    tcp->tcp_state == TCPS_BOUND) {
12084 		conn_t	*new_connp;
12085 		ip_stack_t *ipst = tcp->tcp_tcps->tcps_netstack->netstack_ip;
12086 
12087 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
12088 		if (new_connp != NULL) {
12089 			tcp_reinput(new_connp, mp, arg2);
12090 			return;
12091 		}
12092 		/* We failed to classify. For now just drop the packet */
12093 		freemsg(mp);
12094 		return;
12095 	}
12096 
12097 	if (DB_TYPE(mp) == M_DATA)
12098 		tcp_rput_data(connp, mp, arg2);
12099 	else
12100 		tcp_rput_common(tcp, mp);
12101 }
12102 
12103 /*
12104  * The read side put procedure.
12105  * The packets passed up by ip are assume to be aligned according to
12106  * OK_32PTR and the IP+TCP headers fitting in the first mblk.
12107  */
12108 static void
12109 tcp_rput_common(tcp_t *tcp, mblk_t *mp)
12110 {
12111 	/*
12112 	 * tcp_rput_data() does not expect M_CTL except for the case
12113 	 * where tcp_ipv6_recvancillary is set and we get a IN_PKTINFO
12114 	 * type. Need to make sure that any other M_CTLs don't make
12115 	 * it to tcp_rput_data since it is not expecting any and doesn't
12116 	 * check for it.
12117 	 */
12118 	if (DB_TYPE(mp) == M_CTL) {
12119 		switch (*(uint32_t *)(mp->b_rptr)) {
12120 		case TCP_IOC_ABORT_CONN:
12121 			/*
12122 			 * Handle connection abort request.
12123 			 */
12124 			tcp_ioctl_abort_handler(tcp, mp);
12125 			return;
12126 		case IPSEC_IN:
12127 			/*
12128 			 * Only secure icmp arrive in TCP and they
12129 			 * don't go through data path.
12130 			 */
12131 			tcp_icmp_error(tcp, mp);
12132 			return;
12133 		case IN_PKTINFO:
12134 			/*
12135 			 * Handle IPV6_RECVPKTINFO socket option on AF_INET6
12136 			 * sockets that are receiving IPv4 traffic. tcp
12137 			 */
12138 			ASSERT(tcp->tcp_family == AF_INET6);
12139 			ASSERT(tcp->tcp_ipv6_recvancillary &
12140 			    TCP_IPV6_RECVPKTINFO);
12141 			tcp_rput_data(tcp->tcp_connp, mp,
12142 			    tcp->tcp_connp->conn_sqp);
12143 			return;
12144 		case MDT_IOC_INFO_UPDATE:
12145 			/*
12146 			 * Handle Multidata information update; the
12147 			 * following routine will free the message.
12148 			 */
12149 			if (tcp->tcp_connp->conn_mdt_ok) {
12150 				tcp_mdt_update(tcp,
12151 				    &((ip_mdt_info_t *)mp->b_rptr)->mdt_capab,
12152 				    B_FALSE);
12153 			}
12154 			freemsg(mp);
12155 			return;
12156 		case LSO_IOC_INFO_UPDATE:
12157 			/*
12158 			 * Handle LSO information update; the following
12159 			 * routine will free the message.
12160 			 */
12161 			if (tcp->tcp_connp->conn_lso_ok) {
12162 				tcp_lso_update(tcp,
12163 				    &((ip_lso_info_t *)mp->b_rptr)->lso_capab);
12164 			}
12165 			freemsg(mp);
12166 			return;
12167 		default:
12168 			/*
12169 			 * tcp_icmp_err() will process the M_CTL packets.
12170 			 * Non-ICMP packets, if any, will be discarded in
12171 			 * tcp_icmp_err(). We will process the ICMP packet
12172 			 * even if we are TCP_IS_DETACHED_NONEAGER as the
12173 			 * incoming ICMP packet may result in changing
12174 			 * the tcp_mss, which we would need if we have
12175 			 * packets to retransmit.
12176 			 */
12177 			tcp_icmp_error(tcp, mp);
12178 			return;
12179 		}
12180 	}
12181 
12182 	/* No point processing the message if tcp is already closed */
12183 	if (TCP_IS_DETACHED_NONEAGER(tcp)) {
12184 		freemsg(mp);
12185 		return;
12186 	}
12187 
12188 	tcp_rput_other(tcp, mp);
12189 }
12190 
12191 
12192 /* The minimum of smoothed mean deviation in RTO calculation. */
12193 #define	TCP_SD_MIN	400
12194 
12195 /*
12196  * Set RTO for this connection.  The formula is from Jacobson and Karels'
12197  * "Congestion Avoidance and Control" in SIGCOMM '88.  The variable names
12198  * are the same as those in Appendix A.2 of that paper.
12199  *
12200  * m = new measurement
12201  * sa = smoothed RTT average (8 * average estimates).
12202  * sv = smoothed mean deviation (mdev) of RTT (4 * deviation estimates).
12203  */
12204 static void
12205 tcp_set_rto(tcp_t *tcp, clock_t rtt)
12206 {
12207 	long m = TICK_TO_MSEC(rtt);
12208 	clock_t sa = tcp->tcp_rtt_sa;
12209 	clock_t sv = tcp->tcp_rtt_sd;
12210 	clock_t rto;
12211 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12212 
12213 	BUMP_MIB(&tcps->tcps_mib, tcpRttUpdate);
12214 	tcp->tcp_rtt_update++;
12215 
12216 	/* tcp_rtt_sa is not 0 means this is a new sample. */
12217 	if (sa != 0) {
12218 		/*
12219 		 * Update average estimator:
12220 		 *	new rtt = 7/8 old rtt + 1/8 Error
12221 		 */
12222 
12223 		/* m is now Error in estimate. */
12224 		m -= sa >> 3;
12225 		if ((sa += m) <= 0) {
12226 			/*
12227 			 * Don't allow the smoothed average to be negative.
12228 			 * We use 0 to denote reinitialization of the
12229 			 * variables.
12230 			 */
12231 			sa = 1;
12232 		}
12233 
12234 		/*
12235 		 * Update deviation estimator:
12236 		 *	new mdev = 3/4 old mdev + 1/4 (abs(Error) - old mdev)
12237 		 */
12238 		if (m < 0)
12239 			m = -m;
12240 		m -= sv >> 2;
12241 		sv += m;
12242 	} else {
12243 		/*
12244 		 * This follows BSD's implementation.  So the reinitialized
12245 		 * RTO is 3 * m.  We cannot go less than 2 because if the
12246 		 * link is bandwidth dominated, doubling the window size
12247 		 * during slow start means doubling the RTT.  We want to be
12248 		 * more conservative when we reinitialize our estimates.  3
12249 		 * is just a convenient number.
12250 		 */
12251 		sa = m << 3;
12252 		sv = m << 1;
12253 	}
12254 	if (sv < TCP_SD_MIN) {
12255 		/*
12256 		 * We do not know that if sa captures the delay ACK
12257 		 * effect as in a long train of segments, a receiver
12258 		 * does not delay its ACKs.  So set the minimum of sv
12259 		 * to be TCP_SD_MIN, which is default to 400 ms, twice
12260 		 * of BSD DATO.  That means the minimum of mean
12261 		 * deviation is 100 ms.
12262 		 *
12263 		 */
12264 		sv = TCP_SD_MIN;
12265 	}
12266 	tcp->tcp_rtt_sa = sa;
12267 	tcp->tcp_rtt_sd = sv;
12268 	/*
12269 	 * RTO = average estimates (sa / 8) + 4 * deviation estimates (sv)
12270 	 *
12271 	 * Add tcp_rexmit_interval extra in case of extreme environment
12272 	 * where the algorithm fails to work.  The default value of
12273 	 * tcp_rexmit_interval_extra should be 0.
12274 	 *
12275 	 * As we use a finer grained clock than BSD and update
12276 	 * RTO for every ACKs, add in another .25 of RTT to the
12277 	 * deviation of RTO to accomodate burstiness of 1/4 of
12278 	 * window size.
12279 	 */
12280 	rto = (sa >> 3) + sv + tcps->tcps_rexmit_interval_extra + (sa >> 5);
12281 
12282 	if (rto > tcps->tcps_rexmit_interval_max) {
12283 		tcp->tcp_rto = tcps->tcps_rexmit_interval_max;
12284 	} else if (rto < tcps->tcps_rexmit_interval_min) {
12285 		tcp->tcp_rto = tcps->tcps_rexmit_interval_min;
12286 	} else {
12287 		tcp->tcp_rto = rto;
12288 	}
12289 
12290 	/* Now, we can reset tcp_timer_backoff to use the new RTO... */
12291 	tcp->tcp_timer_backoff = 0;
12292 }
12293 
12294 /*
12295  * tcp_get_seg_mp() is called to get the pointer to a segment in the
12296  * send queue which starts at the given seq. no.
12297  *
12298  * Parameters:
12299  *	tcp_t *tcp: the tcp instance pointer.
12300  *	uint32_t seq: the starting seq. no of the requested segment.
12301  *	int32_t *off: after the execution, *off will be the offset to
12302  *		the returned mblk which points to the requested seq no.
12303  *		It is the caller's responsibility to send in a non-null off.
12304  *
12305  * Return:
12306  *	A mblk_t pointer pointing to the requested segment in send queue.
12307  */
12308 static mblk_t *
12309 tcp_get_seg_mp(tcp_t *tcp, uint32_t seq, int32_t *off)
12310 {
12311 	int32_t	cnt;
12312 	mblk_t	*mp;
12313 
12314 	/* Defensive coding.  Make sure we don't send incorrect data. */
12315 	if (SEQ_LT(seq, tcp->tcp_suna) || SEQ_GEQ(seq, tcp->tcp_snxt))
12316 		return (NULL);
12317 
12318 	cnt = seq - tcp->tcp_suna;
12319 	mp = tcp->tcp_xmit_head;
12320 	while (cnt > 0 && mp != NULL) {
12321 		cnt -= mp->b_wptr - mp->b_rptr;
12322 		if (cnt < 0) {
12323 			cnt += mp->b_wptr - mp->b_rptr;
12324 			break;
12325 		}
12326 		mp = mp->b_cont;
12327 	}
12328 	ASSERT(mp != NULL);
12329 	*off = cnt;
12330 	return (mp);
12331 }
12332 
12333 /*
12334  * This function handles all retransmissions if SACK is enabled for this
12335  * connection.  First it calculates how many segments can be retransmitted
12336  * based on tcp_pipe.  Then it goes thru the notsack list to find eligible
12337  * segments.  A segment is eligible if sack_cnt for that segment is greater
12338  * than or equal tcp_dupack_fast_retransmit.  After it has retransmitted
12339  * all eligible segments, it checks to see if TCP can send some new segments
12340  * (fast recovery).  If it can, set the appropriate flag for tcp_rput_data().
12341  *
12342  * Parameters:
12343  *	tcp_t *tcp: the tcp structure of the connection.
12344  *	uint_t *flags: in return, appropriate value will be set for
12345  *	tcp_rput_data().
12346  */
12347 static void
12348 tcp_sack_rxmit(tcp_t *tcp, uint_t *flags)
12349 {
12350 	notsack_blk_t	*notsack_blk;
12351 	int32_t		usable_swnd;
12352 	int32_t		mss;
12353 	uint32_t	seg_len;
12354 	mblk_t		*xmit_mp;
12355 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12356 
12357 	ASSERT(tcp->tcp_sack_info != NULL);
12358 	ASSERT(tcp->tcp_notsack_list != NULL);
12359 	ASSERT(tcp->tcp_rexmit == B_FALSE);
12360 
12361 	/* Defensive coding in case there is a bug... */
12362 	if (tcp->tcp_notsack_list == NULL) {
12363 		return;
12364 	}
12365 	notsack_blk = tcp->tcp_notsack_list;
12366 	mss = tcp->tcp_mss;
12367 
12368 	/*
12369 	 * Limit the num of outstanding data in the network to be
12370 	 * tcp_cwnd_ssthresh, which is half of the original congestion wnd.
12371 	 */
12372 	usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12373 
12374 	/* At least retransmit 1 MSS of data. */
12375 	if (usable_swnd <= 0) {
12376 		usable_swnd = mss;
12377 	}
12378 
12379 	/* Make sure no new RTT samples will be taken. */
12380 	tcp->tcp_csuna = tcp->tcp_snxt;
12381 
12382 	notsack_blk = tcp->tcp_notsack_list;
12383 	while (usable_swnd > 0) {
12384 		mblk_t		*snxt_mp, *tmp_mp;
12385 		tcp_seq		begin = tcp->tcp_sack_snxt;
12386 		tcp_seq		end;
12387 		int32_t		off;
12388 
12389 		for (; notsack_blk != NULL; notsack_blk = notsack_blk->next) {
12390 			if (SEQ_GT(notsack_blk->end, begin) &&
12391 			    (notsack_blk->sack_cnt >=
12392 			    tcps->tcps_dupack_fast_retransmit)) {
12393 				end = notsack_blk->end;
12394 				if (SEQ_LT(begin, notsack_blk->begin)) {
12395 					begin = notsack_blk->begin;
12396 				}
12397 				break;
12398 			}
12399 		}
12400 		/*
12401 		 * All holes are filled.  Manipulate tcp_cwnd to send more
12402 		 * if we can.  Note that after the SACK recovery, tcp_cwnd is
12403 		 * set to tcp_cwnd_ssthresh.
12404 		 */
12405 		if (notsack_blk == NULL) {
12406 			usable_swnd = tcp->tcp_cwnd_ssthresh - tcp->tcp_pipe;
12407 			if (usable_swnd <= 0 || tcp->tcp_unsent == 0) {
12408 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna;
12409 				ASSERT(tcp->tcp_cwnd > 0);
12410 				return;
12411 			} else {
12412 				usable_swnd = usable_swnd / mss;
12413 				tcp->tcp_cwnd = tcp->tcp_snxt - tcp->tcp_suna +
12414 				    MAX(usable_swnd * mss, mss);
12415 				*flags |= TH_XMIT_NEEDED;
12416 				return;
12417 			}
12418 		}
12419 
12420 		/*
12421 		 * Note that we may send more than usable_swnd allows here
12422 		 * because of round off, but no more than 1 MSS of data.
12423 		 */
12424 		seg_len = end - begin;
12425 		if (seg_len > mss)
12426 			seg_len = mss;
12427 		snxt_mp = tcp_get_seg_mp(tcp, begin, &off);
12428 		ASSERT(snxt_mp != NULL);
12429 		/* This should not happen.  Defensive coding again... */
12430 		if (snxt_mp == NULL) {
12431 			return;
12432 		}
12433 
12434 		xmit_mp = tcp_xmit_mp(tcp, snxt_mp, seg_len, &off,
12435 		    &tmp_mp, begin, B_TRUE, &seg_len, B_TRUE);
12436 		if (xmit_mp == NULL)
12437 			return;
12438 
12439 		usable_swnd -= seg_len;
12440 		tcp->tcp_pipe += seg_len;
12441 		tcp->tcp_sack_snxt = begin + seg_len;
12442 
12443 		tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12444 
12445 		/*
12446 		 * Update the send timestamp to avoid false retransmission.
12447 		 */
12448 		snxt_mp->b_prev = (mblk_t *)lbolt;
12449 
12450 		BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12451 		UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, seg_len);
12452 		BUMP_MIB(&tcps->tcps_mib, tcpOutSackRetransSegs);
12453 		/*
12454 		 * Update tcp_rexmit_max to extend this SACK recovery phase.
12455 		 * This happens when new data sent during fast recovery is
12456 		 * also lost.  If TCP retransmits those new data, it needs
12457 		 * to extend SACK recover phase to avoid starting another
12458 		 * fast retransmit/recovery unnecessarily.
12459 		 */
12460 		if (SEQ_GT(tcp->tcp_sack_snxt, tcp->tcp_rexmit_max)) {
12461 			tcp->tcp_rexmit_max = tcp->tcp_sack_snxt;
12462 		}
12463 	}
12464 }
12465 
12466 /*
12467  * This function handles policy checking at TCP level for non-hard_bound/
12468  * detached connections.
12469  */
12470 static boolean_t
12471 tcp_check_policy(tcp_t *tcp, mblk_t *first_mp, ipha_t *ipha, ip6_t *ip6h,
12472     boolean_t secure, boolean_t mctl_present)
12473 {
12474 	ipsec_latch_t *ipl = NULL;
12475 	ipsec_action_t *act = NULL;
12476 	mblk_t *data_mp;
12477 	ipsec_in_t *ii;
12478 	const char *reason;
12479 	kstat_named_t *counter;
12480 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12481 	ipsec_stack_t	*ipss;
12482 	ip_stack_t	*ipst;
12483 
12484 	ASSERT(mctl_present || !secure);
12485 
12486 	ASSERT((ipha == NULL && ip6h != NULL) ||
12487 	    (ip6h == NULL && ipha != NULL));
12488 
12489 	/*
12490 	 * We don't necessarily have an ipsec_in_act action to verify
12491 	 * policy because of assymetrical policy where we have only
12492 	 * outbound policy and no inbound policy (possible with global
12493 	 * policy).
12494 	 */
12495 	if (!secure) {
12496 		if (act == NULL || act->ipa_act.ipa_type == IPSEC_ACT_BYPASS ||
12497 		    act->ipa_act.ipa_type == IPSEC_ACT_CLEAR)
12498 			return (B_TRUE);
12499 		ipsec_log_policy_failure(IPSEC_POLICY_MISMATCH,
12500 		    "tcp_check_policy", ipha, ip6h, secure,
12501 		    tcps->tcps_netstack);
12502 		ipss = tcps->tcps_netstack->netstack_ipsec;
12503 
12504 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12505 		    DROPPER(ipss, ipds_tcp_clear),
12506 		    &tcps->tcps_dropper);
12507 		return (B_FALSE);
12508 	}
12509 
12510 	/*
12511 	 * We have a secure packet.
12512 	 */
12513 	if (act == NULL) {
12514 		ipsec_log_policy_failure(IPSEC_POLICY_NOT_NEEDED,
12515 		    "tcp_check_policy", ipha, ip6h, secure,
12516 		    tcps->tcps_netstack);
12517 		ipss = tcps->tcps_netstack->netstack_ipsec;
12518 
12519 		ip_drop_packet(first_mp, B_TRUE, NULL, NULL,
12520 		    DROPPER(ipss, ipds_tcp_secure),
12521 		    &tcps->tcps_dropper);
12522 		return (B_FALSE);
12523 	}
12524 
12525 	/*
12526 	 * XXX This whole routine is currently incorrect.  ipl should
12527 	 * be set to the latch pointer, but is currently not set, so
12528 	 * we initialize it to NULL to avoid picking up random garbage.
12529 	 */
12530 	if (ipl == NULL)
12531 		return (B_TRUE);
12532 
12533 	data_mp = first_mp->b_cont;
12534 
12535 	ii = (ipsec_in_t *)first_mp->b_rptr;
12536 
12537 	ipst = tcps->tcps_netstack->netstack_ip;
12538 
12539 	if (ipsec_check_ipsecin_latch(ii, data_mp, ipl, ipha, ip6h, &reason,
12540 	    &counter, tcp->tcp_connp)) {
12541 		BUMP_MIB(&ipst->ips_ip_mib, ipsecInSucceeded);
12542 		return (B_TRUE);
12543 	}
12544 	(void) strlog(TCP_MOD_ID, 0, 0, SL_ERROR|SL_WARN|SL_CONSOLE,
12545 	    "tcp inbound policy mismatch: %s, packet dropped\n",
12546 	    reason);
12547 	BUMP_MIB(&ipst->ips_ip_mib, ipsecInFailed);
12548 
12549 	ip_drop_packet(first_mp, B_TRUE, NULL, NULL, counter,
12550 	    &tcps->tcps_dropper);
12551 	return (B_FALSE);
12552 }
12553 
12554 /*
12555  * tcp_ss_rexmit() is called in tcp_rput_data() to do slow start
12556  * retransmission after a timeout.
12557  *
12558  * To limit the number of duplicate segments, we limit the number of segment
12559  * to be sent in one time to tcp_snd_burst, the burst variable.
12560  */
12561 static void
12562 tcp_ss_rexmit(tcp_t *tcp)
12563 {
12564 	uint32_t	snxt;
12565 	uint32_t	smax;
12566 	int32_t		win;
12567 	int32_t		mss;
12568 	int32_t		off;
12569 	int32_t		burst = tcp->tcp_snd_burst;
12570 	mblk_t		*snxt_mp;
12571 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12572 
12573 	/*
12574 	 * Note that tcp_rexmit can be set even though TCP has retransmitted
12575 	 * all unack'ed segments.
12576 	 */
12577 	if (SEQ_LT(tcp->tcp_rexmit_nxt, tcp->tcp_rexmit_max)) {
12578 		smax = tcp->tcp_rexmit_max;
12579 		snxt = tcp->tcp_rexmit_nxt;
12580 		if (SEQ_LT(snxt, tcp->tcp_suna)) {
12581 			snxt = tcp->tcp_suna;
12582 		}
12583 		win = MIN(tcp->tcp_cwnd, tcp->tcp_swnd);
12584 		win -= snxt - tcp->tcp_suna;
12585 		mss = tcp->tcp_mss;
12586 		snxt_mp = tcp_get_seg_mp(tcp, snxt, &off);
12587 
12588 		while (SEQ_LT(snxt, smax) && (win > 0) &&
12589 		    (burst > 0) && (snxt_mp != NULL)) {
12590 			mblk_t	*xmit_mp;
12591 			mblk_t	*old_snxt_mp = snxt_mp;
12592 			uint32_t cnt = mss;
12593 
12594 			if (win < cnt) {
12595 				cnt = win;
12596 			}
12597 			if (SEQ_GT(snxt + cnt, smax)) {
12598 				cnt = smax - snxt;
12599 			}
12600 			xmit_mp = tcp_xmit_mp(tcp, snxt_mp, cnt, &off,
12601 			    &snxt_mp, snxt, B_TRUE, &cnt, B_TRUE);
12602 			if (xmit_mp == NULL)
12603 				return;
12604 
12605 			tcp_send_data(tcp, tcp->tcp_wq, xmit_mp);
12606 
12607 			snxt += cnt;
12608 			win -= cnt;
12609 			/*
12610 			 * Update the send timestamp to avoid false
12611 			 * retransmission.
12612 			 */
12613 			old_snxt_mp->b_prev = (mblk_t *)lbolt;
12614 			BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
12615 			UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, cnt);
12616 
12617 			tcp->tcp_rexmit_nxt = snxt;
12618 			burst--;
12619 		}
12620 		/*
12621 		 * If we have transmitted all we have at the time
12622 		 * we started the retranmission, we can leave
12623 		 * the rest of the job to tcp_wput_data().  But we
12624 		 * need to check the send window first.  If the
12625 		 * win is not 0, go on with tcp_wput_data().
12626 		 */
12627 		if (SEQ_LT(snxt, smax) || win == 0) {
12628 			return;
12629 		}
12630 	}
12631 	/* Only call tcp_wput_data() if there is data to be sent. */
12632 	if (tcp->tcp_unsent) {
12633 		tcp_wput_data(tcp, NULL, B_FALSE);
12634 	}
12635 }
12636 
12637 /*
12638  * Process all TCP option in SYN segment.  Note that this function should
12639  * be called after tcp_adapt_ire() is called so that the necessary info
12640  * from IRE is already set in the tcp structure.
12641  *
12642  * This function sets up the correct tcp_mss value according to the
12643  * MSS option value and our header size.  It also sets up the window scale
12644  * and timestamp values, and initialize SACK info blocks.  But it does not
12645  * change receive window size after setting the tcp_mss value.  The caller
12646  * should do the appropriate change.
12647  */
12648 void
12649 tcp_process_options(tcp_t *tcp, tcph_t *tcph)
12650 {
12651 	int options;
12652 	tcp_opt_t tcpopt;
12653 	uint32_t mss_max;
12654 	char *tmp_tcph;
12655 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12656 
12657 	tcpopt.tcp = NULL;
12658 	options = tcp_parse_options(tcph, &tcpopt);
12659 
12660 	/*
12661 	 * Process MSS option.  Note that MSS option value does not account
12662 	 * for IP or TCP options.  This means that it is equal to MTU - minimum
12663 	 * IP+TCP header size, which is 40 bytes for IPv4 and 60 bytes for
12664 	 * IPv6.
12665 	 */
12666 	if (!(options & TCP_OPT_MSS_PRESENT)) {
12667 		if (tcp->tcp_ipversion == IPV4_VERSION)
12668 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv4;
12669 		else
12670 			tcpopt.tcp_opt_mss = tcps->tcps_mss_def_ipv6;
12671 	} else {
12672 		if (tcp->tcp_ipversion == IPV4_VERSION)
12673 			mss_max = tcps->tcps_mss_max_ipv4;
12674 		else
12675 			mss_max = tcps->tcps_mss_max_ipv6;
12676 		if (tcpopt.tcp_opt_mss < tcps->tcps_mss_min)
12677 			tcpopt.tcp_opt_mss = tcps->tcps_mss_min;
12678 		else if (tcpopt.tcp_opt_mss > mss_max)
12679 			tcpopt.tcp_opt_mss = mss_max;
12680 	}
12681 
12682 	/* Process Window Scale option. */
12683 	if (options & TCP_OPT_WSCALE_PRESENT) {
12684 		tcp->tcp_snd_ws = tcpopt.tcp_opt_wscale;
12685 		tcp->tcp_snd_ws_ok = B_TRUE;
12686 	} else {
12687 		tcp->tcp_snd_ws = B_FALSE;
12688 		tcp->tcp_snd_ws_ok = B_FALSE;
12689 		tcp->tcp_rcv_ws = B_FALSE;
12690 	}
12691 
12692 	/* Process Timestamp option. */
12693 	if ((options & TCP_OPT_TSTAMP_PRESENT) &&
12694 	    (tcp->tcp_snd_ts_ok || TCP_IS_DETACHED(tcp))) {
12695 		tmp_tcph = (char *)tcp->tcp_tcph;
12696 
12697 		tcp->tcp_snd_ts_ok = B_TRUE;
12698 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
12699 		tcp->tcp_last_rcv_lbolt = lbolt64;
12700 		ASSERT(OK_32PTR(tmp_tcph));
12701 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
12702 
12703 		/* Fill in our template header with basic timestamp option. */
12704 		tmp_tcph += tcp->tcp_tcp_hdr_len;
12705 		tmp_tcph[0] = TCPOPT_NOP;
12706 		tmp_tcph[1] = TCPOPT_NOP;
12707 		tmp_tcph[2] = TCPOPT_TSTAMP;
12708 		tmp_tcph[3] = TCPOPT_TSTAMP_LEN;
12709 		tcp->tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12710 		tcp->tcp_tcp_hdr_len += TCPOPT_REAL_TS_LEN;
12711 		tcp->tcp_tcph->th_offset_and_rsrvd[0] += (3 << 4);
12712 	} else {
12713 		tcp->tcp_snd_ts_ok = B_FALSE;
12714 	}
12715 
12716 	/*
12717 	 * Process SACK options.  If SACK is enabled for this connection,
12718 	 * then allocate the SACK info structure.  Note the following ways
12719 	 * when tcp_snd_sack_ok is set to true.
12720 	 *
12721 	 * For active connection: in tcp_adapt_ire() called in
12722 	 * tcp_rput_other(), or in tcp_rput_other() when tcp_sack_permitted
12723 	 * is checked.
12724 	 *
12725 	 * For passive connection: in tcp_adapt_ire() called in
12726 	 * tcp_accept_comm().
12727 	 *
12728 	 * That's the reason why the extra TCP_IS_DETACHED() check is there.
12729 	 * That check makes sure that if we did not send a SACK OK option,
12730 	 * we will not enable SACK for this connection even though the other
12731 	 * side sends us SACK OK option.  For active connection, the SACK
12732 	 * info structure has already been allocated.  So we need to free
12733 	 * it if SACK is disabled.
12734 	 */
12735 	if ((options & TCP_OPT_SACK_OK_PRESENT) &&
12736 	    (tcp->tcp_snd_sack_ok ||
12737 	    (tcps->tcps_sack_permitted != 0 && TCP_IS_DETACHED(tcp)))) {
12738 		/* This should be true only in the passive case. */
12739 		if (tcp->tcp_sack_info == NULL) {
12740 			ASSERT(TCP_IS_DETACHED(tcp));
12741 			tcp->tcp_sack_info =
12742 			    kmem_cache_alloc(tcp_sack_info_cache, KM_NOSLEEP);
12743 		}
12744 		if (tcp->tcp_sack_info == NULL) {
12745 			tcp->tcp_snd_sack_ok = B_FALSE;
12746 		} else {
12747 			tcp->tcp_snd_sack_ok = B_TRUE;
12748 			if (tcp->tcp_snd_ts_ok) {
12749 				tcp->tcp_max_sack_blk = 3;
12750 			} else {
12751 				tcp->tcp_max_sack_blk = 4;
12752 			}
12753 		}
12754 	} else {
12755 		/*
12756 		 * Resetting tcp_snd_sack_ok to B_FALSE so that
12757 		 * no SACK info will be used for this
12758 		 * connection.  This assumes that SACK usage
12759 		 * permission is negotiated.  This may need
12760 		 * to be changed once this is clarified.
12761 		 */
12762 		if (tcp->tcp_sack_info != NULL) {
12763 			ASSERT(tcp->tcp_notsack_list == NULL);
12764 			kmem_cache_free(tcp_sack_info_cache,
12765 			    tcp->tcp_sack_info);
12766 			tcp->tcp_sack_info = NULL;
12767 		}
12768 		tcp->tcp_snd_sack_ok = B_FALSE;
12769 	}
12770 
12771 	/*
12772 	 * Now we know the exact TCP/IP header length, subtract
12773 	 * that from tcp_mss to get our side's MSS.
12774 	 */
12775 	tcp->tcp_mss -= tcp->tcp_hdr_len;
12776 	/*
12777 	 * Here we assume that the other side's header size will be equal to
12778 	 * our header size.  We calculate the real MSS accordingly.  Need to
12779 	 * take into additional stuffs IPsec puts in.
12780 	 *
12781 	 * Real MSS = Opt.MSS - (our TCP/IP header - min TCP/IP header)
12782 	 */
12783 	tcpopt.tcp_opt_mss -= tcp->tcp_hdr_len + tcp->tcp_ipsec_overhead -
12784 	    ((tcp->tcp_ipversion == IPV4_VERSION ?
12785 	    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) + TCP_MIN_HEADER_LENGTH);
12786 
12787 	/*
12788 	 * Set MSS to the smaller one of both ends of the connection.
12789 	 * We should not have called tcp_mss_set() before, but our
12790 	 * side of the MSS should have been set to a proper value
12791 	 * by tcp_adapt_ire().  tcp_mss_set() will also set up the
12792 	 * STREAM head parameters properly.
12793 	 *
12794 	 * If we have a larger-than-16-bit window but the other side
12795 	 * didn't want to do window scale, tcp_rwnd_set() will take
12796 	 * care of that.
12797 	 */
12798 	tcp_mss_set(tcp, MIN(tcpopt.tcp_opt_mss, tcp->tcp_mss), B_TRUE);
12799 }
12800 
12801 /*
12802  * Sends the T_CONN_IND to the listener. The caller calls this
12803  * functions via squeue to get inside the listener's perimeter
12804  * once the 3 way hand shake is done a T_CONN_IND needs to be
12805  * sent. As an optimization, the caller can call this directly
12806  * if listener's perimeter is same as eager's.
12807  */
12808 /* ARGSUSED */
12809 void
12810 tcp_send_conn_ind(void *arg, mblk_t *mp, void *arg2)
12811 {
12812 	conn_t			*lconnp = (conn_t *)arg;
12813 	tcp_t			*listener = lconnp->conn_tcp;
12814 	tcp_t			*tcp;
12815 	struct T_conn_ind	*conn_ind;
12816 	ipaddr_t 		*addr_cache;
12817 	boolean_t		need_send_conn_ind = B_FALSE;
12818 	tcp_stack_t		*tcps = listener->tcp_tcps;
12819 
12820 	/* retrieve the eager */
12821 	conn_ind = (struct T_conn_ind *)mp->b_rptr;
12822 	ASSERT(conn_ind->OPT_offset != 0 &&
12823 	    conn_ind->OPT_length == sizeof (intptr_t));
12824 	bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
12825 	    conn_ind->OPT_length);
12826 
12827 	/*
12828 	 * TLI/XTI applications will get confused by
12829 	 * sending eager as an option since it violates
12830 	 * the option semantics. So remove the eager as
12831 	 * option since TLI/XTI app doesn't need it anyway.
12832 	 */
12833 	if (!TCP_IS_SOCKET(listener)) {
12834 		conn_ind->OPT_length = 0;
12835 		conn_ind->OPT_offset = 0;
12836 	}
12837 	if (listener->tcp_state == TCPS_CLOSED ||
12838 	    TCP_IS_DETACHED(listener)) {
12839 		/*
12840 		 * If listener has closed, it would have caused a
12841 		 * a cleanup/blowoff to happen for the eager. We
12842 		 * just need to return.
12843 		 */
12844 		freemsg(mp);
12845 		return;
12846 	}
12847 
12848 
12849 	/*
12850 	 * if the conn_req_q is full defer passing up the
12851 	 * T_CONN_IND until space is availabe after t_accept()
12852 	 * processing
12853 	 */
12854 	mutex_enter(&listener->tcp_eager_lock);
12855 
12856 	/*
12857 	 * Take the eager out, if it is in the list of droppable eagers
12858 	 * as we are here because the 3W handshake is over.
12859 	 */
12860 	MAKE_UNDROPPABLE(tcp);
12861 
12862 	if (listener->tcp_conn_req_cnt_q < listener->tcp_conn_req_max) {
12863 		tcp_t *tail;
12864 
12865 		/*
12866 		 * The eager already has an extra ref put in tcp_rput_data
12867 		 * so that it stays till accept comes back even though it
12868 		 * might get into TCPS_CLOSED as a result of a TH_RST etc.
12869 		 */
12870 		ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
12871 		listener->tcp_conn_req_cnt_q0--;
12872 		listener->tcp_conn_req_cnt_q++;
12873 
12874 		/* Move from SYN_RCVD to ESTABLISHED list  */
12875 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12876 		    tcp->tcp_eager_prev_q0;
12877 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12878 		    tcp->tcp_eager_next_q0;
12879 		tcp->tcp_eager_prev_q0 = NULL;
12880 		tcp->tcp_eager_next_q0 = NULL;
12881 
12882 		/*
12883 		 * Insert at end of the queue because sockfs
12884 		 * sends down T_CONN_RES in chronological
12885 		 * order. Leaving the older conn indications
12886 		 * at front of the queue helps reducing search
12887 		 * time.
12888 		 */
12889 		tail = listener->tcp_eager_last_q;
12890 		if (tail != NULL)
12891 			tail->tcp_eager_next_q = tcp;
12892 		else
12893 			listener->tcp_eager_next_q = tcp;
12894 		listener->tcp_eager_last_q = tcp;
12895 		tcp->tcp_eager_next_q = NULL;
12896 		/*
12897 		 * Delay sending up the T_conn_ind until we are
12898 		 * done with the eager. Once we have have sent up
12899 		 * the T_conn_ind, the accept can potentially complete
12900 		 * any time and release the refhold we have on the eager.
12901 		 */
12902 		need_send_conn_ind = B_TRUE;
12903 	} else {
12904 		/*
12905 		 * Defer connection on q0 and set deferred
12906 		 * connection bit true
12907 		 */
12908 		tcp->tcp_conn_def_q0 = B_TRUE;
12909 
12910 		/* take tcp out of q0 ... */
12911 		tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
12912 		    tcp->tcp_eager_next_q0;
12913 		tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
12914 		    tcp->tcp_eager_prev_q0;
12915 
12916 		/* ... and place it at the end of q0 */
12917 		tcp->tcp_eager_prev_q0 = listener->tcp_eager_prev_q0;
12918 		tcp->tcp_eager_next_q0 = listener;
12919 		listener->tcp_eager_prev_q0->tcp_eager_next_q0 = tcp;
12920 		listener->tcp_eager_prev_q0 = tcp;
12921 		tcp->tcp_conn.tcp_eager_conn_ind = mp;
12922 	}
12923 
12924 	/* we have timed out before */
12925 	if (tcp->tcp_syn_rcvd_timeout != 0) {
12926 		tcp->tcp_syn_rcvd_timeout = 0;
12927 		listener->tcp_syn_rcvd_timeout--;
12928 		if (listener->tcp_syn_defense &&
12929 		    listener->tcp_syn_rcvd_timeout <=
12930 		    (tcps->tcps_conn_req_max_q0 >> 5) &&
12931 		    10*MINUTES < TICK_TO_MSEC(lbolt64 -
12932 		    listener->tcp_last_rcv_lbolt)) {
12933 			/*
12934 			 * Turn off the defense mode if we
12935 			 * believe the SYN attack is over.
12936 			 */
12937 			listener->tcp_syn_defense = B_FALSE;
12938 			if (listener->tcp_ip_addr_cache) {
12939 				kmem_free((void *)listener->tcp_ip_addr_cache,
12940 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t));
12941 				listener->tcp_ip_addr_cache = NULL;
12942 			}
12943 		}
12944 	}
12945 	addr_cache = (ipaddr_t *)(listener->tcp_ip_addr_cache);
12946 	if (addr_cache != NULL) {
12947 		/*
12948 		 * We have finished a 3-way handshake with this
12949 		 * remote host. This proves the IP addr is good.
12950 		 * Cache it!
12951 		 */
12952 		addr_cache[IP_ADDR_CACHE_HASH(
12953 		    tcp->tcp_remote)] = tcp->tcp_remote;
12954 	}
12955 	mutex_exit(&listener->tcp_eager_lock);
12956 	if (need_send_conn_ind)
12957 		putnext(listener->tcp_rq, mp);
12958 }
12959 
12960 mblk_t *
12961 tcp_find_pktinfo(tcp_t *tcp, mblk_t *mp, uint_t *ipversp, uint_t *ip_hdr_lenp,
12962     uint_t *ifindexp, ip6_pkt_t *ippp)
12963 {
12964 	ip_pktinfo_t	*pinfo;
12965 	ip6_t		*ip6h;
12966 	uchar_t		*rptr;
12967 	mblk_t		*first_mp = mp;
12968 	boolean_t	mctl_present = B_FALSE;
12969 	uint_t 		ifindex = 0;
12970 	ip6_pkt_t	ipp;
12971 	uint_t		ipvers;
12972 	uint_t		ip_hdr_len;
12973 	tcp_stack_t	*tcps = tcp->tcp_tcps;
12974 
12975 	rptr = mp->b_rptr;
12976 	ASSERT(OK_32PTR(rptr));
12977 	ASSERT(tcp != NULL);
12978 	ipp.ipp_fields = 0;
12979 
12980 	switch DB_TYPE(mp) {
12981 	case M_CTL:
12982 		mp = mp->b_cont;
12983 		if (mp == NULL) {
12984 			freemsg(first_mp);
12985 			return (NULL);
12986 		}
12987 		if (DB_TYPE(mp) != M_DATA) {
12988 			freemsg(first_mp);
12989 			return (NULL);
12990 		}
12991 		mctl_present = B_TRUE;
12992 		break;
12993 	case M_DATA:
12994 		break;
12995 	default:
12996 		cmn_err(CE_NOTE, "tcp_find_pktinfo: unknown db_type");
12997 		freemsg(mp);
12998 		return (NULL);
12999 	}
13000 	ipvers = IPH_HDR_VERSION(rptr);
13001 	if (ipvers == IPV4_VERSION) {
13002 		if (tcp == NULL) {
13003 			ip_hdr_len = IPH_HDR_LENGTH(rptr);
13004 			goto done;
13005 		}
13006 
13007 		ipp.ipp_fields |= IPPF_HOPLIMIT;
13008 		ipp.ipp_hoplimit = ((ipha_t *)rptr)->ipha_ttl;
13009 
13010 		/*
13011 		 * If we have IN_PKTINFO in an M_CTL and tcp_ipv6_recvancillary
13012 		 * has TCP_IPV6_RECVPKTINFO set, pass I/F index along in ipp.
13013 		 */
13014 		if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) &&
13015 		    mctl_present) {
13016 			pinfo = (ip_pktinfo_t *)first_mp->b_rptr;
13017 			if ((MBLKL(first_mp) == sizeof (ip_pktinfo_t)) &&
13018 			    (pinfo->ip_pkt_ulp_type == IN_PKTINFO) &&
13019 			    (pinfo->ip_pkt_flags & IPF_RECVIF)) {
13020 				ipp.ipp_fields |= IPPF_IFINDEX;
13021 				ipp.ipp_ifindex = pinfo->ip_pkt_ifindex;
13022 				ifindex = pinfo->ip_pkt_ifindex;
13023 			}
13024 			freeb(first_mp);
13025 			mctl_present = B_FALSE;
13026 		}
13027 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13028 	} else {
13029 		ip6h = (ip6_t *)rptr;
13030 
13031 		ASSERT(ipvers == IPV6_VERSION);
13032 		ipp.ipp_fields = IPPF_HOPLIMIT | IPPF_TCLASS;
13033 		ipp.ipp_tclass = (ip6h->ip6_flow & 0x0FF00000) >> 20;
13034 		ipp.ipp_hoplimit = ip6h->ip6_hops;
13035 
13036 		if (ip6h->ip6_nxt != IPPROTO_TCP) {
13037 			uint8_t	nexthdrp;
13038 			ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13039 
13040 			/* Look for ifindex information */
13041 			if (ip6h->ip6_nxt == IPPROTO_RAW) {
13042 				ip6i_t *ip6i = (ip6i_t *)ip6h;
13043 				if ((uchar_t *)&ip6i[1] > mp->b_wptr) {
13044 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13045 					freemsg(first_mp);
13046 					return (NULL);
13047 				}
13048 
13049 				if (ip6i->ip6i_flags & IP6I_IFINDEX) {
13050 					ASSERT(ip6i->ip6i_ifindex != 0);
13051 					ipp.ipp_fields |= IPPF_IFINDEX;
13052 					ipp.ipp_ifindex = ip6i->ip6i_ifindex;
13053 					ifindex = ip6i->ip6i_ifindex;
13054 				}
13055 				rptr = (uchar_t *)&ip6i[1];
13056 				mp->b_rptr = rptr;
13057 				if (rptr == mp->b_wptr) {
13058 					mblk_t *mp1;
13059 					mp1 = mp->b_cont;
13060 					freeb(mp);
13061 					mp = mp1;
13062 					rptr = mp->b_rptr;
13063 				}
13064 				if (MBLKL(mp) < IPV6_HDR_LEN +
13065 				    sizeof (tcph_t)) {
13066 					BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13067 					freemsg(first_mp);
13068 					return (NULL);
13069 				}
13070 				ip6h = (ip6_t *)rptr;
13071 			}
13072 
13073 			/*
13074 			 * Find any potentially interesting extension headers
13075 			 * as well as the length of the IPv6 + extension
13076 			 * headers.
13077 			 */
13078 			ip_hdr_len = ip_find_hdr_v6(mp, ip6h, &ipp, &nexthdrp);
13079 			/* Verify if this is a TCP packet */
13080 			if (nexthdrp != IPPROTO_TCP) {
13081 				BUMP_MIB(&ipst->ips_ip_mib, tcpInErrs);
13082 				freemsg(first_mp);
13083 				return (NULL);
13084 			}
13085 		} else {
13086 			ip_hdr_len = IPV6_HDR_LEN;
13087 		}
13088 	}
13089 
13090 done:
13091 	if (ipversp != NULL)
13092 		*ipversp = ipvers;
13093 	if (ip_hdr_lenp != NULL)
13094 		*ip_hdr_lenp = ip_hdr_len;
13095 	if (ippp != NULL)
13096 		*ippp = ipp;
13097 	if (ifindexp != NULL)
13098 		*ifindexp = ifindex;
13099 	if (mctl_present) {
13100 		freeb(first_mp);
13101 	}
13102 	return (mp);
13103 }
13104 
13105 /*
13106  * Handle M_DATA messages from IP. Its called directly from IP via
13107  * squeue for AF_INET type sockets fast path. No M_CTL are expected
13108  * in this path.
13109  *
13110  * For everything else (including AF_INET6 sockets with 'tcp_ipversion'
13111  * v4 and v6), we are called through tcp_input() and a M_CTL can
13112  * be present for options but tcp_find_pktinfo() deals with it. We
13113  * only expect M_DATA packets after tcp_find_pktinfo() is done.
13114  *
13115  * The first argument is always the connp/tcp to which the mp belongs.
13116  * There are no exceptions to this rule. The caller has already put
13117  * a reference on this connp/tcp and once tcp_rput_data() returns,
13118  * the squeue will do the refrele.
13119  *
13120  * The TH_SYN for the listener directly go to tcp_conn_request via
13121  * squeue.
13122  *
13123  * sqp: NULL = recursive, sqp != NULL means called from squeue
13124  */
13125 void
13126 tcp_rput_data(void *arg, mblk_t *mp, void *arg2)
13127 {
13128 	int32_t		bytes_acked;
13129 	int32_t		gap;
13130 	mblk_t		*mp1;
13131 	uint_t		flags;
13132 	uint32_t	new_swnd = 0;
13133 	uchar_t		*iphdr;
13134 	uchar_t		*rptr;
13135 	int32_t		rgap;
13136 	uint32_t	seg_ack;
13137 	int		seg_len;
13138 	uint_t		ip_hdr_len;
13139 	uint32_t	seg_seq;
13140 	tcph_t		*tcph;
13141 	int		urp;
13142 	tcp_opt_t	tcpopt;
13143 	uint_t		ipvers;
13144 	ip6_pkt_t	ipp;
13145 	boolean_t	ofo_seg = B_FALSE; /* Out of order segment */
13146 	uint32_t	cwnd;
13147 	uint32_t	add;
13148 	int		npkt;
13149 	int		mss;
13150 	conn_t		*connp = (conn_t *)arg;
13151 	squeue_t	*sqp = (squeue_t *)arg2;
13152 	tcp_t		*tcp = connp->conn_tcp;
13153 	tcp_stack_t	*tcps = tcp->tcp_tcps;
13154 
13155 	/*
13156 	 * RST from fused tcp loopback peer should trigger an unfuse.
13157 	 */
13158 	if (tcp->tcp_fused) {
13159 		TCP_STAT(tcps, tcp_fusion_aborted);
13160 		tcp_unfuse(tcp);
13161 	}
13162 
13163 	iphdr = mp->b_rptr;
13164 	rptr = mp->b_rptr;
13165 	ASSERT(OK_32PTR(rptr));
13166 
13167 	/*
13168 	 * An AF_INET socket is not capable of receiving any pktinfo. Do inline
13169 	 * processing here. For rest call tcp_find_pktinfo to fill up the
13170 	 * necessary information.
13171 	 */
13172 	if (IPCL_IS_TCP4(connp)) {
13173 		ipvers = IPV4_VERSION;
13174 		ip_hdr_len = IPH_HDR_LENGTH(rptr);
13175 	} else {
13176 		mp = tcp_find_pktinfo(tcp, mp, &ipvers, &ip_hdr_len,
13177 		    NULL, &ipp);
13178 		if (mp == NULL) {
13179 			TCP_STAT(tcps, tcp_rput_v6_error);
13180 			return;
13181 		}
13182 		iphdr = mp->b_rptr;
13183 		rptr = mp->b_rptr;
13184 	}
13185 	ASSERT(DB_TYPE(mp) == M_DATA);
13186 
13187 	tcph = (tcph_t *)&rptr[ip_hdr_len];
13188 	seg_seq = ABE32_TO_U32(tcph->th_seq);
13189 	seg_ack = ABE32_TO_U32(tcph->th_ack);
13190 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
13191 	seg_len = (int)(mp->b_wptr - rptr) -
13192 	    (ip_hdr_len + TCP_HDR_LENGTH(tcph));
13193 	if ((mp1 = mp->b_cont) != NULL && mp1->b_datap->db_type == M_DATA) {
13194 		do {
13195 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
13196 			    (uintptr_t)INT_MAX);
13197 			seg_len += (int)(mp1->b_wptr - mp1->b_rptr);
13198 		} while ((mp1 = mp1->b_cont) != NULL &&
13199 		    mp1->b_datap->db_type == M_DATA);
13200 	}
13201 
13202 	if (tcp->tcp_state == TCPS_TIME_WAIT) {
13203 		tcp_time_wait_processing(tcp, mp, seg_seq, seg_ack,
13204 		    seg_len, tcph);
13205 		return;
13206 	}
13207 
13208 	if (sqp != NULL) {
13209 		/*
13210 		 * This is the correct place to update tcp_last_recv_time. Note
13211 		 * that it is also updated for tcp structure that belongs to
13212 		 * global and listener queues which do not really need updating.
13213 		 * But that should not cause any harm.  And it is updated for
13214 		 * all kinds of incoming segments, not only for data segments.
13215 		 */
13216 		tcp->tcp_last_recv_time = lbolt;
13217 	}
13218 
13219 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13220 
13221 	BUMP_LOCAL(tcp->tcp_ibsegs);
13222 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13223 
13224 	if ((flags & TH_URG) && sqp != NULL) {
13225 		/*
13226 		 * TCP can't handle urgent pointers that arrive before
13227 		 * the connection has been accept()ed since it can't
13228 		 * buffer OOB data.  Discard segment if this happens.
13229 		 *
13230 		 * We can't just rely on a non-null tcp_listener to indicate
13231 		 * that the accept() has completed since unlinking of the
13232 		 * eager and completion of the accept are not atomic.
13233 		 * tcp_detached, when it is not set (B_FALSE) indicates
13234 		 * that the accept() has completed.
13235 		 *
13236 		 * Nor can it reassemble urgent pointers, so discard
13237 		 * if it's not the next segment expected.
13238 		 *
13239 		 * Otherwise, collapse chain into one mblk (discard if
13240 		 * that fails).  This makes sure the headers, retransmitted
13241 		 * data, and new data all are in the same mblk.
13242 		 */
13243 		ASSERT(mp != NULL);
13244 		if (tcp->tcp_detached || !pullupmsg(mp, -1)) {
13245 			freemsg(mp);
13246 			return;
13247 		}
13248 		/* Update pointers into message */
13249 		iphdr = rptr = mp->b_rptr;
13250 		tcph = (tcph_t *)&rptr[ip_hdr_len];
13251 		if (SEQ_GT(seg_seq, tcp->tcp_rnxt)) {
13252 			/*
13253 			 * Since we can't handle any data with this urgent
13254 			 * pointer that is out of sequence, we expunge
13255 			 * the data.  This allows us to still register
13256 			 * the urgent mark and generate the M_PCSIG,
13257 			 * which we can do.
13258 			 */
13259 			mp->b_wptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13260 			seg_len = 0;
13261 		}
13262 	}
13263 
13264 	switch (tcp->tcp_state) {
13265 	case TCPS_SYN_SENT:
13266 		if (flags & TH_ACK) {
13267 			/*
13268 			 * Note that our stack cannot send data before a
13269 			 * connection is established, therefore the
13270 			 * following check is valid.  Otherwise, it has
13271 			 * to be changed.
13272 			 */
13273 			if (SEQ_LEQ(seg_ack, tcp->tcp_iss) ||
13274 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13275 				freemsg(mp);
13276 				if (flags & TH_RST)
13277 					return;
13278 				tcp_xmit_ctl("TCPS_SYN_SENT-Bad_seq",
13279 				    tcp, seg_ack, 0, TH_RST);
13280 				return;
13281 			}
13282 			ASSERT(tcp->tcp_suna + 1 == seg_ack);
13283 		}
13284 		if (flags & TH_RST) {
13285 			freemsg(mp);
13286 			if (flags & TH_ACK)
13287 				(void) tcp_clean_death(tcp,
13288 				    ECONNREFUSED, 13);
13289 			return;
13290 		}
13291 		if (!(flags & TH_SYN)) {
13292 			freemsg(mp);
13293 			return;
13294 		}
13295 
13296 		/* Process all TCP options. */
13297 		tcp_process_options(tcp, tcph);
13298 		/*
13299 		 * The following changes our rwnd to be a multiple of the
13300 		 * MIN(peer MSS, our MSS) for performance reason.
13301 		 */
13302 		(void) tcp_rwnd_set(tcp, MSS_ROUNDUP(tcp->tcp_rq->q_hiwat,
13303 		    tcp->tcp_mss));
13304 
13305 		/* Is the other end ECN capable? */
13306 		if (tcp->tcp_ecn_ok) {
13307 			if ((flags & (TH_ECE|TH_CWR)) != TH_ECE) {
13308 				tcp->tcp_ecn_ok = B_FALSE;
13309 			}
13310 		}
13311 		/*
13312 		 * Clear ECN flags because it may interfere with later
13313 		 * processing.
13314 		 */
13315 		flags &= ~(TH_ECE|TH_CWR);
13316 
13317 		tcp->tcp_irs = seg_seq;
13318 		tcp->tcp_rack = seg_seq;
13319 		tcp->tcp_rnxt = seg_seq + 1;
13320 		U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13321 		if (!TCP_IS_DETACHED(tcp)) {
13322 			/* Allocate room for SACK options if needed. */
13323 			if (tcp->tcp_snd_sack_ok) {
13324 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13325 				    tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
13326 				    (tcp->tcp_loopback ? 0 :
13327 				    tcps->tcps_wroff_xtra));
13328 			} else {
13329 				(void) mi_set_sth_wroff(tcp->tcp_rq,
13330 				    tcp->tcp_hdr_len +
13331 				    (tcp->tcp_loopback ? 0 :
13332 				    tcps->tcps_wroff_xtra));
13333 			}
13334 		}
13335 		if (flags & TH_ACK) {
13336 			/*
13337 			 * If we can't get the confirmation upstream, pretend
13338 			 * we didn't even see this one.
13339 			 *
13340 			 * XXX: how can we pretend we didn't see it if we
13341 			 * have updated rnxt et. al.
13342 			 *
13343 			 * For loopback we defer sending up the T_CONN_CON
13344 			 * until after some checks below.
13345 			 */
13346 			mp1 = NULL;
13347 			if (!tcp_conn_con(tcp, iphdr, tcph, mp,
13348 			    tcp->tcp_loopback ? &mp1 : NULL)) {
13349 				freemsg(mp);
13350 				return;
13351 			}
13352 			/* SYN was acked - making progress */
13353 			if (tcp->tcp_ipversion == IPV6_VERSION)
13354 				tcp->tcp_ip_forward_progress = B_TRUE;
13355 
13356 			/* One for the SYN */
13357 			tcp->tcp_suna = tcp->tcp_iss + 1;
13358 			tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
13359 			tcp->tcp_state = TCPS_ESTABLISHED;
13360 
13361 			/*
13362 			 * If SYN was retransmitted, need to reset all
13363 			 * retransmission info.  This is because this
13364 			 * segment will be treated as a dup ACK.
13365 			 */
13366 			if (tcp->tcp_rexmit) {
13367 				tcp->tcp_rexmit = B_FALSE;
13368 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
13369 				tcp->tcp_rexmit_max = tcp->tcp_snxt;
13370 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
13371 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
13372 				tcp->tcp_ms_we_have_waited = 0;
13373 
13374 				/*
13375 				 * Set tcp_cwnd back to 1 MSS, per
13376 				 * recommendation from
13377 				 * draft-floyd-incr-init-win-01.txt,
13378 				 * Increasing TCP's Initial Window.
13379 				 */
13380 				tcp->tcp_cwnd = tcp->tcp_mss;
13381 			}
13382 
13383 			tcp->tcp_swl1 = seg_seq;
13384 			tcp->tcp_swl2 = seg_ack;
13385 
13386 			new_swnd = BE16_TO_U16(tcph->th_win);
13387 			tcp->tcp_swnd = new_swnd;
13388 			if (new_swnd > tcp->tcp_max_swnd)
13389 				tcp->tcp_max_swnd = new_swnd;
13390 
13391 			/*
13392 			 * Always send the three-way handshake ack immediately
13393 			 * in order to make the connection complete as soon as
13394 			 * possible on the accepting host.
13395 			 */
13396 			flags |= TH_ACK_NEEDED;
13397 
13398 			/*
13399 			 * Special case for loopback.  At this point we have
13400 			 * received SYN-ACK from the remote endpoint.  In
13401 			 * order to ensure that both endpoints reach the
13402 			 * fused state prior to any data exchange, the final
13403 			 * ACK needs to be sent before we indicate T_CONN_CON
13404 			 * to the module upstream.
13405 			 */
13406 			if (tcp->tcp_loopback) {
13407 				mblk_t *ack_mp;
13408 
13409 				ASSERT(!tcp->tcp_unfusable);
13410 				ASSERT(mp1 != NULL);
13411 				/*
13412 				 * For loopback, we always get a pure SYN-ACK
13413 				 * and only need to send back the final ACK
13414 				 * with no data (this is because the other
13415 				 * tcp is ours and we don't do T/TCP).  This
13416 				 * final ACK triggers the passive side to
13417 				 * perform fusion in ESTABLISHED state.
13418 				 */
13419 				if ((ack_mp = tcp_ack_mp(tcp)) != NULL) {
13420 					if (tcp->tcp_ack_tid != 0) {
13421 						(void) TCP_TIMER_CANCEL(tcp,
13422 						    tcp->tcp_ack_tid);
13423 						tcp->tcp_ack_tid = 0;
13424 					}
13425 					tcp_send_data(tcp, tcp->tcp_wq, ack_mp);
13426 					BUMP_LOCAL(tcp->tcp_obsegs);
13427 					BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
13428 
13429 					/* Send up T_CONN_CON */
13430 					putnext(tcp->tcp_rq, mp1);
13431 
13432 					freemsg(mp);
13433 					return;
13434 				}
13435 				/*
13436 				 * Forget fusion; we need to handle more
13437 				 * complex cases below.  Send the deferred
13438 				 * T_CONN_CON message upstream and proceed
13439 				 * as usual.  Mark this tcp as not capable
13440 				 * of fusion.
13441 				 */
13442 				TCP_STAT(tcps, tcp_fusion_unfusable);
13443 				tcp->tcp_unfusable = B_TRUE;
13444 				putnext(tcp->tcp_rq, mp1);
13445 			}
13446 
13447 			/*
13448 			 * Check to see if there is data to be sent.  If
13449 			 * yes, set the transmit flag.  Then check to see
13450 			 * if received data processing needs to be done.
13451 			 * If not, go straight to xmit_check.  This short
13452 			 * cut is OK as we don't support T/TCP.
13453 			 */
13454 			if (tcp->tcp_unsent)
13455 				flags |= TH_XMIT_NEEDED;
13456 
13457 			if (seg_len == 0 && !(flags & TH_URG)) {
13458 				freemsg(mp);
13459 				goto xmit_check;
13460 			}
13461 
13462 			flags &= ~TH_SYN;
13463 			seg_seq++;
13464 			break;
13465 		}
13466 		tcp->tcp_state = TCPS_SYN_RCVD;
13467 		mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, tcp->tcp_mss,
13468 		    NULL, NULL, tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
13469 		if (mp1) {
13470 			DB_CPID(mp1) = tcp->tcp_cpid;
13471 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
13472 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
13473 		}
13474 		freemsg(mp);
13475 		return;
13476 	case TCPS_SYN_RCVD:
13477 		if (flags & TH_ACK) {
13478 			/*
13479 			 * In this state, a SYN|ACK packet is either bogus
13480 			 * because the other side must be ACKing our SYN which
13481 			 * indicates it has seen the ACK for their SYN and
13482 			 * shouldn't retransmit it or we're crossing SYNs
13483 			 * on active open.
13484 			 */
13485 			if ((flags & TH_SYN) && !tcp->tcp_active_open) {
13486 				freemsg(mp);
13487 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_syn",
13488 				    tcp, seg_ack, 0, TH_RST);
13489 				return;
13490 			}
13491 			/*
13492 			 * NOTE: RFC 793 pg. 72 says this should be
13493 			 * tcp->tcp_suna <= seg_ack <= tcp->tcp_snxt
13494 			 * but that would mean we have an ack that ignored
13495 			 * our SYN.
13496 			 */
13497 			if (SEQ_LEQ(seg_ack, tcp->tcp_suna) ||
13498 			    SEQ_GT(seg_ack, tcp->tcp_snxt)) {
13499 				freemsg(mp);
13500 				tcp_xmit_ctl("TCPS_SYN_RCVD-bad_ack",
13501 				    tcp, seg_ack, 0, TH_RST);
13502 				return;
13503 			}
13504 		}
13505 		break;
13506 	case TCPS_LISTEN:
13507 		/*
13508 		 * Only a TLI listener can come through this path when a
13509 		 * acceptor is going back to be a listener and a packet
13510 		 * for the acceptor hits the classifier. For a socket
13511 		 * listener, this can never happen because a listener
13512 		 * can never accept connection on itself and hence a
13513 		 * socket acceptor can not go back to being a listener.
13514 		 */
13515 		ASSERT(!TCP_IS_SOCKET(tcp));
13516 		/*FALLTHRU*/
13517 	case TCPS_CLOSED:
13518 	case TCPS_BOUND: {
13519 		conn_t	*new_connp;
13520 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
13521 
13522 		new_connp = ipcl_classify(mp, connp->conn_zoneid, ipst);
13523 		if (new_connp != NULL) {
13524 			tcp_reinput(new_connp, mp, connp->conn_sqp);
13525 			return;
13526 		}
13527 		/* We failed to classify. For now just drop the packet */
13528 		freemsg(mp);
13529 		return;
13530 	}
13531 	case TCPS_IDLE:
13532 		/*
13533 		 * Handle the case where the tcp_clean_death() has happened
13534 		 * on a connection (application hasn't closed yet) but a packet
13535 		 * was already queued on squeue before tcp_clean_death()
13536 		 * was processed. Calling tcp_clean_death() twice on same
13537 		 * connection can result in weird behaviour.
13538 		 */
13539 		freemsg(mp);
13540 		return;
13541 	default:
13542 		break;
13543 	}
13544 
13545 	/*
13546 	 * Already on the correct queue/perimeter.
13547 	 * If this is a detached connection and not an eager
13548 	 * connection hanging off a listener then new data
13549 	 * (past the FIN) will cause a reset.
13550 	 * We do a special check here where it
13551 	 * is out of the main line, rather than check
13552 	 * if we are detached every time we see new
13553 	 * data down below.
13554 	 */
13555 	if (TCP_IS_DETACHED_NONEAGER(tcp) &&
13556 	    (seg_len > 0 && SEQ_GT(seg_seq + seg_len, tcp->tcp_rnxt))) {
13557 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
13558 		DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
13559 
13560 		freemsg(mp);
13561 		/*
13562 		 * This could be an SSL closure alert. We're detached so just
13563 		 * acknowledge it this last time.
13564 		 */
13565 		if (tcp->tcp_kssl_ctx != NULL) {
13566 			kssl_release_ctx(tcp->tcp_kssl_ctx);
13567 			tcp->tcp_kssl_ctx = NULL;
13568 
13569 			tcp->tcp_rnxt += seg_len;
13570 			U32_TO_ABE32(tcp->tcp_rnxt, tcp->tcp_tcph->th_ack);
13571 			flags |= TH_ACK_NEEDED;
13572 			goto ack_check;
13573 		}
13574 
13575 		tcp_xmit_ctl("new data when detached", tcp,
13576 		    tcp->tcp_snxt, 0, TH_RST);
13577 		(void) tcp_clean_death(tcp, EPROTO, 12);
13578 		return;
13579 	}
13580 
13581 	mp->b_rptr = (uchar_t *)tcph + TCP_HDR_LENGTH(tcph);
13582 	urp = BE16_TO_U16(tcph->th_urp) - TCP_OLD_URP_INTERPRETATION;
13583 	new_swnd = BE16_TO_U16(tcph->th_win) <<
13584 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
13585 
13586 	if (tcp->tcp_snd_ts_ok) {
13587 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
13588 			/*
13589 			 * This segment is not acceptable.
13590 			 * Drop it and send back an ACK.
13591 			 */
13592 			freemsg(mp);
13593 			flags |= TH_ACK_NEEDED;
13594 			goto ack_check;
13595 		}
13596 	} else if (tcp->tcp_snd_sack_ok) {
13597 		ASSERT(tcp->tcp_sack_info != NULL);
13598 		tcpopt.tcp = tcp;
13599 		/*
13600 		 * SACK info in already updated in tcp_parse_options.  Ignore
13601 		 * all other TCP options...
13602 		 */
13603 		(void) tcp_parse_options(tcph, &tcpopt);
13604 	}
13605 try_again:;
13606 	mss = tcp->tcp_mss;
13607 	gap = seg_seq - tcp->tcp_rnxt;
13608 	rgap = tcp->tcp_rwnd - (gap + seg_len);
13609 	/*
13610 	 * gap is the amount of sequence space between what we expect to see
13611 	 * and what we got for seg_seq.  A positive value for gap means
13612 	 * something got lost.  A negative value means we got some old stuff.
13613 	 */
13614 	if (gap < 0) {
13615 		/* Old stuff present.  Is the SYN in there? */
13616 		if (seg_seq == tcp->tcp_irs && (flags & TH_SYN) &&
13617 		    (seg_len != 0)) {
13618 			flags &= ~TH_SYN;
13619 			seg_seq++;
13620 			urp--;
13621 			/* Recompute the gaps after noting the SYN. */
13622 			goto try_again;
13623 		}
13624 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
13625 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
13626 		    (seg_len > -gap ? -gap : seg_len));
13627 		/* Remove the old stuff from seg_len. */
13628 		seg_len += gap;
13629 		/*
13630 		 * Anything left?
13631 		 * Make sure to check for unack'd FIN when rest of data
13632 		 * has been previously ack'd.
13633 		 */
13634 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
13635 			/*
13636 			 * Resets are only valid if they lie within our offered
13637 			 * window.  If the RST bit is set, we just ignore this
13638 			 * segment.
13639 			 */
13640 			if (flags & TH_RST) {
13641 				freemsg(mp);
13642 				return;
13643 			}
13644 
13645 			/*
13646 			 * The arriving of dup data packets indicate that we
13647 			 * may have postponed an ack for too long, or the other
13648 			 * side's RTT estimate is out of shape. Start acking
13649 			 * more often.
13650 			 */
13651 			if (SEQ_GEQ(seg_seq + seg_len - gap, tcp->tcp_rack) &&
13652 			    tcp->tcp_rack_cnt >= 1 &&
13653 			    tcp->tcp_rack_abs_max > 2) {
13654 				tcp->tcp_rack_abs_max--;
13655 			}
13656 			tcp->tcp_rack_cur_max = 1;
13657 
13658 			/*
13659 			 * This segment is "unacceptable".  None of its
13660 			 * sequence space lies within our advertized window.
13661 			 *
13662 			 * Adjust seg_len to the original value for tracing.
13663 			 */
13664 			seg_len -= gap;
13665 			if (tcp->tcp_debug) {
13666 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
13667 				    "tcp_rput: unacceptable, gap %d, rgap %d, "
13668 				    "flags 0x%x, seg_seq %u, seg_ack %u, "
13669 				    "seg_len %d, rnxt %u, snxt %u, %s",
13670 				    gap, rgap, flags, seg_seq, seg_ack,
13671 				    seg_len, tcp->tcp_rnxt, tcp->tcp_snxt,
13672 				    tcp_display(tcp, NULL,
13673 				    DISP_ADDR_AND_PORT));
13674 			}
13675 
13676 			/*
13677 			 * Arrange to send an ACK in response to the
13678 			 * unacceptable segment per RFC 793 page 69. There
13679 			 * is only one small difference between ours and the
13680 			 * acceptability test in the RFC - we accept ACK-only
13681 			 * packet with SEG.SEQ = RCV.NXT+RCV.WND and no ACK
13682 			 * will be generated.
13683 			 *
13684 			 * Note that we have to ACK an ACK-only packet at least
13685 			 * for stacks that send 0-length keep-alives with
13686 			 * SEG.SEQ = SND.NXT-1 as recommended by RFC1122,
13687 			 * section 4.2.3.6. As long as we don't ever generate
13688 			 * an unacceptable packet in response to an incoming
13689 			 * packet that is unacceptable, it should not cause
13690 			 * "ACK wars".
13691 			 */
13692 			flags |=  TH_ACK_NEEDED;
13693 
13694 			/*
13695 			 * Continue processing this segment in order to use the
13696 			 * ACK information it contains, but skip all other
13697 			 * sequence-number processing.	Processing the ACK
13698 			 * information is necessary in order to
13699 			 * re-synchronize connections that may have lost
13700 			 * synchronization.
13701 			 *
13702 			 * We clear seg_len and flag fields related to
13703 			 * sequence number processing as they are not
13704 			 * to be trusted for an unacceptable segment.
13705 			 */
13706 			seg_len = 0;
13707 			flags &= ~(TH_SYN | TH_FIN | TH_URG);
13708 			goto process_ack;
13709 		}
13710 
13711 		/* Fix seg_seq, and chew the gap off the front. */
13712 		seg_seq = tcp->tcp_rnxt;
13713 		urp += gap;
13714 		do {
13715 			mblk_t	*mp2;
13716 			ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13717 			    (uintptr_t)UINT_MAX);
13718 			gap += (uint_t)(mp->b_wptr - mp->b_rptr);
13719 			if (gap > 0) {
13720 				mp->b_rptr = mp->b_wptr - gap;
13721 				break;
13722 			}
13723 			mp2 = mp;
13724 			mp = mp->b_cont;
13725 			freeb(mp2);
13726 		} while (gap < 0);
13727 		/*
13728 		 * If the urgent data has already been acknowledged, we
13729 		 * should ignore TH_URG below
13730 		 */
13731 		if (urp < 0)
13732 			flags &= ~TH_URG;
13733 	}
13734 	/*
13735 	 * rgap is the amount of stuff received out of window.  A negative
13736 	 * value is the amount out of window.
13737 	 */
13738 	if (rgap < 0) {
13739 		mblk_t	*mp2;
13740 
13741 		if (tcp->tcp_rwnd == 0) {
13742 			BUMP_MIB(&tcps->tcps_mib, tcpInWinProbe);
13743 		} else {
13744 			BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
13745 			UPDATE_MIB(&tcps->tcps_mib,
13746 			    tcpInDataPastWinBytes, -rgap);
13747 		}
13748 
13749 		/*
13750 		 * seg_len does not include the FIN, so if more than
13751 		 * just the FIN is out of window, we act like we don't
13752 		 * see it.  (If just the FIN is out of window, rgap
13753 		 * will be zero and we will go ahead and acknowledge
13754 		 * the FIN.)
13755 		 */
13756 		flags &= ~TH_FIN;
13757 
13758 		/* Fix seg_len and make sure there is something left. */
13759 		seg_len += rgap;
13760 		if (seg_len <= 0) {
13761 			/*
13762 			 * Resets are only valid if they lie within our offered
13763 			 * window.  If the RST bit is set, we just ignore this
13764 			 * segment.
13765 			 */
13766 			if (flags & TH_RST) {
13767 				freemsg(mp);
13768 				return;
13769 			}
13770 
13771 			/* Per RFC 793, we need to send back an ACK. */
13772 			flags |= TH_ACK_NEEDED;
13773 
13774 			/*
13775 			 * Send SIGURG as soon as possible i.e. even
13776 			 * if the TH_URG was delivered in a window probe
13777 			 * packet (which will be unacceptable).
13778 			 *
13779 			 * We generate a signal if none has been generated
13780 			 * for this connection or if this is a new urgent
13781 			 * byte. Also send a zero-length "unmarked" message
13782 			 * to inform SIOCATMARK that this is not the mark.
13783 			 *
13784 			 * tcp_urp_last_valid is cleared when the T_exdata_ind
13785 			 * is sent up. This plus the check for old data
13786 			 * (gap >= 0) handles the wraparound of the sequence
13787 			 * number space without having to always track the
13788 			 * correct MAX(tcp_urp_last, tcp_rnxt). (BSD tracks
13789 			 * this max in its rcv_up variable).
13790 			 *
13791 			 * This prevents duplicate SIGURGS due to a "late"
13792 			 * zero-window probe when the T_EXDATA_IND has already
13793 			 * been sent up.
13794 			 */
13795 			if ((flags & TH_URG) &&
13796 			    (!tcp->tcp_urp_last_valid || SEQ_GT(urp + seg_seq,
13797 			    tcp->tcp_urp_last))) {
13798 				mp1 = allocb(0, BPRI_MED);
13799 				if (mp1 == NULL) {
13800 					freemsg(mp);
13801 					return;
13802 				}
13803 				if (!TCP_IS_DETACHED(tcp) &&
13804 				    !putnextctl1(tcp->tcp_rq, M_PCSIG,
13805 				    SIGURG)) {
13806 					/* Try again on the rexmit. */
13807 					freemsg(mp1);
13808 					freemsg(mp);
13809 					return;
13810 				}
13811 				/*
13812 				 * If the next byte would be the mark
13813 				 * then mark with MARKNEXT else mark
13814 				 * with NOTMARKNEXT.
13815 				 */
13816 				if (gap == 0 && urp == 0)
13817 					mp1->b_flag |= MSGMARKNEXT;
13818 				else
13819 					mp1->b_flag |= MSGNOTMARKNEXT;
13820 				freemsg(tcp->tcp_urp_mark_mp);
13821 				tcp->tcp_urp_mark_mp = mp1;
13822 				flags |= TH_SEND_URP_MARK;
13823 				tcp->tcp_urp_last_valid = B_TRUE;
13824 				tcp->tcp_urp_last = urp + seg_seq;
13825 			}
13826 			/*
13827 			 * If this is a zero window probe, continue to
13828 			 * process the ACK part.  But we need to set seg_len
13829 			 * to 0 to avoid data processing.  Otherwise just
13830 			 * drop the segment and send back an ACK.
13831 			 */
13832 			if (tcp->tcp_rwnd == 0 && seg_seq == tcp->tcp_rnxt) {
13833 				flags &= ~(TH_SYN | TH_URG);
13834 				seg_len = 0;
13835 				goto process_ack;
13836 			} else {
13837 				freemsg(mp);
13838 				goto ack_check;
13839 			}
13840 		}
13841 		/* Pitch out of window stuff off the end. */
13842 		rgap = seg_len;
13843 		mp2 = mp;
13844 		do {
13845 			ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
13846 			    (uintptr_t)INT_MAX);
13847 			rgap -= (int)(mp2->b_wptr - mp2->b_rptr);
13848 			if (rgap < 0) {
13849 				mp2->b_wptr += rgap;
13850 				if ((mp1 = mp2->b_cont) != NULL) {
13851 					mp2->b_cont = NULL;
13852 					freemsg(mp1);
13853 				}
13854 				break;
13855 			}
13856 		} while ((mp2 = mp2->b_cont) != NULL);
13857 	}
13858 ok:;
13859 	/*
13860 	 * TCP should check ECN info for segments inside the window only.
13861 	 * Therefore the check should be done here.
13862 	 */
13863 	if (tcp->tcp_ecn_ok) {
13864 		if (flags & TH_CWR) {
13865 			tcp->tcp_ecn_echo_on = B_FALSE;
13866 		}
13867 		/*
13868 		 * Note that both ECN_CE and CWR can be set in the
13869 		 * same segment.  In this case, we once again turn
13870 		 * on ECN_ECHO.
13871 		 */
13872 		if (tcp->tcp_ipversion == IPV4_VERSION) {
13873 			uchar_t tos = ((ipha_t *)rptr)->ipha_type_of_service;
13874 
13875 			if ((tos & IPH_ECN_CE) == IPH_ECN_CE) {
13876 				tcp->tcp_ecn_echo_on = B_TRUE;
13877 			}
13878 		} else {
13879 			uint32_t vcf = ((ip6_t *)rptr)->ip6_vcf;
13880 
13881 			if ((vcf & htonl(IPH_ECN_CE << 20)) ==
13882 			    htonl(IPH_ECN_CE << 20)) {
13883 				tcp->tcp_ecn_echo_on = B_TRUE;
13884 			}
13885 		}
13886 	}
13887 
13888 	/*
13889 	 * Check whether we can update tcp_ts_recent.  This test is
13890 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
13891 	 * Extensions for High Performance: An Update", Internet Draft.
13892 	 */
13893 	if (tcp->tcp_snd_ts_ok &&
13894 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
13895 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
13896 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
13897 		tcp->tcp_last_rcv_lbolt = lbolt64;
13898 	}
13899 
13900 	if (seg_seq != tcp->tcp_rnxt || tcp->tcp_reass_head) {
13901 		/*
13902 		 * FIN in an out of order segment.  We record this in
13903 		 * tcp_valid_bits and the seq num of FIN in tcp_ofo_fin_seq.
13904 		 * Clear the FIN so that any check on FIN flag will fail.
13905 		 * Remember that FIN also counts in the sequence number
13906 		 * space.  So we need to ack out of order FIN only segments.
13907 		 */
13908 		if (flags & TH_FIN) {
13909 			tcp->tcp_valid_bits |= TCP_OFO_FIN_VALID;
13910 			tcp->tcp_ofo_fin_seq = seg_seq + seg_len;
13911 			flags &= ~TH_FIN;
13912 			flags |= TH_ACK_NEEDED;
13913 		}
13914 		if (seg_len > 0) {
13915 			/* Fill in the SACK blk list. */
13916 			if (tcp->tcp_snd_sack_ok) {
13917 				ASSERT(tcp->tcp_sack_info != NULL);
13918 				tcp_sack_insert(tcp->tcp_sack_list,
13919 				    seg_seq, seg_seq + seg_len,
13920 				    &(tcp->tcp_num_sack_blk));
13921 			}
13922 
13923 			/*
13924 			 * Attempt reassembly and see if we have something
13925 			 * ready to go.
13926 			 */
13927 			mp = tcp_reass(tcp, mp, seg_seq);
13928 			/* Always ack out of order packets */
13929 			flags |= TH_ACK_NEEDED | TH_PUSH;
13930 			if (mp) {
13931 				ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
13932 				    (uintptr_t)INT_MAX);
13933 				seg_len = mp->b_cont ? msgdsize(mp) :
13934 				    (int)(mp->b_wptr - mp->b_rptr);
13935 				seg_seq = tcp->tcp_rnxt;
13936 				/*
13937 				 * A gap is filled and the seq num and len
13938 				 * of the gap match that of a previously
13939 				 * received FIN, put the FIN flag back in.
13940 				 */
13941 				if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13942 				    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13943 					flags |= TH_FIN;
13944 					tcp->tcp_valid_bits &=
13945 					    ~TCP_OFO_FIN_VALID;
13946 				}
13947 			} else {
13948 				/*
13949 				 * Keep going even with NULL mp.
13950 				 * There may be a useful ACK or something else
13951 				 * we don't want to miss.
13952 				 *
13953 				 * But TCP should not perform fast retransmit
13954 				 * because of the ack number.  TCP uses
13955 				 * seg_len == 0 to determine if it is a pure
13956 				 * ACK.  And this is not a pure ACK.
13957 				 */
13958 				seg_len = 0;
13959 				ofo_seg = B_TRUE;
13960 			}
13961 		}
13962 	} else if (seg_len > 0) {
13963 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
13964 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
13965 		/*
13966 		 * If an out of order FIN was received before, and the seq
13967 		 * num and len of the new segment match that of the FIN,
13968 		 * put the FIN flag back in.
13969 		 */
13970 		if ((tcp->tcp_valid_bits & TCP_OFO_FIN_VALID) &&
13971 		    seg_seq + seg_len == tcp->tcp_ofo_fin_seq) {
13972 			flags |= TH_FIN;
13973 			tcp->tcp_valid_bits &= ~TCP_OFO_FIN_VALID;
13974 		}
13975 	}
13976 	if ((flags & (TH_RST | TH_SYN | TH_URG | TH_ACK)) != TH_ACK) {
13977 	if (flags & TH_RST) {
13978 		freemsg(mp);
13979 		switch (tcp->tcp_state) {
13980 		case TCPS_SYN_RCVD:
13981 			(void) tcp_clean_death(tcp, ECONNREFUSED, 14);
13982 			break;
13983 		case TCPS_ESTABLISHED:
13984 		case TCPS_FIN_WAIT_1:
13985 		case TCPS_FIN_WAIT_2:
13986 		case TCPS_CLOSE_WAIT:
13987 			(void) tcp_clean_death(tcp, ECONNRESET, 15);
13988 			break;
13989 		case TCPS_CLOSING:
13990 		case TCPS_LAST_ACK:
13991 			(void) tcp_clean_death(tcp, 0, 16);
13992 			break;
13993 		default:
13994 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
13995 			(void) tcp_clean_death(tcp, ENXIO, 17);
13996 			break;
13997 		}
13998 		return;
13999 	}
14000 	if (flags & TH_SYN) {
14001 		/*
14002 		 * See RFC 793, Page 71
14003 		 *
14004 		 * The seq number must be in the window as it should
14005 		 * be "fixed" above.  If it is outside window, it should
14006 		 * be already rejected.  Note that we allow seg_seq to be
14007 		 * rnxt + rwnd because we want to accept 0 window probe.
14008 		 */
14009 		ASSERT(SEQ_GEQ(seg_seq, tcp->tcp_rnxt) &&
14010 		    SEQ_LEQ(seg_seq, tcp->tcp_rnxt + tcp->tcp_rwnd));
14011 		freemsg(mp);
14012 		/*
14013 		 * If the ACK flag is not set, just use our snxt as the
14014 		 * seq number of the RST segment.
14015 		 */
14016 		if (!(flags & TH_ACK)) {
14017 			seg_ack = tcp->tcp_snxt;
14018 		}
14019 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
14020 		    TH_RST|TH_ACK);
14021 		ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
14022 		(void) tcp_clean_death(tcp, ECONNRESET, 18);
14023 		return;
14024 	}
14025 	/*
14026 	 * urp could be -1 when the urp field in the packet is 0
14027 	 * and TCP_OLD_URP_INTERPRETATION is set. This implies that the urgent
14028 	 * byte was at seg_seq - 1, in which case we ignore the urgent flag.
14029 	 */
14030 	if (flags & TH_URG && urp >= 0) {
14031 		if (!tcp->tcp_urp_last_valid ||
14032 		    SEQ_GT(urp + seg_seq, tcp->tcp_urp_last)) {
14033 			/*
14034 			 * If we haven't generated the signal yet for this
14035 			 * urgent pointer value, do it now.  Also, send up a
14036 			 * zero-length M_DATA indicating whether or not this is
14037 			 * the mark. The latter is not needed when a
14038 			 * T_EXDATA_IND is sent up. However, if there are
14039 			 * allocation failures this code relies on the sender
14040 			 * retransmitting and the socket code for determining
14041 			 * the mark should not block waiting for the peer to
14042 			 * transmit. Thus, for simplicity we always send up the
14043 			 * mark indication.
14044 			 */
14045 			mp1 = allocb(0, BPRI_MED);
14046 			if (mp1 == NULL) {
14047 				freemsg(mp);
14048 				return;
14049 			}
14050 			if (!TCP_IS_DETACHED(tcp) &&
14051 			    !putnextctl1(tcp->tcp_rq, M_PCSIG, SIGURG)) {
14052 				/* Try again on the rexmit. */
14053 				freemsg(mp1);
14054 				freemsg(mp);
14055 				return;
14056 			}
14057 			/*
14058 			 * Mark with NOTMARKNEXT for now.
14059 			 * The code below will change this to MARKNEXT
14060 			 * if we are at the mark.
14061 			 *
14062 			 * If there are allocation failures (e.g. in dupmsg
14063 			 * below) the next time tcp_rput_data sees the urgent
14064 			 * segment it will send up the MSG*MARKNEXT message.
14065 			 */
14066 			mp1->b_flag |= MSGNOTMARKNEXT;
14067 			freemsg(tcp->tcp_urp_mark_mp);
14068 			tcp->tcp_urp_mark_mp = mp1;
14069 			flags |= TH_SEND_URP_MARK;
14070 #ifdef DEBUG
14071 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14072 			    "tcp_rput: sent M_PCSIG 2 seq %x urp %x "
14073 			    "last %x, %s",
14074 			    seg_seq, urp, tcp->tcp_urp_last,
14075 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14076 #endif /* DEBUG */
14077 			tcp->tcp_urp_last_valid = B_TRUE;
14078 			tcp->tcp_urp_last = urp + seg_seq;
14079 		} else if (tcp->tcp_urp_mark_mp != NULL) {
14080 			/*
14081 			 * An allocation failure prevented the previous
14082 			 * tcp_rput_data from sending up the allocated
14083 			 * MSG*MARKNEXT message - send it up this time
14084 			 * around.
14085 			 */
14086 			flags |= TH_SEND_URP_MARK;
14087 		}
14088 
14089 		/*
14090 		 * If the urgent byte is in this segment, make sure that it is
14091 		 * all by itself.  This makes it much easier to deal with the
14092 		 * possibility of an allocation failure on the T_exdata_ind.
14093 		 * Note that seg_len is the number of bytes in the segment, and
14094 		 * urp is the offset into the segment of the urgent byte.
14095 		 * urp < seg_len means that the urgent byte is in this segment.
14096 		 */
14097 		if (urp < seg_len) {
14098 			if (seg_len != 1) {
14099 				uint32_t  tmp_rnxt;
14100 				/*
14101 				 * Break it up and feed it back in.
14102 				 * Re-attach the IP header.
14103 				 */
14104 				mp->b_rptr = iphdr;
14105 				if (urp > 0) {
14106 					/*
14107 					 * There is stuff before the urgent
14108 					 * byte.
14109 					 */
14110 					mp1 = dupmsg(mp);
14111 					if (!mp1) {
14112 						/*
14113 						 * Trim from urgent byte on.
14114 						 * The rest will come back.
14115 						 */
14116 						(void) adjmsg(mp,
14117 						    urp - seg_len);
14118 						tcp_rput_data(connp,
14119 						    mp, NULL);
14120 						return;
14121 					}
14122 					(void) adjmsg(mp1, urp - seg_len);
14123 					/* Feed this piece back in. */
14124 					tmp_rnxt = tcp->tcp_rnxt;
14125 					tcp_rput_data(connp, mp1, NULL);
14126 					/*
14127 					 * If the data passed back in was not
14128 					 * processed (ie: bad ACK) sending
14129 					 * the remainder back in will cause a
14130 					 * loop. In this case, drop the
14131 					 * packet and let the sender try
14132 					 * sending a good packet.
14133 					 */
14134 					if (tmp_rnxt == tcp->tcp_rnxt) {
14135 						freemsg(mp);
14136 						return;
14137 					}
14138 				}
14139 				if (urp != seg_len - 1) {
14140 					uint32_t  tmp_rnxt;
14141 					/*
14142 					 * There is stuff after the urgent
14143 					 * byte.
14144 					 */
14145 					mp1 = dupmsg(mp);
14146 					if (!mp1) {
14147 						/*
14148 						 * Trim everything beyond the
14149 						 * urgent byte.  The rest will
14150 						 * come back.
14151 						 */
14152 						(void) adjmsg(mp,
14153 						    urp + 1 - seg_len);
14154 						tcp_rput_data(connp,
14155 						    mp, NULL);
14156 						return;
14157 					}
14158 					(void) adjmsg(mp1, urp + 1 - seg_len);
14159 					tmp_rnxt = tcp->tcp_rnxt;
14160 					tcp_rput_data(connp, mp1, NULL);
14161 					/*
14162 					 * If the data passed back in was not
14163 					 * processed (ie: bad ACK) sending
14164 					 * the remainder back in will cause a
14165 					 * loop. In this case, drop the
14166 					 * packet and let the sender try
14167 					 * sending a good packet.
14168 					 */
14169 					if (tmp_rnxt == tcp->tcp_rnxt) {
14170 						freemsg(mp);
14171 						return;
14172 					}
14173 				}
14174 				tcp_rput_data(connp, mp, NULL);
14175 				return;
14176 			}
14177 			/*
14178 			 * This segment contains only the urgent byte.  We
14179 			 * have to allocate the T_exdata_ind, if we can.
14180 			 */
14181 			if (!tcp->tcp_urp_mp) {
14182 				struct T_exdata_ind *tei;
14183 				mp1 = allocb(sizeof (struct T_exdata_ind),
14184 				    BPRI_MED);
14185 				if (!mp1) {
14186 					/*
14187 					 * Sigh... It'll be back.
14188 					 * Generate any MSG*MARK message now.
14189 					 */
14190 					freemsg(mp);
14191 					seg_len = 0;
14192 					if (flags & TH_SEND_URP_MARK) {
14193 
14194 
14195 						ASSERT(tcp->tcp_urp_mark_mp);
14196 						tcp->tcp_urp_mark_mp->b_flag &=
14197 						    ~MSGNOTMARKNEXT;
14198 						tcp->tcp_urp_mark_mp->b_flag |=
14199 						    MSGMARKNEXT;
14200 					}
14201 					goto ack_check;
14202 				}
14203 				mp1->b_datap->db_type = M_PROTO;
14204 				tei = (struct T_exdata_ind *)mp1->b_rptr;
14205 				tei->PRIM_type = T_EXDATA_IND;
14206 				tei->MORE_flag = 0;
14207 				mp1->b_wptr = (uchar_t *)&tei[1];
14208 				tcp->tcp_urp_mp = mp1;
14209 #ifdef DEBUG
14210 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14211 				    "tcp_rput: allocated exdata_ind %s",
14212 				    tcp_display(tcp, NULL,
14213 				    DISP_PORT_ONLY));
14214 #endif /* DEBUG */
14215 				/*
14216 				 * There is no need to send a separate MSG*MARK
14217 				 * message since the T_EXDATA_IND will be sent
14218 				 * now.
14219 				 */
14220 				flags &= ~TH_SEND_URP_MARK;
14221 				freemsg(tcp->tcp_urp_mark_mp);
14222 				tcp->tcp_urp_mark_mp = NULL;
14223 			}
14224 			/*
14225 			 * Now we are all set.  On the next putnext upstream,
14226 			 * tcp_urp_mp will be non-NULL and will get prepended
14227 			 * to what has to be this piece containing the urgent
14228 			 * byte.  If for any reason we abort this segment below,
14229 			 * if it comes back, we will have this ready, or it
14230 			 * will get blown off in close.
14231 			 */
14232 		} else if (urp == seg_len) {
14233 			/*
14234 			 * The urgent byte is the next byte after this sequence
14235 			 * number. If there is data it is marked with
14236 			 * MSGMARKNEXT and any tcp_urp_mark_mp is discarded
14237 			 * since it is not needed. Otherwise, if the code
14238 			 * above just allocated a zero-length tcp_urp_mark_mp
14239 			 * message, that message is tagged with MSGMARKNEXT.
14240 			 * Sending up these MSGMARKNEXT messages makes
14241 			 * SIOCATMARK work correctly even though
14242 			 * the T_EXDATA_IND will not be sent up until the
14243 			 * urgent byte arrives.
14244 			 */
14245 			if (seg_len != 0) {
14246 				flags |= TH_MARKNEXT_NEEDED;
14247 				freemsg(tcp->tcp_urp_mark_mp);
14248 				tcp->tcp_urp_mark_mp = NULL;
14249 				flags &= ~TH_SEND_URP_MARK;
14250 			} else if (tcp->tcp_urp_mark_mp != NULL) {
14251 				flags |= TH_SEND_URP_MARK;
14252 				tcp->tcp_urp_mark_mp->b_flag &=
14253 				    ~MSGNOTMARKNEXT;
14254 				tcp->tcp_urp_mark_mp->b_flag |= MSGMARKNEXT;
14255 			}
14256 #ifdef DEBUG
14257 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14258 			    "tcp_rput: AT MARK, len %d, flags 0x%x, %s",
14259 			    seg_len, flags,
14260 			    tcp_display(tcp, NULL, DISP_PORT_ONLY));
14261 #endif /* DEBUG */
14262 		} else {
14263 			/* Data left until we hit mark */
14264 #ifdef DEBUG
14265 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
14266 			    "tcp_rput: URP %d bytes left, %s",
14267 			    urp - seg_len, tcp_display(tcp, NULL,
14268 			    DISP_PORT_ONLY));
14269 #endif /* DEBUG */
14270 		}
14271 	}
14272 
14273 process_ack:
14274 	if (!(flags & TH_ACK)) {
14275 		freemsg(mp);
14276 		goto xmit_check;
14277 	}
14278 	}
14279 	bytes_acked = (int)(seg_ack - tcp->tcp_suna);
14280 
14281 	if (tcp->tcp_ipversion == IPV6_VERSION && bytes_acked > 0)
14282 		tcp->tcp_ip_forward_progress = B_TRUE;
14283 	if (tcp->tcp_state == TCPS_SYN_RCVD) {
14284 		if ((tcp->tcp_conn.tcp_eager_conn_ind != NULL) &&
14285 		    ((tcp->tcp_kssl_ent == NULL) || !tcp->tcp_kssl_pending)) {
14286 			/* 3-way handshake complete - pass up the T_CONN_IND */
14287 			tcp_t	*listener = tcp->tcp_listener;
14288 			mblk_t	*mp = tcp->tcp_conn.tcp_eager_conn_ind;
14289 
14290 			tcp->tcp_tconnind_started = B_TRUE;
14291 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
14292 			/*
14293 			 * We are here means eager is fine but it can
14294 			 * get a TH_RST at any point between now and till
14295 			 * accept completes and disappear. We need to
14296 			 * ensure that reference to eager is valid after
14297 			 * we get out of eager's perimeter. So we do
14298 			 * an extra refhold.
14299 			 */
14300 			CONN_INC_REF(connp);
14301 
14302 			/*
14303 			 * The listener also exists because of the refhold
14304 			 * done in tcp_conn_request. Its possible that it
14305 			 * might have closed. We will check that once we
14306 			 * get inside listeners context.
14307 			 */
14308 			CONN_INC_REF(listener->tcp_connp);
14309 			if (listener->tcp_connp->conn_sqp ==
14310 			    connp->conn_sqp) {
14311 				tcp_send_conn_ind(listener->tcp_connp, mp,
14312 				    listener->tcp_connp->conn_sqp);
14313 				CONN_DEC_REF(listener->tcp_connp);
14314 			} else if (!tcp->tcp_loopback) {
14315 				squeue_fill(listener->tcp_connp->conn_sqp, mp,
14316 				    tcp_send_conn_ind,
14317 				    listener->tcp_connp, SQTAG_TCP_CONN_IND);
14318 			} else {
14319 				squeue_enter(listener->tcp_connp->conn_sqp, mp,
14320 				    tcp_send_conn_ind, listener->tcp_connp,
14321 				    SQTAG_TCP_CONN_IND);
14322 			}
14323 		}
14324 
14325 		if (tcp->tcp_active_open) {
14326 			/*
14327 			 * We are seeing the final ack in the three way
14328 			 * hand shake of a active open'ed connection
14329 			 * so we must send up a T_CONN_CON
14330 			 */
14331 			if (!tcp_conn_con(tcp, iphdr, tcph, mp, NULL)) {
14332 				freemsg(mp);
14333 				return;
14334 			}
14335 			/*
14336 			 * Don't fuse the loopback endpoints for
14337 			 * simultaneous active opens.
14338 			 */
14339 			if (tcp->tcp_loopback) {
14340 				TCP_STAT(tcps, tcp_fusion_unfusable);
14341 				tcp->tcp_unfusable = B_TRUE;
14342 			}
14343 		}
14344 
14345 		tcp->tcp_suna = tcp->tcp_iss + 1;	/* One for the SYN */
14346 		bytes_acked--;
14347 		/* SYN was acked - making progress */
14348 		if (tcp->tcp_ipversion == IPV6_VERSION)
14349 			tcp->tcp_ip_forward_progress = B_TRUE;
14350 
14351 		/*
14352 		 * If SYN was retransmitted, need to reset all
14353 		 * retransmission info as this segment will be
14354 		 * treated as a dup ACK.
14355 		 */
14356 		if (tcp->tcp_rexmit) {
14357 			tcp->tcp_rexmit = B_FALSE;
14358 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14359 			tcp->tcp_rexmit_max = tcp->tcp_snxt;
14360 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14361 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14362 			tcp->tcp_ms_we_have_waited = 0;
14363 			tcp->tcp_cwnd = mss;
14364 		}
14365 
14366 		/*
14367 		 * We set the send window to zero here.
14368 		 * This is needed if there is data to be
14369 		 * processed already on the queue.
14370 		 * Later (at swnd_update label), the
14371 		 * "new_swnd > tcp_swnd" condition is satisfied
14372 		 * the XMIT_NEEDED flag is set in the current
14373 		 * (SYN_RCVD) state. This ensures tcp_wput_data() is
14374 		 * called if there is already data on queue in
14375 		 * this state.
14376 		 */
14377 		tcp->tcp_swnd = 0;
14378 
14379 		if (new_swnd > tcp->tcp_max_swnd)
14380 			tcp->tcp_max_swnd = new_swnd;
14381 		tcp->tcp_swl1 = seg_seq;
14382 		tcp->tcp_swl2 = seg_ack;
14383 		tcp->tcp_state = TCPS_ESTABLISHED;
14384 		tcp->tcp_valid_bits &= ~TCP_ISS_VALID;
14385 
14386 		/* Fuse when both sides are in ESTABLISHED state */
14387 		if (tcp->tcp_loopback && do_tcp_fusion)
14388 			tcp_fuse(tcp, iphdr, tcph);
14389 
14390 	}
14391 	/* This code follows 4.4BSD-Lite2 mostly. */
14392 	if (bytes_acked < 0)
14393 		goto est;
14394 
14395 	/*
14396 	 * If TCP is ECN capable and the congestion experience bit is
14397 	 * set, reduce tcp_cwnd and tcp_ssthresh.  But this should only be
14398 	 * done once per window (or more loosely, per RTT).
14399 	 */
14400 	if (tcp->tcp_cwr && SEQ_GT(seg_ack, tcp->tcp_cwr_snd_max))
14401 		tcp->tcp_cwr = B_FALSE;
14402 	if (tcp->tcp_ecn_ok && (flags & TH_ECE)) {
14403 		if (!tcp->tcp_cwr) {
14404 			npkt = ((tcp->tcp_snxt - tcp->tcp_suna) >> 1) / mss;
14405 			tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) * mss;
14406 			tcp->tcp_cwnd = npkt * mss;
14407 			/*
14408 			 * If the cwnd is 0, use the timer to clock out
14409 			 * new segments.  This is required by the ECN spec.
14410 			 */
14411 			if (npkt == 0) {
14412 				TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14413 				/*
14414 				 * This makes sure that when the ACK comes
14415 				 * back, we will increase tcp_cwnd by 1 MSS.
14416 				 */
14417 				tcp->tcp_cwnd_cnt = 0;
14418 			}
14419 			tcp->tcp_cwr = B_TRUE;
14420 			/*
14421 			 * This marks the end of the current window of in
14422 			 * flight data.  That is why we don't use
14423 			 * tcp_suna + tcp_swnd.  Only data in flight can
14424 			 * provide ECN info.
14425 			 */
14426 			tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14427 			tcp->tcp_ecn_cwr_sent = B_FALSE;
14428 		}
14429 	}
14430 
14431 	mp1 = tcp->tcp_xmit_head;
14432 	if (bytes_acked == 0) {
14433 		if (!ofo_seg && seg_len == 0 && new_swnd == tcp->tcp_swnd) {
14434 			int dupack_cnt;
14435 
14436 			BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
14437 			/*
14438 			 * Fast retransmit.  When we have seen exactly three
14439 			 * identical ACKs while we have unacked data
14440 			 * outstanding we take it as a hint that our peer
14441 			 * dropped something.
14442 			 *
14443 			 * If TCP is retransmitting, don't do fast retransmit.
14444 			 */
14445 			if (mp1 && tcp->tcp_suna != tcp->tcp_snxt &&
14446 			    ! tcp->tcp_rexmit) {
14447 				/* Do Limited Transmit */
14448 				if ((dupack_cnt = ++tcp->tcp_dupack_cnt) <
14449 				    tcps->tcps_dupack_fast_retransmit) {
14450 					/*
14451 					 * RFC 3042
14452 					 *
14453 					 * What we need to do is temporarily
14454 					 * increase tcp_cwnd so that new
14455 					 * data can be sent if it is allowed
14456 					 * by the receive window (tcp_rwnd).
14457 					 * tcp_wput_data() will take care of
14458 					 * the rest.
14459 					 *
14460 					 * If the connection is SACK capable,
14461 					 * only do limited xmit when there
14462 					 * is SACK info.
14463 					 *
14464 					 * Note how tcp_cwnd is incremented.
14465 					 * The first dup ACK will increase
14466 					 * it by 1 MSS.  The second dup ACK
14467 					 * will increase it by 2 MSS.  This
14468 					 * means that only 1 new segment will
14469 					 * be sent for each dup ACK.
14470 					 */
14471 					if (tcp->tcp_unsent > 0 &&
14472 					    (!tcp->tcp_snd_sack_ok ||
14473 					    (tcp->tcp_snd_sack_ok &&
14474 					    tcp->tcp_notsack_list != NULL))) {
14475 						tcp->tcp_cwnd += mss <<
14476 						    (tcp->tcp_dupack_cnt - 1);
14477 						flags |= TH_LIMIT_XMIT;
14478 					}
14479 				} else if (dupack_cnt ==
14480 				    tcps->tcps_dupack_fast_retransmit) {
14481 
14482 				/*
14483 				 * If we have reduced tcp_ssthresh
14484 				 * because of ECN, do not reduce it again
14485 				 * unless it is already one window of data
14486 				 * away.  After one window of data, tcp_cwr
14487 				 * should then be cleared.  Note that
14488 				 * for non ECN capable connection, tcp_cwr
14489 				 * should always be false.
14490 				 *
14491 				 * Adjust cwnd since the duplicate
14492 				 * ack indicates that a packet was
14493 				 * dropped (due to congestion.)
14494 				 */
14495 				if (!tcp->tcp_cwr) {
14496 					npkt = ((tcp->tcp_snxt -
14497 					    tcp->tcp_suna) >> 1) / mss;
14498 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
14499 					    mss;
14500 					tcp->tcp_cwnd = (npkt +
14501 					    tcp->tcp_dupack_cnt) * mss;
14502 				}
14503 				if (tcp->tcp_ecn_ok) {
14504 					tcp->tcp_cwr = B_TRUE;
14505 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
14506 					tcp->tcp_ecn_cwr_sent = B_FALSE;
14507 				}
14508 
14509 				/*
14510 				 * We do Hoe's algorithm.  Refer to her
14511 				 * paper "Improving the Start-up Behavior
14512 				 * of a Congestion Control Scheme for TCP,"
14513 				 * appeared in SIGCOMM'96.
14514 				 *
14515 				 * Save highest seq no we have sent so far.
14516 				 * Be careful about the invisible FIN byte.
14517 				 */
14518 				if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
14519 				    (tcp->tcp_unsent == 0)) {
14520 					tcp->tcp_rexmit_max = tcp->tcp_fss;
14521 				} else {
14522 					tcp->tcp_rexmit_max = tcp->tcp_snxt;
14523 				}
14524 
14525 				/*
14526 				 * Do not allow bursty traffic during.
14527 				 * fast recovery.  Refer to Fall and Floyd's
14528 				 * paper "Simulation-based Comparisons of
14529 				 * Tahoe, Reno and SACK TCP" (in CCR?)
14530 				 * This is a best current practise.
14531 				 */
14532 				tcp->tcp_snd_burst = TCP_CWND_SS;
14533 
14534 				/*
14535 				 * For SACK:
14536 				 * Calculate tcp_pipe, which is the
14537 				 * estimated number of bytes in
14538 				 * network.
14539 				 *
14540 				 * tcp_fack is the highest sack'ed seq num
14541 				 * TCP has received.
14542 				 *
14543 				 * tcp_pipe is explained in the above quoted
14544 				 * Fall and Floyd's paper.  tcp_fack is
14545 				 * explained in Mathis and Mahdavi's
14546 				 * "Forward Acknowledgment: Refining TCP
14547 				 * Congestion Control" in SIGCOMM '96.
14548 				 */
14549 				if (tcp->tcp_snd_sack_ok) {
14550 					ASSERT(tcp->tcp_sack_info != NULL);
14551 					if (tcp->tcp_notsack_list != NULL) {
14552 						tcp->tcp_pipe = tcp->tcp_snxt -
14553 						    tcp->tcp_fack;
14554 						tcp->tcp_sack_snxt = seg_ack;
14555 						flags |= TH_NEED_SACK_REXMIT;
14556 					} else {
14557 						/*
14558 						 * Always initialize tcp_pipe
14559 						 * even though we don't have
14560 						 * any SACK info.  If later
14561 						 * we get SACK info and
14562 						 * tcp_pipe is not initialized,
14563 						 * funny things will happen.
14564 						 */
14565 						tcp->tcp_pipe =
14566 						    tcp->tcp_cwnd_ssthresh;
14567 					}
14568 				} else {
14569 					flags |= TH_REXMIT_NEEDED;
14570 				} /* tcp_snd_sack_ok */
14571 
14572 				} else {
14573 					/*
14574 					 * Here we perform congestion
14575 					 * avoidance, but NOT slow start.
14576 					 * This is known as the Fast
14577 					 * Recovery Algorithm.
14578 					 */
14579 					if (tcp->tcp_snd_sack_ok &&
14580 					    tcp->tcp_notsack_list != NULL) {
14581 						flags |= TH_NEED_SACK_REXMIT;
14582 						tcp->tcp_pipe -= mss;
14583 						if (tcp->tcp_pipe < 0)
14584 							tcp->tcp_pipe = 0;
14585 					} else {
14586 					/*
14587 					 * We know that one more packet has
14588 					 * left the pipe thus we can update
14589 					 * cwnd.
14590 					 */
14591 					cwnd = tcp->tcp_cwnd + mss;
14592 					if (cwnd > tcp->tcp_cwnd_max)
14593 						cwnd = tcp->tcp_cwnd_max;
14594 					tcp->tcp_cwnd = cwnd;
14595 					if (tcp->tcp_unsent > 0)
14596 						flags |= TH_XMIT_NEEDED;
14597 					}
14598 				}
14599 			}
14600 		} else if (tcp->tcp_zero_win_probe) {
14601 			/*
14602 			 * If the window has opened, need to arrange
14603 			 * to send additional data.
14604 			 */
14605 			if (new_swnd != 0) {
14606 				/* tcp_suna != tcp_snxt */
14607 				/* Packet contains a window update */
14608 				BUMP_MIB(&tcps->tcps_mib, tcpInWinUpdate);
14609 				tcp->tcp_zero_win_probe = 0;
14610 				tcp->tcp_timer_backoff = 0;
14611 				tcp->tcp_ms_we_have_waited = 0;
14612 
14613 				/*
14614 				 * Transmit starting with tcp_suna since
14615 				 * the one byte probe is not ack'ed.
14616 				 * If TCP has sent more than one identical
14617 				 * probe, tcp_rexmit will be set.  That means
14618 				 * tcp_ss_rexmit() will send out the one
14619 				 * byte along with new data.  Otherwise,
14620 				 * fake the retransmission.
14621 				 */
14622 				flags |= TH_XMIT_NEEDED;
14623 				if (!tcp->tcp_rexmit) {
14624 					tcp->tcp_rexmit = B_TRUE;
14625 					tcp->tcp_dupack_cnt = 0;
14626 					tcp->tcp_rexmit_nxt = tcp->tcp_suna;
14627 					tcp->tcp_rexmit_max = tcp->tcp_suna + 1;
14628 				}
14629 			}
14630 		}
14631 		goto swnd_update;
14632 	}
14633 
14634 	/*
14635 	 * Check for "acceptability" of ACK value per RFC 793, pages 72 - 73.
14636 	 * If the ACK value acks something that we have not yet sent, it might
14637 	 * be an old duplicate segment.  Send an ACK to re-synchronize the
14638 	 * other side.
14639 	 * Note: reset in response to unacceptable ACK in SYN_RECEIVE
14640 	 * state is handled above, so we can always just drop the segment and
14641 	 * send an ACK here.
14642 	 *
14643 	 * Should we send ACKs in response to ACK only segments?
14644 	 */
14645 	if (SEQ_GT(seg_ack, tcp->tcp_snxt)) {
14646 		BUMP_MIB(&tcps->tcps_mib, tcpInAckUnsent);
14647 		/* drop the received segment */
14648 		freemsg(mp);
14649 
14650 		/*
14651 		 * Send back an ACK.  If tcp_drop_ack_unsent_cnt is
14652 		 * greater than 0, check if the number of such
14653 		 * bogus ACks is greater than that count.  If yes,
14654 		 * don't send back any ACK.  This prevents TCP from
14655 		 * getting into an ACK storm if somehow an attacker
14656 		 * successfully spoofs an acceptable segment to our
14657 		 * peer.
14658 		 */
14659 		if (tcp_drop_ack_unsent_cnt > 0 &&
14660 		    ++tcp->tcp_in_ack_unsent > tcp_drop_ack_unsent_cnt) {
14661 			TCP_STAT(tcps, tcp_in_ack_unsent_drop);
14662 			return;
14663 		}
14664 		mp = tcp_ack_mp(tcp);
14665 		if (mp != NULL) {
14666 			BUMP_LOCAL(tcp->tcp_obsegs);
14667 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
14668 			tcp_send_data(tcp, tcp->tcp_wq, mp);
14669 		}
14670 		return;
14671 	}
14672 
14673 	/*
14674 	 * TCP gets a new ACK, update the notsack'ed list to delete those
14675 	 * blocks that are covered by this ACK.
14676 	 */
14677 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
14678 		tcp_notsack_remove(&(tcp->tcp_notsack_list), seg_ack,
14679 		    &(tcp->tcp_num_notsack_blk), &(tcp->tcp_cnt_notsack_list));
14680 	}
14681 
14682 	/*
14683 	 * If we got an ACK after fast retransmit, check to see
14684 	 * if it is a partial ACK.  If it is not and the congestion
14685 	 * window was inflated to account for the other side's
14686 	 * cached packets, retract it.  If it is, do Hoe's algorithm.
14687 	 */
14688 	if (tcp->tcp_dupack_cnt >= tcps->tcps_dupack_fast_retransmit) {
14689 		ASSERT(tcp->tcp_rexmit == B_FALSE);
14690 		if (SEQ_GEQ(seg_ack, tcp->tcp_rexmit_max)) {
14691 			tcp->tcp_dupack_cnt = 0;
14692 			/*
14693 			 * Restore the orig tcp_cwnd_ssthresh after
14694 			 * fast retransmit phase.
14695 			 */
14696 			if (tcp->tcp_cwnd > tcp->tcp_cwnd_ssthresh) {
14697 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh;
14698 			}
14699 			tcp->tcp_rexmit_max = seg_ack;
14700 			tcp->tcp_cwnd_cnt = 0;
14701 			tcp->tcp_snd_burst = tcp->tcp_localnet ?
14702 			    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14703 
14704 			/*
14705 			 * Remove all notsack info to avoid confusion with
14706 			 * the next fast retrasnmit/recovery phase.
14707 			 */
14708 			if (tcp->tcp_snd_sack_ok &&
14709 			    tcp->tcp_notsack_list != NULL) {
14710 				TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
14711 			}
14712 		} else {
14713 			if (tcp->tcp_snd_sack_ok &&
14714 			    tcp->tcp_notsack_list != NULL) {
14715 				flags |= TH_NEED_SACK_REXMIT;
14716 				tcp->tcp_pipe -= mss;
14717 				if (tcp->tcp_pipe < 0)
14718 					tcp->tcp_pipe = 0;
14719 			} else {
14720 				/*
14721 				 * Hoe's algorithm:
14722 				 *
14723 				 * Retransmit the unack'ed segment and
14724 				 * restart fast recovery.  Note that we
14725 				 * need to scale back tcp_cwnd to the
14726 				 * original value when we started fast
14727 				 * recovery.  This is to prevent overly
14728 				 * aggressive behaviour in sending new
14729 				 * segments.
14730 				 */
14731 				tcp->tcp_cwnd = tcp->tcp_cwnd_ssthresh +
14732 				    tcps->tcps_dupack_fast_retransmit * mss;
14733 				tcp->tcp_cwnd_cnt = tcp->tcp_cwnd;
14734 				flags |= TH_REXMIT_NEEDED;
14735 			}
14736 		}
14737 	} else {
14738 		tcp->tcp_dupack_cnt = 0;
14739 		if (tcp->tcp_rexmit) {
14740 			/*
14741 			 * TCP is retranmitting.  If the ACK ack's all
14742 			 * outstanding data, update tcp_rexmit_max and
14743 			 * tcp_rexmit_nxt.  Otherwise, update tcp_rexmit_nxt
14744 			 * to the correct value.
14745 			 *
14746 			 * Note that SEQ_LEQ() is used.  This is to avoid
14747 			 * unnecessary fast retransmit caused by dup ACKs
14748 			 * received when TCP does slow start retransmission
14749 			 * after a time out.  During this phase, TCP may
14750 			 * send out segments which are already received.
14751 			 * This causes dup ACKs to be sent back.
14752 			 */
14753 			if (SEQ_LEQ(seg_ack, tcp->tcp_rexmit_max)) {
14754 				if (SEQ_GT(seg_ack, tcp->tcp_rexmit_nxt)) {
14755 					tcp->tcp_rexmit_nxt = seg_ack;
14756 				}
14757 				if (seg_ack != tcp->tcp_rexmit_max) {
14758 					flags |= TH_XMIT_NEEDED;
14759 				}
14760 			} else {
14761 				tcp->tcp_rexmit = B_FALSE;
14762 				tcp->tcp_xmit_zc_clean = B_FALSE;
14763 				tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
14764 				tcp->tcp_snd_burst = tcp->tcp_localnet ?
14765 				    TCP_CWND_INFINITE : TCP_CWND_NORMAL;
14766 			}
14767 			tcp->tcp_ms_we_have_waited = 0;
14768 		}
14769 	}
14770 
14771 	BUMP_MIB(&tcps->tcps_mib, tcpInAckSegs);
14772 	UPDATE_MIB(&tcps->tcps_mib, tcpInAckBytes, bytes_acked);
14773 	tcp->tcp_suna = seg_ack;
14774 	if (tcp->tcp_zero_win_probe != 0) {
14775 		tcp->tcp_zero_win_probe = 0;
14776 		tcp->tcp_timer_backoff = 0;
14777 	}
14778 
14779 	/*
14780 	 * If tcp_xmit_head is NULL, then it must be the FIN being ack'ed.
14781 	 * Note that it cannot be the SYN being ack'ed.  The code flow
14782 	 * will not reach here.
14783 	 */
14784 	if (mp1 == NULL) {
14785 		goto fin_acked;
14786 	}
14787 
14788 	/*
14789 	 * Update the congestion window.
14790 	 *
14791 	 * If TCP is not ECN capable or TCP is ECN capable but the
14792 	 * congestion experience bit is not set, increase the tcp_cwnd as
14793 	 * usual.
14794 	 */
14795 	if (!tcp->tcp_ecn_ok || !(flags & TH_ECE)) {
14796 		cwnd = tcp->tcp_cwnd;
14797 		add = mss;
14798 
14799 		if (cwnd >= tcp->tcp_cwnd_ssthresh) {
14800 			/*
14801 			 * This is to prevent an increase of less than 1 MSS of
14802 			 * tcp_cwnd.  With partial increase, tcp_wput_data()
14803 			 * may send out tinygrams in order to preserve mblk
14804 			 * boundaries.
14805 			 *
14806 			 * By initializing tcp_cwnd_cnt to new tcp_cwnd and
14807 			 * decrementing it by 1 MSS for every ACKs, tcp_cwnd is
14808 			 * increased by 1 MSS for every RTTs.
14809 			 */
14810 			if (tcp->tcp_cwnd_cnt <= 0) {
14811 				tcp->tcp_cwnd_cnt = cwnd + add;
14812 			} else {
14813 				tcp->tcp_cwnd_cnt -= add;
14814 				add = 0;
14815 			}
14816 		}
14817 		tcp->tcp_cwnd = MIN(cwnd + add, tcp->tcp_cwnd_max);
14818 	}
14819 
14820 	/* See if the latest urgent data has been acknowledged */
14821 	if ((tcp->tcp_valid_bits & TCP_URG_VALID) &&
14822 	    SEQ_GT(seg_ack, tcp->tcp_urg))
14823 		tcp->tcp_valid_bits &= ~TCP_URG_VALID;
14824 
14825 	/* Can we update the RTT estimates? */
14826 	if (tcp->tcp_snd_ts_ok) {
14827 		/* Ignore zero timestamp echo-reply. */
14828 		if (tcpopt.tcp_opt_ts_ecr != 0) {
14829 			tcp_set_rto(tcp, (int32_t)lbolt -
14830 			    (int32_t)tcpopt.tcp_opt_ts_ecr);
14831 		}
14832 
14833 		/* If needed, restart the timer. */
14834 		if (tcp->tcp_set_timer == 1) {
14835 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14836 			tcp->tcp_set_timer = 0;
14837 		}
14838 		/*
14839 		 * Update tcp_csuna in case the other side stops sending
14840 		 * us timestamps.
14841 		 */
14842 		tcp->tcp_csuna = tcp->tcp_snxt;
14843 	} else if (SEQ_GT(seg_ack, tcp->tcp_csuna)) {
14844 		/*
14845 		 * An ACK sequence we haven't seen before, so get the RTT
14846 		 * and update the RTO. But first check if the timestamp is
14847 		 * valid to use.
14848 		 */
14849 		if ((mp1->b_next != NULL) &&
14850 		    SEQ_GT(seg_ack, (uint32_t)(uintptr_t)(mp1->b_next)))
14851 			tcp_set_rto(tcp, (int32_t)lbolt -
14852 			    (int32_t)(intptr_t)mp1->b_prev);
14853 		else
14854 			BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14855 
14856 		/* Remeber the last sequence to be ACKed */
14857 		tcp->tcp_csuna = seg_ack;
14858 		if (tcp->tcp_set_timer == 1) {
14859 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
14860 			tcp->tcp_set_timer = 0;
14861 		}
14862 	} else {
14863 		BUMP_MIB(&tcps->tcps_mib, tcpRttNoUpdate);
14864 	}
14865 
14866 	/* Eat acknowledged bytes off the xmit queue. */
14867 	for (;;) {
14868 		mblk_t	*mp2;
14869 		uchar_t	*wptr;
14870 
14871 		wptr = mp1->b_wptr;
14872 		ASSERT((uintptr_t)(wptr - mp1->b_rptr) <= (uintptr_t)INT_MAX);
14873 		bytes_acked -= (int)(wptr - mp1->b_rptr);
14874 		if (bytes_acked < 0) {
14875 			mp1->b_rptr = wptr + bytes_acked;
14876 			/*
14877 			 * Set a new timestamp if all the bytes timed by the
14878 			 * old timestamp have been ack'ed.
14879 			 */
14880 			if (SEQ_GT(seg_ack,
14881 			    (uint32_t)(uintptr_t)(mp1->b_next))) {
14882 				mp1->b_prev = (mblk_t *)(uintptr_t)lbolt;
14883 				mp1->b_next = NULL;
14884 			}
14885 			break;
14886 		}
14887 		mp1->b_next = NULL;
14888 		mp1->b_prev = NULL;
14889 		mp2 = mp1;
14890 		mp1 = mp1->b_cont;
14891 
14892 		/*
14893 		 * This notification is required for some zero-copy
14894 		 * clients to maintain a copy semantic. After the data
14895 		 * is ack'ed, client is safe to modify or reuse the buffer.
14896 		 */
14897 		if (tcp->tcp_snd_zcopy_aware &&
14898 		    (mp2->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
14899 			tcp_zcopy_notify(tcp);
14900 		freeb(mp2);
14901 		if (bytes_acked == 0) {
14902 			if (mp1 == NULL) {
14903 				/* Everything is ack'ed, clear the tail. */
14904 				tcp->tcp_xmit_tail = NULL;
14905 				/*
14906 				 * Cancel the timer unless we are still
14907 				 * waiting for an ACK for the FIN packet.
14908 				 */
14909 				if (tcp->tcp_timer_tid != 0 &&
14910 				    tcp->tcp_snxt == tcp->tcp_suna) {
14911 					(void) TCP_TIMER_CANCEL(tcp,
14912 					    tcp->tcp_timer_tid);
14913 					tcp->tcp_timer_tid = 0;
14914 				}
14915 				goto pre_swnd_update;
14916 			}
14917 			if (mp2 != tcp->tcp_xmit_tail)
14918 				break;
14919 			tcp->tcp_xmit_tail = mp1;
14920 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
14921 			    (uintptr_t)INT_MAX);
14922 			tcp->tcp_xmit_tail_unsent = (int)(mp1->b_wptr -
14923 			    mp1->b_rptr);
14924 			break;
14925 		}
14926 		if (mp1 == NULL) {
14927 			/*
14928 			 * More was acked but there is nothing more
14929 			 * outstanding.  This means that the FIN was
14930 			 * just acked or that we're talking to a clown.
14931 			 */
14932 fin_acked:
14933 			ASSERT(tcp->tcp_fin_sent);
14934 			tcp->tcp_xmit_tail = NULL;
14935 			if (tcp->tcp_fin_sent) {
14936 				/* FIN was acked - making progress */
14937 				if (tcp->tcp_ipversion == IPV6_VERSION &&
14938 				    !tcp->tcp_fin_acked)
14939 					tcp->tcp_ip_forward_progress = B_TRUE;
14940 				tcp->tcp_fin_acked = B_TRUE;
14941 				if (tcp->tcp_linger_tid != 0 &&
14942 				    TCP_TIMER_CANCEL(tcp,
14943 				    tcp->tcp_linger_tid) >= 0) {
14944 					tcp_stop_lingering(tcp);
14945 					freemsg(mp);
14946 					mp = NULL;
14947 				}
14948 			} else {
14949 				/*
14950 				 * We should never get here because
14951 				 * we have already checked that the
14952 				 * number of bytes ack'ed should be
14953 				 * smaller than or equal to what we
14954 				 * have sent so far (it is the
14955 				 * acceptability check of the ACK).
14956 				 * We can only get here if the send
14957 				 * queue is corrupted.
14958 				 *
14959 				 * Terminate the connection and
14960 				 * panic the system.  It is better
14961 				 * for us to panic instead of
14962 				 * continuing to avoid other disaster.
14963 				 */
14964 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
14965 				    tcp->tcp_rnxt, TH_RST|TH_ACK);
14966 				panic("Memory corruption "
14967 				    "detected for connection %s.",
14968 				    tcp_display(tcp, NULL,
14969 				    DISP_ADDR_AND_PORT));
14970 				/*NOTREACHED*/
14971 			}
14972 			goto pre_swnd_update;
14973 		}
14974 		ASSERT(mp2 != tcp->tcp_xmit_tail);
14975 	}
14976 	if (tcp->tcp_unsent) {
14977 		flags |= TH_XMIT_NEEDED;
14978 	}
14979 pre_swnd_update:
14980 	tcp->tcp_xmit_head = mp1;
14981 swnd_update:
14982 	/*
14983 	 * The following check is different from most other implementations.
14984 	 * For bi-directional transfer, when segments are dropped, the
14985 	 * "normal" check will not accept a window update in those
14986 	 * retransmitted segemnts.  Failing to do that, TCP may send out
14987 	 * segments which are outside receiver's window.  As TCP accepts
14988 	 * the ack in those retransmitted segments, if the window update in
14989 	 * the same segment is not accepted, TCP will incorrectly calculates
14990 	 * that it can send more segments.  This can create a deadlock
14991 	 * with the receiver if its window becomes zero.
14992 	 */
14993 	if (SEQ_LT(tcp->tcp_swl2, seg_ack) ||
14994 	    SEQ_LT(tcp->tcp_swl1, seg_seq) ||
14995 	    (tcp->tcp_swl1 == seg_seq && new_swnd > tcp->tcp_swnd)) {
14996 		/*
14997 		 * The criteria for update is:
14998 		 *
14999 		 * 1. the segment acknowledges some data.  Or
15000 		 * 2. the segment is new, i.e. it has a higher seq num. Or
15001 		 * 3. the segment is not old and the advertised window is
15002 		 * larger than the previous advertised window.
15003 		 */
15004 		if (tcp->tcp_unsent && new_swnd > tcp->tcp_swnd)
15005 			flags |= TH_XMIT_NEEDED;
15006 		tcp->tcp_swnd = new_swnd;
15007 		if (new_swnd > tcp->tcp_max_swnd)
15008 			tcp->tcp_max_swnd = new_swnd;
15009 		tcp->tcp_swl1 = seg_seq;
15010 		tcp->tcp_swl2 = seg_ack;
15011 	}
15012 est:
15013 	if (tcp->tcp_state > TCPS_ESTABLISHED) {
15014 
15015 		switch (tcp->tcp_state) {
15016 		case TCPS_FIN_WAIT_1:
15017 			if (tcp->tcp_fin_acked) {
15018 				tcp->tcp_state = TCPS_FIN_WAIT_2;
15019 				/*
15020 				 * We implement the non-standard BSD/SunOS
15021 				 * FIN_WAIT_2 flushing algorithm.
15022 				 * If there is no user attached to this
15023 				 * TCP endpoint, then this TCP struct
15024 				 * could hang around forever in FIN_WAIT_2
15025 				 * state if the peer forgets to send us
15026 				 * a FIN.  To prevent this, we wait only
15027 				 * 2*MSL (a convenient time value) for
15028 				 * the FIN to arrive.  If it doesn't show up,
15029 				 * we flush the TCP endpoint.  This algorithm,
15030 				 * though a violation of RFC-793, has worked
15031 				 * for over 10 years in BSD systems.
15032 				 * Note: SunOS 4.x waits 675 seconds before
15033 				 * flushing the FIN_WAIT_2 connection.
15034 				 */
15035 				TCP_TIMER_RESTART(tcp,
15036 				    tcps->tcps_fin_wait_2_flush_interval);
15037 			}
15038 			break;
15039 		case TCPS_FIN_WAIT_2:
15040 			break;	/* Shutdown hook? */
15041 		case TCPS_LAST_ACK:
15042 			freemsg(mp);
15043 			if (tcp->tcp_fin_acked) {
15044 				(void) tcp_clean_death(tcp, 0, 19);
15045 				return;
15046 			}
15047 			goto xmit_check;
15048 		case TCPS_CLOSING:
15049 			if (tcp->tcp_fin_acked) {
15050 				tcp->tcp_state = TCPS_TIME_WAIT;
15051 				/*
15052 				 * Unconditionally clear the exclusive binding
15053 				 * bit so this TIME-WAIT connection won't
15054 				 * interfere with new ones.
15055 				 */
15056 				tcp->tcp_exclbind = 0;
15057 				if (!TCP_IS_DETACHED(tcp)) {
15058 					TCP_TIMER_RESTART(tcp,
15059 					    tcps->tcps_time_wait_interval);
15060 				} else {
15061 					tcp_time_wait_append(tcp);
15062 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15063 				}
15064 			}
15065 			/*FALLTHRU*/
15066 		case TCPS_CLOSE_WAIT:
15067 			freemsg(mp);
15068 			goto xmit_check;
15069 		default:
15070 			ASSERT(tcp->tcp_state != TCPS_TIME_WAIT);
15071 			break;
15072 		}
15073 	}
15074 	if (flags & TH_FIN) {
15075 		/* Make sure we ack the fin */
15076 		flags |= TH_ACK_NEEDED;
15077 		if (!tcp->tcp_fin_rcvd) {
15078 			tcp->tcp_fin_rcvd = B_TRUE;
15079 			tcp->tcp_rnxt++;
15080 			tcph = tcp->tcp_tcph;
15081 			U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15082 
15083 			/*
15084 			 * Generate the ordrel_ind at the end unless we
15085 			 * are an eager guy.
15086 			 * In the eager case tcp_rsrv will do this when run
15087 			 * after tcp_accept is done.
15088 			 */
15089 			if (tcp->tcp_listener == NULL &&
15090 			    !TCP_IS_DETACHED(tcp) && (!tcp->tcp_hard_binding))
15091 				flags |= TH_ORDREL_NEEDED;
15092 			switch (tcp->tcp_state) {
15093 			case TCPS_SYN_RCVD:
15094 			case TCPS_ESTABLISHED:
15095 				tcp->tcp_state = TCPS_CLOSE_WAIT;
15096 				/* Keepalive? */
15097 				break;
15098 			case TCPS_FIN_WAIT_1:
15099 				if (!tcp->tcp_fin_acked) {
15100 					tcp->tcp_state = TCPS_CLOSING;
15101 					break;
15102 				}
15103 				/* FALLTHRU */
15104 			case TCPS_FIN_WAIT_2:
15105 				tcp->tcp_state = TCPS_TIME_WAIT;
15106 				/*
15107 				 * Unconditionally clear the exclusive binding
15108 				 * bit so this TIME-WAIT connection won't
15109 				 * interfere with new ones.
15110 				 */
15111 				tcp->tcp_exclbind = 0;
15112 				if (!TCP_IS_DETACHED(tcp)) {
15113 					TCP_TIMER_RESTART(tcp,
15114 					    tcps->tcps_time_wait_interval);
15115 				} else {
15116 					tcp_time_wait_append(tcp);
15117 					TCP_DBGSTAT(tcps, tcp_rput_time_wait);
15118 				}
15119 				if (seg_len) {
15120 					/*
15121 					 * implies data piggybacked on FIN.
15122 					 * break to handle data.
15123 					 */
15124 					break;
15125 				}
15126 				freemsg(mp);
15127 				goto ack_check;
15128 			}
15129 		}
15130 	}
15131 	if (mp == NULL)
15132 		goto xmit_check;
15133 	if (seg_len == 0) {
15134 		freemsg(mp);
15135 		goto xmit_check;
15136 	}
15137 	if (mp->b_rptr == mp->b_wptr) {
15138 		/*
15139 		 * The header has been consumed, so we remove the
15140 		 * zero-length mblk here.
15141 		 */
15142 		mp1 = mp;
15143 		mp = mp->b_cont;
15144 		freeb(mp1);
15145 	}
15146 	tcph = tcp->tcp_tcph;
15147 	tcp->tcp_rack_cnt++;
15148 	{
15149 		uint32_t cur_max;
15150 
15151 		cur_max = tcp->tcp_rack_cur_max;
15152 		if (tcp->tcp_rack_cnt >= cur_max) {
15153 			/*
15154 			 * We have more unacked data than we should - send
15155 			 * an ACK now.
15156 			 */
15157 			flags |= TH_ACK_NEEDED;
15158 			cur_max++;
15159 			if (cur_max > tcp->tcp_rack_abs_max)
15160 				tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
15161 			else
15162 				tcp->tcp_rack_cur_max = cur_max;
15163 		} else if (TCP_IS_DETACHED(tcp)) {
15164 			/* We don't have an ACK timer for detached TCP. */
15165 			flags |= TH_ACK_NEEDED;
15166 		} else if (seg_len < mss) {
15167 			/*
15168 			 * If we get a segment that is less than an mss, and we
15169 			 * already have unacknowledged data, and the amount
15170 			 * unacknowledged is not a multiple of mss, then we
15171 			 * better generate an ACK now.  Otherwise, this may be
15172 			 * the tail piece of a transaction, and we would rather
15173 			 * wait for the response.
15174 			 */
15175 			uint32_t udif;
15176 			ASSERT((uintptr_t)(tcp->tcp_rnxt - tcp->tcp_rack) <=
15177 			    (uintptr_t)INT_MAX);
15178 			udif = (int)(tcp->tcp_rnxt - tcp->tcp_rack);
15179 			if (udif && (udif % mss))
15180 				flags |= TH_ACK_NEEDED;
15181 			else
15182 				flags |= TH_ACK_TIMER_NEEDED;
15183 		} else {
15184 			/* Start delayed ack timer */
15185 			flags |= TH_ACK_TIMER_NEEDED;
15186 		}
15187 	}
15188 	tcp->tcp_rnxt += seg_len;
15189 	U32_TO_ABE32(tcp->tcp_rnxt, tcph->th_ack);
15190 
15191 	/* Update SACK list */
15192 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
15193 		tcp_sack_remove(tcp->tcp_sack_list, tcp->tcp_rnxt,
15194 		    &(tcp->tcp_num_sack_blk));
15195 	}
15196 
15197 	if (tcp->tcp_urp_mp) {
15198 		tcp->tcp_urp_mp->b_cont = mp;
15199 		mp = tcp->tcp_urp_mp;
15200 		tcp->tcp_urp_mp = NULL;
15201 		/* Ready for a new signal. */
15202 		tcp->tcp_urp_last_valid = B_FALSE;
15203 #ifdef DEBUG
15204 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15205 		    "tcp_rput: sending exdata_ind %s",
15206 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15207 #endif /* DEBUG */
15208 	}
15209 
15210 	/*
15211 	 * Check for ancillary data changes compared to last segment.
15212 	 */
15213 	if (tcp->tcp_ipv6_recvancillary != 0) {
15214 		mp = tcp_rput_add_ancillary(tcp, mp, &ipp);
15215 		ASSERT(mp != NULL);
15216 	}
15217 
15218 	if (tcp->tcp_listener || tcp->tcp_hard_binding) {
15219 		/*
15220 		 * Side queue inbound data until the accept happens.
15221 		 * tcp_accept/tcp_rput drains this when the accept happens.
15222 		 * M_DATA is queued on b_cont. Otherwise (T_OPTDATA_IND or
15223 		 * T_EXDATA_IND) it is queued on b_next.
15224 		 * XXX Make urgent data use this. Requires:
15225 		 *	Removing tcp_listener check for TH_URG
15226 		 *	Making M_PCPROTO and MARK messages skip the eager case
15227 		 */
15228 
15229 		if (tcp->tcp_kssl_pending) {
15230 			DTRACE_PROBE1(kssl_mblk__ksslinput_pending,
15231 			    mblk_t *, mp);
15232 			tcp_kssl_input(tcp, mp);
15233 		} else {
15234 			tcp_rcv_enqueue(tcp, mp, seg_len);
15235 		}
15236 	} else {
15237 		sodirect_t	*sodp = tcp->tcp_sodirect;
15238 
15239 		/*
15240 		 * If an sodirect connection and an enabled sodirect_t then
15241 		 * sodp will be set to point to the tcp_t/sonode_t shared
15242 		 * sodirect_t and the sodirect_t's lock will be held.
15243 		 */
15244 		if (sodp != NULL) {
15245 			mutex_enter(sodp->sod_lockp);
15246 			if (!(sodp->sod_state & SOD_ENABLED) ||
15247 			    (tcp->tcp_kssl_ctx != NULL &&
15248 			    DB_TYPE(mp) == M_DATA)) {
15249 				mutex_exit(sodp->sod_lockp);
15250 				sodp = NULL;
15251 			}
15252 		}
15253 		if (mp->b_datap->db_type != M_DATA ||
15254 		    (flags & TH_MARKNEXT_NEEDED)) {
15255 			if (sodp != NULL) {
15256 				if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15257 					sodp->sod_uioa.uioa_state &= UIOA_CLR;
15258 					sodp->sod_uioa.uioa_state |= UIOA_FINI;
15259 				}
15260 				if (!SOD_QEMPTY(sodp) &&
15261 				    (sodp->sod_state & SOD_WAKE_NOT)) {
15262 					flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15263 					/* sod_wakeup() did the mutex_exit() */
15264 				} else {
15265 					mutex_exit(sodp->sod_lockp);
15266 				}
15267 			} else if (tcp->tcp_rcv_list != NULL) {
15268 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15269 			}
15270 			ASSERT(tcp->tcp_rcv_list == NULL ||
15271 			    tcp->tcp_fused_sigurg);
15272 
15273 			if (flags & TH_MARKNEXT_NEEDED) {
15274 #ifdef DEBUG
15275 				(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15276 				    "tcp_rput: sending MSGMARKNEXT %s",
15277 				    tcp_display(tcp, NULL,
15278 				    DISP_PORT_ONLY));
15279 #endif /* DEBUG */
15280 				mp->b_flag |= MSGMARKNEXT;
15281 				flags &= ~TH_MARKNEXT_NEEDED;
15282 			}
15283 
15284 			/* Does this need SSL processing first? */
15285 			if ((tcp->tcp_kssl_ctx != NULL) &&
15286 			    (DB_TYPE(mp) == M_DATA)) {
15287 				DTRACE_PROBE1(kssl_mblk__ksslinput_data1,
15288 				    mblk_t *, mp);
15289 				tcp_kssl_input(tcp, mp);
15290 			} else {
15291 				putnext(tcp->tcp_rq, mp);
15292 				if (!canputnext(tcp->tcp_rq))
15293 					tcp->tcp_rwnd -= seg_len;
15294 			}
15295 		} else if ((tcp->tcp_kssl_ctx != NULL) &&
15296 		    (DB_TYPE(mp) == M_DATA)) {
15297 			/* Do SSL processing first */
15298 			DTRACE_PROBE1(kssl_mblk__ksslinput_data2,
15299 			    mblk_t *, mp);
15300 			tcp_kssl_input(tcp, mp);
15301 		} else if (sodp != NULL) {
15302 			/*
15303 			 * Sodirect so all mblk_t's are queued on the
15304 			 * socket directly, check for wakeup of blocked
15305 			 * reader (if any), and last if flow-controled.
15306 			 */
15307 			flags |= tcp_rcv_sod_enqueue(tcp, sodp, mp, seg_len);
15308 			if ((sodp->sod_state & SOD_WAKE_NEED) ||
15309 			    (flags & (TH_PUSH|TH_FIN))) {
15310 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15311 				/* sod_wakeup() did the mutex_exit() */
15312 			} else {
15313 				if (SOD_QFULL(sodp)) {
15314 					/* Q is full, need backenable */
15315 					SOD_QSETBE(sodp);
15316 				}
15317 				mutex_exit(sodp->sod_lockp);
15318 			}
15319 		} else if ((flags & (TH_PUSH|TH_FIN)) ||
15320 		    tcp->tcp_rcv_cnt + seg_len >= tcp->tcp_rq->q_hiwat >> 3) {
15321 			if (tcp->tcp_rcv_list != NULL) {
15322 				/*
15323 				 * Enqueue the new segment first and then
15324 				 * call tcp_rcv_drain() to send all data
15325 				 * up.  The other way to do this is to
15326 				 * send all queued data up and then call
15327 				 * putnext() to send the new segment up.
15328 				 * This way can remove the else part later
15329 				 * on.
15330 				 *
15331 				 * We don't this to avoid one more call to
15332 				 * canputnext() as tcp_rcv_drain() needs to
15333 				 * call canputnext().
15334 				 */
15335 				tcp_rcv_enqueue(tcp, mp, seg_len);
15336 				flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15337 			} else {
15338 				putnext(tcp->tcp_rq, mp);
15339 				if (!canputnext(tcp->tcp_rq))
15340 					tcp->tcp_rwnd -= seg_len;
15341 			}
15342 		} else {
15343 			/*
15344 			 * Enqueue all packets when processing an mblk
15345 			 * from the co queue and also enqueue normal packets.
15346 			 */
15347 			tcp_rcv_enqueue(tcp, mp, seg_len);
15348 		}
15349 		/*
15350 		 * Make sure the timer is running if we have data waiting
15351 		 * for a push bit. This provides resiliency against
15352 		 * implementations that do not correctly generate push bits.
15353 		 *
15354 		 * Note, for sodirect if Q isn't empty and there's not a
15355 		 * pending wakeup then we need a timer. Also note that sodp
15356 		 * is assumed to be still valid after exit()ing the sod_lockp
15357 		 * above and while the SOD state can change it can only change
15358 		 * such that the Q is empty now even though data was added
15359 		 * above.
15360 		 */
15361 		if (((sodp != NULL && !SOD_QEMPTY(sodp) &&
15362 		    (sodp->sod_state & SOD_WAKE_NOT)) ||
15363 		    (sodp == NULL && tcp->tcp_rcv_list != NULL)) &&
15364 		    tcp->tcp_push_tid == 0) {
15365 			/*
15366 			 * The connection may be closed at this point, so don't
15367 			 * do anything for a detached tcp.
15368 			 */
15369 			if (!TCP_IS_DETACHED(tcp))
15370 				tcp->tcp_push_tid = TCP_TIMER(tcp,
15371 				    tcp_push_timer,
15372 				    MSEC_TO_TICK(
15373 				    tcps->tcps_push_timer_interval));
15374 		}
15375 	}
15376 
15377 xmit_check:
15378 	/* Is there anything left to do? */
15379 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15380 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_ACK_NEEDED|
15381 	    TH_NEED_SACK_REXMIT|TH_LIMIT_XMIT|TH_ACK_TIMER_NEEDED|
15382 	    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15383 		goto done;
15384 
15385 	/* Any transmit work to do and a non-zero window? */
15386 	if ((flags & (TH_REXMIT_NEEDED|TH_XMIT_NEEDED|TH_NEED_SACK_REXMIT|
15387 	    TH_LIMIT_XMIT)) && tcp->tcp_swnd != 0) {
15388 		if (flags & TH_REXMIT_NEEDED) {
15389 			uint32_t snd_size = tcp->tcp_snxt - tcp->tcp_suna;
15390 
15391 			BUMP_MIB(&tcps->tcps_mib, tcpOutFastRetrans);
15392 			if (snd_size > mss)
15393 				snd_size = mss;
15394 			if (snd_size > tcp->tcp_swnd)
15395 				snd_size = tcp->tcp_swnd;
15396 			mp1 = tcp_xmit_mp(tcp, tcp->tcp_xmit_head, snd_size,
15397 			    NULL, NULL, tcp->tcp_suna, B_TRUE, &snd_size,
15398 			    B_TRUE);
15399 
15400 			if (mp1 != NULL) {
15401 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15402 				tcp->tcp_csuna = tcp->tcp_snxt;
15403 				BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
15404 				UPDATE_MIB(&tcps->tcps_mib,
15405 				    tcpRetransBytes, snd_size);
15406 				tcp_send_data(tcp, tcp->tcp_wq, mp1);
15407 			}
15408 		}
15409 		if (flags & TH_NEED_SACK_REXMIT) {
15410 			tcp_sack_rxmit(tcp, &flags);
15411 		}
15412 		/*
15413 		 * For TH_LIMIT_XMIT, tcp_wput_data() is called to send
15414 		 * out new segment.  Note that tcp_rexmit should not be
15415 		 * set, otherwise TH_LIMIT_XMIT should not be set.
15416 		 */
15417 		if (flags & (TH_XMIT_NEEDED|TH_LIMIT_XMIT)) {
15418 			if (!tcp->tcp_rexmit) {
15419 				tcp_wput_data(tcp, NULL, B_FALSE);
15420 			} else {
15421 				tcp_ss_rexmit(tcp);
15422 			}
15423 		}
15424 		/*
15425 		 * Adjust tcp_cwnd back to normal value after sending
15426 		 * new data segments.
15427 		 */
15428 		if (flags & TH_LIMIT_XMIT) {
15429 			tcp->tcp_cwnd -= mss << (tcp->tcp_dupack_cnt - 1);
15430 			/*
15431 			 * This will restart the timer.  Restarting the
15432 			 * timer is used to avoid a timeout before the
15433 			 * limited transmitted segment's ACK gets back.
15434 			 */
15435 			if (tcp->tcp_xmit_head != NULL)
15436 				tcp->tcp_xmit_head->b_prev = (mblk_t *)lbolt;
15437 		}
15438 
15439 		/* Anything more to do? */
15440 		if ((flags & (TH_ACK_NEEDED|TH_ACK_TIMER_NEEDED|
15441 		    TH_ORDREL_NEEDED|TH_SEND_URP_MARK)) == 0)
15442 			goto done;
15443 	}
15444 ack_check:
15445 	if (flags & TH_SEND_URP_MARK) {
15446 		ASSERT(tcp->tcp_urp_mark_mp);
15447 		/*
15448 		 * Send up any queued data and then send the mark message
15449 		 */
15450 		sodirect_t *sodp;
15451 
15452 		SOD_PTR_ENTER(tcp, sodp);
15453 
15454 		mp1 = tcp->tcp_urp_mark_mp;
15455 		tcp->tcp_urp_mark_mp = NULL;
15456 		if (sodp != NULL) {
15457 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15458 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15459 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15460 			}
15461 			ASSERT(tcp->tcp_rcv_list == NULL);
15462 
15463 			flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15464 			/* sod_wakeup() does the mutex_exit() */
15465 		} else if (tcp->tcp_rcv_list != NULL) {
15466 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15467 
15468 			ASSERT(tcp->tcp_rcv_list == NULL ||
15469 			    tcp->tcp_fused_sigurg);
15470 
15471 		}
15472 		putnext(tcp->tcp_rq, mp1);
15473 #ifdef DEBUG
15474 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
15475 		    "tcp_rput: sending zero-length %s %s",
15476 		    ((mp1->b_flag & MSGMARKNEXT) ? "MSGMARKNEXT" :
15477 		    "MSGNOTMARKNEXT"),
15478 		    tcp_display(tcp, NULL, DISP_PORT_ONLY));
15479 #endif /* DEBUG */
15480 		flags &= ~TH_SEND_URP_MARK;
15481 	}
15482 	if (flags & TH_ACK_NEEDED) {
15483 		/*
15484 		 * Time to send an ack for some reason.
15485 		 */
15486 		mp1 = tcp_ack_mp(tcp);
15487 
15488 		if (mp1 != NULL) {
15489 			tcp_send_data(tcp, tcp->tcp_wq, mp1);
15490 			BUMP_LOCAL(tcp->tcp_obsegs);
15491 			BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
15492 		}
15493 		if (tcp->tcp_ack_tid != 0) {
15494 			(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
15495 			tcp->tcp_ack_tid = 0;
15496 		}
15497 	}
15498 	if (flags & TH_ACK_TIMER_NEEDED) {
15499 		/*
15500 		 * Arrange for deferred ACK or push wait timeout.
15501 		 * Start timer if it is not already running.
15502 		 */
15503 		if (tcp->tcp_ack_tid == 0) {
15504 			tcp->tcp_ack_tid = TCP_TIMER(tcp, tcp_ack_timer,
15505 			    MSEC_TO_TICK(tcp->tcp_localnet ?
15506 			    (clock_t)tcps->tcps_local_dack_interval :
15507 			    (clock_t)tcps->tcps_deferred_ack_interval));
15508 		}
15509 	}
15510 	if (flags & TH_ORDREL_NEEDED) {
15511 		/*
15512 		 * Send up the ordrel_ind unless we are an eager guy.
15513 		 * In the eager case tcp_rsrv will do this when run
15514 		 * after tcp_accept is done.
15515 		 */
15516 		sodirect_t *sodp;
15517 
15518 		ASSERT(tcp->tcp_listener == NULL);
15519 
15520 		SOD_PTR_ENTER(tcp, sodp);
15521 		if (sodp != NULL) {
15522 			if (sodp->sod_uioa.uioa_state & UIOA_ENABLED) {
15523 				sodp->sod_uioa.uioa_state &= UIOA_CLR;
15524 				sodp->sod_uioa.uioa_state |= UIOA_FINI;
15525 			}
15526 			/* No more sodirect */
15527 			tcp->tcp_sodirect = NULL;
15528 			if (!SOD_QEMPTY(sodp)) {
15529 				/* Mblk(s) to process, notify */
15530 				flags |= tcp_rcv_sod_wakeup(tcp, sodp);
15531 				/* sod_wakeup() does the mutex_exit() */
15532 			} else {
15533 				/* Nothing to process */
15534 				mutex_exit(sodp->sod_lockp);
15535 			}
15536 		} else if (tcp->tcp_rcv_list != NULL) {
15537 			/*
15538 			 * Push any mblk(s) enqueued from co processing.
15539 			 */
15540 			flags |= tcp_rcv_drain(tcp->tcp_rq, tcp);
15541 
15542 			ASSERT(tcp->tcp_rcv_list == NULL ||
15543 			    tcp->tcp_fused_sigurg);
15544 		}
15545 
15546 		mp1 = tcp->tcp_ordrel_mp;
15547 		tcp->tcp_ordrel_mp = NULL;
15548 		tcp->tcp_ordrel_done = B_TRUE;
15549 		putnext(tcp->tcp_rq, mp1);
15550 	}
15551 done:
15552 	ASSERT(!(flags & TH_MARKNEXT_NEEDED));
15553 }
15554 
15555 /*
15556  * This function does PAWS protection check. Returns B_TRUE if the
15557  * segment passes the PAWS test, else returns B_FALSE.
15558  */
15559 boolean_t
15560 tcp_paws_check(tcp_t *tcp, tcph_t *tcph, tcp_opt_t *tcpoptp)
15561 {
15562 	uint8_t	flags;
15563 	int	options;
15564 	uint8_t *up;
15565 
15566 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
15567 	/*
15568 	 * If timestamp option is aligned nicely, get values inline,
15569 	 * otherwise call general routine to parse.  Only do that
15570 	 * if timestamp is the only option.
15571 	 */
15572 	if (TCP_HDR_LENGTH(tcph) == (uint32_t)TCP_MIN_HEADER_LENGTH +
15573 	    TCPOPT_REAL_TS_LEN &&
15574 	    OK_32PTR((up = ((uint8_t *)tcph) +
15575 	    TCP_MIN_HEADER_LENGTH)) &&
15576 	    *(uint32_t *)up == TCPOPT_NOP_NOP_TSTAMP) {
15577 		tcpoptp->tcp_opt_ts_val = ABE32_TO_U32((up+4));
15578 		tcpoptp->tcp_opt_ts_ecr = ABE32_TO_U32((up+8));
15579 
15580 		options = TCP_OPT_TSTAMP_PRESENT;
15581 	} else {
15582 		if (tcp->tcp_snd_sack_ok) {
15583 			tcpoptp->tcp = tcp;
15584 		} else {
15585 			tcpoptp->tcp = NULL;
15586 		}
15587 		options = tcp_parse_options(tcph, tcpoptp);
15588 	}
15589 
15590 	if (options & TCP_OPT_TSTAMP_PRESENT) {
15591 		/*
15592 		 * Do PAWS per RFC 1323 section 4.2.  Accept RST
15593 		 * regardless of the timestamp, page 18 RFC 1323.bis.
15594 		 */
15595 		if ((flags & TH_RST) == 0 &&
15596 		    TSTMP_LT(tcpoptp->tcp_opt_ts_val,
15597 		    tcp->tcp_ts_recent)) {
15598 			if (TSTMP_LT(lbolt64, tcp->tcp_last_rcv_lbolt +
15599 			    PAWS_TIMEOUT)) {
15600 				/* This segment is not acceptable. */
15601 				return (B_FALSE);
15602 			} else {
15603 				/*
15604 				 * Connection has been idle for
15605 				 * too long.  Reset the timestamp
15606 				 * and assume the segment is valid.
15607 				 */
15608 				tcp->tcp_ts_recent =
15609 				    tcpoptp->tcp_opt_ts_val;
15610 			}
15611 		}
15612 	} else {
15613 		/*
15614 		 * If we don't get a timestamp on every packet, we
15615 		 * figure we can't really trust 'em, so we stop sending
15616 		 * and parsing them.
15617 		 */
15618 		tcp->tcp_snd_ts_ok = B_FALSE;
15619 
15620 		tcp->tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15621 		tcp->tcp_tcp_hdr_len -= TCPOPT_REAL_TS_LEN;
15622 		tcp->tcp_tcph->th_offset_and_rsrvd[0] -= (3 << 4);
15623 		/*
15624 		 * Adjust the tcp_mss accordingly. We also need to
15625 		 * adjust tcp_cwnd here in accordance with the new mss.
15626 		 * But we avoid doing a slow start here so as to not
15627 		 * to lose on the transfer rate built up so far.
15628 		 */
15629 		tcp_mss_set(tcp, tcp->tcp_mss + TCPOPT_REAL_TS_LEN, B_FALSE);
15630 		if (tcp->tcp_snd_sack_ok) {
15631 			ASSERT(tcp->tcp_sack_info != NULL);
15632 			tcp->tcp_max_sack_blk = 4;
15633 		}
15634 	}
15635 	return (B_TRUE);
15636 }
15637 
15638 /*
15639  * Attach ancillary data to a received TCP segments for the
15640  * ancillary pieces requested by the application that are
15641  * different than they were in the previous data segment.
15642  *
15643  * Save the "current" values once memory allocation is ok so that
15644  * when memory allocation fails we can just wait for the next data segment.
15645  */
15646 static mblk_t *
15647 tcp_rput_add_ancillary(tcp_t *tcp, mblk_t *mp, ip6_pkt_t *ipp)
15648 {
15649 	struct T_optdata_ind *todi;
15650 	int optlen;
15651 	uchar_t *optptr;
15652 	struct T_opthdr *toh;
15653 	uint_t addflag;	/* Which pieces to add */
15654 	mblk_t *mp1;
15655 
15656 	optlen = 0;
15657 	addflag = 0;
15658 	/* If app asked for pktinfo and the index has changed ... */
15659 	if ((ipp->ipp_fields & IPPF_IFINDEX) &&
15660 	    ipp->ipp_ifindex != tcp->tcp_recvifindex &&
15661 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO)) {
15662 		optlen += sizeof (struct T_opthdr) +
15663 		    sizeof (struct in6_pktinfo);
15664 		addflag |= TCP_IPV6_RECVPKTINFO;
15665 	}
15666 	/* If app asked for hoplimit and it has changed ... */
15667 	if ((ipp->ipp_fields & IPPF_HOPLIMIT) &&
15668 	    ipp->ipp_hoplimit != tcp->tcp_recvhops &&
15669 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPLIMIT)) {
15670 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15671 		addflag |= TCP_IPV6_RECVHOPLIMIT;
15672 	}
15673 	/* If app asked for tclass and it has changed ... */
15674 	if ((ipp->ipp_fields & IPPF_TCLASS) &&
15675 	    ipp->ipp_tclass != tcp->tcp_recvtclass &&
15676 	    (tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVTCLASS)) {
15677 		optlen += sizeof (struct T_opthdr) + sizeof (uint_t);
15678 		addflag |= TCP_IPV6_RECVTCLASS;
15679 	}
15680 	/*
15681 	 * If app asked for hopbyhop headers and it has changed ...
15682 	 * For security labels, note that (1) security labels can't change on
15683 	 * a connected socket at all, (2) we're connected to at most one peer,
15684 	 * (3) if anything changes, then it must be some other extra option.
15685 	 */
15686 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVHOPOPTS) &&
15687 	    ip_cmpbuf(tcp->tcp_hopopts, tcp->tcp_hopoptslen,
15688 	    (ipp->ipp_fields & IPPF_HOPOPTS),
15689 	    ipp->ipp_hopopts, ipp->ipp_hopoptslen)) {
15690 		optlen += sizeof (struct T_opthdr) + ipp->ipp_hopoptslen -
15691 		    tcp->tcp_label_len;
15692 		addflag |= TCP_IPV6_RECVHOPOPTS;
15693 		if (!ip_allocbuf((void **)&tcp->tcp_hopopts,
15694 		    &tcp->tcp_hopoptslen, (ipp->ipp_fields & IPPF_HOPOPTS),
15695 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen))
15696 			return (mp);
15697 	}
15698 	/* If app asked for dst headers before routing headers ... */
15699 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTDSTOPTS) &&
15700 	    ip_cmpbuf(tcp->tcp_rtdstopts, tcp->tcp_rtdstoptslen,
15701 	    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15702 	    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen)) {
15703 		optlen += sizeof (struct T_opthdr) +
15704 		    ipp->ipp_rtdstoptslen;
15705 		addflag |= TCP_IPV6_RECVRTDSTOPTS;
15706 		if (!ip_allocbuf((void **)&tcp->tcp_rtdstopts,
15707 		    &tcp->tcp_rtdstoptslen, (ipp->ipp_fields & IPPF_RTDSTOPTS),
15708 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen))
15709 			return (mp);
15710 	}
15711 	/* If app asked for routing headers and it has changed ... */
15712 	if ((tcp->tcp_ipv6_recvancillary & TCP_IPV6_RECVRTHDR) &&
15713 	    ip_cmpbuf(tcp->tcp_rthdr, tcp->tcp_rthdrlen,
15714 	    (ipp->ipp_fields & IPPF_RTHDR),
15715 	    ipp->ipp_rthdr, ipp->ipp_rthdrlen)) {
15716 		optlen += sizeof (struct T_opthdr) + ipp->ipp_rthdrlen;
15717 		addflag |= TCP_IPV6_RECVRTHDR;
15718 		if (!ip_allocbuf((void **)&tcp->tcp_rthdr,
15719 		    &tcp->tcp_rthdrlen, (ipp->ipp_fields & IPPF_RTHDR),
15720 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen))
15721 			return (mp);
15722 	}
15723 	/* If app asked for dest headers and it has changed ... */
15724 	if ((tcp->tcp_ipv6_recvancillary &
15725 	    (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) &&
15726 	    ip_cmpbuf(tcp->tcp_dstopts, tcp->tcp_dstoptslen,
15727 	    (ipp->ipp_fields & IPPF_DSTOPTS),
15728 	    ipp->ipp_dstopts, ipp->ipp_dstoptslen)) {
15729 		optlen += sizeof (struct T_opthdr) + ipp->ipp_dstoptslen;
15730 		addflag |= TCP_IPV6_RECVDSTOPTS;
15731 		if (!ip_allocbuf((void **)&tcp->tcp_dstopts,
15732 		    &tcp->tcp_dstoptslen, (ipp->ipp_fields & IPPF_DSTOPTS),
15733 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen))
15734 			return (mp);
15735 	}
15736 
15737 	if (optlen == 0) {
15738 		/* Nothing to add */
15739 		return (mp);
15740 	}
15741 	mp1 = allocb(sizeof (struct T_optdata_ind) + optlen, BPRI_MED);
15742 	if (mp1 == NULL) {
15743 		/*
15744 		 * Defer sending ancillary data until the next TCP segment
15745 		 * arrives.
15746 		 */
15747 		return (mp);
15748 	}
15749 	mp1->b_cont = mp;
15750 	mp = mp1;
15751 	mp->b_wptr += sizeof (*todi) + optlen;
15752 	mp->b_datap->db_type = M_PROTO;
15753 	todi = (struct T_optdata_ind *)mp->b_rptr;
15754 	todi->PRIM_type = T_OPTDATA_IND;
15755 	todi->DATA_flag = 1;	/* MORE data */
15756 	todi->OPT_length = optlen;
15757 	todi->OPT_offset = sizeof (*todi);
15758 	optptr = (uchar_t *)&todi[1];
15759 	/*
15760 	 * If app asked for pktinfo and the index has changed ...
15761 	 * Note that the local address never changes for the connection.
15762 	 */
15763 	if (addflag & TCP_IPV6_RECVPKTINFO) {
15764 		struct in6_pktinfo *pkti;
15765 
15766 		toh = (struct T_opthdr *)optptr;
15767 		toh->level = IPPROTO_IPV6;
15768 		toh->name = IPV6_PKTINFO;
15769 		toh->len = sizeof (*toh) + sizeof (*pkti);
15770 		toh->status = 0;
15771 		optptr += sizeof (*toh);
15772 		pkti = (struct in6_pktinfo *)optptr;
15773 		if (tcp->tcp_ipversion == IPV6_VERSION)
15774 			pkti->ipi6_addr = tcp->tcp_ip6h->ip6_src;
15775 		else
15776 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
15777 			    &pkti->ipi6_addr);
15778 		pkti->ipi6_ifindex = ipp->ipp_ifindex;
15779 		optptr += sizeof (*pkti);
15780 		ASSERT(OK_32PTR(optptr));
15781 		/* Save as "last" value */
15782 		tcp->tcp_recvifindex = ipp->ipp_ifindex;
15783 	}
15784 	/* If app asked for hoplimit and it has changed ... */
15785 	if (addflag & TCP_IPV6_RECVHOPLIMIT) {
15786 		toh = (struct T_opthdr *)optptr;
15787 		toh->level = IPPROTO_IPV6;
15788 		toh->name = IPV6_HOPLIMIT;
15789 		toh->len = sizeof (*toh) + sizeof (uint_t);
15790 		toh->status = 0;
15791 		optptr += sizeof (*toh);
15792 		*(uint_t *)optptr = ipp->ipp_hoplimit;
15793 		optptr += sizeof (uint_t);
15794 		ASSERT(OK_32PTR(optptr));
15795 		/* Save as "last" value */
15796 		tcp->tcp_recvhops = ipp->ipp_hoplimit;
15797 	}
15798 	/* If app asked for tclass and it has changed ... */
15799 	if (addflag & TCP_IPV6_RECVTCLASS) {
15800 		toh = (struct T_opthdr *)optptr;
15801 		toh->level = IPPROTO_IPV6;
15802 		toh->name = IPV6_TCLASS;
15803 		toh->len = sizeof (*toh) + sizeof (uint_t);
15804 		toh->status = 0;
15805 		optptr += sizeof (*toh);
15806 		*(uint_t *)optptr = ipp->ipp_tclass;
15807 		optptr += sizeof (uint_t);
15808 		ASSERT(OK_32PTR(optptr));
15809 		/* Save as "last" value */
15810 		tcp->tcp_recvtclass = ipp->ipp_tclass;
15811 	}
15812 	if (addflag & TCP_IPV6_RECVHOPOPTS) {
15813 		toh = (struct T_opthdr *)optptr;
15814 		toh->level = IPPROTO_IPV6;
15815 		toh->name = IPV6_HOPOPTS;
15816 		toh->len = sizeof (*toh) + ipp->ipp_hopoptslen -
15817 		    tcp->tcp_label_len;
15818 		toh->status = 0;
15819 		optptr += sizeof (*toh);
15820 		bcopy((uchar_t *)ipp->ipp_hopopts + tcp->tcp_label_len, optptr,
15821 		    ipp->ipp_hopoptslen - tcp->tcp_label_len);
15822 		optptr += ipp->ipp_hopoptslen - tcp->tcp_label_len;
15823 		ASSERT(OK_32PTR(optptr));
15824 		/* Save as last value */
15825 		ip_savebuf((void **)&tcp->tcp_hopopts, &tcp->tcp_hopoptslen,
15826 		    (ipp->ipp_fields & IPPF_HOPOPTS),
15827 		    ipp->ipp_hopopts, ipp->ipp_hopoptslen);
15828 	}
15829 	if (addflag & TCP_IPV6_RECVRTDSTOPTS) {
15830 		toh = (struct T_opthdr *)optptr;
15831 		toh->level = IPPROTO_IPV6;
15832 		toh->name = IPV6_RTHDRDSTOPTS;
15833 		toh->len = sizeof (*toh) + ipp->ipp_rtdstoptslen;
15834 		toh->status = 0;
15835 		optptr += sizeof (*toh);
15836 		bcopy(ipp->ipp_rtdstopts, optptr, ipp->ipp_rtdstoptslen);
15837 		optptr += ipp->ipp_rtdstoptslen;
15838 		ASSERT(OK_32PTR(optptr));
15839 		/* Save as last value */
15840 		ip_savebuf((void **)&tcp->tcp_rtdstopts,
15841 		    &tcp->tcp_rtdstoptslen,
15842 		    (ipp->ipp_fields & IPPF_RTDSTOPTS),
15843 		    ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
15844 	}
15845 	if (addflag & TCP_IPV6_RECVRTHDR) {
15846 		toh = (struct T_opthdr *)optptr;
15847 		toh->level = IPPROTO_IPV6;
15848 		toh->name = IPV6_RTHDR;
15849 		toh->len = sizeof (*toh) + ipp->ipp_rthdrlen;
15850 		toh->status = 0;
15851 		optptr += sizeof (*toh);
15852 		bcopy(ipp->ipp_rthdr, optptr, ipp->ipp_rthdrlen);
15853 		optptr += ipp->ipp_rthdrlen;
15854 		ASSERT(OK_32PTR(optptr));
15855 		/* Save as last value */
15856 		ip_savebuf((void **)&tcp->tcp_rthdr, &tcp->tcp_rthdrlen,
15857 		    (ipp->ipp_fields & IPPF_RTHDR),
15858 		    ipp->ipp_rthdr, ipp->ipp_rthdrlen);
15859 	}
15860 	if (addflag & (TCP_IPV6_RECVDSTOPTS | TCP_OLD_IPV6_RECVDSTOPTS)) {
15861 		toh = (struct T_opthdr *)optptr;
15862 		toh->level = IPPROTO_IPV6;
15863 		toh->name = IPV6_DSTOPTS;
15864 		toh->len = sizeof (*toh) + ipp->ipp_dstoptslen;
15865 		toh->status = 0;
15866 		optptr += sizeof (*toh);
15867 		bcopy(ipp->ipp_dstopts, optptr, ipp->ipp_dstoptslen);
15868 		optptr += ipp->ipp_dstoptslen;
15869 		ASSERT(OK_32PTR(optptr));
15870 		/* Save as last value */
15871 		ip_savebuf((void **)&tcp->tcp_dstopts, &tcp->tcp_dstoptslen,
15872 		    (ipp->ipp_fields & IPPF_DSTOPTS),
15873 		    ipp->ipp_dstopts, ipp->ipp_dstoptslen);
15874 	}
15875 	ASSERT(optptr == mp->b_wptr);
15876 	return (mp);
15877 }
15878 
15879 
15880 /*
15881  * Handle a *T_BIND_REQ that has failed either due to a T_ERROR_ACK
15882  * or a "bad" IRE detected by tcp_adapt_ire.
15883  * We can't tell if the failure was due to the laddr or the faddr
15884  * thus we clear out all addresses and ports.
15885  */
15886 static void
15887 tcp_bind_failed(tcp_t *tcp, mblk_t *mp, int error)
15888 {
15889 	queue_t	*q = tcp->tcp_rq;
15890 	tcph_t	*tcph;
15891 	struct T_error_ack *tea;
15892 	conn_t	*connp = tcp->tcp_connp;
15893 
15894 
15895 	ASSERT(mp->b_datap->db_type == M_PCPROTO);
15896 
15897 	if (mp->b_cont) {
15898 		freemsg(mp->b_cont);
15899 		mp->b_cont = NULL;
15900 	}
15901 	tea = (struct T_error_ack *)mp->b_rptr;
15902 	switch (tea->PRIM_type) {
15903 	case T_BIND_ACK:
15904 		/*
15905 		 * Need to unbind with classifier since we were just told that
15906 		 * our bind succeeded.
15907 		 */
15908 		tcp->tcp_hard_bound = B_FALSE;
15909 		tcp->tcp_hard_binding = B_FALSE;
15910 
15911 		ipcl_hash_remove(connp);
15912 		/* Reuse the mblk if possible */
15913 		ASSERT(mp->b_datap->db_lim - mp->b_datap->db_base >=
15914 		    sizeof (*tea));
15915 		mp->b_rptr = mp->b_datap->db_base;
15916 		mp->b_wptr = mp->b_rptr + sizeof (*tea);
15917 		tea = (struct T_error_ack *)mp->b_rptr;
15918 		tea->PRIM_type = T_ERROR_ACK;
15919 		tea->TLI_error = TSYSERR;
15920 		tea->UNIX_error = error;
15921 		if (tcp->tcp_state >= TCPS_SYN_SENT) {
15922 			tea->ERROR_prim = T_CONN_REQ;
15923 		} else {
15924 			tea->ERROR_prim = O_T_BIND_REQ;
15925 		}
15926 		break;
15927 
15928 	case T_ERROR_ACK:
15929 		if (tcp->tcp_state >= TCPS_SYN_SENT)
15930 			tea->ERROR_prim = T_CONN_REQ;
15931 		break;
15932 	default:
15933 		panic("tcp_bind_failed: unexpected TPI type");
15934 		/*NOTREACHED*/
15935 	}
15936 
15937 	tcp->tcp_state = TCPS_IDLE;
15938 	if (tcp->tcp_ipversion == IPV4_VERSION)
15939 		tcp->tcp_ipha->ipha_src = 0;
15940 	else
15941 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
15942 	/*
15943 	 * Copy of the src addr. in tcp_t is needed since
15944 	 * the lookup funcs. can only look at tcp_t
15945 	 */
15946 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
15947 
15948 	tcph = tcp->tcp_tcph;
15949 	tcph->th_lport[0] = 0;
15950 	tcph->th_lport[1] = 0;
15951 	tcp_bind_hash_remove(tcp);
15952 	bzero(&connp->u_port, sizeof (connp->u_port));
15953 	/* blow away saved option results if any */
15954 	if (tcp->tcp_conn.tcp_opts_conn_req != NULL)
15955 		tcp_close_mpp(&tcp->tcp_conn.tcp_opts_conn_req);
15956 
15957 	conn_delete_ire(tcp->tcp_connp, NULL);
15958 	putnext(q, mp);
15959 }
15960 
15961 /*
15962  * tcp_rput_other is called by tcp_rput to handle everything other than M_DATA
15963  * messages.
15964  */
15965 void
15966 tcp_rput_other(tcp_t *tcp, mblk_t *mp)
15967 {
15968 	mblk_t	*mp1;
15969 	uchar_t	*rptr = mp->b_rptr;
15970 	queue_t	*q = tcp->tcp_rq;
15971 	struct T_error_ack *tea;
15972 	uint32_t mss;
15973 	mblk_t *syn_mp;
15974 	mblk_t *mdti;
15975 	mblk_t *lsoi;
15976 	int	retval;
15977 	mblk_t *ire_mp;
15978 	tcp_stack_t	*tcps = tcp->tcp_tcps;
15979 
15980 	switch (mp->b_datap->db_type) {
15981 	case M_PROTO:
15982 	case M_PCPROTO:
15983 		ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
15984 		if ((mp->b_wptr - rptr) < sizeof (t_scalar_t))
15985 			break;
15986 		tea = (struct T_error_ack *)rptr;
15987 		switch (tea->PRIM_type) {
15988 		case T_BIND_ACK:
15989 			/*
15990 			 * Adapt Multidata information, if any.  The
15991 			 * following tcp_mdt_update routine will free
15992 			 * the message.
15993 			 */
15994 			if ((mdti = tcp_mdt_info_mp(mp)) != NULL) {
15995 				tcp_mdt_update(tcp, &((ip_mdt_info_t *)mdti->
15996 				    b_rptr)->mdt_capab, B_TRUE);
15997 				freemsg(mdti);
15998 			}
15999 
16000 			/*
16001 			 * Check to update LSO information with tcp, and
16002 			 * tcp_lso_update routine will free the message.
16003 			 */
16004 			if ((lsoi = tcp_lso_info_mp(mp)) != NULL) {
16005 				tcp_lso_update(tcp, &((ip_lso_info_t *)lsoi->
16006 				    b_rptr)->lso_capab);
16007 				freemsg(lsoi);
16008 			}
16009 
16010 			/* Get the IRE, if we had requested for it */
16011 			ire_mp = tcp_ire_mp(mp);
16012 
16013 			if (tcp->tcp_hard_binding) {
16014 				tcp->tcp_hard_binding = B_FALSE;
16015 				tcp->tcp_hard_bound = B_TRUE;
16016 				CL_INET_CONNECT(tcp);
16017 			} else {
16018 				if (ire_mp != NULL)
16019 					freeb(ire_mp);
16020 				goto after_syn_sent;
16021 			}
16022 
16023 			retval = tcp_adapt_ire(tcp, ire_mp);
16024 			if (ire_mp != NULL)
16025 				freeb(ire_mp);
16026 			if (retval == 0) {
16027 				tcp_bind_failed(tcp, mp,
16028 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
16029 				    ENETUNREACH : EADDRNOTAVAIL));
16030 				return;
16031 			}
16032 			/*
16033 			 * Don't let an endpoint connect to itself.
16034 			 * Also checked in tcp_connect() but that
16035 			 * check can't handle the case when the
16036 			 * local IP address is INADDR_ANY.
16037 			 */
16038 			if (tcp->tcp_ipversion == IPV4_VERSION) {
16039 				if ((tcp->tcp_ipha->ipha_dst ==
16040 				    tcp->tcp_ipha->ipha_src) &&
16041 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16042 				    tcp->tcp_tcph->th_fport))) {
16043 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16044 					return;
16045 				}
16046 			} else {
16047 				if (IN6_ARE_ADDR_EQUAL(
16048 				    &tcp->tcp_ip6h->ip6_dst,
16049 				    &tcp->tcp_ip6h->ip6_src) &&
16050 				    (BE16_EQL(tcp->tcp_tcph->th_lport,
16051 				    tcp->tcp_tcph->th_fport))) {
16052 					tcp_bind_failed(tcp, mp, EADDRNOTAVAIL);
16053 					return;
16054 				}
16055 			}
16056 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT);
16057 			/*
16058 			 * This should not be possible!  Just for
16059 			 * defensive coding...
16060 			 */
16061 			if (tcp->tcp_state != TCPS_SYN_SENT)
16062 				goto after_syn_sent;
16063 
16064 			if (is_system_labeled() &&
16065 			    !tcp_update_label(tcp, CONN_CRED(tcp->tcp_connp))) {
16066 				tcp_bind_failed(tcp, mp, EHOSTUNREACH);
16067 				return;
16068 			}
16069 
16070 			ASSERT(q == tcp->tcp_rq);
16071 			/*
16072 			 * tcp_adapt_ire() does not adjust
16073 			 * for TCP/IP header length.
16074 			 */
16075 			mss = tcp->tcp_mss - tcp->tcp_hdr_len;
16076 
16077 			/*
16078 			 * Just make sure our rwnd is at
16079 			 * least tcp_recv_hiwat_mss * MSS
16080 			 * large, and round up to the nearest
16081 			 * MSS.
16082 			 *
16083 			 * We do the round up here because
16084 			 * we need to get the interface
16085 			 * MTU first before we can do the
16086 			 * round up.
16087 			 */
16088 			tcp->tcp_rwnd = MAX(MSS_ROUNDUP(tcp->tcp_rwnd, mss),
16089 			    tcps->tcps_recv_hiwat_minmss * mss);
16090 			q->q_hiwat = tcp->tcp_rwnd;
16091 			tcp_set_ws_value(tcp);
16092 			U32_TO_ABE16((tcp->tcp_rwnd >> tcp->tcp_rcv_ws),
16093 			    tcp->tcp_tcph->th_win);
16094 			if (tcp->tcp_rcv_ws > 0 || tcps->tcps_wscale_always)
16095 				tcp->tcp_snd_ws_ok = B_TRUE;
16096 
16097 			/*
16098 			 * Set tcp_snd_ts_ok to true
16099 			 * so that tcp_xmit_mp will
16100 			 * include the timestamp
16101 			 * option in the SYN segment.
16102 			 */
16103 			if (tcps->tcps_tstamp_always ||
16104 			    (tcp->tcp_rcv_ws && tcps->tcps_tstamp_if_wscale)) {
16105 				tcp->tcp_snd_ts_ok = B_TRUE;
16106 			}
16107 
16108 			/*
16109 			 * tcp_snd_sack_ok can be set in
16110 			 * tcp_adapt_ire() if the sack metric
16111 			 * is set.  So check it here also.
16112 			 */
16113 			if (tcps->tcps_sack_permitted == 2 ||
16114 			    tcp->tcp_snd_sack_ok) {
16115 				if (tcp->tcp_sack_info == NULL) {
16116 					tcp->tcp_sack_info =
16117 					    kmem_cache_alloc(
16118 					    tcp_sack_info_cache,
16119 					    KM_SLEEP);
16120 				}
16121 				tcp->tcp_snd_sack_ok = B_TRUE;
16122 			}
16123 
16124 			/*
16125 			 * Should we use ECN?  Note that the current
16126 			 * default value (SunOS 5.9) of tcp_ecn_permitted
16127 			 * is 1.  The reason for doing this is that there
16128 			 * are equipments out there that will drop ECN
16129 			 * enabled IP packets.  Setting it to 1 avoids
16130 			 * compatibility problems.
16131 			 */
16132 			if (tcps->tcps_ecn_permitted == 2)
16133 				tcp->tcp_ecn_ok = B_TRUE;
16134 
16135 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
16136 			syn_mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
16137 			    tcp->tcp_iss, B_FALSE, NULL, B_FALSE);
16138 			if (syn_mp) {
16139 				cred_t *cr;
16140 				pid_t pid;
16141 
16142 				/*
16143 				 * Obtain the credential from the
16144 				 * thread calling connect(); the credential
16145 				 * lives on in the second mblk which
16146 				 * originated from T_CONN_REQ and is echoed
16147 				 * with the T_BIND_ACK from ip.  If none
16148 				 * can be found, default to the creator
16149 				 * of the socket.
16150 				 */
16151 				if (mp->b_cont == NULL ||
16152 				    (cr = DB_CRED(mp->b_cont)) == NULL) {
16153 					cr = tcp->tcp_cred;
16154 					pid = tcp->tcp_cpid;
16155 				} else {
16156 					pid = DB_CPID(mp->b_cont);
16157 				}
16158 				mblk_setcred(syn_mp, cr);
16159 				DB_CPID(syn_mp) = pid;
16160 				tcp_send_data(tcp, tcp->tcp_wq, syn_mp);
16161 			}
16162 		after_syn_sent:
16163 			/*
16164 			 * A trailer mblk indicates a waiting client upstream.
16165 			 * We complete here the processing begun in
16166 			 * either tcp_bind() or tcp_connect() by passing
16167 			 * upstream the reply message they supplied.
16168 			 */
16169 			mp1 = mp;
16170 			mp = mp->b_cont;
16171 			freeb(mp1);
16172 			if (mp)
16173 				break;
16174 			return;
16175 		case T_ERROR_ACK:
16176 			if (tcp->tcp_debug) {
16177 				(void) strlog(TCP_MOD_ID, 0, 1,
16178 				    SL_TRACE|SL_ERROR,
16179 				    "tcp_rput_other: case T_ERROR_ACK, "
16180 				    "ERROR_prim == %d",
16181 				    tea->ERROR_prim);
16182 			}
16183 			switch (tea->ERROR_prim) {
16184 			case O_T_BIND_REQ:
16185 			case T_BIND_REQ:
16186 				tcp_bind_failed(tcp, mp,
16187 				    (int)((tcp->tcp_state >= TCPS_SYN_SENT) ?
16188 				    ENETUNREACH : EADDRNOTAVAIL));
16189 				return;
16190 			case T_UNBIND_REQ:
16191 				tcp->tcp_hard_binding = B_FALSE;
16192 				tcp->tcp_hard_bound = B_FALSE;
16193 				if (mp->b_cont) {
16194 					freemsg(mp->b_cont);
16195 					mp->b_cont = NULL;
16196 				}
16197 				if (tcp->tcp_unbind_pending)
16198 					tcp->tcp_unbind_pending = 0;
16199 				else {
16200 					/* From tcp_ip_unbind() - free */
16201 					freemsg(mp);
16202 					return;
16203 				}
16204 				break;
16205 			case T_SVR4_OPTMGMT_REQ:
16206 				if (tcp->tcp_drop_opt_ack_cnt > 0) {
16207 					/* T_OPTMGMT_REQ generated by TCP */
16208 					printf("T_SVR4_OPTMGMT_REQ failed "
16209 					    "%d/%d - dropped (cnt %d)\n",
16210 					    tea->TLI_error, tea->UNIX_error,
16211 					    tcp->tcp_drop_opt_ack_cnt);
16212 					freemsg(mp);
16213 					tcp->tcp_drop_opt_ack_cnt--;
16214 					return;
16215 				}
16216 				break;
16217 			}
16218 			if (tea->ERROR_prim == T_SVR4_OPTMGMT_REQ &&
16219 			    tcp->tcp_drop_opt_ack_cnt > 0) {
16220 				printf("T_SVR4_OPTMGMT_REQ failed %d/%d "
16221 				    "- dropped (cnt %d)\n",
16222 				    tea->TLI_error, tea->UNIX_error,
16223 				    tcp->tcp_drop_opt_ack_cnt);
16224 				freemsg(mp);
16225 				tcp->tcp_drop_opt_ack_cnt--;
16226 				return;
16227 			}
16228 			break;
16229 		case T_OPTMGMT_ACK:
16230 			if (tcp->tcp_drop_opt_ack_cnt > 0) {
16231 				/* T_OPTMGMT_REQ generated by TCP */
16232 				freemsg(mp);
16233 				tcp->tcp_drop_opt_ack_cnt--;
16234 				return;
16235 			}
16236 			break;
16237 		default:
16238 			break;
16239 		}
16240 		break;
16241 	case M_FLUSH:
16242 		if (*rptr & FLUSHR)
16243 			flushq(q, FLUSHDATA);
16244 		break;
16245 	default:
16246 		/* M_CTL will be directly sent to tcp_icmp_error() */
16247 		ASSERT(DB_TYPE(mp) != M_CTL);
16248 		break;
16249 	}
16250 	/*
16251 	 * Make sure we set this bit before sending the ACK for
16252 	 * bind. Otherwise accept could possibly run and free
16253 	 * this tcp struct.
16254 	 */
16255 	putnext(q, mp);
16256 }
16257 
16258 /* ARGSUSED */
16259 static void
16260 tcp_rsrv_input(void *arg, mblk_t *mp, void *arg2)
16261 {
16262 	conn_t	*connp = (conn_t *)arg;
16263 	tcp_t	*tcp = connp->conn_tcp;
16264 	queue_t	*q = tcp->tcp_rq;
16265 	uint_t	thwin;
16266 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16267 	sodirect_t	*sodp;
16268 	boolean_t	fc;
16269 
16270 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
16271 	tcp->tcp_rsrv_mp = mp;
16272 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
16273 
16274 	TCP_STAT(tcps, tcp_rsrv_calls);
16275 
16276 	if (TCP_IS_DETACHED(tcp) || q == NULL) {
16277 		return;
16278 	}
16279 
16280 	if (tcp->tcp_fused) {
16281 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16282 
16283 		ASSERT(tcp->tcp_fused);
16284 		ASSERT(peer_tcp != NULL && peer_tcp->tcp_fused);
16285 		ASSERT(peer_tcp->tcp_loopback_peer == tcp);
16286 		ASSERT(!TCP_IS_DETACHED(tcp));
16287 		ASSERT(tcp->tcp_connp->conn_sqp ==
16288 		    peer_tcp->tcp_connp->conn_sqp);
16289 
16290 		/*
16291 		 * Normally we would not get backenabled in synchronous
16292 		 * streams mode, but in case this happens, we need to plug
16293 		 * synchronous streams during our drain to prevent a race
16294 		 * with tcp_fuse_rrw() or tcp_fuse_rinfop().
16295 		 */
16296 		TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
16297 		if (tcp->tcp_rcv_list != NULL)
16298 			(void) tcp_rcv_drain(tcp->tcp_rq, tcp);
16299 
16300 		if (peer_tcp > tcp) {
16301 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16302 			mutex_enter(&tcp->tcp_non_sq_lock);
16303 		} else {
16304 			mutex_enter(&tcp->tcp_non_sq_lock);
16305 			mutex_enter(&peer_tcp->tcp_non_sq_lock);
16306 		}
16307 
16308 		if (peer_tcp->tcp_flow_stopped &&
16309 		    (TCP_UNSENT_BYTES(peer_tcp) <=
16310 		    peer_tcp->tcp_xmit_lowater)) {
16311 			tcp_clrqfull(peer_tcp);
16312 		}
16313 		mutex_exit(&peer_tcp->tcp_non_sq_lock);
16314 		mutex_exit(&tcp->tcp_non_sq_lock);
16315 
16316 		TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
16317 		TCP_STAT(tcps, tcp_fusion_backenabled);
16318 		return;
16319 	}
16320 
16321 	SOD_PTR_ENTER(tcp, sodp);
16322 	if (sodp != NULL) {
16323 		/* An sodirect connection */
16324 		if (SOD_QFULL(sodp)) {
16325 			/* Flow-controlled, need another back-enable */
16326 			fc = B_TRUE;
16327 			SOD_QSETBE(sodp);
16328 		} else {
16329 			/* Not flow-controlled */
16330 			fc = B_FALSE;
16331 		}
16332 		mutex_exit(sodp->sod_lockp);
16333 	} else if (canputnext(q)) {
16334 		/* STREAMS, not flow-controlled */
16335 		fc = B_FALSE;
16336 	} else {
16337 		/* STREAMS, flow-controlled */
16338 		fc = B_TRUE;
16339 	}
16340 	if (!fc) {
16341 		/* Not flow-controlled, open rwnd */
16342 		tcp->tcp_rwnd = q->q_hiwat;
16343 		thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
16344 		    << tcp->tcp_rcv_ws;
16345 		thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
16346 		/*
16347 		 * Send back a window update immediately if TCP is above
16348 		 * ESTABLISHED state and the increase of the rcv window
16349 		 * that the other side knows is at least 1 MSS after flow
16350 		 * control is lifted.
16351 		 */
16352 		if (tcp->tcp_state >= TCPS_ESTABLISHED &&
16353 		    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
16354 			tcp_xmit_ctl(NULL, tcp,
16355 			    (tcp->tcp_swnd == 0) ? tcp->tcp_suna :
16356 			    tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
16357 			BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
16358 		}
16359 	}
16360 }
16361 
16362 /*
16363  * The read side service routine is called mostly when we get back-enabled as a
16364  * result of flow control relief.  Since we don't actually queue anything in
16365  * TCP, we have no data to send out of here.  What we do is clear the receive
16366  * window, and send out a window update.
16367  */
16368 static void
16369 tcp_rsrv(queue_t *q)
16370 {
16371 	conn_t		*connp = Q_TO_CONN(q);
16372 	tcp_t		*tcp = connp->conn_tcp;
16373 	mblk_t		*mp;
16374 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16375 
16376 	/* No code does a putq on the read side */
16377 	ASSERT(q->q_first == NULL);
16378 
16379 	/* Nothing to do for the default queue */
16380 	if (q == tcps->tcps_g_q) {
16381 		return;
16382 	}
16383 
16384 	/*
16385 	 * If tcp->tcp_rsrv_mp == NULL, it means that tcp_rsrv() has already
16386 	 * been run.  So just return.
16387 	 */
16388 	mutex_enter(&tcp->tcp_rsrv_mp_lock);
16389 	if ((mp = tcp->tcp_rsrv_mp) == NULL) {
16390 		mutex_exit(&tcp->tcp_rsrv_mp_lock);
16391 		return;
16392 	}
16393 	tcp->tcp_rsrv_mp = NULL;
16394 	mutex_exit(&tcp->tcp_rsrv_mp_lock);
16395 
16396 	CONN_INC_REF(connp);
16397 	squeue_enter(connp->conn_sqp, mp, tcp_rsrv_input, connp,
16398 	    SQTAG_TCP_RSRV);
16399 }
16400 
16401 /*
16402  * tcp_rwnd_set() is called to adjust the receive window to a desired value.
16403  * We do not allow the receive window to shrink.  After setting rwnd,
16404  * set the flow control hiwat of the stream.
16405  *
16406  * This function is called in 2 cases:
16407  *
16408  * 1) Before data transfer begins, in tcp_accept_comm() for accepting a
16409  *    connection (passive open) and in tcp_rput_data() for active connect.
16410  *    This is called after tcp_mss_set() when the desired MSS value is known.
16411  *    This makes sure that our window size is a mutiple of the other side's
16412  *    MSS.
16413  * 2) Handling SO_RCVBUF option.
16414  *
16415  * It is ASSUMED that the requested size is a multiple of the current MSS.
16416  *
16417  * XXX - Should allow a lower rwnd than tcp_recv_hiwat_minmss * mss if the
16418  * user requests so.
16419  */
16420 static int
16421 tcp_rwnd_set(tcp_t *tcp, uint32_t rwnd)
16422 {
16423 	uint32_t	mss = tcp->tcp_mss;
16424 	uint32_t	old_max_rwnd;
16425 	uint32_t	max_transmittable_rwnd;
16426 	boolean_t	tcp_detached = TCP_IS_DETACHED(tcp);
16427 	tcp_stack_t	*tcps = tcp->tcp_tcps;
16428 
16429 	if (tcp->tcp_fused) {
16430 		size_t sth_hiwat;
16431 		tcp_t *peer_tcp = tcp->tcp_loopback_peer;
16432 
16433 		ASSERT(peer_tcp != NULL);
16434 		/*
16435 		 * Record the stream head's high water mark for
16436 		 * this endpoint; this is used for flow-control
16437 		 * purposes in tcp_fuse_output().
16438 		 */
16439 		sth_hiwat = tcp_fuse_set_rcv_hiwat(tcp, rwnd);
16440 		if (!tcp_detached)
16441 			(void) mi_set_sth_hiwat(tcp->tcp_rq, sth_hiwat);
16442 
16443 		/*
16444 		 * In the fusion case, the maxpsz stream head value of
16445 		 * our peer is set according to its send buffer size
16446 		 * and our receive buffer size; since the latter may
16447 		 * have changed we need to update the peer's maxpsz.
16448 		 */
16449 		(void) tcp_maxpsz_set(peer_tcp, B_TRUE);
16450 		return (rwnd);
16451 	}
16452 
16453 	if (tcp_detached)
16454 		old_max_rwnd = tcp->tcp_rwnd;
16455 	else
16456 		old_max_rwnd = tcp->tcp_rq->q_hiwat;
16457 
16458 	/*
16459 	 * Insist on a receive window that is at least
16460 	 * tcp_recv_hiwat_minmss * MSS (default 4 * MSS) to avoid
16461 	 * funny TCP interactions of Nagle algorithm, SWS avoidance
16462 	 * and delayed acknowledgement.
16463 	 */
16464 	rwnd = MAX(rwnd, tcps->tcps_recv_hiwat_minmss * mss);
16465 
16466 	/*
16467 	 * If window size info has already been exchanged, TCP should not
16468 	 * shrink the window.  Shrinking window is doable if done carefully.
16469 	 * We may add that support later.  But so far there is not a real
16470 	 * need to do that.
16471 	 */
16472 	if (rwnd < old_max_rwnd && tcp->tcp_state > TCPS_SYN_SENT) {
16473 		/* MSS may have changed, do a round up again. */
16474 		rwnd = MSS_ROUNDUP(old_max_rwnd, mss);
16475 	}
16476 
16477 	/*
16478 	 * tcp_rcv_ws starts with TCP_MAX_WINSHIFT so the following check
16479 	 * can be applied even before the window scale option is decided.
16480 	 */
16481 	max_transmittable_rwnd = TCP_MAXWIN << tcp->tcp_rcv_ws;
16482 	if (rwnd > max_transmittable_rwnd) {
16483 		rwnd = max_transmittable_rwnd -
16484 		    (max_transmittable_rwnd % mss);
16485 		if (rwnd < mss)
16486 			rwnd = max_transmittable_rwnd;
16487 		/*
16488 		 * If we're over the limit we may have to back down tcp_rwnd.
16489 		 * The increment below won't work for us. So we set all three
16490 		 * here and the increment below will have no effect.
16491 		 */
16492 		tcp->tcp_rwnd = old_max_rwnd = rwnd;
16493 	}
16494 	if (tcp->tcp_localnet) {
16495 		tcp->tcp_rack_abs_max =
16496 		    MIN(tcps->tcps_local_dacks_max, rwnd / mss / 2);
16497 	} else {
16498 		/*
16499 		 * For a remote host on a different subnet (through a router),
16500 		 * we ack every other packet to be conforming to RFC1122.
16501 		 * tcp_deferred_acks_max is default to 2.
16502 		 */
16503 		tcp->tcp_rack_abs_max =
16504 		    MIN(tcps->tcps_deferred_acks_max, rwnd / mss / 2);
16505 	}
16506 	if (tcp->tcp_rack_cur_max > tcp->tcp_rack_abs_max)
16507 		tcp->tcp_rack_cur_max = tcp->tcp_rack_abs_max;
16508 	else
16509 		tcp->tcp_rack_cur_max = 0;
16510 	/*
16511 	 * Increment the current rwnd by the amount the maximum grew (we
16512 	 * can not overwrite it since we might be in the middle of a
16513 	 * connection.)
16514 	 */
16515 	tcp->tcp_rwnd += rwnd - old_max_rwnd;
16516 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws, tcp->tcp_tcph->th_win);
16517 	if ((tcp->tcp_rcv_ws > 0) && rwnd > tcp->tcp_cwnd_max)
16518 		tcp->tcp_cwnd_max = rwnd;
16519 
16520 	if (tcp_detached)
16521 		return (rwnd);
16522 	/*
16523 	 * We set the maximum receive window into rq->q_hiwat.
16524 	 * This is not actually used for flow control.
16525 	 */
16526 	tcp->tcp_rq->q_hiwat = rwnd;
16527 	/*
16528 	 * Set the Stream head high water mark. This doesn't have to be
16529 	 * here, since we are simply using default values, but we would
16530 	 * prefer to choose these values algorithmically, with a likely
16531 	 * relationship to rwnd.
16532 	 */
16533 	(void) mi_set_sth_hiwat(tcp->tcp_rq,
16534 	    MAX(rwnd, tcps->tcps_sth_rcv_hiwat));
16535 	return (rwnd);
16536 }
16537 
16538 /*
16539  * Return SNMP stuff in buffer in mpdata.
16540  */
16541 mblk_t *
16542 tcp_snmp_get(queue_t *q, mblk_t *mpctl)
16543 {
16544 	mblk_t			*mpdata;
16545 	mblk_t			*mp_conn_ctl = NULL;
16546 	mblk_t			*mp_conn_tail;
16547 	mblk_t			*mp_attr_ctl = NULL;
16548 	mblk_t			*mp_attr_tail;
16549 	mblk_t			*mp6_conn_ctl = NULL;
16550 	mblk_t			*mp6_conn_tail;
16551 	mblk_t			*mp6_attr_ctl = NULL;
16552 	mblk_t			*mp6_attr_tail;
16553 	struct opthdr		*optp;
16554 	mib2_tcpConnEntry_t	tce;
16555 	mib2_tcp6ConnEntry_t	tce6;
16556 	mib2_transportMLPEntry_t mlp;
16557 	connf_t			*connfp;
16558 	int			i;
16559 	boolean_t 		ispriv;
16560 	zoneid_t 		zoneid;
16561 	int			v4_conn_idx;
16562 	int			v6_conn_idx;
16563 	conn_t			*connp = Q_TO_CONN(q);
16564 	tcp_stack_t		*tcps;
16565 	ip_stack_t		*ipst;
16566 	mblk_t			*mp2ctl;
16567 
16568 	/*
16569 	 * make a copy of the original message
16570 	 */
16571 	mp2ctl = copymsg(mpctl);
16572 
16573 	if (mpctl == NULL ||
16574 	    (mpdata = mpctl->b_cont) == NULL ||
16575 	    (mp_conn_ctl = copymsg(mpctl)) == NULL ||
16576 	    (mp_attr_ctl = copymsg(mpctl)) == NULL ||
16577 	    (mp6_conn_ctl = copymsg(mpctl)) == NULL ||
16578 	    (mp6_attr_ctl = copymsg(mpctl)) == NULL) {
16579 		freemsg(mp_conn_ctl);
16580 		freemsg(mp_attr_ctl);
16581 		freemsg(mp6_conn_ctl);
16582 		freemsg(mp6_attr_ctl);
16583 		freemsg(mpctl);
16584 		freemsg(mp2ctl);
16585 		return (NULL);
16586 	}
16587 
16588 	ipst = connp->conn_netstack->netstack_ip;
16589 	tcps = connp->conn_netstack->netstack_tcp;
16590 
16591 	/* build table of connections -- need count in fixed part */
16592 	SET_MIB(tcps->tcps_mib.tcpRtoAlgorithm, 4);   /* vanj */
16593 	SET_MIB(tcps->tcps_mib.tcpRtoMin, tcps->tcps_rexmit_interval_min);
16594 	SET_MIB(tcps->tcps_mib.tcpRtoMax, tcps->tcps_rexmit_interval_max);
16595 	SET_MIB(tcps->tcps_mib.tcpMaxConn, -1);
16596 	SET_MIB(tcps->tcps_mib.tcpCurrEstab, 0);
16597 
16598 	ispriv =
16599 	    secpolicy_ip_config((Q_TO_CONN(q))->conn_cred, B_TRUE) == 0;
16600 	zoneid = Q_TO_CONN(q)->conn_zoneid;
16601 
16602 	v4_conn_idx = v6_conn_idx = 0;
16603 	mp_conn_tail = mp_attr_tail = mp6_conn_tail = mp6_attr_tail = NULL;
16604 
16605 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
16606 		ipst = tcps->tcps_netstack->netstack_ip;
16607 
16608 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
16609 
16610 		connp = NULL;
16611 
16612 		while ((connp =
16613 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
16614 			tcp_t *tcp;
16615 			boolean_t needattr;
16616 
16617 			if (connp->conn_zoneid != zoneid)
16618 				continue;	/* not in this zone */
16619 
16620 			tcp = connp->conn_tcp;
16621 			UPDATE_MIB(&tcps->tcps_mib,
16622 			    tcpHCInSegs, tcp->tcp_ibsegs);
16623 			tcp->tcp_ibsegs = 0;
16624 			UPDATE_MIB(&tcps->tcps_mib,
16625 			    tcpHCOutSegs, tcp->tcp_obsegs);
16626 			tcp->tcp_obsegs = 0;
16627 
16628 			tce6.tcp6ConnState = tce.tcpConnState =
16629 			    tcp_snmp_state(tcp);
16630 			if (tce.tcpConnState == MIB2_TCP_established ||
16631 			    tce.tcpConnState == MIB2_TCP_closeWait)
16632 				BUMP_MIB(&tcps->tcps_mib, tcpCurrEstab);
16633 
16634 			needattr = B_FALSE;
16635 			bzero(&mlp, sizeof (mlp));
16636 			if (connp->conn_mlp_type != mlptSingle) {
16637 				if (connp->conn_mlp_type == mlptShared ||
16638 				    connp->conn_mlp_type == mlptBoth)
16639 					mlp.tme_flags |= MIB2_TMEF_SHARED;
16640 				if (connp->conn_mlp_type == mlptPrivate ||
16641 				    connp->conn_mlp_type == mlptBoth)
16642 					mlp.tme_flags |= MIB2_TMEF_PRIVATE;
16643 				needattr = B_TRUE;
16644 			}
16645 			if (connp->conn_peercred != NULL) {
16646 				ts_label_t *tsl;
16647 
16648 				tsl = crgetlabel(connp->conn_peercred);
16649 				mlp.tme_doi = label2doi(tsl);
16650 				mlp.tme_label = *label2bslabel(tsl);
16651 				needattr = B_TRUE;
16652 			}
16653 
16654 			/* Create a message to report on IPv6 entries */
16655 			if (tcp->tcp_ipversion == IPV6_VERSION) {
16656 			tce6.tcp6ConnLocalAddress = tcp->tcp_ip_src_v6;
16657 			tce6.tcp6ConnRemAddress = tcp->tcp_remote_v6;
16658 			tce6.tcp6ConnLocalPort = ntohs(tcp->tcp_lport);
16659 			tce6.tcp6ConnRemPort = ntohs(tcp->tcp_fport);
16660 			tce6.tcp6ConnIfIndex = tcp->tcp_bound_if;
16661 			/* Don't want just anybody seeing these... */
16662 			if (ispriv) {
16663 				tce6.tcp6ConnEntryInfo.ce_snxt =
16664 				    tcp->tcp_snxt;
16665 				tce6.tcp6ConnEntryInfo.ce_suna =
16666 				    tcp->tcp_suna;
16667 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16668 				    tcp->tcp_rnxt;
16669 				tce6.tcp6ConnEntryInfo.ce_rack =
16670 				    tcp->tcp_rack;
16671 			} else {
16672 				/*
16673 				 * Netstat, unfortunately, uses this to
16674 				 * get send/receive queue sizes.  How to fix?
16675 				 * Why not compute the difference only?
16676 				 */
16677 				tce6.tcp6ConnEntryInfo.ce_snxt =
16678 				    tcp->tcp_snxt - tcp->tcp_suna;
16679 				tce6.tcp6ConnEntryInfo.ce_suna = 0;
16680 				tce6.tcp6ConnEntryInfo.ce_rnxt =
16681 				    tcp->tcp_rnxt - tcp->tcp_rack;
16682 				tce6.tcp6ConnEntryInfo.ce_rack = 0;
16683 			}
16684 
16685 			tce6.tcp6ConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16686 			tce6.tcp6ConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16687 			tce6.tcp6ConnEntryInfo.ce_rto =  tcp->tcp_rto;
16688 			tce6.tcp6ConnEntryInfo.ce_mss =  tcp->tcp_mss;
16689 			tce6.tcp6ConnEntryInfo.ce_state = tcp->tcp_state;
16690 
16691 			tce6.tcp6ConnCreationProcess =
16692 			    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16693 			    tcp->tcp_cpid;
16694 			tce6.tcp6ConnCreationTime = tcp->tcp_open_time;
16695 
16696 			(void) snmp_append_data2(mp6_conn_ctl->b_cont,
16697 			    &mp6_conn_tail, (char *)&tce6, sizeof (tce6));
16698 
16699 			mlp.tme_connidx = v6_conn_idx++;
16700 			if (needattr)
16701 				(void) snmp_append_data2(mp6_attr_ctl->b_cont,
16702 				    &mp6_attr_tail, (char *)&mlp, sizeof (mlp));
16703 			}
16704 			/*
16705 			 * Create an IPv4 table entry for IPv4 entries and also
16706 			 * for IPv6 entries which are bound to in6addr_any
16707 			 * but don't have IPV6_V6ONLY set.
16708 			 * (i.e. anything an IPv4 peer could connect to)
16709 			 */
16710 			if (tcp->tcp_ipversion == IPV4_VERSION ||
16711 			    (tcp->tcp_state <= TCPS_LISTEN &&
16712 			    !tcp->tcp_connp->conn_ipv6_v6only &&
16713 			    IN6_IS_ADDR_UNSPECIFIED(&tcp->tcp_ip_src_v6))) {
16714 				if (tcp->tcp_ipversion == IPV6_VERSION) {
16715 					tce.tcpConnRemAddress = INADDR_ANY;
16716 					tce.tcpConnLocalAddress = INADDR_ANY;
16717 				} else {
16718 					tce.tcpConnRemAddress =
16719 					    tcp->tcp_remote;
16720 					tce.tcpConnLocalAddress =
16721 					    tcp->tcp_ip_src;
16722 				}
16723 				tce.tcpConnLocalPort = ntohs(tcp->tcp_lport);
16724 				tce.tcpConnRemPort = ntohs(tcp->tcp_fport);
16725 				/* Don't want just anybody seeing these... */
16726 				if (ispriv) {
16727 					tce.tcpConnEntryInfo.ce_snxt =
16728 					    tcp->tcp_snxt;
16729 					tce.tcpConnEntryInfo.ce_suna =
16730 					    tcp->tcp_suna;
16731 					tce.tcpConnEntryInfo.ce_rnxt =
16732 					    tcp->tcp_rnxt;
16733 					tce.tcpConnEntryInfo.ce_rack =
16734 					    tcp->tcp_rack;
16735 				} else {
16736 					/*
16737 					 * Netstat, unfortunately, uses this to
16738 					 * get send/receive queue sizes.  How
16739 					 * to fix?
16740 					 * Why not compute the difference only?
16741 					 */
16742 					tce.tcpConnEntryInfo.ce_snxt =
16743 					    tcp->tcp_snxt - tcp->tcp_suna;
16744 					tce.tcpConnEntryInfo.ce_suna = 0;
16745 					tce.tcpConnEntryInfo.ce_rnxt =
16746 					    tcp->tcp_rnxt - tcp->tcp_rack;
16747 					tce.tcpConnEntryInfo.ce_rack = 0;
16748 				}
16749 
16750 				tce.tcpConnEntryInfo.ce_swnd = tcp->tcp_swnd;
16751 				tce.tcpConnEntryInfo.ce_rwnd = tcp->tcp_rwnd;
16752 				tce.tcpConnEntryInfo.ce_rto =  tcp->tcp_rto;
16753 				tce.tcpConnEntryInfo.ce_mss =  tcp->tcp_mss;
16754 				tce.tcpConnEntryInfo.ce_state =
16755 				    tcp->tcp_state;
16756 
16757 				tce.tcpConnCreationProcess =
16758 				    (tcp->tcp_cpid < 0) ? MIB2_UNKNOWN_PROCESS :
16759 				    tcp->tcp_cpid;
16760 				tce.tcpConnCreationTime = tcp->tcp_open_time;
16761 
16762 				(void) snmp_append_data2(mp_conn_ctl->b_cont,
16763 				    &mp_conn_tail, (char *)&tce, sizeof (tce));
16764 
16765 				mlp.tme_connidx = v4_conn_idx++;
16766 				if (needattr)
16767 					(void) snmp_append_data2(
16768 					    mp_attr_ctl->b_cont,
16769 					    &mp_attr_tail, (char *)&mlp,
16770 					    sizeof (mlp));
16771 			}
16772 		}
16773 	}
16774 
16775 	/* fixed length structure for IPv4 and IPv6 counters */
16776 	SET_MIB(tcps->tcps_mib.tcpConnTableSize, sizeof (mib2_tcpConnEntry_t));
16777 	SET_MIB(tcps->tcps_mib.tcp6ConnTableSize,
16778 	    sizeof (mib2_tcp6ConnEntry_t));
16779 	/* synchronize 32- and 64-bit counters */
16780 	SYNC32_MIB(&tcps->tcps_mib, tcpInSegs, tcpHCInSegs);
16781 	SYNC32_MIB(&tcps->tcps_mib, tcpOutSegs, tcpHCOutSegs);
16782 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
16783 	optp->level = MIB2_TCP;
16784 	optp->name = 0;
16785 	(void) snmp_append_data(mpdata, (char *)&tcps->tcps_mib,
16786 	    sizeof (tcps->tcps_mib));
16787 	optp->len = msgdsize(mpdata);
16788 	qreply(q, mpctl);
16789 
16790 	/* table of connections... */
16791 	optp = (struct opthdr *)&mp_conn_ctl->b_rptr[
16792 	    sizeof (struct T_optmgmt_ack)];
16793 	optp->level = MIB2_TCP;
16794 	optp->name = MIB2_TCP_CONN;
16795 	optp->len = msgdsize(mp_conn_ctl->b_cont);
16796 	qreply(q, mp_conn_ctl);
16797 
16798 	/* table of MLP attributes... */
16799 	optp = (struct opthdr *)&mp_attr_ctl->b_rptr[
16800 	    sizeof (struct T_optmgmt_ack)];
16801 	optp->level = MIB2_TCP;
16802 	optp->name = EXPER_XPORT_MLP;
16803 	optp->len = msgdsize(mp_attr_ctl->b_cont);
16804 	if (optp->len == 0)
16805 		freemsg(mp_attr_ctl);
16806 	else
16807 		qreply(q, mp_attr_ctl);
16808 
16809 	/* table of IPv6 connections... */
16810 	optp = (struct opthdr *)&mp6_conn_ctl->b_rptr[
16811 	    sizeof (struct T_optmgmt_ack)];
16812 	optp->level = MIB2_TCP6;
16813 	optp->name = MIB2_TCP6_CONN;
16814 	optp->len = msgdsize(mp6_conn_ctl->b_cont);
16815 	qreply(q, mp6_conn_ctl);
16816 
16817 	/* table of IPv6 MLP attributes... */
16818 	optp = (struct opthdr *)&mp6_attr_ctl->b_rptr[
16819 	    sizeof (struct T_optmgmt_ack)];
16820 	optp->level = MIB2_TCP6;
16821 	optp->name = EXPER_XPORT_MLP;
16822 	optp->len = msgdsize(mp6_attr_ctl->b_cont);
16823 	if (optp->len == 0)
16824 		freemsg(mp6_attr_ctl);
16825 	else
16826 		qreply(q, mp6_attr_ctl);
16827 	return (mp2ctl);
16828 }
16829 
16830 /* Return 0 if invalid set request, 1 otherwise, including non-tcp requests  */
16831 /* ARGSUSED */
16832 int
16833 tcp_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
16834 {
16835 	mib2_tcpConnEntry_t	*tce = (mib2_tcpConnEntry_t *)ptr;
16836 
16837 	switch (level) {
16838 	case MIB2_TCP:
16839 		switch (name) {
16840 		case 13:
16841 			if (tce->tcpConnState != MIB2_TCP_deleteTCB)
16842 				return (0);
16843 			/* TODO: delete entry defined by tce */
16844 			return (1);
16845 		default:
16846 			return (0);
16847 		}
16848 	default:
16849 		return (1);
16850 	}
16851 }
16852 
16853 /* Translate TCP state to MIB2 TCP state. */
16854 static int
16855 tcp_snmp_state(tcp_t *tcp)
16856 {
16857 	if (tcp == NULL)
16858 		return (0);
16859 
16860 	switch (tcp->tcp_state) {
16861 	case TCPS_CLOSED:
16862 	case TCPS_IDLE:	/* RFC1213 doesn't have analogue for IDLE & BOUND */
16863 	case TCPS_BOUND:
16864 		return (MIB2_TCP_closed);
16865 	case TCPS_LISTEN:
16866 		return (MIB2_TCP_listen);
16867 	case TCPS_SYN_SENT:
16868 		return (MIB2_TCP_synSent);
16869 	case TCPS_SYN_RCVD:
16870 		return (MIB2_TCP_synReceived);
16871 	case TCPS_ESTABLISHED:
16872 		return (MIB2_TCP_established);
16873 	case TCPS_CLOSE_WAIT:
16874 		return (MIB2_TCP_closeWait);
16875 	case TCPS_FIN_WAIT_1:
16876 		return (MIB2_TCP_finWait1);
16877 	case TCPS_CLOSING:
16878 		return (MIB2_TCP_closing);
16879 	case TCPS_LAST_ACK:
16880 		return (MIB2_TCP_lastAck);
16881 	case TCPS_FIN_WAIT_2:
16882 		return (MIB2_TCP_finWait2);
16883 	case TCPS_TIME_WAIT:
16884 		return (MIB2_TCP_timeWait);
16885 	default:
16886 		return (0);
16887 	}
16888 }
16889 
16890 static char tcp_report_header[] =
16891 	"TCP     " MI_COL_HDRPAD_STR
16892 	"zone dest            snxt     suna     "
16893 	"swnd       rnxt     rack     rwnd       rto   mss   w sw rw t "
16894 	"recent   [lport,fport] state";
16895 
16896 /*
16897  * TCP status report triggered via the Named Dispatch mechanism.
16898  */
16899 /* ARGSUSED */
16900 static void
16901 tcp_report_item(mblk_t *mp, tcp_t *tcp, int hashval, tcp_t *thisstream,
16902     cred_t *cr)
16903 {
16904 	char hash[10], addrbuf[INET6_ADDRSTRLEN];
16905 	boolean_t ispriv = secpolicy_ip_config(cr, B_TRUE) == 0;
16906 	char cflag;
16907 	in6_addr_t	v6dst;
16908 	char buf[80];
16909 	uint_t print_len, buf_len;
16910 
16911 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16912 	if (buf_len <= 0)
16913 		return;
16914 
16915 	if (hashval >= 0)
16916 		(void) sprintf(hash, "%03d ", hashval);
16917 	else
16918 		hash[0] = '\0';
16919 
16920 	/*
16921 	 * Note that we use the remote address in the tcp_b  structure.
16922 	 * This means that it will print out the real destination address,
16923 	 * not the next hop's address if source routing is used.  This
16924 	 * avoid the confusion on the output because user may not
16925 	 * know that source routing is used for a connection.
16926 	 */
16927 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16928 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_remote, &v6dst);
16929 	} else {
16930 		v6dst = tcp->tcp_remote_v6;
16931 	}
16932 	(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16933 	/*
16934 	 * the ispriv checks are so that normal users cannot determine
16935 	 * sequence number information using NDD.
16936 	 */
16937 
16938 	if (TCP_IS_DETACHED(tcp))
16939 		cflag = '*';
16940 	else
16941 		cflag = ' ';
16942 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16943 	    "%s " MI_COL_PTRFMT_STR "%d %s %08x %08x %010d %08x %08x "
16944 	    "%010d %05ld %05d %1d %02d %02d %1d %08x %s%c\n",
16945 	    hash,
16946 	    (void *)tcp,
16947 	    tcp->tcp_connp->conn_zoneid,
16948 	    addrbuf,
16949 	    (ispriv) ? tcp->tcp_snxt : 0,
16950 	    (ispriv) ? tcp->tcp_suna : 0,
16951 	    tcp->tcp_swnd,
16952 	    (ispriv) ? tcp->tcp_rnxt : 0,
16953 	    (ispriv) ? tcp->tcp_rack : 0,
16954 	    tcp->tcp_rwnd,
16955 	    tcp->tcp_rto,
16956 	    tcp->tcp_mss,
16957 	    tcp->tcp_snd_ws_ok,
16958 	    tcp->tcp_snd_ws,
16959 	    tcp->tcp_rcv_ws,
16960 	    tcp->tcp_snd_ts_ok,
16961 	    tcp->tcp_ts_recent,
16962 	    tcp_display(tcp, buf, DISP_PORT_ONLY), cflag);
16963 	if (print_len < buf_len) {
16964 		((mblk_t *)mp)->b_wptr += print_len;
16965 	} else {
16966 		((mblk_t *)mp)->b_wptr += buf_len;
16967 	}
16968 }
16969 
16970 /*
16971  * TCP status report (for listeners only) triggered via the Named Dispatch
16972  * mechanism.
16973  */
16974 /* ARGSUSED */
16975 static void
16976 tcp_report_listener(mblk_t *mp, tcp_t *tcp, int hashval)
16977 {
16978 	char addrbuf[INET6_ADDRSTRLEN];
16979 	in6_addr_t	v6dst;
16980 	uint_t print_len, buf_len;
16981 
16982 	buf_len = mp->b_datap->db_lim - mp->b_wptr;
16983 	if (buf_len <= 0)
16984 		return;
16985 
16986 	if (tcp->tcp_ipversion == IPV4_VERSION) {
16987 		IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src, &v6dst);
16988 		(void) inet_ntop(AF_INET6, &v6dst, addrbuf, sizeof (addrbuf));
16989 	} else {
16990 		(void) inet_ntop(AF_INET6, &tcp->tcp_ip6h->ip6_src,
16991 		    addrbuf, sizeof (addrbuf));
16992 	}
16993 	print_len = snprintf((char *)mp->b_wptr, buf_len,
16994 	    "%03d "
16995 	    MI_COL_PTRFMT_STR
16996 	    "%d %s %05u %08u %d/%d/%d%c\n",
16997 	    hashval, (void *)tcp,
16998 	    tcp->tcp_connp->conn_zoneid,
16999 	    addrbuf,
17000 	    (uint_t)BE16_TO_U16(tcp->tcp_tcph->th_lport),
17001 	    tcp->tcp_conn_req_seqnum,
17002 	    tcp->tcp_conn_req_cnt_q0, tcp->tcp_conn_req_cnt_q,
17003 	    tcp->tcp_conn_req_max,
17004 	    tcp->tcp_syn_defense ? '*' : ' ');
17005 	if (print_len < buf_len) {
17006 		((mblk_t *)mp)->b_wptr += print_len;
17007 	} else {
17008 		((mblk_t *)mp)->b_wptr += buf_len;
17009 	}
17010 }
17011 
17012 /* TCP status report triggered via the Named Dispatch mechanism. */
17013 /* ARGSUSED */
17014 static int
17015 tcp_status_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17016 {
17017 	tcp_t	*tcp;
17018 	int	i;
17019 	conn_t	*connp;
17020 	connf_t	*connfp;
17021 	zoneid_t zoneid;
17022 	tcp_stack_t *tcps;
17023 	ip_stack_t *ipst;
17024 
17025 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17026 	tcps = Q_TO_TCP(q)->tcp_tcps;
17027 
17028 	/*
17029 	 * Because of the ndd constraint, at most we can have 64K buffer
17030 	 * to put in all TCP info.  So to be more efficient, just
17031 	 * allocate a 64K buffer here, assuming we need that large buffer.
17032 	 * This may be a problem as any user can read tcp_status.  Therefore
17033 	 * we limit the rate of doing this using tcp_ndd_get_info_interval.
17034 	 * This should be OK as normal users should not do this too often.
17035 	 */
17036 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17037 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17038 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17039 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17040 			return (0);
17041 		}
17042 	}
17043 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17044 		/* The following may work even if we cannot get a large buf. */
17045 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17046 		return (0);
17047 	}
17048 
17049 	(void) mi_mpprintf(mp, "%s", tcp_report_header);
17050 
17051 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
17052 
17053 		ipst = tcps->tcps_netstack->netstack_ip;
17054 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
17055 
17056 		connp = NULL;
17057 
17058 		while ((connp =
17059 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17060 			tcp = connp->conn_tcp;
17061 			if (zoneid != GLOBAL_ZONEID &&
17062 			    zoneid != connp->conn_zoneid)
17063 				continue;
17064 			tcp_report_item(mp->b_cont, tcp, -1, tcp,
17065 			    cr);
17066 		}
17067 
17068 	}
17069 
17070 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17071 	return (0);
17072 }
17073 
17074 /* TCP status report triggered via the Named Dispatch mechanism. */
17075 /* ARGSUSED */
17076 static int
17077 tcp_bind_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17078 {
17079 	tf_t	*tbf;
17080 	tcp_t	*tcp;
17081 	int	i;
17082 	zoneid_t zoneid;
17083 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
17084 
17085 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17086 
17087 	/* Refer to comments in tcp_status_report(). */
17088 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17089 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17090 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17091 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17092 			return (0);
17093 		}
17094 	}
17095 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17096 		/* The following may work even if we cannot get a large buf. */
17097 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17098 		return (0);
17099 	}
17100 
17101 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17102 
17103 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
17104 		tbf = &tcps->tcps_bind_fanout[i];
17105 		mutex_enter(&tbf->tf_lock);
17106 		for (tcp = tbf->tf_tcp; tcp != NULL;
17107 		    tcp = tcp->tcp_bind_hash) {
17108 			if (zoneid != GLOBAL_ZONEID &&
17109 			    zoneid != tcp->tcp_connp->conn_zoneid)
17110 				continue;
17111 			CONN_INC_REF(tcp->tcp_connp);
17112 			tcp_report_item(mp->b_cont, tcp, i,
17113 			    Q_TO_TCP(q), cr);
17114 			CONN_DEC_REF(tcp->tcp_connp);
17115 		}
17116 		mutex_exit(&tbf->tf_lock);
17117 	}
17118 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17119 	return (0);
17120 }
17121 
17122 /* TCP status report triggered via the Named Dispatch mechanism. */
17123 /* ARGSUSED */
17124 static int
17125 tcp_listen_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17126 {
17127 	connf_t	*connfp;
17128 	conn_t	*connp;
17129 	tcp_t	*tcp;
17130 	int	i;
17131 	zoneid_t zoneid;
17132 	tcp_stack_t *tcps;
17133 	ip_stack_t	*ipst;
17134 
17135 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17136 	tcps = Q_TO_TCP(q)->tcp_tcps;
17137 
17138 	/* Refer to comments in tcp_status_report(). */
17139 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17140 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17141 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17142 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17143 			return (0);
17144 		}
17145 	}
17146 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17147 		/* The following may work even if we cannot get a large buf. */
17148 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17149 		return (0);
17150 	}
17151 
17152 	(void) mi_mpprintf(mp,
17153 	    "    TCP    " MI_COL_HDRPAD_STR
17154 	    "zone IP addr         port  seqnum   backlog (q0/q/max)");
17155 
17156 	ipst = tcps->tcps_netstack->netstack_ip;
17157 
17158 	for (i = 0; i < ipst->ips_ipcl_bind_fanout_size; i++) {
17159 		connfp = &ipst->ips_ipcl_bind_fanout[i];
17160 		connp = NULL;
17161 		while ((connp =
17162 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17163 			tcp = connp->conn_tcp;
17164 			if (zoneid != GLOBAL_ZONEID &&
17165 			    zoneid != connp->conn_zoneid)
17166 				continue;
17167 			tcp_report_listener(mp->b_cont, tcp, i);
17168 		}
17169 	}
17170 
17171 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17172 	return (0);
17173 }
17174 
17175 /* TCP status report triggered via the Named Dispatch mechanism. */
17176 /* ARGSUSED */
17177 static int
17178 tcp_conn_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17179 {
17180 	connf_t	*connfp;
17181 	conn_t	*connp;
17182 	tcp_t	*tcp;
17183 	int	i;
17184 	zoneid_t zoneid;
17185 	tcp_stack_t *tcps;
17186 	ip_stack_t *ipst;
17187 
17188 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17189 	tcps = Q_TO_TCP(q)->tcp_tcps;
17190 	ipst = tcps->tcps_netstack->netstack_ip;
17191 
17192 	/* Refer to comments in tcp_status_report(). */
17193 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17194 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17195 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17196 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17197 			return (0);
17198 		}
17199 	}
17200 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17201 		/* The following may work even if we cannot get a large buf. */
17202 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17203 		return (0);
17204 	}
17205 
17206 	(void) mi_mpprintf(mp, "tcp_conn_hash_size = %d",
17207 	    ipst->ips_ipcl_conn_fanout_size);
17208 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17209 
17210 	for (i = 0; i < ipst->ips_ipcl_conn_fanout_size; i++) {
17211 		connfp =  &ipst->ips_ipcl_conn_fanout[i];
17212 		connp = NULL;
17213 		while ((connp =
17214 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
17215 			tcp = connp->conn_tcp;
17216 			if (zoneid != GLOBAL_ZONEID &&
17217 			    zoneid != connp->conn_zoneid)
17218 				continue;
17219 			tcp_report_item(mp->b_cont, tcp, i,
17220 			    Q_TO_TCP(q), cr);
17221 		}
17222 	}
17223 
17224 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17225 	return (0);
17226 }
17227 
17228 /* TCP status report triggered via the Named Dispatch mechanism. */
17229 /* ARGSUSED */
17230 static int
17231 tcp_acceptor_hash_report(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *cr)
17232 {
17233 	tf_t	*tf;
17234 	tcp_t	*tcp;
17235 	int	i;
17236 	zoneid_t zoneid;
17237 	tcp_stack_t	*tcps;
17238 
17239 	zoneid = Q_TO_CONN(q)->conn_zoneid;
17240 	tcps = Q_TO_TCP(q)->tcp_tcps;
17241 
17242 	/* Refer to comments in tcp_status_report(). */
17243 	if (cr == NULL || secpolicy_ip_config(cr, B_TRUE) != 0) {
17244 		if (ddi_get_lbolt() - tcps->tcps_last_ndd_get_info_time <
17245 		    drv_usectohz(tcps->tcps_ndd_get_info_interval * 1000)) {
17246 			(void) mi_mpprintf(mp, NDD_TOO_QUICK_MSG);
17247 			return (0);
17248 		}
17249 	}
17250 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
17251 		/* The following may work even if we cannot get a large buf. */
17252 		(void) mi_mpprintf(mp, NDD_OUT_OF_BUF_MSG);
17253 		return (0);
17254 	}
17255 
17256 	(void) mi_mpprintf(mp, "    %s", tcp_report_header);
17257 
17258 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
17259 		tf = &tcps->tcps_acceptor_fanout[i];
17260 		mutex_enter(&tf->tf_lock);
17261 		for (tcp = tf->tf_tcp; tcp != NULL;
17262 		    tcp = tcp->tcp_acceptor_hash) {
17263 			if (zoneid != GLOBAL_ZONEID &&
17264 			    zoneid != tcp->tcp_connp->conn_zoneid)
17265 				continue;
17266 			tcp_report_item(mp->b_cont, tcp, i,
17267 			    Q_TO_TCP(q), cr);
17268 		}
17269 		mutex_exit(&tf->tf_lock);
17270 	}
17271 	tcps->tcps_last_ndd_get_info_time = ddi_get_lbolt();
17272 	return (0);
17273 }
17274 
17275 /*
17276  * tcp_timer is the timer service routine.  It handles the retransmission,
17277  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
17278  * from the state of the tcp instance what kind of action needs to be done
17279  * at the time it is called.
17280  */
17281 static void
17282 tcp_timer(void *arg)
17283 {
17284 	mblk_t		*mp;
17285 	clock_t		first_threshold;
17286 	clock_t		second_threshold;
17287 	clock_t		ms;
17288 	uint32_t	mss;
17289 	conn_t		*connp = (conn_t *)arg;
17290 	tcp_t		*tcp = connp->conn_tcp;
17291 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17292 
17293 	tcp->tcp_timer_tid = 0;
17294 
17295 	if (tcp->tcp_fused)
17296 		return;
17297 
17298 	first_threshold =  tcp->tcp_first_timer_threshold;
17299 	second_threshold = tcp->tcp_second_timer_threshold;
17300 	switch (tcp->tcp_state) {
17301 	case TCPS_IDLE:
17302 	case TCPS_BOUND:
17303 	case TCPS_LISTEN:
17304 		return;
17305 	case TCPS_SYN_RCVD: {
17306 		tcp_t	*listener = tcp->tcp_listener;
17307 
17308 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
17309 			ASSERT(tcp->tcp_rq == listener->tcp_rq);
17310 			/* it's our first timeout */
17311 			tcp->tcp_syn_rcvd_timeout = 1;
17312 			mutex_enter(&listener->tcp_eager_lock);
17313 			listener->tcp_syn_rcvd_timeout++;
17314 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
17315 				/*
17316 				 * Make this eager available for drop if we
17317 				 * need to drop one to accomodate a new
17318 				 * incoming SYN request.
17319 				 */
17320 				MAKE_DROPPABLE(listener, tcp);
17321 			}
17322 			if (!listener->tcp_syn_defense &&
17323 			    (listener->tcp_syn_rcvd_timeout >
17324 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
17325 			    (tcps->tcps_conn_req_max_q0 > 200)) {
17326 				/* We may be under attack. Put on a defense. */
17327 				listener->tcp_syn_defense = B_TRUE;
17328 				cmn_err(CE_WARN, "High TCP connect timeout "
17329 				    "rate! System (port %d) may be under a "
17330 				    "SYN flood attack!",
17331 				    BE16_TO_U16(listener->tcp_tcph->th_lport));
17332 
17333 				listener->tcp_ip_addr_cache = kmem_zalloc(
17334 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
17335 				    KM_NOSLEEP);
17336 			}
17337 			mutex_exit(&listener->tcp_eager_lock);
17338 		} else if (listener != NULL) {
17339 			mutex_enter(&listener->tcp_eager_lock);
17340 			tcp->tcp_syn_rcvd_timeout++;
17341 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
17342 			    !tcp->tcp_closemp_used) {
17343 				/*
17344 				 * This is our second timeout. Put the tcp in
17345 				 * the list of droppable eagers to allow it to
17346 				 * be dropped, if needed. We don't check
17347 				 * whether tcp_dontdrop is set or not to
17348 				 * protect ourselve from a SYN attack where a
17349 				 * remote host can spoof itself as one of the
17350 				 * good IP source and continue to hold
17351 				 * resources too long.
17352 				 */
17353 				MAKE_DROPPABLE(listener, tcp);
17354 			}
17355 			mutex_exit(&listener->tcp_eager_lock);
17356 		}
17357 	}
17358 		/* FALLTHRU */
17359 	case TCPS_SYN_SENT:
17360 		first_threshold =  tcp->tcp_first_ctimer_threshold;
17361 		second_threshold = tcp->tcp_second_ctimer_threshold;
17362 		break;
17363 	case TCPS_ESTABLISHED:
17364 	case TCPS_FIN_WAIT_1:
17365 	case TCPS_CLOSING:
17366 	case TCPS_CLOSE_WAIT:
17367 	case TCPS_LAST_ACK:
17368 		/* If we have data to rexmit */
17369 		if (tcp->tcp_suna != tcp->tcp_snxt) {
17370 			clock_t	time_to_wait;
17371 
17372 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetrans);
17373 			if (!tcp->tcp_xmit_head)
17374 				break;
17375 			time_to_wait = lbolt -
17376 			    (clock_t)tcp->tcp_xmit_head->b_prev;
17377 			time_to_wait = tcp->tcp_rto -
17378 			    TICK_TO_MSEC(time_to_wait);
17379 			/*
17380 			 * If the timer fires too early, 1 clock tick earlier,
17381 			 * restart the timer.
17382 			 */
17383 			if (time_to_wait > msec_per_tick) {
17384 				TCP_STAT(tcps, tcp_timer_fire_early);
17385 				TCP_TIMER_RESTART(tcp, time_to_wait);
17386 				return;
17387 			}
17388 			/*
17389 			 * When we probe zero windows, we force the swnd open.
17390 			 * If our peer acks with a closed window swnd will be
17391 			 * set to zero by tcp_rput(). As long as we are
17392 			 * receiving acks tcp_rput will
17393 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
17394 			 * first and second interval actions.  NOTE: the timer
17395 			 * interval is allowed to continue its exponential
17396 			 * backoff.
17397 			 */
17398 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
17399 				if (tcp->tcp_debug) {
17400 					(void) strlog(TCP_MOD_ID, 0, 1,
17401 					    SL_TRACE, "tcp_timer: zero win");
17402 				}
17403 			} else {
17404 				/*
17405 				 * After retransmission, we need to do
17406 				 * slow start.  Set the ssthresh to one
17407 				 * half of current effective window and
17408 				 * cwnd to one MSS.  Also reset
17409 				 * tcp_cwnd_cnt.
17410 				 *
17411 				 * Note that if tcp_ssthresh is reduced because
17412 				 * of ECN, do not reduce it again unless it is
17413 				 * already one window of data away (tcp_cwr
17414 				 * should then be cleared) or this is a
17415 				 * timeout for a retransmitted segment.
17416 				 */
17417 				uint32_t npkt;
17418 
17419 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
17420 					npkt = ((tcp->tcp_timer_backoff ?
17421 					    tcp->tcp_cwnd_ssthresh :
17422 					    tcp->tcp_snxt -
17423 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
17424 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
17425 					    tcp->tcp_mss;
17426 				}
17427 				tcp->tcp_cwnd = tcp->tcp_mss;
17428 				tcp->tcp_cwnd_cnt = 0;
17429 				if (tcp->tcp_ecn_ok) {
17430 					tcp->tcp_cwr = B_TRUE;
17431 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
17432 					tcp->tcp_ecn_cwr_sent = B_FALSE;
17433 				}
17434 			}
17435 			break;
17436 		}
17437 		/*
17438 		 * We have something to send yet we cannot send.  The
17439 		 * reason can be:
17440 		 *
17441 		 * 1. Zero send window: we need to do zero window probe.
17442 		 * 2. Zero cwnd: because of ECN, we need to "clock out
17443 		 * segments.
17444 		 * 3. SWS avoidance: receiver may have shrunk window,
17445 		 * reset our knowledge.
17446 		 *
17447 		 * Note that condition 2 can happen with either 1 or
17448 		 * 3.  But 1 and 3 are exclusive.
17449 		 */
17450 		if (tcp->tcp_unsent != 0) {
17451 			if (tcp->tcp_cwnd == 0) {
17452 				/*
17453 				 * Set tcp_cwnd to 1 MSS so that a
17454 				 * new segment can be sent out.  We
17455 				 * are "clocking out" new data when
17456 				 * the network is really congested.
17457 				 */
17458 				ASSERT(tcp->tcp_ecn_ok);
17459 				tcp->tcp_cwnd = tcp->tcp_mss;
17460 			}
17461 			if (tcp->tcp_swnd == 0) {
17462 				/* Extend window for zero window probe */
17463 				tcp->tcp_swnd++;
17464 				tcp->tcp_zero_win_probe = B_TRUE;
17465 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinProbe);
17466 			} else {
17467 				/*
17468 				 * Handle timeout from sender SWS avoidance.
17469 				 * Reset our knowledge of the max send window
17470 				 * since the receiver might have reduced its
17471 				 * receive buffer.  Avoid setting tcp_max_swnd
17472 				 * to one since that will essentially disable
17473 				 * the SWS checks.
17474 				 *
17475 				 * Note that since we don't have a SWS
17476 				 * state variable, if the timeout is set
17477 				 * for ECN but not for SWS, this
17478 				 * code will also be executed.  This is
17479 				 * fine as tcp_max_swnd is updated
17480 				 * constantly and it will not affect
17481 				 * anything.
17482 				 */
17483 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
17484 			}
17485 			tcp_wput_data(tcp, NULL, B_FALSE);
17486 			return;
17487 		}
17488 		/* Is there a FIN that needs to be to re retransmitted? */
17489 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17490 		    !tcp->tcp_fin_acked)
17491 			break;
17492 		/* Nothing to do, return without restarting timer. */
17493 		TCP_STAT(tcps, tcp_timer_fire_miss);
17494 		return;
17495 	case TCPS_FIN_WAIT_2:
17496 		/*
17497 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
17498 		 * We waited some time for for peer's FIN, but it hasn't
17499 		 * arrived.  We flush the connection now to avoid
17500 		 * case where the peer has rebooted.
17501 		 */
17502 		if (TCP_IS_DETACHED(tcp)) {
17503 			(void) tcp_clean_death(tcp, 0, 23);
17504 		} else {
17505 			TCP_TIMER_RESTART(tcp,
17506 			    tcps->tcps_fin_wait_2_flush_interval);
17507 		}
17508 		return;
17509 	case TCPS_TIME_WAIT:
17510 		(void) tcp_clean_death(tcp, 0, 24);
17511 		return;
17512 	default:
17513 		if (tcp->tcp_debug) {
17514 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
17515 			    "tcp_timer: strange state (%d) %s",
17516 			    tcp->tcp_state, tcp_display(tcp, NULL,
17517 			    DISP_PORT_ONLY));
17518 		}
17519 		return;
17520 	}
17521 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
17522 		/*
17523 		 * For zero window probe, we need to send indefinitely,
17524 		 * unless we have not heard from the other side for some
17525 		 * time...
17526 		 */
17527 		if ((tcp->tcp_zero_win_probe == 0) ||
17528 		    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >
17529 		    second_threshold)) {
17530 			BUMP_MIB(&tcps->tcps_mib, tcpTimRetransDrop);
17531 			/*
17532 			 * If TCP is in SYN_RCVD state, send back a
17533 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
17534 			 * should be zero in TCPS_SYN_RCVD state.
17535 			 */
17536 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
17537 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
17538 				    "in SYN_RCVD",
17539 				    tcp, tcp->tcp_snxt,
17540 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
17541 			}
17542 			(void) tcp_clean_death(tcp,
17543 			    tcp->tcp_client_errno ?
17544 			    tcp->tcp_client_errno : ETIMEDOUT, 25);
17545 			return;
17546 		} else {
17547 			/*
17548 			 * Set tcp_ms_we_have_waited to second_threshold
17549 			 * so that in next timeout, we will do the above
17550 			 * check (lbolt - tcp_last_recv_time).  This is
17551 			 * also to avoid overflow.
17552 			 *
17553 			 * We don't need to decrement tcp_timer_backoff
17554 			 * to avoid overflow because it will be decremented
17555 			 * later if new timeout value is greater than
17556 			 * tcp_rexmit_interval_max.  In the case when
17557 			 * tcp_rexmit_interval_max is greater than
17558 			 * second_threshold, it means that we will wait
17559 			 * longer than second_threshold to send the next
17560 			 * window probe.
17561 			 */
17562 			tcp->tcp_ms_we_have_waited = second_threshold;
17563 		}
17564 	} else if (ms > first_threshold) {
17565 		if (tcp->tcp_snd_zcopy_aware && (!tcp->tcp_xmit_zc_clean) &&
17566 		    tcp->tcp_xmit_head != NULL) {
17567 			tcp->tcp_xmit_head =
17568 			    tcp_zcopy_backoff(tcp, tcp->tcp_xmit_head, 1);
17569 		}
17570 		/*
17571 		 * We have been retransmitting for too long...  The RTT
17572 		 * we calculated is probably incorrect.  Reinitialize it.
17573 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
17574 		 * tcp_rtt_update so that we won't accidentally cache a
17575 		 * bad value.  But only do this if this is not a zero
17576 		 * window probe.
17577 		 */
17578 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
17579 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
17580 			    (tcp->tcp_rtt_sa >> 5);
17581 			tcp->tcp_rtt_sa = 0;
17582 			tcp_ip_notify(tcp);
17583 			tcp->tcp_rtt_update = 0;
17584 		}
17585 	}
17586 	tcp->tcp_timer_backoff++;
17587 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
17588 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
17589 	    tcps->tcps_rexmit_interval_min) {
17590 		/*
17591 		 * This means the original RTO is tcp_rexmit_interval_min.
17592 		 * So we will use tcp_rexmit_interval_min as the RTO value
17593 		 * and do the backoff.
17594 		 */
17595 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
17596 	} else {
17597 		ms <<= tcp->tcp_timer_backoff;
17598 	}
17599 	if (ms > tcps->tcps_rexmit_interval_max) {
17600 		ms = tcps->tcps_rexmit_interval_max;
17601 		/*
17602 		 * ms is at max, decrement tcp_timer_backoff to avoid
17603 		 * overflow.
17604 		 */
17605 		tcp->tcp_timer_backoff--;
17606 	}
17607 	tcp->tcp_ms_we_have_waited += ms;
17608 	if (tcp->tcp_zero_win_probe == 0) {
17609 		tcp->tcp_rto = ms;
17610 	}
17611 	TCP_TIMER_RESTART(tcp, ms);
17612 	/*
17613 	 * This is after a timeout and tcp_rto is backed off.  Set
17614 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
17615 	 * restart the timer with a correct value.
17616 	 */
17617 	tcp->tcp_set_timer = 1;
17618 	mss = tcp->tcp_snxt - tcp->tcp_suna;
17619 	if (mss > tcp->tcp_mss)
17620 		mss = tcp->tcp_mss;
17621 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
17622 		mss = tcp->tcp_swnd;
17623 
17624 	if ((mp = tcp->tcp_xmit_head) != NULL)
17625 		mp->b_prev = (mblk_t *)lbolt;
17626 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
17627 	    B_TRUE);
17628 
17629 	/*
17630 	 * When slow start after retransmission begins, start with
17631 	 * this seq no.  tcp_rexmit_max marks the end of special slow
17632 	 * start phase.  tcp_snd_burst controls how many segments
17633 	 * can be sent because of an ack.
17634 	 */
17635 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
17636 	tcp->tcp_snd_burst = TCP_CWND_SS;
17637 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
17638 	    (tcp->tcp_unsent == 0)) {
17639 		tcp->tcp_rexmit_max = tcp->tcp_fss;
17640 	} else {
17641 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
17642 	}
17643 	tcp->tcp_rexmit = B_TRUE;
17644 	tcp->tcp_dupack_cnt = 0;
17645 
17646 	/*
17647 	 * Remove all rexmit SACK blk to start from fresh.
17648 	 */
17649 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
17650 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list);
17651 		tcp->tcp_num_notsack_blk = 0;
17652 		tcp->tcp_cnt_notsack_list = 0;
17653 	}
17654 	if (mp == NULL) {
17655 		return;
17656 	}
17657 	/* Attach credentials to retransmitted initial SYNs. */
17658 	if (tcp->tcp_state == TCPS_SYN_SENT) {
17659 		mblk_setcred(mp, tcp->tcp_cred);
17660 		DB_CPID(mp) = tcp->tcp_cpid;
17661 	}
17662 
17663 	tcp->tcp_csuna = tcp->tcp_snxt;
17664 	BUMP_MIB(&tcps->tcps_mib, tcpRetransSegs);
17665 	UPDATE_MIB(&tcps->tcps_mib, tcpRetransBytes, mss);
17666 	tcp_send_data(tcp, tcp->tcp_wq, mp);
17667 
17668 }
17669 
17670 /* tcp_unbind is called by tcp_wput_proto to handle T_UNBIND_REQ messages. */
17671 static void
17672 tcp_unbind(tcp_t *tcp, mblk_t *mp)
17673 {
17674 	conn_t	*connp;
17675 
17676 	switch (tcp->tcp_state) {
17677 	case TCPS_BOUND:
17678 	case TCPS_LISTEN:
17679 		break;
17680 	default:
17681 		tcp_err_ack(tcp, mp, TOUTSTATE, 0);
17682 		return;
17683 	}
17684 
17685 	/*
17686 	 * Need to clean up all the eagers since after the unbind, segments
17687 	 * will no longer be delivered to this listener stream.
17688 	 */
17689 	mutex_enter(&tcp->tcp_eager_lock);
17690 	if (tcp->tcp_conn_req_cnt_q0 != 0 || tcp->tcp_conn_req_cnt_q != 0) {
17691 		tcp_eager_cleanup(tcp, 0);
17692 	}
17693 	mutex_exit(&tcp->tcp_eager_lock);
17694 
17695 	if (tcp->tcp_ipversion == IPV4_VERSION) {
17696 		tcp->tcp_ipha->ipha_src = 0;
17697 	} else {
17698 		V6_SET_ZERO(tcp->tcp_ip6h->ip6_src);
17699 	}
17700 	V6_SET_ZERO(tcp->tcp_ip_src_v6);
17701 	bzero(tcp->tcp_tcph->th_lport, sizeof (tcp->tcp_tcph->th_lport));
17702 	tcp_bind_hash_remove(tcp);
17703 	tcp->tcp_state = TCPS_IDLE;
17704 	tcp->tcp_mdt = B_FALSE;
17705 	/* Send M_FLUSH according to TPI */
17706 	(void) putnextctl1(tcp->tcp_rq, M_FLUSH, FLUSHRW);
17707 	connp = tcp->tcp_connp;
17708 	connp->conn_mdt_ok = B_FALSE;
17709 	ipcl_hash_remove(connp);
17710 	bzero(&connp->conn_ports, sizeof (connp->conn_ports));
17711 	mp = mi_tpi_ok_ack_alloc(mp);
17712 	putnext(tcp->tcp_rq, mp);
17713 }
17714 
17715 /*
17716  * Don't let port fall into the privileged range.
17717  * Since the extra privileged ports can be arbitrary we also
17718  * ensure that we exclude those from consideration.
17719  * tcp_g_epriv_ports is not sorted thus we loop over it until
17720  * there are no changes.
17721  *
17722  * Note: No locks are held when inspecting tcp_g_*epriv_ports
17723  * but instead the code relies on:
17724  * - the fact that the address of the array and its size never changes
17725  * - the atomic assignment of the elements of the array
17726  *
17727  * Returns 0 if there are no more ports available.
17728  *
17729  * TS note: skip multilevel ports.
17730  */
17731 static in_port_t
17732 tcp_update_next_port(in_port_t port, const tcp_t *tcp, boolean_t random)
17733 {
17734 	int i;
17735 	boolean_t restart = B_FALSE;
17736 	tcp_stack_t *tcps = tcp->tcp_tcps;
17737 
17738 	if (random && tcp_random_anon_port != 0) {
17739 		(void) random_get_pseudo_bytes((uint8_t *)&port,
17740 		    sizeof (in_port_t));
17741 		/*
17742 		 * Unless changed by a sys admin, the smallest anon port
17743 		 * is 32768 and the largest anon port is 65535.  It is
17744 		 * very likely (50%) for the random port to be smaller
17745 		 * than the smallest anon port.  When that happens,
17746 		 * add port % (anon port range) to the smallest anon
17747 		 * port to get the random port.  It should fall into the
17748 		 * valid anon port range.
17749 		 */
17750 		if (port < tcps->tcps_smallest_anon_port) {
17751 			port = tcps->tcps_smallest_anon_port +
17752 			    port % (tcps->tcps_largest_anon_port -
17753 			    tcps->tcps_smallest_anon_port);
17754 		}
17755 	}
17756 
17757 retry:
17758 	if (port < tcps->tcps_smallest_anon_port)
17759 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17760 
17761 	if (port > tcps->tcps_largest_anon_port) {
17762 		if (restart)
17763 			return (0);
17764 		restart = B_TRUE;
17765 		port = (in_port_t)tcps->tcps_smallest_anon_port;
17766 	}
17767 
17768 	if (port < tcps->tcps_smallest_nonpriv_port)
17769 		port = (in_port_t)tcps->tcps_smallest_nonpriv_port;
17770 
17771 	for (i = 0; i < tcps->tcps_g_num_epriv_ports; i++) {
17772 		if (port == tcps->tcps_g_epriv_ports[i]) {
17773 			port++;
17774 			/*
17775 			 * Make sure whether the port is in the
17776 			 * valid range.
17777 			 */
17778 			goto retry;
17779 		}
17780 	}
17781 	if (is_system_labeled() &&
17782 	    (i = tsol_next_port(crgetzone(tcp->tcp_cred), port,
17783 	    IPPROTO_TCP, B_TRUE)) != 0) {
17784 		port = i;
17785 		goto retry;
17786 	}
17787 	return (port);
17788 }
17789 
17790 /*
17791  * Return the next anonymous port in the privileged port range for
17792  * bind checking.  It starts at IPPORT_RESERVED - 1 and goes
17793  * downwards.  This is the same behavior as documented in the userland
17794  * library call rresvport(3N).
17795  *
17796  * TS note: skip multilevel ports.
17797  */
17798 static in_port_t
17799 tcp_get_next_priv_port(const tcp_t *tcp)
17800 {
17801 	static in_port_t next_priv_port = IPPORT_RESERVED - 1;
17802 	in_port_t nextport;
17803 	boolean_t restart = B_FALSE;
17804 	tcp_stack_t *tcps = tcp->tcp_tcps;
17805 retry:
17806 	if (next_priv_port < tcps->tcps_min_anonpriv_port ||
17807 	    next_priv_port >= IPPORT_RESERVED) {
17808 		next_priv_port = IPPORT_RESERVED - 1;
17809 		if (restart)
17810 			return (0);
17811 		restart = B_TRUE;
17812 	}
17813 	if (is_system_labeled() &&
17814 	    (nextport = tsol_next_port(crgetzone(tcp->tcp_cred),
17815 	    next_priv_port, IPPROTO_TCP, B_FALSE)) != 0) {
17816 		next_priv_port = nextport;
17817 		goto retry;
17818 	}
17819 	return (next_priv_port--);
17820 }
17821 
17822 /* The write side r/w procedure. */
17823 
17824 #if CCS_STATS
17825 struct {
17826 	struct {
17827 		int64_t count, bytes;
17828 	} tot, hit;
17829 } wrw_stats;
17830 #endif
17831 
17832 /*
17833  * Call by tcp_wput() to handle all non data, except M_PROTO and M_PCPROTO,
17834  * messages.
17835  */
17836 /* ARGSUSED */
17837 static void
17838 tcp_wput_nondata(void *arg, mblk_t *mp, void *arg2)
17839 {
17840 	conn_t	*connp = (conn_t *)arg;
17841 	tcp_t	*tcp = connp->conn_tcp;
17842 	queue_t	*q = tcp->tcp_wq;
17843 
17844 	ASSERT(DB_TYPE(mp) != M_IOCTL);
17845 	/*
17846 	 * TCP is D_MP and qprocsoff() is done towards the end of the tcp_close.
17847 	 * Once the close starts, streamhead and sockfs will not let any data
17848 	 * packets come down (close ensures that there are no threads using the
17849 	 * queue and no new threads will come down) but since qprocsoff()
17850 	 * hasn't happened yet, a M_FLUSH or some non data message might
17851 	 * get reflected back (in response to our own FLUSHRW) and get
17852 	 * processed after tcp_close() is done. The conn would still be valid
17853 	 * because a ref would have added but we need to check the state
17854 	 * before actually processing the packet.
17855 	 */
17856 	if (TCP_IS_DETACHED(tcp) || (tcp->tcp_state == TCPS_CLOSED)) {
17857 		freemsg(mp);
17858 		return;
17859 	}
17860 
17861 	switch (DB_TYPE(mp)) {
17862 	case M_IOCDATA:
17863 		tcp_wput_iocdata(tcp, mp);
17864 		break;
17865 	case M_FLUSH:
17866 		tcp_wput_flush(tcp, mp);
17867 		break;
17868 	default:
17869 		CALL_IP_WPUT(connp, q, mp);
17870 		break;
17871 	}
17872 }
17873 
17874 /*
17875  * The TCP fast path write put procedure.
17876  * NOTE: the logic of the fast path is duplicated from tcp_wput_data()
17877  */
17878 /* ARGSUSED */
17879 void
17880 tcp_output(void *arg, mblk_t *mp, void *arg2)
17881 {
17882 	int		len;
17883 	int		hdrlen;
17884 	int		plen;
17885 	mblk_t		*mp1;
17886 	uchar_t		*rptr;
17887 	uint32_t	snxt;
17888 	tcph_t		*tcph;
17889 	struct datab	*db;
17890 	uint32_t	suna;
17891 	uint32_t	mss;
17892 	ipaddr_t	*dst;
17893 	ipaddr_t	*src;
17894 	uint32_t	sum;
17895 	int		usable;
17896 	conn_t		*connp = (conn_t *)arg;
17897 	tcp_t		*tcp = connp->conn_tcp;
17898 	uint32_t	msize;
17899 	tcp_stack_t	*tcps = tcp->tcp_tcps;
17900 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
17901 
17902 	/*
17903 	 * Try and ASSERT the minimum possible references on the
17904 	 * conn early enough. Since we are executing on write side,
17905 	 * the connection is obviously not detached and that means
17906 	 * there is a ref each for TCP and IP. Since we are behind
17907 	 * the squeue, the minimum references needed are 3. If the
17908 	 * conn is in classifier hash list, there should be an
17909 	 * extra ref for that (we check both the possibilities).
17910 	 */
17911 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
17912 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
17913 
17914 	ASSERT(DB_TYPE(mp) == M_DATA);
17915 	msize = (mp->b_cont == NULL) ? MBLKL(mp) : msgdsize(mp);
17916 
17917 	mutex_enter(&tcp->tcp_non_sq_lock);
17918 	tcp->tcp_squeue_bytes -= msize;
17919 	mutex_exit(&tcp->tcp_non_sq_lock);
17920 
17921 	/* Check to see if this connection wants to be re-fused. */
17922 	if (tcp->tcp_refuse && !ipst->ips_ipobs_enabled) {
17923 		if (tcp->tcp_ipversion == IPV4_VERSION) {
17924 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ipha,
17925 			    &tcp->tcp_saved_tcph);
17926 		} else {
17927 			tcp_fuse(tcp, (uchar_t *)&tcp->tcp_saved_ip6h,
17928 			    &tcp->tcp_saved_tcph);
17929 		}
17930 	}
17931 	/* Bypass tcp protocol for fused tcp loopback */
17932 	if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
17933 		return;
17934 
17935 	mss = tcp->tcp_mss;
17936 	if (tcp->tcp_xmit_zc_clean)
17937 		mp = tcp_zcopy_backoff(tcp, mp, 0);
17938 
17939 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
17940 	len = (int)(mp->b_wptr - mp->b_rptr);
17941 
17942 	/*
17943 	 * Criteria for fast path:
17944 	 *
17945 	 *   1. no unsent data
17946 	 *   2. single mblk in request
17947 	 *   3. connection established
17948 	 *   4. data in mblk
17949 	 *   5. len <= mss
17950 	 *   6. no tcp_valid bits
17951 	 */
17952 	if ((tcp->tcp_unsent != 0) ||
17953 	    (tcp->tcp_cork) ||
17954 	    (mp->b_cont != NULL) ||
17955 	    (tcp->tcp_state != TCPS_ESTABLISHED) ||
17956 	    (len == 0) ||
17957 	    (len > mss) ||
17958 	    (tcp->tcp_valid_bits != 0)) {
17959 		tcp_wput_data(tcp, mp, B_FALSE);
17960 		return;
17961 	}
17962 
17963 	ASSERT(tcp->tcp_xmit_tail_unsent == 0);
17964 	ASSERT(tcp->tcp_fin_sent == 0);
17965 
17966 	/* queue new packet onto retransmission queue */
17967 	if (tcp->tcp_xmit_head == NULL) {
17968 		tcp->tcp_xmit_head = mp;
17969 	} else {
17970 		tcp->tcp_xmit_last->b_cont = mp;
17971 	}
17972 	tcp->tcp_xmit_last = mp;
17973 	tcp->tcp_xmit_tail = mp;
17974 
17975 	/* find out how much we can send */
17976 	/* BEGIN CSTYLED */
17977 	/*
17978 	 *    un-acked           usable
17979 	 *  |--------------|-----------------|
17980 	 *  tcp_suna       tcp_snxt          tcp_suna+tcp_swnd
17981 	 */
17982 	/* END CSTYLED */
17983 
17984 	/* start sending from tcp_snxt */
17985 	snxt = tcp->tcp_snxt;
17986 
17987 	/*
17988 	 * Check to see if this connection has been idled for some
17989 	 * time and no ACK is expected.  If it is, we need to slow
17990 	 * start again to get back the connection's "self-clock" as
17991 	 * described in VJ's paper.
17992 	 *
17993 	 * Refer to the comment in tcp_mss_set() for the calculation
17994 	 * of tcp_cwnd after idle.
17995 	 */
17996 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
17997 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
17998 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
17999 	}
18000 
18001 	usable = tcp->tcp_swnd;		/* tcp window size */
18002 	if (usable > tcp->tcp_cwnd)
18003 		usable = tcp->tcp_cwnd;	/* congestion window smaller */
18004 	usable -= snxt;		/* subtract stuff already sent */
18005 	suna = tcp->tcp_suna;
18006 	usable += suna;
18007 	/* usable can be < 0 if the congestion window is smaller */
18008 	if (len > usable) {
18009 		/* Can't send complete M_DATA in one shot */
18010 		goto slow;
18011 	}
18012 
18013 	mutex_enter(&tcp->tcp_non_sq_lock);
18014 	if (tcp->tcp_flow_stopped &&
18015 	    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
18016 		tcp_clrqfull(tcp);
18017 	}
18018 	mutex_exit(&tcp->tcp_non_sq_lock);
18019 
18020 	/*
18021 	 * determine if anything to send (Nagle).
18022 	 *
18023 	 *   1. len < tcp_mss (i.e. small)
18024 	 *   2. unacknowledged data present
18025 	 *   3. len < nagle limit
18026 	 *   4. last packet sent < nagle limit (previous packet sent)
18027 	 */
18028 	if ((len < mss) && (snxt != suna) &&
18029 	    (len < (int)tcp->tcp_naglim) &&
18030 	    (tcp->tcp_last_sent_len < tcp->tcp_naglim)) {
18031 		/*
18032 		 * This was the first unsent packet and normally
18033 		 * mss < xmit_hiwater so there is no need to worry
18034 		 * about flow control. The next packet will go
18035 		 * through the flow control check in tcp_wput_data().
18036 		 */
18037 		/* leftover work from above */
18038 		tcp->tcp_unsent = len;
18039 		tcp->tcp_xmit_tail_unsent = len;
18040 
18041 		return;
18042 	}
18043 
18044 	/* len <= tcp->tcp_mss && len == unsent so no silly window */
18045 
18046 	if (snxt == suna) {
18047 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
18048 	}
18049 
18050 	/* we have always sent something */
18051 	tcp->tcp_rack_cnt = 0;
18052 
18053 	tcp->tcp_snxt = snxt + len;
18054 	tcp->tcp_rack = tcp->tcp_rnxt;
18055 
18056 	if ((mp1 = dupb(mp)) == 0)
18057 		goto no_memory;
18058 	mp->b_prev = (mblk_t *)(uintptr_t)lbolt;
18059 	mp->b_next = (mblk_t *)(uintptr_t)snxt;
18060 
18061 	/* adjust tcp header information */
18062 	tcph = tcp->tcp_tcph;
18063 	tcph->th_flags[0] = (TH_ACK|TH_PUSH);
18064 
18065 	sum = len + tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
18066 	sum = (sum >> 16) + (sum & 0xFFFF);
18067 	U16_TO_ABE16(sum, tcph->th_sum);
18068 
18069 	U32_TO_ABE32(snxt, tcph->th_seq);
18070 
18071 	BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
18072 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
18073 	BUMP_LOCAL(tcp->tcp_obsegs);
18074 
18075 	/* Update the latest receive window size in TCP header. */
18076 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
18077 	    tcph->th_win);
18078 
18079 	tcp->tcp_last_sent_len = (ushort_t)len;
18080 
18081 	plen = len + tcp->tcp_hdr_len;
18082 
18083 	if (tcp->tcp_ipversion == IPV4_VERSION) {
18084 		tcp->tcp_ipha->ipha_length = htons(plen);
18085 	} else {
18086 		tcp->tcp_ip6h->ip6_plen = htons(plen -
18087 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
18088 	}
18089 
18090 	/* see if we need to allocate a mblk for the headers */
18091 	hdrlen = tcp->tcp_hdr_len;
18092 	rptr = mp1->b_rptr - hdrlen;
18093 	db = mp1->b_datap;
18094 	if ((db->db_ref != 2) || rptr < db->db_base ||
18095 	    (!OK_32PTR(rptr))) {
18096 		/* NOTE: we assume allocb returns an OK_32PTR */
18097 		mp = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
18098 		    tcps->tcps_wroff_xtra, BPRI_MED);
18099 		if (!mp) {
18100 			freemsg(mp1);
18101 			goto no_memory;
18102 		}
18103 		mp->b_cont = mp1;
18104 		mp1 = mp;
18105 		/* Leave room for Link Level header */
18106 		/* hdrlen = tcp->tcp_hdr_len; */
18107 		rptr = &mp1->b_rptr[tcps->tcps_wroff_xtra];
18108 		mp1->b_wptr = &rptr[hdrlen];
18109 	}
18110 	mp1->b_rptr = rptr;
18111 
18112 	/* Fill in the timestamp option. */
18113 	if (tcp->tcp_snd_ts_ok) {
18114 		U32_TO_BE32((uint32_t)lbolt,
18115 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
18116 		U32_TO_BE32(tcp->tcp_ts_recent,
18117 		    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
18118 	} else {
18119 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
18120 	}
18121 
18122 	/* copy header into outgoing packet */
18123 	dst = (ipaddr_t *)rptr;
18124 	src = (ipaddr_t *)tcp->tcp_iphc;
18125 	dst[0] = src[0];
18126 	dst[1] = src[1];
18127 	dst[2] = src[2];
18128 	dst[3] = src[3];
18129 	dst[4] = src[4];
18130 	dst[5] = src[5];
18131 	dst[6] = src[6];
18132 	dst[7] = src[7];
18133 	dst[8] = src[8];
18134 	dst[9] = src[9];
18135 	if (hdrlen -= 40) {
18136 		hdrlen >>= 2;
18137 		dst += 10;
18138 		src += 10;
18139 		do {
18140 			*dst++ = *src++;
18141 		} while (--hdrlen);
18142 	}
18143 
18144 	/*
18145 	 * Set the ECN info in the TCP header.  Note that this
18146 	 * is not the template header.
18147 	 */
18148 	if (tcp->tcp_ecn_ok) {
18149 		SET_ECT(tcp, rptr);
18150 
18151 		tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
18152 		if (tcp->tcp_ecn_echo_on)
18153 			tcph->th_flags[0] |= TH_ECE;
18154 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
18155 			tcph->th_flags[0] |= TH_CWR;
18156 			tcp->tcp_ecn_cwr_sent = B_TRUE;
18157 		}
18158 	}
18159 
18160 	if (tcp->tcp_ip_forward_progress) {
18161 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
18162 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
18163 		tcp->tcp_ip_forward_progress = B_FALSE;
18164 	}
18165 	tcp_send_data(tcp, tcp->tcp_wq, mp1);
18166 	return;
18167 
18168 	/*
18169 	 * If we ran out of memory, we pretend to have sent the packet
18170 	 * and that it was lost on the wire.
18171 	 */
18172 no_memory:
18173 	return;
18174 
18175 slow:
18176 	/* leftover work from above */
18177 	tcp->tcp_unsent = len;
18178 	tcp->tcp_xmit_tail_unsent = len;
18179 	tcp_wput_data(tcp, NULL, B_FALSE);
18180 }
18181 
18182 /*
18183  * The function called through squeue to get behind eager's perimeter to
18184  * finish the accept processing.
18185  */
18186 /* ARGSUSED */
18187 void
18188 tcp_accept_finish(void *arg, mblk_t *mp, void *arg2)
18189 {
18190 	conn_t			*connp = (conn_t *)arg;
18191 	tcp_t			*tcp = connp->conn_tcp;
18192 	queue_t			*q = tcp->tcp_rq;
18193 	mblk_t			*mp1;
18194 	mblk_t			*stropt_mp = mp;
18195 	struct  stroptions	*stropt;
18196 	uint_t			thwin;
18197 	tcp_stack_t	*tcps = tcp->tcp_tcps;
18198 
18199 	/*
18200 	 * Drop the eager's ref on the listener, that was placed when
18201 	 * this eager began life in tcp_conn_request.
18202 	 */
18203 	CONN_DEC_REF(tcp->tcp_saved_listener->tcp_connp);
18204 
18205 	tcp->tcp_detached = B_FALSE;
18206 
18207 	if (tcp->tcp_state <= TCPS_BOUND || tcp->tcp_accept_error) {
18208 		/*
18209 		 * Someone blewoff the eager before we could finish
18210 		 * the accept.
18211 		 *
18212 		 * The only reason eager exists it because we put in
18213 		 * a ref on it when conn ind went up. We need to send
18214 		 * a disconnect indication up while the last reference
18215 		 * on the eager will be dropped by the squeue when we
18216 		 * return.
18217 		 */
18218 		ASSERT(tcp->tcp_listener == NULL);
18219 		if (tcp->tcp_issocket || tcp->tcp_send_discon_ind) {
18220 			struct	T_discon_ind	*tdi;
18221 
18222 			(void) putnextctl1(q, M_FLUSH, FLUSHRW);
18223 			/*
18224 			 * Let us reuse the incoming mblk to avoid memory
18225 			 * allocation failure problems. We know that the
18226 			 * size of the incoming mblk i.e. stroptions is greater
18227 			 * than sizeof T_discon_ind. So the reallocb below
18228 			 * can't fail.
18229 			 */
18230 			freemsg(mp->b_cont);
18231 			mp->b_cont = NULL;
18232 			ASSERT(DB_REF(mp) == 1);
18233 			mp = reallocb(mp, sizeof (struct T_discon_ind),
18234 			    B_FALSE);
18235 			ASSERT(mp != NULL);
18236 			DB_TYPE(mp) = M_PROTO;
18237 			((union T_primitives *)mp->b_rptr)->type = T_DISCON_IND;
18238 			tdi = (struct T_discon_ind *)mp->b_rptr;
18239 			if (tcp->tcp_issocket) {
18240 				tdi->DISCON_reason = ECONNREFUSED;
18241 				tdi->SEQ_number = 0;
18242 			} else {
18243 				tdi->DISCON_reason = ENOPROTOOPT;
18244 				tdi->SEQ_number =
18245 				    tcp->tcp_conn_req_seqnum;
18246 			}
18247 			mp->b_wptr = mp->b_rptr + sizeof (struct T_discon_ind);
18248 			putnext(q, mp);
18249 		} else {
18250 			freemsg(mp);
18251 		}
18252 		if (tcp->tcp_hard_binding) {
18253 			tcp->tcp_hard_binding = B_FALSE;
18254 			tcp->tcp_hard_bound = B_TRUE;
18255 		}
18256 		return;
18257 	}
18258 
18259 	mp1 = stropt_mp->b_cont;
18260 	stropt_mp->b_cont = NULL;
18261 	ASSERT(DB_TYPE(stropt_mp) == M_SETOPTS);
18262 	stropt = (struct stroptions *)stropt_mp->b_rptr;
18263 
18264 	while (mp1 != NULL) {
18265 		mp = mp1;
18266 		mp1 = mp1->b_cont;
18267 		mp->b_cont = NULL;
18268 		tcp->tcp_drop_opt_ack_cnt++;
18269 		CALL_IP_WPUT(connp, tcp->tcp_wq, mp);
18270 	}
18271 	mp = NULL;
18272 
18273 	/*
18274 	 * For a loopback connection with tcp_direct_sockfs on, note that
18275 	 * we don't have to protect tcp_rcv_list yet because synchronous
18276 	 * streams has not yet been enabled and tcp_fuse_rrw() cannot
18277 	 * possibly race with us.
18278 	 */
18279 
18280 	/*
18281 	 * Set the max window size (tcp_rq->q_hiwat) of the acceptor
18282 	 * properly.  This is the first time we know of the acceptor'
18283 	 * queue.  So we do it here.
18284 	 */
18285 	if (tcp->tcp_rcv_list == NULL) {
18286 		/*
18287 		 * Recv queue is empty, tcp_rwnd should not have changed.
18288 		 * That means it should be equal to the listener's tcp_rwnd.
18289 		 */
18290 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd;
18291 	} else {
18292 #ifdef DEBUG
18293 		uint_t cnt = 0;
18294 
18295 		mp1 = tcp->tcp_rcv_list;
18296 		while ((mp = mp1) != NULL) {
18297 			mp1 = mp->b_next;
18298 			cnt += msgdsize(mp);
18299 		}
18300 		ASSERT(cnt != 0 && tcp->tcp_rcv_cnt == cnt);
18301 #endif
18302 		/* There is some data, add them back to get the max. */
18303 		tcp->tcp_rq->q_hiwat = tcp->tcp_rwnd + tcp->tcp_rcv_cnt;
18304 	}
18305 	/*
18306 	 * This is the first time we run on the correct
18307 	 * queue after tcp_accept. So fix all the q parameters
18308 	 * here.
18309 	 */
18310 	stropt->so_flags = SO_HIWAT | SO_MAXBLK | SO_WROFF;
18311 	stropt->so_maxblk = tcp_maxpsz_set(tcp, B_FALSE);
18312 
18313 	/*
18314 	 * Record the stream head's high water mark for this endpoint;
18315 	 * this is used for flow-control purposes.
18316 	 */
18317 	stropt->so_hiwat = tcp->tcp_fused ?
18318 	    tcp_fuse_set_rcv_hiwat(tcp, q->q_hiwat) :
18319 	    MAX(q->q_hiwat, tcps->tcps_sth_rcv_hiwat);
18320 
18321 	/*
18322 	 * Determine what write offset value to use depending on SACK and
18323 	 * whether the endpoint is fused or not.
18324 	 */
18325 	if (tcp->tcp_fused) {
18326 		ASSERT(tcp->tcp_loopback);
18327 		ASSERT(tcp->tcp_loopback_peer != NULL);
18328 		/*
18329 		 * For fused tcp loopback, set the stream head's write
18330 		 * offset value to zero since we won't be needing any room
18331 		 * for TCP/IP headers.  This would also improve performance
18332 		 * since it would reduce the amount of work done by kmem.
18333 		 * Non-fused tcp loopback case is handled separately below.
18334 		 */
18335 		stropt->so_wroff = 0;
18336 		/*
18337 		 * Update the peer's transmit parameters according to
18338 		 * our recently calculated high water mark value.
18339 		 */
18340 		(void) tcp_maxpsz_set(tcp->tcp_loopback_peer, B_TRUE);
18341 	} else if (tcp->tcp_snd_sack_ok) {
18342 		stropt->so_wroff = tcp->tcp_hdr_len + TCPOPT_MAX_SACK_LEN +
18343 		    (tcp->tcp_loopback ? 0 : tcps->tcps_wroff_xtra);
18344 	} else {
18345 		stropt->so_wroff = tcp->tcp_hdr_len + (tcp->tcp_loopback ? 0 :
18346 		    tcps->tcps_wroff_xtra);
18347 	}
18348 
18349 	/*
18350 	 * If this is endpoint is handling SSL, then reserve extra
18351 	 * offset and space at the end.
18352 	 * Also have the stream head allocate SSL3_MAX_RECORD_LEN packets,
18353 	 * overriding the previous setting. The extra cost of signing and
18354 	 * encrypting multiple MSS-size records (12 of them with Ethernet),
18355 	 * instead of a single contiguous one by the stream head
18356 	 * largely outweighs the statistical reduction of ACKs, when
18357 	 * applicable. The peer will also save on decryption and verification
18358 	 * costs.
18359 	 */
18360 	if (tcp->tcp_kssl_ctx != NULL) {
18361 		stropt->so_wroff += SSL3_WROFFSET;
18362 
18363 		stropt->so_flags |= SO_TAIL;
18364 		stropt->so_tail = SSL3_MAX_TAIL_LEN;
18365 
18366 		stropt->so_flags |= SO_COPYOPT;
18367 		stropt->so_copyopt = ZCVMUNSAFE;
18368 
18369 		stropt->so_maxblk = SSL3_MAX_RECORD_LEN;
18370 	}
18371 
18372 	/* Send the options up */
18373 	putnext(q, stropt_mp);
18374 
18375 	/*
18376 	 * Pass up any data and/or a fin that has been received.
18377 	 *
18378 	 * Adjust receive window in case it had decreased
18379 	 * (because there is data <=> tcp_rcv_list != NULL)
18380 	 * while the connection was detached. Note that
18381 	 * in case the eager was flow-controlled, w/o this
18382 	 * code, the rwnd may never open up again!
18383 	 */
18384 	if (tcp->tcp_rcv_list != NULL) {
18385 		/* We drain directly in case of fused tcp loopback */
18386 		sodirect_t *sodp;
18387 
18388 		if (!tcp->tcp_fused && canputnext(q)) {
18389 			tcp->tcp_rwnd = q->q_hiwat;
18390 			thwin = ((uint_t)BE16_TO_U16(tcp->tcp_tcph->th_win))
18391 			    << tcp->tcp_rcv_ws;
18392 			thwin -= tcp->tcp_rnxt - tcp->tcp_rack;
18393 			if (tcp->tcp_state >= TCPS_ESTABLISHED &&
18394 			    (q->q_hiwat - thwin >= tcp->tcp_mss)) {
18395 				tcp_xmit_ctl(NULL,
18396 				    tcp, (tcp->tcp_swnd == 0) ?
18397 				    tcp->tcp_suna : tcp->tcp_snxt,
18398 				    tcp->tcp_rnxt, TH_ACK);
18399 				BUMP_MIB(&tcps->tcps_mib, tcpOutWinUpdate);
18400 			}
18401 
18402 		}
18403 
18404 		SOD_PTR_ENTER(tcp, sodp);
18405 		if (sodp != NULL) {
18406 			/* Sodirect, move from rcv_list */
18407 			ASSERT(!tcp->tcp_fused);
18408 			while ((mp = tcp->tcp_rcv_list) != NULL) {
18409 				tcp->tcp_rcv_list = mp->b_next;
18410 				mp->b_next = NULL;
18411 				(void) tcp_rcv_sod_enqueue(tcp, sodp, mp,
18412 				    msgdsize(mp));
18413 			}
18414 			tcp->tcp_rcv_last_head = NULL;
18415 			tcp->tcp_rcv_last_tail = NULL;
18416 			tcp->tcp_rcv_cnt = 0;
18417 			(void) tcp_rcv_sod_wakeup(tcp, sodp);
18418 			/* sod_wakeup() did the mutex_exit() */
18419 		} else {
18420 			/* Not sodirect, drain */
18421 			(void) tcp_rcv_drain(q, tcp);
18422 		}
18423 
18424 		/*
18425 		 * For fused tcp loopback, back-enable peer endpoint
18426 		 * if it's currently flow-controlled.
18427 		 */
18428 		if (tcp->tcp_fused) {
18429 			tcp_t *peer_tcp = tcp->tcp_loopback_peer;
18430 
18431 			ASSERT(peer_tcp != NULL);
18432 			ASSERT(peer_tcp->tcp_fused);
18433 			/*
18434 			 * In order to change the peer's tcp_flow_stopped,
18435 			 * we need to take locks for both end points. The
18436 			 * highest address is taken first.
18437 			 */
18438 			if (peer_tcp > tcp) {
18439 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18440 				mutex_enter(&tcp->tcp_non_sq_lock);
18441 			} else {
18442 				mutex_enter(&tcp->tcp_non_sq_lock);
18443 				mutex_enter(&peer_tcp->tcp_non_sq_lock);
18444 			}
18445 			if (peer_tcp->tcp_flow_stopped) {
18446 				tcp_clrqfull(peer_tcp);
18447 				TCP_STAT(tcps, tcp_fusion_backenabled);
18448 			}
18449 			mutex_exit(&peer_tcp->tcp_non_sq_lock);
18450 			mutex_exit(&tcp->tcp_non_sq_lock);
18451 		}
18452 	}
18453 	ASSERT(tcp->tcp_rcv_list == NULL || tcp->tcp_fused_sigurg);
18454 	if (tcp->tcp_fin_rcvd && !tcp->tcp_ordrel_done) {
18455 		mp = tcp->tcp_ordrel_mp;
18456 		tcp->tcp_ordrel_mp = NULL;
18457 		tcp->tcp_ordrel_done = B_TRUE;
18458 		putnext(q, mp);
18459 	}
18460 	if (tcp->tcp_hard_binding) {
18461 		tcp->tcp_hard_binding = B_FALSE;
18462 		tcp->tcp_hard_bound = B_TRUE;
18463 	}
18464 
18465 	/* We can enable synchronous streams now */
18466 	if (tcp->tcp_fused) {
18467 		tcp_fuse_syncstr_enable_pair(tcp);
18468 	}
18469 
18470 	if (tcp->tcp_ka_enabled) {
18471 		tcp->tcp_ka_last_intrvl = 0;
18472 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_killer,
18473 		    MSEC_TO_TICK(tcp->tcp_ka_interval));
18474 	}
18475 
18476 	/*
18477 	 * At this point, eager is fully established and will
18478 	 * have the following references -
18479 	 *
18480 	 * 2 references for connection to exist (1 for TCP and 1 for IP).
18481 	 * 1 reference for the squeue which will be dropped by the squeue as
18482 	 *	soon as this function returns.
18483 	 * There will be 1 additonal reference for being in classifier
18484 	 *	hash list provided something bad hasn't happened.
18485 	 */
18486 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
18487 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
18488 }
18489 
18490 /*
18491  * The function called through squeue to get behind listener's perimeter to
18492  * send a deffered conn_ind.
18493  */
18494 /* ARGSUSED */
18495 void
18496 tcp_send_pending(void *arg, mblk_t *mp, void *arg2)
18497 {
18498 	conn_t	*connp = (conn_t *)arg;
18499 	tcp_t *listener = connp->conn_tcp;
18500 
18501 	if (listener->tcp_state == TCPS_CLOSED ||
18502 	    TCP_IS_DETACHED(listener)) {
18503 		/*
18504 		 * If listener has closed, it would have caused a
18505 		 * a cleanup/blowoff to happen for the eager.
18506 		 */
18507 		tcp_t *tcp;
18508 		struct T_conn_ind	*conn_ind;
18509 
18510 		conn_ind = (struct T_conn_ind *)mp->b_rptr;
18511 		bcopy(mp->b_rptr + conn_ind->OPT_offset, &tcp,
18512 		    conn_ind->OPT_length);
18513 		/*
18514 		 * We need to drop the ref on eager that was put
18515 		 * tcp_rput_data() before trying to send the conn_ind
18516 		 * to listener. The conn_ind was deferred in tcp_send_conn_ind
18517 		 * and tcp_wput_accept() is sending this deferred conn_ind but
18518 		 * listener is closed so we drop the ref.
18519 		 */
18520 		CONN_DEC_REF(tcp->tcp_connp);
18521 		freemsg(mp);
18522 		return;
18523 	}
18524 	putnext(listener->tcp_rq, mp);
18525 }
18526 
18527 
18528 /*
18529  * This is the STREAMS entry point for T_CONN_RES coming down on
18530  * Acceptor STREAM when  sockfs listener does accept processing.
18531  * Read the block comment on top of tcp_conn_request().
18532  */
18533 void
18534 tcp_wput_accept(queue_t *q, mblk_t *mp)
18535 {
18536 	queue_t *rq = RD(q);
18537 	struct T_conn_res *conn_res;
18538 	tcp_t *eager;
18539 	tcp_t *listener;
18540 	struct T_ok_ack *ok;
18541 	t_scalar_t PRIM_type;
18542 	mblk_t *opt_mp;
18543 	conn_t *econnp;
18544 
18545 	ASSERT(DB_TYPE(mp) == M_PROTO);
18546 
18547 	conn_res = (struct T_conn_res *)mp->b_rptr;
18548 	ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <= (uintptr_t)INT_MAX);
18549 	if ((mp->b_wptr - mp->b_rptr) < sizeof (struct T_conn_res)) {
18550 		mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18551 		if (mp != NULL)
18552 			putnext(rq, mp);
18553 		return;
18554 	}
18555 	switch (conn_res->PRIM_type) {
18556 	case O_T_CONN_RES:
18557 	case T_CONN_RES:
18558 		/*
18559 		 * We pass up an err ack if allocb fails. This will
18560 		 * cause sockfs to issue a T_DISCON_REQ which will cause
18561 		 * tcp_eager_blowoff to be called. sockfs will then call
18562 		 * rq->q_qinfo->qi_qclose to cleanup the acceptor stream.
18563 		 * we need to do the allocb up here because we have to
18564 		 * make sure rq->q_qinfo->qi_qclose still points to the
18565 		 * correct function (tcpclose_accept) in case allocb
18566 		 * fails.
18567 		 */
18568 		opt_mp = allocb(sizeof (struct stroptions), BPRI_HI);
18569 		if (opt_mp == NULL) {
18570 			mp = mi_tpi_err_ack_alloc(mp, TPROTO, 0);
18571 			if (mp != NULL)
18572 				putnext(rq, mp);
18573 			return;
18574 		}
18575 
18576 		bcopy(mp->b_rptr + conn_res->OPT_offset,
18577 		    &eager, conn_res->OPT_length);
18578 		PRIM_type = conn_res->PRIM_type;
18579 		mp->b_datap->db_type = M_PCPROTO;
18580 		mp->b_wptr = mp->b_rptr + sizeof (struct T_ok_ack);
18581 		ok = (struct T_ok_ack *)mp->b_rptr;
18582 		ok->PRIM_type = T_OK_ACK;
18583 		ok->CORRECT_prim = PRIM_type;
18584 		econnp = eager->tcp_connp;
18585 		econnp->conn_dev = (dev_t)RD(q)->q_ptr;
18586 		econnp->conn_minor_arena = (vmem_t *)(WR(q)->q_ptr);
18587 		eager->tcp_rq = rq;
18588 		eager->tcp_wq = q;
18589 		rq->q_ptr = econnp;
18590 		rq->q_qinfo = &tcp_rinitv4;	/* No open - same as rinitv6 */
18591 		q->q_ptr = econnp;
18592 		q->q_qinfo = &tcp_winit;
18593 		listener = eager->tcp_listener;
18594 		eager->tcp_issocket = B_TRUE;
18595 
18596 		/*
18597 		 * TCP is _D_SODIRECT and sockfs is directly above so
18598 		 * save shared sodirect_t pointer (if any).
18599 		 *
18600 		 * If tcp_fused and sodirect enabled disable it.
18601 		 */
18602 		eager->tcp_sodirect = SOD_QTOSODP(eager->tcp_rq);
18603 		if (eager->tcp_fused && eager->tcp_sodirect != NULL) {
18604 			/* Fused, disable sodirect */
18605 			mutex_enter(eager->tcp_sodirect->sod_lockp);
18606 			SOD_DISABLE(eager->tcp_sodirect);
18607 			mutex_exit(eager->tcp_sodirect->sod_lockp);
18608 			eager->tcp_sodirect = NULL;
18609 		}
18610 
18611 		econnp->conn_zoneid = listener->tcp_connp->conn_zoneid;
18612 		econnp->conn_allzones = listener->tcp_connp->conn_allzones;
18613 		ASSERT(econnp->conn_netstack ==
18614 		    listener->tcp_connp->conn_netstack);
18615 		ASSERT(eager->tcp_tcps == listener->tcp_tcps);
18616 
18617 		/* Put the ref for IP */
18618 		CONN_INC_REF(econnp);
18619 
18620 		/*
18621 		 * We should have minimum of 3 references on the conn
18622 		 * at this point. One each for TCP and IP and one for
18623 		 * the T_conn_ind that was sent up when the 3-way handshake
18624 		 * completed. In the normal case we would also have another
18625 		 * reference (making a total of 4) for the conn being in the
18626 		 * classifier hash list. However the eager could have received
18627 		 * an RST subsequently and tcp_closei_local could have removed
18628 		 * the eager from the classifier hash list, hence we can't
18629 		 * assert that reference.
18630 		 */
18631 		ASSERT(econnp->conn_ref >= 3);
18632 
18633 		/*
18634 		 * Send the new local address also up to sockfs. There
18635 		 * should already be enough space in the mp that came
18636 		 * down from soaccept().
18637 		 */
18638 		if (eager->tcp_family == AF_INET) {
18639 			sin_t *sin;
18640 
18641 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18642 			    (sizeof (struct T_ok_ack) + sizeof (sin_t)));
18643 			sin = (sin_t *)mp->b_wptr;
18644 			mp->b_wptr += sizeof (sin_t);
18645 			sin->sin_family = AF_INET;
18646 			sin->sin_port = eager->tcp_lport;
18647 			sin->sin_addr.s_addr = eager->tcp_ipha->ipha_src;
18648 		} else {
18649 			sin6_t *sin6;
18650 
18651 			ASSERT((mp->b_datap->db_lim - mp->b_datap->db_base) >=
18652 			    sizeof (struct T_ok_ack) + sizeof (sin6_t));
18653 			sin6 = (sin6_t *)mp->b_wptr;
18654 			mp->b_wptr += sizeof (sin6_t);
18655 			sin6->sin6_family = AF_INET6;
18656 			sin6->sin6_port = eager->tcp_lport;
18657 			if (eager->tcp_ipversion == IPV4_VERSION) {
18658 				sin6->sin6_flowinfo = 0;
18659 				IN6_IPADDR_TO_V4MAPPED(
18660 				    eager->tcp_ipha->ipha_src,
18661 				    &sin6->sin6_addr);
18662 			} else {
18663 				ASSERT(eager->tcp_ip6h != NULL);
18664 				sin6->sin6_flowinfo =
18665 				    eager->tcp_ip6h->ip6_vcf &
18666 				    ~IPV6_VERS_AND_FLOW_MASK;
18667 				sin6->sin6_addr = eager->tcp_ip6h->ip6_src;
18668 			}
18669 			sin6->sin6_scope_id = 0;
18670 			sin6->__sin6_src_id = 0;
18671 		}
18672 
18673 		putnext(rq, mp);
18674 
18675 		opt_mp->b_datap->db_type = M_SETOPTS;
18676 		opt_mp->b_wptr += sizeof (struct stroptions);
18677 
18678 		/*
18679 		 * Prepare for inheriting IPV6_BOUND_IF and IPV6_RECVPKTINFO
18680 		 * from listener to acceptor. The message is chained on the
18681 		 * bind_mp which tcp_rput_other will send down to IP.
18682 		 */
18683 		if (listener->tcp_bound_if != 0) {
18684 			/* allocate optmgmt req */
18685 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18686 			    IPV6_BOUND_IF, (char *)&listener->tcp_bound_if,
18687 			    sizeof (int));
18688 			if (mp != NULL)
18689 				linkb(opt_mp, mp);
18690 		}
18691 		if (listener->tcp_ipv6_recvancillary & TCP_IPV6_RECVPKTINFO) {
18692 			uint_t on = 1;
18693 
18694 			/* allocate optmgmt req */
18695 			mp = tcp_setsockopt_mp(IPPROTO_IPV6,
18696 			    IPV6_RECVPKTINFO, (char *)&on, sizeof (on));
18697 			if (mp != NULL)
18698 				linkb(opt_mp, mp);
18699 		}
18700 
18701 
18702 		mutex_enter(&listener->tcp_eager_lock);
18703 
18704 		if (listener->tcp_eager_prev_q0->tcp_conn_def_q0) {
18705 
18706 			tcp_t *tail;
18707 			tcp_t *tcp;
18708 			mblk_t *mp1;
18709 
18710 			tcp = listener->tcp_eager_prev_q0;
18711 			/*
18712 			 * listener->tcp_eager_prev_q0 points to the TAIL of the
18713 			 * deferred T_conn_ind queue. We need to get to the head
18714 			 * of the queue in order to send up T_conn_ind the same
18715 			 * order as how the 3WHS is completed.
18716 			 */
18717 			while (tcp != listener) {
18718 				if (!tcp->tcp_eager_prev_q0->tcp_conn_def_q0 &&
18719 				    !tcp->tcp_kssl_pending)
18720 					break;
18721 				else
18722 					tcp = tcp->tcp_eager_prev_q0;
18723 			}
18724 			/* None of the pending eagers can be sent up now */
18725 			if (tcp == listener)
18726 				goto no_more_eagers;
18727 
18728 			mp1 = tcp->tcp_conn.tcp_eager_conn_ind;
18729 			tcp->tcp_conn.tcp_eager_conn_ind = NULL;
18730 			/* Move from q0 to q */
18731 			ASSERT(listener->tcp_conn_req_cnt_q0 > 0);
18732 			listener->tcp_conn_req_cnt_q0--;
18733 			listener->tcp_conn_req_cnt_q++;
18734 			tcp->tcp_eager_next_q0->tcp_eager_prev_q0 =
18735 			    tcp->tcp_eager_prev_q0;
18736 			tcp->tcp_eager_prev_q0->tcp_eager_next_q0 =
18737 			    tcp->tcp_eager_next_q0;
18738 			tcp->tcp_eager_prev_q0 = NULL;
18739 			tcp->tcp_eager_next_q0 = NULL;
18740 			tcp->tcp_conn_def_q0 = B_FALSE;
18741 
18742 			/* Make sure the tcp isn't in the list of droppables */
18743 			ASSERT(tcp->tcp_eager_next_drop_q0 == NULL &&
18744 			    tcp->tcp_eager_prev_drop_q0 == NULL);
18745 
18746 			/*
18747 			 * Insert at end of the queue because sockfs sends
18748 			 * down T_CONN_RES in chronological order. Leaving
18749 			 * the older conn indications at front of the queue
18750 			 * helps reducing search time.
18751 			 */
18752 			tail = listener->tcp_eager_last_q;
18753 			if (tail != NULL) {
18754 				tail->tcp_eager_next_q = tcp;
18755 			} else {
18756 				listener->tcp_eager_next_q = tcp;
18757 			}
18758 			listener->tcp_eager_last_q = tcp;
18759 			tcp->tcp_eager_next_q = NULL;
18760 
18761 			/* Need to get inside the listener perimeter */
18762 			CONN_INC_REF(listener->tcp_connp);
18763 			squeue_fill(listener->tcp_connp->conn_sqp, mp1,
18764 			    tcp_send_pending, listener->tcp_connp,
18765 			    SQTAG_TCP_SEND_PENDING);
18766 		}
18767 no_more_eagers:
18768 		tcp_eager_unlink(eager);
18769 		mutex_exit(&listener->tcp_eager_lock);
18770 
18771 		/*
18772 		 * At this point, the eager is detached from the listener
18773 		 * but we still have an extra refs on eager (apart from the
18774 		 * usual tcp references). The ref was placed in tcp_rput_data
18775 		 * before sending the conn_ind in tcp_send_conn_ind.
18776 		 * The ref will be dropped in tcp_accept_finish().
18777 		 */
18778 		squeue_enter_nodrain(econnp->conn_sqp, opt_mp,
18779 		    tcp_accept_finish, econnp, SQTAG_TCP_ACCEPT_FINISH_Q0);
18780 		return;
18781 	default:
18782 		mp = mi_tpi_err_ack_alloc(mp, TNOTSUPPORT, 0);
18783 		if (mp != NULL)
18784 			putnext(rq, mp);
18785 		return;
18786 	}
18787 }
18788 
18789 static int
18790 tcp_getmyname(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18791 {
18792 	sin_t *sin = (sin_t *)sa;
18793 	sin6_t *sin6 = (sin6_t *)sa;
18794 
18795 	switch (tcp->tcp_family) {
18796 	case AF_INET:
18797 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18798 
18799 		if (*salenp < sizeof (sin_t))
18800 			return (EINVAL);
18801 
18802 		*sin = sin_null;
18803 		sin->sin_family = AF_INET;
18804 		sin->sin_port = tcp->tcp_lport;
18805 		sin->sin_addr.s_addr = tcp->tcp_ipha->ipha_src;
18806 		break;
18807 
18808 	case AF_INET6:
18809 		if (*salenp < sizeof (sin6_t))
18810 			return (EINVAL);
18811 
18812 		*sin6 = sin6_null;
18813 		sin6->sin6_family = AF_INET6;
18814 		sin6->sin6_port = tcp->tcp_lport;
18815 		if (tcp->tcp_ipversion == IPV4_VERSION) {
18816 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
18817 			    &sin6->sin6_addr);
18818 		} else {
18819 			sin6->sin6_addr = tcp->tcp_ip6h->ip6_src;
18820 		}
18821 		break;
18822 	}
18823 
18824 	return (0);
18825 }
18826 
18827 static int
18828 tcp_getpeername(tcp_t *tcp, struct sockaddr *sa, uint_t *salenp)
18829 {
18830 	sin_t *sin = (sin_t *)sa;
18831 	sin6_t *sin6 = (sin6_t *)sa;
18832 
18833 	if (tcp->tcp_state < TCPS_SYN_RCVD)
18834 		return (ENOTCONN);
18835 
18836 	switch (tcp->tcp_family) {
18837 	case AF_INET:
18838 		ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
18839 
18840 		if (*salenp < sizeof (sin_t))
18841 			return (EINVAL);
18842 
18843 		*sin = sin_null;
18844 		sin->sin_family = AF_INET;
18845 		sin->sin_port = tcp->tcp_fport;
18846 		IN6_V4MAPPED_TO_IPADDR(&tcp->tcp_remote_v6,
18847 		    sin->sin_addr.s_addr);
18848 		break;
18849 
18850 	case AF_INET6:
18851 		if (*salenp < sizeof (sin6_t))
18852 			return (EINVAL);
18853 
18854 		*sin6 = sin6_null;
18855 		sin6->sin6_family = AF_INET6;
18856 		sin6->sin6_port = tcp->tcp_fport;
18857 		sin6->sin6_addr = tcp->tcp_remote_v6;
18858 		if (tcp->tcp_ipversion == IPV6_VERSION) {
18859 			sin6->sin6_flowinfo = tcp->tcp_ip6h->ip6_vcf &
18860 			    ~IPV6_VERS_AND_FLOW_MASK;
18861 		}
18862 		break;
18863 	}
18864 
18865 	return (0);
18866 }
18867 
18868 /*
18869  * Handle special out-of-band ioctl requests (see PSARC/2008/265).
18870  */
18871 static void
18872 tcp_wput_cmdblk(queue_t *q, mblk_t *mp)
18873 {
18874 	void	*data;
18875 	mblk_t	*datamp = mp->b_cont;
18876 	tcp_t	*tcp = Q_TO_TCP(q);
18877 	cmdblk_t *cmdp = (cmdblk_t *)mp->b_rptr;
18878 
18879 	if (datamp == NULL || MBLKL(datamp) < cmdp->cb_len) {
18880 		cmdp->cb_error = EPROTO;
18881 		qreply(q, mp);
18882 		return;
18883 	}
18884 
18885 	data = datamp->b_rptr;
18886 
18887 	switch (cmdp->cb_cmd) {
18888 	case TI_GETPEERNAME:
18889 		cmdp->cb_error = tcp_getpeername(tcp, data, &cmdp->cb_len);
18890 		break;
18891 	case TI_GETMYNAME:
18892 		cmdp->cb_error = tcp_getmyname(tcp, data, &cmdp->cb_len);
18893 		break;
18894 	default:
18895 		cmdp->cb_error = EINVAL;
18896 		break;
18897 	}
18898 
18899 	qreply(q, mp);
18900 }
18901 
18902 void
18903 tcp_wput(queue_t *q, mblk_t *mp)
18904 {
18905 	conn_t	*connp = Q_TO_CONN(q);
18906 	tcp_t	*tcp;
18907 	void (*output_proc)();
18908 	t_scalar_t type;
18909 	uchar_t *rptr;
18910 	struct iocblk	*iocp;
18911 	uint32_t	msize;
18912 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
18913 
18914 	ASSERT(connp->conn_ref >= 2);
18915 
18916 	switch (DB_TYPE(mp)) {
18917 	case M_DATA:
18918 		tcp = connp->conn_tcp;
18919 		ASSERT(tcp != NULL);
18920 
18921 		msize = msgdsize(mp);
18922 
18923 		mutex_enter(&tcp->tcp_non_sq_lock);
18924 		tcp->tcp_squeue_bytes += msize;
18925 		if (TCP_UNSENT_BYTES(tcp) > tcp->tcp_xmit_hiwater) {
18926 			tcp_setqfull(tcp);
18927 		}
18928 		mutex_exit(&tcp->tcp_non_sq_lock);
18929 
18930 		CONN_INC_REF(connp);
18931 		(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
18932 		    tcp_output, connp, SQTAG_TCP_OUTPUT);
18933 		return;
18934 
18935 	case M_CMD:
18936 		tcp_wput_cmdblk(q, mp);
18937 		return;
18938 
18939 	case M_PROTO:
18940 	case M_PCPROTO:
18941 		/*
18942 		 * if it is a snmp message, don't get behind the squeue
18943 		 */
18944 		tcp = connp->conn_tcp;
18945 		rptr = mp->b_rptr;
18946 		if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
18947 			type = ((union T_primitives *)rptr)->type;
18948 		} else {
18949 			if (tcp->tcp_debug) {
18950 				(void) strlog(TCP_MOD_ID, 0, 1,
18951 				    SL_ERROR|SL_TRACE,
18952 				    "tcp_wput_proto, dropping one...");
18953 			}
18954 			freemsg(mp);
18955 			return;
18956 		}
18957 		if (type == T_SVR4_OPTMGMT_REQ) {
18958 			cred_t	*cr = DB_CREDDEF(mp, tcp->tcp_cred);
18959 			if (snmpcom_req(q, mp, tcp_snmp_set, ip_snmp_get,
18960 			    cr)) {
18961 				/*
18962 				 * This was a SNMP request
18963 				 */
18964 				return;
18965 			} else {
18966 				output_proc = tcp_wput_proto;
18967 			}
18968 		} else {
18969 			output_proc = tcp_wput_proto;
18970 		}
18971 		break;
18972 	case M_IOCTL:
18973 		/*
18974 		 * Most ioctls can be processed right away without going via
18975 		 * squeues - process them right here. Those that do require
18976 		 * squeue (currently TCP_IOC_DEFAULT_Q and _SIOCSOCKFALLBACK)
18977 		 * are processed by tcp_wput_ioctl().
18978 		 */
18979 		iocp = (struct iocblk *)mp->b_rptr;
18980 		tcp = connp->conn_tcp;
18981 
18982 		switch (iocp->ioc_cmd) {
18983 		case TCP_IOC_ABORT_CONN:
18984 			tcp_ioctl_abort_conn(q, mp);
18985 			return;
18986 		case TI_GETPEERNAME:
18987 		case TI_GETMYNAME:
18988 			mi_copyin(q, mp, NULL,
18989 			    SIZEOF_STRUCT(strbuf, iocp->ioc_flag));
18990 			return;
18991 		case ND_SET:
18992 			/* nd_getset does the necessary checks */
18993 		case ND_GET:
18994 			if (!nd_getset(q, tcps->tcps_g_nd, mp)) {
18995 				CALL_IP_WPUT(connp, q, mp);
18996 				return;
18997 			}
18998 			qreply(q, mp);
18999 			return;
19000 		case TCP_IOC_DEFAULT_Q:
19001 			/*
19002 			 * Wants to be the default wq. Check the credentials
19003 			 * first, the rest is executed via squeue.
19004 			 */
19005 			if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
19006 				iocp->ioc_error = EPERM;
19007 				iocp->ioc_count = 0;
19008 				mp->b_datap->db_type = M_IOCACK;
19009 				qreply(q, mp);
19010 				return;
19011 			}
19012 			output_proc = tcp_wput_ioctl;
19013 			break;
19014 		default:
19015 			output_proc = tcp_wput_ioctl;
19016 			break;
19017 		}
19018 		break;
19019 	default:
19020 		output_proc = tcp_wput_nondata;
19021 		break;
19022 	}
19023 
19024 	CONN_INC_REF(connp);
19025 	(*tcp_squeue_wput_proc)(connp->conn_sqp, mp,
19026 	    output_proc, connp, SQTAG_TCP_WPUT_OTHER);
19027 }
19028 
19029 /*
19030  * Initial STREAMS write side put() procedure for sockets. It tries to
19031  * handle the T_CAPABILITY_REQ which sockfs sends down while setting
19032  * up the socket without using the squeue. Non T_CAPABILITY_REQ messages
19033  * are handled by tcp_wput() as usual.
19034  *
19035  * All further messages will also be handled by tcp_wput() because we cannot
19036  * be sure that the above short cut is safe later.
19037  */
19038 static void
19039 tcp_wput_sock(queue_t *wq, mblk_t *mp)
19040 {
19041 	conn_t			*connp = Q_TO_CONN(wq);
19042 	tcp_t			*tcp = connp->conn_tcp;
19043 	struct T_capability_req	*car = (struct T_capability_req *)mp->b_rptr;
19044 
19045 	ASSERT(wq->q_qinfo == &tcp_sock_winit);
19046 	wq->q_qinfo = &tcp_winit;
19047 
19048 	ASSERT(IPCL_IS_TCP(connp));
19049 	ASSERT(TCP_IS_SOCKET(tcp));
19050 
19051 	if (DB_TYPE(mp) == M_PCPROTO &&
19052 	    MBLKL(mp) == sizeof (struct T_capability_req) &&
19053 	    car->PRIM_type == T_CAPABILITY_REQ) {
19054 		tcp_capability_req(tcp, mp);
19055 		return;
19056 	}
19057 
19058 	tcp_wput(wq, mp);
19059 }
19060 
19061 static boolean_t
19062 tcp_zcopy_check(tcp_t *tcp)
19063 {
19064 	conn_t	*connp = tcp->tcp_connp;
19065 	ire_t	*ire;
19066 	boolean_t	zc_enabled = B_FALSE;
19067 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19068 
19069 	if (do_tcpzcopy == 2)
19070 		zc_enabled = B_TRUE;
19071 	else if (tcp->tcp_ipversion == IPV4_VERSION &&
19072 	    IPCL_IS_CONNECTED(connp) &&
19073 	    (connp->conn_flags & IPCL_CHECK_POLICY) == 0 &&
19074 	    connp->conn_dontroute == 0 &&
19075 	    !connp->conn_nexthop_set &&
19076 	    connp->conn_outgoing_ill == NULL &&
19077 	    connp->conn_nofailover_ill == NULL &&
19078 	    do_tcpzcopy == 1) {
19079 		/*
19080 		 * the checks above  closely resemble the fast path checks
19081 		 * in tcp_send_data().
19082 		 */
19083 		mutex_enter(&connp->conn_lock);
19084 		ire = connp->conn_ire_cache;
19085 		ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19086 		if (ire != NULL && !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19087 			IRE_REFHOLD(ire);
19088 			if (ire->ire_stq != NULL) {
19089 				ill_t	*ill = (ill_t *)ire->ire_stq->q_ptr;
19090 
19091 				zc_enabled = ill && (ill->ill_capabilities &
19092 				    ILL_CAPAB_ZEROCOPY) &&
19093 				    (ill->ill_zerocopy_capab->
19094 				    ill_zerocopy_flags != 0);
19095 			}
19096 			IRE_REFRELE(ire);
19097 		}
19098 		mutex_exit(&connp->conn_lock);
19099 	}
19100 	tcp->tcp_snd_zcopy_on = zc_enabled;
19101 	if (!TCP_IS_DETACHED(tcp)) {
19102 		if (zc_enabled) {
19103 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMSAFE);
19104 			TCP_STAT(tcps, tcp_zcopy_on);
19105 		} else {
19106 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19107 			TCP_STAT(tcps, tcp_zcopy_off);
19108 		}
19109 	}
19110 	return (zc_enabled);
19111 }
19112 
19113 static mblk_t *
19114 tcp_zcopy_disable(tcp_t *tcp, mblk_t *bp)
19115 {
19116 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19117 
19118 	if (do_tcpzcopy == 2)
19119 		return (bp);
19120 	else if (tcp->tcp_snd_zcopy_on) {
19121 		tcp->tcp_snd_zcopy_on = B_FALSE;
19122 		if (!TCP_IS_DETACHED(tcp)) {
19123 			(void) mi_set_sth_copyopt(tcp->tcp_rq, ZCVMUNSAFE);
19124 			TCP_STAT(tcps, tcp_zcopy_disable);
19125 		}
19126 	}
19127 	return (tcp_zcopy_backoff(tcp, bp, 0));
19128 }
19129 
19130 /*
19131  * Backoff from a zero-copy mblk by copying data to a new mblk and freeing
19132  * the original desballoca'ed segmapped mblk.
19133  */
19134 static mblk_t *
19135 tcp_zcopy_backoff(tcp_t *tcp, mblk_t *bp, int fix_xmitlist)
19136 {
19137 	mblk_t *head, *tail, *nbp;
19138 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19139 
19140 	if (IS_VMLOANED_MBLK(bp)) {
19141 		TCP_STAT(tcps, tcp_zcopy_backoff);
19142 		if ((head = copyb(bp)) == NULL) {
19143 			/* fail to backoff; leave it for the next backoff */
19144 			tcp->tcp_xmit_zc_clean = B_FALSE;
19145 			return (bp);
19146 		}
19147 		if (bp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19148 			if (fix_xmitlist)
19149 				tcp_zcopy_notify(tcp);
19150 			else
19151 				head->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19152 		}
19153 		nbp = bp->b_cont;
19154 		if (fix_xmitlist) {
19155 			head->b_prev = bp->b_prev;
19156 			head->b_next = bp->b_next;
19157 			if (tcp->tcp_xmit_tail == bp)
19158 				tcp->tcp_xmit_tail = head;
19159 		}
19160 		bp->b_next = NULL;
19161 		bp->b_prev = NULL;
19162 		freeb(bp);
19163 	} else {
19164 		head = bp;
19165 		nbp = bp->b_cont;
19166 	}
19167 	tail = head;
19168 	while (nbp) {
19169 		if (IS_VMLOANED_MBLK(nbp)) {
19170 			TCP_STAT(tcps, tcp_zcopy_backoff);
19171 			if ((tail->b_cont = copyb(nbp)) == NULL) {
19172 				tcp->tcp_xmit_zc_clean = B_FALSE;
19173 				tail->b_cont = nbp;
19174 				return (head);
19175 			}
19176 			tail = tail->b_cont;
19177 			if (nbp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) {
19178 				if (fix_xmitlist)
19179 					tcp_zcopy_notify(tcp);
19180 				else
19181 					tail->b_datap->db_struioflag |=
19182 					    STRUIO_ZCNOTIFY;
19183 			}
19184 			bp = nbp;
19185 			nbp = nbp->b_cont;
19186 			if (fix_xmitlist) {
19187 				tail->b_prev = bp->b_prev;
19188 				tail->b_next = bp->b_next;
19189 				if (tcp->tcp_xmit_tail == bp)
19190 					tcp->tcp_xmit_tail = tail;
19191 			}
19192 			bp->b_next = NULL;
19193 			bp->b_prev = NULL;
19194 			freeb(bp);
19195 		} else {
19196 			tail->b_cont = nbp;
19197 			tail = nbp;
19198 			nbp = nbp->b_cont;
19199 		}
19200 	}
19201 	if (fix_xmitlist) {
19202 		tcp->tcp_xmit_last = tail;
19203 		tcp->tcp_xmit_zc_clean = B_TRUE;
19204 	}
19205 	return (head);
19206 }
19207 
19208 static void
19209 tcp_zcopy_notify(tcp_t *tcp)
19210 {
19211 	struct stdata	*stp;
19212 
19213 	if (tcp->tcp_detached)
19214 		return;
19215 	stp = STREAM(tcp->tcp_rq);
19216 	mutex_enter(&stp->sd_lock);
19217 	stp->sd_flag |= STZCNOTIFY;
19218 	cv_broadcast(&stp->sd_zcopy_wait);
19219 	mutex_exit(&stp->sd_lock);
19220 }
19221 
19222 static boolean_t
19223 tcp_send_find_ire(tcp_t *tcp, ipaddr_t *dst, ire_t **irep)
19224 {
19225 	ire_t	*ire;
19226 	conn_t	*connp = tcp->tcp_connp;
19227 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19228 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19229 
19230 	mutex_enter(&connp->conn_lock);
19231 	ire = connp->conn_ire_cache;
19232 	ASSERT(!(connp->conn_state_flags & CONN_INCIPIENT));
19233 
19234 	if ((ire != NULL) &&
19235 	    (((dst != NULL) && (ire->ire_addr == *dst)) || ((dst == NULL) &&
19236 	    IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, &tcp->tcp_ip6h->ip6_dst))) &&
19237 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19238 		IRE_REFHOLD(ire);
19239 		mutex_exit(&connp->conn_lock);
19240 	} else {
19241 		boolean_t cached = B_FALSE;
19242 		ts_label_t *tsl;
19243 
19244 		/* force a recheck later on */
19245 		tcp->tcp_ire_ill_check_done = B_FALSE;
19246 
19247 		TCP_DBGSTAT(tcps, tcp_ire_null1);
19248 		connp->conn_ire_cache = NULL;
19249 		mutex_exit(&connp->conn_lock);
19250 
19251 		if (ire != NULL)
19252 			IRE_REFRELE_NOTR(ire);
19253 
19254 		tsl = crgetlabel(CONN_CRED(connp));
19255 		ire = (dst ?
19256 		    ire_cache_lookup(*dst, connp->conn_zoneid, tsl, ipst) :
19257 		    ire_cache_lookup_v6(&tcp->tcp_ip6h->ip6_dst,
19258 		    connp->conn_zoneid, tsl, ipst));
19259 
19260 		if (ire == NULL) {
19261 			TCP_STAT(tcps, tcp_ire_null);
19262 			return (B_FALSE);
19263 		}
19264 
19265 		IRE_REFHOLD_NOTR(ire);
19266 
19267 		mutex_enter(&connp->conn_lock);
19268 		if (CONN_CACHE_IRE(connp)) {
19269 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
19270 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
19271 				TCP_CHECK_IREINFO(tcp, ire);
19272 				connp->conn_ire_cache = ire;
19273 				cached = B_TRUE;
19274 			}
19275 			rw_exit(&ire->ire_bucket->irb_lock);
19276 		}
19277 		mutex_exit(&connp->conn_lock);
19278 
19279 		/*
19280 		 * We can continue to use the ire but since it was
19281 		 * not cached, we should drop the extra reference.
19282 		 */
19283 		if (!cached)
19284 			IRE_REFRELE_NOTR(ire);
19285 
19286 		/*
19287 		 * Rampart note: no need to select a new label here, since
19288 		 * labels are not allowed to change during the life of a TCP
19289 		 * connection.
19290 		 */
19291 	}
19292 
19293 	*irep = ire;
19294 
19295 	return (B_TRUE);
19296 }
19297 
19298 /*
19299  * Called from tcp_send() or tcp_send_data() to find workable IRE.
19300  *
19301  * 0 = success;
19302  * 1 = failed to find ire and ill.
19303  */
19304 static boolean_t
19305 tcp_send_find_ire_ill(tcp_t *tcp, mblk_t *mp, ire_t **irep, ill_t **illp)
19306 {
19307 	ipha_t		*ipha;
19308 	ipaddr_t	dst;
19309 	ire_t		*ire;
19310 	ill_t		*ill;
19311 	conn_t		*connp = tcp->tcp_connp;
19312 	mblk_t		*ire_fp_mp;
19313 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19314 
19315 	if (mp != NULL)
19316 		ipha = (ipha_t *)mp->b_rptr;
19317 	else
19318 		ipha = tcp->tcp_ipha;
19319 	dst = ipha->ipha_dst;
19320 
19321 	if (!tcp_send_find_ire(tcp, &dst, &ire))
19322 		return (B_FALSE);
19323 
19324 	if ((ire->ire_flags & RTF_MULTIRT) ||
19325 	    (ire->ire_stq == NULL) ||
19326 	    (ire->ire_nce == NULL) ||
19327 	    ((ire_fp_mp = ire->ire_nce->nce_fp_mp) == NULL) ||
19328 	    ((mp != NULL) && (ire->ire_max_frag < ntohs(ipha->ipha_length) ||
19329 	    MBLKL(ire_fp_mp) > MBLKHEAD(mp)))) {
19330 		TCP_STAT(tcps, tcp_ip_ire_send);
19331 		IRE_REFRELE(ire);
19332 		return (B_FALSE);
19333 	}
19334 
19335 	ill = ire_to_ill(ire);
19336 	if (connp->conn_outgoing_ill != NULL) {
19337 		ill_t *conn_outgoing_ill = NULL;
19338 		/*
19339 		 * Choose a good ill in the group to send the packets on.
19340 		 */
19341 		ire = conn_set_outgoing_ill(connp, ire, &conn_outgoing_ill);
19342 		ill = ire_to_ill(ire);
19343 	}
19344 	ASSERT(ill != NULL);
19345 
19346 	if (!tcp->tcp_ire_ill_check_done) {
19347 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
19348 		tcp->tcp_ire_ill_check_done = B_TRUE;
19349 	}
19350 
19351 	*irep = ire;
19352 	*illp = ill;
19353 
19354 	return (B_TRUE);
19355 }
19356 
19357 static void
19358 tcp_send_data(tcp_t *tcp, queue_t *q, mblk_t *mp)
19359 {
19360 	ipha_t		*ipha;
19361 	ipaddr_t	src;
19362 	ipaddr_t	dst;
19363 	uint32_t	cksum;
19364 	ire_t		*ire;
19365 	uint16_t	*up;
19366 	ill_t		*ill;
19367 	conn_t		*connp = tcp->tcp_connp;
19368 	uint32_t	hcksum_txflags = 0;
19369 	mblk_t		*ire_fp_mp;
19370 	uint_t		ire_fp_mp_len;
19371 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19372 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
19373 
19374 	ASSERT(DB_TYPE(mp) == M_DATA);
19375 
19376 	if (DB_CRED(mp) == NULL)
19377 		mblk_setcred(mp, CONN_CRED(connp));
19378 
19379 	ipha = (ipha_t *)mp->b_rptr;
19380 	src = ipha->ipha_src;
19381 	dst = ipha->ipha_dst;
19382 
19383 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
19384 
19385 	/*
19386 	 * Drop off fast path for IPv6 and also if options are present or
19387 	 * we need to resolve a TS label.
19388 	 */
19389 	if (tcp->tcp_ipversion != IPV4_VERSION ||
19390 	    !IPCL_IS_CONNECTED(connp) ||
19391 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
19392 	    (connp->conn_flags & IPCL_CHECK_POLICY) != 0 ||
19393 	    !connp->conn_ulp_labeled ||
19394 	    ipha->ipha_ident == IP_HDR_INCLUDED ||
19395 	    ipha->ipha_version_and_hdr_length != IP_SIMPLE_HDR_VERSION ||
19396 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
19397 		if (tcp->tcp_snd_zcopy_aware)
19398 			mp = tcp_zcopy_disable(tcp, mp);
19399 		TCP_STAT(tcps, tcp_ip_send);
19400 		CALL_IP_WPUT(connp, q, mp);
19401 		return;
19402 	}
19403 
19404 	if (!tcp_send_find_ire_ill(tcp, mp, &ire, &ill)) {
19405 		if (tcp->tcp_snd_zcopy_aware)
19406 			mp = tcp_zcopy_backoff(tcp, mp, 0);
19407 		CALL_IP_WPUT(connp, q, mp);
19408 		return;
19409 	}
19410 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
19411 	ire_fp_mp_len = MBLKL(ire_fp_mp);
19412 
19413 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
19414 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
19415 #ifndef _BIG_ENDIAN
19416 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
19417 #endif
19418 
19419 	/*
19420 	 * Check to see if we need to re-enable LSO/MDT for this connection
19421 	 * because it was previously disabled due to changes in the ill;
19422 	 * note that by doing it here, this re-enabling only applies when
19423 	 * the packet is not dispatched through CALL_IP_WPUT().
19424 	 *
19425 	 * That means for IPv4, it is worth re-enabling LSO/MDT for the fastpath
19426 	 * case, since that's how we ended up here.  For IPv6, we do the
19427 	 * re-enabling work in ip_xmit_v6(), albeit indirectly via squeue.
19428 	 */
19429 	if (connp->conn_lso_ok && !tcp->tcp_lso && ILL_LSO_TCP_USABLE(ill)) {
19430 		/*
19431 		 * Restore LSO for this connection, so that next time around
19432 		 * it is eligible to go through tcp_lsosend() path again.
19433 		 */
19434 		TCP_STAT(tcps, tcp_lso_enabled);
19435 		tcp->tcp_lso = B_TRUE;
19436 		ip1dbg(("tcp_send_data: reenabling LSO for connp %p on "
19437 		    "interface %s\n", (void *)connp, ill->ill_name));
19438 	} else if (connp->conn_mdt_ok && !tcp->tcp_mdt && ILL_MDT_USABLE(ill)) {
19439 		/*
19440 		 * Restore MDT for this connection, so that next time around
19441 		 * it is eligible to go through tcp_multisend() path again.
19442 		 */
19443 		TCP_STAT(tcps, tcp_mdt_conn_resumed1);
19444 		tcp->tcp_mdt = B_TRUE;
19445 		ip1dbg(("tcp_send_data: reenabling MDT for connp %p on "
19446 		    "interface %s\n", (void *)connp, ill->ill_name));
19447 	}
19448 
19449 	if (tcp->tcp_snd_zcopy_aware) {
19450 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
19451 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
19452 			mp = tcp_zcopy_disable(tcp, mp);
19453 		/*
19454 		 * we shouldn't need to reset ipha as the mp containing
19455 		 * ipha should never be a zero-copy mp.
19456 		 */
19457 	}
19458 
19459 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
19460 		ASSERT(ill->ill_hcksum_capab != NULL);
19461 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
19462 	}
19463 
19464 	/* pseudo-header checksum (do it in parts for IP header checksum) */
19465 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
19466 
19467 	ASSERT(ipha->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION);
19468 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
19469 
19470 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
19471 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
19472 
19473 	/* Software checksum? */
19474 	if (DB_CKSUMFLAGS(mp) == 0) {
19475 		TCP_STAT(tcps, tcp_out_sw_cksum);
19476 		TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
19477 		    ntohs(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH);
19478 	}
19479 
19480 	/* Calculate IP header checksum if hardware isn't capable */
19481 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
19482 		IP_HDR_CKSUM(ipha, cksum, ((uint32_t *)ipha)[0],
19483 		    ((uint16_t *)ipha)[4]);
19484 	}
19485 
19486 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
19487 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
19488 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
19489 
19490 	UPDATE_OB_PKT_COUNT(ire);
19491 	ire->ire_last_used_time = lbolt;
19492 
19493 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
19494 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
19495 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
19496 	    ntohs(ipha->ipha_length));
19497 
19498 	if (ILL_DLS_CAPABLE(ill)) {
19499 		/*
19500 		 * Send the packet directly to DLD, where it may be queued
19501 		 * depending on the availability of transmit resources at
19502 		 * the media layer.
19503 		 */
19504 		IP_DLS_ILL_TX(ill, ipha, mp, ipst, ire_fp_mp_len);
19505 	} else {
19506 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
19507 		DTRACE_PROBE4(ip4__physical__out__start,
19508 		    ill_t *, NULL, ill_t *, out_ill,
19509 		    ipha_t *, ipha, mblk_t *, mp);
19510 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
19511 		    ipst->ips_ipv4firewall_physical_out,
19512 		    NULL, out_ill, ipha, mp, mp, 0, ipst);
19513 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
19514 
19515 		if (mp != NULL) {
19516 			if (ipst->ips_ipobs_enabled) {
19517 				ipobs_hook(mp, IPOBS_HOOK_OUTBOUND,
19518 				    IP_REAL_ZONEID(connp->conn_zoneid, ipst),
19519 				    ALL_ZONES, ill, IPV4_VERSION, ire_fp_mp_len,
19520 				    ipst);
19521 			}
19522 			DTRACE_IP_FASTPATH(mp, ipha, out_ill, ipha, NULL);
19523 			putnext(ire->ire_stq, mp);
19524 		}
19525 	}
19526 	IRE_REFRELE(ire);
19527 }
19528 
19529 /*
19530  * This handles the case when the receiver has shrunk its win. Per RFC 1122
19531  * if the receiver shrinks the window, i.e. moves the right window to the
19532  * left, the we should not send new data, but should retransmit normally the
19533  * old unacked data between suna and suna + swnd. We might has sent data
19534  * that is now outside the new window, pretend that we didn't send  it.
19535  */
19536 static void
19537 tcp_process_shrunk_swnd(tcp_t *tcp, uint32_t shrunk_count)
19538 {
19539 	uint32_t	snxt = tcp->tcp_snxt;
19540 	mblk_t		*xmit_tail;
19541 	int32_t		offset;
19542 
19543 	ASSERT(shrunk_count > 0);
19544 
19545 	/* Pretend we didn't send the data outside the window */
19546 	snxt -= shrunk_count;
19547 
19548 	/* Get the mblk and the offset in it per the shrunk window */
19549 	xmit_tail = tcp_get_seg_mp(tcp, snxt, &offset);
19550 
19551 	ASSERT(xmit_tail != NULL);
19552 
19553 	/* Reset all the values per the now shrunk window */
19554 	tcp->tcp_snxt = snxt;
19555 	tcp->tcp_xmit_tail = xmit_tail;
19556 	tcp->tcp_xmit_tail_unsent = xmit_tail->b_wptr - xmit_tail->b_rptr -
19557 	    offset;
19558 	tcp->tcp_unsent += shrunk_count;
19559 
19560 	if (tcp->tcp_suna == tcp->tcp_snxt && tcp->tcp_swnd == 0)
19561 		/*
19562 		 * Make sure the timer is running so that we will probe a zero
19563 		 * window.
19564 		 */
19565 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19566 }
19567 
19568 
19569 /*
19570  * The TCP normal data output path.
19571  * NOTE: the logic of the fast path is duplicated from this function.
19572  */
19573 static void
19574 tcp_wput_data(tcp_t *tcp, mblk_t *mp, boolean_t urgent)
19575 {
19576 	int		len;
19577 	mblk_t		*local_time;
19578 	mblk_t		*mp1;
19579 	uint32_t	snxt;
19580 	int		tail_unsent;
19581 	int		tcpstate;
19582 	int		usable = 0;
19583 	mblk_t		*xmit_tail;
19584 	queue_t		*q = tcp->tcp_wq;
19585 	int32_t		mss;
19586 	int32_t		num_sack_blk = 0;
19587 	int32_t		tcp_hdr_len;
19588 	int32_t		tcp_tcp_hdr_len;
19589 	int		mdt_thres;
19590 	int		rc;
19591 	tcp_stack_t	*tcps = tcp->tcp_tcps;
19592 	ip_stack_t	*ipst;
19593 
19594 	tcpstate = tcp->tcp_state;
19595 	if (mp == NULL) {
19596 		/*
19597 		 * tcp_wput_data() with NULL mp should only be called when
19598 		 * there is unsent data.
19599 		 */
19600 		ASSERT(tcp->tcp_unsent > 0);
19601 		/* Really tacky... but we need this for detached closes. */
19602 		len = tcp->tcp_unsent;
19603 		goto data_null;
19604 	}
19605 
19606 #if CCS_STATS
19607 	wrw_stats.tot.count++;
19608 	wrw_stats.tot.bytes += msgdsize(mp);
19609 #endif
19610 	ASSERT(mp->b_datap->db_type == M_DATA);
19611 	/*
19612 	 * Don't allow data after T_ORDREL_REQ or T_DISCON_REQ,
19613 	 * or before a connection attempt has begun.
19614 	 */
19615 	if (tcpstate < TCPS_SYN_SENT || tcpstate > TCPS_CLOSE_WAIT ||
19616 	    (tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19617 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) != 0) {
19618 #ifdef DEBUG
19619 			cmn_err(CE_WARN,
19620 			    "tcp_wput_data: data after ordrel, %s",
19621 			    tcp_display(tcp, NULL,
19622 			    DISP_ADDR_AND_PORT));
19623 #else
19624 			if (tcp->tcp_debug) {
19625 				(void) strlog(TCP_MOD_ID, 0, 1,
19626 				    SL_TRACE|SL_ERROR,
19627 				    "tcp_wput_data: data after ordrel, %s\n",
19628 				    tcp_display(tcp, NULL,
19629 				    DISP_ADDR_AND_PORT));
19630 			}
19631 #endif /* DEBUG */
19632 		}
19633 		if (tcp->tcp_snd_zcopy_aware &&
19634 		    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY) != 0)
19635 			tcp_zcopy_notify(tcp);
19636 		freemsg(mp);
19637 		mutex_enter(&tcp->tcp_non_sq_lock);
19638 		if (tcp->tcp_flow_stopped &&
19639 		    TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19640 			tcp_clrqfull(tcp);
19641 		}
19642 		mutex_exit(&tcp->tcp_non_sq_lock);
19643 		return;
19644 	}
19645 
19646 	/* Strip empties */
19647 	for (;;) {
19648 		ASSERT((uintptr_t)(mp->b_wptr - mp->b_rptr) <=
19649 		    (uintptr_t)INT_MAX);
19650 		len = (int)(mp->b_wptr - mp->b_rptr);
19651 		if (len > 0)
19652 			break;
19653 		mp1 = mp;
19654 		mp = mp->b_cont;
19655 		freeb(mp1);
19656 		if (!mp) {
19657 			return;
19658 		}
19659 	}
19660 
19661 	/* If we are the first on the list ... */
19662 	if (tcp->tcp_xmit_head == NULL) {
19663 		tcp->tcp_xmit_head = mp;
19664 		tcp->tcp_xmit_tail = mp;
19665 		tcp->tcp_xmit_tail_unsent = len;
19666 	} else {
19667 		/* If tiny tx and room in txq tail, pullup to save mblks. */
19668 		struct datab *dp;
19669 
19670 		mp1 = tcp->tcp_xmit_last;
19671 		if (len < tcp_tx_pull_len &&
19672 		    (dp = mp1->b_datap)->db_ref == 1 &&
19673 		    dp->db_lim - mp1->b_wptr >= len) {
19674 			ASSERT(len > 0);
19675 			ASSERT(!mp1->b_cont);
19676 			if (len == 1) {
19677 				*mp1->b_wptr++ = *mp->b_rptr;
19678 			} else {
19679 				bcopy(mp->b_rptr, mp1->b_wptr, len);
19680 				mp1->b_wptr += len;
19681 			}
19682 			if (mp1 == tcp->tcp_xmit_tail)
19683 				tcp->tcp_xmit_tail_unsent += len;
19684 			mp1->b_cont = mp->b_cont;
19685 			if (tcp->tcp_snd_zcopy_aware &&
19686 			    (mp->b_datap->db_struioflag & STRUIO_ZCNOTIFY))
19687 				mp1->b_datap->db_struioflag |= STRUIO_ZCNOTIFY;
19688 			freeb(mp);
19689 			mp = mp1;
19690 		} else {
19691 			tcp->tcp_xmit_last->b_cont = mp;
19692 		}
19693 		len += tcp->tcp_unsent;
19694 	}
19695 
19696 	/* Tack on however many more positive length mblks we have */
19697 	if ((mp1 = mp->b_cont) != NULL) {
19698 		do {
19699 			int tlen;
19700 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
19701 			    (uintptr_t)INT_MAX);
19702 			tlen = (int)(mp1->b_wptr - mp1->b_rptr);
19703 			if (tlen <= 0) {
19704 				mp->b_cont = mp1->b_cont;
19705 				freeb(mp1);
19706 			} else {
19707 				len += tlen;
19708 				mp = mp1;
19709 			}
19710 		} while ((mp1 = mp->b_cont) != NULL);
19711 	}
19712 	tcp->tcp_xmit_last = mp;
19713 	tcp->tcp_unsent = len;
19714 
19715 	if (urgent)
19716 		usable = 1;
19717 
19718 data_null:
19719 	snxt = tcp->tcp_snxt;
19720 	xmit_tail = tcp->tcp_xmit_tail;
19721 	tail_unsent = tcp->tcp_xmit_tail_unsent;
19722 
19723 	/*
19724 	 * Note that tcp_mss has been adjusted to take into account the
19725 	 * timestamp option if applicable.  Because SACK options do not
19726 	 * appear in every TCP segments and they are of variable lengths,
19727 	 * they cannot be included in tcp_mss.  Thus we need to calculate
19728 	 * the actual segment length when we need to send a segment which
19729 	 * includes SACK options.
19730 	 */
19731 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
19732 		int32_t	opt_len;
19733 
19734 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
19735 		    tcp->tcp_num_sack_blk);
19736 		opt_len = num_sack_blk * sizeof (sack_blk_t) + TCPOPT_NOP_LEN *
19737 		    2 + TCPOPT_HEADER_LEN;
19738 		mss = tcp->tcp_mss - opt_len;
19739 		tcp_hdr_len = tcp->tcp_hdr_len + opt_len;
19740 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + opt_len;
19741 	} else {
19742 		mss = tcp->tcp_mss;
19743 		tcp_hdr_len = tcp->tcp_hdr_len;
19744 		tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
19745 	}
19746 
19747 	if ((tcp->tcp_suna == snxt) && !tcp->tcp_localnet &&
19748 	    (TICK_TO_MSEC(lbolt - tcp->tcp_last_recv_time) >= tcp->tcp_rto)) {
19749 		SET_TCP_INIT_CWND(tcp, mss, tcps->tcps_slow_start_after_idle);
19750 	}
19751 	if (tcpstate == TCPS_SYN_RCVD) {
19752 		/*
19753 		 * The three-way connection establishment handshake is not
19754 		 * complete yet. We want to queue the data for transmission
19755 		 * after entering ESTABLISHED state (RFC793). A jump to
19756 		 * "done" label effectively leaves data on the queue.
19757 		 */
19758 		goto done;
19759 	} else {
19760 		int usable_r;
19761 
19762 		/*
19763 		 * In the special case when cwnd is zero, which can only
19764 		 * happen if the connection is ECN capable, return now.
19765 		 * New segments is sent using tcp_timer().  The timer
19766 		 * is set in tcp_rput_data().
19767 		 */
19768 		if (tcp->tcp_cwnd == 0) {
19769 			/*
19770 			 * Note that tcp_cwnd is 0 before 3-way handshake is
19771 			 * finished.
19772 			 */
19773 			ASSERT(tcp->tcp_ecn_ok ||
19774 			    tcp->tcp_state < TCPS_ESTABLISHED);
19775 			return;
19776 		}
19777 
19778 		/* NOTE: trouble if xmitting while SYN not acked? */
19779 		usable_r = snxt - tcp->tcp_suna;
19780 		usable_r = tcp->tcp_swnd - usable_r;
19781 
19782 		/*
19783 		 * Check if the receiver has shrunk the window.  If
19784 		 * tcp_wput_data() with NULL mp is called, tcp_fin_sent
19785 		 * cannot be set as there is unsent data, so FIN cannot
19786 		 * be sent out.  Otherwise, we need to take into account
19787 		 * of FIN as it consumes an "invisible" sequence number.
19788 		 */
19789 		ASSERT(tcp->tcp_fin_sent == 0);
19790 		if (usable_r < 0) {
19791 			/*
19792 			 * The receiver has shrunk the window and we have sent
19793 			 * -usable_r date beyond the window, re-adjust.
19794 			 *
19795 			 * If TCP window scaling is enabled, there can be
19796 			 * round down error as the advertised receive window
19797 			 * is actually right shifted n bits.  This means that
19798 			 * the lower n bits info is wiped out.  It will look
19799 			 * like the window is shrunk.  Do a check here to
19800 			 * see if the shrunk amount is actually within the
19801 			 * error in window calculation.  If it is, just
19802 			 * return.  Note that this check is inside the
19803 			 * shrunk window check.  This makes sure that even
19804 			 * though tcp_process_shrunk_swnd() is not called,
19805 			 * we will stop further processing.
19806 			 */
19807 			if ((-usable_r >> tcp->tcp_snd_ws) > 0) {
19808 				tcp_process_shrunk_swnd(tcp, -usable_r);
19809 			}
19810 			return;
19811 		}
19812 
19813 		/* usable = MIN(swnd, cwnd) - unacked_bytes */
19814 		if (tcp->tcp_swnd > tcp->tcp_cwnd)
19815 			usable_r -= tcp->tcp_swnd - tcp->tcp_cwnd;
19816 
19817 		/* usable = MIN(usable, unsent) */
19818 		if (usable_r > len)
19819 			usable_r = len;
19820 
19821 		/* usable = MAX(usable, {1 for urgent, 0 for data}) */
19822 		if (usable_r > 0) {
19823 			usable = usable_r;
19824 		} else {
19825 			/* Bypass all other unnecessary processing. */
19826 			goto done;
19827 		}
19828 	}
19829 
19830 	local_time = (mblk_t *)lbolt;
19831 
19832 	/*
19833 	 * "Our" Nagle Algorithm.  This is not the same as in the old
19834 	 * BSD.  This is more in line with the true intent of Nagle.
19835 	 *
19836 	 * The conditions are:
19837 	 * 1. The amount of unsent data (or amount of data which can be
19838 	 *    sent, whichever is smaller) is less than Nagle limit.
19839 	 * 2. The last sent size is also less than Nagle limit.
19840 	 * 3. There is unack'ed data.
19841 	 * 4. Urgent pointer is not set.  Send urgent data ignoring the
19842 	 *    Nagle algorithm.  This reduces the probability that urgent
19843 	 *    bytes get "merged" together.
19844 	 * 5. The app has not closed the connection.  This eliminates the
19845 	 *    wait time of the receiving side waiting for the last piece of
19846 	 *    (small) data.
19847 	 *
19848 	 * If all are satisified, exit without sending anything.  Note
19849 	 * that Nagle limit can be smaller than 1 MSS.  Nagle limit is
19850 	 * the smaller of 1 MSS and global tcp_naglim_def (default to be
19851 	 * 4095).
19852 	 */
19853 	if (usable < (int)tcp->tcp_naglim &&
19854 	    tcp->tcp_naglim > tcp->tcp_last_sent_len &&
19855 	    snxt != tcp->tcp_suna &&
19856 	    !(tcp->tcp_valid_bits & TCP_URG_VALID) &&
19857 	    !(tcp->tcp_valid_bits & TCP_FSS_VALID)) {
19858 		goto done;
19859 	}
19860 
19861 	if (tcp->tcp_cork) {
19862 		/*
19863 		 * if the tcp->tcp_cork option is set, then we have to force
19864 		 * TCP not to send partial segment (smaller than MSS bytes).
19865 		 * We are calculating the usable now based on full mss and
19866 		 * will save the rest of remaining data for later.
19867 		 */
19868 		if (usable < mss)
19869 			goto done;
19870 		usable = (usable / mss) * mss;
19871 	}
19872 
19873 	/* Update the latest receive window size in TCP header. */
19874 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
19875 	    tcp->tcp_tcph->th_win);
19876 
19877 	/*
19878 	 * Determine if it's worthwhile to attempt LSO or MDT, based on:
19879 	 *
19880 	 * 1. Simple TCP/IP{v4,v6} (no options).
19881 	 * 2. IPSEC/IPQoS processing is not needed for the TCP connection.
19882 	 * 3. If the TCP connection is in ESTABLISHED state.
19883 	 * 4. The TCP is not detached.
19884 	 *
19885 	 * If any of the above conditions have changed during the
19886 	 * connection, stop using LSO/MDT and restore the stream head
19887 	 * parameters accordingly.
19888 	 */
19889 	ipst = tcps->tcps_netstack->netstack_ip;
19890 
19891 	if ((tcp->tcp_lso || tcp->tcp_mdt) &&
19892 	    ((tcp->tcp_ipversion == IPV4_VERSION &&
19893 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
19894 	    (tcp->tcp_ipversion == IPV6_VERSION &&
19895 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN) ||
19896 	    tcp->tcp_state != TCPS_ESTABLISHED ||
19897 	    TCP_IS_DETACHED(tcp) || !CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp) ||
19898 	    CONN_IPSEC_OUT_ENCAPSULATED(tcp->tcp_connp) ||
19899 	    IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
19900 		if (tcp->tcp_lso) {
19901 			tcp->tcp_connp->conn_lso_ok = B_FALSE;
19902 			tcp->tcp_lso = B_FALSE;
19903 		} else {
19904 			tcp->tcp_connp->conn_mdt_ok = B_FALSE;
19905 			tcp->tcp_mdt = B_FALSE;
19906 		}
19907 
19908 		/* Anything other than detached is considered pathological */
19909 		if (!TCP_IS_DETACHED(tcp)) {
19910 			if (tcp->tcp_lso)
19911 				TCP_STAT(tcps, tcp_lso_disabled);
19912 			else
19913 				TCP_STAT(tcps, tcp_mdt_conn_halted1);
19914 			(void) tcp_maxpsz_set(tcp, B_TRUE);
19915 		}
19916 	}
19917 
19918 	/* Use MDT if sendable amount is greater than the threshold */
19919 	if (tcp->tcp_mdt &&
19920 	    (mdt_thres = mss << tcp_mdt_smss_threshold, usable > mdt_thres) &&
19921 	    (tail_unsent > mdt_thres || (xmit_tail->b_cont != NULL &&
19922 	    MBLKL(xmit_tail->b_cont) > mdt_thres)) &&
19923 	    (tcp->tcp_valid_bits == 0 ||
19924 	    tcp->tcp_valid_bits == TCP_FSS_VALID)) {
19925 		ASSERT(tcp->tcp_connp->conn_mdt_ok);
19926 		rc = tcp_multisend(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19927 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19928 		    local_time, mdt_thres);
19929 	} else {
19930 		rc = tcp_send(q, tcp, mss, tcp_hdr_len, tcp_tcp_hdr_len,
19931 		    num_sack_blk, &usable, &snxt, &tail_unsent, &xmit_tail,
19932 		    local_time, INT_MAX);
19933 	}
19934 
19935 	/* Pretend that all we were trying to send really got sent */
19936 	if (rc < 0 && tail_unsent < 0) {
19937 		do {
19938 			xmit_tail = xmit_tail->b_cont;
19939 			xmit_tail->b_prev = local_time;
19940 			ASSERT((uintptr_t)(xmit_tail->b_wptr -
19941 			    xmit_tail->b_rptr) <= (uintptr_t)INT_MAX);
19942 			tail_unsent += (int)(xmit_tail->b_wptr -
19943 			    xmit_tail->b_rptr);
19944 		} while (tail_unsent < 0);
19945 	}
19946 done:;
19947 	tcp->tcp_xmit_tail = xmit_tail;
19948 	tcp->tcp_xmit_tail_unsent = tail_unsent;
19949 	len = tcp->tcp_snxt - snxt;
19950 	if (len) {
19951 		/*
19952 		 * If new data was sent, need to update the notsack
19953 		 * list, which is, afterall, data blocks that have
19954 		 * not been sack'ed by the receiver.  New data is
19955 		 * not sack'ed.
19956 		 */
19957 		if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL) {
19958 			/* len is a negative value. */
19959 			tcp->tcp_pipe -= len;
19960 			tcp_notsack_update(&(tcp->tcp_notsack_list),
19961 			    tcp->tcp_snxt, snxt,
19962 			    &(tcp->tcp_num_notsack_blk),
19963 			    &(tcp->tcp_cnt_notsack_list));
19964 		}
19965 		tcp->tcp_snxt = snxt + tcp->tcp_fin_sent;
19966 		tcp->tcp_rack = tcp->tcp_rnxt;
19967 		tcp->tcp_rack_cnt = 0;
19968 		if ((snxt + len) == tcp->tcp_suna) {
19969 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19970 		}
19971 	} else if (snxt == tcp->tcp_suna && tcp->tcp_swnd == 0) {
19972 		/*
19973 		 * Didn't send anything. Make sure the timer is running
19974 		 * so that we will probe a zero window.
19975 		 */
19976 		TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
19977 	}
19978 	/* Note that len is the amount we just sent but with a negative sign */
19979 	tcp->tcp_unsent += len;
19980 	mutex_enter(&tcp->tcp_non_sq_lock);
19981 	if (tcp->tcp_flow_stopped) {
19982 		if (TCP_UNSENT_BYTES(tcp) <= tcp->tcp_xmit_lowater) {
19983 			tcp_clrqfull(tcp);
19984 		}
19985 	} else if (TCP_UNSENT_BYTES(tcp) >= tcp->tcp_xmit_hiwater) {
19986 		tcp_setqfull(tcp);
19987 	}
19988 	mutex_exit(&tcp->tcp_non_sq_lock);
19989 }
19990 
19991 /*
19992  * tcp_fill_header is called by tcp_send() and tcp_multisend() to fill the
19993  * outgoing TCP header with the template header, as well as other
19994  * options such as time-stamp, ECN and/or SACK.
19995  */
19996 static void
19997 tcp_fill_header(tcp_t *tcp, uchar_t *rptr, clock_t now, int num_sack_blk)
19998 {
19999 	tcph_t *tcp_tmpl, *tcp_h;
20000 	uint32_t *dst, *src;
20001 	int hdrlen;
20002 
20003 	ASSERT(OK_32PTR(rptr));
20004 
20005 	/* Template header */
20006 	tcp_tmpl = tcp->tcp_tcph;
20007 
20008 	/* Header of outgoing packet */
20009 	tcp_h = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
20010 
20011 	/* dst and src are opaque 32-bit fields, used for copying */
20012 	dst = (uint32_t *)rptr;
20013 	src = (uint32_t *)tcp->tcp_iphc;
20014 	hdrlen = tcp->tcp_hdr_len;
20015 
20016 	/* Fill time-stamp option if needed */
20017 	if (tcp->tcp_snd_ts_ok) {
20018 		U32_TO_BE32((uint32_t)now,
20019 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 4);
20020 		U32_TO_BE32(tcp->tcp_ts_recent,
20021 		    (char *)tcp_tmpl + TCP_MIN_HEADER_LENGTH + 8);
20022 	} else {
20023 		ASSERT(tcp->tcp_tcp_hdr_len == TCP_MIN_HEADER_LENGTH);
20024 	}
20025 
20026 	/*
20027 	 * Copy the template header; is this really more efficient than
20028 	 * calling bcopy()?  For simple IPv4/TCP, it may be the case,
20029 	 * but perhaps not for other scenarios.
20030 	 */
20031 	dst[0] = src[0];
20032 	dst[1] = src[1];
20033 	dst[2] = src[2];
20034 	dst[3] = src[3];
20035 	dst[4] = src[4];
20036 	dst[5] = src[5];
20037 	dst[6] = src[6];
20038 	dst[7] = src[7];
20039 	dst[8] = src[8];
20040 	dst[9] = src[9];
20041 	if (hdrlen -= 40) {
20042 		hdrlen >>= 2;
20043 		dst += 10;
20044 		src += 10;
20045 		do {
20046 			*dst++ = *src++;
20047 		} while (--hdrlen);
20048 	}
20049 
20050 	/*
20051 	 * Set the ECN info in the TCP header if it is not a zero
20052 	 * window probe.  Zero window probe is only sent in
20053 	 * tcp_wput_data() and tcp_timer().
20054 	 */
20055 	if (tcp->tcp_ecn_ok && !tcp->tcp_zero_win_probe) {
20056 		SET_ECT(tcp, rptr);
20057 
20058 		if (tcp->tcp_ecn_echo_on)
20059 			tcp_h->th_flags[0] |= TH_ECE;
20060 		if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
20061 			tcp_h->th_flags[0] |= TH_CWR;
20062 			tcp->tcp_ecn_cwr_sent = B_TRUE;
20063 		}
20064 	}
20065 
20066 	/* Fill in SACK options */
20067 	if (num_sack_blk > 0) {
20068 		uchar_t *wptr = rptr + tcp->tcp_hdr_len;
20069 		sack_blk_t *tmp;
20070 		int32_t	i;
20071 
20072 		wptr[0] = TCPOPT_NOP;
20073 		wptr[1] = TCPOPT_NOP;
20074 		wptr[2] = TCPOPT_SACK;
20075 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
20076 		    sizeof (sack_blk_t);
20077 		wptr += TCPOPT_REAL_SACK_LEN;
20078 
20079 		tmp = tcp->tcp_sack_list;
20080 		for (i = 0; i < num_sack_blk; i++) {
20081 			U32_TO_BE32(tmp[i].begin, wptr);
20082 			wptr += sizeof (tcp_seq);
20083 			U32_TO_BE32(tmp[i].end, wptr);
20084 			wptr += sizeof (tcp_seq);
20085 		}
20086 		tcp_h->th_offset_and_rsrvd[0] +=
20087 		    ((num_sack_blk * 2 + 1) << 4);
20088 	}
20089 }
20090 
20091 /*
20092  * tcp_mdt_add_attrs() is called by tcp_multisend() in order to attach
20093  * the destination address and SAP attribute, and if necessary, the
20094  * hardware checksum offload attribute to a Multidata message.
20095  */
20096 static int
20097 tcp_mdt_add_attrs(multidata_t *mmd, const mblk_t *dlmp, const boolean_t hwcksum,
20098     const uint32_t start, const uint32_t stuff, const uint32_t end,
20099     const uint32_t flags, tcp_stack_t *tcps)
20100 {
20101 	/* Add global destination address & SAP attribute */
20102 	if (dlmp == NULL || !ip_md_addr_attr(mmd, NULL, dlmp)) {
20103 		ip1dbg(("tcp_mdt_add_attrs: can't add global physical "
20104 		    "destination address+SAP\n"));
20105 
20106 		if (dlmp != NULL)
20107 			TCP_STAT(tcps, tcp_mdt_allocfail);
20108 		return (-1);
20109 	}
20110 
20111 	/* Add global hwcksum attribute */
20112 	if (hwcksum &&
20113 	    !ip_md_hcksum_attr(mmd, NULL, start, stuff, end, flags)) {
20114 		ip1dbg(("tcp_mdt_add_attrs: can't add global hardware "
20115 		    "checksum attribute\n"));
20116 
20117 		TCP_STAT(tcps, tcp_mdt_allocfail);
20118 		return (-1);
20119 	}
20120 
20121 	return (0);
20122 }
20123 
20124 /*
20125  * Smaller and private version of pdescinfo_t used specifically for TCP,
20126  * which allows for only two payload spans per packet.
20127  */
20128 typedef struct tcp_pdescinfo_s PDESCINFO_STRUCT(2) tcp_pdescinfo_t;
20129 
20130 /*
20131  * tcp_multisend() is called by tcp_wput_data() for Multidata Transmit
20132  * scheme, and returns one the following:
20133  *
20134  * -1 = failed allocation.
20135  *  0 = success; burst count reached, or usable send window is too small,
20136  *      and that we'd rather wait until later before sending again.
20137  */
20138 static int
20139 tcp_multisend(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
20140     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
20141     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
20142     const int mdt_thres)
20143 {
20144 	mblk_t		*md_mp_head, *md_mp, *md_pbuf, *md_pbuf_nxt, *md_hbuf;
20145 	multidata_t	*mmd;
20146 	uint_t		obsegs, obbytes, hdr_frag_sz;
20147 	uint_t		cur_hdr_off, cur_pld_off, base_pld_off, first_snxt;
20148 	int		num_burst_seg, max_pld;
20149 	pdesc_t		*pkt;
20150 	tcp_pdescinfo_t	tcp_pkt_info;
20151 	pdescinfo_t	*pkt_info;
20152 	int		pbuf_idx, pbuf_idx_nxt;
20153 	int		seg_len, len, spill, af;
20154 	boolean_t	add_buffer, zcopy, clusterwide;
20155 	boolean_t	rconfirm = B_FALSE;
20156 	boolean_t	done = B_FALSE;
20157 	uint32_t	cksum;
20158 	uint32_t	hwcksum_flags;
20159 	ire_t		*ire = NULL;
20160 	ill_t		*ill;
20161 	ipha_t		*ipha;
20162 	ip6_t		*ip6h;
20163 	ipaddr_t	src, dst;
20164 	ill_zerocopy_capab_t *zc_cap = NULL;
20165 	uint16_t	*up;
20166 	int		err;
20167 	conn_t		*connp;
20168 	tcp_stack_t	*tcps = tcp->tcp_tcps;
20169 	ip_stack_t 	*ipst = tcps->tcps_netstack->netstack_ip;
20170 	int		usable_mmd, tail_unsent_mmd;
20171 	uint_t		snxt_mmd, obsegs_mmd, obbytes_mmd;
20172 	mblk_t		*xmit_tail_mmd;
20173 
20174 #ifdef	_BIG_ENDIAN
20175 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 28) & 0x7)
20176 #else
20177 #define	IPVER(ip6h)	((((uint32_t *)ip6h)[0] >> 4) & 0x7)
20178 #endif
20179 
20180 #define	PREP_NEW_MULTIDATA() {			\
20181 	mmd = NULL;				\
20182 	md_mp = md_hbuf = NULL;			\
20183 	cur_hdr_off = 0;			\
20184 	max_pld = tcp->tcp_mdt_max_pld;		\
20185 	pbuf_idx = pbuf_idx_nxt = -1;		\
20186 	add_buffer = B_TRUE;			\
20187 	zcopy = B_FALSE;			\
20188 }
20189 
20190 #define	PREP_NEW_PBUF() {			\
20191 	md_pbuf = md_pbuf_nxt = NULL;		\
20192 	pbuf_idx = pbuf_idx_nxt = -1;		\
20193 	cur_pld_off = 0;			\
20194 	first_snxt = *snxt;			\
20195 	ASSERT(*tail_unsent > 0);		\
20196 	base_pld_off = MBLKL(*xmit_tail) - *tail_unsent; \
20197 }
20198 
20199 	ASSERT(mdt_thres >= mss);
20200 	ASSERT(*usable > 0 && *usable > mdt_thres);
20201 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
20202 	ASSERT(!TCP_IS_DETACHED(tcp));
20203 	ASSERT(tcp->tcp_valid_bits == 0 ||
20204 	    tcp->tcp_valid_bits == TCP_FSS_VALID);
20205 	ASSERT((tcp->tcp_ipversion == IPV4_VERSION &&
20206 	    tcp->tcp_ip_hdr_len == IP_SIMPLE_HDR_LENGTH) ||
20207 	    (tcp->tcp_ipversion == IPV6_VERSION &&
20208 	    tcp->tcp_ip_hdr_len == IPV6_HDR_LEN));
20209 
20210 	connp = tcp->tcp_connp;
20211 	ASSERT(connp != NULL);
20212 	ASSERT(CONN_IS_LSO_MD_FASTPATH(connp));
20213 	ASSERT(!CONN_IPSEC_OUT_ENCAPSULATED(connp));
20214 
20215 	usable_mmd = tail_unsent_mmd = 0;
20216 	snxt_mmd = obsegs_mmd = obbytes_mmd = 0;
20217 	xmit_tail_mmd = NULL;
20218 	/*
20219 	 * Note that tcp will only declare at most 2 payload spans per
20220 	 * packet, which is much lower than the maximum allowable number
20221 	 * of packet spans per Multidata.  For this reason, we use the
20222 	 * privately declared and smaller descriptor info structure, in
20223 	 * order to save some stack space.
20224 	 */
20225 	pkt_info = (pdescinfo_t *)&tcp_pkt_info;
20226 
20227 	af = (tcp->tcp_ipversion == IPV4_VERSION) ? AF_INET : AF_INET6;
20228 	if (af == AF_INET) {
20229 		dst = tcp->tcp_ipha->ipha_dst;
20230 		src = tcp->tcp_ipha->ipha_src;
20231 		ASSERT(!CLASSD(dst));
20232 	}
20233 	ASSERT(af == AF_INET ||
20234 	    !IN6_IS_ADDR_MULTICAST(&tcp->tcp_ip6h->ip6_dst));
20235 
20236 	obsegs = obbytes = 0;
20237 	num_burst_seg = tcp->tcp_snd_burst;
20238 	md_mp_head = NULL;
20239 	PREP_NEW_MULTIDATA();
20240 
20241 	/*
20242 	 * Before we go on further, make sure there is an IRE that we can
20243 	 * use, and that the ILL supports MDT.  Otherwise, there's no point
20244 	 * in proceeding any further, and we should just hand everything
20245 	 * off to the legacy path.
20246 	 */
20247 	if (!tcp_send_find_ire(tcp, (af == AF_INET) ? &dst : NULL, &ire))
20248 		goto legacy_send_no_md;
20249 
20250 	ASSERT(ire != NULL);
20251 	ASSERT(af != AF_INET || ire->ire_ipversion == IPV4_VERSION);
20252 	ASSERT(af == AF_INET || !IN6_IS_ADDR_V4MAPPED(&(ire->ire_addr_v6)));
20253 	ASSERT(af == AF_INET || ire->ire_nce != NULL);
20254 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
20255 	/*
20256 	 * If we do support loopback for MDT (which requires modifications
20257 	 * to the receiving paths), the following assertions should go away,
20258 	 * and we would be sending the Multidata to loopback conn later on.
20259 	 */
20260 	ASSERT(!IRE_IS_LOCAL(ire));
20261 	ASSERT(ire->ire_stq != NULL);
20262 
20263 	ill = ire_to_ill(ire);
20264 	ASSERT(ill != NULL);
20265 	ASSERT(!ILL_MDT_CAPABLE(ill) || ill->ill_mdt_capab != NULL);
20266 
20267 	if (!tcp->tcp_ire_ill_check_done) {
20268 		tcp_ire_ill_check(tcp, ire, ill, B_TRUE);
20269 		tcp->tcp_ire_ill_check_done = B_TRUE;
20270 	}
20271 
20272 	/*
20273 	 * If the underlying interface conditions have changed, or if the
20274 	 * new interface does not support MDT, go back to legacy path.
20275 	 */
20276 	if (!ILL_MDT_USABLE(ill) || (ire->ire_flags & RTF_MULTIRT) != 0) {
20277 		/* don't go through this path anymore for this connection */
20278 		TCP_STAT(tcps, tcp_mdt_conn_halted2);
20279 		tcp->tcp_mdt = B_FALSE;
20280 		ip1dbg(("tcp_multisend: disabling MDT for connp %p on "
20281 		    "interface %s\n", (void *)connp, ill->ill_name));
20282 		/* IRE will be released prior to returning */
20283 		goto legacy_send_no_md;
20284 	}
20285 
20286 	if (ill->ill_capabilities & ILL_CAPAB_ZEROCOPY)
20287 		zc_cap = ill->ill_zerocopy_capab;
20288 
20289 	/*
20290 	 * Check if we can take tcp fast-path. Note that "incomplete"
20291 	 * ire's (where the link-layer for next hop is not resolved
20292 	 * or where the fast-path header in nce_fp_mp is not available
20293 	 * yet) are sent down the legacy (slow) path.
20294 	 * NOTE: We should fix ip_xmit_v4 to handle M_MULTIDATA
20295 	 */
20296 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
20297 		/* IRE will be released prior to returning */
20298 		goto legacy_send_no_md;
20299 	}
20300 
20301 	/* go to legacy path if interface doesn't support zerocopy */
20302 	if (tcp->tcp_snd_zcopy_aware && do_tcpzcopy != 2 &&
20303 	    (zc_cap == NULL || zc_cap->ill_zerocopy_flags == 0)) {
20304 		/* IRE will be released prior to returning */
20305 		goto legacy_send_no_md;
20306 	}
20307 
20308 	/* does the interface support hardware checksum offload? */
20309 	hwcksum_flags = 0;
20310 	if (ILL_HCKSUM_CAPABLE(ill) &&
20311 	    (ill->ill_hcksum_capab->ill_hcksum_txflags &
20312 	    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6 | HCKSUM_INET_PARTIAL |
20313 	    HCKSUM_IPHDRCKSUM)) && dohwcksum) {
20314 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20315 		    HCKSUM_IPHDRCKSUM)
20316 			hwcksum_flags = HCK_IPV4_HDRCKSUM;
20317 
20318 		if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20319 		    (HCKSUM_INET_FULL_V4 | HCKSUM_INET_FULL_V6))
20320 			hwcksum_flags |= HCK_FULLCKSUM;
20321 		else if (ill->ill_hcksum_capab->ill_hcksum_txflags &
20322 		    HCKSUM_INET_PARTIAL)
20323 			hwcksum_flags |= HCK_PARTIALCKSUM;
20324 	}
20325 
20326 	/*
20327 	 * Each header fragment consists of the leading extra space,
20328 	 * followed by the TCP/IP header, and the trailing extra space.
20329 	 * We make sure that each header fragment begins on a 32-bit
20330 	 * aligned memory address (tcp_mdt_hdr_head is already 32-bit
20331 	 * aligned in tcp_mdt_update).
20332 	 */
20333 	hdr_frag_sz = roundup((tcp->tcp_mdt_hdr_head + tcp_hdr_len +
20334 	    tcp->tcp_mdt_hdr_tail), 4);
20335 
20336 	/* are we starting from the beginning of data block? */
20337 	if (*tail_unsent == 0) {
20338 		*xmit_tail = (*xmit_tail)->b_cont;
20339 		ASSERT((uintptr_t)MBLKL(*xmit_tail) <= (uintptr_t)INT_MAX);
20340 		*tail_unsent = (int)MBLKL(*xmit_tail);
20341 	}
20342 
20343 	/*
20344 	 * Here we create one or more Multidata messages, each made up of
20345 	 * one header buffer and up to N payload buffers.  This entire
20346 	 * operation is done within two loops:
20347 	 *
20348 	 * The outer loop mostly deals with creating the Multidata message,
20349 	 * as well as the header buffer that gets added to it.  It also
20350 	 * links the Multidata messages together such that all of them can
20351 	 * be sent down to the lower layer in a single putnext call; this
20352 	 * linking behavior depends on the tcp_mdt_chain tunable.
20353 	 *
20354 	 * The inner loop takes an existing Multidata message, and adds
20355 	 * one or more (up to tcp_mdt_max_pld) payload buffers to it.  It
20356 	 * packetizes those buffers by filling up the corresponding header
20357 	 * buffer fragments with the proper IP and TCP headers, and by
20358 	 * describing the layout of each packet in the packet descriptors
20359 	 * that get added to the Multidata.
20360 	 */
20361 	do {
20362 		/*
20363 		 * If usable send window is too small, or data blocks in
20364 		 * transmit list are smaller than our threshold (i.e. app
20365 		 * performs large writes followed by small ones), we hand
20366 		 * off the control over to the legacy path.  Note that we'll
20367 		 * get back the control once it encounters a large block.
20368 		 */
20369 		if (*usable < mss || (*tail_unsent <= mdt_thres &&
20370 		    (*xmit_tail)->b_cont != NULL &&
20371 		    MBLKL((*xmit_tail)->b_cont) <= mdt_thres)) {
20372 			/* send down what we've got so far */
20373 			if (md_mp_head != NULL) {
20374 				tcp_multisend_data(tcp, ire, ill, md_mp_head,
20375 				    obsegs, obbytes, &rconfirm);
20376 			}
20377 			/*
20378 			 * Pass control over to tcp_send(), but tell it to
20379 			 * return to us once a large-size transmission is
20380 			 * possible.
20381 			 */
20382 			TCP_STAT(tcps, tcp_mdt_legacy_small);
20383 			if ((err = tcp_send(q, tcp, mss, tcp_hdr_len,
20384 			    tcp_tcp_hdr_len, num_sack_blk, usable, snxt,
20385 			    tail_unsent, xmit_tail, local_time,
20386 			    mdt_thres)) <= 0) {
20387 				/* burst count reached, or alloc failed */
20388 				IRE_REFRELE(ire);
20389 				return (err);
20390 			}
20391 
20392 			/* tcp_send() may have sent everything, so check */
20393 			if (*usable <= 0) {
20394 				IRE_REFRELE(ire);
20395 				return (0);
20396 			}
20397 
20398 			TCP_STAT(tcps, tcp_mdt_legacy_ret);
20399 			/*
20400 			 * We may have delivered the Multidata, so make sure
20401 			 * to re-initialize before the next round.
20402 			 */
20403 			md_mp_head = NULL;
20404 			obsegs = obbytes = 0;
20405 			num_burst_seg = tcp->tcp_snd_burst;
20406 			PREP_NEW_MULTIDATA();
20407 
20408 			/* are we starting from the beginning of data block? */
20409 			if (*tail_unsent == 0) {
20410 				*xmit_tail = (*xmit_tail)->b_cont;
20411 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20412 				    (uintptr_t)INT_MAX);
20413 				*tail_unsent = (int)MBLKL(*xmit_tail);
20414 			}
20415 		}
20416 		/*
20417 		 * Record current values for parameters we may need to pass
20418 		 * to tcp_send() or tcp_multisend_data(). We checkpoint at
20419 		 * each iteration of the outer loop (each multidata message
20420 		 * creation). If we have a failure in the inner loop, we send
20421 		 * any complete multidata messages we have before reverting
20422 		 * to using the traditional non-md path.
20423 		 */
20424 		snxt_mmd = *snxt;
20425 		usable_mmd = *usable;
20426 		xmit_tail_mmd = *xmit_tail;
20427 		tail_unsent_mmd = *tail_unsent;
20428 		obsegs_mmd = obsegs;
20429 		obbytes_mmd = obbytes;
20430 
20431 		/*
20432 		 * max_pld limits the number of mblks in tcp's transmit
20433 		 * queue that can be added to a Multidata message.  Once
20434 		 * this counter reaches zero, no more additional mblks
20435 		 * can be added to it.  What happens afterwards depends
20436 		 * on whether or not we are set to chain the Multidata
20437 		 * messages.  If we are to link them together, reset
20438 		 * max_pld to its original value (tcp_mdt_max_pld) and
20439 		 * prepare to create a new Multidata message which will
20440 		 * get linked to md_mp_head.  Else, leave it alone and
20441 		 * let the inner loop break on its own.
20442 		 */
20443 		if (tcp_mdt_chain && max_pld == 0)
20444 			PREP_NEW_MULTIDATA();
20445 
20446 		/* adding a payload buffer; re-initialize values */
20447 		if (add_buffer)
20448 			PREP_NEW_PBUF();
20449 
20450 		/*
20451 		 * If we don't have a Multidata, either because we just
20452 		 * (re)entered this outer loop, or after we branched off
20453 		 * to tcp_send above, setup the Multidata and header
20454 		 * buffer to be used.
20455 		 */
20456 		if (md_mp == NULL) {
20457 			int md_hbuflen;
20458 			uint32_t start, stuff;
20459 
20460 			/*
20461 			 * Calculate Multidata header buffer size large enough
20462 			 * to hold all of the headers that can possibly be
20463 			 * sent at this moment.  We'd rather over-estimate
20464 			 * the size than running out of space; this is okay
20465 			 * since this buffer is small anyway.
20466 			 */
20467 			md_hbuflen = (howmany(*usable, mss) + 1) * hdr_frag_sz;
20468 
20469 			/*
20470 			 * Start and stuff offset for partial hardware
20471 			 * checksum offload; these are currently for IPv4.
20472 			 * For full checksum offload, they are set to zero.
20473 			 */
20474 			if ((hwcksum_flags & HCK_PARTIALCKSUM)) {
20475 				if (af == AF_INET) {
20476 					start = IP_SIMPLE_HDR_LENGTH;
20477 					stuff = IP_SIMPLE_HDR_LENGTH +
20478 					    TCP_CHECKSUM_OFFSET;
20479 				} else {
20480 					start = IPV6_HDR_LEN;
20481 					stuff = IPV6_HDR_LEN +
20482 					    TCP_CHECKSUM_OFFSET;
20483 				}
20484 			} else {
20485 				start = stuff = 0;
20486 			}
20487 
20488 			/*
20489 			 * Create the header buffer, Multidata, as well as
20490 			 * any necessary attributes (destination address,
20491 			 * SAP and hardware checksum offload) that should
20492 			 * be associated with the Multidata message.
20493 			 */
20494 			ASSERT(cur_hdr_off == 0);
20495 			if ((md_hbuf = allocb(md_hbuflen, BPRI_HI)) == NULL ||
20496 			    ((md_hbuf->b_wptr += md_hbuflen),
20497 			    (mmd = mmd_alloc(md_hbuf, &md_mp,
20498 			    KM_NOSLEEP)) == NULL) || (tcp_mdt_add_attrs(mmd,
20499 			    /* fastpath mblk */
20500 			    ire->ire_nce->nce_res_mp,
20501 			    /* hardware checksum enabled */
20502 			    (hwcksum_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)),
20503 			    /* hardware checksum offsets */
20504 			    start, stuff, 0,
20505 			    /* hardware checksum flag */
20506 			    hwcksum_flags, tcps) != 0)) {
20507 legacy_send:
20508 				/*
20509 				 * We arrive here from a failure within the
20510 				 * inner (packetizer) loop or we fail one of
20511 				 * the conditionals above. We restore the
20512 				 * previously checkpointed values for:
20513 				 *    xmit_tail
20514 				 *    usable
20515 				 *    tail_unsent
20516 				 *    snxt
20517 				 *    obbytes
20518 				 *    obsegs
20519 				 * We should then be able to dispatch any
20520 				 * complete multidata before reverting to the
20521 				 * traditional path with consistent parameters
20522 				 * (the inner loop updates these as it
20523 				 * iterates).
20524 				 */
20525 				*xmit_tail = xmit_tail_mmd;
20526 				*usable = usable_mmd;
20527 				*tail_unsent = tail_unsent_mmd;
20528 				*snxt = snxt_mmd;
20529 				obbytes = obbytes_mmd;
20530 				obsegs = obsegs_mmd;
20531 				if (md_mp != NULL) {
20532 					/* Unlink message from the chain */
20533 					if (md_mp_head != NULL) {
20534 						err = (intptr_t)rmvb(md_mp_head,
20535 						    md_mp);
20536 						/*
20537 						 * We can't assert that rmvb
20538 						 * did not return -1, since we
20539 						 * may get here before linkb
20540 						 * happens.  We do, however,
20541 						 * check if we just removed the
20542 						 * only element in the list.
20543 						 */
20544 						if (err == 0)
20545 							md_mp_head = NULL;
20546 					}
20547 					/* md_hbuf gets freed automatically */
20548 					TCP_STAT(tcps, tcp_mdt_discarded);
20549 					freeb(md_mp);
20550 				} else {
20551 					/* Either allocb or mmd_alloc failed */
20552 					TCP_STAT(tcps, tcp_mdt_allocfail);
20553 					if (md_hbuf != NULL)
20554 						freeb(md_hbuf);
20555 				}
20556 
20557 				/* send down what we've got so far */
20558 				if (md_mp_head != NULL) {
20559 					tcp_multisend_data(tcp, ire, ill,
20560 					    md_mp_head, obsegs, obbytes,
20561 					    &rconfirm);
20562 				}
20563 legacy_send_no_md:
20564 				if (ire != NULL)
20565 					IRE_REFRELE(ire);
20566 				/*
20567 				 * Too bad; let the legacy path handle this.
20568 				 * We specify INT_MAX for the threshold, since
20569 				 * we gave up with the Multidata processings
20570 				 * and let the old path have it all.
20571 				 */
20572 				TCP_STAT(tcps, tcp_mdt_legacy_all);
20573 				return (tcp_send(q, tcp, mss, tcp_hdr_len,
20574 				    tcp_tcp_hdr_len, num_sack_blk, usable,
20575 				    snxt, tail_unsent, xmit_tail, local_time,
20576 				    INT_MAX));
20577 			}
20578 
20579 			/* link to any existing ones, if applicable */
20580 			TCP_STAT(tcps, tcp_mdt_allocd);
20581 			if (md_mp_head == NULL) {
20582 				md_mp_head = md_mp;
20583 			} else if (tcp_mdt_chain) {
20584 				TCP_STAT(tcps, tcp_mdt_linked);
20585 				linkb(md_mp_head, md_mp);
20586 			}
20587 		}
20588 
20589 		ASSERT(md_mp_head != NULL);
20590 		ASSERT(tcp_mdt_chain || md_mp_head->b_cont == NULL);
20591 		ASSERT(md_mp != NULL && mmd != NULL);
20592 		ASSERT(md_hbuf != NULL);
20593 
20594 		/*
20595 		 * Packetize the transmittable portion of the data block;
20596 		 * each data block is essentially added to the Multidata
20597 		 * as a payload buffer.  We also deal with adding more
20598 		 * than one payload buffers, which happens when the remaining
20599 		 * packetized portion of the current payload buffer is less
20600 		 * than MSS, while the next data block in transmit queue
20601 		 * has enough data to make up for one.  This "spillover"
20602 		 * case essentially creates a split-packet, where portions
20603 		 * of the packet's payload fragments may span across two
20604 		 * virtually discontiguous address blocks.
20605 		 */
20606 		seg_len = mss;
20607 		do {
20608 			len = seg_len;
20609 
20610 			/* one must remain NULL for DTRACE_IP_FASTPATH */
20611 			ipha = NULL;
20612 			ip6h = NULL;
20613 
20614 			ASSERT(len > 0);
20615 			ASSERT(max_pld >= 0);
20616 			ASSERT(!add_buffer || cur_pld_off == 0);
20617 
20618 			/*
20619 			 * First time around for this payload buffer; note
20620 			 * in the case of a spillover, the following has
20621 			 * been done prior to adding the split-packet
20622 			 * descriptor to Multidata, and we don't want to
20623 			 * repeat the process.
20624 			 */
20625 			if (add_buffer) {
20626 				ASSERT(mmd != NULL);
20627 				ASSERT(md_pbuf == NULL);
20628 				ASSERT(md_pbuf_nxt == NULL);
20629 				ASSERT(pbuf_idx == -1 && pbuf_idx_nxt == -1);
20630 
20631 				/*
20632 				 * Have we reached the limit?  We'd get to
20633 				 * this case when we're not chaining the
20634 				 * Multidata messages together, and since
20635 				 * we're done, terminate this loop.
20636 				 */
20637 				if (max_pld == 0)
20638 					break; /* done */
20639 
20640 				if ((md_pbuf = dupb(*xmit_tail)) == NULL) {
20641 					TCP_STAT(tcps, tcp_mdt_allocfail);
20642 					goto legacy_send; /* out_of_mem */
20643 				}
20644 
20645 				if (IS_VMLOANED_MBLK(md_pbuf) && !zcopy &&
20646 				    zc_cap != NULL) {
20647 					if (!ip_md_zcopy_attr(mmd, NULL,
20648 					    zc_cap->ill_zerocopy_flags)) {
20649 						freeb(md_pbuf);
20650 						TCP_STAT(tcps,
20651 						    tcp_mdt_allocfail);
20652 						/* out_of_mem */
20653 						goto legacy_send;
20654 					}
20655 					zcopy = B_TRUE;
20656 				}
20657 
20658 				md_pbuf->b_rptr += base_pld_off;
20659 
20660 				/*
20661 				 * Add a payload buffer to the Multidata; this
20662 				 * operation must not fail, or otherwise our
20663 				 * logic in this routine is broken.  There
20664 				 * is no memory allocation done by the
20665 				 * routine, so any returned failure simply
20666 				 * tells us that we've done something wrong.
20667 				 *
20668 				 * A failure tells us that either we're adding
20669 				 * the same payload buffer more than once, or
20670 				 * we're trying to add more buffers than
20671 				 * allowed (max_pld calculation is wrong).
20672 				 * None of the above cases should happen, and
20673 				 * we panic because either there's horrible
20674 				 * heap corruption, and/or programming mistake.
20675 				 */
20676 				pbuf_idx = mmd_addpldbuf(mmd, md_pbuf);
20677 				if (pbuf_idx < 0) {
20678 					cmn_err(CE_PANIC, "tcp_multisend: "
20679 					    "payload buffer logic error "
20680 					    "detected for tcp %p mmd %p "
20681 					    "pbuf %p (%d)\n",
20682 					    (void *)tcp, (void *)mmd,
20683 					    (void *)md_pbuf, pbuf_idx);
20684 				}
20685 
20686 				ASSERT(max_pld > 0);
20687 				--max_pld;
20688 				add_buffer = B_FALSE;
20689 			}
20690 
20691 			ASSERT(md_mp_head != NULL);
20692 			ASSERT(md_pbuf != NULL);
20693 			ASSERT(md_pbuf_nxt == NULL);
20694 			ASSERT(pbuf_idx != -1);
20695 			ASSERT(pbuf_idx_nxt == -1);
20696 			ASSERT(*usable > 0);
20697 
20698 			/*
20699 			 * We spillover to the next payload buffer only
20700 			 * if all of the following is true:
20701 			 *
20702 			 *   1. There is not enough data on the current
20703 			 *	payload buffer to make up `len',
20704 			 *   2. We are allowed to send `len',
20705 			 *   3. The next payload buffer length is large
20706 			 *	enough to accomodate `spill'.
20707 			 */
20708 			if ((spill = len - *tail_unsent) > 0 &&
20709 			    *usable >= len &&
20710 			    MBLKL((*xmit_tail)->b_cont) >= spill &&
20711 			    max_pld > 0) {
20712 				md_pbuf_nxt = dupb((*xmit_tail)->b_cont);
20713 				if (md_pbuf_nxt == NULL) {
20714 					TCP_STAT(tcps, tcp_mdt_allocfail);
20715 					goto legacy_send; /* out_of_mem */
20716 				}
20717 
20718 				if (IS_VMLOANED_MBLK(md_pbuf_nxt) && !zcopy &&
20719 				    zc_cap != NULL) {
20720 					if (!ip_md_zcopy_attr(mmd, NULL,
20721 					    zc_cap->ill_zerocopy_flags)) {
20722 						freeb(md_pbuf_nxt);
20723 						TCP_STAT(tcps,
20724 						    tcp_mdt_allocfail);
20725 						/* out_of_mem */
20726 						goto legacy_send;
20727 					}
20728 					zcopy = B_TRUE;
20729 				}
20730 
20731 				/*
20732 				 * See comments above on the first call to
20733 				 * mmd_addpldbuf for explanation on the panic.
20734 				 */
20735 				pbuf_idx_nxt = mmd_addpldbuf(mmd, md_pbuf_nxt);
20736 				if (pbuf_idx_nxt < 0) {
20737 					panic("tcp_multisend: "
20738 					    "next payload buffer logic error "
20739 					    "detected for tcp %p mmd %p "
20740 					    "pbuf %p (%d)\n",
20741 					    (void *)tcp, (void *)mmd,
20742 					    (void *)md_pbuf_nxt, pbuf_idx_nxt);
20743 				}
20744 
20745 				ASSERT(max_pld > 0);
20746 				--max_pld;
20747 			} else if (spill > 0) {
20748 				/*
20749 				 * If there's a spillover, but the following
20750 				 * xmit_tail couldn't give us enough octets
20751 				 * to reach "len", then stop the current
20752 				 * Multidata creation and let the legacy
20753 				 * tcp_send() path take over.  We don't want
20754 				 * to send the tiny segment as part of this
20755 				 * Multidata for performance reasons; instead,
20756 				 * we let the legacy path deal with grouping
20757 				 * it with the subsequent small mblks.
20758 				 */
20759 				if (*usable >= len &&
20760 				    MBLKL((*xmit_tail)->b_cont) < spill) {
20761 					max_pld = 0;
20762 					break;	/* done */
20763 				}
20764 
20765 				/*
20766 				 * We can't spillover, and we are near
20767 				 * the end of the current payload buffer,
20768 				 * so send what's left.
20769 				 */
20770 				ASSERT(*tail_unsent > 0);
20771 				len = *tail_unsent;
20772 			}
20773 
20774 			/* tail_unsent is negated if there is a spillover */
20775 			*tail_unsent -= len;
20776 			*usable -= len;
20777 			ASSERT(*usable >= 0);
20778 
20779 			if (*usable < mss)
20780 				seg_len = *usable;
20781 			/*
20782 			 * Sender SWS avoidance; see comments in tcp_send();
20783 			 * everything else is the same, except that we only
20784 			 * do this here if there is no more data to be sent
20785 			 * following the current xmit_tail.  We don't check
20786 			 * for 1-byte urgent data because we shouldn't get
20787 			 * here if TCP_URG_VALID is set.
20788 			 */
20789 			if (*usable > 0 && *usable < mss &&
20790 			    ((md_pbuf_nxt == NULL &&
20791 			    (*xmit_tail)->b_cont == NULL) ||
20792 			    (md_pbuf_nxt != NULL &&
20793 			    (*xmit_tail)->b_cont->b_cont == NULL)) &&
20794 			    seg_len < (tcp->tcp_max_swnd >> 1) &&
20795 			    (tcp->tcp_unsent -
20796 			    ((*snxt + len) - tcp->tcp_snxt)) > seg_len &&
20797 			    !tcp->tcp_zero_win_probe) {
20798 				if ((*snxt + len) == tcp->tcp_snxt &&
20799 				    (*snxt + len) == tcp->tcp_suna) {
20800 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
20801 				}
20802 				done = B_TRUE;
20803 			}
20804 
20805 			/*
20806 			 * Prime pump for IP's checksumming on our behalf;
20807 			 * include the adjustment for a source route if any.
20808 			 * Do this only for software/partial hardware checksum
20809 			 * offload, as this field gets zeroed out later for
20810 			 * the full hardware checksum offload case.
20811 			 */
20812 			if (!(hwcksum_flags & HCK_FULLCKSUM)) {
20813 				cksum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
20814 				cksum = (cksum >> 16) + (cksum & 0xFFFF);
20815 				U16_TO_ABE16(cksum, tcp->tcp_tcph->th_sum);
20816 			}
20817 
20818 			U32_TO_ABE32(*snxt, tcp->tcp_tcph->th_seq);
20819 			*snxt += len;
20820 
20821 			tcp->tcp_tcph->th_flags[0] = TH_ACK;
20822 			/*
20823 			 * We set the PUSH bit only if TCP has no more buffered
20824 			 * data to be transmitted (or if sender SWS avoidance
20825 			 * takes place), as opposed to setting it for every
20826 			 * last packet in the burst.
20827 			 */
20828 			if (done ||
20829 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) == 0)
20830 				tcp->tcp_tcph->th_flags[0] |= TH_PUSH;
20831 
20832 			/*
20833 			 * Set FIN bit if this is our last segment; snxt
20834 			 * already includes its length, and it will not
20835 			 * be adjusted after this point.
20836 			 */
20837 			if (tcp->tcp_valid_bits == TCP_FSS_VALID &&
20838 			    *snxt == tcp->tcp_fss) {
20839 				if (!tcp->tcp_fin_acked) {
20840 					tcp->tcp_tcph->th_flags[0] |= TH_FIN;
20841 					BUMP_MIB(&tcps->tcps_mib,
20842 					    tcpOutControl);
20843 				}
20844 				if (!tcp->tcp_fin_sent) {
20845 					tcp->tcp_fin_sent = B_TRUE;
20846 					/*
20847 					 * tcp state must be ESTABLISHED
20848 					 * in order for us to get here in
20849 					 * the first place.
20850 					 */
20851 					tcp->tcp_state = TCPS_FIN_WAIT_1;
20852 
20853 					/*
20854 					 * Upon returning from this routine,
20855 					 * tcp_wput_data() will set tcp_snxt
20856 					 * to be equal to snxt + tcp_fin_sent.
20857 					 * This is essentially the same as
20858 					 * setting it to tcp_fss + 1.
20859 					 */
20860 				}
20861 			}
20862 
20863 			tcp->tcp_last_sent_len = (ushort_t)len;
20864 
20865 			len += tcp_hdr_len;
20866 			if (tcp->tcp_ipversion == IPV4_VERSION)
20867 				tcp->tcp_ipha->ipha_length = htons(len);
20868 			else
20869 				tcp->tcp_ip6h->ip6_plen = htons(len -
20870 				    ((char *)&tcp->tcp_ip6h[1] -
20871 				    tcp->tcp_iphc));
20872 
20873 			pkt_info->flags = (PDESC_HBUF_REF | PDESC_PBUF_REF);
20874 
20875 			/* setup header fragment */
20876 			PDESC_HDR_ADD(pkt_info,
20877 			    md_hbuf->b_rptr + cur_hdr_off,	/* base */
20878 			    tcp->tcp_mdt_hdr_head,		/* head room */
20879 			    tcp_hdr_len,			/* len */
20880 			    tcp->tcp_mdt_hdr_tail);		/* tail room */
20881 
20882 			ASSERT(pkt_info->hdr_lim - pkt_info->hdr_base ==
20883 			    hdr_frag_sz);
20884 			ASSERT(MBLKIN(md_hbuf,
20885 			    (pkt_info->hdr_base - md_hbuf->b_rptr),
20886 			    PDESC_HDRSIZE(pkt_info)));
20887 
20888 			/* setup first payload fragment */
20889 			PDESC_PLD_INIT(pkt_info);
20890 			PDESC_PLD_SPAN_ADD(pkt_info,
20891 			    pbuf_idx,				/* index */
20892 			    md_pbuf->b_rptr + cur_pld_off,	/* start */
20893 			    tcp->tcp_last_sent_len);		/* len */
20894 
20895 			/* create a split-packet in case of a spillover */
20896 			if (md_pbuf_nxt != NULL) {
20897 				ASSERT(spill > 0);
20898 				ASSERT(pbuf_idx_nxt > pbuf_idx);
20899 				ASSERT(!add_buffer);
20900 
20901 				md_pbuf = md_pbuf_nxt;
20902 				md_pbuf_nxt = NULL;
20903 				pbuf_idx = pbuf_idx_nxt;
20904 				pbuf_idx_nxt = -1;
20905 				cur_pld_off = spill;
20906 
20907 				/* trim out first payload fragment */
20908 				PDESC_PLD_SPAN_TRIM(pkt_info, 0, spill);
20909 
20910 				/* setup second payload fragment */
20911 				PDESC_PLD_SPAN_ADD(pkt_info,
20912 				    pbuf_idx,			/* index */
20913 				    md_pbuf->b_rptr,		/* start */
20914 				    spill);			/* len */
20915 
20916 				if ((*xmit_tail)->b_next == NULL) {
20917 					/*
20918 					 * Store the lbolt used for RTT
20919 					 * estimation. We can only record one
20920 					 * timestamp per mblk so we do it when
20921 					 * we reach the end of the payload
20922 					 * buffer.  Also we only take a new
20923 					 * timestamp sample when the previous
20924 					 * timed data from the same mblk has
20925 					 * been ack'ed.
20926 					 */
20927 					(*xmit_tail)->b_prev = local_time;
20928 					(*xmit_tail)->b_next =
20929 					    (mblk_t *)(uintptr_t)first_snxt;
20930 				}
20931 
20932 				first_snxt = *snxt - spill;
20933 
20934 				/*
20935 				 * Advance xmit_tail; usable could be 0 by
20936 				 * the time we got here, but we made sure
20937 				 * above that we would only spillover to
20938 				 * the next data block if usable includes
20939 				 * the spilled-over amount prior to the
20940 				 * subtraction.  Therefore, we are sure
20941 				 * that xmit_tail->b_cont can't be NULL.
20942 				 */
20943 				ASSERT((*xmit_tail)->b_cont != NULL);
20944 				*xmit_tail = (*xmit_tail)->b_cont;
20945 				ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
20946 				    (uintptr_t)INT_MAX);
20947 				*tail_unsent = (int)MBLKL(*xmit_tail) - spill;
20948 			} else {
20949 				cur_pld_off += tcp->tcp_last_sent_len;
20950 			}
20951 
20952 			/*
20953 			 * Fill in the header using the template header, and
20954 			 * add options such as time-stamp, ECN and/or SACK,
20955 			 * as needed.
20956 			 */
20957 			tcp_fill_header(tcp, pkt_info->hdr_rptr,
20958 			    (clock_t)local_time, num_sack_blk);
20959 
20960 			/* take care of some IP header businesses */
20961 			if (af == AF_INET) {
20962 				ipha = (ipha_t *)pkt_info->hdr_rptr;
20963 
20964 				ASSERT(OK_32PTR((uchar_t *)ipha));
20965 				ASSERT(PDESC_HDRL(pkt_info) >=
20966 				    IP_SIMPLE_HDR_LENGTH);
20967 				ASSERT(ipha->ipha_version_and_hdr_length ==
20968 				    IP_SIMPLE_HDR_VERSION);
20969 
20970 				/*
20971 				 * Assign ident value for current packet; see
20972 				 * related comments in ip_wput_ire() about the
20973 				 * contract private interface with clustering
20974 				 * group.
20975 				 */
20976 				clusterwide = B_FALSE;
20977 				if (cl_inet_ipident != NULL) {
20978 					ASSERT(cl_inet_isclusterwide != NULL);
20979 					if ((*cl_inet_isclusterwide)(IPPROTO_IP,
20980 					    AF_INET,
20981 					    (uint8_t *)(uintptr_t)src)) {
20982 						ipha->ipha_ident =
20983 						    (*cl_inet_ipident)
20984 						    (IPPROTO_IP, AF_INET,
20985 						    (uint8_t *)(uintptr_t)src,
20986 						    (uint8_t *)(uintptr_t)dst);
20987 						clusterwide = B_TRUE;
20988 					}
20989 				}
20990 
20991 				if (!clusterwide) {
20992 					ipha->ipha_ident = (uint16_t)
20993 					    atomic_add_32_nv(
20994 						&ire->ire_ident, 1);
20995 				}
20996 #ifndef _BIG_ENDIAN
20997 				ipha->ipha_ident = (ipha->ipha_ident << 8) |
20998 				    (ipha->ipha_ident >> 8);
20999 #endif
21000 			} else {
21001 				ip6h = (ip6_t *)pkt_info->hdr_rptr;
21002 
21003 				ASSERT(OK_32PTR((uchar_t *)ip6h));
21004 				ASSERT(IPVER(ip6h) == IPV6_VERSION);
21005 				ASSERT(ip6h->ip6_nxt == IPPROTO_TCP);
21006 				ASSERT(PDESC_HDRL(pkt_info) >=
21007 				    (IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET +
21008 				    TCP_CHECKSUM_SIZE));
21009 				ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21010 
21011 				if (tcp->tcp_ip_forward_progress) {
21012 					rconfirm = B_TRUE;
21013 					tcp->tcp_ip_forward_progress = B_FALSE;
21014 				}
21015 			}
21016 
21017 			/* at least one payload span, and at most two */
21018 			ASSERT(pkt_info->pld_cnt > 0 && pkt_info->pld_cnt < 3);
21019 
21020 			/* add the packet descriptor to Multidata */
21021 			if ((pkt = mmd_addpdesc(mmd, pkt_info, &err,
21022 			    KM_NOSLEEP)) == NULL) {
21023 				/*
21024 				 * Any failure other than ENOMEM indicates
21025 				 * that we have passed in invalid pkt_info
21026 				 * or parameters to mmd_addpdesc, which must
21027 				 * not happen.
21028 				 *
21029 				 * EINVAL is a result of failure on boundary
21030 				 * checks against the pkt_info contents.  It
21031 				 * should not happen, and we panic because
21032 				 * either there's horrible heap corruption,
21033 				 * and/or programming mistake.
21034 				 */
21035 				if (err != ENOMEM) {
21036 					cmn_err(CE_PANIC, "tcp_multisend: "
21037 					    "pdesc logic error detected for "
21038 					    "tcp %p mmd %p pinfo %p (%d)\n",
21039 					    (void *)tcp, (void *)mmd,
21040 					    (void *)pkt_info, err);
21041 				}
21042 				TCP_STAT(tcps, tcp_mdt_addpdescfail);
21043 				goto legacy_send; /* out_of_mem */
21044 			}
21045 			ASSERT(pkt != NULL);
21046 
21047 			/* calculate IP header and TCP checksums */
21048 			if (af == AF_INET) {
21049 				/* calculate pseudo-header checksum */
21050 				cksum = (dst >> 16) + (dst & 0xFFFF) +
21051 				    (src >> 16) + (src & 0xFFFF);
21052 
21053 				/* offset for TCP header checksum */
21054 				up = IPH_TCPH_CHECKSUMP(ipha,
21055 				    IP_SIMPLE_HDR_LENGTH);
21056 			} else {
21057 				up = (uint16_t *)&ip6h->ip6_src;
21058 
21059 				/* calculate pseudo-header checksum */
21060 				cksum = up[0] + up[1] + up[2] + up[3] +
21061 				    up[4] + up[5] + up[6] + up[7] +
21062 				    up[8] + up[9] + up[10] + up[11] +
21063 				    up[12] + up[13] + up[14] + up[15];
21064 
21065 				/* Fold the initial sum */
21066 				cksum = (cksum & 0xffff) + (cksum >> 16);
21067 
21068 				up = (uint16_t *)(((uchar_t *)ip6h) +
21069 				    IPV6_HDR_LEN + TCP_CHECKSUM_OFFSET);
21070 			}
21071 
21072 			if (hwcksum_flags & HCK_FULLCKSUM) {
21073 				/* clear checksum field for hardware */
21074 				*up = 0;
21075 			} else if (hwcksum_flags & HCK_PARTIALCKSUM) {
21076 				uint32_t sum;
21077 
21078 				/* pseudo-header checksumming */
21079 				sum = *up + cksum + IP_TCP_CSUM_COMP;
21080 				sum = (sum & 0xFFFF) + (sum >> 16);
21081 				*up = (sum & 0xFFFF) + (sum >> 16);
21082 			} else {
21083 				/* software checksumming */
21084 				TCP_STAT(tcps, tcp_out_sw_cksum);
21085 				TCP_STAT_UPDATE(tcps, tcp_out_sw_cksum_bytes,
21086 				    tcp->tcp_hdr_len + tcp->tcp_last_sent_len);
21087 				*up = IP_MD_CSUM(pkt, tcp->tcp_ip_hdr_len,
21088 				    cksum + IP_TCP_CSUM_COMP);
21089 				if (*up == 0)
21090 					*up = 0xFFFF;
21091 			}
21092 
21093 			/* IPv4 header checksum */
21094 			if (af == AF_INET) {
21095 				if (hwcksum_flags & HCK_IPV4_HDRCKSUM) {
21096 					ipha->ipha_hdr_checksum = 0;
21097 				} else {
21098 					IP_HDR_CKSUM(ipha, cksum,
21099 					    ((uint32_t *)ipha)[0],
21100 					    ((uint16_t *)ipha)[4]);
21101 				}
21102 			}
21103 
21104 			if (af == AF_INET &&
21105 			    HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) ||
21106 			    af == AF_INET6 &&
21107 			    HOOKS6_INTERESTED_PHYSICAL_OUT(ipst)) {
21108 				mblk_t	*mp, *mp1;
21109 				uchar_t	*hdr_rptr, *hdr_wptr;
21110 				uchar_t	*pld_rptr, *pld_wptr;
21111 
21112 				/*
21113 				 * We reconstruct a pseudo packet for the hooks
21114 				 * framework using mmd_transform_link().
21115 				 * If it is a split packet we pullup the
21116 				 * payload. FW_HOOKS expects a pkt comprising
21117 				 * of two mblks: a header and the payload.
21118 				 */
21119 				if ((mp = mmd_transform_link(pkt)) == NULL) {
21120 					TCP_STAT(tcps, tcp_mdt_allocfail);
21121 					goto legacy_send;
21122 				}
21123 
21124 				if (pkt_info->pld_cnt > 1) {
21125 					/* split payload, more than one pld */
21126 					if ((mp1 = msgpullup(mp->b_cont, -1)) ==
21127 					    NULL) {
21128 						freemsg(mp);
21129 						TCP_STAT(tcps,
21130 						    tcp_mdt_allocfail);
21131 						goto legacy_send;
21132 					}
21133 					freemsg(mp->b_cont);
21134 					mp->b_cont = mp1;
21135 				} else {
21136 					mp1 = mp->b_cont;
21137 				}
21138 				ASSERT(mp1 != NULL && mp1->b_cont == NULL);
21139 
21140 				/*
21141 				 * Remember the message offsets. This is so we
21142 				 * can detect changes when we return from the
21143 				 * FW_HOOKS callbacks.
21144 				 */
21145 				hdr_rptr = mp->b_rptr;
21146 				hdr_wptr = mp->b_wptr;
21147 				pld_rptr = mp->b_cont->b_rptr;
21148 				pld_wptr = mp->b_cont->b_wptr;
21149 
21150 				if (af == AF_INET) {
21151 					DTRACE_PROBE4(
21152 					    ip4__physical__out__start,
21153 					    ill_t *, NULL,
21154 					    ill_t *, ill,
21155 					    ipha_t *, ipha,
21156 					    mblk_t *, mp);
21157 					FW_HOOKS(
21158 					    ipst->ips_ip4_physical_out_event,
21159 					    ipst->ips_ipv4firewall_physical_out,
21160 					    NULL, ill, ipha, mp, mp, 0, ipst);
21161 					DTRACE_PROBE1(
21162 					    ip4__physical__out__end,
21163 					    mblk_t *, mp);
21164 				} else {
21165 					DTRACE_PROBE4(
21166 					    ip6__physical__out_start,
21167 					    ill_t *, NULL,
21168 					    ill_t *, ill,
21169 					    ip6_t *, ip6h,
21170 					    mblk_t *, mp);
21171 					FW_HOOKS6(
21172 					    ipst->ips_ip6_physical_out_event,
21173 					    ipst->ips_ipv6firewall_physical_out,
21174 					    NULL, ill, ip6h, mp, mp, 0, ipst);
21175 					DTRACE_PROBE1(
21176 					    ip6__physical__out__end,
21177 					    mblk_t *, mp);
21178 				}
21179 
21180 				if (mp == NULL ||
21181 				    (mp1 = mp->b_cont) == NULL ||
21182 				    mp->b_rptr != hdr_rptr ||
21183 				    mp->b_wptr != hdr_wptr ||
21184 				    mp1->b_rptr != pld_rptr ||
21185 				    mp1->b_wptr != pld_wptr ||
21186 				    mp1->b_cont != NULL) {
21187 					/*
21188 					 * We abandon multidata processing and
21189 					 * return to the normal path, either
21190 					 * when a packet is blocked, or when
21191 					 * the boundaries of header buffer or
21192 					 * payload buffer have been changed by
21193 					 * FW_HOOKS[6].
21194 					 */
21195 					if (mp != NULL)
21196 						freemsg(mp);
21197 					goto legacy_send;
21198 				}
21199 				/* Finished with the pseudo packet */
21200 				freemsg(mp);
21201 			}
21202 			DTRACE_IP_FASTPATH(md_hbuf, pkt_info->hdr_rptr,
21203 			    ill, ipha, ip6h);
21204 			/* advance header offset */
21205 			cur_hdr_off += hdr_frag_sz;
21206 
21207 			obbytes += tcp->tcp_last_sent_len;
21208 			++obsegs;
21209 		} while (!done && *usable > 0 && --num_burst_seg > 0 &&
21210 		    *tail_unsent > 0);
21211 
21212 		if ((*xmit_tail)->b_next == NULL) {
21213 			/*
21214 			 * Store the lbolt used for RTT estimation. We can only
21215 			 * record one timestamp per mblk so we do it when we
21216 			 * reach the end of the payload buffer. Also we only
21217 			 * take a new timestamp sample when the previous timed
21218 			 * data from the same mblk has been ack'ed.
21219 			 */
21220 			(*xmit_tail)->b_prev = local_time;
21221 			(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)first_snxt;
21222 		}
21223 
21224 		ASSERT(*tail_unsent >= 0);
21225 		if (*tail_unsent > 0) {
21226 			/*
21227 			 * We got here because we broke out of the above
21228 			 * loop due to of one of the following cases:
21229 			 *
21230 			 *   1. len < adjusted MSS (i.e. small),
21231 			 *   2. Sender SWS avoidance,
21232 			 *   3. max_pld is zero.
21233 			 *
21234 			 * We are done for this Multidata, so trim our
21235 			 * last payload buffer (if any) accordingly.
21236 			 */
21237 			if (md_pbuf != NULL)
21238 				md_pbuf->b_wptr -= *tail_unsent;
21239 		} else if (*usable > 0) {
21240 			*xmit_tail = (*xmit_tail)->b_cont;
21241 			ASSERT((uintptr_t)MBLKL(*xmit_tail) <=
21242 			    (uintptr_t)INT_MAX);
21243 			*tail_unsent = (int)MBLKL(*xmit_tail);
21244 			add_buffer = B_TRUE;
21245 		}
21246 	} while (!done && *usable > 0 && num_burst_seg > 0 &&
21247 	    (tcp_mdt_chain || max_pld > 0));
21248 
21249 	if (md_mp_head != NULL) {
21250 		/* send everything down */
21251 		tcp_multisend_data(tcp, ire, ill, md_mp_head, obsegs, obbytes,
21252 		    &rconfirm);
21253 	}
21254 
21255 #undef PREP_NEW_MULTIDATA
21256 #undef PREP_NEW_PBUF
21257 #undef IPVER
21258 
21259 	IRE_REFRELE(ire);
21260 	return (0);
21261 }
21262 
21263 /*
21264  * A wrapper function for sending one or more Multidata messages down to
21265  * the module below ip; this routine does not release the reference of the
21266  * IRE (caller does that).  This routine is analogous to tcp_send_data().
21267  */
21268 static void
21269 tcp_multisend_data(tcp_t *tcp, ire_t *ire, const ill_t *ill, mblk_t *md_mp_head,
21270     const uint_t obsegs, const uint_t obbytes, boolean_t *rconfirm)
21271 {
21272 	uint64_t delta;
21273 	nce_t *nce;
21274 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21275 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21276 
21277 	ASSERT(ire != NULL && ill != NULL);
21278 	ASSERT(ire->ire_stq != NULL);
21279 	ASSERT(md_mp_head != NULL);
21280 	ASSERT(rconfirm != NULL);
21281 
21282 	/* adjust MIBs and IRE timestamp */
21283 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, md_mp_head, tcp_t *, tcp);
21284 	tcp->tcp_obsegs += obsegs;
21285 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataSegs, obsegs);
21286 	UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, obbytes);
21287 	TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out, obsegs);
21288 
21289 	if (tcp->tcp_ipversion == IPV4_VERSION) {
21290 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v4, obsegs);
21291 	} else {
21292 		TCP_STAT_UPDATE(tcps, tcp_mdt_pkt_out_v6, obsegs);
21293 	}
21294 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests, obsegs);
21295 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, obsegs);
21296 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, obbytes);
21297 
21298 	ire->ire_ob_pkt_count += obsegs;
21299 	if (ire->ire_ipif != NULL)
21300 		atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, obsegs);
21301 	ire->ire_last_used_time = lbolt;
21302 
21303 	if (ipst->ips_ipobs_enabled) {
21304 		multidata_t *dlmdp = mmd_getmultidata(md_mp_head);
21305 		pdesc_t *dl_pkt;
21306 		pdescinfo_t pinfo;
21307 		mblk_t *nmp;
21308 		zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21309 
21310 		for (dl_pkt = mmd_getfirstpdesc(dlmdp, &pinfo);
21311 		    (dl_pkt != NULL);
21312 		    dl_pkt = mmd_getnextpdesc(dl_pkt, &pinfo)) {
21313 			if ((nmp = mmd_transform_link(dl_pkt)) == NULL)
21314 				continue;
21315 			ipobs_hook(nmp, IPOBS_HOOK_OUTBOUND, szone,
21316 			    ALL_ZONES, ill, tcp->tcp_ipversion, 0, ipst);
21317 			freemsg(nmp);
21318 		}
21319 	}
21320 
21321 	/* send it down */
21322 	if (ILL_DLS_CAPABLE(ill)) {
21323 		ill_dls_capab_t *ill_dls = ill->ill_dls_capab;
21324 		ill_dls->ill_tx(ill_dls->ill_tx_handle, md_mp_head);
21325 	} else {
21326 		putnext(ire->ire_stq, md_mp_head);
21327 	}
21328 
21329 	/* we're done for TCP/IPv4 */
21330 	if (tcp->tcp_ipversion == IPV4_VERSION)
21331 		return;
21332 
21333 	nce = ire->ire_nce;
21334 
21335 	ASSERT(nce != NULL);
21336 	ASSERT(!(nce->nce_flags & (NCE_F_NONUD|NCE_F_PERMANENT)));
21337 	ASSERT(nce->nce_state != ND_INCOMPLETE);
21338 
21339 	/* reachability confirmation? */
21340 	if (*rconfirm) {
21341 		nce->nce_last = TICK_TO_MSEC(lbolt64);
21342 		if (nce->nce_state != ND_REACHABLE) {
21343 			mutex_enter(&nce->nce_lock);
21344 			nce->nce_state = ND_REACHABLE;
21345 			nce->nce_pcnt = ND_MAX_UNICAST_SOLICIT;
21346 			mutex_exit(&nce->nce_lock);
21347 			(void) untimeout(nce->nce_timeout_id);
21348 			if (ip_debug > 2) {
21349 				/* ip1dbg */
21350 				pr_addr_dbg("tcp_multisend_data: state "
21351 				    "for %s changed to REACHABLE\n",
21352 				    AF_INET6, &ire->ire_addr_v6);
21353 			}
21354 		}
21355 		/* reset transport reachability confirmation */
21356 		*rconfirm = B_FALSE;
21357 	}
21358 
21359 	delta =  TICK_TO_MSEC(lbolt64) - nce->nce_last;
21360 	ip1dbg(("tcp_multisend_data: delta = %" PRId64
21361 	    " ill_reachable_time = %d \n", delta, ill->ill_reachable_time));
21362 
21363 	if (delta > (uint64_t)ill->ill_reachable_time) {
21364 		mutex_enter(&nce->nce_lock);
21365 		switch (nce->nce_state) {
21366 		case ND_REACHABLE:
21367 		case ND_STALE:
21368 			/*
21369 			 * ND_REACHABLE is identical to ND_STALE in this
21370 			 * specific case. If reachable time has expired for
21371 			 * this neighbor (delta is greater than reachable
21372 			 * time), conceptually, the neighbor cache is no
21373 			 * longer in REACHABLE state, but already in STALE
21374 			 * state.  So the correct transition here is to
21375 			 * ND_DELAY.
21376 			 */
21377 			nce->nce_state = ND_DELAY;
21378 			mutex_exit(&nce->nce_lock);
21379 			NDP_RESTART_TIMER(nce,
21380 			    ipst->ips_delay_first_probe_time);
21381 			if (ip_debug > 3) {
21382 				/* ip2dbg */
21383 				pr_addr_dbg("tcp_multisend_data: state "
21384 				    "for %s changed to DELAY\n",
21385 				    AF_INET6, &ire->ire_addr_v6);
21386 			}
21387 			break;
21388 		case ND_DELAY:
21389 		case ND_PROBE:
21390 			mutex_exit(&nce->nce_lock);
21391 			/* Timers have already started */
21392 			break;
21393 		case ND_UNREACHABLE:
21394 			/*
21395 			 * ndp timer has detected that this nce is
21396 			 * unreachable and initiated deleting this nce
21397 			 * and all its associated IREs. This is a race
21398 			 * where we found the ire before it was deleted
21399 			 * and have just sent out a packet using this
21400 			 * unreachable nce.
21401 			 */
21402 			mutex_exit(&nce->nce_lock);
21403 			break;
21404 		default:
21405 			ASSERT(0);
21406 		}
21407 	}
21408 }
21409 
21410 /*
21411  * Derived from tcp_send_data().
21412  */
21413 static void
21414 tcp_lsosend_data(tcp_t *tcp, mblk_t *mp, ire_t *ire, ill_t *ill, const int mss,
21415     int num_lso_seg)
21416 {
21417 	ipha_t		*ipha;
21418 	mblk_t		*ire_fp_mp;
21419 	uint_t		ire_fp_mp_len;
21420 	uint32_t	hcksum_txflags = 0;
21421 	ipaddr_t	src;
21422 	ipaddr_t	dst;
21423 	uint32_t	cksum;
21424 	uint16_t	*up;
21425 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21426 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
21427 
21428 	ASSERT(DB_TYPE(mp) == M_DATA);
21429 	ASSERT(tcp->tcp_state == TCPS_ESTABLISHED);
21430 	ASSERT(tcp->tcp_ipversion == IPV4_VERSION);
21431 	ASSERT(tcp->tcp_connp != NULL);
21432 	ASSERT(CONN_IS_LSO_MD_FASTPATH(tcp->tcp_connp));
21433 
21434 	ipha = (ipha_t *)mp->b_rptr;
21435 	src = ipha->ipha_src;
21436 	dst = ipha->ipha_dst;
21437 
21438 	DTRACE_PROBE2(tcp__trace__send, mblk_t *, mp, tcp_t *, tcp);
21439 
21440 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
21441 	ipha->ipha_ident = (uint16_t)atomic_add_32_nv(&ire->ire_ident,
21442 	    num_lso_seg);
21443 #ifndef _BIG_ENDIAN
21444 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
21445 #endif
21446 	if (tcp->tcp_snd_zcopy_aware) {
21447 		if ((ill->ill_capabilities & ILL_CAPAB_ZEROCOPY) == 0 ||
21448 		    (ill->ill_zerocopy_capab->ill_zerocopy_flags == 0))
21449 			mp = tcp_zcopy_disable(tcp, mp);
21450 	}
21451 
21452 	if (ILL_HCKSUM_CAPABLE(ill) && dohwcksum) {
21453 		ASSERT(ill->ill_hcksum_capab != NULL);
21454 		hcksum_txflags = ill->ill_hcksum_capab->ill_hcksum_txflags;
21455 	}
21456 
21457 	/*
21458 	 * Since the TCP checksum should be recalculated by h/w, we can just
21459 	 * zero the checksum field for HCK_FULLCKSUM, or calculate partial
21460 	 * pseudo-header checksum for HCK_PARTIALCKSUM.
21461 	 * The partial pseudo-header excludes TCP length, that was calculated
21462 	 * in tcp_send(), so to zero *up before further processing.
21463 	 */
21464 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
21465 
21466 	up = IPH_TCPH_CHECKSUMP(ipha, IP_SIMPLE_HDR_LENGTH);
21467 	*up = 0;
21468 
21469 	IP_CKSUM_XMIT_FAST(ire->ire_ipversion, hcksum_txflags, mp, ipha, up,
21470 	    IPPROTO_TCP, IP_SIMPLE_HDR_LENGTH, ntohs(ipha->ipha_length), cksum);
21471 
21472 	/*
21473 	 * Append LSO flag to DB_LSOFLAGS(mp) and set the mss to DB_LSOMSS(mp).
21474 	 */
21475 	DB_LSOFLAGS(mp) |= HW_LSO;
21476 	DB_LSOMSS(mp) = mss;
21477 
21478 	ire_fp_mp = ire->ire_nce->nce_fp_mp;
21479 	ire_fp_mp_len = MBLKL(ire_fp_mp);
21480 	ASSERT(DB_TYPE(ire_fp_mp) == M_DATA);
21481 	mp->b_rptr = (uchar_t *)ipha - ire_fp_mp_len;
21482 	bcopy(ire_fp_mp->b_rptr, mp->b_rptr, ire_fp_mp_len);
21483 
21484 	UPDATE_OB_PKT_COUNT(ire);
21485 	ire->ire_last_used_time = lbolt;
21486 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
21487 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
21488 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
21489 	    ntohs(ipha->ipha_length));
21490 
21491 	if (ILL_DLS_CAPABLE(ill)) {
21492 		/*
21493 		 * Send the packet directly to DLD, where it may be queued
21494 		 * depending on the availability of transmit resources at
21495 		 * the media layer.
21496 		 */
21497 		IP_DLS_ILL_TX(ill, ipha, mp, ipst, ire_fp_mp_len);
21498 	} else {
21499 		ill_t *out_ill = (ill_t *)ire->ire_stq->q_ptr;
21500 		DTRACE_PROBE4(ip4__physical__out__start,
21501 		    ill_t *, NULL, ill_t *, out_ill,
21502 		    ipha_t *, ipha, mblk_t *, mp);
21503 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
21504 		    ipst->ips_ipv4firewall_physical_out,
21505 		    NULL, out_ill, ipha, mp, mp, 0, ipst);
21506 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
21507 
21508 		if (mp != NULL) {
21509 			if (ipst->ips_ipobs_enabled) {
21510 				zoneid_t szone = tcp->tcp_connp->conn_zoneid;
21511 
21512 				ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
21513 				    ALL_ZONES, ill, tcp->tcp_ipversion,
21514 				    ire_fp_mp_len, ipst);
21515 			}
21516 			DTRACE_IP_FASTPATH(mp, ipha, out_ill, ipha, NULL);
21517 			putnext(ire->ire_stq, mp);
21518 		}
21519 	}
21520 }
21521 
21522 /*
21523  * tcp_send() is called by tcp_wput_data() for non-Multidata transmission
21524  * scheme, and returns one of the following:
21525  *
21526  * -1 = failed allocation.
21527  *  0 = success; burst count reached, or usable send window is too small,
21528  *      and that we'd rather wait until later before sending again.
21529  *  1 = success; we are called from tcp_multisend(), and both usable send
21530  *      window and tail_unsent are greater than the MDT threshold, and thus
21531  *      Multidata Transmit should be used instead.
21532  */
21533 static int
21534 tcp_send(queue_t *q, tcp_t *tcp, const int mss, const int tcp_hdr_len,
21535     const int tcp_tcp_hdr_len, const int num_sack_blk, int *usable,
21536     uint_t *snxt, int *tail_unsent, mblk_t **xmit_tail, mblk_t *local_time,
21537     const int mdt_thres)
21538 {
21539 	int num_burst_seg = tcp->tcp_snd_burst;
21540 	ire_t		*ire = NULL;
21541 	ill_t		*ill = NULL;
21542 	mblk_t		*ire_fp_mp = NULL;
21543 	uint_t		ire_fp_mp_len = 0;
21544 	int		num_lso_seg = 1;
21545 	uint_t		lso_usable;
21546 	boolean_t	do_lso_send = B_FALSE;
21547 	tcp_stack_t	*tcps = tcp->tcp_tcps;
21548 
21549 	/*
21550 	 * Check LSO capability before any further work. And the similar check
21551 	 * need to be done in for(;;) loop.
21552 	 * LSO will be deployed when therer is more than one mss of available
21553 	 * data and a burst transmission is allowed.
21554 	 */
21555 	if (tcp->tcp_lso &&
21556 	    (tcp->tcp_valid_bits == 0 ||
21557 	    tcp->tcp_valid_bits == TCP_FSS_VALID) &&
21558 	    num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21559 		/*
21560 		 * Try to find usable IRE/ILL and do basic check to the ILL.
21561 		 */
21562 		if (tcp_send_find_ire_ill(tcp, NULL, &ire, &ill)) {
21563 			/*
21564 			 * Enable LSO with this transmission.
21565 			 * Since IRE has been hold in
21566 			 * tcp_send_find_ire_ill(), IRE_REFRELE(ire)
21567 			 * should be called before return.
21568 			 */
21569 			do_lso_send = B_TRUE;
21570 			ire_fp_mp = ire->ire_nce->nce_fp_mp;
21571 			ire_fp_mp_len = MBLKL(ire_fp_mp);
21572 			/* Round up to multiple of 4 */
21573 			ire_fp_mp_len = ((ire_fp_mp_len + 3) / 4) * 4;
21574 		} else {
21575 			do_lso_send = B_FALSE;
21576 			ill = NULL;
21577 		}
21578 	}
21579 
21580 	for (;;) {
21581 		struct datab	*db;
21582 		tcph_t		*tcph;
21583 		uint32_t	sum;
21584 		mblk_t		*mp, *mp1;
21585 		uchar_t		*rptr;
21586 		int		len;
21587 
21588 		/*
21589 		 * If we're called by tcp_multisend(), and the amount of
21590 		 * sendable data as well as the size of current xmit_tail
21591 		 * is beyond the MDT threshold, return to the caller and
21592 		 * let the large data transmit be done using MDT.
21593 		 */
21594 		if (*usable > 0 && *usable > mdt_thres &&
21595 		    (*tail_unsent > mdt_thres || (*tail_unsent == 0 &&
21596 		    MBLKL((*xmit_tail)->b_cont) > mdt_thres))) {
21597 			ASSERT(tcp->tcp_mdt);
21598 			return (1);	/* success; do large send */
21599 		}
21600 
21601 		if (num_burst_seg == 0)
21602 			break;		/* success; burst count reached */
21603 
21604 		/*
21605 		 * Calculate the maximum payload length we can send in *one*
21606 		 * time.
21607 		 */
21608 		if (do_lso_send) {
21609 			/*
21610 			 * Check whether need to do LSO any more.
21611 			 */
21612 			if (num_burst_seg >= 2 && (*usable - 1) / mss >= 1) {
21613 				lso_usable = MIN(tcp->tcp_lso_max, *usable);
21614 				lso_usable = MIN(lso_usable,
21615 				    num_burst_seg * mss);
21616 
21617 				num_lso_seg = lso_usable / mss;
21618 				if (lso_usable % mss) {
21619 					num_lso_seg++;
21620 					tcp->tcp_last_sent_len = (ushort_t)
21621 					    (lso_usable % mss);
21622 				} else {
21623 					tcp->tcp_last_sent_len = (ushort_t)mss;
21624 				}
21625 			} else {
21626 				do_lso_send = B_FALSE;
21627 				num_lso_seg = 1;
21628 				lso_usable = mss;
21629 			}
21630 		}
21631 
21632 		ASSERT(num_lso_seg <= IP_MAXPACKET / mss + 1);
21633 
21634 		/*
21635 		 * Adjust num_burst_seg here.
21636 		 */
21637 		num_burst_seg -= num_lso_seg;
21638 
21639 		len = mss;
21640 		if (len > *usable) {
21641 			ASSERT(do_lso_send == B_FALSE);
21642 
21643 			len = *usable;
21644 			if (len <= 0) {
21645 				/* Terminate the loop */
21646 				break;	/* success; too small */
21647 			}
21648 			/*
21649 			 * Sender silly-window avoidance.
21650 			 * Ignore this if we are going to send a
21651 			 * zero window probe out.
21652 			 *
21653 			 * TODO: force data into microscopic window?
21654 			 *	==> (!pushed || (unsent > usable))
21655 			 */
21656 			if (len < (tcp->tcp_max_swnd >> 1) &&
21657 			    (tcp->tcp_unsent - (*snxt - tcp->tcp_snxt)) > len &&
21658 			    !((tcp->tcp_valid_bits & TCP_URG_VALID) &&
21659 			    len == 1) && (! tcp->tcp_zero_win_probe)) {
21660 				/*
21661 				 * If the retransmit timer is not running
21662 				 * we start it so that we will retransmit
21663 				 * in the case when the the receiver has
21664 				 * decremented the window.
21665 				 */
21666 				if (*snxt == tcp->tcp_snxt &&
21667 				    *snxt == tcp->tcp_suna) {
21668 					/*
21669 					 * We are not supposed to send
21670 					 * anything.  So let's wait a little
21671 					 * bit longer before breaking SWS
21672 					 * avoidance.
21673 					 *
21674 					 * What should the value be?
21675 					 * Suggestion: MAX(init rexmit time,
21676 					 * tcp->tcp_rto)
21677 					 */
21678 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
21679 				}
21680 				break;	/* success; too small */
21681 			}
21682 		}
21683 
21684 		tcph = tcp->tcp_tcph;
21685 
21686 		/*
21687 		 * The reason to adjust len here is that we need to set flags
21688 		 * and calculate checksum.
21689 		 */
21690 		if (do_lso_send)
21691 			len = lso_usable;
21692 
21693 		*usable -= len; /* Approximate - can be adjusted later */
21694 		if (*usable > 0)
21695 			tcph->th_flags[0] = TH_ACK;
21696 		else
21697 			tcph->th_flags[0] = (TH_ACK | TH_PUSH);
21698 
21699 		/*
21700 		 * Prime pump for IP's checksumming on our behalf
21701 		 * Include the adjustment for a source route if any.
21702 		 */
21703 		sum = len + tcp_tcp_hdr_len + tcp->tcp_sum;
21704 		sum = (sum >> 16) + (sum & 0xFFFF);
21705 		U16_TO_ABE16(sum, tcph->th_sum);
21706 
21707 		U32_TO_ABE32(*snxt, tcph->th_seq);
21708 
21709 		/*
21710 		 * Branch off to tcp_xmit_mp() if any of the VALID bits is
21711 		 * set.  For the case when TCP_FSS_VALID is the only valid
21712 		 * bit (normal active close), branch off only when we think
21713 		 * that the FIN flag needs to be set.  Note for this case,
21714 		 * that (snxt + len) may not reflect the actual seg_len,
21715 		 * as len may be further reduced in tcp_xmit_mp().  If len
21716 		 * gets modified, we will end up here again.
21717 		 */
21718 		if (tcp->tcp_valid_bits != 0 &&
21719 		    (tcp->tcp_valid_bits != TCP_FSS_VALID ||
21720 		    ((*snxt + len) == tcp->tcp_fss))) {
21721 			uchar_t		*prev_rptr;
21722 			uint32_t	prev_snxt = tcp->tcp_snxt;
21723 
21724 			if (*tail_unsent == 0) {
21725 				ASSERT((*xmit_tail)->b_cont != NULL);
21726 				*xmit_tail = (*xmit_tail)->b_cont;
21727 				prev_rptr = (*xmit_tail)->b_rptr;
21728 				*tail_unsent = (int)((*xmit_tail)->b_wptr -
21729 				    (*xmit_tail)->b_rptr);
21730 			} else {
21731 				prev_rptr = (*xmit_tail)->b_rptr;
21732 				(*xmit_tail)->b_rptr = (*xmit_tail)->b_wptr -
21733 				    *tail_unsent;
21734 			}
21735 			mp = tcp_xmit_mp(tcp, *xmit_tail, len, NULL, NULL,
21736 			    *snxt, B_FALSE, (uint32_t *)&len, B_FALSE);
21737 			/* Restore tcp_snxt so we get amount sent right. */
21738 			tcp->tcp_snxt = prev_snxt;
21739 			if (prev_rptr == (*xmit_tail)->b_rptr) {
21740 				/*
21741 				 * If the previous timestamp is still in use,
21742 				 * don't stomp on it.
21743 				 */
21744 				if ((*xmit_tail)->b_next == NULL) {
21745 					(*xmit_tail)->b_prev = local_time;
21746 					(*xmit_tail)->b_next =
21747 					    (mblk_t *)(uintptr_t)(*snxt);
21748 				}
21749 			} else
21750 				(*xmit_tail)->b_rptr = prev_rptr;
21751 
21752 			if (mp == NULL) {
21753 				if (ire != NULL)
21754 					IRE_REFRELE(ire);
21755 				return (-1);
21756 			}
21757 			mp1 = mp->b_cont;
21758 
21759 			if (len <= mss) /* LSO is unusable (!do_lso_send) */
21760 				tcp->tcp_last_sent_len = (ushort_t)len;
21761 			while (mp1->b_cont) {
21762 				*xmit_tail = (*xmit_tail)->b_cont;
21763 				(*xmit_tail)->b_prev = local_time;
21764 				(*xmit_tail)->b_next =
21765 				    (mblk_t *)(uintptr_t)(*snxt);
21766 				mp1 = mp1->b_cont;
21767 			}
21768 			*snxt += len;
21769 			*tail_unsent = (*xmit_tail)->b_wptr - mp1->b_wptr;
21770 			BUMP_LOCAL(tcp->tcp_obsegs);
21771 			BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21772 			UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21773 			tcp_send_data(tcp, q, mp);
21774 			continue;
21775 		}
21776 
21777 		*snxt += len;	/* Adjust later if we don't send all of len */
21778 		BUMP_MIB(&tcps->tcps_mib, tcpOutDataSegs);
21779 		UPDATE_MIB(&tcps->tcps_mib, tcpOutDataBytes, len);
21780 
21781 		if (*tail_unsent) {
21782 			/* Are the bytes above us in flight? */
21783 			rptr = (*xmit_tail)->b_wptr - *tail_unsent;
21784 			if (rptr != (*xmit_tail)->b_rptr) {
21785 				*tail_unsent -= len;
21786 				if (len <= mss) /* LSO is unusable */
21787 					tcp->tcp_last_sent_len = (ushort_t)len;
21788 				len += tcp_hdr_len;
21789 				if (tcp->tcp_ipversion == IPV4_VERSION)
21790 					tcp->tcp_ipha->ipha_length = htons(len);
21791 				else
21792 					tcp->tcp_ip6h->ip6_plen =
21793 					    htons(len -
21794 					    ((char *)&tcp->tcp_ip6h[1] -
21795 					    tcp->tcp_iphc));
21796 				mp = dupb(*xmit_tail);
21797 				if (mp == NULL) {
21798 					if (ire != NULL)
21799 						IRE_REFRELE(ire);
21800 					return (-1);	/* out_of_mem */
21801 				}
21802 				mp->b_rptr = rptr;
21803 				/*
21804 				 * If the old timestamp is no longer in use,
21805 				 * sample a new timestamp now.
21806 				 */
21807 				if ((*xmit_tail)->b_next == NULL) {
21808 					(*xmit_tail)->b_prev = local_time;
21809 					(*xmit_tail)->b_next =
21810 					    (mblk_t *)(uintptr_t)(*snxt-len);
21811 				}
21812 				goto must_alloc;
21813 			}
21814 		} else {
21815 			*xmit_tail = (*xmit_tail)->b_cont;
21816 			ASSERT((uintptr_t)((*xmit_tail)->b_wptr -
21817 			    (*xmit_tail)->b_rptr) <= (uintptr_t)INT_MAX);
21818 			*tail_unsent = (int)((*xmit_tail)->b_wptr -
21819 			    (*xmit_tail)->b_rptr);
21820 		}
21821 
21822 		(*xmit_tail)->b_prev = local_time;
21823 		(*xmit_tail)->b_next = (mblk_t *)(uintptr_t)(*snxt - len);
21824 
21825 		*tail_unsent -= len;
21826 		if (len <= mss) /* LSO is unusable (!do_lso_send) */
21827 			tcp->tcp_last_sent_len = (ushort_t)len;
21828 
21829 		len += tcp_hdr_len;
21830 		if (tcp->tcp_ipversion == IPV4_VERSION)
21831 			tcp->tcp_ipha->ipha_length = htons(len);
21832 		else
21833 			tcp->tcp_ip6h->ip6_plen = htons(len -
21834 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
21835 
21836 		mp = dupb(*xmit_tail);
21837 		if (mp == NULL) {
21838 			if (ire != NULL)
21839 				IRE_REFRELE(ire);
21840 			return (-1);	/* out_of_mem */
21841 		}
21842 
21843 		len = tcp_hdr_len;
21844 		/*
21845 		 * There are four reasons to allocate a new hdr mblk:
21846 		 *  1) The bytes above us are in use by another packet
21847 		 *  2) We don't have good alignment
21848 		 *  3) The mblk is being shared
21849 		 *  4) We don't have enough room for a header
21850 		 */
21851 		rptr = mp->b_rptr - len;
21852 		if (!OK_32PTR(rptr) ||
21853 		    ((db = mp->b_datap), db->db_ref != 2) ||
21854 		    rptr < db->db_base + ire_fp_mp_len) {
21855 			/* NOTE: we assume allocb returns an OK_32PTR */
21856 
21857 		must_alloc:;
21858 			mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
21859 			    tcps->tcps_wroff_xtra + ire_fp_mp_len, BPRI_MED);
21860 			if (mp1 == NULL) {
21861 				freemsg(mp);
21862 				if (ire != NULL)
21863 					IRE_REFRELE(ire);
21864 				return (-1);	/* out_of_mem */
21865 			}
21866 			mp1->b_cont = mp;
21867 			mp = mp1;
21868 			/* Leave room for Link Level header */
21869 			len = tcp_hdr_len;
21870 			rptr =
21871 			    &mp->b_rptr[tcps->tcps_wroff_xtra + ire_fp_mp_len];
21872 			mp->b_wptr = &rptr[len];
21873 		}
21874 
21875 		/*
21876 		 * Fill in the header using the template header, and add
21877 		 * options such as time-stamp, ECN and/or SACK, as needed.
21878 		 */
21879 		tcp_fill_header(tcp, rptr, (clock_t)local_time, num_sack_blk);
21880 
21881 		mp->b_rptr = rptr;
21882 
21883 		if (*tail_unsent) {
21884 			int spill = *tail_unsent;
21885 
21886 			mp1 = mp->b_cont;
21887 			if (mp1 == NULL)
21888 				mp1 = mp;
21889 
21890 			/*
21891 			 * If we're a little short, tack on more mblks until
21892 			 * there is no more spillover.
21893 			 */
21894 			while (spill < 0) {
21895 				mblk_t *nmp;
21896 				int nmpsz;
21897 
21898 				nmp = (*xmit_tail)->b_cont;
21899 				nmpsz = MBLKL(nmp);
21900 
21901 				/*
21902 				 * Excess data in mblk; can we split it?
21903 				 * If MDT is enabled for the connection,
21904 				 * keep on splitting as this is a transient
21905 				 * send path.
21906 				 */
21907 				if (!do_lso_send && !tcp->tcp_mdt &&
21908 				    (spill + nmpsz > 0)) {
21909 					/*
21910 					 * Don't split if stream head was
21911 					 * told to break up larger writes
21912 					 * into smaller ones.
21913 					 */
21914 					if (tcp->tcp_maxpsz > 0)
21915 						break;
21916 
21917 					/*
21918 					 * Next mblk is less than SMSS/2
21919 					 * rounded up to nearest 64-byte;
21920 					 * let it get sent as part of the
21921 					 * next segment.
21922 					 */
21923 					if (tcp->tcp_localnet &&
21924 					    !tcp->tcp_cork &&
21925 					    (nmpsz < roundup((mss >> 1), 64)))
21926 						break;
21927 				}
21928 
21929 				*xmit_tail = nmp;
21930 				ASSERT((uintptr_t)nmpsz <= (uintptr_t)INT_MAX);
21931 				/* Stash for rtt use later */
21932 				(*xmit_tail)->b_prev = local_time;
21933 				(*xmit_tail)->b_next =
21934 				    (mblk_t *)(uintptr_t)(*snxt - len);
21935 				mp1->b_cont = dupb(*xmit_tail);
21936 				mp1 = mp1->b_cont;
21937 
21938 				spill += nmpsz;
21939 				if (mp1 == NULL) {
21940 					*tail_unsent = spill;
21941 					freemsg(mp);
21942 					if (ire != NULL)
21943 						IRE_REFRELE(ire);
21944 					return (-1);	/* out_of_mem */
21945 				}
21946 			}
21947 
21948 			/* Trim back any surplus on the last mblk */
21949 			if (spill >= 0) {
21950 				mp1->b_wptr -= spill;
21951 				*tail_unsent = spill;
21952 			} else {
21953 				/*
21954 				 * We did not send everything we could in
21955 				 * order to remain within the b_cont limit.
21956 				 */
21957 				*usable -= spill;
21958 				*snxt += spill;
21959 				tcp->tcp_last_sent_len += spill;
21960 				UPDATE_MIB(&tcps->tcps_mib,
21961 				    tcpOutDataBytes, spill);
21962 				/*
21963 				 * Adjust the checksum
21964 				 */
21965 				tcph = (tcph_t *)(rptr + tcp->tcp_ip_hdr_len);
21966 				sum += spill;
21967 				sum = (sum >> 16) + (sum & 0xFFFF);
21968 				U16_TO_ABE16(sum, tcph->th_sum);
21969 				if (tcp->tcp_ipversion == IPV4_VERSION) {
21970 					sum = ntohs(
21971 					    ((ipha_t *)rptr)->ipha_length) +
21972 					    spill;
21973 					((ipha_t *)rptr)->ipha_length =
21974 					    htons(sum);
21975 				} else {
21976 					sum = ntohs(
21977 					    ((ip6_t *)rptr)->ip6_plen) +
21978 					    spill;
21979 					((ip6_t *)rptr)->ip6_plen =
21980 					    htons(sum);
21981 				}
21982 				*tail_unsent = 0;
21983 			}
21984 		}
21985 		if (tcp->tcp_ip_forward_progress) {
21986 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
21987 			*(uint32_t *)mp->b_rptr  |= IP_FORWARD_PROG;
21988 			tcp->tcp_ip_forward_progress = B_FALSE;
21989 		}
21990 
21991 		if (do_lso_send) {
21992 			tcp_lsosend_data(tcp, mp, ire, ill, mss,
21993 			    num_lso_seg);
21994 			tcp->tcp_obsegs += num_lso_seg;
21995 
21996 			TCP_STAT(tcps, tcp_lso_times);
21997 			TCP_STAT_UPDATE(tcps, tcp_lso_pkt_out, num_lso_seg);
21998 		} else {
21999 			tcp_send_data(tcp, q, mp);
22000 			BUMP_LOCAL(tcp->tcp_obsegs);
22001 		}
22002 	}
22003 
22004 	if (ire != NULL)
22005 		IRE_REFRELE(ire);
22006 	return (0);
22007 }
22008 
22009 /* Unlink and return any mblk that looks like it contains a MDT info */
22010 static mblk_t *
22011 tcp_mdt_info_mp(mblk_t *mp)
22012 {
22013 	mblk_t	*prev_mp;
22014 
22015 	for (;;) {
22016 		prev_mp = mp;
22017 		/* no more to process? */
22018 		if ((mp = mp->b_cont) == NULL)
22019 			break;
22020 
22021 		switch (DB_TYPE(mp)) {
22022 		case M_CTL:
22023 			if (*(uint32_t *)mp->b_rptr != MDT_IOC_INFO_UPDATE)
22024 				continue;
22025 			ASSERT(prev_mp != NULL);
22026 			prev_mp->b_cont = mp->b_cont;
22027 			mp->b_cont = NULL;
22028 			return (mp);
22029 		default:
22030 			break;
22031 		}
22032 	}
22033 	return (mp);
22034 }
22035 
22036 /* MDT info update routine, called when IP notifies us about MDT */
22037 static void
22038 tcp_mdt_update(tcp_t *tcp, ill_mdt_capab_t *mdt_capab, boolean_t first)
22039 {
22040 	boolean_t prev_state;
22041 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22042 
22043 	/*
22044 	 * IP is telling us to abort MDT on this connection?  We know
22045 	 * this because the capability is only turned off when IP
22046 	 * encounters some pathological cases, e.g. link-layer change
22047 	 * where the new driver doesn't support MDT, or in situation
22048 	 * where MDT usage on the link-layer has been switched off.
22049 	 * IP would not have sent us the initial MDT_IOC_INFO_UPDATE
22050 	 * if the link-layer doesn't support MDT, and if it does, it
22051 	 * will indicate that the feature is to be turned on.
22052 	 */
22053 	prev_state = tcp->tcp_mdt;
22054 	tcp->tcp_mdt = (mdt_capab->ill_mdt_on != 0);
22055 	if (!tcp->tcp_mdt && !first) {
22056 		TCP_STAT(tcps, tcp_mdt_conn_halted3);
22057 		ip1dbg(("tcp_mdt_update: disabling MDT for connp %p\n",
22058 		    (void *)tcp->tcp_connp));
22059 	}
22060 
22061 	/*
22062 	 * We currently only support MDT on simple TCP/{IPv4,IPv6},
22063 	 * so disable MDT otherwise.  The checks are done here
22064 	 * and in tcp_wput_data().
22065 	 */
22066 	if (tcp->tcp_mdt &&
22067 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22068 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22069 	    (tcp->tcp_ipversion == IPV6_VERSION &&
22070 	    tcp->tcp_ip_hdr_len != IPV6_HDR_LEN))
22071 		tcp->tcp_mdt = B_FALSE;
22072 
22073 	if (tcp->tcp_mdt) {
22074 		if (mdt_capab->ill_mdt_version != MDT_VERSION_2) {
22075 			cmn_err(CE_NOTE, "tcp_mdt_update: unknown MDT "
22076 			    "version (%d), expected version is %d",
22077 			    mdt_capab->ill_mdt_version, MDT_VERSION_2);
22078 			tcp->tcp_mdt = B_FALSE;
22079 			return;
22080 		}
22081 
22082 		/*
22083 		 * We need the driver to be able to handle at least three
22084 		 * spans per packet in order for tcp MDT to be utilized.
22085 		 * The first is for the header portion, while the rest are
22086 		 * needed to handle a packet that straddles across two
22087 		 * virtually non-contiguous buffers; a typical tcp packet
22088 		 * therefore consists of only two spans.  Note that we take
22089 		 * a zero as "don't care".
22090 		 */
22091 		if (mdt_capab->ill_mdt_span_limit > 0 &&
22092 		    mdt_capab->ill_mdt_span_limit < 3) {
22093 			tcp->tcp_mdt = B_FALSE;
22094 			return;
22095 		}
22096 
22097 		/* a zero means driver wants default value */
22098 		tcp->tcp_mdt_max_pld = MIN(mdt_capab->ill_mdt_max_pld,
22099 		    tcps->tcps_mdt_max_pbufs);
22100 		if (tcp->tcp_mdt_max_pld == 0)
22101 			tcp->tcp_mdt_max_pld = tcps->tcps_mdt_max_pbufs;
22102 
22103 		/* ensure 32-bit alignment */
22104 		tcp->tcp_mdt_hdr_head = roundup(MAX(tcps->tcps_mdt_hdr_head_min,
22105 		    mdt_capab->ill_mdt_hdr_head), 4);
22106 		tcp->tcp_mdt_hdr_tail = roundup(MAX(tcps->tcps_mdt_hdr_tail_min,
22107 		    mdt_capab->ill_mdt_hdr_tail), 4);
22108 
22109 		if (!first && !prev_state) {
22110 			TCP_STAT(tcps, tcp_mdt_conn_resumed2);
22111 			ip1dbg(("tcp_mdt_update: reenabling MDT for connp %p\n",
22112 			    (void *)tcp->tcp_connp));
22113 		}
22114 	}
22115 }
22116 
22117 /* Unlink and return any mblk that looks like it contains a LSO info */
22118 static mblk_t *
22119 tcp_lso_info_mp(mblk_t *mp)
22120 {
22121 	mblk_t	*prev_mp;
22122 
22123 	for (;;) {
22124 		prev_mp = mp;
22125 		/* no more to process? */
22126 		if ((mp = mp->b_cont) == NULL)
22127 			break;
22128 
22129 		switch (DB_TYPE(mp)) {
22130 		case M_CTL:
22131 			if (*(uint32_t *)mp->b_rptr != LSO_IOC_INFO_UPDATE)
22132 				continue;
22133 			ASSERT(prev_mp != NULL);
22134 			prev_mp->b_cont = mp->b_cont;
22135 			mp->b_cont = NULL;
22136 			return (mp);
22137 		default:
22138 			break;
22139 		}
22140 	}
22141 
22142 	return (mp);
22143 }
22144 
22145 /* LSO info update routine, called when IP notifies us about LSO */
22146 static void
22147 tcp_lso_update(tcp_t *tcp, ill_lso_capab_t *lso_capab)
22148 {
22149 	tcp_stack_t *tcps = tcp->tcp_tcps;
22150 
22151 	/*
22152 	 * IP is telling us to abort LSO on this connection?  We know
22153 	 * this because the capability is only turned off when IP
22154 	 * encounters some pathological cases, e.g. link-layer change
22155 	 * where the new NIC/driver doesn't support LSO, or in situation
22156 	 * where LSO usage on the link-layer has been switched off.
22157 	 * IP would not have sent us the initial LSO_IOC_INFO_UPDATE
22158 	 * if the link-layer doesn't support LSO, and if it does, it
22159 	 * will indicate that the feature is to be turned on.
22160 	 */
22161 	tcp->tcp_lso = (lso_capab->ill_lso_on != 0);
22162 	TCP_STAT(tcps, tcp_lso_enabled);
22163 
22164 	/*
22165 	 * We currently only support LSO on simple TCP/IPv4,
22166 	 * so disable LSO otherwise.  The checks are done here
22167 	 * and in tcp_wput_data().
22168 	 */
22169 	if (tcp->tcp_lso &&
22170 	    (tcp->tcp_ipversion == IPV4_VERSION &&
22171 	    tcp->tcp_ip_hdr_len != IP_SIMPLE_HDR_LENGTH) ||
22172 	    (tcp->tcp_ipversion == IPV6_VERSION)) {
22173 		tcp->tcp_lso = B_FALSE;
22174 		TCP_STAT(tcps, tcp_lso_disabled);
22175 	} else {
22176 		tcp->tcp_lso_max = MIN(TCP_MAX_LSO_LENGTH,
22177 		    lso_capab->ill_lso_max);
22178 	}
22179 }
22180 
22181 static void
22182 tcp_ire_ill_check(tcp_t *tcp, ire_t *ire, ill_t *ill, boolean_t check_lso_mdt)
22183 {
22184 	conn_t *connp = tcp->tcp_connp;
22185 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22186 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22187 
22188 	ASSERT(ire != NULL);
22189 
22190 	/*
22191 	 * We may be in the fastpath here, and although we essentially do
22192 	 * similar checks as in ip_bind_connected{_v6}/ip_xxinfo_return,
22193 	 * we try to keep things as brief as possible.  After all, these
22194 	 * are only best-effort checks, and we do more thorough ones prior
22195 	 * to calling tcp_send()/tcp_multisend().
22196 	 */
22197 	if ((ipst->ips_ip_lso_outbound || ipst->ips_ip_multidata_outbound) &&
22198 	    check_lso_mdt && !(ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK)) &&
22199 	    ill != NULL && !CONN_IPSEC_OUT_ENCAPSULATED(connp) &&
22200 	    !(ire->ire_flags & RTF_MULTIRT) &&
22201 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
22202 	    CONN_IS_LSO_MD_FASTPATH(connp)) {
22203 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
22204 			/* Cache the result */
22205 			connp->conn_lso_ok = B_TRUE;
22206 
22207 			ASSERT(ill->ill_lso_capab != NULL);
22208 			if (!ill->ill_lso_capab->ill_lso_on) {
22209 				ill->ill_lso_capab->ill_lso_on = 1;
22210 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22211 				    "LSO for interface %s\n", (void *)connp,
22212 				    ill->ill_name));
22213 			}
22214 			tcp_lso_update(tcp, ill->ill_lso_capab);
22215 		} else if (ipst->ips_ip_multidata_outbound &&
22216 		    ILL_MDT_CAPABLE(ill)) {
22217 			/* Cache the result */
22218 			connp->conn_mdt_ok = B_TRUE;
22219 
22220 			ASSERT(ill->ill_mdt_capab != NULL);
22221 			if (!ill->ill_mdt_capab->ill_mdt_on) {
22222 				ill->ill_mdt_capab->ill_mdt_on = 1;
22223 				ip1dbg(("tcp_ire_ill_check: connp %p enables "
22224 				    "MDT for interface %s\n", (void *)connp,
22225 				    ill->ill_name));
22226 			}
22227 			tcp_mdt_update(tcp, ill->ill_mdt_capab, B_TRUE);
22228 		}
22229 	}
22230 
22231 	/*
22232 	 * The goal is to reduce the number of generated tcp segments by
22233 	 * setting the maxpsz multiplier to 0; this will have an affect on
22234 	 * tcp_maxpsz_set().  With this behavior, tcp will pack more data
22235 	 * into each packet, up to SMSS bytes.  Doing this reduces the number
22236 	 * of outbound segments and incoming ACKs, thus allowing for better
22237 	 * network and system performance.  In contrast the legacy behavior
22238 	 * may result in sending less than SMSS size, because the last mblk
22239 	 * for some packets may have more data than needed to make up SMSS,
22240 	 * and the legacy code refused to "split" it.
22241 	 *
22242 	 * We apply the new behavior on following situations:
22243 	 *
22244 	 *   1) Loopback connections,
22245 	 *   2) Connections in which the remote peer is not on local subnet,
22246 	 *   3) Local subnet connections over the bge interface (see below).
22247 	 *
22248 	 * Ideally, we would like this behavior to apply for interfaces other
22249 	 * than bge.  However, doing so would negatively impact drivers which
22250 	 * perform dynamic mapping and unmapping of DMA resources, which are
22251 	 * increased by setting the maxpsz multiplier to 0 (more mblks per
22252 	 * packet will be generated by tcp).  The bge driver does not suffer
22253 	 * from this, as it copies the mblks into pre-mapped buffers, and
22254 	 * therefore does not require more I/O resources than before.
22255 	 *
22256 	 * Otherwise, this behavior is present on all network interfaces when
22257 	 * the destination endpoint is non-local, since reducing the number
22258 	 * of packets in general is good for the network.
22259 	 *
22260 	 * TODO We need to remove this hard-coded conditional for bge once
22261 	 *	a better "self-tuning" mechanism, or a way to comprehend
22262 	 *	the driver transmit strategy is devised.  Until the solution
22263 	 *	is found and well understood, we live with this hack.
22264 	 */
22265 	if (!tcp_static_maxpsz &&
22266 	    (tcp->tcp_loopback || !tcp->tcp_localnet ||
22267 	    (ill->ill_name_length > 3 && bcmp(ill->ill_name, "bge", 3) == 0))) {
22268 		/* override the default value */
22269 		tcp->tcp_maxpsz = 0;
22270 
22271 		ip3dbg(("tcp_ire_ill_check: connp %p tcp_maxpsz %d on "
22272 		    "interface %s\n", (void *)connp, tcp->tcp_maxpsz,
22273 		    ill != NULL ? ill->ill_name : ipif_loopback_name));
22274 	}
22275 
22276 	/* set the stream head parameters accordingly */
22277 	(void) tcp_maxpsz_set(tcp, B_TRUE);
22278 }
22279 
22280 /* tcp_wput_flush is called by tcp_wput_nondata to handle M_FLUSH messages. */
22281 static void
22282 tcp_wput_flush(tcp_t *tcp, mblk_t *mp)
22283 {
22284 	uchar_t	fval = *mp->b_rptr;
22285 	mblk_t	*tail;
22286 	queue_t	*q = tcp->tcp_wq;
22287 
22288 	/* TODO: How should flush interact with urgent data? */
22289 	if ((fval & FLUSHW) && tcp->tcp_xmit_head &&
22290 	    !(tcp->tcp_valid_bits & TCP_URG_VALID)) {
22291 		/*
22292 		 * Flush only data that has not yet been put on the wire.  If
22293 		 * we flush data that we have already transmitted, life, as we
22294 		 * know it, may come to an end.
22295 		 */
22296 		tail = tcp->tcp_xmit_tail;
22297 		tail->b_wptr -= tcp->tcp_xmit_tail_unsent;
22298 		tcp->tcp_xmit_tail_unsent = 0;
22299 		tcp->tcp_unsent = 0;
22300 		if (tail->b_wptr != tail->b_rptr)
22301 			tail = tail->b_cont;
22302 		if (tail) {
22303 			mblk_t **excess = &tcp->tcp_xmit_head;
22304 			for (;;) {
22305 				mblk_t *mp1 = *excess;
22306 				if (mp1 == tail)
22307 					break;
22308 				tcp->tcp_xmit_tail = mp1;
22309 				tcp->tcp_xmit_last = mp1;
22310 				excess = &mp1->b_cont;
22311 			}
22312 			*excess = NULL;
22313 			tcp_close_mpp(&tail);
22314 			if (tcp->tcp_snd_zcopy_aware)
22315 				tcp_zcopy_notify(tcp);
22316 		}
22317 		/*
22318 		 * We have no unsent data, so unsent must be less than
22319 		 * tcp_xmit_lowater, so re-enable flow.
22320 		 */
22321 		mutex_enter(&tcp->tcp_non_sq_lock);
22322 		if (tcp->tcp_flow_stopped) {
22323 			tcp_clrqfull(tcp);
22324 		}
22325 		mutex_exit(&tcp->tcp_non_sq_lock);
22326 	}
22327 	/*
22328 	 * TODO: you can't just flush these, you have to increase rwnd for one
22329 	 * thing.  For another, how should urgent data interact?
22330 	 */
22331 	if (fval & FLUSHR) {
22332 		*mp->b_rptr = fval & ~FLUSHW;
22333 		/* XXX */
22334 		qreply(q, mp);
22335 		return;
22336 	}
22337 	freemsg(mp);
22338 }
22339 
22340 /*
22341  * tcp_wput_iocdata is called by tcp_wput_nondata to handle all M_IOCDATA
22342  * messages.
22343  */
22344 static void
22345 tcp_wput_iocdata(tcp_t *tcp, mblk_t *mp)
22346 {
22347 	mblk_t	*mp1;
22348 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
22349 	STRUCT_HANDLE(strbuf, sb);
22350 	queue_t *q = tcp->tcp_wq;
22351 	int	error;
22352 	uint_t	addrlen;
22353 
22354 	/* Make sure it is one of ours. */
22355 	switch (iocp->ioc_cmd) {
22356 	case TI_GETMYNAME:
22357 	case TI_GETPEERNAME:
22358 		break;
22359 	default:
22360 		CALL_IP_WPUT(tcp->tcp_connp, q, mp);
22361 		return;
22362 	}
22363 	switch (mi_copy_state(q, mp, &mp1)) {
22364 	case -1:
22365 		return;
22366 	case MI_COPY_CASE(MI_COPY_IN, 1):
22367 		break;
22368 	case MI_COPY_CASE(MI_COPY_OUT, 1):
22369 		/* Copy out the strbuf. */
22370 		mi_copyout(q, mp);
22371 		return;
22372 	case MI_COPY_CASE(MI_COPY_OUT, 2):
22373 		/* All done. */
22374 		mi_copy_done(q, mp, 0);
22375 		return;
22376 	default:
22377 		mi_copy_done(q, mp, EPROTO);
22378 		return;
22379 	}
22380 	/* Check alignment of the strbuf */
22381 	if (!OK_32PTR(mp1->b_rptr)) {
22382 		mi_copy_done(q, mp, EINVAL);
22383 		return;
22384 	}
22385 
22386 	STRUCT_SET_HANDLE(sb, iocp->ioc_flag, (void *)mp1->b_rptr);
22387 	addrlen = tcp->tcp_family == AF_INET ? sizeof (sin_t) : sizeof (sin6_t);
22388 	if (STRUCT_FGET(sb, maxlen) < addrlen) {
22389 		mi_copy_done(q, mp, EINVAL);
22390 		return;
22391 	}
22392 
22393 	mp1 = mi_copyout_alloc(q, mp, STRUCT_FGETP(sb, buf), addrlen, B_TRUE);
22394 	if (mp1 == NULL)
22395 		return;
22396 
22397 	switch (iocp->ioc_cmd) {
22398 	case TI_GETMYNAME:
22399 		error = tcp_getmyname(tcp, (void *)mp1->b_rptr, &addrlen);
22400 		break;
22401 	case TI_GETPEERNAME:
22402 		error = tcp_getpeername(tcp, (void *)mp1->b_rptr, &addrlen);
22403 		break;
22404 	}
22405 
22406 	if (error != 0) {
22407 		mi_copy_done(q, mp, error);
22408 	} else {
22409 		mp1->b_wptr += addrlen;
22410 		STRUCT_FSET(sb, len, addrlen);
22411 
22412 		/* Copy out the address */
22413 		mi_copyout(q, mp);
22414 	}
22415 }
22416 
22417 /*
22418  * tcp_wput_ioctl is called by tcp_wput_nondata() to handle all M_IOCTL
22419  * messages.
22420  */
22421 /* ARGSUSED */
22422 static void
22423 tcp_wput_ioctl(void *arg, mblk_t *mp, void *arg2)
22424 {
22425 	conn_t 	*connp = (conn_t *)arg;
22426 	tcp_t	*tcp = connp->conn_tcp;
22427 	queue_t	*q = tcp->tcp_wq;
22428 	struct iocblk	*iocp;
22429 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22430 
22431 	ASSERT(DB_TYPE(mp) == M_IOCTL);
22432 	/*
22433 	 * Try and ASSERT the minimum possible references on the
22434 	 * conn early enough. Since we are executing on write side,
22435 	 * the connection is obviously not detached and that means
22436 	 * there is a ref each for TCP and IP. Since we are behind
22437 	 * the squeue, the minimum references needed are 3. If the
22438 	 * conn is in classifier hash list, there should be an
22439 	 * extra ref for that (we check both the possibilities).
22440 	 */
22441 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22442 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22443 
22444 	iocp = (struct iocblk *)mp->b_rptr;
22445 	switch (iocp->ioc_cmd) {
22446 	case TCP_IOC_DEFAULT_Q:
22447 		/* Wants to be the default wq. */
22448 		if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
22449 			iocp->ioc_error = EPERM;
22450 			iocp->ioc_count = 0;
22451 			mp->b_datap->db_type = M_IOCACK;
22452 			qreply(q, mp);
22453 			return;
22454 		}
22455 		tcp_def_q_set(tcp, mp);
22456 		return;
22457 	case _SIOCSOCKFALLBACK:
22458 		/*
22459 		 * Either sockmod is about to be popped and the socket
22460 		 * would now be treated as a plain stream, or a module
22461 		 * is about to be pushed so we could no longer use read-
22462 		 * side synchronous streams for fused loopback tcp.
22463 		 * Drain any queued data and disable direct sockfs
22464 		 * interface from now on.
22465 		 */
22466 		if (!tcp->tcp_issocket) {
22467 			DB_TYPE(mp) = M_IOCNAK;
22468 			iocp->ioc_error = EINVAL;
22469 		} else {
22470 #ifdef	_ILP32
22471 			tcp->tcp_acceptor_id = (t_uscalar_t)RD(q);
22472 #else
22473 			tcp->tcp_acceptor_id = tcp->tcp_connp->conn_dev;
22474 #endif
22475 			/*
22476 			 * Insert this socket into the acceptor hash.
22477 			 * We might need it for T_CONN_RES message
22478 			 */
22479 			tcp_acceptor_hash_insert(tcp->tcp_acceptor_id, tcp);
22480 
22481 			if (tcp->tcp_fused) {
22482 				/*
22483 				 * This is a fused loopback tcp; disable
22484 				 * read-side synchronous streams interface
22485 				 * and drain any queued data.  It is okay
22486 				 * to do this for non-synchronous streams
22487 				 * fused tcp as well.
22488 				 */
22489 				tcp_fuse_disable_pair(tcp, B_FALSE);
22490 			}
22491 			tcp->tcp_issocket = B_FALSE;
22492 			tcp->tcp_sodirect = NULL;
22493 			TCP_STAT(tcps, tcp_sock_fallback);
22494 
22495 			DB_TYPE(mp) = M_IOCACK;
22496 			iocp->ioc_error = 0;
22497 		}
22498 		iocp->ioc_count = 0;
22499 		iocp->ioc_rval = 0;
22500 		qreply(q, mp);
22501 		return;
22502 	}
22503 	CALL_IP_WPUT(connp, q, mp);
22504 }
22505 
22506 /*
22507  * This routine is called by tcp_wput() to handle all TPI requests.
22508  */
22509 /* ARGSUSED */
22510 static void
22511 tcp_wput_proto(void *arg, mblk_t *mp, void *arg2)
22512 {
22513 	conn_t 	*connp = (conn_t *)arg;
22514 	tcp_t	*tcp = connp->conn_tcp;
22515 	union T_primitives *tprim = (union T_primitives *)mp->b_rptr;
22516 	uchar_t *rptr;
22517 	t_scalar_t type;
22518 	int len;
22519 	cred_t *cr = DB_CREDDEF(mp, tcp->tcp_cred);
22520 
22521 	/*
22522 	 * Try and ASSERT the minimum possible references on the
22523 	 * conn early enough. Since we are executing on write side,
22524 	 * the connection is obviously not detached and that means
22525 	 * there is a ref each for TCP and IP. Since we are behind
22526 	 * the squeue, the minimum references needed are 3. If the
22527 	 * conn is in classifier hash list, there should be an
22528 	 * extra ref for that (we check both the possibilities).
22529 	 */
22530 	ASSERT((connp->conn_fanout != NULL && connp->conn_ref >= 4) ||
22531 	    (connp->conn_fanout == NULL && connp->conn_ref >= 3));
22532 
22533 	rptr = mp->b_rptr;
22534 	ASSERT((uintptr_t)(mp->b_wptr - rptr) <= (uintptr_t)INT_MAX);
22535 	if ((mp->b_wptr - rptr) >= sizeof (t_scalar_t)) {
22536 		type = ((union T_primitives *)rptr)->type;
22537 		if (type == T_EXDATA_REQ) {
22538 			uint32_t msize = msgdsize(mp->b_cont);
22539 
22540 			len = msize - 1;
22541 			if (len < 0) {
22542 				freemsg(mp);
22543 				return;
22544 			}
22545 			/*
22546 			 * Try to force urgent data out on the wire.
22547 			 * Even if we have unsent data this will
22548 			 * at least send the urgent flag.
22549 			 * XXX does not handle more flag correctly.
22550 			 */
22551 			len += tcp->tcp_unsent;
22552 			len += tcp->tcp_snxt;
22553 			tcp->tcp_urg = len;
22554 			tcp->tcp_valid_bits |= TCP_URG_VALID;
22555 
22556 			/* Bypass tcp protocol for fused tcp loopback */
22557 			if (tcp->tcp_fused && tcp_fuse_output(tcp, mp, msize))
22558 				return;
22559 		} else if (type != T_DATA_REQ) {
22560 			goto non_urgent_data;
22561 		}
22562 		/* TODO: options, flags, ... from user */
22563 		/* Set length to zero for reclamation below */
22564 		tcp_wput_data(tcp, mp->b_cont, B_TRUE);
22565 		freeb(mp);
22566 		return;
22567 	} else {
22568 		if (tcp->tcp_debug) {
22569 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22570 			    "tcp_wput_proto, dropping one...");
22571 		}
22572 		freemsg(mp);
22573 		return;
22574 	}
22575 
22576 non_urgent_data:
22577 
22578 	switch ((int)tprim->type) {
22579 	case T_SSL_PROXY_BIND_REQ:	/* an SSL proxy endpoint bind request */
22580 		/*
22581 		 * save the kssl_ent_t from the next block, and convert this
22582 		 * back to a normal bind_req.
22583 		 */
22584 		if (mp->b_cont != NULL) {
22585 			ASSERT(MBLKL(mp->b_cont) >= sizeof (kssl_ent_t));
22586 
22587 			if (tcp->tcp_kssl_ent != NULL) {
22588 				kssl_release_ent(tcp->tcp_kssl_ent, NULL,
22589 				    KSSL_NO_PROXY);
22590 				tcp->tcp_kssl_ent = NULL;
22591 			}
22592 			bcopy(mp->b_cont->b_rptr, &tcp->tcp_kssl_ent,
22593 			    sizeof (kssl_ent_t));
22594 			kssl_hold_ent(tcp->tcp_kssl_ent);
22595 			freemsg(mp->b_cont);
22596 			mp->b_cont = NULL;
22597 		}
22598 		tprim->type = T_BIND_REQ;
22599 
22600 	/* FALLTHROUGH */
22601 	case O_T_BIND_REQ:	/* bind request */
22602 	case T_BIND_REQ:	/* new semantics bind request */
22603 		tcp_bind(tcp, mp);
22604 		break;
22605 	case T_UNBIND_REQ:	/* unbind request */
22606 		tcp_unbind(tcp, mp);
22607 		break;
22608 	case O_T_CONN_RES:	/* old connection response XXX */
22609 	case T_CONN_RES:	/* connection response */
22610 		tcp_accept(tcp, mp);
22611 		break;
22612 	case T_CONN_REQ:	/* connection request */
22613 		tcp_connect(tcp, mp);
22614 		break;
22615 	case T_DISCON_REQ:	/* disconnect request */
22616 		tcp_disconnect(tcp, mp);
22617 		break;
22618 	case T_CAPABILITY_REQ:
22619 		tcp_capability_req(tcp, mp);	/* capability request */
22620 		break;
22621 	case T_INFO_REQ:	/* information request */
22622 		tcp_info_req(tcp, mp);
22623 		break;
22624 	case T_SVR4_OPTMGMT_REQ:	/* manage options req */
22625 		(void) svr4_optcom_req(tcp->tcp_wq, mp, cr,
22626 		    &tcp_opt_obj, B_TRUE);
22627 		break;
22628 	case T_OPTMGMT_REQ:
22629 		/*
22630 		 * Note:  no support for snmpcom_req() through new
22631 		 * T_OPTMGMT_REQ. See comments in ip.c
22632 		 */
22633 		/* Only IP is allowed to return meaningful value */
22634 		(void) tpi_optcom_req(tcp->tcp_wq, mp, cr, &tcp_opt_obj,
22635 		    B_TRUE);
22636 		break;
22637 
22638 	case T_UNITDATA_REQ:	/* unitdata request */
22639 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22640 		break;
22641 	case T_ORDREL_REQ:	/* orderly release req */
22642 		freemsg(mp);
22643 
22644 		if (tcp->tcp_fused)
22645 			tcp_unfuse(tcp);
22646 
22647 		if (tcp_xmit_end(tcp) != 0) {
22648 			/*
22649 			 * We were crossing FINs and got a reset from
22650 			 * the other side. Just ignore it.
22651 			 */
22652 			if (tcp->tcp_debug) {
22653 				(void) strlog(TCP_MOD_ID, 0, 1,
22654 				    SL_ERROR|SL_TRACE,
22655 				    "tcp_wput_proto, T_ORDREL_REQ out of "
22656 				    "state %s",
22657 				    tcp_display(tcp, NULL,
22658 				    DISP_ADDR_AND_PORT));
22659 			}
22660 		}
22661 		break;
22662 	case T_ADDR_REQ:
22663 		tcp_addr_req(tcp, mp);
22664 		break;
22665 	default:
22666 		if (tcp->tcp_debug) {
22667 			(void) strlog(TCP_MOD_ID, 0, 1, SL_ERROR|SL_TRACE,
22668 			    "tcp_wput_proto, bogus TPI msg, type %d",
22669 			    tprim->type);
22670 		}
22671 		/*
22672 		 * We used to M_ERROR.  Sending TNOTSUPPORT gives the user
22673 		 * to recover.
22674 		 */
22675 		tcp_err_ack(tcp, mp, TNOTSUPPORT, 0);
22676 		break;
22677 	}
22678 }
22679 
22680 /*
22681  * The TCP write service routine should never be called...
22682  */
22683 /* ARGSUSED */
22684 static void
22685 tcp_wsrv(queue_t *q)
22686 {
22687 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
22688 
22689 	TCP_STAT(tcps, tcp_wsrv_called);
22690 }
22691 
22692 /* Non overlapping byte exchanger */
22693 static void
22694 tcp_xchg(uchar_t *a, uchar_t *b, int len)
22695 {
22696 	uchar_t	uch;
22697 
22698 	while (len-- > 0) {
22699 		uch = a[len];
22700 		a[len] = b[len];
22701 		b[len] = uch;
22702 	}
22703 }
22704 
22705 /*
22706  * Send out a control packet on the tcp connection specified.  This routine
22707  * is typically called where we need a simple ACK or RST generated.
22708  */
22709 static void
22710 tcp_xmit_ctl(char *str, tcp_t *tcp, uint32_t seq, uint32_t ack, int ctl)
22711 {
22712 	uchar_t		*rptr;
22713 	tcph_t		*tcph;
22714 	ipha_t		*ipha = NULL;
22715 	ip6_t		*ip6h = NULL;
22716 	uint32_t	sum;
22717 	int		tcp_hdr_len;
22718 	int		tcp_ip_hdr_len;
22719 	mblk_t		*mp;
22720 	tcp_stack_t	*tcps = tcp->tcp_tcps;
22721 
22722 	/*
22723 	 * Save sum for use in source route later.
22724 	 */
22725 	ASSERT(tcp != NULL);
22726 	sum = tcp->tcp_tcp_hdr_len + tcp->tcp_sum;
22727 	tcp_hdr_len = tcp->tcp_hdr_len;
22728 	tcp_ip_hdr_len = tcp->tcp_ip_hdr_len;
22729 
22730 	/* If a text string is passed in with the request, pass it to strlog. */
22731 	if (str != NULL && tcp->tcp_debug) {
22732 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22733 		    "tcp_xmit_ctl: '%s', seq 0x%x, ack 0x%x, ctl 0x%x",
22734 		    str, seq, ack, ctl);
22735 	}
22736 	mp = allocb(tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH + tcps->tcps_wroff_xtra,
22737 	    BPRI_MED);
22738 	if (mp == NULL) {
22739 		return;
22740 	}
22741 	rptr = &mp->b_rptr[tcps->tcps_wroff_xtra];
22742 	mp->b_rptr = rptr;
22743 	mp->b_wptr = &rptr[tcp_hdr_len];
22744 	bcopy(tcp->tcp_iphc, rptr, tcp_hdr_len);
22745 
22746 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22747 		ipha = (ipha_t *)rptr;
22748 		ipha->ipha_length = htons(tcp_hdr_len);
22749 	} else {
22750 		ip6h = (ip6_t *)rptr;
22751 		ASSERT(tcp != NULL);
22752 		ip6h->ip6_plen = htons(tcp->tcp_hdr_len -
22753 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
22754 	}
22755 	tcph = (tcph_t *)&rptr[tcp_ip_hdr_len];
22756 	tcph->th_flags[0] = (uint8_t)ctl;
22757 	if (ctl & TH_RST) {
22758 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
22759 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
22760 		/*
22761 		 * Don't send TSopt w/ TH_RST packets per RFC 1323.
22762 		 */
22763 		if (tcp->tcp_snd_ts_ok &&
22764 		    tcp->tcp_state > TCPS_SYN_SENT) {
22765 			mp->b_wptr = &rptr[tcp_hdr_len - TCPOPT_REAL_TS_LEN];
22766 			*(mp->b_wptr) = TCPOPT_EOL;
22767 			if (tcp->tcp_ipversion == IPV4_VERSION) {
22768 				ipha->ipha_length = htons(tcp_hdr_len -
22769 				    TCPOPT_REAL_TS_LEN);
22770 			} else {
22771 				ip6h->ip6_plen = htons(ntohs(ip6h->ip6_plen) -
22772 				    TCPOPT_REAL_TS_LEN);
22773 			}
22774 			tcph->th_offset_and_rsrvd[0] -= (3 << 4);
22775 			sum -= TCPOPT_REAL_TS_LEN;
22776 		}
22777 	}
22778 	if (ctl & TH_ACK) {
22779 		if (tcp->tcp_snd_ts_ok) {
22780 			U32_TO_BE32(lbolt,
22781 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
22782 			U32_TO_BE32(tcp->tcp_ts_recent,
22783 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
22784 		}
22785 
22786 		/* Update the latest receive window size in TCP header. */
22787 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
22788 		    tcph->th_win);
22789 		tcp->tcp_rack = ack;
22790 		tcp->tcp_rack_cnt = 0;
22791 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
22792 	}
22793 	BUMP_LOCAL(tcp->tcp_obsegs);
22794 	U32_TO_BE32(seq, tcph->th_seq);
22795 	U32_TO_BE32(ack, tcph->th_ack);
22796 	/*
22797 	 * Include the adjustment for a source route if any.
22798 	 */
22799 	sum = (sum >> 16) + (sum & 0xFFFF);
22800 	U16_TO_BE16(sum, tcph->th_sum);
22801 	tcp_send_data(tcp, tcp->tcp_wq, mp);
22802 }
22803 
22804 /*
22805  * If this routine returns B_TRUE, TCP can generate a RST in response
22806  * to a segment.  If it returns B_FALSE, TCP should not respond.
22807  */
22808 static boolean_t
22809 tcp_send_rst_chk(tcp_stack_t *tcps)
22810 {
22811 	clock_t	now;
22812 
22813 	/*
22814 	 * TCP needs to protect itself from generating too many RSTs.
22815 	 * This can be a DoS attack by sending us random segments
22816 	 * soliciting RSTs.
22817 	 *
22818 	 * What we do here is to have a limit of tcp_rst_sent_rate RSTs
22819 	 * in each 1 second interval.  In this way, TCP still generate
22820 	 * RSTs in normal cases but when under attack, the impact is
22821 	 * limited.
22822 	 */
22823 	if (tcps->tcps_rst_sent_rate_enabled != 0) {
22824 		now = lbolt;
22825 		/* lbolt can wrap around. */
22826 		if ((tcps->tcps_last_rst_intrvl > now) ||
22827 		    (TICK_TO_MSEC(now - tcps->tcps_last_rst_intrvl) >
22828 		    1*SECONDS)) {
22829 			tcps->tcps_last_rst_intrvl = now;
22830 			tcps->tcps_rst_cnt = 1;
22831 		} else if (++tcps->tcps_rst_cnt > tcps->tcps_rst_sent_rate) {
22832 			return (B_FALSE);
22833 		}
22834 	}
22835 	return (B_TRUE);
22836 }
22837 
22838 /*
22839  * Send down the advice IP ioctl to tell IP to mark an IRE temporary.
22840  */
22841 static void
22842 tcp_ip_ire_mark_advice(tcp_t *tcp)
22843 {
22844 	mblk_t *mp;
22845 	ipic_t *ipic;
22846 
22847 	if (tcp->tcp_ipversion == IPV4_VERSION) {
22848 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
22849 		    &ipic);
22850 	} else {
22851 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
22852 		    &ipic);
22853 	}
22854 	if (mp == NULL)
22855 		return;
22856 	ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
22857 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
22858 }
22859 
22860 /*
22861  * Return an IP advice ioctl mblk and set ipic to be the pointer
22862  * to the advice structure.
22863  */
22864 static mblk_t *
22865 tcp_ip_advise_mblk(void *addr, int addr_len, ipic_t **ipic)
22866 {
22867 	struct iocblk *ioc;
22868 	mblk_t *mp, *mp1;
22869 
22870 	mp = allocb(sizeof (ipic_t) + addr_len, BPRI_HI);
22871 	if (mp == NULL)
22872 		return (NULL);
22873 	bzero(mp->b_rptr, sizeof (ipic_t) + addr_len);
22874 	*ipic = (ipic_t *)mp->b_rptr;
22875 	(*ipic)->ipic_cmd = IP_IOC_IRE_ADVISE_NO_REPLY;
22876 	(*ipic)->ipic_addr_offset = sizeof (ipic_t);
22877 
22878 	bcopy(addr, *ipic + 1, addr_len);
22879 
22880 	(*ipic)->ipic_addr_length = addr_len;
22881 	mp->b_wptr = &mp->b_rptr[sizeof (ipic_t) + addr_len];
22882 
22883 	mp1 = mkiocb(IP_IOCTL);
22884 	if (mp1 == NULL) {
22885 		freemsg(mp);
22886 		return (NULL);
22887 	}
22888 	mp1->b_cont = mp;
22889 	ioc = (struct iocblk *)mp1->b_rptr;
22890 	ioc->ioc_count = sizeof (ipic_t) + addr_len;
22891 
22892 	return (mp1);
22893 }
22894 
22895 /*
22896  * Generate a reset based on an inbound packet, connp is set by caller
22897  * when RST is in response to an unexpected inbound packet for which
22898  * there is active tcp state in the system.
22899  *
22900  * IPSEC NOTE : Try to send the reply with the same protection as it came
22901  * in.  We still have the ipsec_mp that the packet was attached to. Thus
22902  * the packet will go out at the same level of protection as it came in by
22903  * converting the IPSEC_IN to IPSEC_OUT.
22904  */
22905 static void
22906 tcp_xmit_early_reset(char *str, mblk_t *mp, uint32_t seq,
22907     uint32_t ack, int ctl, uint_t ip_hdr_len, zoneid_t zoneid,
22908     tcp_stack_t *tcps, conn_t *connp)
22909 {
22910 	ipha_t		*ipha = NULL;
22911 	ip6_t		*ip6h = NULL;
22912 	ushort_t	len;
22913 	tcph_t		*tcph;
22914 	int		i;
22915 	mblk_t		*ipsec_mp;
22916 	boolean_t	mctl_present;
22917 	ipic_t		*ipic;
22918 	ipaddr_t	v4addr;
22919 	in6_addr_t	v6addr;
22920 	int		addr_len;
22921 	void		*addr;
22922 	queue_t		*q = tcps->tcps_g_q;
22923 	tcp_t		*tcp;
22924 	cred_t		*cr;
22925 	mblk_t		*nmp;
22926 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
22927 
22928 	if (tcps->tcps_g_q == NULL) {
22929 		/*
22930 		 * For non-zero stackids the default queue isn't created
22931 		 * until the first open, thus there can be a need to send
22932 		 * a reset before then. But we can't do that, hence we just
22933 		 * drop the packet. Later during boot, when the default queue
22934 		 * has been setup, a retransmitted packet from the peer
22935 		 * will result in a reset.
22936 		 */
22937 		ASSERT(tcps->tcps_netstack->netstack_stackid !=
22938 		    GLOBAL_NETSTACKID);
22939 		freemsg(mp);
22940 		return;
22941 	}
22942 
22943 	if (connp != NULL)
22944 		tcp = connp->conn_tcp;
22945 	else
22946 		tcp = Q_TO_TCP(q);
22947 
22948 	if (!tcp_send_rst_chk(tcps)) {
22949 		tcps->tcps_rst_unsent++;
22950 		freemsg(mp);
22951 		return;
22952 	}
22953 
22954 	if (mp->b_datap->db_type == M_CTL) {
22955 		ipsec_mp = mp;
22956 		mp = mp->b_cont;
22957 		mctl_present = B_TRUE;
22958 	} else {
22959 		ipsec_mp = mp;
22960 		mctl_present = B_FALSE;
22961 	}
22962 
22963 	if (str && q && tcps->tcps_dbg) {
22964 		(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE,
22965 		    "tcp_xmit_early_reset: '%s', seq 0x%x, ack 0x%x, "
22966 		    "flags 0x%x",
22967 		    str, seq, ack, ctl);
22968 	}
22969 	if (mp->b_datap->db_ref != 1) {
22970 		mblk_t *mp1 = copyb(mp);
22971 		freemsg(mp);
22972 		mp = mp1;
22973 		if (!mp) {
22974 			if (mctl_present)
22975 				freeb(ipsec_mp);
22976 			return;
22977 		} else {
22978 			if (mctl_present) {
22979 				ipsec_mp->b_cont = mp;
22980 			} else {
22981 				ipsec_mp = mp;
22982 			}
22983 		}
22984 	} else if (mp->b_cont) {
22985 		freemsg(mp->b_cont);
22986 		mp->b_cont = NULL;
22987 	}
22988 	/*
22989 	 * We skip reversing source route here.
22990 	 * (for now we replace all IP options with EOL)
22991 	 */
22992 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
22993 		ipha = (ipha_t *)mp->b_rptr;
22994 		for (i = IP_SIMPLE_HDR_LENGTH; i < (int)ip_hdr_len; i++)
22995 			mp->b_rptr[i] = IPOPT_EOL;
22996 		/*
22997 		 * Make sure that src address isn't flagrantly invalid.
22998 		 * Not all broadcast address checking for the src address
22999 		 * is possible, since we don't know the netmask of the src
23000 		 * addr.  No check for destination address is done, since
23001 		 * IP will not pass up a packet with a broadcast dest
23002 		 * address to TCP.  Similar checks are done below for IPv6.
23003 		 */
23004 		if (ipha->ipha_src == 0 || ipha->ipha_src == INADDR_BROADCAST ||
23005 		    CLASSD(ipha->ipha_src)) {
23006 			freemsg(ipsec_mp);
23007 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
23008 			return;
23009 		}
23010 	} else {
23011 		ip6h = (ip6_t *)mp->b_rptr;
23012 
23013 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6h->ip6_src) ||
23014 		    IN6_IS_ADDR_MULTICAST(&ip6h->ip6_src)) {
23015 			freemsg(ipsec_mp);
23016 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsInDiscards);
23017 			return;
23018 		}
23019 
23020 		/* Remove any extension headers assuming partial overlay */
23021 		if (ip_hdr_len > IPV6_HDR_LEN) {
23022 			uint8_t *to;
23023 
23024 			to = mp->b_rptr + ip_hdr_len - IPV6_HDR_LEN;
23025 			ovbcopy(ip6h, to, IPV6_HDR_LEN);
23026 			mp->b_rptr += ip_hdr_len - IPV6_HDR_LEN;
23027 			ip_hdr_len = IPV6_HDR_LEN;
23028 			ip6h = (ip6_t *)mp->b_rptr;
23029 			ip6h->ip6_nxt = IPPROTO_TCP;
23030 		}
23031 	}
23032 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
23033 	if (tcph->th_flags[0] & TH_RST) {
23034 		freemsg(ipsec_mp);
23035 		return;
23036 	}
23037 	tcph->th_offset_and_rsrvd[0] = (5 << 4);
23038 	len = ip_hdr_len + sizeof (tcph_t);
23039 	mp->b_wptr = &mp->b_rptr[len];
23040 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23041 		ipha->ipha_length = htons(len);
23042 		/* Swap addresses */
23043 		v4addr = ipha->ipha_src;
23044 		ipha->ipha_src = ipha->ipha_dst;
23045 		ipha->ipha_dst = v4addr;
23046 		ipha->ipha_ident = 0;
23047 		ipha->ipha_ttl = (uchar_t)tcps->tcps_ipv4_ttl;
23048 		addr_len = IP_ADDR_LEN;
23049 		addr = &v4addr;
23050 	} else {
23051 		/* No ip6i_t in this case */
23052 		ip6h->ip6_plen = htons(len - IPV6_HDR_LEN);
23053 		/* Swap addresses */
23054 		v6addr = ip6h->ip6_src;
23055 		ip6h->ip6_src = ip6h->ip6_dst;
23056 		ip6h->ip6_dst = v6addr;
23057 		ip6h->ip6_hops = (uchar_t)tcps->tcps_ipv6_hoplimit;
23058 		addr_len = IPV6_ADDR_LEN;
23059 		addr = &v6addr;
23060 	}
23061 	tcp_xchg(tcph->th_fport, tcph->th_lport, 2);
23062 	U32_TO_BE32(ack, tcph->th_ack);
23063 	U32_TO_BE32(seq, tcph->th_seq);
23064 	U16_TO_BE16(0, tcph->th_win);
23065 	U16_TO_BE16(sizeof (tcph_t), tcph->th_sum);
23066 	tcph->th_flags[0] = (uint8_t)ctl;
23067 	if (ctl & TH_RST) {
23068 		BUMP_MIB(&tcps->tcps_mib, tcpOutRsts);
23069 		BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23070 	}
23071 
23072 	/* IP trusts us to set up labels when required. */
23073 	if (is_system_labeled() && (cr = DB_CRED(mp)) != NULL &&
23074 	    crgetlabel(cr) != NULL) {
23075 		int err;
23076 
23077 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION)
23078 			err = tsol_check_label(cr, &mp,
23079 			    tcp->tcp_connp->conn_mac_exempt,
23080 			    tcps->tcps_netstack->netstack_ip);
23081 		else
23082 			err = tsol_check_label_v6(cr, &mp,
23083 			    tcp->tcp_connp->conn_mac_exempt,
23084 			    tcps->tcps_netstack->netstack_ip);
23085 		if (mctl_present)
23086 			ipsec_mp->b_cont = mp;
23087 		else
23088 			ipsec_mp = mp;
23089 		if (err != 0) {
23090 			freemsg(ipsec_mp);
23091 			return;
23092 		}
23093 		if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23094 			ipha = (ipha_t *)mp->b_rptr;
23095 		} else {
23096 			ip6h = (ip6_t *)mp->b_rptr;
23097 		}
23098 	}
23099 
23100 	if (mctl_present) {
23101 		ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23102 
23103 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23104 		if (!ipsec_in_to_out(ipsec_mp, ipha, ip6h)) {
23105 			return;
23106 		}
23107 	}
23108 	if (zoneid == ALL_ZONES)
23109 		zoneid = GLOBAL_ZONEID;
23110 
23111 	/* Add the zoneid so ip_output routes it properly */
23112 	if ((nmp = ip_prepend_zoneid(ipsec_mp, zoneid, ipst)) == NULL) {
23113 		freemsg(ipsec_mp);
23114 		return;
23115 	}
23116 	ipsec_mp = nmp;
23117 
23118 	/*
23119 	 * NOTE:  one might consider tracing a TCP packet here, but
23120 	 * this function has no active TCP state and no tcp structure
23121 	 * that has a trace buffer.  If we traced here, we would have
23122 	 * to keep a local trace buffer in tcp_record_trace().
23123 	 *
23124 	 * TSol note: The mblk that contains the incoming packet was
23125 	 * reused by tcp_xmit_listener_reset, so it already contains
23126 	 * the right credentials and we don't need to call mblk_setcred.
23127 	 * Also the conn's cred is not right since it is associated
23128 	 * with tcps_g_q.
23129 	 */
23130 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, ipsec_mp);
23131 
23132 	/*
23133 	 * Tell IP to mark the IRE used for this destination temporary.
23134 	 * This way, we can limit our exposure to DoS attack because IP
23135 	 * creates an IRE for each destination.  If there are too many,
23136 	 * the time to do any routing lookup will be extremely long.  And
23137 	 * the lookup can be in interrupt context.
23138 	 *
23139 	 * Note that in normal circumstances, this marking should not
23140 	 * affect anything.  It would be nice if only 1 message is
23141 	 * needed to inform IP that the IRE created for this RST should
23142 	 * not be added to the cache table.  But there is currently
23143 	 * not such communication mechanism between TCP and IP.  So
23144 	 * the best we can do now is to send the advice ioctl to IP
23145 	 * to mark the IRE temporary.
23146 	 */
23147 	if ((mp = tcp_ip_advise_mblk(addr, addr_len, &ipic)) != NULL) {
23148 		ipic->ipic_ire_marks |= IRE_MARK_TEMPORARY;
23149 		CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23150 	}
23151 }
23152 
23153 /*
23154  * Initiate closedown sequence on an active connection.  (May be called as
23155  * writer.)  Return value zero for OK return, non-zero for error return.
23156  */
23157 static int
23158 tcp_xmit_end(tcp_t *tcp)
23159 {
23160 	ipic_t	*ipic;
23161 	mblk_t	*mp;
23162 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23163 
23164 	if (tcp->tcp_state < TCPS_SYN_RCVD ||
23165 	    tcp->tcp_state > TCPS_CLOSE_WAIT) {
23166 		/*
23167 		 * Invalid state, only states TCPS_SYN_RCVD,
23168 		 * TCPS_ESTABLISHED and TCPS_CLOSE_WAIT are valid
23169 		 */
23170 		return (-1);
23171 	}
23172 
23173 	tcp->tcp_fss = tcp->tcp_snxt + tcp->tcp_unsent;
23174 	tcp->tcp_valid_bits |= TCP_FSS_VALID;
23175 	/*
23176 	 * If there is nothing more unsent, send the FIN now.
23177 	 * Otherwise, it will go out with the last segment.
23178 	 */
23179 	if (tcp->tcp_unsent == 0) {
23180 		mp = tcp_xmit_mp(tcp, NULL, 0, NULL, NULL,
23181 		    tcp->tcp_fss, B_FALSE, NULL, B_FALSE);
23182 
23183 		if (mp) {
23184 			tcp_send_data(tcp, tcp->tcp_wq, mp);
23185 		} else {
23186 			/*
23187 			 * Couldn't allocate msg.  Pretend we got it out.
23188 			 * Wait for rexmit timeout.
23189 			 */
23190 			tcp->tcp_snxt = tcp->tcp_fss + 1;
23191 			TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23192 		}
23193 
23194 		/*
23195 		 * If needed, update tcp_rexmit_snxt as tcp_snxt is
23196 		 * changed.
23197 		 */
23198 		if (tcp->tcp_rexmit && tcp->tcp_rexmit_nxt == tcp->tcp_fss) {
23199 			tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
23200 		}
23201 	} else {
23202 		/*
23203 		 * If tcp->tcp_cork is set, then the data will not get sent,
23204 		 * so we have to check that and unset it first.
23205 		 */
23206 		if (tcp->tcp_cork)
23207 			tcp->tcp_cork = B_FALSE;
23208 		tcp_wput_data(tcp, NULL, B_FALSE);
23209 	}
23210 
23211 	/*
23212 	 * If TCP does not get enough samples of RTT or tcp_rtt_updates
23213 	 * is 0, don't update the cache.
23214 	 */
23215 	if (tcps->tcps_rtt_updates == 0 ||
23216 	    tcp->tcp_rtt_update < tcps->tcps_rtt_updates)
23217 		return (0);
23218 
23219 	/*
23220 	 * NOTE: should not update if source routes i.e. if tcp_remote if
23221 	 * different from the destination.
23222 	 */
23223 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23224 		if (tcp->tcp_remote !=  tcp->tcp_ipha->ipha_dst) {
23225 			return (0);
23226 		}
23227 		mp = tcp_ip_advise_mblk(&tcp->tcp_ipha->ipha_dst, IP_ADDR_LEN,
23228 		    &ipic);
23229 	} else {
23230 		if (!(IN6_ARE_ADDR_EQUAL(&tcp->tcp_remote_v6,
23231 		    &tcp->tcp_ip6h->ip6_dst))) {
23232 			return (0);
23233 		}
23234 		mp = tcp_ip_advise_mblk(&tcp->tcp_ip6h->ip6_dst, IPV6_ADDR_LEN,
23235 		    &ipic);
23236 	}
23237 
23238 	/* Record route attributes in the IRE for use by future connections. */
23239 	if (mp == NULL)
23240 		return (0);
23241 
23242 	/*
23243 	 * We do not have a good algorithm to update ssthresh at this time.
23244 	 * So don't do any update.
23245 	 */
23246 	ipic->ipic_rtt = tcp->tcp_rtt_sa;
23247 	ipic->ipic_rtt_sd = tcp->tcp_rtt_sd;
23248 
23249 	CALL_IP_WPUT(tcp->tcp_connp, tcp->tcp_wq, mp);
23250 	return (0);
23251 }
23252 
23253 /*
23254  * Generate a "no listener here" RST in response to an "unknown" segment.
23255  * connp is set by caller when RST is in response to an unexpected
23256  * inbound packet for which there is active tcp state in the system.
23257  * Note that we are reusing the incoming mp to construct the outgoing RST.
23258  */
23259 void
23260 tcp_xmit_listeners_reset(mblk_t *mp, uint_t ip_hdr_len, zoneid_t zoneid,
23261     tcp_stack_t *tcps, conn_t *connp)
23262 {
23263 	uchar_t		*rptr;
23264 	uint32_t	seg_len;
23265 	tcph_t		*tcph;
23266 	uint32_t	seg_seq;
23267 	uint32_t	seg_ack;
23268 	uint_t		flags;
23269 	mblk_t		*ipsec_mp;
23270 	ipha_t 		*ipha;
23271 	ip6_t 		*ip6h;
23272 	boolean_t	mctl_present = B_FALSE;
23273 	boolean_t	check = B_TRUE;
23274 	boolean_t	policy_present;
23275 	ipsec_stack_t	*ipss = tcps->tcps_netstack->netstack_ipsec;
23276 
23277 	TCP_STAT(tcps, tcp_no_listener);
23278 
23279 	ipsec_mp = mp;
23280 
23281 	if (mp->b_datap->db_type == M_CTL) {
23282 		ipsec_in_t *ii;
23283 
23284 		mctl_present = B_TRUE;
23285 		mp = mp->b_cont;
23286 
23287 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
23288 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
23289 		if (ii->ipsec_in_dont_check) {
23290 			check = B_FALSE;
23291 			if (!ii->ipsec_in_secure) {
23292 				freeb(ipsec_mp);
23293 				mctl_present = B_FALSE;
23294 				ipsec_mp = mp;
23295 			}
23296 		}
23297 	}
23298 
23299 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
23300 		policy_present = ipss->ipsec_inbound_v4_policy_present;
23301 		ipha = (ipha_t *)mp->b_rptr;
23302 		ip6h = NULL;
23303 	} else {
23304 		policy_present = ipss->ipsec_inbound_v6_policy_present;
23305 		ipha = NULL;
23306 		ip6h = (ip6_t *)mp->b_rptr;
23307 	}
23308 
23309 	if (check && policy_present) {
23310 		/*
23311 		 * The conn_t parameter is NULL because we already know
23312 		 * nobody's home.
23313 		 */
23314 		ipsec_mp = ipsec_check_global_policy(
23315 		    ipsec_mp, (conn_t *)NULL, ipha, ip6h, mctl_present,
23316 		    tcps->tcps_netstack);
23317 		if (ipsec_mp == NULL)
23318 			return;
23319 	}
23320 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
23321 		DTRACE_PROBE2(
23322 		    tx__ip__log__error__nolistener__tcp,
23323 		    char *, "Could not reply with RST to mp(1)",
23324 		    mblk_t *, mp);
23325 		ip2dbg(("tcp_xmit_listeners_reset: not permitted to reply\n"));
23326 		freemsg(ipsec_mp);
23327 		return;
23328 	}
23329 
23330 	rptr = mp->b_rptr;
23331 
23332 	tcph = (tcph_t *)&rptr[ip_hdr_len];
23333 	seg_seq = BE32_TO_U32(tcph->th_seq);
23334 	seg_ack = BE32_TO_U32(tcph->th_ack);
23335 	flags = tcph->th_flags[0];
23336 
23337 	seg_len = msgdsize(mp) - (TCP_HDR_LENGTH(tcph) + ip_hdr_len);
23338 	if (flags & TH_RST) {
23339 		freemsg(ipsec_mp);
23340 	} else if (flags & TH_ACK) {
23341 		tcp_xmit_early_reset("no tcp, reset",
23342 		    ipsec_mp, seg_ack, 0, TH_RST, ip_hdr_len, zoneid, tcps,
23343 		    connp);
23344 	} else {
23345 		if (flags & TH_SYN) {
23346 			seg_len++;
23347 		} else {
23348 			/*
23349 			 * Here we violate the RFC.  Note that a normal
23350 			 * TCP will never send a segment without the ACK
23351 			 * flag, except for RST or SYN segment.  This
23352 			 * segment is neither.  Just drop it on the
23353 			 * floor.
23354 			 */
23355 			freemsg(ipsec_mp);
23356 			tcps->tcps_rst_unsent++;
23357 			return;
23358 		}
23359 
23360 		tcp_xmit_early_reset("no tcp, reset/ack",
23361 		    ipsec_mp, 0, seg_seq + seg_len,
23362 		    TH_RST | TH_ACK, ip_hdr_len, zoneid, tcps, connp);
23363 	}
23364 }
23365 
23366 /*
23367  * tcp_xmit_mp is called to return a pointer to an mblk chain complete with
23368  * ip and tcp header ready to pass down to IP.  If the mp passed in is
23369  * non-NULL, then up to max_to_send bytes of data will be dup'ed off that
23370  * mblk. (If sendall is not set the dup'ing will stop at an mblk boundary
23371  * otherwise it will dup partial mblks.)
23372  * Otherwise, an appropriate ACK packet will be generated.  This
23373  * routine is not usually called to send new data for the first time.  It
23374  * is mostly called out of the timer for retransmits, and to generate ACKs.
23375  *
23376  * If offset is not NULL, the returned mblk chain's first mblk's b_rptr will
23377  * be adjusted by *offset.  And after dupb(), the offset and the ending mblk
23378  * of the original mblk chain will be returned in *offset and *end_mp.
23379  */
23380 mblk_t *
23381 tcp_xmit_mp(tcp_t *tcp, mblk_t *mp, int32_t max_to_send, int32_t *offset,
23382     mblk_t **end_mp, uint32_t seq, boolean_t sendall, uint32_t *seg_len,
23383     boolean_t rexmit)
23384 {
23385 	int	data_length;
23386 	int32_t	off = 0;
23387 	uint_t	flags;
23388 	mblk_t	*mp1;
23389 	mblk_t	*mp2;
23390 	uchar_t	*rptr;
23391 	tcph_t	*tcph;
23392 	int32_t	num_sack_blk = 0;
23393 	int32_t	sack_opt_len = 0;
23394 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23395 
23396 	/* Allocate for our maximum TCP header + link-level */
23397 	mp1 = allocb(tcp->tcp_ip_hdr_len + TCP_MAX_HDR_LENGTH +
23398 	    tcps->tcps_wroff_xtra, BPRI_MED);
23399 	if (!mp1)
23400 		return (NULL);
23401 	data_length = 0;
23402 
23403 	/*
23404 	 * Note that tcp_mss has been adjusted to take into account the
23405 	 * timestamp option if applicable.  Because SACK options do not
23406 	 * appear in every TCP segments and they are of variable lengths,
23407 	 * they cannot be included in tcp_mss.  Thus we need to calculate
23408 	 * the actual segment length when we need to send a segment which
23409 	 * includes SACK options.
23410 	 */
23411 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23412 		num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23413 		    tcp->tcp_num_sack_blk);
23414 		sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23415 		    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23416 		if (max_to_send + sack_opt_len > tcp->tcp_mss)
23417 			max_to_send -= sack_opt_len;
23418 	}
23419 
23420 	if (offset != NULL) {
23421 		off = *offset;
23422 		/* We use offset as an indicator that end_mp is not NULL. */
23423 		*end_mp = NULL;
23424 	}
23425 	for (mp2 = mp1; mp && data_length != max_to_send; mp = mp->b_cont) {
23426 		/* This could be faster with cooperation from downstream */
23427 		if (mp2 != mp1 && !sendall &&
23428 		    data_length + (int)(mp->b_wptr - mp->b_rptr) >
23429 		    max_to_send)
23430 			/*
23431 			 * Don't send the next mblk since the whole mblk
23432 			 * does not fit.
23433 			 */
23434 			break;
23435 		mp2->b_cont = dupb(mp);
23436 		mp2 = mp2->b_cont;
23437 		if (!mp2) {
23438 			freemsg(mp1);
23439 			return (NULL);
23440 		}
23441 		mp2->b_rptr += off;
23442 		ASSERT((uintptr_t)(mp2->b_wptr - mp2->b_rptr) <=
23443 		    (uintptr_t)INT_MAX);
23444 
23445 		data_length += (int)(mp2->b_wptr - mp2->b_rptr);
23446 		if (data_length > max_to_send) {
23447 			mp2->b_wptr -= data_length - max_to_send;
23448 			data_length = max_to_send;
23449 			off = mp2->b_wptr - mp->b_rptr;
23450 			break;
23451 		} else {
23452 			off = 0;
23453 		}
23454 	}
23455 	if (offset != NULL) {
23456 		*offset = off;
23457 		*end_mp = mp;
23458 	}
23459 	if (seg_len != NULL) {
23460 		*seg_len = data_length;
23461 	}
23462 
23463 	/* Update the latest receive window size in TCP header. */
23464 	U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23465 	    tcp->tcp_tcph->th_win);
23466 
23467 	rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23468 	mp1->b_rptr = rptr;
23469 	mp1->b_wptr = rptr + tcp->tcp_hdr_len + sack_opt_len;
23470 	bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23471 	tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23472 	U32_TO_ABE32(seq, tcph->th_seq);
23473 
23474 	/*
23475 	 * Use tcp_unsent to determine if the PUSH bit should be used assumes
23476 	 * that this function was called from tcp_wput_data. Thus, when called
23477 	 * to retransmit data the setting of the PUSH bit may appear some
23478 	 * what random in that it might get set when it should not. This
23479 	 * should not pose any performance issues.
23480 	 */
23481 	if (data_length != 0 && (tcp->tcp_unsent == 0 ||
23482 	    tcp->tcp_unsent == data_length)) {
23483 		flags = TH_ACK | TH_PUSH;
23484 	} else {
23485 		flags = TH_ACK;
23486 	}
23487 
23488 	if (tcp->tcp_ecn_ok) {
23489 		if (tcp->tcp_ecn_echo_on)
23490 			flags |= TH_ECE;
23491 
23492 		/*
23493 		 * Only set ECT bit and ECN_CWR if a segment contains new data.
23494 		 * There is no TCP flow control for non-data segments, and
23495 		 * only data segment is transmitted reliably.
23496 		 */
23497 		if (data_length > 0 && !rexmit) {
23498 			SET_ECT(tcp, rptr);
23499 			if (tcp->tcp_cwr && !tcp->tcp_ecn_cwr_sent) {
23500 				flags |= TH_CWR;
23501 				tcp->tcp_ecn_cwr_sent = B_TRUE;
23502 			}
23503 		}
23504 	}
23505 
23506 	if (tcp->tcp_valid_bits) {
23507 		uint32_t u1;
23508 
23509 		if ((tcp->tcp_valid_bits & TCP_ISS_VALID) &&
23510 		    seq == tcp->tcp_iss) {
23511 			uchar_t	*wptr;
23512 
23513 			/*
23514 			 * If TCP_ISS_VALID and the seq number is tcp_iss,
23515 			 * TCP can only be in SYN-SENT, SYN-RCVD or
23516 			 * FIN-WAIT-1 state.  It can be FIN-WAIT-1 if
23517 			 * our SYN is not ack'ed but the app closes this
23518 			 * TCP connection.
23519 			 */
23520 			ASSERT(tcp->tcp_state == TCPS_SYN_SENT ||
23521 			    tcp->tcp_state == TCPS_SYN_RCVD ||
23522 			    tcp->tcp_state == TCPS_FIN_WAIT_1);
23523 
23524 			/*
23525 			 * Tack on the MSS option.  It is always needed
23526 			 * for both active and passive open.
23527 			 *
23528 			 * MSS option value should be interface MTU - MIN
23529 			 * TCP/IP header according to RFC 793 as it means
23530 			 * the maximum segment size TCP can receive.  But
23531 			 * to get around some broken middle boxes/end hosts
23532 			 * out there, we allow the option value to be the
23533 			 * same as the MSS option size on the peer side.
23534 			 * In this way, the other side will not send
23535 			 * anything larger than they can receive.
23536 			 *
23537 			 * Note that for SYN_SENT state, the ndd param
23538 			 * tcp_use_smss_as_mss_opt has no effect as we
23539 			 * don't know the peer's MSS option value. So
23540 			 * the only case we need to take care of is in
23541 			 * SYN_RCVD state, which is done later.
23542 			 */
23543 			wptr = mp1->b_wptr;
23544 			wptr[0] = TCPOPT_MAXSEG;
23545 			wptr[1] = TCPOPT_MAXSEG_LEN;
23546 			wptr += 2;
23547 			u1 = tcp->tcp_if_mtu -
23548 			    (tcp->tcp_ipversion == IPV4_VERSION ?
23549 			    IP_SIMPLE_HDR_LENGTH : IPV6_HDR_LEN) -
23550 			    TCP_MIN_HEADER_LENGTH;
23551 			U16_TO_BE16(u1, wptr);
23552 			mp1->b_wptr = wptr + 2;
23553 			/* Update the offset to cover the additional word */
23554 			tcph->th_offset_and_rsrvd[0] += (1 << 4);
23555 
23556 			/*
23557 			 * Note that the following way of filling in
23558 			 * TCP options are not optimal.  Some NOPs can
23559 			 * be saved.  But there is no need at this time
23560 			 * to optimize it.  When it is needed, we will
23561 			 * do it.
23562 			 */
23563 			switch (tcp->tcp_state) {
23564 			case TCPS_SYN_SENT:
23565 				flags = TH_SYN;
23566 
23567 				if (tcp->tcp_snd_ts_ok) {
23568 					uint32_t llbolt = (uint32_t)lbolt;
23569 
23570 					wptr = mp1->b_wptr;
23571 					wptr[0] = TCPOPT_NOP;
23572 					wptr[1] = TCPOPT_NOP;
23573 					wptr[2] = TCPOPT_TSTAMP;
23574 					wptr[3] = TCPOPT_TSTAMP_LEN;
23575 					wptr += 4;
23576 					U32_TO_BE32(llbolt, wptr);
23577 					wptr += 4;
23578 					ASSERT(tcp->tcp_ts_recent == 0);
23579 					U32_TO_BE32(0L, wptr);
23580 					mp1->b_wptr += TCPOPT_REAL_TS_LEN;
23581 					tcph->th_offset_and_rsrvd[0] +=
23582 					    (3 << 4);
23583 				}
23584 
23585 				/*
23586 				 * Set up all the bits to tell other side
23587 				 * we are ECN capable.
23588 				 */
23589 				if (tcp->tcp_ecn_ok) {
23590 					flags |= (TH_ECE | TH_CWR);
23591 				}
23592 				break;
23593 			case TCPS_SYN_RCVD:
23594 				flags |= TH_SYN;
23595 
23596 				/*
23597 				 * Reset the MSS option value to be SMSS
23598 				 * We should probably add back the bytes
23599 				 * for timestamp option and IPsec.  We
23600 				 * don't do that as this is a workaround
23601 				 * for broken middle boxes/end hosts, it
23602 				 * is better for us to be more cautious.
23603 				 * They may not take these things into
23604 				 * account in their SMSS calculation.  Thus
23605 				 * the peer's calculated SMSS may be smaller
23606 				 * than what it can be.  This should be OK.
23607 				 */
23608 				if (tcps->tcps_use_smss_as_mss_opt) {
23609 					u1 = tcp->tcp_mss;
23610 					U16_TO_BE16(u1, wptr);
23611 				}
23612 
23613 				/*
23614 				 * If the other side is ECN capable, reply
23615 				 * that we are also ECN capable.
23616 				 */
23617 				if (tcp->tcp_ecn_ok)
23618 					flags |= TH_ECE;
23619 				break;
23620 			default:
23621 				/*
23622 				 * The above ASSERT() makes sure that this
23623 				 * must be FIN-WAIT-1 state.  Our SYN has
23624 				 * not been ack'ed so retransmit it.
23625 				 */
23626 				flags |= TH_SYN;
23627 				break;
23628 			}
23629 
23630 			if (tcp->tcp_snd_ws_ok) {
23631 				wptr = mp1->b_wptr;
23632 				wptr[0] =  TCPOPT_NOP;
23633 				wptr[1] =  TCPOPT_WSCALE;
23634 				wptr[2] =  TCPOPT_WS_LEN;
23635 				wptr[3] = (uchar_t)tcp->tcp_rcv_ws;
23636 				mp1->b_wptr += TCPOPT_REAL_WS_LEN;
23637 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23638 			}
23639 
23640 			if (tcp->tcp_snd_sack_ok) {
23641 				wptr = mp1->b_wptr;
23642 				wptr[0] = TCPOPT_NOP;
23643 				wptr[1] = TCPOPT_NOP;
23644 				wptr[2] = TCPOPT_SACK_PERMITTED;
23645 				wptr[3] = TCPOPT_SACK_OK_LEN;
23646 				mp1->b_wptr += TCPOPT_REAL_SACK_OK_LEN;
23647 				tcph->th_offset_and_rsrvd[0] += (1 << 4);
23648 			}
23649 
23650 			/* allocb() of adequate mblk assures space */
23651 			ASSERT((uintptr_t)(mp1->b_wptr - mp1->b_rptr) <=
23652 			    (uintptr_t)INT_MAX);
23653 			u1 = (int)(mp1->b_wptr - mp1->b_rptr);
23654 			/*
23655 			 * Get IP set to checksum on our behalf
23656 			 * Include the adjustment for a source route if any.
23657 			 */
23658 			u1 += tcp->tcp_sum;
23659 			u1 = (u1 >> 16) + (u1 & 0xFFFF);
23660 			U16_TO_BE16(u1, tcph->th_sum);
23661 			BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23662 		}
23663 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
23664 		    (seq + data_length) == tcp->tcp_fss) {
23665 			if (!tcp->tcp_fin_acked) {
23666 				flags |= TH_FIN;
23667 				BUMP_MIB(&tcps->tcps_mib, tcpOutControl);
23668 			}
23669 			if (!tcp->tcp_fin_sent) {
23670 				tcp->tcp_fin_sent = B_TRUE;
23671 				switch (tcp->tcp_state) {
23672 				case TCPS_SYN_RCVD:
23673 				case TCPS_ESTABLISHED:
23674 					tcp->tcp_state = TCPS_FIN_WAIT_1;
23675 					break;
23676 				case TCPS_CLOSE_WAIT:
23677 					tcp->tcp_state = TCPS_LAST_ACK;
23678 					break;
23679 				}
23680 				if (tcp->tcp_suna == tcp->tcp_snxt)
23681 					TCP_TIMER_RESTART(tcp, tcp->tcp_rto);
23682 				tcp->tcp_snxt = tcp->tcp_fss + 1;
23683 			}
23684 		}
23685 		/*
23686 		 * Note the trick here.  u1 is unsigned.  When tcp_urg
23687 		 * is smaller than seq, u1 will become a very huge value.
23688 		 * So the comparison will fail.  Also note that tcp_urp
23689 		 * should be positive, see RFC 793 page 17.
23690 		 */
23691 		u1 = tcp->tcp_urg - seq + TCP_OLD_URP_INTERPRETATION;
23692 		if ((tcp->tcp_valid_bits & TCP_URG_VALID) && u1 != 0 &&
23693 		    u1 < (uint32_t)(64 * 1024)) {
23694 			flags |= TH_URG;
23695 			BUMP_MIB(&tcps->tcps_mib, tcpOutUrg);
23696 			U32_TO_ABE16(u1, tcph->th_urp);
23697 		}
23698 	}
23699 	tcph->th_flags[0] = (uchar_t)flags;
23700 	tcp->tcp_rack = tcp->tcp_rnxt;
23701 	tcp->tcp_rack_cnt = 0;
23702 
23703 	if (tcp->tcp_snd_ts_ok) {
23704 		if (tcp->tcp_state != TCPS_SYN_SENT) {
23705 			uint32_t llbolt = (uint32_t)lbolt;
23706 
23707 			U32_TO_BE32(llbolt,
23708 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23709 			U32_TO_BE32(tcp->tcp_ts_recent,
23710 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23711 		}
23712 	}
23713 
23714 	if (num_sack_blk > 0) {
23715 		uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23716 		sack_blk_t *tmp;
23717 		int32_t	i;
23718 
23719 		wptr[0] = TCPOPT_NOP;
23720 		wptr[1] = TCPOPT_NOP;
23721 		wptr[2] = TCPOPT_SACK;
23722 		wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23723 		    sizeof (sack_blk_t);
23724 		wptr += TCPOPT_REAL_SACK_LEN;
23725 
23726 		tmp = tcp->tcp_sack_list;
23727 		for (i = 0; i < num_sack_blk; i++) {
23728 			U32_TO_BE32(tmp[i].begin, wptr);
23729 			wptr += sizeof (tcp_seq);
23730 			U32_TO_BE32(tmp[i].end, wptr);
23731 			wptr += sizeof (tcp_seq);
23732 		}
23733 		tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1) << 4);
23734 	}
23735 	ASSERT((uintptr_t)(mp1->b_wptr - rptr) <= (uintptr_t)INT_MAX);
23736 	data_length += (int)(mp1->b_wptr - rptr);
23737 	if (tcp->tcp_ipversion == IPV4_VERSION) {
23738 		((ipha_t *)rptr)->ipha_length = htons(data_length);
23739 	} else {
23740 		ip6_t *ip6 = (ip6_t *)(rptr +
23741 		    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23742 		    sizeof (ip6i_t) : 0));
23743 
23744 		ip6->ip6_plen = htons(data_length -
23745 		    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23746 	}
23747 
23748 	/*
23749 	 * Prime pump for IP
23750 	 * Include the adjustment for a source route if any.
23751 	 */
23752 	data_length -= tcp->tcp_ip_hdr_len;
23753 	data_length += tcp->tcp_sum;
23754 	data_length = (data_length >> 16) + (data_length & 0xFFFF);
23755 	U16_TO_ABE16(data_length, tcph->th_sum);
23756 	if (tcp->tcp_ip_forward_progress) {
23757 		ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23758 		*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23759 		tcp->tcp_ip_forward_progress = B_FALSE;
23760 	}
23761 	return (mp1);
23762 }
23763 
23764 /* This function handles the push timeout. */
23765 void
23766 tcp_push_timer(void *arg)
23767 {
23768 	conn_t	*connp = (conn_t *)arg;
23769 	tcp_t *tcp = connp->conn_tcp;
23770 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23771 	uint_t		flags;
23772 	sodirect_t	*sodp;
23773 
23774 	TCP_DBGSTAT(tcps, tcp_push_timer_cnt);
23775 
23776 	ASSERT(tcp->tcp_listener == NULL);
23777 
23778 	/*
23779 	 * We need to plug synchronous streams during our drain to prevent
23780 	 * a race with tcp_fuse_rrw() or tcp_fusion_rinfop().
23781 	 */
23782 	TCP_FUSE_SYNCSTR_PLUG_DRAIN(tcp);
23783 	tcp->tcp_push_tid = 0;
23784 
23785 	SOD_PTR_ENTER(tcp, sodp);
23786 	if (sodp != NULL) {
23787 		flags = tcp_rcv_sod_wakeup(tcp, sodp);
23788 		/* sod_wakeup() does the mutex_exit() */
23789 	} else if (tcp->tcp_rcv_list != NULL) {
23790 		flags = tcp_rcv_drain(tcp->tcp_rq, tcp);
23791 	}
23792 	if (flags == TH_ACK_NEEDED)
23793 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
23794 
23795 	TCP_FUSE_SYNCSTR_UNPLUG_DRAIN(tcp);
23796 }
23797 
23798 /*
23799  * This function handles delayed ACK timeout.
23800  */
23801 static void
23802 tcp_ack_timer(void *arg)
23803 {
23804 	conn_t	*connp = (conn_t *)arg;
23805 	tcp_t *tcp = connp->conn_tcp;
23806 	mblk_t *mp;
23807 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23808 
23809 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
23810 
23811 	tcp->tcp_ack_tid = 0;
23812 
23813 	if (tcp->tcp_fused)
23814 		return;
23815 
23816 	/*
23817 	 * Do not send ACK if there is no outstanding unack'ed data.
23818 	 */
23819 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
23820 		return;
23821 	}
23822 
23823 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
23824 		/*
23825 		 * Make sure we don't allow deferred ACKs to result in
23826 		 * timer-based ACKing.  If we have held off an ACK
23827 		 * when there was more than an mss here, and the timer
23828 		 * goes off, we have to worry about the possibility
23829 		 * that the sender isn't doing slow-start, or is out
23830 		 * of step with us for some other reason.  We fall
23831 		 * permanently back in the direction of
23832 		 * ACK-every-other-packet as suggested in RFC 1122.
23833 		 */
23834 		if (tcp->tcp_rack_abs_max > 2)
23835 			tcp->tcp_rack_abs_max--;
23836 		tcp->tcp_rack_cur_max = 2;
23837 	}
23838 	mp = tcp_ack_mp(tcp);
23839 
23840 	if (mp != NULL) {
23841 		BUMP_LOCAL(tcp->tcp_obsegs);
23842 		BUMP_MIB(&tcps->tcps_mib, tcpOutAck);
23843 		BUMP_MIB(&tcps->tcps_mib, tcpOutAckDelayed);
23844 		tcp_send_data(tcp, tcp->tcp_wq, mp);
23845 	}
23846 }
23847 
23848 
23849 /* Generate an ACK-only (no data) segment for a TCP endpoint */
23850 static mblk_t *
23851 tcp_ack_mp(tcp_t *tcp)
23852 {
23853 	uint32_t	seq_no;
23854 	tcp_stack_t	*tcps = tcp->tcp_tcps;
23855 
23856 	/*
23857 	 * There are a few cases to be considered while setting the sequence no.
23858 	 * Essentially, we can come here while processing an unacceptable pkt
23859 	 * in the TCPS_SYN_RCVD state, in which case we set the sequence number
23860 	 * to snxt (per RFC 793), note the swnd wouldn't have been set yet.
23861 	 * If we are here for a zero window probe, stick with suna. In all
23862 	 * other cases, we check if suna + swnd encompasses snxt and set
23863 	 * the sequence number to snxt, if so. If snxt falls outside the
23864 	 * window (the receiver probably shrunk its window), we will go with
23865 	 * suna + swnd, otherwise the sequence no will be unacceptable to the
23866 	 * receiver.
23867 	 */
23868 	if (tcp->tcp_zero_win_probe) {
23869 		seq_no = tcp->tcp_suna;
23870 	} else if (tcp->tcp_state == TCPS_SYN_RCVD) {
23871 		ASSERT(tcp->tcp_swnd == 0);
23872 		seq_no = tcp->tcp_snxt;
23873 	} else {
23874 		seq_no = SEQ_GT(tcp->tcp_snxt,
23875 		    (tcp->tcp_suna + tcp->tcp_swnd)) ?
23876 		    (tcp->tcp_suna + tcp->tcp_swnd) : tcp->tcp_snxt;
23877 	}
23878 
23879 	if (tcp->tcp_valid_bits) {
23880 		/*
23881 		 * For the complex case where we have to send some
23882 		 * controls (FIN or SYN), let tcp_xmit_mp do it.
23883 		 */
23884 		return (tcp_xmit_mp(tcp, NULL, 0, NULL, NULL, seq_no, B_FALSE,
23885 		    NULL, B_FALSE));
23886 	} else {
23887 		/* Generate a simple ACK */
23888 		int	data_length;
23889 		uchar_t	*rptr;
23890 		tcph_t	*tcph;
23891 		mblk_t	*mp1;
23892 		int32_t	tcp_hdr_len;
23893 		int32_t	tcp_tcp_hdr_len;
23894 		int32_t	num_sack_blk = 0;
23895 		int32_t sack_opt_len;
23896 
23897 		/*
23898 		 * Allocate space for TCP + IP headers
23899 		 * and link-level header
23900 		 */
23901 		if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
23902 			num_sack_blk = MIN(tcp->tcp_max_sack_blk,
23903 			    tcp->tcp_num_sack_blk);
23904 			sack_opt_len = num_sack_blk * sizeof (sack_blk_t) +
23905 			    TCPOPT_NOP_LEN * 2 + TCPOPT_HEADER_LEN;
23906 			tcp_hdr_len = tcp->tcp_hdr_len + sack_opt_len;
23907 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len + sack_opt_len;
23908 		} else {
23909 			tcp_hdr_len = tcp->tcp_hdr_len;
23910 			tcp_tcp_hdr_len = tcp->tcp_tcp_hdr_len;
23911 		}
23912 		mp1 = allocb(tcp_hdr_len + tcps->tcps_wroff_xtra, BPRI_MED);
23913 		if (!mp1)
23914 			return (NULL);
23915 
23916 		/* Update the latest receive window size in TCP header. */
23917 		U32_TO_ABE16(tcp->tcp_rwnd >> tcp->tcp_rcv_ws,
23918 		    tcp->tcp_tcph->th_win);
23919 		/* copy in prototype TCP + IP header */
23920 		rptr = mp1->b_rptr + tcps->tcps_wroff_xtra;
23921 		mp1->b_rptr = rptr;
23922 		mp1->b_wptr = rptr + tcp_hdr_len;
23923 		bcopy(tcp->tcp_iphc, rptr, tcp->tcp_hdr_len);
23924 
23925 		tcph = (tcph_t *)&rptr[tcp->tcp_ip_hdr_len];
23926 
23927 		/* Set the TCP sequence number. */
23928 		U32_TO_ABE32(seq_no, tcph->th_seq);
23929 
23930 		/* Set up the TCP flag field. */
23931 		tcph->th_flags[0] = (uchar_t)TH_ACK;
23932 		if (tcp->tcp_ecn_echo_on)
23933 			tcph->th_flags[0] |= TH_ECE;
23934 
23935 		tcp->tcp_rack = tcp->tcp_rnxt;
23936 		tcp->tcp_rack_cnt = 0;
23937 
23938 		/* fill in timestamp option if in use */
23939 		if (tcp->tcp_snd_ts_ok) {
23940 			uint32_t llbolt = (uint32_t)lbolt;
23941 
23942 			U32_TO_BE32(llbolt,
23943 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+4);
23944 			U32_TO_BE32(tcp->tcp_ts_recent,
23945 			    (char *)tcph+TCP_MIN_HEADER_LENGTH+8);
23946 		}
23947 
23948 		/* Fill in SACK options */
23949 		if (num_sack_blk > 0) {
23950 			uchar_t *wptr = (uchar_t *)tcph + tcp->tcp_tcp_hdr_len;
23951 			sack_blk_t *tmp;
23952 			int32_t	i;
23953 
23954 			wptr[0] = TCPOPT_NOP;
23955 			wptr[1] = TCPOPT_NOP;
23956 			wptr[2] = TCPOPT_SACK;
23957 			wptr[3] = TCPOPT_HEADER_LEN + num_sack_blk *
23958 			    sizeof (sack_blk_t);
23959 			wptr += TCPOPT_REAL_SACK_LEN;
23960 
23961 			tmp = tcp->tcp_sack_list;
23962 			for (i = 0; i < num_sack_blk; i++) {
23963 				U32_TO_BE32(tmp[i].begin, wptr);
23964 				wptr += sizeof (tcp_seq);
23965 				U32_TO_BE32(tmp[i].end, wptr);
23966 				wptr += sizeof (tcp_seq);
23967 			}
23968 			tcph->th_offset_and_rsrvd[0] += ((num_sack_blk * 2 + 1)
23969 			    << 4);
23970 		}
23971 
23972 		if (tcp->tcp_ipversion == IPV4_VERSION) {
23973 			((ipha_t *)rptr)->ipha_length = htons(tcp_hdr_len);
23974 		} else {
23975 			/* Check for ip6i_t header in sticky hdrs */
23976 			ip6_t *ip6 = (ip6_t *)(rptr +
23977 			    (((ip6_t *)rptr)->ip6_nxt == IPPROTO_RAW ?
23978 			    sizeof (ip6i_t) : 0));
23979 
23980 			ip6->ip6_plen = htons(tcp_hdr_len -
23981 			    ((char *)&tcp->tcp_ip6h[1] - tcp->tcp_iphc));
23982 		}
23983 
23984 		/*
23985 		 * Prime pump for checksum calculation in IP.  Include the
23986 		 * adjustment for a source route if any.
23987 		 */
23988 		data_length = tcp_tcp_hdr_len + tcp->tcp_sum;
23989 		data_length = (data_length >> 16) + (data_length & 0xFFFF);
23990 		U16_TO_ABE16(data_length, tcph->th_sum);
23991 
23992 		if (tcp->tcp_ip_forward_progress) {
23993 			ASSERT(tcp->tcp_ipversion == IPV6_VERSION);
23994 			*(uint32_t *)mp1->b_rptr  |= IP_FORWARD_PROG;
23995 			tcp->tcp_ip_forward_progress = B_FALSE;
23996 		}
23997 		return (mp1);
23998 	}
23999 }
24000 
24001 /*
24002  * Hash list insertion routine for tcp_t structures.
24003  * Inserts entries with the ones bound to a specific IP address first
24004  * followed by those bound to INADDR_ANY.
24005  */
24006 static void
24007 tcp_bind_hash_insert(tf_t *tbf, tcp_t *tcp, int caller_holds_lock)
24008 {
24009 	tcp_t	**tcpp;
24010 	tcp_t	*tcpnext;
24011 
24012 	if (tcp->tcp_ptpbhn != NULL) {
24013 		ASSERT(!caller_holds_lock);
24014 		tcp_bind_hash_remove(tcp);
24015 	}
24016 	tcpp = &tbf->tf_tcp;
24017 	if (!caller_holds_lock) {
24018 		mutex_enter(&tbf->tf_lock);
24019 	} else {
24020 		ASSERT(MUTEX_HELD(&tbf->tf_lock));
24021 	}
24022 	tcpnext = tcpp[0];
24023 	if (tcpnext) {
24024 		/*
24025 		 * If the new tcp bound to the INADDR_ANY address
24026 		 * and the first one in the list is not bound to
24027 		 * INADDR_ANY we skip all entries until we find the
24028 		 * first one bound to INADDR_ANY.
24029 		 * This makes sure that applications binding to a
24030 		 * specific address get preference over those binding to
24031 		 * INADDR_ANY.
24032 		 */
24033 		if (V6_OR_V4_INADDR_ANY(tcp->tcp_bound_source_v6) &&
24034 		    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6)) {
24035 			while ((tcpnext = tcpp[0]) != NULL &&
24036 			    !V6_OR_V4_INADDR_ANY(tcpnext->tcp_bound_source_v6))
24037 				tcpp = &(tcpnext->tcp_bind_hash);
24038 			if (tcpnext)
24039 				tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24040 		} else
24041 			tcpnext->tcp_ptpbhn = &tcp->tcp_bind_hash;
24042 	}
24043 	tcp->tcp_bind_hash = tcpnext;
24044 	tcp->tcp_ptpbhn = tcpp;
24045 	tcpp[0] = tcp;
24046 	if (!caller_holds_lock)
24047 		mutex_exit(&tbf->tf_lock);
24048 }
24049 
24050 /*
24051  * Hash list removal routine for tcp_t structures.
24052  */
24053 static void
24054 tcp_bind_hash_remove(tcp_t *tcp)
24055 {
24056 	tcp_t	*tcpnext;
24057 	kmutex_t *lockp;
24058 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24059 
24060 	if (tcp->tcp_ptpbhn == NULL)
24061 		return;
24062 
24063 	/*
24064 	 * Extract the lock pointer in case there are concurrent
24065 	 * hash_remove's for this instance.
24066 	 */
24067 	ASSERT(tcp->tcp_lport != 0);
24068 	lockp = &tcps->tcps_bind_fanout[TCP_BIND_HASH(tcp->tcp_lport)].tf_lock;
24069 
24070 	ASSERT(lockp != NULL);
24071 	mutex_enter(lockp);
24072 	if (tcp->tcp_ptpbhn) {
24073 		tcpnext = tcp->tcp_bind_hash;
24074 		if (tcpnext) {
24075 			tcpnext->tcp_ptpbhn = tcp->tcp_ptpbhn;
24076 			tcp->tcp_bind_hash = NULL;
24077 		}
24078 		*tcp->tcp_ptpbhn = tcpnext;
24079 		tcp->tcp_ptpbhn = NULL;
24080 	}
24081 	mutex_exit(lockp);
24082 }
24083 
24084 
24085 /*
24086  * Hash list lookup routine for tcp_t structures.
24087  * Returns with a CONN_INC_REF tcp structure. Caller must do a CONN_DEC_REF.
24088  */
24089 static tcp_t *
24090 tcp_acceptor_hash_lookup(t_uscalar_t id, tcp_stack_t *tcps)
24091 {
24092 	tf_t	*tf;
24093 	tcp_t	*tcp;
24094 
24095 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24096 	mutex_enter(&tf->tf_lock);
24097 	for (tcp = tf->tf_tcp; tcp != NULL;
24098 	    tcp = tcp->tcp_acceptor_hash) {
24099 		if (tcp->tcp_acceptor_id == id) {
24100 			CONN_INC_REF(tcp->tcp_connp);
24101 			mutex_exit(&tf->tf_lock);
24102 			return (tcp);
24103 		}
24104 	}
24105 	mutex_exit(&tf->tf_lock);
24106 	return (NULL);
24107 }
24108 
24109 
24110 /*
24111  * Hash list insertion routine for tcp_t structures.
24112  */
24113 void
24114 tcp_acceptor_hash_insert(t_uscalar_t id, tcp_t *tcp)
24115 {
24116 	tf_t	*tf;
24117 	tcp_t	**tcpp;
24118 	tcp_t	*tcpnext;
24119 	tcp_stack_t	*tcps = tcp->tcp_tcps;
24120 
24121 	tf = &tcps->tcps_acceptor_fanout[TCP_ACCEPTOR_HASH(id)];
24122 
24123 	if (tcp->tcp_ptpahn != NULL)
24124 		tcp_acceptor_hash_remove(tcp);
24125 	tcpp = &tf->tf_tcp;
24126 	mutex_enter(&tf->tf_lock);
24127 	tcpnext = tcpp[0];
24128 	if (tcpnext)
24129 		tcpnext->tcp_ptpahn = &tcp->tcp_acceptor_hash;
24130 	tcp->tcp_acceptor_hash = tcpnext;
24131 	tcp->tcp_ptpahn = tcpp;
24132 	tcpp[0] = tcp;
24133 	tcp->tcp_acceptor_lockp = &tf->tf_lock;	/* For tcp_*_hash_remove */
24134 	mutex_exit(&tf->tf_lock);
24135 }
24136 
24137 /*
24138  * Hash list removal routine for tcp_t structures.
24139  */
24140 static void
24141 tcp_acceptor_hash_remove(tcp_t *tcp)
24142 {
24143 	tcp_t	*tcpnext;
24144 	kmutex_t *lockp;
24145 
24146 	/*
24147 	 * Extract the lock pointer in case there are concurrent
24148 	 * hash_remove's for this instance.
24149 	 */
24150 	lockp = tcp->tcp_acceptor_lockp;
24151 
24152 	if (tcp->tcp_ptpahn == NULL)
24153 		return;
24154 
24155 	ASSERT(lockp != NULL);
24156 	mutex_enter(lockp);
24157 	if (tcp->tcp_ptpahn) {
24158 		tcpnext = tcp->tcp_acceptor_hash;
24159 		if (tcpnext) {
24160 			tcpnext->tcp_ptpahn = tcp->tcp_ptpahn;
24161 			tcp->tcp_acceptor_hash = NULL;
24162 		}
24163 		*tcp->tcp_ptpahn = tcpnext;
24164 		tcp->tcp_ptpahn = NULL;
24165 	}
24166 	mutex_exit(lockp);
24167 	tcp->tcp_acceptor_lockp = NULL;
24168 }
24169 
24170 /* Data for fast netmask macro used by tcp_hsp_lookup */
24171 
24172 static ipaddr_t netmasks[] = {
24173 	IN_CLASSA_NET, IN_CLASSA_NET, IN_CLASSB_NET,
24174 	IN_CLASSC_NET | IN_CLASSD_NET  /* Class C,D,E */
24175 };
24176 
24177 #define	netmask(addr) (netmasks[(ipaddr_t)(addr) >> 30])
24178 
24179 /*
24180  * XXX This routine should go away and instead we should use the metrics
24181  * associated with the routes to determine the default sndspace and rcvspace.
24182  */
24183 static tcp_hsp_t *
24184 tcp_hsp_lookup(ipaddr_t addr, tcp_stack_t *tcps)
24185 {
24186 	tcp_hsp_t *hsp = NULL;
24187 
24188 	/* Quick check without acquiring the lock. */
24189 	if (tcps->tcps_hsp_hash == NULL)
24190 		return (NULL);
24191 
24192 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24193 
24194 	/* This routine finds the best-matching HSP for address addr. */
24195 
24196 	if (tcps->tcps_hsp_hash) {
24197 		int i;
24198 		ipaddr_t srchaddr;
24199 		tcp_hsp_t *hsp_net;
24200 
24201 		/* We do three passes: host, network, and subnet. */
24202 
24203 		srchaddr = addr;
24204 
24205 		for (i = 1; i <= 3; i++) {
24206 			/* Look for exact match on srchaddr */
24207 
24208 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(srchaddr)];
24209 			while (hsp) {
24210 				if (hsp->tcp_hsp_vers == IPV4_VERSION &&
24211 				    hsp->tcp_hsp_addr == srchaddr)
24212 					break;
24213 				hsp = hsp->tcp_hsp_next;
24214 			}
24215 			ASSERT(hsp == NULL ||
24216 			    hsp->tcp_hsp_vers == IPV4_VERSION);
24217 
24218 			/*
24219 			 * If this is the first pass:
24220 			 *   If we found a match, great, return it.
24221 			 *   If not, search for the network on the second pass.
24222 			 */
24223 
24224 			if (i == 1)
24225 				if (hsp)
24226 					break;
24227 				else
24228 				{
24229 					srchaddr = addr & netmask(addr);
24230 					continue;
24231 				}
24232 
24233 			/*
24234 			 * If this is the second pass:
24235 			 *   If we found a match, but there's a subnet mask,
24236 			 *    save the match but try again using the subnet
24237 			 *    mask on the third pass.
24238 			 *   Otherwise, return whatever we found.
24239 			 */
24240 
24241 			if (i == 2) {
24242 				if (hsp && hsp->tcp_hsp_subnet) {
24243 					hsp_net = hsp;
24244 					srchaddr = addr & hsp->tcp_hsp_subnet;
24245 					continue;
24246 				} else {
24247 					break;
24248 				}
24249 			}
24250 
24251 			/*
24252 			 * This must be the third pass.  If we didn't find
24253 			 * anything, return the saved network HSP instead.
24254 			 */
24255 
24256 			if (!hsp)
24257 				hsp = hsp_net;
24258 		}
24259 	}
24260 
24261 	rw_exit(&tcps->tcps_hsp_lock);
24262 	return (hsp);
24263 }
24264 
24265 /*
24266  * XXX Equally broken as the IPv4 routine. Doesn't handle longest
24267  * match lookup.
24268  */
24269 static tcp_hsp_t *
24270 tcp_hsp_lookup_ipv6(in6_addr_t *v6addr, tcp_stack_t *tcps)
24271 {
24272 	tcp_hsp_t *hsp = NULL;
24273 
24274 	/* Quick check without acquiring the lock. */
24275 	if (tcps->tcps_hsp_hash == NULL)
24276 		return (NULL);
24277 
24278 	rw_enter(&tcps->tcps_hsp_lock, RW_READER);
24279 
24280 	/* This routine finds the best-matching HSP for address addr. */
24281 
24282 	if (tcps->tcps_hsp_hash) {
24283 		int i;
24284 		in6_addr_t v6srchaddr;
24285 		tcp_hsp_t *hsp_net;
24286 
24287 		/* We do three passes: host, network, and subnet. */
24288 
24289 		v6srchaddr = *v6addr;
24290 
24291 		for (i = 1; i <= 3; i++) {
24292 			/* Look for exact match on srchaddr */
24293 
24294 			hsp = tcps->tcps_hsp_hash[TCP_HSP_HASH(
24295 			    V4_PART_OF_V6(v6srchaddr))];
24296 			while (hsp) {
24297 				if (hsp->tcp_hsp_vers == IPV6_VERSION &&
24298 				    IN6_ARE_ADDR_EQUAL(&hsp->tcp_hsp_addr_v6,
24299 				    &v6srchaddr))
24300 					break;
24301 				hsp = hsp->tcp_hsp_next;
24302 			}
24303 
24304 			/*
24305 			 * If this is the first pass:
24306 			 *   If we found a match, great, return it.
24307 			 *   If not, search for the network on the second pass.
24308 			 */
24309 
24310 			if (i == 1)
24311 				if (hsp)
24312 					break;
24313 				else {
24314 					/* Assume a 64 bit mask */
24315 					v6srchaddr.s6_addr32[0] =
24316 					    v6addr->s6_addr32[0];
24317 					v6srchaddr.s6_addr32[1] =
24318 					    v6addr->s6_addr32[1];
24319 					v6srchaddr.s6_addr32[2] = 0;
24320 					v6srchaddr.s6_addr32[3] = 0;
24321 					continue;
24322 				}
24323 
24324 			/*
24325 			 * If this is the second pass:
24326 			 *   If we found a match, but there's a subnet mask,
24327 			 *    save the match but try again using the subnet
24328 			 *    mask on the third pass.
24329 			 *   Otherwise, return whatever we found.
24330 			 */
24331 
24332 			if (i == 2) {
24333 				ASSERT(hsp == NULL ||
24334 				    hsp->tcp_hsp_vers == IPV6_VERSION);
24335 				if (hsp &&
24336 				    !IN6_IS_ADDR_UNSPECIFIED(
24337 				    &hsp->tcp_hsp_subnet_v6)) {
24338 					hsp_net = hsp;
24339 					V6_MASK_COPY(*v6addr,
24340 					    hsp->tcp_hsp_subnet_v6, v6srchaddr);
24341 					continue;
24342 				} else {
24343 					break;
24344 				}
24345 			}
24346 
24347 			/*
24348 			 * This must be the third pass.  If we didn't find
24349 			 * anything, return the saved network HSP instead.
24350 			 */
24351 
24352 			if (!hsp)
24353 				hsp = hsp_net;
24354 		}
24355 	}
24356 
24357 	rw_exit(&tcps->tcps_hsp_lock);
24358 	return (hsp);
24359 }
24360 
24361 /*
24362  * Type three generator adapted from the random() function in 4.4 BSD:
24363  */
24364 
24365 /*
24366  * Copyright (c) 1983, 1993
24367  *	The Regents of the University of California.  All rights reserved.
24368  *
24369  * Redistribution and use in source and binary forms, with or without
24370  * modification, are permitted provided that the following conditions
24371  * are met:
24372  * 1. Redistributions of source code must retain the above copyright
24373  *    notice, this list of conditions and the following disclaimer.
24374  * 2. Redistributions in binary form must reproduce the above copyright
24375  *    notice, this list of conditions and the following disclaimer in the
24376  *    documentation and/or other materials provided with the distribution.
24377  * 3. All advertising materials mentioning features or use of this software
24378  *    must display the following acknowledgement:
24379  *	This product includes software developed by the University of
24380  *	California, Berkeley and its contributors.
24381  * 4. Neither the name of the University nor the names of its contributors
24382  *    may be used to endorse or promote products derived from this software
24383  *    without specific prior written permission.
24384  *
24385  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24386  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24387  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24388  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24389  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24390  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24391  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24392  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24393  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24394  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24395  * SUCH DAMAGE.
24396  */
24397 
24398 /* Type 3 -- x**31 + x**3 + 1 */
24399 #define	DEG_3		31
24400 #define	SEP_3		3
24401 
24402 
24403 /* Protected by tcp_random_lock */
24404 static int tcp_randtbl[DEG_3 + 1];
24405 
24406 static int *tcp_random_fptr = &tcp_randtbl[SEP_3 + 1];
24407 static int *tcp_random_rptr = &tcp_randtbl[1];
24408 
24409 static int *tcp_random_state = &tcp_randtbl[1];
24410 static int *tcp_random_end_ptr = &tcp_randtbl[DEG_3 + 1];
24411 
24412 kmutex_t tcp_random_lock;
24413 
24414 void
24415 tcp_random_init(void)
24416 {
24417 	int i;
24418 	hrtime_t hrt;
24419 	time_t wallclock;
24420 	uint64_t result;
24421 
24422 	/*
24423 	 * Use high-res timer and current time for seed.  Gethrtime() returns
24424 	 * a longlong, which may contain resolution down to nanoseconds.
24425 	 * The current time will either be a 32-bit or a 64-bit quantity.
24426 	 * XOR the two together in a 64-bit result variable.
24427 	 * Convert the result to a 32-bit value by multiplying the high-order
24428 	 * 32-bits by the low-order 32-bits.
24429 	 */
24430 
24431 	hrt = gethrtime();
24432 	(void) drv_getparm(TIME, &wallclock);
24433 	result = (uint64_t)wallclock ^ (uint64_t)hrt;
24434 	mutex_enter(&tcp_random_lock);
24435 	tcp_random_state[0] = ((result >> 32) & 0xffffffff) *
24436 	    (result & 0xffffffff);
24437 
24438 	for (i = 1; i < DEG_3; i++)
24439 		tcp_random_state[i] = 1103515245 * tcp_random_state[i - 1]
24440 		    + 12345;
24441 	tcp_random_fptr = &tcp_random_state[SEP_3];
24442 	tcp_random_rptr = &tcp_random_state[0];
24443 	mutex_exit(&tcp_random_lock);
24444 	for (i = 0; i < 10 * DEG_3; i++)
24445 		(void) tcp_random();
24446 }
24447 
24448 /*
24449  * tcp_random: Return a random number in the range [1 - (128K + 1)].
24450  * This range is selected to be approximately centered on TCP_ISS / 2,
24451  * and easy to compute. We get this value by generating a 32-bit random
24452  * number, selecting out the high-order 17 bits, and then adding one so
24453  * that we never return zero.
24454  */
24455 int
24456 tcp_random(void)
24457 {
24458 	int i;
24459 
24460 	mutex_enter(&tcp_random_lock);
24461 	*tcp_random_fptr += *tcp_random_rptr;
24462 
24463 	/*
24464 	 * The high-order bits are more random than the low-order bits,
24465 	 * so we select out the high-order 17 bits and add one so that
24466 	 * we never return zero.
24467 	 */
24468 	i = ((*tcp_random_fptr >> 15) & 0x1ffff) + 1;
24469 	if (++tcp_random_fptr >= tcp_random_end_ptr) {
24470 		tcp_random_fptr = tcp_random_state;
24471 		++tcp_random_rptr;
24472 	} else if (++tcp_random_rptr >= tcp_random_end_ptr)
24473 		tcp_random_rptr = tcp_random_state;
24474 
24475 	mutex_exit(&tcp_random_lock);
24476 	return (i);
24477 }
24478 
24479 /*
24480  * XXX This will go away when TPI is extended to send
24481  * info reqs to sockfs/timod .....
24482  * Given a queue, set the max packet size for the write
24483  * side of the queue below stream head.  This value is
24484  * cached on the stream head.
24485  * Returns 1 on success, 0 otherwise.
24486  */
24487 static int
24488 setmaxps(queue_t *q, int maxpsz)
24489 {
24490 	struct stdata	*stp;
24491 	queue_t		*wq;
24492 	stp = STREAM(q);
24493 
24494 	/*
24495 	 * At this point change of a queue parameter is not allowed
24496 	 * when a multiplexor is sitting on top.
24497 	 */
24498 	if (stp->sd_flag & STPLEX)
24499 		return (0);
24500 
24501 	claimstr(stp->sd_wrq);
24502 	wq = stp->sd_wrq->q_next;
24503 	ASSERT(wq != NULL);
24504 	(void) strqset(wq, QMAXPSZ, 0, maxpsz);
24505 	releasestr(stp->sd_wrq);
24506 	return (1);
24507 }
24508 
24509 static int
24510 tcp_conprim_opt_process(tcp_t *tcp, mblk_t *mp, int *do_disconnectp,
24511     int *t_errorp, int *sys_errorp)
24512 {
24513 	int error;
24514 	int is_absreq_failure;
24515 	t_scalar_t *opt_lenp;
24516 	t_scalar_t opt_offset;
24517 	int prim_type;
24518 	struct T_conn_req *tcreqp;
24519 	struct T_conn_res *tcresp;
24520 	cred_t *cr;
24521 
24522 	cr = DB_CREDDEF(mp, tcp->tcp_cred);
24523 
24524 	prim_type = ((union T_primitives *)mp->b_rptr)->type;
24525 	ASSERT(prim_type == T_CONN_REQ || prim_type == O_T_CONN_RES ||
24526 	    prim_type == T_CONN_RES);
24527 
24528 	switch (prim_type) {
24529 	case T_CONN_REQ:
24530 		tcreqp = (struct T_conn_req *)mp->b_rptr;
24531 		opt_offset = tcreqp->OPT_offset;
24532 		opt_lenp = (t_scalar_t *)&tcreqp->OPT_length;
24533 		break;
24534 	case O_T_CONN_RES:
24535 	case T_CONN_RES:
24536 		tcresp = (struct T_conn_res *)mp->b_rptr;
24537 		opt_offset = tcresp->OPT_offset;
24538 		opt_lenp = (t_scalar_t *)&tcresp->OPT_length;
24539 		break;
24540 	}
24541 
24542 	*t_errorp = 0;
24543 	*sys_errorp = 0;
24544 	*do_disconnectp = 0;
24545 
24546 	error = tpi_optcom_buf(tcp->tcp_wq, mp, opt_lenp,
24547 	    opt_offset, cr, &tcp_opt_obj,
24548 	    NULL, &is_absreq_failure);
24549 
24550 	switch (error) {
24551 	case  0:		/* no error */
24552 		ASSERT(is_absreq_failure == 0);
24553 		return (0);
24554 	case ENOPROTOOPT:
24555 		*t_errorp = TBADOPT;
24556 		break;
24557 	case EACCES:
24558 		*t_errorp = TACCES;
24559 		break;
24560 	default:
24561 		*t_errorp = TSYSERR; *sys_errorp = error;
24562 		break;
24563 	}
24564 	if (is_absreq_failure != 0) {
24565 		/*
24566 		 * The connection request should get the local ack
24567 		 * T_OK_ACK and then a T_DISCON_IND.
24568 		 */
24569 		*do_disconnectp = 1;
24570 	}
24571 	return (-1);
24572 }
24573 
24574 /*
24575  * Split this function out so that if the secret changes, I'm okay.
24576  *
24577  * Initialize the tcp_iss_cookie and tcp_iss_key.
24578  */
24579 
24580 #define	PASSWD_SIZE 16  /* MUST be multiple of 4 */
24581 
24582 static void
24583 tcp_iss_key_init(uint8_t *phrase, int len, tcp_stack_t *tcps)
24584 {
24585 	struct {
24586 		int32_t current_time;
24587 		uint32_t randnum;
24588 		uint16_t pad;
24589 		uint8_t ether[6];
24590 		uint8_t passwd[PASSWD_SIZE];
24591 	} tcp_iss_cookie;
24592 	time_t t;
24593 
24594 	/*
24595 	 * Start with the current absolute time.
24596 	 */
24597 	(void) drv_getparm(TIME, &t);
24598 	tcp_iss_cookie.current_time = t;
24599 
24600 	/*
24601 	 * XXX - Need a more random number per RFC 1750, not this crap.
24602 	 * OTOH, if what follows is pretty random, then I'm in better shape.
24603 	 */
24604 	tcp_iss_cookie.randnum = (uint32_t)(gethrtime() + tcp_random());
24605 	tcp_iss_cookie.pad = 0x365c;  /* Picked from HMAC pad values. */
24606 
24607 	/*
24608 	 * The cpu_type_info is pretty non-random.  Ugggh.  It does serve
24609 	 * as a good template.
24610 	 */
24611 	bcopy(&cpu_list->cpu_type_info, &tcp_iss_cookie.passwd,
24612 	    min(PASSWD_SIZE, sizeof (cpu_list->cpu_type_info)));
24613 
24614 	/*
24615 	 * The pass-phrase.  Normally this is supplied by user-called NDD.
24616 	 */
24617 	bcopy(phrase, &tcp_iss_cookie.passwd, min(PASSWD_SIZE, len));
24618 
24619 	/*
24620 	 * See 4010593 if this section becomes a problem again,
24621 	 * but the local ethernet address is useful here.
24622 	 */
24623 	(void) localetheraddr(NULL,
24624 	    (struct ether_addr *)&tcp_iss_cookie.ether);
24625 
24626 	/*
24627 	 * Hash 'em all together.  The MD5Final is called per-connection.
24628 	 */
24629 	mutex_enter(&tcps->tcps_iss_key_lock);
24630 	MD5Init(&tcps->tcps_iss_key);
24631 	MD5Update(&tcps->tcps_iss_key, (uchar_t *)&tcp_iss_cookie,
24632 	    sizeof (tcp_iss_cookie));
24633 	mutex_exit(&tcps->tcps_iss_key_lock);
24634 }
24635 
24636 /*
24637  * Set the RFC 1948 pass phrase
24638  */
24639 /* ARGSUSED */
24640 static int
24641 tcp_1948_phrase_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
24642     cred_t *cr)
24643 {
24644 	tcp_stack_t	*tcps = Q_TO_TCP(q)->tcp_tcps;
24645 
24646 	/*
24647 	 * Basically, value contains a new pass phrase.  Pass it along!
24648 	 */
24649 	tcp_iss_key_init((uint8_t *)value, strlen(value), tcps);
24650 	return (0);
24651 }
24652 
24653 /* ARGSUSED */
24654 static int
24655 tcp_sack_info_constructor(void *buf, void *cdrarg, int kmflags)
24656 {
24657 	bzero(buf, sizeof (tcp_sack_info_t));
24658 	return (0);
24659 }
24660 
24661 /* ARGSUSED */
24662 static int
24663 tcp_iphc_constructor(void *buf, void *cdrarg, int kmflags)
24664 {
24665 	bzero(buf, TCP_MAX_COMBINED_HEADER_LENGTH);
24666 	return (0);
24667 }
24668 
24669 /*
24670  * Make sure we wait until the default queue is setup, yet allow
24671  * tcp_g_q_create() to open a TCP stream.
24672  * We need to allow tcp_g_q_create() do do an open
24673  * of tcp, hence we compare curhread.
24674  * All others have to wait until the tcps_g_q has been
24675  * setup.
24676  */
24677 void
24678 tcp_g_q_setup(tcp_stack_t *tcps)
24679 {
24680 	mutex_enter(&tcps->tcps_g_q_lock);
24681 	if (tcps->tcps_g_q != NULL) {
24682 		mutex_exit(&tcps->tcps_g_q_lock);
24683 		return;
24684 	}
24685 	if (tcps->tcps_g_q_creator == NULL) {
24686 		/* This thread will set it up */
24687 		tcps->tcps_g_q_creator = curthread;
24688 		mutex_exit(&tcps->tcps_g_q_lock);
24689 		tcp_g_q_create(tcps);
24690 		mutex_enter(&tcps->tcps_g_q_lock);
24691 		ASSERT(tcps->tcps_g_q_creator == curthread);
24692 		tcps->tcps_g_q_creator = NULL;
24693 		cv_signal(&tcps->tcps_g_q_cv);
24694 		ASSERT(tcps->tcps_g_q != NULL);
24695 		mutex_exit(&tcps->tcps_g_q_lock);
24696 		return;
24697 	}
24698 	/* Everybody but the creator has to wait */
24699 	if (tcps->tcps_g_q_creator != curthread) {
24700 		while (tcps->tcps_g_q == NULL)
24701 			cv_wait(&tcps->tcps_g_q_cv, &tcps->tcps_g_q_lock);
24702 	}
24703 	mutex_exit(&tcps->tcps_g_q_lock);
24704 }
24705 
24706 #define	IP	"ip"
24707 
24708 #define	TCP6DEV		"/devices/pseudo/tcp6@0:tcp6"
24709 
24710 /*
24711  * Create a default tcp queue here instead of in strplumb
24712  */
24713 void
24714 tcp_g_q_create(tcp_stack_t *tcps)
24715 {
24716 	int error;
24717 	ldi_handle_t	lh = NULL;
24718 	ldi_ident_t	li = NULL;
24719 	int		rval;
24720 	cred_t		*cr;
24721 	major_t IP_MAJ;
24722 
24723 #ifdef NS_DEBUG
24724 	(void) printf("tcp_g_q_create()\n");
24725 #endif
24726 
24727 	IP_MAJ = ddi_name_to_major(IP);
24728 
24729 	ASSERT(tcps->tcps_g_q_creator == curthread);
24730 
24731 	error = ldi_ident_from_major(IP_MAJ, &li);
24732 	if (error) {
24733 #ifdef DEBUG
24734 		printf("tcp_g_q_create: lyr ident get failed error %d\n",
24735 		    error);
24736 #endif
24737 		return;
24738 	}
24739 
24740 	cr = zone_get_kcred(netstackid_to_zoneid(
24741 	    tcps->tcps_netstack->netstack_stackid));
24742 	ASSERT(cr != NULL);
24743 	/*
24744 	 * We set the tcp default queue to IPv6 because IPv4 falls
24745 	 * back to IPv6 when it can't find a client, but
24746 	 * IPv6 does not fall back to IPv4.
24747 	 */
24748 	error = ldi_open_by_name(TCP6DEV, FREAD|FWRITE, cr, &lh, li);
24749 	if (error) {
24750 #ifdef DEBUG
24751 		printf("tcp_g_q_create: open of TCP6DEV failed error %d\n",
24752 		    error);
24753 #endif
24754 		goto out;
24755 	}
24756 
24757 	/*
24758 	 * This ioctl causes the tcp framework to cache a pointer to
24759 	 * this stream, so we don't want to close the stream after
24760 	 * this operation.
24761 	 * Use the kernel credentials that are for the zone we're in.
24762 	 */
24763 	error = ldi_ioctl(lh, TCP_IOC_DEFAULT_Q,
24764 	    (intptr_t)0, FKIOCTL, cr, &rval);
24765 	if (error) {
24766 #ifdef DEBUG
24767 		printf("tcp_g_q_create: ioctl TCP_IOC_DEFAULT_Q failed "
24768 		    "error %d\n", error);
24769 #endif
24770 		goto out;
24771 	}
24772 	tcps->tcps_g_q_lh = lh;	/* For tcp_g_q_close */
24773 	lh = NULL;
24774 out:
24775 	/* Close layered handles */
24776 	if (li)
24777 		ldi_ident_release(li);
24778 	/* Keep cred around until _inactive needs it */
24779 	tcps->tcps_g_q_cr = cr;
24780 }
24781 
24782 /*
24783  * We keep tcp_g_q set until all other tcp_t's in the zone
24784  * has gone away, and then when tcp_g_q_inactive() is called
24785  * we clear it.
24786  */
24787 void
24788 tcp_g_q_destroy(tcp_stack_t *tcps)
24789 {
24790 #ifdef NS_DEBUG
24791 	(void) printf("tcp_g_q_destroy()for stack %d\n",
24792 	    tcps->tcps_netstack->netstack_stackid);
24793 #endif
24794 
24795 	if (tcps->tcps_g_q == NULL) {
24796 		return;	/* Nothing to cleanup */
24797 	}
24798 	/*
24799 	 * Drop reference corresponding to the default queue.
24800 	 * This reference was added from tcp_open when the default queue
24801 	 * was created, hence we compensate for this extra drop in
24802 	 * tcp_g_q_close. If the refcnt drops to zero here it means
24803 	 * the default queue was the last one to be open, in which
24804 	 * case, then tcp_g_q_inactive will be
24805 	 * called as a result of the refrele.
24806 	 */
24807 	TCPS_REFRELE(tcps);
24808 }
24809 
24810 /*
24811  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24812  * Run by tcp_q_q_inactive using a taskq.
24813  */
24814 static void
24815 tcp_g_q_close(void *arg)
24816 {
24817 	tcp_stack_t *tcps = arg;
24818 	int error;
24819 	ldi_handle_t	lh = NULL;
24820 	ldi_ident_t	li = NULL;
24821 	cred_t		*cr;
24822 	major_t IP_MAJ;
24823 
24824 	IP_MAJ = ddi_name_to_major(IP);
24825 
24826 #ifdef NS_DEBUG
24827 	(void) printf("tcp_g_q_inactive() for stack %d refcnt %d\n",
24828 	    tcps->tcps_netstack->netstack_stackid,
24829 	    tcps->tcps_netstack->netstack_refcnt);
24830 #endif
24831 	lh = tcps->tcps_g_q_lh;
24832 	if (lh == NULL)
24833 		return;	/* Nothing to cleanup */
24834 
24835 	ASSERT(tcps->tcps_refcnt == 1);
24836 	ASSERT(tcps->tcps_g_q != NULL);
24837 
24838 	error = ldi_ident_from_major(IP_MAJ, &li);
24839 	if (error) {
24840 #ifdef DEBUG
24841 		printf("tcp_g_q_inactive: lyr ident get failed error %d\n",
24842 		    error);
24843 #endif
24844 		return;
24845 	}
24846 
24847 	cr = tcps->tcps_g_q_cr;
24848 	tcps->tcps_g_q_cr = NULL;
24849 	ASSERT(cr != NULL);
24850 
24851 	/*
24852 	 * Make sure we can break the recursion when tcp_close decrements
24853 	 * the reference count causing g_q_inactive to be called again.
24854 	 */
24855 	tcps->tcps_g_q_lh = NULL;
24856 
24857 	/* close the default queue */
24858 	(void) ldi_close(lh, FREAD|FWRITE, cr);
24859 	/*
24860 	 * At this point in time tcps and the rest of netstack_t might
24861 	 * have been deleted.
24862 	 */
24863 	tcps = NULL;
24864 
24865 	/* Close layered handles */
24866 	ldi_ident_release(li);
24867 	crfree(cr);
24868 }
24869 
24870 /*
24871  * Called when last tcp_t drops reference count using TCPS_REFRELE.
24872  *
24873  * Have to ensure that the ldi routines are not used by an
24874  * interrupt thread by using a taskq.
24875  */
24876 void
24877 tcp_g_q_inactive(tcp_stack_t *tcps)
24878 {
24879 	if (tcps->tcps_g_q_lh == NULL)
24880 		return;	/* Nothing to cleanup */
24881 
24882 	ASSERT(tcps->tcps_refcnt == 0);
24883 	TCPS_REFHOLD(tcps); /* Compensate for what g_q_destroy did */
24884 
24885 	if (servicing_interrupt()) {
24886 		(void) taskq_dispatch(tcp_taskq, tcp_g_q_close,
24887 		    (void *) tcps, TQ_SLEEP);
24888 	} else {
24889 		tcp_g_q_close(tcps);
24890 	}
24891 }
24892 
24893 /*
24894  * Called by IP when IP is loaded into the kernel
24895  */
24896 void
24897 tcp_ddi_g_init(void)
24898 {
24899 	tcp_timercache = kmem_cache_create("tcp_timercache",
24900 	    sizeof (tcp_timer_t) + sizeof (mblk_t), 0,
24901 	    NULL, NULL, NULL, NULL, NULL, 0);
24902 
24903 	tcp_sack_info_cache = kmem_cache_create("tcp_sack_info_cache",
24904 	    sizeof (tcp_sack_info_t), 0,
24905 	    tcp_sack_info_constructor, NULL, NULL, NULL, NULL, 0);
24906 
24907 	tcp_iphc_cache = kmem_cache_create("tcp_iphc_cache",
24908 	    TCP_MAX_COMBINED_HEADER_LENGTH, 0,
24909 	    tcp_iphc_constructor, NULL, NULL, NULL, NULL, 0);
24910 
24911 	mutex_init(&tcp_random_lock, NULL, MUTEX_DEFAULT, NULL);
24912 
24913 	/* Initialize the random number generator */
24914 	tcp_random_init();
24915 
24916 	tcp_squeue_wput_proc = tcp_squeue_switch(tcp_squeue_wput);
24917 	tcp_squeue_close_proc = tcp_squeue_switch(tcp_squeue_close);
24918 
24919 	/* A single callback independently of how many netstacks we have */
24920 	ip_squeue_init(tcp_squeue_add);
24921 
24922 	tcp_g_kstat = tcp_g_kstat_init(&tcp_g_statistics);
24923 
24924 	tcp_taskq = taskq_create("tcp_taskq", 1, minclsyspri, 1, 1,
24925 	    TASKQ_PREPOPULATE);
24926 
24927 	/*
24928 	 * We want to be informed each time a stack is created or
24929 	 * destroyed in the kernel, so we can maintain the
24930 	 * set of tcp_stack_t's.
24931 	 */
24932 	netstack_register(NS_TCP, tcp_stack_init, tcp_stack_shutdown,
24933 	    tcp_stack_fini);
24934 }
24935 
24936 
24937 /*
24938  * Initialize the TCP stack instance.
24939  */
24940 static void *
24941 tcp_stack_init(netstackid_t stackid, netstack_t *ns)
24942 {
24943 	tcp_stack_t	*tcps;
24944 	tcpparam_t	*pa;
24945 	int		i;
24946 
24947 	tcps = (tcp_stack_t *)kmem_zalloc(sizeof (*tcps), KM_SLEEP);
24948 	tcps->tcps_netstack = ns;
24949 
24950 	/* Initialize locks */
24951 	rw_init(&tcps->tcps_hsp_lock, NULL, RW_DEFAULT, NULL);
24952 	mutex_init(&tcps->tcps_g_q_lock, NULL, MUTEX_DEFAULT, NULL);
24953 	cv_init(&tcps->tcps_g_q_cv, NULL, CV_DEFAULT, NULL);
24954 	mutex_init(&tcps->tcps_iss_key_lock, NULL, MUTEX_DEFAULT, NULL);
24955 	mutex_init(&tcps->tcps_epriv_port_lock, NULL, MUTEX_DEFAULT, NULL);
24956 
24957 	tcps->tcps_g_num_epriv_ports = TCP_NUM_EPRIV_PORTS;
24958 	tcps->tcps_g_epriv_ports[0] = 2049;
24959 	tcps->tcps_g_epriv_ports[1] = 4045;
24960 	tcps->tcps_min_anonpriv_port = 512;
24961 
24962 	tcps->tcps_bind_fanout = kmem_zalloc(sizeof (tf_t) *
24963 	    TCP_BIND_FANOUT_SIZE, KM_SLEEP);
24964 	tcps->tcps_acceptor_fanout = kmem_zalloc(sizeof (tf_t) *
24965 	    TCP_FANOUT_SIZE, KM_SLEEP);
24966 
24967 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
24968 		mutex_init(&tcps->tcps_bind_fanout[i].tf_lock, NULL,
24969 		    MUTEX_DEFAULT, NULL);
24970 	}
24971 
24972 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
24973 		mutex_init(&tcps->tcps_acceptor_fanout[i].tf_lock, NULL,
24974 		    MUTEX_DEFAULT, NULL);
24975 	}
24976 
24977 	/* TCP's IPsec code calls the packet dropper. */
24978 	ip_drop_register(&tcps->tcps_dropper, "TCP IPsec policy enforcement");
24979 
24980 	pa = (tcpparam_t *)kmem_alloc(sizeof (lcl_tcp_param_arr), KM_SLEEP);
24981 	tcps->tcps_params = pa;
24982 	bcopy(lcl_tcp_param_arr, tcps->tcps_params, sizeof (lcl_tcp_param_arr));
24983 
24984 	(void) tcp_param_register(&tcps->tcps_g_nd, tcps->tcps_params,
24985 	    A_CNT(lcl_tcp_param_arr), tcps);
24986 
24987 	/*
24988 	 * Note: To really walk the device tree you need the devinfo
24989 	 * pointer to your device which is only available after probe/attach.
24990 	 * The following is safe only because it uses ddi_root_node()
24991 	 */
24992 	tcp_max_optsize = optcom_max_optsize(tcp_opt_obj.odb_opt_des_arr,
24993 	    tcp_opt_obj.odb_opt_arr_cnt);
24994 
24995 	/*
24996 	 * Initialize RFC 1948 secret values.  This will probably be reset once
24997 	 * by the boot scripts.
24998 	 *
24999 	 * Use NULL name, as the name is caught by the new lockstats.
25000 	 *
25001 	 * Initialize with some random, non-guessable string, like the global
25002 	 * T_INFO_ACK.
25003 	 */
25004 
25005 	tcp_iss_key_init((uint8_t *)&tcp_g_t_info_ack,
25006 	    sizeof (tcp_g_t_info_ack), tcps);
25007 
25008 	tcps->tcps_kstat = tcp_kstat2_init(stackid, &tcps->tcps_statistics);
25009 	tcps->tcps_mibkp = tcp_kstat_init(stackid, tcps);
25010 
25011 	return (tcps);
25012 }
25013 
25014 /*
25015  * Called when the IP module is about to be unloaded.
25016  */
25017 void
25018 tcp_ddi_g_destroy(void)
25019 {
25020 	tcp_g_kstat_fini(tcp_g_kstat);
25021 	tcp_g_kstat = NULL;
25022 	bzero(&tcp_g_statistics, sizeof (tcp_g_statistics));
25023 
25024 	mutex_destroy(&tcp_random_lock);
25025 
25026 	kmem_cache_destroy(tcp_timercache);
25027 	kmem_cache_destroy(tcp_sack_info_cache);
25028 	kmem_cache_destroy(tcp_iphc_cache);
25029 
25030 	netstack_unregister(NS_TCP);
25031 	taskq_destroy(tcp_taskq);
25032 }
25033 
25034 /*
25035  * Shut down the TCP stack instance.
25036  */
25037 /* ARGSUSED */
25038 static void
25039 tcp_stack_shutdown(netstackid_t stackid, void *arg)
25040 {
25041 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25042 
25043 	tcp_g_q_destroy(tcps);
25044 }
25045 
25046 /*
25047  * Free the TCP stack instance.
25048  */
25049 static void
25050 tcp_stack_fini(netstackid_t stackid, void *arg)
25051 {
25052 	tcp_stack_t *tcps = (tcp_stack_t *)arg;
25053 	int i;
25054 
25055 	nd_free(&tcps->tcps_g_nd);
25056 	kmem_free(tcps->tcps_params, sizeof (lcl_tcp_param_arr));
25057 	tcps->tcps_params = NULL;
25058 	kmem_free(tcps->tcps_wroff_xtra_param, sizeof (tcpparam_t));
25059 	tcps->tcps_wroff_xtra_param = NULL;
25060 	kmem_free(tcps->tcps_mdt_head_param, sizeof (tcpparam_t));
25061 	tcps->tcps_mdt_head_param = NULL;
25062 	kmem_free(tcps->tcps_mdt_tail_param, sizeof (tcpparam_t));
25063 	tcps->tcps_mdt_tail_param = NULL;
25064 	kmem_free(tcps->tcps_mdt_max_pbufs_param, sizeof (tcpparam_t));
25065 	tcps->tcps_mdt_max_pbufs_param = NULL;
25066 
25067 	for (i = 0; i < TCP_BIND_FANOUT_SIZE; i++) {
25068 		ASSERT(tcps->tcps_bind_fanout[i].tf_tcp == NULL);
25069 		mutex_destroy(&tcps->tcps_bind_fanout[i].tf_lock);
25070 	}
25071 
25072 	for (i = 0; i < TCP_FANOUT_SIZE; i++) {
25073 		ASSERT(tcps->tcps_acceptor_fanout[i].tf_tcp == NULL);
25074 		mutex_destroy(&tcps->tcps_acceptor_fanout[i].tf_lock);
25075 	}
25076 
25077 	kmem_free(tcps->tcps_bind_fanout, sizeof (tf_t) * TCP_BIND_FANOUT_SIZE);
25078 	tcps->tcps_bind_fanout = NULL;
25079 
25080 	kmem_free(tcps->tcps_acceptor_fanout, sizeof (tf_t) * TCP_FANOUT_SIZE);
25081 	tcps->tcps_acceptor_fanout = NULL;
25082 
25083 	mutex_destroy(&tcps->tcps_iss_key_lock);
25084 	rw_destroy(&tcps->tcps_hsp_lock);
25085 	mutex_destroy(&tcps->tcps_g_q_lock);
25086 	cv_destroy(&tcps->tcps_g_q_cv);
25087 	mutex_destroy(&tcps->tcps_epriv_port_lock);
25088 
25089 	ip_drop_unregister(&tcps->tcps_dropper);
25090 
25091 	tcp_kstat2_fini(stackid, tcps->tcps_kstat);
25092 	tcps->tcps_kstat = NULL;
25093 	bzero(&tcps->tcps_statistics, sizeof (tcps->tcps_statistics));
25094 
25095 	tcp_kstat_fini(stackid, tcps->tcps_mibkp);
25096 	tcps->tcps_mibkp = NULL;
25097 
25098 	kmem_free(tcps, sizeof (*tcps));
25099 }
25100 
25101 /*
25102  * Generate ISS, taking into account NDD changes may happen halfway through.
25103  * (If the iss is not zero, set it.)
25104  */
25105 
25106 static void
25107 tcp_iss_init(tcp_t *tcp)
25108 {
25109 	MD5_CTX context;
25110 	struct { uint32_t ports; in6_addr_t src; in6_addr_t dst; } arg;
25111 	uint32_t answer[4];
25112 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25113 
25114 	tcps->tcps_iss_incr_extra += (ISS_INCR >> 1);
25115 	tcp->tcp_iss = tcps->tcps_iss_incr_extra;
25116 	switch (tcps->tcps_strong_iss) {
25117 	case 2:
25118 		mutex_enter(&tcps->tcps_iss_key_lock);
25119 		context = tcps->tcps_iss_key;
25120 		mutex_exit(&tcps->tcps_iss_key_lock);
25121 		arg.ports = tcp->tcp_ports;
25122 		if (tcp->tcp_ipversion == IPV4_VERSION) {
25123 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_src,
25124 			    &arg.src);
25125 			IN6_IPADDR_TO_V4MAPPED(tcp->tcp_ipha->ipha_dst,
25126 			    &arg.dst);
25127 		} else {
25128 			arg.src = tcp->tcp_ip6h->ip6_src;
25129 			arg.dst = tcp->tcp_ip6h->ip6_dst;
25130 		}
25131 		MD5Update(&context, (uchar_t *)&arg, sizeof (arg));
25132 		MD5Final((uchar_t *)answer, &context);
25133 		tcp->tcp_iss += answer[0] ^ answer[1] ^ answer[2] ^ answer[3];
25134 		/*
25135 		 * Now that we've hashed into a unique per-connection sequence
25136 		 * space, add a random increment per strong_iss == 1.  So I
25137 		 * guess we'll have to...
25138 		 */
25139 		/* FALLTHRU */
25140 	case 1:
25141 		tcp->tcp_iss += (gethrtime() >> ISS_NSEC_SHT) + tcp_random();
25142 		break;
25143 	default:
25144 		tcp->tcp_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25145 		break;
25146 	}
25147 	tcp->tcp_valid_bits = TCP_ISS_VALID;
25148 	tcp->tcp_fss = tcp->tcp_iss - 1;
25149 	tcp->tcp_suna = tcp->tcp_iss;
25150 	tcp->tcp_snxt = tcp->tcp_iss + 1;
25151 	tcp->tcp_rexmit_nxt = tcp->tcp_snxt;
25152 	tcp->tcp_csuna = tcp->tcp_snxt;
25153 }
25154 
25155 /*
25156  * Exported routine for extracting active tcp connection status.
25157  *
25158  * This is used by the Solaris Cluster Networking software to
25159  * gather a list of connections that need to be forwarded to
25160  * specific nodes in the cluster when configuration changes occur.
25161  *
25162  * The callback is invoked for each tcp_t structure. Returning
25163  * non-zero from the callback routine terminates the search.
25164  */
25165 int
25166 cl_tcp_walk_list(int (*cl_callback)(cl_tcp_info_t *, void *),
25167     void *arg)
25168 {
25169 	netstack_handle_t nh;
25170 	netstack_t *ns;
25171 	int ret = 0;
25172 
25173 	netstack_next_init(&nh);
25174 	while ((ns = netstack_next(&nh)) != NULL) {
25175 		ret = cl_tcp_walk_list_stack(cl_callback, arg,
25176 		    ns->netstack_tcp);
25177 		netstack_rele(ns);
25178 	}
25179 	netstack_next_fini(&nh);
25180 	return (ret);
25181 }
25182 
25183 static int
25184 cl_tcp_walk_list_stack(int (*callback)(cl_tcp_info_t *, void *), void *arg,
25185     tcp_stack_t *tcps)
25186 {
25187 	tcp_t *tcp;
25188 	cl_tcp_info_t	cl_tcpi;
25189 	connf_t	*connfp;
25190 	conn_t	*connp;
25191 	int	i;
25192 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25193 
25194 	ASSERT(callback != NULL);
25195 
25196 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
25197 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
25198 		connp = NULL;
25199 
25200 		while ((connp =
25201 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
25202 
25203 			tcp = connp->conn_tcp;
25204 			cl_tcpi.cl_tcpi_version = CL_TCPI_V1;
25205 			cl_tcpi.cl_tcpi_ipversion = tcp->tcp_ipversion;
25206 			cl_tcpi.cl_tcpi_state = tcp->tcp_state;
25207 			cl_tcpi.cl_tcpi_lport = tcp->tcp_lport;
25208 			cl_tcpi.cl_tcpi_fport = tcp->tcp_fport;
25209 			/*
25210 			 * The macros tcp_laddr and tcp_faddr give the IPv4
25211 			 * addresses. They are copied implicitly below as
25212 			 * mapped addresses.
25213 			 */
25214 			cl_tcpi.cl_tcpi_laddr_v6 = tcp->tcp_ip_src_v6;
25215 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25216 				cl_tcpi.cl_tcpi_faddr =
25217 				    tcp->tcp_ipha->ipha_dst;
25218 			} else {
25219 				cl_tcpi.cl_tcpi_faddr_v6 =
25220 				    tcp->tcp_ip6h->ip6_dst;
25221 			}
25222 
25223 			/*
25224 			 * If the callback returns non-zero
25225 			 * we terminate the traversal.
25226 			 */
25227 			if ((*callback)(&cl_tcpi, arg) != 0) {
25228 				CONN_DEC_REF(tcp->tcp_connp);
25229 				return (1);
25230 			}
25231 		}
25232 	}
25233 
25234 	return (0);
25235 }
25236 
25237 /*
25238  * Macros used for accessing the different types of sockaddr
25239  * structures inside a tcp_ioc_abort_conn_t.
25240  */
25241 #define	TCP_AC_V4LADDR(acp) ((sin_t *)&(acp)->ac_local)
25242 #define	TCP_AC_V4RADDR(acp) ((sin_t *)&(acp)->ac_remote)
25243 #define	TCP_AC_V4LOCAL(acp) (TCP_AC_V4LADDR(acp)->sin_addr.s_addr)
25244 #define	TCP_AC_V4REMOTE(acp) (TCP_AC_V4RADDR(acp)->sin_addr.s_addr)
25245 #define	TCP_AC_V4LPORT(acp) (TCP_AC_V4LADDR(acp)->sin_port)
25246 #define	TCP_AC_V4RPORT(acp) (TCP_AC_V4RADDR(acp)->sin_port)
25247 #define	TCP_AC_V6LADDR(acp) ((sin6_t *)&(acp)->ac_local)
25248 #define	TCP_AC_V6RADDR(acp) ((sin6_t *)&(acp)->ac_remote)
25249 #define	TCP_AC_V6LOCAL(acp) (TCP_AC_V6LADDR(acp)->sin6_addr)
25250 #define	TCP_AC_V6REMOTE(acp) (TCP_AC_V6RADDR(acp)->sin6_addr)
25251 #define	TCP_AC_V6LPORT(acp) (TCP_AC_V6LADDR(acp)->sin6_port)
25252 #define	TCP_AC_V6RPORT(acp) (TCP_AC_V6RADDR(acp)->sin6_port)
25253 
25254 /*
25255  * Return the correct error code to mimic the behavior
25256  * of a connection reset.
25257  */
25258 #define	TCP_AC_GET_ERRCODE(state, err) {	\
25259 		switch ((state)) {		\
25260 		case TCPS_SYN_SENT:		\
25261 		case TCPS_SYN_RCVD:		\
25262 			(err) = ECONNREFUSED;	\
25263 			break;			\
25264 		case TCPS_ESTABLISHED:		\
25265 		case TCPS_FIN_WAIT_1:		\
25266 		case TCPS_FIN_WAIT_2:		\
25267 		case TCPS_CLOSE_WAIT:		\
25268 			(err) = ECONNRESET;	\
25269 			break;			\
25270 		case TCPS_CLOSING:		\
25271 		case TCPS_LAST_ACK:		\
25272 		case TCPS_TIME_WAIT:		\
25273 			(err) = 0;		\
25274 			break;			\
25275 		default:			\
25276 			(err) = ENXIO;		\
25277 		}				\
25278 	}
25279 
25280 /*
25281  * Check if a tcp structure matches the info in acp.
25282  */
25283 #define	TCP_AC_ADDR_MATCH(acp, tcp)					\
25284 	(((acp)->ac_local.ss_family == AF_INET) ?		\
25285 	((TCP_AC_V4LOCAL((acp)) == INADDR_ANY ||		\
25286 	TCP_AC_V4LOCAL((acp)) == (tcp)->tcp_ip_src) &&	\
25287 	(TCP_AC_V4REMOTE((acp)) == INADDR_ANY ||		\
25288 	TCP_AC_V4REMOTE((acp)) == (tcp)->tcp_remote) &&	\
25289 	(TCP_AC_V4LPORT((acp)) == 0 ||				\
25290 	TCP_AC_V4LPORT((acp)) == (tcp)->tcp_lport) &&		\
25291 	(TCP_AC_V4RPORT((acp)) == 0 ||				\
25292 	TCP_AC_V4RPORT((acp)) == (tcp)->tcp_fport) &&		\
25293 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25294 	(acp)->ac_end >= (tcp)->tcp_state) :		\
25295 	((IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL((acp))) ||	\
25296 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6LOCAL((acp)),		\
25297 	&(tcp)->tcp_ip_src_v6)) &&				\
25298 	(IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE((acp))) ||	\
25299 	IN6_ARE_ADDR_EQUAL(&TCP_AC_V6REMOTE((acp)),		\
25300 	&(tcp)->tcp_remote_v6)) &&				\
25301 	(TCP_AC_V6LPORT((acp)) == 0 ||				\
25302 	TCP_AC_V6LPORT((acp)) == (tcp)->tcp_lport) &&		\
25303 	(TCP_AC_V6RPORT((acp)) == 0 ||				\
25304 	TCP_AC_V6RPORT((acp)) == (tcp)->tcp_fport) &&		\
25305 	(acp)->ac_start <= (tcp)->tcp_state &&	\
25306 	(acp)->ac_end >= (tcp)->tcp_state))
25307 
25308 #define	TCP_AC_MATCH(acp, tcp)					\
25309 	(((acp)->ac_zoneid == ALL_ZONES ||			\
25310 	(acp)->ac_zoneid == tcp->tcp_connp->conn_zoneid) ?	\
25311 	TCP_AC_ADDR_MATCH(acp, tcp) : 0)
25312 
25313 /*
25314  * Build a message containing a tcp_ioc_abort_conn_t structure
25315  * which is filled in with information from acp and tp.
25316  */
25317 static mblk_t *
25318 tcp_ioctl_abort_build_msg(tcp_ioc_abort_conn_t *acp, tcp_t *tp)
25319 {
25320 	mblk_t *mp;
25321 	tcp_ioc_abort_conn_t *tacp;
25322 
25323 	mp = allocb(sizeof (uint32_t) + sizeof (*acp), BPRI_LO);
25324 	if (mp == NULL)
25325 		return (NULL);
25326 
25327 	mp->b_datap->db_type = M_CTL;
25328 
25329 	*((uint32_t *)mp->b_rptr) = TCP_IOC_ABORT_CONN;
25330 	tacp = (tcp_ioc_abort_conn_t *)((uchar_t *)mp->b_rptr +
25331 	    sizeof (uint32_t));
25332 
25333 	tacp->ac_start = acp->ac_start;
25334 	tacp->ac_end = acp->ac_end;
25335 	tacp->ac_zoneid = acp->ac_zoneid;
25336 
25337 	if (acp->ac_local.ss_family == AF_INET) {
25338 		tacp->ac_local.ss_family = AF_INET;
25339 		tacp->ac_remote.ss_family = AF_INET;
25340 		TCP_AC_V4LOCAL(tacp) = tp->tcp_ip_src;
25341 		TCP_AC_V4REMOTE(tacp) = tp->tcp_remote;
25342 		TCP_AC_V4LPORT(tacp) = tp->tcp_lport;
25343 		TCP_AC_V4RPORT(tacp) = tp->tcp_fport;
25344 	} else {
25345 		tacp->ac_local.ss_family = AF_INET6;
25346 		tacp->ac_remote.ss_family = AF_INET6;
25347 		TCP_AC_V6LOCAL(tacp) = tp->tcp_ip_src_v6;
25348 		TCP_AC_V6REMOTE(tacp) = tp->tcp_remote_v6;
25349 		TCP_AC_V6LPORT(tacp) = tp->tcp_lport;
25350 		TCP_AC_V6RPORT(tacp) = tp->tcp_fport;
25351 	}
25352 	mp->b_wptr = (uchar_t *)mp->b_rptr + sizeof (uint32_t) + sizeof (*acp);
25353 	return (mp);
25354 }
25355 
25356 /*
25357  * Print a tcp_ioc_abort_conn_t structure.
25358  */
25359 static void
25360 tcp_ioctl_abort_dump(tcp_ioc_abort_conn_t *acp)
25361 {
25362 	char lbuf[128];
25363 	char rbuf[128];
25364 	sa_family_t af;
25365 	in_port_t lport, rport;
25366 	ushort_t logflags;
25367 
25368 	af = acp->ac_local.ss_family;
25369 
25370 	if (af == AF_INET) {
25371 		(void) inet_ntop(af, (const void *)&TCP_AC_V4LOCAL(acp),
25372 		    lbuf, 128);
25373 		(void) inet_ntop(af, (const void *)&TCP_AC_V4REMOTE(acp),
25374 		    rbuf, 128);
25375 		lport = ntohs(TCP_AC_V4LPORT(acp));
25376 		rport = ntohs(TCP_AC_V4RPORT(acp));
25377 	} else {
25378 		(void) inet_ntop(af, (const void *)&TCP_AC_V6LOCAL(acp),
25379 		    lbuf, 128);
25380 		(void) inet_ntop(af, (const void *)&TCP_AC_V6REMOTE(acp),
25381 		    rbuf, 128);
25382 		lport = ntohs(TCP_AC_V6LPORT(acp));
25383 		rport = ntohs(TCP_AC_V6RPORT(acp));
25384 	}
25385 
25386 	logflags = SL_TRACE | SL_NOTE;
25387 	/*
25388 	 * Don't print this message to the console if the operation was done
25389 	 * to a non-global zone.
25390 	 */
25391 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25392 		logflags |= SL_CONSOLE;
25393 	(void) strlog(TCP_MOD_ID, 0, 1, logflags,
25394 	    "TCP_IOC_ABORT_CONN: local = %s:%d, remote = %s:%d, "
25395 	    "start = %d, end = %d\n", lbuf, lport, rbuf, rport,
25396 	    acp->ac_start, acp->ac_end);
25397 }
25398 
25399 /*
25400  * Called inside tcp_rput when a message built using
25401  * tcp_ioctl_abort_build_msg is put into a queue.
25402  * Note that when we get here there is no wildcard in acp any more.
25403  */
25404 static void
25405 tcp_ioctl_abort_handler(tcp_t *tcp, mblk_t *mp)
25406 {
25407 	tcp_ioc_abort_conn_t *acp;
25408 
25409 	acp = (tcp_ioc_abort_conn_t *)(mp->b_rptr + sizeof (uint32_t));
25410 	if (tcp->tcp_state <= acp->ac_end) {
25411 		/*
25412 		 * If we get here, we are already on the correct
25413 		 * squeue. This ioctl follows the following path
25414 		 * tcp_wput -> tcp_wput_ioctl -> tcp_ioctl_abort_conn
25415 		 * ->tcp_ioctl_abort->squeue_fill (if on a
25416 		 * different squeue)
25417 		 */
25418 		int errcode;
25419 
25420 		TCP_AC_GET_ERRCODE(tcp->tcp_state, errcode);
25421 		(void) tcp_clean_death(tcp, errcode, 26);
25422 	}
25423 	freemsg(mp);
25424 }
25425 
25426 /*
25427  * Abort all matching connections on a hash chain.
25428  */
25429 static int
25430 tcp_ioctl_abort_bucket(tcp_ioc_abort_conn_t *acp, int index, int *count,
25431     boolean_t exact, tcp_stack_t *tcps)
25432 {
25433 	int nmatch, err = 0;
25434 	tcp_t *tcp;
25435 	MBLKP mp, last, listhead = NULL;
25436 	conn_t	*tconnp;
25437 	connf_t	*connfp;
25438 	ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25439 
25440 	connfp = &ipst->ips_ipcl_conn_fanout[index];
25441 
25442 startover:
25443 	nmatch = 0;
25444 
25445 	mutex_enter(&connfp->connf_lock);
25446 	for (tconnp = connfp->connf_head; tconnp != NULL;
25447 	    tconnp = tconnp->conn_next) {
25448 		tcp = tconnp->conn_tcp;
25449 		if (TCP_AC_MATCH(acp, tcp)) {
25450 			CONN_INC_REF(tcp->tcp_connp);
25451 			mp = tcp_ioctl_abort_build_msg(acp, tcp);
25452 			if (mp == NULL) {
25453 				err = ENOMEM;
25454 				CONN_DEC_REF(tcp->tcp_connp);
25455 				break;
25456 			}
25457 			mp->b_prev = (mblk_t *)tcp;
25458 
25459 			if (listhead == NULL) {
25460 				listhead = mp;
25461 				last = mp;
25462 			} else {
25463 				last->b_next = mp;
25464 				last = mp;
25465 			}
25466 			nmatch++;
25467 			if (exact)
25468 				break;
25469 		}
25470 
25471 		/* Avoid holding lock for too long. */
25472 		if (nmatch >= 500)
25473 			break;
25474 	}
25475 	mutex_exit(&connfp->connf_lock);
25476 
25477 	/* Pass mp into the correct tcp */
25478 	while ((mp = listhead) != NULL) {
25479 		listhead = listhead->b_next;
25480 		tcp = (tcp_t *)mp->b_prev;
25481 		mp->b_next = mp->b_prev = NULL;
25482 		squeue_fill(tcp->tcp_connp->conn_sqp, mp,
25483 		    tcp_input, tcp->tcp_connp, SQTAG_TCP_ABORT_BUCKET);
25484 	}
25485 
25486 	*count += nmatch;
25487 	if (nmatch >= 500 && err == 0)
25488 		goto startover;
25489 	return (err);
25490 }
25491 
25492 /*
25493  * Abort all connections that matches the attributes specified in acp.
25494  */
25495 static int
25496 tcp_ioctl_abort(tcp_ioc_abort_conn_t *acp, tcp_stack_t *tcps)
25497 {
25498 	sa_family_t af;
25499 	uint32_t  ports;
25500 	uint16_t *pports;
25501 	int err = 0, count = 0;
25502 	boolean_t exact = B_FALSE; /* set when there is no wildcard */
25503 	int index = -1;
25504 	ushort_t logflags;
25505 	ip_stack_t	*ipst = tcps->tcps_netstack->netstack_ip;
25506 
25507 	af = acp->ac_local.ss_family;
25508 
25509 	if (af == AF_INET) {
25510 		if (TCP_AC_V4REMOTE(acp) != INADDR_ANY &&
25511 		    TCP_AC_V4LPORT(acp) != 0 && TCP_AC_V4RPORT(acp) != 0) {
25512 			pports = (uint16_t *)&ports;
25513 			pports[1] = TCP_AC_V4LPORT(acp);
25514 			pports[0] = TCP_AC_V4RPORT(acp);
25515 			exact = (TCP_AC_V4LOCAL(acp) != INADDR_ANY);
25516 		}
25517 	} else {
25518 		if (!IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6REMOTE(acp)) &&
25519 		    TCP_AC_V6LPORT(acp) != 0 && TCP_AC_V6RPORT(acp) != 0) {
25520 			pports = (uint16_t *)&ports;
25521 			pports[1] = TCP_AC_V6LPORT(acp);
25522 			pports[0] = TCP_AC_V6RPORT(acp);
25523 			exact = !IN6_IS_ADDR_UNSPECIFIED(&TCP_AC_V6LOCAL(acp));
25524 		}
25525 	}
25526 
25527 	/*
25528 	 * For cases where remote addr, local port, and remote port are non-
25529 	 * wildcards, tcp_ioctl_abort_bucket will only be called once.
25530 	 */
25531 	if (index != -1) {
25532 		err = tcp_ioctl_abort_bucket(acp, index,
25533 		    &count, exact, tcps);
25534 	} else {
25535 		/*
25536 		 * loop through all entries for wildcard case
25537 		 */
25538 		for (index = 0;
25539 		    index < ipst->ips_ipcl_conn_fanout_size;
25540 		    index++) {
25541 			err = tcp_ioctl_abort_bucket(acp, index,
25542 			    &count, exact, tcps);
25543 			if (err != 0)
25544 				break;
25545 		}
25546 	}
25547 
25548 	logflags = SL_TRACE | SL_NOTE;
25549 	/*
25550 	 * Don't print this message to the console if the operation was done
25551 	 * to a non-global zone.
25552 	 */
25553 	if (acp->ac_zoneid == GLOBAL_ZONEID || acp->ac_zoneid == ALL_ZONES)
25554 		logflags |= SL_CONSOLE;
25555 	(void) strlog(TCP_MOD_ID, 0, 1, logflags, "TCP_IOC_ABORT_CONN: "
25556 	    "aborted %d connection%c\n", count, ((count > 1) ? 's' : ' '));
25557 	if (err == 0 && count == 0)
25558 		err = ENOENT;
25559 	return (err);
25560 }
25561 
25562 /*
25563  * Process the TCP_IOC_ABORT_CONN ioctl request.
25564  */
25565 static void
25566 tcp_ioctl_abort_conn(queue_t *q, mblk_t *mp)
25567 {
25568 	int	err;
25569 	IOCP    iocp;
25570 	MBLKP   mp1;
25571 	sa_family_t laf, raf;
25572 	tcp_ioc_abort_conn_t *acp;
25573 	zone_t		*zptr;
25574 	conn_t		*connp = Q_TO_CONN(q);
25575 	zoneid_t	zoneid = connp->conn_zoneid;
25576 	tcp_t		*tcp = connp->conn_tcp;
25577 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25578 
25579 	iocp = (IOCP)mp->b_rptr;
25580 
25581 	if ((mp1 = mp->b_cont) == NULL ||
25582 	    iocp->ioc_count != sizeof (tcp_ioc_abort_conn_t)) {
25583 		err = EINVAL;
25584 		goto out;
25585 	}
25586 
25587 	/* check permissions */
25588 	if (secpolicy_ip_config(iocp->ioc_cr, B_FALSE) != 0) {
25589 		err = EPERM;
25590 		goto out;
25591 	}
25592 
25593 	if (mp1->b_cont != NULL) {
25594 		freemsg(mp1->b_cont);
25595 		mp1->b_cont = NULL;
25596 	}
25597 
25598 	acp = (tcp_ioc_abort_conn_t *)mp1->b_rptr;
25599 	laf = acp->ac_local.ss_family;
25600 	raf = acp->ac_remote.ss_family;
25601 
25602 	/* check that a zone with the supplied zoneid exists */
25603 	if (acp->ac_zoneid != GLOBAL_ZONEID && acp->ac_zoneid != ALL_ZONES) {
25604 		zptr = zone_find_by_id(zoneid);
25605 		if (zptr != NULL) {
25606 			zone_rele(zptr);
25607 		} else {
25608 			err = EINVAL;
25609 			goto out;
25610 		}
25611 	}
25612 
25613 	/*
25614 	 * For exclusive stacks we set the zoneid to zero
25615 	 * to make TCP operate as if in the global zone.
25616 	 */
25617 	if (tcps->tcps_netstack->netstack_stackid != GLOBAL_NETSTACKID)
25618 		acp->ac_zoneid = GLOBAL_ZONEID;
25619 
25620 	if (acp->ac_start < TCPS_SYN_SENT || acp->ac_end > TCPS_TIME_WAIT ||
25621 	    acp->ac_start > acp->ac_end || laf != raf ||
25622 	    (laf != AF_INET && laf != AF_INET6)) {
25623 		err = EINVAL;
25624 		goto out;
25625 	}
25626 
25627 	tcp_ioctl_abort_dump(acp);
25628 	err = tcp_ioctl_abort(acp, tcps);
25629 
25630 out:
25631 	if (mp1 != NULL) {
25632 		freemsg(mp1);
25633 		mp->b_cont = NULL;
25634 	}
25635 
25636 	if (err != 0)
25637 		miocnak(q, mp, 0, err);
25638 	else
25639 		miocack(q, mp, 0, 0);
25640 }
25641 
25642 /*
25643  * tcp_time_wait_processing() handles processing of incoming packets when
25644  * the tcp is in the TIME_WAIT state.
25645  * A TIME_WAIT tcp that has an associated open TCP stream is never put
25646  * on the time wait list.
25647  */
25648 void
25649 tcp_time_wait_processing(tcp_t *tcp, mblk_t *mp, uint32_t seg_seq,
25650     uint32_t seg_ack, int seg_len, tcph_t *tcph)
25651 {
25652 	int32_t		bytes_acked;
25653 	int32_t		gap;
25654 	int32_t		rgap;
25655 	tcp_opt_t	tcpopt;
25656 	uint_t		flags;
25657 	uint32_t	new_swnd = 0;
25658 	conn_t		*connp;
25659 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25660 
25661 	BUMP_LOCAL(tcp->tcp_ibsegs);
25662 	DTRACE_PROBE2(tcp__trace__recv, mblk_t *, mp, tcp_t *, tcp);
25663 
25664 	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
25665 	new_swnd = BE16_TO_U16(tcph->th_win) <<
25666 	    ((tcph->th_flags[0] & TH_SYN) ? 0 : tcp->tcp_snd_ws);
25667 	if (tcp->tcp_snd_ts_ok) {
25668 		if (!tcp_paws_check(tcp, tcph, &tcpopt)) {
25669 			tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25670 			    tcp->tcp_rnxt, TH_ACK);
25671 			goto done;
25672 		}
25673 	}
25674 	gap = seg_seq - tcp->tcp_rnxt;
25675 	rgap = tcp->tcp_rwnd - (gap + seg_len);
25676 	if (gap < 0) {
25677 		BUMP_MIB(&tcps->tcps_mib, tcpInDataDupSegs);
25678 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataDupBytes,
25679 		    (seg_len > -gap ? -gap : seg_len));
25680 		seg_len += gap;
25681 		if (seg_len < 0 || (seg_len == 0 && !(flags & TH_FIN))) {
25682 			if (flags & TH_RST) {
25683 				goto done;
25684 			}
25685 			if ((flags & TH_FIN) && seg_len == -1) {
25686 				/*
25687 				 * When TCP receives a duplicate FIN in
25688 				 * TIME_WAIT state, restart the 2 MSL timer.
25689 				 * See page 73 in RFC 793. Make sure this TCP
25690 				 * is already on the TIME_WAIT list. If not,
25691 				 * just restart the timer.
25692 				 */
25693 				if (TCP_IS_DETACHED(tcp)) {
25694 					if (tcp_time_wait_remove(tcp, NULL) ==
25695 					    B_TRUE) {
25696 						tcp_time_wait_append(tcp);
25697 						TCP_DBGSTAT(tcps,
25698 						    tcp_rput_time_wait);
25699 					}
25700 				} else {
25701 					ASSERT(tcp != NULL);
25702 					TCP_TIMER_RESTART(tcp,
25703 					    tcps->tcps_time_wait_interval);
25704 				}
25705 				tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25706 				    tcp->tcp_rnxt, TH_ACK);
25707 				goto done;
25708 			}
25709 			flags |=  TH_ACK_NEEDED;
25710 			seg_len = 0;
25711 			goto process_ack;
25712 		}
25713 
25714 		/* Fix seg_seq, and chew the gap off the front. */
25715 		seg_seq = tcp->tcp_rnxt;
25716 	}
25717 
25718 	if ((flags & TH_SYN) && gap > 0 && rgap < 0) {
25719 		/*
25720 		 * Make sure that when we accept the connection, pick
25721 		 * an ISS greater than (tcp_snxt + ISS_INCR/2) for the
25722 		 * old connection.
25723 		 *
25724 		 * The next ISS generated is equal to tcp_iss_incr_extra
25725 		 * + ISS_INCR/2 + other components depending on the
25726 		 * value of tcp_strong_iss.  We pre-calculate the new
25727 		 * ISS here and compare with tcp_snxt to determine if
25728 		 * we need to make adjustment to tcp_iss_incr_extra.
25729 		 *
25730 		 * The above calculation is ugly and is a
25731 		 * waste of CPU cycles...
25732 		 */
25733 		uint32_t new_iss = tcps->tcps_iss_incr_extra;
25734 		int32_t adj;
25735 		ip_stack_t *ipst = tcps->tcps_netstack->netstack_ip;
25736 
25737 		switch (tcps->tcps_strong_iss) {
25738 		case 2: {
25739 			/* Add time and MD5 components. */
25740 			uint32_t answer[4];
25741 			struct {
25742 				uint32_t ports;
25743 				in6_addr_t src;
25744 				in6_addr_t dst;
25745 			} arg;
25746 			MD5_CTX context;
25747 
25748 			mutex_enter(&tcps->tcps_iss_key_lock);
25749 			context = tcps->tcps_iss_key;
25750 			mutex_exit(&tcps->tcps_iss_key_lock);
25751 			arg.ports = tcp->tcp_ports;
25752 			/* We use MAPPED addresses in tcp_iss_init */
25753 			arg.src = tcp->tcp_ip_src_v6;
25754 			if (tcp->tcp_ipversion == IPV4_VERSION) {
25755 				IN6_IPADDR_TO_V4MAPPED(
25756 				    tcp->tcp_ipha->ipha_dst,
25757 				    &arg.dst);
25758 			} else {
25759 				arg.dst =
25760 				    tcp->tcp_ip6h->ip6_dst;
25761 			}
25762 			MD5Update(&context, (uchar_t *)&arg,
25763 			    sizeof (arg));
25764 			MD5Final((uchar_t *)answer, &context);
25765 			answer[0] ^= answer[1] ^ answer[2] ^ answer[3];
25766 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + answer[0];
25767 			break;
25768 		}
25769 		case 1:
25770 			/* Add time component and min random (i.e. 1). */
25771 			new_iss += (gethrtime() >> ISS_NSEC_SHT) + 1;
25772 			break;
25773 		default:
25774 			/* Add only time component. */
25775 			new_iss += (uint32_t)gethrestime_sec() * ISS_INCR;
25776 			break;
25777 		}
25778 		if ((adj = (int32_t)(tcp->tcp_snxt - new_iss)) > 0) {
25779 			/*
25780 			 * New ISS not guaranteed to be ISS_INCR/2
25781 			 * ahead of the current tcp_snxt, so add the
25782 			 * difference to tcp_iss_incr_extra.
25783 			 */
25784 			tcps->tcps_iss_incr_extra += adj;
25785 		}
25786 		/*
25787 		 * If tcp_clean_death() can not perform the task now,
25788 		 * drop the SYN packet and let the other side re-xmit.
25789 		 * Otherwise pass the SYN packet back in, since the
25790 		 * old tcp state has been cleaned up or freed.
25791 		 */
25792 		if (tcp_clean_death(tcp, 0, 27) == -1)
25793 			goto done;
25794 		/*
25795 		 * We will come back to tcp_rput_data
25796 		 * on the global queue. Packets destined
25797 		 * for the global queue will be checked
25798 		 * with global policy. But the policy for
25799 		 * this packet has already been checked as
25800 		 * this was destined for the detached
25801 		 * connection. We need to bypass policy
25802 		 * check this time by attaching a dummy
25803 		 * ipsec_in with ipsec_in_dont_check set.
25804 		 */
25805 		connp = ipcl_classify(mp, tcp->tcp_connp->conn_zoneid, ipst);
25806 		if (connp != NULL) {
25807 			TCP_STAT(tcps, tcp_time_wait_syn_success);
25808 			tcp_reinput(connp, mp, tcp->tcp_connp->conn_sqp);
25809 			return;
25810 		}
25811 		goto done;
25812 	}
25813 
25814 	/*
25815 	 * rgap is the amount of stuff received out of window.  A negative
25816 	 * value is the amount out of window.
25817 	 */
25818 	if (rgap < 0) {
25819 		BUMP_MIB(&tcps->tcps_mib, tcpInDataPastWinSegs);
25820 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataPastWinBytes, -rgap);
25821 		/* Fix seg_len and make sure there is something left. */
25822 		seg_len += rgap;
25823 		if (seg_len <= 0) {
25824 			if (flags & TH_RST) {
25825 				goto done;
25826 			}
25827 			flags |=  TH_ACK_NEEDED;
25828 			seg_len = 0;
25829 			goto process_ack;
25830 		}
25831 	}
25832 	/*
25833 	 * Check whether we can update tcp_ts_recent.  This test is
25834 	 * NOT the one in RFC 1323 3.4.  It is from Braden, 1993, "TCP
25835 	 * Extensions for High Performance: An Update", Internet Draft.
25836 	 */
25837 	if (tcp->tcp_snd_ts_ok &&
25838 	    TSTMP_GEQ(tcpopt.tcp_opt_ts_val, tcp->tcp_ts_recent) &&
25839 	    SEQ_LEQ(seg_seq, tcp->tcp_rack)) {
25840 		tcp->tcp_ts_recent = tcpopt.tcp_opt_ts_val;
25841 		tcp->tcp_last_rcv_lbolt = lbolt64;
25842 	}
25843 
25844 	if (seg_seq != tcp->tcp_rnxt && seg_len > 0) {
25845 		/* Always ack out of order packets */
25846 		flags |= TH_ACK_NEEDED;
25847 		seg_len = 0;
25848 	} else if (seg_len > 0) {
25849 		BUMP_MIB(&tcps->tcps_mib, tcpInClosed);
25850 		BUMP_MIB(&tcps->tcps_mib, tcpInDataInorderSegs);
25851 		UPDATE_MIB(&tcps->tcps_mib, tcpInDataInorderBytes, seg_len);
25852 	}
25853 	if (flags & TH_RST) {
25854 		(void) tcp_clean_death(tcp, 0, 28);
25855 		goto done;
25856 	}
25857 	if (flags & TH_SYN) {
25858 		tcp_xmit_ctl("TH_SYN", tcp, seg_ack, seg_seq + 1,
25859 		    TH_RST|TH_ACK);
25860 		/*
25861 		 * Do not delete the TCP structure if it is in
25862 		 * TIME_WAIT state.  Refer to RFC 1122, 4.2.2.13.
25863 		 */
25864 		goto done;
25865 	}
25866 process_ack:
25867 	if (flags & TH_ACK) {
25868 		bytes_acked = (int)(seg_ack - tcp->tcp_suna);
25869 		if (bytes_acked <= 0) {
25870 			if (bytes_acked == 0 && seg_len == 0 &&
25871 			    new_swnd == tcp->tcp_swnd)
25872 				BUMP_MIB(&tcps->tcps_mib, tcpInDupAck);
25873 		} else {
25874 			/* Acks something not sent */
25875 			flags |= TH_ACK_NEEDED;
25876 		}
25877 	}
25878 	if (flags & TH_ACK_NEEDED) {
25879 		/*
25880 		 * Time to send an ack for some reason.
25881 		 */
25882 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt,
25883 		    tcp->tcp_rnxt, TH_ACK);
25884 	}
25885 done:
25886 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
25887 		DB_CKSUMSTART(mp) = 0;
25888 		mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
25889 		TCP_STAT(tcps, tcp_time_wait_syn_fail);
25890 	}
25891 	freemsg(mp);
25892 }
25893 
25894 /*
25895  * Allocate a T_SVR4_OPTMGMT_REQ.
25896  * The caller needs to increment tcp_drop_opt_ack_cnt when sending these so
25897  * that tcp_rput_other can drop the acks.
25898  */
25899 static mblk_t *
25900 tcp_setsockopt_mp(int level, int cmd, char *opt, int optlen)
25901 {
25902 	mblk_t *mp;
25903 	struct T_optmgmt_req *tor;
25904 	struct opthdr *oh;
25905 	uint_t size;
25906 	char *optptr;
25907 
25908 	size = sizeof (*tor) + sizeof (*oh) + optlen;
25909 	mp = allocb(size, BPRI_MED);
25910 	if (mp == NULL)
25911 		return (NULL);
25912 
25913 	mp->b_wptr += size;
25914 	mp->b_datap->db_type = M_PROTO;
25915 	tor = (struct T_optmgmt_req *)mp->b_rptr;
25916 	tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
25917 	tor->MGMT_flags = T_NEGOTIATE;
25918 	tor->OPT_length = sizeof (*oh) + optlen;
25919 	tor->OPT_offset = (t_scalar_t)sizeof (*tor);
25920 
25921 	oh = (struct opthdr *)&tor[1];
25922 	oh->level = level;
25923 	oh->name = cmd;
25924 	oh->len = optlen;
25925 	if (optlen != 0) {
25926 		optptr = (char *)&oh[1];
25927 		bcopy(opt, optptr, optlen);
25928 	}
25929 	return (mp);
25930 }
25931 
25932 /*
25933  * TCP Timers Implementation.
25934  */
25935 timeout_id_t
25936 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
25937 {
25938 	mblk_t *mp;
25939 	tcp_timer_t *tcpt;
25940 	tcp_t *tcp = connp->conn_tcp;
25941 	tcp_stack_t	*tcps = tcp->tcp_tcps;
25942 
25943 	ASSERT(connp->conn_sqp != NULL);
25944 
25945 	TCP_DBGSTAT(tcps, tcp_timeout_calls);
25946 
25947 	if (tcp->tcp_timercache == NULL) {
25948 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
25949 	} else {
25950 		TCP_DBGSTAT(tcps, tcp_timeout_cached_alloc);
25951 		mp = tcp->tcp_timercache;
25952 		tcp->tcp_timercache = mp->b_next;
25953 		mp->b_next = NULL;
25954 		ASSERT(mp->b_wptr == NULL);
25955 	}
25956 
25957 	CONN_INC_REF(connp);
25958 	tcpt = (tcp_timer_t *)mp->b_rptr;
25959 	tcpt->connp = connp;
25960 	tcpt->tcpt_proc = f;
25961 	/*
25962 	 * TCP timers are normal timeouts. Plus, they do not require more than
25963 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
25964 	 * rounding up the expiration to the next resolution boundary, we can
25965 	 * batch timers in the callout subsystem to make TCP timers more
25966 	 * efficient. The roundup also protects short timers from expiring too
25967 	 * early before they have a chance to be cancelled.
25968 	 */
25969 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
25970 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
25971 
25972 	return ((timeout_id_t)mp);
25973 }
25974 
25975 static void
25976 tcp_timer_callback(void *arg)
25977 {
25978 	mblk_t *mp = (mblk_t *)arg;
25979 	tcp_timer_t *tcpt;
25980 	conn_t	*connp;
25981 
25982 	tcpt = (tcp_timer_t *)mp->b_rptr;
25983 	connp = tcpt->connp;
25984 	squeue_fill(connp->conn_sqp, mp,
25985 	    tcp_timer_handler, connp, SQTAG_TCP_TIMER);
25986 }
25987 
25988 static void
25989 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2)
25990 {
25991 	tcp_timer_t *tcpt;
25992 	conn_t *connp = (conn_t *)arg;
25993 	tcp_t *tcp = connp->conn_tcp;
25994 
25995 	tcpt = (tcp_timer_t *)mp->b_rptr;
25996 	ASSERT(connp == tcpt->connp);
25997 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
25998 
25999 	/*
26000 	 * If the TCP has reached the closed state, don't proceed any
26001 	 * further. This TCP logically does not exist on the system.
26002 	 * tcpt_proc could for example access queues, that have already
26003 	 * been qprocoff'ed off. Also see comments at the start of tcp_input
26004 	 */
26005 	if (tcp->tcp_state != TCPS_CLOSED) {
26006 		(*tcpt->tcpt_proc)(connp);
26007 	} else {
26008 		tcp->tcp_timer_tid = 0;
26009 	}
26010 	tcp_timer_free(connp->conn_tcp, mp);
26011 }
26012 
26013 /*
26014  * There is potential race with untimeout and the handler firing at the same
26015  * time. The mblock may be freed by the handler while we are trying to use
26016  * it. But since both should execute on the same squeue, this race should not
26017  * occur.
26018  */
26019 clock_t
26020 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
26021 {
26022 	mblk_t	*mp = (mblk_t *)id;
26023 	tcp_timer_t *tcpt;
26024 	clock_t delta;
26025 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26026 
26027 	TCP_DBGSTAT(tcps, tcp_timeout_cancel_reqs);
26028 
26029 	if (mp == NULL)
26030 		return (-1);
26031 
26032 	tcpt = (tcp_timer_t *)mp->b_rptr;
26033 	ASSERT(tcpt->connp == connp);
26034 
26035 	delta = untimeout_default(tcpt->tcpt_tid, 0);
26036 
26037 	if (delta >= 0) {
26038 		TCP_DBGSTAT(tcps, tcp_timeout_canceled);
26039 		tcp_timer_free(connp->conn_tcp, mp);
26040 		CONN_DEC_REF(connp);
26041 	}
26042 
26043 	return (delta);
26044 }
26045 
26046 /*
26047  * Allocate space for the timer event. The allocation looks like mblk, but it is
26048  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
26049  *
26050  * Dealing with failures: If we can't allocate from the timer cache we try
26051  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
26052  * points to b_rptr.
26053  * If we can't allocate anything using allocb_tryhard(), we perform a last
26054  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
26055  * save the actual allocation size in b_datap.
26056  */
26057 mblk_t *
26058 tcp_timermp_alloc(int kmflags)
26059 {
26060 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
26061 	    kmflags & ~KM_PANIC);
26062 
26063 	if (mp != NULL) {
26064 		mp->b_next = mp->b_prev = NULL;
26065 		mp->b_rptr = (uchar_t *)(&mp[1]);
26066 		mp->b_wptr = NULL;
26067 		mp->b_datap = NULL;
26068 		mp->b_queue = NULL;
26069 		mp->b_cont = NULL;
26070 	} else if (kmflags & KM_PANIC) {
26071 		/*
26072 		 * Failed to allocate memory for the timer. Try allocating from
26073 		 * dblock caches.
26074 		 */
26075 		/* ipclassifier calls this from a constructor - hence no tcps */
26076 		TCP_G_STAT(tcp_timermp_allocfail);
26077 		mp = allocb_tryhard(sizeof (tcp_timer_t));
26078 		if (mp == NULL) {
26079 			size_t size = 0;
26080 			/*
26081 			 * Memory is really low. Try tryhard allocation.
26082 			 *
26083 			 * ipclassifier calls this from a constructor -
26084 			 * hence no tcps
26085 			 */
26086 			TCP_G_STAT(tcp_timermp_allocdblfail);
26087 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
26088 			    sizeof (tcp_timer_t), &size, kmflags);
26089 			mp->b_rptr = (uchar_t *)(&mp[1]);
26090 			mp->b_next = mp->b_prev = NULL;
26091 			mp->b_wptr = (uchar_t *)-1;
26092 			mp->b_datap = (dblk_t *)size;
26093 			mp->b_queue = NULL;
26094 			mp->b_cont = NULL;
26095 		}
26096 		ASSERT(mp->b_wptr != NULL);
26097 	}
26098 	/* ipclassifier calls this from a constructor - hence no tcps */
26099 	TCP_G_DBGSTAT(tcp_timermp_alloced);
26100 
26101 	return (mp);
26102 }
26103 
26104 /*
26105  * Free per-tcp timer cache.
26106  * It can only contain entries from tcp_timercache.
26107  */
26108 void
26109 tcp_timermp_free(tcp_t *tcp)
26110 {
26111 	mblk_t *mp;
26112 
26113 	while ((mp = tcp->tcp_timercache) != NULL) {
26114 		ASSERT(mp->b_wptr == NULL);
26115 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
26116 		kmem_cache_free(tcp_timercache, mp);
26117 	}
26118 }
26119 
26120 /*
26121  * Free timer event. Put it on the per-tcp timer cache if there is not too many
26122  * events there already (currently at most two events are cached).
26123  * If the event is not allocated from the timer cache, free it right away.
26124  */
26125 static void
26126 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
26127 {
26128 	mblk_t *mp1 = tcp->tcp_timercache;
26129 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26130 
26131 	if (mp->b_wptr != NULL) {
26132 		/*
26133 		 * This allocation is not from a timer cache, free it right
26134 		 * away.
26135 		 */
26136 		if (mp->b_wptr != (uchar_t *)-1)
26137 			freeb(mp);
26138 		else
26139 			kmem_free(mp, (size_t)mp->b_datap);
26140 	} else if (mp1 == NULL || mp1->b_next == NULL) {
26141 		/* Cache this timer block for future allocations */
26142 		mp->b_rptr = (uchar_t *)(&mp[1]);
26143 		mp->b_next = mp1;
26144 		tcp->tcp_timercache = mp;
26145 	} else {
26146 		kmem_cache_free(tcp_timercache, mp);
26147 		TCP_DBGSTAT(tcps, tcp_timermp_freed);
26148 	}
26149 }
26150 
26151 /*
26152  * End of TCP Timers implementation.
26153  */
26154 
26155 /*
26156  * tcp_{set,clr}qfull() functions are used to either set or clear QFULL
26157  * on the specified backing STREAMS q. Note, the caller may make the
26158  * decision to call based on the tcp_t.tcp_flow_stopped value which
26159  * when check outside the q's lock is only an advisory check ...
26160  */
26161 
26162 void
26163 tcp_setqfull(tcp_t *tcp)
26164 {
26165 	queue_t *q = tcp->tcp_wq;
26166 	tcp_stack_t	*tcps = tcp->tcp_tcps;
26167 
26168 	if (!(q->q_flag & QFULL)) {
26169 		mutex_enter(QLOCK(q));
26170 		if (!(q->q_flag & QFULL)) {
26171 			/* still need to set QFULL */
26172 			q->q_flag |= QFULL;
26173 			tcp->tcp_flow_stopped = B_TRUE;
26174 			mutex_exit(QLOCK(q));
26175 			TCP_STAT(tcps, tcp_flwctl_on);
26176 		} else {
26177 			mutex_exit(QLOCK(q));
26178 		}
26179 	}
26180 }
26181 
26182 void
26183 tcp_clrqfull(tcp_t *tcp)
26184 {
26185 	queue_t *q = tcp->tcp_wq;
26186 
26187 	if (q->q_flag & QFULL) {
26188 		mutex_enter(QLOCK(q));
26189 		if (q->q_flag & QFULL) {
26190 			q->q_flag &= ~QFULL;
26191 			tcp->tcp_flow_stopped = B_FALSE;
26192 			mutex_exit(QLOCK(q));
26193 			if (q->q_flag & QWANTW)
26194 				qbackenable(q, 0);
26195 		} else {
26196 			mutex_exit(QLOCK(q));
26197 		}
26198 	}
26199 }
26200 
26201 
26202 /*
26203  * kstats related to squeues i.e. not per IP instance
26204  */
26205 static void *
26206 tcp_g_kstat_init(tcp_g_stat_t *tcp_g_statp)
26207 {
26208 	kstat_t *ksp;
26209 
26210 	tcp_g_stat_t template = {
26211 		{ "tcp_timermp_alloced",	KSTAT_DATA_UINT64 },
26212 		{ "tcp_timermp_allocfail",	KSTAT_DATA_UINT64 },
26213 		{ "tcp_timermp_allocdblfail",	KSTAT_DATA_UINT64 },
26214 		{ "tcp_freelist_cleanup",	KSTAT_DATA_UINT64 },
26215 	};
26216 
26217 	ksp = kstat_create(TCP_MOD_NAME, 0, "tcpstat_g", "net",
26218 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26219 	    KSTAT_FLAG_VIRTUAL);
26220 
26221 	if (ksp == NULL)
26222 		return (NULL);
26223 
26224 	bcopy(&template, tcp_g_statp, sizeof (template));
26225 	ksp->ks_data = (void *)tcp_g_statp;
26226 
26227 	kstat_install(ksp);
26228 	return (ksp);
26229 }
26230 
26231 static void
26232 tcp_g_kstat_fini(kstat_t *ksp)
26233 {
26234 	if (ksp != NULL) {
26235 		kstat_delete(ksp);
26236 	}
26237 }
26238 
26239 
26240 static void *
26241 tcp_kstat2_init(netstackid_t stackid, tcp_stat_t *tcps_statisticsp)
26242 {
26243 	kstat_t *ksp;
26244 
26245 	tcp_stat_t template = {
26246 		{ "tcp_time_wait",		KSTAT_DATA_UINT64 },
26247 		{ "tcp_time_wait_syn",		KSTAT_DATA_UINT64 },
26248 		{ "tcp_time_wait_success",	KSTAT_DATA_UINT64 },
26249 		{ "tcp_time_wait_fail",		KSTAT_DATA_UINT64 },
26250 		{ "tcp_reinput_syn",		KSTAT_DATA_UINT64 },
26251 		{ "tcp_ip_output",		KSTAT_DATA_UINT64 },
26252 		{ "tcp_detach_non_time_wait",	KSTAT_DATA_UINT64 },
26253 		{ "tcp_detach_time_wait",	KSTAT_DATA_UINT64 },
26254 		{ "tcp_time_wait_reap",		KSTAT_DATA_UINT64 },
26255 		{ "tcp_clean_death_nondetached",	KSTAT_DATA_UINT64 },
26256 		{ "tcp_reinit_calls",		KSTAT_DATA_UINT64 },
26257 		{ "tcp_eager_err1",		KSTAT_DATA_UINT64 },
26258 		{ "tcp_eager_err2",		KSTAT_DATA_UINT64 },
26259 		{ "tcp_eager_blowoff_calls",	KSTAT_DATA_UINT64 },
26260 		{ "tcp_eager_blowoff_q",	KSTAT_DATA_UINT64 },
26261 		{ "tcp_eager_blowoff_q0",	KSTAT_DATA_UINT64 },
26262 		{ "tcp_not_hard_bound",		KSTAT_DATA_UINT64 },
26263 		{ "tcp_no_listener",		KSTAT_DATA_UINT64 },
26264 		{ "tcp_found_eager",		KSTAT_DATA_UINT64 },
26265 		{ "tcp_wrong_queue",		KSTAT_DATA_UINT64 },
26266 		{ "tcp_found_eager_binding1",	KSTAT_DATA_UINT64 },
26267 		{ "tcp_found_eager_bound1",	KSTAT_DATA_UINT64 },
26268 		{ "tcp_eager_has_listener1",	KSTAT_DATA_UINT64 },
26269 		{ "tcp_open_alloc",		KSTAT_DATA_UINT64 },
26270 		{ "tcp_open_detached_alloc",	KSTAT_DATA_UINT64 },
26271 		{ "tcp_rput_time_wait",		KSTAT_DATA_UINT64 },
26272 		{ "tcp_listendrop",		KSTAT_DATA_UINT64 },
26273 		{ "tcp_listendropq0",		KSTAT_DATA_UINT64 },
26274 		{ "tcp_wrong_rq",		KSTAT_DATA_UINT64 },
26275 		{ "tcp_rsrv_calls",		KSTAT_DATA_UINT64 },
26276 		{ "tcp_eagerfree2",		KSTAT_DATA_UINT64 },
26277 		{ "tcp_eagerfree3",		KSTAT_DATA_UINT64 },
26278 		{ "tcp_eagerfree4",		KSTAT_DATA_UINT64 },
26279 		{ "tcp_eagerfree5",		KSTAT_DATA_UINT64 },
26280 		{ "tcp_timewait_syn_fail",	KSTAT_DATA_UINT64 },
26281 		{ "tcp_listen_badflags",	KSTAT_DATA_UINT64 },
26282 		{ "tcp_timeout_calls",		KSTAT_DATA_UINT64 },
26283 		{ "tcp_timeout_cached_alloc",	KSTAT_DATA_UINT64 },
26284 		{ "tcp_timeout_cancel_reqs",	KSTAT_DATA_UINT64 },
26285 		{ "tcp_timeout_canceled",	KSTAT_DATA_UINT64 },
26286 		{ "tcp_timermp_freed",		KSTAT_DATA_UINT64 },
26287 		{ "tcp_push_timer_cnt",		KSTAT_DATA_UINT64 },
26288 		{ "tcp_ack_timer_cnt",		KSTAT_DATA_UINT64 },
26289 		{ "tcp_ire_null1",		KSTAT_DATA_UINT64 },
26290 		{ "tcp_ire_null",		KSTAT_DATA_UINT64 },
26291 		{ "tcp_ip_send",		KSTAT_DATA_UINT64 },
26292 		{ "tcp_ip_ire_send",		KSTAT_DATA_UINT64 },
26293 		{ "tcp_wsrv_called",		KSTAT_DATA_UINT64 },
26294 		{ "tcp_flwctl_on",		KSTAT_DATA_UINT64 },
26295 		{ "tcp_timer_fire_early",	KSTAT_DATA_UINT64 },
26296 		{ "tcp_timer_fire_miss",	KSTAT_DATA_UINT64 },
26297 		{ "tcp_rput_v6_error",		KSTAT_DATA_UINT64 },
26298 		{ "tcp_out_sw_cksum",		KSTAT_DATA_UINT64 },
26299 		{ "tcp_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
26300 		{ "tcp_zcopy_on",		KSTAT_DATA_UINT64 },
26301 		{ "tcp_zcopy_off",		KSTAT_DATA_UINT64 },
26302 		{ "tcp_zcopy_backoff",		KSTAT_DATA_UINT64 },
26303 		{ "tcp_zcopy_disable",		KSTAT_DATA_UINT64 },
26304 		{ "tcp_mdt_pkt_out",		KSTAT_DATA_UINT64 },
26305 		{ "tcp_mdt_pkt_out_v4",		KSTAT_DATA_UINT64 },
26306 		{ "tcp_mdt_pkt_out_v6",		KSTAT_DATA_UINT64 },
26307 		{ "tcp_mdt_discarded",		KSTAT_DATA_UINT64 },
26308 		{ "tcp_mdt_conn_halted1",	KSTAT_DATA_UINT64 },
26309 		{ "tcp_mdt_conn_halted2",	KSTAT_DATA_UINT64 },
26310 		{ "tcp_mdt_conn_halted3",	KSTAT_DATA_UINT64 },
26311 		{ "tcp_mdt_conn_resumed1",	KSTAT_DATA_UINT64 },
26312 		{ "tcp_mdt_conn_resumed2",	KSTAT_DATA_UINT64 },
26313 		{ "tcp_mdt_legacy_small",	KSTAT_DATA_UINT64 },
26314 		{ "tcp_mdt_legacy_all",		KSTAT_DATA_UINT64 },
26315 		{ "tcp_mdt_legacy_ret",		KSTAT_DATA_UINT64 },
26316 		{ "tcp_mdt_allocfail",		KSTAT_DATA_UINT64 },
26317 		{ "tcp_mdt_addpdescfail",	KSTAT_DATA_UINT64 },
26318 		{ "tcp_mdt_allocd",		KSTAT_DATA_UINT64 },
26319 		{ "tcp_mdt_linked",		KSTAT_DATA_UINT64 },
26320 		{ "tcp_fusion_flowctl",		KSTAT_DATA_UINT64 },
26321 		{ "tcp_fusion_backenabled",	KSTAT_DATA_UINT64 },
26322 		{ "tcp_fusion_urg",		KSTAT_DATA_UINT64 },
26323 		{ "tcp_fusion_putnext",		KSTAT_DATA_UINT64 },
26324 		{ "tcp_fusion_unfusable",	KSTAT_DATA_UINT64 },
26325 		{ "tcp_fusion_aborted",		KSTAT_DATA_UINT64 },
26326 		{ "tcp_fusion_unqualified",	KSTAT_DATA_UINT64 },
26327 		{ "tcp_fusion_rrw_busy",	KSTAT_DATA_UINT64 },
26328 		{ "tcp_fusion_rrw_msgcnt",	KSTAT_DATA_UINT64 },
26329 		{ "tcp_fusion_rrw_plugged",	KSTAT_DATA_UINT64 },
26330 		{ "tcp_in_ack_unsent_drop",	KSTAT_DATA_UINT64 },
26331 		{ "tcp_sock_fallback",		KSTAT_DATA_UINT64 },
26332 		{ "tcp_lso_enabled",		KSTAT_DATA_UINT64 },
26333 		{ "tcp_lso_disabled",		KSTAT_DATA_UINT64 },
26334 		{ "tcp_lso_times",		KSTAT_DATA_UINT64 },
26335 		{ "tcp_lso_pkt_out",		KSTAT_DATA_UINT64 },
26336 	};
26337 
26338 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, "tcpstat", "net",
26339 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
26340 	    KSTAT_FLAG_VIRTUAL, stackid);
26341 
26342 	if (ksp == NULL)
26343 		return (NULL);
26344 
26345 	bcopy(&template, tcps_statisticsp, sizeof (template));
26346 	ksp->ks_data = (void *)tcps_statisticsp;
26347 	ksp->ks_private = (void *)(uintptr_t)stackid;
26348 
26349 	kstat_install(ksp);
26350 	return (ksp);
26351 }
26352 
26353 static void
26354 tcp_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
26355 {
26356 	if (ksp != NULL) {
26357 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26358 		kstat_delete_netstack(ksp, stackid);
26359 	}
26360 }
26361 
26362 /*
26363  * TCP Kstats implementation
26364  */
26365 static void *
26366 tcp_kstat_init(netstackid_t stackid, tcp_stack_t *tcps)
26367 {
26368 	kstat_t	*ksp;
26369 
26370 	tcp_named_kstat_t template = {
26371 		{ "rtoAlgorithm",	KSTAT_DATA_INT32, 0 },
26372 		{ "rtoMin",		KSTAT_DATA_INT32, 0 },
26373 		{ "rtoMax",		KSTAT_DATA_INT32, 0 },
26374 		{ "maxConn",		KSTAT_DATA_INT32, 0 },
26375 		{ "activeOpens",	KSTAT_DATA_UINT32, 0 },
26376 		{ "passiveOpens",	KSTAT_DATA_UINT32, 0 },
26377 		{ "attemptFails",	KSTAT_DATA_UINT32, 0 },
26378 		{ "estabResets",	KSTAT_DATA_UINT32, 0 },
26379 		{ "currEstab",		KSTAT_DATA_UINT32, 0 },
26380 		{ "inSegs",		KSTAT_DATA_UINT64, 0 },
26381 		{ "outSegs",		KSTAT_DATA_UINT64, 0 },
26382 		{ "retransSegs",	KSTAT_DATA_UINT32, 0 },
26383 		{ "connTableSize",	KSTAT_DATA_INT32, 0 },
26384 		{ "outRsts",		KSTAT_DATA_UINT32, 0 },
26385 		{ "outDataSegs",	KSTAT_DATA_UINT32, 0 },
26386 		{ "outDataBytes",	KSTAT_DATA_UINT32, 0 },
26387 		{ "retransBytes",	KSTAT_DATA_UINT32, 0 },
26388 		{ "outAck",		KSTAT_DATA_UINT32, 0 },
26389 		{ "outAckDelayed",	KSTAT_DATA_UINT32, 0 },
26390 		{ "outUrg",		KSTAT_DATA_UINT32, 0 },
26391 		{ "outWinUpdate",	KSTAT_DATA_UINT32, 0 },
26392 		{ "outWinProbe",	KSTAT_DATA_UINT32, 0 },
26393 		{ "outControl",		KSTAT_DATA_UINT32, 0 },
26394 		{ "outFastRetrans",	KSTAT_DATA_UINT32, 0 },
26395 		{ "inAckSegs",		KSTAT_DATA_UINT32, 0 },
26396 		{ "inAckBytes",		KSTAT_DATA_UINT32, 0 },
26397 		{ "inDupAck",		KSTAT_DATA_UINT32, 0 },
26398 		{ "inAckUnsent",	KSTAT_DATA_UINT32, 0 },
26399 		{ "inDataInorderSegs",	KSTAT_DATA_UINT32, 0 },
26400 		{ "inDataInorderBytes",	KSTAT_DATA_UINT32, 0 },
26401 		{ "inDataUnorderSegs",	KSTAT_DATA_UINT32, 0 },
26402 		{ "inDataUnorderBytes",	KSTAT_DATA_UINT32, 0 },
26403 		{ "inDataDupSegs",	KSTAT_DATA_UINT32, 0 },
26404 		{ "inDataDupBytes",	KSTAT_DATA_UINT32, 0 },
26405 		{ "inDataPartDupSegs",	KSTAT_DATA_UINT32, 0 },
26406 		{ "inDataPartDupBytes",	KSTAT_DATA_UINT32, 0 },
26407 		{ "inDataPastWinSegs",	KSTAT_DATA_UINT32, 0 },
26408 		{ "inDataPastWinBytes",	KSTAT_DATA_UINT32, 0 },
26409 		{ "inWinProbe",		KSTAT_DATA_UINT32, 0 },
26410 		{ "inWinUpdate",	KSTAT_DATA_UINT32, 0 },
26411 		{ "inClosed",		KSTAT_DATA_UINT32, 0 },
26412 		{ "rttUpdate",		KSTAT_DATA_UINT32, 0 },
26413 		{ "rttNoUpdate",	KSTAT_DATA_UINT32, 0 },
26414 		{ "timRetrans",		KSTAT_DATA_UINT32, 0 },
26415 		{ "timRetransDrop",	KSTAT_DATA_UINT32, 0 },
26416 		{ "timKeepalive",	KSTAT_DATA_UINT32, 0 },
26417 		{ "timKeepaliveProbe",	KSTAT_DATA_UINT32, 0 },
26418 		{ "timKeepaliveDrop",	KSTAT_DATA_UINT32, 0 },
26419 		{ "listenDrop",		KSTAT_DATA_UINT32, 0 },
26420 		{ "listenDropQ0",	KSTAT_DATA_UINT32, 0 },
26421 		{ "halfOpenDrop",	KSTAT_DATA_UINT32, 0 },
26422 		{ "outSackRetransSegs",	KSTAT_DATA_UINT32, 0 },
26423 		{ "connTableSize6",	KSTAT_DATA_INT32, 0 }
26424 	};
26425 
26426 	ksp = kstat_create_netstack(TCP_MOD_NAME, 0, TCP_MOD_NAME, "mib2",
26427 	    KSTAT_TYPE_NAMED, NUM_OF_FIELDS(tcp_named_kstat_t), 0, stackid);
26428 
26429 	if (ksp == NULL)
26430 		return (NULL);
26431 
26432 	template.rtoAlgorithm.value.ui32 = 4;
26433 	template.rtoMin.value.ui32 = tcps->tcps_rexmit_interval_min;
26434 	template.rtoMax.value.ui32 = tcps->tcps_rexmit_interval_max;
26435 	template.maxConn.value.i32 = -1;
26436 
26437 	bcopy(&template, ksp->ks_data, sizeof (template));
26438 	ksp->ks_update = tcp_kstat_update;
26439 	ksp->ks_private = (void *)(uintptr_t)stackid;
26440 
26441 	kstat_install(ksp);
26442 	return (ksp);
26443 }
26444 
26445 static void
26446 tcp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
26447 {
26448 	if (ksp != NULL) {
26449 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
26450 		kstat_delete_netstack(ksp, stackid);
26451 	}
26452 }
26453 
26454 static int
26455 tcp_kstat_update(kstat_t *kp, int rw)
26456 {
26457 	tcp_named_kstat_t *tcpkp;
26458 	tcp_t		*tcp;
26459 	connf_t		*connfp;
26460 	conn_t		*connp;
26461 	int 		i;
26462 	netstackid_t	stackid = (netstackid_t)(uintptr_t)kp->ks_private;
26463 	netstack_t	*ns;
26464 	tcp_stack_t	*tcps;
26465 	ip_stack_t	*ipst;
26466 
26467 	if ((kp == NULL) || (kp->ks_data == NULL))
26468 		return (EIO);
26469 
26470 	if (rw == KSTAT_WRITE)
26471 		return (EACCES);
26472 
26473 	ns = netstack_find_by_stackid(stackid);
26474 	if (ns == NULL)
26475 		return (-1);
26476 	tcps = ns->netstack_tcp;
26477 	if (tcps == NULL) {
26478 		netstack_rele(ns);
26479 		return (-1);
26480 	}
26481 	tcpkp = (tcp_named_kstat_t *)kp->ks_data;
26482 
26483 	tcpkp->currEstab.value.ui32 = 0;
26484 
26485 	ipst = ns->netstack_ip;
26486 
26487 	for (i = 0; i < CONN_G_HASH_SIZE; i++) {
26488 		connfp = &ipst->ips_ipcl_globalhash_fanout[i];
26489 		connp = NULL;
26490 		while ((connp =
26491 		    ipcl_get_next_conn(connfp, connp, IPCL_TCP)) != NULL) {
26492 			tcp = connp->conn_tcp;
26493 			switch (tcp_snmp_state(tcp)) {
26494 			case MIB2_TCP_established:
26495 			case MIB2_TCP_closeWait:
26496 				tcpkp->currEstab.value.ui32++;
26497 				break;
26498 			}
26499 		}
26500 	}
26501 
26502 	tcpkp->activeOpens.value.ui32 = tcps->tcps_mib.tcpActiveOpens;
26503 	tcpkp->passiveOpens.value.ui32 = tcps->tcps_mib.tcpPassiveOpens;
26504 	tcpkp->attemptFails.value.ui32 = tcps->tcps_mib.tcpAttemptFails;
26505 	tcpkp->estabResets.value.ui32 = tcps->tcps_mib.tcpEstabResets;
26506 	tcpkp->inSegs.value.ui64 = tcps->tcps_mib.tcpHCInSegs;
26507 	tcpkp->outSegs.value.ui64 = tcps->tcps_mib.tcpHCOutSegs;
26508 	tcpkp->retransSegs.value.ui32 =	tcps->tcps_mib.tcpRetransSegs;
26509 	tcpkp->connTableSize.value.i32 = tcps->tcps_mib.tcpConnTableSize;
26510 	tcpkp->outRsts.value.ui32 = tcps->tcps_mib.tcpOutRsts;
26511 	tcpkp->outDataSegs.value.ui32 = tcps->tcps_mib.tcpOutDataSegs;
26512 	tcpkp->outDataBytes.value.ui32 = tcps->tcps_mib.tcpOutDataBytes;
26513 	tcpkp->retransBytes.value.ui32 = tcps->tcps_mib.tcpRetransBytes;
26514 	tcpkp->outAck.value.ui32 = tcps->tcps_mib.tcpOutAck;
26515 	tcpkp->outAckDelayed.value.ui32 = tcps->tcps_mib.tcpOutAckDelayed;
26516 	tcpkp->outUrg.value.ui32 = tcps->tcps_mib.tcpOutUrg;
26517 	tcpkp->outWinUpdate.value.ui32 = tcps->tcps_mib.tcpOutWinUpdate;
26518 	tcpkp->outWinProbe.value.ui32 = tcps->tcps_mib.tcpOutWinProbe;
26519 	tcpkp->outControl.value.ui32 = tcps->tcps_mib.tcpOutControl;
26520 	tcpkp->outFastRetrans.value.ui32 = tcps->tcps_mib.tcpOutFastRetrans;
26521 	tcpkp->inAckSegs.value.ui32 = tcps->tcps_mib.tcpInAckSegs;
26522 	tcpkp->inAckBytes.value.ui32 = tcps->tcps_mib.tcpInAckBytes;
26523 	tcpkp->inDupAck.value.ui32 = tcps->tcps_mib.tcpInDupAck;
26524 	tcpkp->inAckUnsent.value.ui32 = tcps->tcps_mib.tcpInAckUnsent;
26525 	tcpkp->inDataInorderSegs.value.ui32 =
26526 	    tcps->tcps_mib.tcpInDataInorderSegs;
26527 	tcpkp->inDataInorderBytes.value.ui32 =
26528 	    tcps->tcps_mib.tcpInDataInorderBytes;
26529 	tcpkp->inDataUnorderSegs.value.ui32 =
26530 	    tcps->tcps_mib.tcpInDataUnorderSegs;
26531 	tcpkp->inDataUnorderBytes.value.ui32 =
26532 	    tcps->tcps_mib.tcpInDataUnorderBytes;
26533 	tcpkp->inDataDupSegs.value.ui32 = tcps->tcps_mib.tcpInDataDupSegs;
26534 	tcpkp->inDataDupBytes.value.ui32 = tcps->tcps_mib.tcpInDataDupBytes;
26535 	tcpkp->inDataPartDupSegs.value.ui32 =
26536 	    tcps->tcps_mib.tcpInDataPartDupSegs;
26537 	tcpkp->inDataPartDupBytes.value.ui32 =
26538 	    tcps->tcps_mib.tcpInDataPartDupBytes;
26539 	tcpkp->inDataPastWinSegs.value.ui32 =
26540 	    tcps->tcps_mib.tcpInDataPastWinSegs;
26541 	tcpkp->inDataPastWinBytes.value.ui32 =
26542 	    tcps->tcps_mib.tcpInDataPastWinBytes;
26543 	tcpkp->inWinProbe.value.ui32 = tcps->tcps_mib.tcpInWinProbe;
26544 	tcpkp->inWinUpdate.value.ui32 = tcps->tcps_mib.tcpInWinUpdate;
26545 	tcpkp->inClosed.value.ui32 = tcps->tcps_mib.tcpInClosed;
26546 	tcpkp->rttNoUpdate.value.ui32 = tcps->tcps_mib.tcpRttNoUpdate;
26547 	tcpkp->rttUpdate.value.ui32 = tcps->tcps_mib.tcpRttUpdate;
26548 	tcpkp->timRetrans.value.ui32 = tcps->tcps_mib.tcpTimRetrans;
26549 	tcpkp->timRetransDrop.value.ui32 = tcps->tcps_mib.tcpTimRetransDrop;
26550 	tcpkp->timKeepalive.value.ui32 = tcps->tcps_mib.tcpTimKeepalive;
26551 	tcpkp->timKeepaliveProbe.value.ui32 =
26552 	    tcps->tcps_mib.tcpTimKeepaliveProbe;
26553 	tcpkp->timKeepaliveDrop.value.ui32 =
26554 	    tcps->tcps_mib.tcpTimKeepaliveDrop;
26555 	tcpkp->listenDrop.value.ui32 = tcps->tcps_mib.tcpListenDrop;
26556 	tcpkp->listenDropQ0.value.ui32 = tcps->tcps_mib.tcpListenDropQ0;
26557 	tcpkp->halfOpenDrop.value.ui32 = tcps->tcps_mib.tcpHalfOpenDrop;
26558 	tcpkp->outSackRetransSegs.value.ui32 =
26559 	    tcps->tcps_mib.tcpOutSackRetransSegs;
26560 	tcpkp->connTableSize6.value.i32 = tcps->tcps_mib.tcp6ConnTableSize;
26561 
26562 	netstack_rele(ns);
26563 	return (0);
26564 }
26565 
26566 void
26567 tcp_reinput(conn_t *connp, mblk_t *mp, squeue_t *sqp)
26568 {
26569 	uint16_t	hdr_len;
26570 	ipha_t		*ipha;
26571 	uint8_t		*nexthdrp;
26572 	tcph_t		*tcph;
26573 	tcp_stack_t	*tcps = connp->conn_tcp->tcp_tcps;
26574 
26575 	/* Already has an eager */
26576 	if ((mp->b_datap->db_struioflag & STRUIO_EAGER) != 0) {
26577 		TCP_STAT(tcps, tcp_reinput_syn);
26578 		squeue_enter(connp->conn_sqp, mp, connp->conn_recv,
26579 		    connp, SQTAG_TCP_REINPUT_EAGER);
26580 		return;
26581 	}
26582 
26583 	switch (IPH_HDR_VERSION(mp->b_rptr)) {
26584 	case IPV4_VERSION:
26585 		ipha = (ipha_t *)mp->b_rptr;
26586 		hdr_len = IPH_HDR_LENGTH(ipha);
26587 		break;
26588 	case IPV6_VERSION:
26589 		if (!ip_hdr_length_nexthdr_v6(mp, (ip6_t *)mp->b_rptr,
26590 		    &hdr_len, &nexthdrp)) {
26591 			CONN_DEC_REF(connp);
26592 			freemsg(mp);
26593 			return;
26594 		}
26595 		break;
26596 	}
26597 
26598 	tcph = (tcph_t *)&mp->b_rptr[hdr_len];
26599 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
26600 		mp->b_datap->db_struioflag |= STRUIO_EAGER;
26601 		DB_CKSUMSTART(mp) = (intptr_t)sqp;
26602 	}
26603 
26604 	squeue_fill(connp->conn_sqp, mp, connp->conn_recv, connp,
26605 	    SQTAG_TCP_REINPUT);
26606 }
26607 
26608 static squeue_func_t
26609 tcp_squeue_switch(int val)
26610 {
26611 	squeue_func_t rval = squeue_fill;
26612 
26613 	switch (val) {
26614 	case 1:
26615 		rval = squeue_enter_nodrain;
26616 		break;
26617 	case 2:
26618 		rval = squeue_enter;
26619 		break;
26620 	default:
26621 		break;
26622 	}
26623 	return (rval);
26624 }
26625 
26626 /*
26627  * This is called once for each squeue - globally for all stack
26628  * instances.
26629  */
26630 static void
26631 tcp_squeue_add(squeue_t *sqp)
26632 {
26633 	tcp_squeue_priv_t *tcp_time_wait = kmem_zalloc(
26634 	    sizeof (tcp_squeue_priv_t), KM_SLEEP);
26635 
26636 	*squeue_getprivate(sqp, SQPRIVATE_TCP) = (intptr_t)tcp_time_wait;
26637 	tcp_time_wait->tcp_time_wait_tid =
26638 	    timeout_generic(CALLOUT_NORMAL, tcp_time_wait_collector, sqp,
26639 	    TICK_TO_NSEC(TCP_TIME_WAIT_DELAY), CALLOUT_TCP_RESOLUTION,
26640 	    CALLOUT_FLAG_ROUNDUP);
26641 	if (tcp_free_list_max_cnt == 0) {
26642 		int tcp_ncpus = ((boot_max_ncpus == -1) ?
26643 		    max_ncpus : boot_max_ncpus);
26644 
26645 		/*
26646 		 * Limit number of entries to 1% of availble memory / tcp_ncpus
26647 		 */
26648 		tcp_free_list_max_cnt = (freemem * PAGESIZE) /
26649 		    (tcp_ncpus * sizeof (tcp_t) * 100);
26650 	}
26651 	tcp_time_wait->tcp_free_list_cnt = 0;
26652 }
26653